AMDGPU: Add v_mfma_i32_16x16x64_i8 for gfx950 (#116728)
[llvm-project.git] / llvm / lib / Target / X86 / X86ISelLowering.cpp
blob934654a09c17242a7ce32e3a80f6464994c37ad0
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.
12 //===----------------------------------------------------------------------===//
14 #include "X86ISelLowering.h"
15 #include "MCTargetDesc/X86ShuffleDecode.h"
16 #include "X86.h"
17 #include "X86FrameLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86IntrinsicsInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/ProfileSummaryInfo.h"
29 #include "llvm/Analysis/VectorUtils.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/SDPatternMatch.h"
39 #include "llvm/CodeGen/TargetLowering.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/EHPersonalities.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/IRBuilder.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/PatternMatch.h"
52 #include "llvm/MC/MCAsmInfo.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCExpr.h"
55 #include "llvm/MC/MCSymbol.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/KnownBits.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include <algorithm>
63 #include <bitset>
64 #include <cctype>
65 #include <numeric>
66 using namespace llvm;
68 #define DEBUG_TYPE "x86-isel"
70 static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
71 "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
72 cl::desc(
73 "Sets the preferable loop alignment for experiments (as log2 bytes) "
74 "for innermost loops only. If specified, this option overrides "
75 "alignment set by x86-experimental-pref-loop-alignment."),
76 cl::Hidden);
78 static cl::opt<int> BrMergingBaseCostThresh(
79 "x86-br-merging-base-cost", cl::init(2),
80 cl::desc(
81 "Sets the cost threshold for when multiple conditionals will be merged "
82 "into one branch versus be split in multiple branches. Merging "
83 "conditionals saves branches at the cost of additional instructions. "
84 "This value sets the instruction cost limit, below which conditionals "
85 "will be merged, and above which conditionals will be split. Set to -1 "
86 "to never merge branches."),
87 cl::Hidden);
89 static cl::opt<int> BrMergingCcmpBias(
90 "x86-br-merging-ccmp-bias", cl::init(6),
91 cl::desc("Increases 'x86-br-merging-base-cost' in cases that the target "
92 "supports conditional compare instructions."),
93 cl::Hidden);
95 static cl::opt<bool>
96 WidenShift("x86-widen-shift", cl::init(true),
97 cl::desc("Replacte narrow shifts with wider shifts."),
98 cl::Hidden);
100 static cl::opt<int> BrMergingLikelyBias(
101 "x86-br-merging-likely-bias", cl::init(0),
102 cl::desc("Increases 'x86-br-merging-base-cost' in cases that it is likely "
103 "that all conditionals will be executed. For example for merging "
104 "the conditionals (a == b && c > d), if its known that a == b is "
105 "likely, then it is likely that if the conditionals are split "
106 "both sides will be executed, so it may be desirable to increase "
107 "the instruction cost threshold. Set to -1 to never merge likely "
108 "branches."),
109 cl::Hidden);
111 static cl::opt<int> BrMergingUnlikelyBias(
112 "x86-br-merging-unlikely-bias", cl::init(-1),
113 cl::desc(
114 "Decreases 'x86-br-merging-base-cost' in cases that it is unlikely "
115 "that all conditionals will be executed. For example for merging "
116 "the conditionals (a == b && c > d), if its known that a == b is "
117 "unlikely, then it is unlikely that if the conditionals are split "
118 "both sides will be executed, so it may be desirable to decrease "
119 "the instruction cost threshold. Set to -1 to never merge unlikely "
120 "branches."),
121 cl::Hidden);
123 static cl::opt<bool> MulConstantOptimization(
124 "mul-constant-optimization", cl::init(true),
125 cl::desc("Replace 'mul x, Const' with more effective instructions like "
126 "SHIFT, LEA, etc."),
127 cl::Hidden);
129 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
130 const X86Subtarget &STI)
131 : TargetLowering(TM), Subtarget(STI) {
132 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
133 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
135 // Set up the TargetLowering object.
137 // X86 is weird. It always uses i8 for shift amounts and setcc results.
138 setBooleanContents(ZeroOrOneBooleanContent);
139 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
140 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
142 // X86 instruction cache is coherent with its data cache so we can use the
143 // default expansion to a no-op.
144 setOperationAction(ISD::CLEAR_CACHE, MVT::Other, Expand);
146 // For 64-bit, since we have so many registers, use the ILP scheduler.
147 // For 32-bit, use the register pressure specific scheduling.
148 // For Atom, always use ILP scheduling.
149 if (Subtarget.isAtom())
150 setSchedulingPreference(Sched::ILP);
151 else if (Subtarget.is64Bit())
152 setSchedulingPreference(Sched::ILP);
153 else
154 setSchedulingPreference(Sched::RegPressure);
155 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
156 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
158 // Bypass expensive divides and use cheaper ones.
159 if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
160 if (Subtarget.hasSlowDivide32())
161 addBypassSlowDiv(32, 8);
162 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
163 addBypassSlowDiv(64, 32);
166 // Setup Windows compiler runtime calls.
167 if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
168 static const struct {
169 const RTLIB::Libcall Op;
170 const char * const Name;
171 const CallingConv::ID CC;
172 } LibraryCalls[] = {
173 { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
174 { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
175 { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
176 { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
177 { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
180 for (const auto &LC : LibraryCalls) {
181 setLibcallName(LC.Op, LC.Name);
182 setLibcallCallingConv(LC.Op, LC.CC);
186 if (Subtarget.canUseCMPXCHG16B())
187 setMaxAtomicSizeInBitsSupported(128);
188 else if (Subtarget.canUseCMPXCHG8B())
189 setMaxAtomicSizeInBitsSupported(64);
190 else
191 setMaxAtomicSizeInBitsSupported(32);
193 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
195 setMaxLargeFPConvertBitWidthSupported(128);
197 // Set up the register classes.
198 addRegisterClass(MVT::i8, &X86::GR8RegClass);
199 addRegisterClass(MVT::i16, &X86::GR16RegClass);
200 addRegisterClass(MVT::i32, &X86::GR32RegClass);
201 if (Subtarget.is64Bit())
202 addRegisterClass(MVT::i64, &X86::GR64RegClass);
204 for (MVT VT : MVT::integer_valuetypes())
205 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
207 // We don't accept any truncstore of integer registers.
208 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
209 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
210 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
211 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
212 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
213 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
215 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
217 // SETOEQ and SETUNE require checking two conditions.
218 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
219 setCondCodeAction(ISD::SETOEQ, VT, Expand);
220 setCondCodeAction(ISD::SETUNE, VT, Expand);
223 // Integer absolute.
224 if (Subtarget.canUseCMOV()) {
225 setOperationAction(ISD::ABS , MVT::i16 , Custom);
226 setOperationAction(ISD::ABS , MVT::i32 , Custom);
227 if (Subtarget.is64Bit())
228 setOperationAction(ISD::ABS , MVT::i64 , Custom);
231 // Absolute difference.
232 for (auto Op : {ISD::ABDS, ISD::ABDU}) {
233 setOperationAction(Op , MVT::i8 , Custom);
234 setOperationAction(Op , MVT::i16 , Custom);
235 setOperationAction(Op , MVT::i32 , Custom);
236 if (Subtarget.is64Bit())
237 setOperationAction(Op , MVT::i64 , Custom);
240 // Signed saturation subtraction.
241 setOperationAction(ISD::SSUBSAT , MVT::i8 , Custom);
242 setOperationAction(ISD::SSUBSAT , MVT::i16 , Custom);
243 setOperationAction(ISD::SSUBSAT , MVT::i32 , Custom);
244 if (Subtarget.is64Bit())
245 setOperationAction(ISD::SSUBSAT , MVT::i64 , Custom);
247 // Funnel shifts.
248 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
249 // For slow shld targets we only lower for code size.
250 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
252 setOperationAction(ShiftOp , MVT::i8 , Custom);
253 setOperationAction(ShiftOp , MVT::i16 , Custom);
254 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
255 if (Subtarget.is64Bit())
256 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
259 if (!Subtarget.useSoftFloat()) {
260 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
261 // operation.
262 setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
263 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
264 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
265 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
266 // We have an algorithm for SSE2, and we turn this into a 64-bit
267 // FILD or VCVTUSI2SS/SD for other targets.
268 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
269 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
270 // We have an algorithm for SSE2->double, and we turn this into a
271 // 64-bit FILD followed by conditional FADD for other targets.
272 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
273 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
275 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
276 // this operation.
277 setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
278 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
279 // SSE has no i16 to fp conversion, only i32. We promote in the handler
280 // to allow f80 to use i16 and f64 to use i16 with sse1 only
281 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
282 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
283 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
284 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
285 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
289 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
291 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 // this operation.
293 setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
294 // FIXME: This doesn't generate invalid exception when it should. PR44019.
295 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8, Promote);
296 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
297 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
298 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
299 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
300 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
301 // are Legal, f80 is custom lowered.
302 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
303 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 // conversion.
307 setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
308 // FIXME: This doesn't generate invalid exception when it should. PR44019.
309 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8, Promote);
310 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
311 // FIXME: This doesn't generate invalid exception when it should. PR44019.
312 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
313 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
314 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
315 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
316 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
318 setOperationAction(ISD::LRINT, MVT::f32, Custom);
319 setOperationAction(ISD::LRINT, MVT::f64, Custom);
320 setOperationAction(ISD::LLRINT, MVT::f32, Custom);
321 setOperationAction(ISD::LLRINT, MVT::f64, Custom);
323 if (!Subtarget.is64Bit()) {
324 setOperationAction(ISD::LRINT, MVT::i64, Custom);
325 setOperationAction(ISD::LLRINT, MVT::i64, Custom);
329 if (Subtarget.hasSSE2()) {
330 // Custom lowering for saturating float to int conversions.
331 // We handle promotion to larger result types manually.
332 for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
333 setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
334 setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
336 setOperationAction(ISD::FCANONICALIZE, MVT::f32, Custom);
337 if (Subtarget.is64Bit()) {
338 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
339 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
340 setOperationAction(ISD::FCANONICALIZE, MVT::f64, Custom);
343 if (Subtarget.hasAVX10_2()) {
344 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Legal);
345 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Legal);
346 if (Subtarget.is64Bit()) {
347 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Legal);
348 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Legal);
352 // Handle address space casts between mixed sized pointers.
353 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
354 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
356 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
357 if (!Subtarget.hasSSE2()) {
358 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
359 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
360 setOperationAction(ISD::FCANONICALIZE, MVT::f32, Custom);
361 setOperationAction(ISD::FCANONICALIZE, MVT::f80, Custom);
362 setOperationAction(ISD::FCANONICALIZE, MVT::f64, Custom);
363 if (Subtarget.is64Bit()) {
364 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
365 // Without SSE, i64->f64 goes through memory.
366 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
368 } else if (!Subtarget.is64Bit())
369 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
371 // Scalar integer divide and remainder are lowered to use operations that
372 // produce two results, to match the available instructions. This exposes
373 // the two-result form to trivial CSE, which is able to combine x/y and x%y
374 // into a single instruction.
376 // Scalar integer multiply-high is also lowered to use two-result
377 // operations, to match the available instructions. However, plain multiply
378 // (low) operations are left as Legal, as there are single-result
379 // instructions for this in x86. Using the two-result multiply instructions
380 // when both high and low results are needed must be arranged by dagcombine.
381 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
382 setOperationAction(ISD::MULHS, VT, Expand);
383 setOperationAction(ISD::MULHU, VT, Expand);
384 setOperationAction(ISD::SDIV, VT, Expand);
385 setOperationAction(ISD::UDIV, VT, Expand);
386 setOperationAction(ISD::SREM, VT, Expand);
387 setOperationAction(ISD::UREM, VT, Expand);
390 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
391 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
392 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
393 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
394 setOperationAction(ISD::BR_CC, VT, Expand);
395 setOperationAction(ISD::SELECT_CC, VT, Expand);
397 if (Subtarget.is64Bit())
398 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
399 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
403 setOperationAction(ISD::FREM , MVT::f32 , Expand);
404 setOperationAction(ISD::FREM , MVT::f64 , Expand);
405 setOperationAction(ISD::FREM , MVT::f80 , Expand);
406 setOperationAction(ISD::FREM , MVT::f128 , Expand);
408 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
409 setOperationAction(ISD::GET_ROUNDING , MVT::i32 , Custom);
410 setOperationAction(ISD::SET_ROUNDING , MVT::Other, Custom);
411 setOperationAction(ISD::GET_FPENV_MEM , MVT::Other, Custom);
412 setOperationAction(ISD::SET_FPENV_MEM , MVT::Other, Custom);
413 setOperationAction(ISD::RESET_FPENV , MVT::Other, Custom);
416 // Promote the i8 variants and force them on up to i32 which has a shorter
417 // encoding.
418 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
419 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
420 // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
421 // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
422 // promote that too.
423 setOperationPromotedToType(ISD::CTTZ , MVT::i16 , MVT::i32);
424 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , MVT::i32);
426 if (!Subtarget.hasBMI()) {
427 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
428 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
429 if (Subtarget.is64Bit()) {
430 setOperationPromotedToType(ISD::CTTZ , MVT::i32, MVT::i64);
431 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
432 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
436 if (Subtarget.hasLZCNT()) {
437 // When promoting the i8 variants, force them to i32 for a shorter
438 // encoding.
439 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
440 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
441 } else {
442 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
443 if (VT == MVT::i64 && !Subtarget.is64Bit())
444 continue;
445 setOperationAction(ISD::CTLZ , VT, Custom);
446 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
450 for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
451 ISD::STRICT_FP_TO_FP16}) {
452 // Special handling for half-precision floating point conversions.
453 // If we don't have F16C support, then lower half float conversions
454 // into library calls.
455 setOperationAction(
456 Op, MVT::f32,
457 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
458 // There's never any support for operations beyond MVT::f32.
459 setOperationAction(Op, MVT::f64, Expand);
460 setOperationAction(Op, MVT::f80, Expand);
461 setOperationAction(Op, MVT::f128, Expand);
464 for (auto VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
465 setOperationAction(ISD::STRICT_FP_TO_BF16, VT, Expand);
466 setOperationAction(ISD::STRICT_BF16_TO_FP, VT, Expand);
469 for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
470 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
471 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
472 setTruncStoreAction(VT, MVT::f16, Expand);
473 setTruncStoreAction(VT, MVT::bf16, Expand);
475 setOperationAction(ISD::BF16_TO_FP, VT, Expand);
476 setOperationAction(ISD::FP_TO_BF16, VT, Custom);
479 setOperationAction(ISD::PARITY, MVT::i8, Custom);
480 setOperationAction(ISD::PARITY, MVT::i16, Custom);
481 setOperationAction(ISD::PARITY, MVT::i32, Custom);
482 if (Subtarget.is64Bit())
483 setOperationAction(ISD::PARITY, MVT::i64, Custom);
484 if (Subtarget.hasPOPCNT()) {
485 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
486 // popcntw is longer to encode than popcntl and also has a false dependency
487 // on the dest that popcntl hasn't had since Cannon Lake.
488 setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
489 } else {
490 setOperationAction(ISD::CTPOP , MVT::i8 , Custom);
491 setOperationAction(ISD::CTPOP , MVT::i16 , Custom);
492 setOperationAction(ISD::CTPOP , MVT::i32 , Custom);
493 setOperationAction(ISD::CTPOP , MVT::i64 , Custom);
496 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
498 if (!Subtarget.hasMOVBE())
499 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
501 // X86 wants to expand cmov itself.
502 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
503 setOperationAction(ISD::SELECT, VT, Custom);
504 setOperationAction(ISD::SETCC, VT, Custom);
505 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
506 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
508 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
509 if (VT == MVT::i64 && !Subtarget.is64Bit())
510 continue;
511 setOperationAction(ISD::SELECT, VT, Custom);
512 setOperationAction(ISD::SETCC, VT, Custom);
515 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
516 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
517 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
519 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
520 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
521 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
522 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
523 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
524 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
525 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
526 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
528 // Darwin ABI issue.
529 for (auto VT : { MVT::i32, MVT::i64 }) {
530 if (VT == MVT::i64 && !Subtarget.is64Bit())
531 continue;
532 setOperationAction(ISD::ConstantPool , VT, Custom);
533 setOperationAction(ISD::JumpTable , VT, Custom);
534 setOperationAction(ISD::GlobalAddress , VT, Custom);
535 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
536 setOperationAction(ISD::ExternalSymbol , VT, Custom);
537 setOperationAction(ISD::BlockAddress , VT, Custom);
540 // 64-bit shl, sra, srl (iff 32-bit x86)
541 for (auto VT : { MVT::i32, MVT::i64 }) {
542 if (VT == MVT::i64 && !Subtarget.is64Bit())
543 continue;
544 setOperationAction(ISD::SHL_PARTS, VT, Custom);
545 setOperationAction(ISD::SRA_PARTS, VT, Custom);
546 setOperationAction(ISD::SRL_PARTS, VT, Custom);
549 if (Subtarget.hasSSEPrefetch())
550 setOperationAction(ISD::PREFETCH , MVT::Other, Custom);
552 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
554 // Expand certain atomics
555 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
556 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
557 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
558 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
559 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
560 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
561 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
562 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
565 if (!Subtarget.is64Bit())
566 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
568 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
569 // All CPUs supporting AVX will atomically load/store aligned 128-bit
570 // values, so we can emit [V]MOVAPS/[V]MOVDQA.
571 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
572 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
575 if (Subtarget.canUseCMPXCHG16B())
576 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
578 // FIXME - use subtarget debug flags
579 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
580 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
581 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
582 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
585 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
586 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
588 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
589 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
591 setOperationAction(ISD::TRAP, MVT::Other, Legal);
592 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
593 if (Subtarget.isTargetPS())
594 setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
595 else
596 setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
598 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
599 setOperationAction(ISD::VASTART , MVT::Other, Custom);
600 setOperationAction(ISD::VAEND , MVT::Other, Expand);
601 bool Is64Bit = Subtarget.is64Bit();
602 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
603 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
605 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
606 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
608 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
610 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
611 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
612 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
614 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
616 auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
617 setOperationAction(ISD::FABS, VT, Action);
618 setOperationAction(ISD::FNEG, VT, Action);
619 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
620 setOperationAction(ISD::FREM, VT, Action);
621 setOperationAction(ISD::FMA, VT, Action);
622 setOperationAction(ISD::FMINNUM, VT, Action);
623 setOperationAction(ISD::FMAXNUM, VT, Action);
624 setOperationAction(ISD::FMINIMUM, VT, Action);
625 setOperationAction(ISD::FMAXIMUM, VT, Action);
626 setOperationAction(ISD::FSIN, VT, Action);
627 setOperationAction(ISD::FCOS, VT, Action);
628 setOperationAction(ISD::FSINCOS, VT, Action);
629 setOperationAction(ISD::FTAN, VT, Action);
630 setOperationAction(ISD::FSQRT, VT, Action);
631 setOperationAction(ISD::FPOW, VT, Action);
632 setOperationAction(ISD::FPOWI, VT, Action);
633 setOperationAction(ISD::FLOG, VT, Action);
634 setOperationAction(ISD::FLOG2, VT, Action);
635 setOperationAction(ISD::FLOG10, VT, Action);
636 setOperationAction(ISD::FEXP, VT, Action);
637 setOperationAction(ISD::FEXP2, VT, Action);
638 setOperationAction(ISD::FEXP10, VT, Action);
639 setOperationAction(ISD::FCEIL, VT, Action);
640 setOperationAction(ISD::FFLOOR, VT, Action);
641 setOperationAction(ISD::FNEARBYINT, VT, Action);
642 setOperationAction(ISD::FRINT, VT, Action);
643 setOperationAction(ISD::BR_CC, VT, Action);
644 setOperationAction(ISD::SETCC, VT, Action);
645 setOperationAction(ISD::SELECT, VT, Custom);
646 setOperationAction(ISD::SELECT_CC, VT, Action);
647 setOperationAction(ISD::FROUND, VT, Action);
648 setOperationAction(ISD::FROUNDEVEN, VT, Action);
649 setOperationAction(ISD::FTRUNC, VT, Action);
650 setOperationAction(ISD::FLDEXP, VT, Action);
653 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
654 // f16, f32 and f64 use SSE.
655 // Set up the FP register classes.
656 addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
657 : &X86::FR16RegClass);
658 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
659 : &X86::FR32RegClass);
660 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
661 : &X86::FR64RegClass);
663 // Disable f32->f64 extload as we can only generate this in one instruction
664 // under optsize. So its easier to pattern match (fpext (load)) for that
665 // case instead of needing to emit 2 instructions for extload in the
666 // non-optsize case.
667 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
669 for (auto VT : { MVT::f32, MVT::f64 }) {
670 // Use ANDPD to simulate FABS.
671 setOperationAction(ISD::FABS, VT, Custom);
673 // Use XORP to simulate FNEG.
674 setOperationAction(ISD::FNEG, VT, Custom);
676 // Use ANDPD and ORPD to simulate FCOPYSIGN.
677 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
679 // These might be better off as horizontal vector ops.
680 setOperationAction(ISD::FADD, VT, Custom);
681 setOperationAction(ISD::FSUB, VT, Custom);
683 // We don't support sin/cos/fmod
684 setOperationAction(ISD::FSIN , VT, Expand);
685 setOperationAction(ISD::FCOS , VT, Expand);
686 setOperationAction(ISD::FSINCOS, VT, Expand);
689 // Half type will be promoted by default.
690 setF16Action(MVT::f16, Promote);
691 setOperationAction(ISD::FADD, MVT::f16, Promote);
692 setOperationAction(ISD::FSUB, MVT::f16, Promote);
693 setOperationAction(ISD::FMUL, MVT::f16, Promote);
694 setOperationAction(ISD::FDIV, MVT::f16, Promote);
695 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
696 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
697 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
699 setOperationAction(ISD::STRICT_FADD, MVT::f16, Promote);
700 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Promote);
701 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Promote);
702 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Promote);
703 setOperationAction(ISD::STRICT_FMA, MVT::f16, Promote);
704 setOperationAction(ISD::STRICT_FMINNUM, MVT::f16, Promote);
705 setOperationAction(ISD::STRICT_FMAXNUM, MVT::f16, Promote);
706 setOperationAction(ISD::STRICT_FMINIMUM, MVT::f16, Promote);
707 setOperationAction(ISD::STRICT_FMAXIMUM, MVT::f16, Promote);
708 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Promote);
709 setOperationAction(ISD::STRICT_FPOW, MVT::f16, Promote);
710 setOperationAction(ISD::STRICT_FLDEXP, MVT::f16, Promote);
711 setOperationAction(ISD::STRICT_FLOG, MVT::f16, Promote);
712 setOperationAction(ISD::STRICT_FLOG2, MVT::f16, Promote);
713 setOperationAction(ISD::STRICT_FLOG10, MVT::f16, Promote);
714 setOperationAction(ISD::STRICT_FEXP, MVT::f16, Promote);
715 setOperationAction(ISD::STRICT_FEXP2, MVT::f16, Promote);
716 setOperationAction(ISD::STRICT_FCEIL, MVT::f16, Promote);
717 setOperationAction(ISD::STRICT_FFLOOR, MVT::f16, Promote);
718 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f16, Promote);
719 setOperationAction(ISD::STRICT_FRINT, MVT::f16, Promote);
720 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Promote);
721 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Promote);
722 setOperationAction(ISD::STRICT_FROUND, MVT::f16, Promote);
723 setOperationAction(ISD::STRICT_FROUNDEVEN, MVT::f16, Promote);
724 setOperationAction(ISD::STRICT_FTRUNC, MVT::f16, Promote);
725 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
726 setOperationAction(ISD::FCANONICALIZE, MVT::f16, Custom);
727 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
728 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
730 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
731 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
733 // Lower this to MOVMSK plus an AND.
734 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
735 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
737 } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
738 (UseX87 || Is64Bit)) {
739 // Use SSE for f32, x87 for f64.
740 // Set up the FP register classes.
741 addRegisterClass(MVT::f32, &X86::FR32RegClass);
742 if (UseX87)
743 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
745 // Use ANDPS to simulate FABS.
746 setOperationAction(ISD::FABS , MVT::f32, Custom);
748 // Use XORP to simulate FNEG.
749 setOperationAction(ISD::FNEG , MVT::f32, Custom);
751 if (UseX87)
752 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
754 // Use ANDPS and ORPS to simulate FCOPYSIGN.
755 if (UseX87)
756 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
757 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
759 // We don't support sin/cos/fmod
760 setOperationAction(ISD::FSIN , MVT::f32, Expand);
761 setOperationAction(ISD::FCOS , MVT::f32, Expand);
762 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
764 if (UseX87) {
765 // Always expand sin/cos functions even though x87 has an instruction.
766 setOperationAction(ISD::FSIN, MVT::f64, Expand);
767 setOperationAction(ISD::FCOS, MVT::f64, Expand);
768 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
770 } else if (UseX87) {
771 // f32 and f64 in x87.
772 // Set up the FP register classes.
773 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
774 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
776 for (auto VT : { MVT::f32, MVT::f64 }) {
777 setOperationAction(ISD::UNDEF, VT, Expand);
778 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
780 // Always expand sin/cos functions even though x87 has an instruction.
781 setOperationAction(ISD::FSIN , VT, Expand);
782 setOperationAction(ISD::FCOS , VT, Expand);
783 setOperationAction(ISD::FSINCOS, VT, Expand);
787 // Expand FP32 immediates into loads from the stack, save special cases.
788 if (isTypeLegal(MVT::f32)) {
789 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
790 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
791 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
792 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
793 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
794 } else // SSE immediates.
795 addLegalFPImmediate(APFloat(+0.0f)); // xorps
797 // Expand FP64 immediates into loads from the stack, save special cases.
798 if (isTypeLegal(MVT::f64)) {
799 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
800 addLegalFPImmediate(APFloat(+0.0)); // FLD0
801 addLegalFPImmediate(APFloat(+1.0)); // FLD1
802 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
803 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
804 } else // SSE immediates.
805 addLegalFPImmediate(APFloat(+0.0)); // xorpd
807 // Support fp16 0 immediate.
808 if (isTypeLegal(MVT::f16))
809 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
811 // Handle constrained floating-point operations of scalar.
812 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
813 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
814 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
815 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
816 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
817 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
818 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
819 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
820 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
821 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
822 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
823 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
825 // We don't support FMA.
826 setOperationAction(ISD::FMA, MVT::f64, Expand);
827 setOperationAction(ISD::FMA, MVT::f32, Expand);
829 // f80 always uses X87.
830 if (UseX87) {
831 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
832 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
833 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
835 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
836 addLegalFPImmediate(TmpFlt); // FLD0
837 TmpFlt.changeSign();
838 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
840 bool ignored;
841 APFloat TmpFlt2(+1.0);
842 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
843 &ignored);
844 addLegalFPImmediate(TmpFlt2); // FLD1
845 TmpFlt2.changeSign();
846 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
849 // Always expand sin/cos functions even though x87 has an instruction.
850 // clang-format off
851 setOperationAction(ISD::FSIN , MVT::f80, Expand);
852 setOperationAction(ISD::FCOS , MVT::f80, Expand);
853 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
854 setOperationAction(ISD::FTAN , MVT::f80, Expand);
855 setOperationAction(ISD::FASIN , MVT::f80, Expand);
856 setOperationAction(ISD::FACOS , MVT::f80, Expand);
857 setOperationAction(ISD::FATAN , MVT::f80, Expand);
858 setOperationAction(ISD::FATAN2 , MVT::f80, Expand);
859 setOperationAction(ISD::FSINH , MVT::f80, Expand);
860 setOperationAction(ISD::FCOSH , MVT::f80, Expand);
861 setOperationAction(ISD::FTANH , MVT::f80, Expand);
862 // clang-format on
864 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
865 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
866 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
867 setOperationAction(ISD::FRINT, MVT::f80, Expand);
868 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
869 setOperationAction(ISD::FROUNDEVEN, MVT::f80, Expand);
870 setOperationAction(ISD::FMA, MVT::f80, Expand);
871 setOperationAction(ISD::LROUND, MVT::f80, LibCall);
872 setOperationAction(ISD::LLROUND, MVT::f80, LibCall);
873 setOperationAction(ISD::LRINT, MVT::f80, Custom);
874 setOperationAction(ISD::LLRINT, MVT::f80, Custom);
876 // Handle constrained floating-point operations of scalar.
877 setOperationAction(ISD::STRICT_FADD , MVT::f80, Legal);
878 setOperationAction(ISD::STRICT_FSUB , MVT::f80, Legal);
879 setOperationAction(ISD::STRICT_FMUL , MVT::f80, Legal);
880 setOperationAction(ISD::STRICT_FDIV , MVT::f80, Legal);
881 setOperationAction(ISD::STRICT_FSQRT , MVT::f80, Legal);
882 if (isTypeLegal(MVT::f16)) {
883 setOperationAction(ISD::FP_EXTEND, MVT::f80, Custom);
884 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Custom);
885 } else {
886 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
888 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
889 // as Custom.
890 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
893 // f128 uses xmm registers, but most operations require libcalls.
894 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
895 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
896 : &X86::VR128RegClass);
898 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
900 setOperationAction(ISD::FADD, MVT::f128, LibCall);
901 setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
902 setOperationAction(ISD::FSUB, MVT::f128, LibCall);
903 setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
904 setOperationAction(ISD::FDIV, MVT::f128, LibCall);
905 setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
906 setOperationAction(ISD::FMUL, MVT::f128, LibCall);
907 setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
908 setOperationAction(ISD::FMA, MVT::f128, LibCall);
909 setOperationAction(ISD::STRICT_FMA, MVT::f128, LibCall);
911 setOperationAction(ISD::FABS, MVT::f128, Custom);
912 setOperationAction(ISD::FNEG, MVT::f128, Custom);
913 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
915 // clang-format off
916 setOperationAction(ISD::FSIN, MVT::f128, LibCall);
917 setOperationAction(ISD::STRICT_FSIN, MVT::f128, LibCall);
918 setOperationAction(ISD::FCOS, MVT::f128, LibCall);
919 setOperationAction(ISD::STRICT_FCOS, MVT::f128, LibCall);
920 setOperationAction(ISD::FSINCOS, MVT::f128, LibCall);
921 setOperationAction(ISD::FTAN, MVT::f128, LibCall);
922 setOperationAction(ISD::STRICT_FTAN, MVT::f128, LibCall);
923 // clang-format on
924 // No STRICT_FSINCOS
925 setOperationAction(ISD::FSQRT, MVT::f128, LibCall);
926 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
928 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
929 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
930 // We need to custom handle any FP_ROUND with an f128 input, but
931 // LegalizeDAG uses the result type to know when to run a custom handler.
932 // So we have to list all legal floating point result types here.
933 if (isTypeLegal(MVT::f32)) {
934 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
935 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
937 if (isTypeLegal(MVT::f64)) {
938 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
939 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
941 if (isTypeLegal(MVT::f80)) {
942 setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
943 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
944 setOperationAction(ISD::FCANONICALIZE, MVT::f80, Custom);
947 setOperationAction(ISD::SETCC, MVT::f128, Custom);
949 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
950 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
951 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
952 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
953 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
954 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
957 // Always use a library call for pow.
958 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
959 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
960 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
961 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
963 setOperationAction(ISD::FLOG, MVT::f80, Expand);
964 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
965 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
966 setOperationAction(ISD::FEXP, MVT::f80, Expand);
967 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
968 setOperationAction(ISD::FEXP10, MVT::f80, Expand);
969 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
970 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
972 // Some FP actions are always expanded for vector types.
973 for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
974 MVT::v4f32, MVT::v8f32, MVT::v16f32,
975 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
976 // clang-format off
977 setOperationAction(ISD::FSIN, VT, Expand);
978 setOperationAction(ISD::FSINCOS, VT, Expand);
979 setOperationAction(ISD::FCOS, VT, Expand);
980 setOperationAction(ISD::FTAN, VT, Expand);
981 setOperationAction(ISD::FREM, VT, Expand);
982 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
983 setOperationAction(ISD::FPOW, VT, Expand);
984 setOperationAction(ISD::FLOG, VT, Expand);
985 setOperationAction(ISD::FLOG2, VT, Expand);
986 setOperationAction(ISD::FLOG10, VT, Expand);
987 setOperationAction(ISD::FEXP, VT, Expand);
988 setOperationAction(ISD::FEXP2, VT, Expand);
989 setOperationAction(ISD::FEXP10, VT, Expand);
990 // clang-format on
993 // First set operation action for all vector types to either promote
994 // (for widening) or expand (for scalarization). Then we will selectively
995 // turn on ones that can be effectively codegen'd.
996 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
997 setOperationAction(ISD::SDIV, VT, Expand);
998 setOperationAction(ISD::UDIV, VT, Expand);
999 setOperationAction(ISD::SREM, VT, Expand);
1000 setOperationAction(ISD::UREM, VT, Expand);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
1002 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
1003 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
1004 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
1005 setOperationAction(ISD::FMA, VT, Expand);
1006 setOperationAction(ISD::FFLOOR, VT, Expand);
1007 setOperationAction(ISD::FCEIL, VT, Expand);
1008 setOperationAction(ISD::FTRUNC, VT, Expand);
1009 setOperationAction(ISD::FRINT, VT, Expand);
1010 setOperationAction(ISD::FNEARBYINT, VT, Expand);
1011 setOperationAction(ISD::FROUNDEVEN, VT, Expand);
1012 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1013 setOperationAction(ISD::MULHS, VT, Expand);
1014 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1015 setOperationAction(ISD::MULHU, VT, Expand);
1016 setOperationAction(ISD::SDIVREM, VT, Expand);
1017 setOperationAction(ISD::UDIVREM, VT, Expand);
1018 setOperationAction(ISD::CTPOP, VT, Expand);
1019 setOperationAction(ISD::CTTZ, VT, Expand);
1020 setOperationAction(ISD::CTLZ, VT, Expand);
1021 setOperationAction(ISD::ROTL, VT, Expand);
1022 setOperationAction(ISD::ROTR, VT, Expand);
1023 setOperationAction(ISD::BSWAP, VT, Expand);
1024 setOperationAction(ISD::SETCC, VT, Expand);
1025 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
1026 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
1027 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
1028 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
1029 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
1030 setOperationAction(ISD::TRUNCATE, VT, Expand);
1031 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
1032 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
1033 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
1034 setOperationAction(ISD::SELECT_CC, VT, Expand);
1035 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1036 setTruncStoreAction(InnerVT, VT, Expand);
1038 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
1039 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
1041 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
1042 // types, we have to deal with them whether we ask for Expansion or not.
1043 // Setting Expand causes its own optimisation problems though, so leave
1044 // them legal.
1045 if (VT.getVectorElementType() == MVT::i1)
1046 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1048 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
1049 // split/scalarized right now.
1050 if (VT.getVectorElementType() == MVT::f16 ||
1051 VT.getVectorElementType() == MVT::bf16)
1052 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1056 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
1057 // with -msoft-float, disable use of MMX as well.
1058 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
1059 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
1060 // No operations on x86mmx supported, everything uses intrinsics.
1063 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
1064 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1065 : &X86::VR128RegClass);
1067 setOperationAction(ISD::FMAXIMUM, MVT::f32, Custom);
1068 setOperationAction(ISD::FMINIMUM, MVT::f32, Custom);
1070 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
1071 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
1072 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
1073 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1074 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
1075 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1076 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1077 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
1078 setOperationAction(ISD::FCANONICALIZE, MVT::v4f32, Custom);
1080 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
1081 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
1082 setOperationAction(ISD::FCANONICALIZE, MVT::v2f32, Custom);
1084 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1085 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1086 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1087 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1088 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1091 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1092 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1093 : &X86::VR128RegClass);
1095 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1096 // registers cannot be used even for integer operations.
1097 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1098 : &X86::VR128RegClass);
1099 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1100 : &X86::VR128RegClass);
1101 addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1102 : &X86::VR128RegClass);
1103 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1104 : &X86::VR128RegClass);
1105 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1106 : &X86::VR128RegClass);
1108 for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 }) {
1109 setOperationAction(ISD::FMAXIMUM, VT, Custom);
1110 setOperationAction(ISD::FMINIMUM, VT, Custom);
1113 for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
1114 MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
1115 setOperationAction(ISD::SDIV, VT, Custom);
1116 setOperationAction(ISD::SREM, VT, Custom);
1117 setOperationAction(ISD::UDIV, VT, Custom);
1118 setOperationAction(ISD::UREM, VT, Custom);
1121 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
1122 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
1123 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
1125 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1126 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1127 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1128 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
1129 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
1130 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
1131 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
1132 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
1133 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
1134 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1135 setOperationAction(ISD::AVGCEILU, MVT::v16i8, Legal);
1136 setOperationAction(ISD::AVGCEILU, MVT::v8i16, Legal);
1138 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
1139 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
1140 setOperationAction(ISD::UMULO, MVT::v2i32, Custom);
1142 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
1143 setOperationAction(ISD::FCANONICALIZE, MVT::v2f64, Custom);
1144 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
1145 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
1147 setOperationAction(ISD::LRINT, MVT::v4f32, Custom);
1149 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1150 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1151 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1152 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1153 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1156 setOperationAction(ISD::UADDSAT, MVT::v16i8, Legal);
1157 setOperationAction(ISD::SADDSAT, MVT::v16i8, Legal);
1158 setOperationAction(ISD::USUBSAT, MVT::v16i8, Legal);
1159 setOperationAction(ISD::SSUBSAT, MVT::v16i8, Legal);
1160 setOperationAction(ISD::UADDSAT, MVT::v8i16, Legal);
1161 setOperationAction(ISD::SADDSAT, MVT::v8i16, Legal);
1162 setOperationAction(ISD::USUBSAT, MVT::v8i16, Legal);
1163 setOperationAction(ISD::SSUBSAT, MVT::v8i16, Legal);
1164 setOperationAction(ISD::USUBSAT, MVT::v4i32, Custom);
1165 setOperationAction(ISD::USUBSAT, MVT::v2i64, Custom);
1167 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1168 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1169 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1170 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1172 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1173 setOperationAction(ISD::SETCC, VT, Custom);
1174 setOperationAction(ISD::CTPOP, VT, Custom);
1175 setOperationAction(ISD::ABS, VT, Custom);
1176 setOperationAction(ISD::ABDS, VT, Custom);
1177 setOperationAction(ISD::ABDU, VT, Custom);
1179 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1180 // setcc all the way to isel and prefer SETGT in some isel patterns.
1181 setCondCodeAction(ISD::SETLT, VT, Custom);
1182 setCondCodeAction(ISD::SETLE, VT, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
1187 setOperationAction(ISD::STRICT_FSETCC, MVT::v2f64, Custom);
1188 setOperationAction(ISD::STRICT_FSETCC, MVT::v4f32, Custom);
1189 setOperationAction(ISD::STRICT_FSETCCS, MVT::v2f64, Custom);
1190 setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f32, Custom);
1192 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1193 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1194 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1195 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1196 setOperationAction(ISD::VSELECT, VT, Custom);
1197 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1200 for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1201 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1202 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1203 setOperationAction(ISD::VSELECT, VT, Custom);
1205 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1206 continue;
1208 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1209 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1211 setF16Action(MVT::v8f16, Expand);
1212 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1213 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1214 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1215 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1216 setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1217 setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1218 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Custom);
1220 // Custom lower v2i64 and v2f64 selects.
1221 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1222 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1223 setOperationAction(ISD::SELECT, MVT::v4i32, Custom);
1224 setOperationAction(ISD::SELECT, MVT::v8i16, Custom);
1225 setOperationAction(ISD::SELECT, MVT::v8f16, Custom);
1226 setOperationAction(ISD::SELECT, MVT::v16i8, Custom);
1228 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Custom);
1229 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Custom);
1230 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
1231 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1232 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Custom);
1233 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i32, Custom);
1235 // Custom legalize these to avoid over promotion or custom promotion.
1236 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1237 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1238 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1239 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1240 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1243 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
1244 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Custom);
1245 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
1246 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i32, Custom);
1248 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
1249 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i32, Custom);
1251 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
1252 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Custom);
1254 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1255 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1256 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f32, Custom);
1257 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1258 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f32, Custom);
1260 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1261 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v2f32, Custom);
1262 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1263 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v2f32, Custom);
1265 // We want to legalize this to an f64 load rather than an i64 load on
1266 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1267 // store.
1268 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1269 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1270 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1271 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1272 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1273 setOperationAction(ISD::STORE, MVT::v8i8, Custom);
1275 // Add 32-bit vector stores to help vectorization opportunities.
1276 setOperationAction(ISD::STORE, MVT::v2i16, Custom);
1277 setOperationAction(ISD::STORE, MVT::v4i8, Custom);
1279 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1280 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1281 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1282 if (!Subtarget.hasAVX512())
1283 setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1285 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1286 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1287 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1289 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1291 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
1292 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
1293 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Custom);
1294 setOperationAction(ISD::TRUNCATE, MVT::v2i64, Custom);
1295 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
1296 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
1297 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1298 setOperationAction(ISD::TRUNCATE, MVT::v4i64, Custom);
1299 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
1300 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1301 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1302 setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1303 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1304 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1305 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1306 setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1308 // In the customized shift lowering, the legal v4i32/v2i64 cases
1309 // in AVX2 will be recognized.
1310 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1311 setOperationAction(ISD::SRL, VT, Custom);
1312 setOperationAction(ISD::SHL, VT, Custom);
1313 setOperationAction(ISD::SRA, VT, Custom);
1314 if (VT == MVT::v2i64) continue;
1315 setOperationAction(ISD::ROTL, VT, Custom);
1316 setOperationAction(ISD::ROTR, VT, Custom);
1317 setOperationAction(ISD::FSHL, VT, Custom);
1318 setOperationAction(ISD::FSHR, VT, Custom);
1321 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1322 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1323 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1324 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1325 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1328 if (Subtarget.hasGFNI()) {
1329 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
1330 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
1331 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
1332 setOperationAction(ISD::BITREVERSE, MVT::i64, Custom);
1335 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1336 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1337 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1338 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1340 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1341 setOperationAction(ISD::BITREVERSE, VT, Custom);
1342 setOperationAction(ISD::CTLZ, VT, Custom);
1345 // These might be better off as horizontal vector ops.
1346 setOperationAction(ISD::ADD, MVT::i16, Custom);
1347 setOperationAction(ISD::ADD, MVT::i32, Custom);
1348 setOperationAction(ISD::SUB, MVT::i16, Custom);
1349 setOperationAction(ISD::SUB, MVT::i32, Custom);
1352 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1353 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1354 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1355 setOperationAction(ISD::STRICT_FFLOOR, RoundedTy, Legal);
1356 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1357 setOperationAction(ISD::STRICT_FCEIL, RoundedTy, Legal);
1358 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1359 setOperationAction(ISD::STRICT_FTRUNC, RoundedTy, Legal);
1360 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1361 setOperationAction(ISD::STRICT_FRINT, RoundedTy, Legal);
1362 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1363 setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy, Legal);
1364 setOperationAction(ISD::FROUNDEVEN, RoundedTy, Legal);
1365 setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy, Legal);
1367 setOperationAction(ISD::FROUND, RoundedTy, Custom);
1370 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1371 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1372 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1373 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1374 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1375 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1376 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1377 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1379 setOperationAction(ISD::UADDSAT, MVT::v4i32, Custom);
1380 setOperationAction(ISD::SADDSAT, MVT::v2i64, Custom);
1381 setOperationAction(ISD::SSUBSAT, MVT::v2i64, Custom);
1383 // FIXME: Do we need to handle scalar-to-vector here?
1384 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1385 setOperationAction(ISD::SMULO, MVT::v2i32, Custom);
1387 // We directly match byte blends in the backend as they match the VSELECT
1388 // condition form.
1389 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1391 // SSE41 brings specific instructions for doing vector sign extend even in
1392 // cases where we don't have SRA.
1393 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1394 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1395 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1398 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1399 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1400 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1401 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1402 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1403 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1404 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1405 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1408 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1409 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1410 // do the pre and post work in the vector domain.
1411 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Custom);
1412 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1413 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1414 // so that DAG combine doesn't try to turn it into uint_to_fp.
1415 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Custom);
1416 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1420 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1421 setOperationAction(ISD::UADDSAT, MVT::v2i64, Custom);
1424 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1425 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1426 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1427 setOperationAction(ISD::ROTL, VT, Custom);
1428 setOperationAction(ISD::ROTR, VT, Custom);
1431 // XOP can efficiently perform BITREVERSE with VPPERM.
1432 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1433 setOperationAction(ISD::BITREVERSE, VT, Custom);
1436 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1437 bool HasInt256 = Subtarget.hasInt256();
1439 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1440 : &X86::VR256RegClass);
1441 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1442 : &X86::VR256RegClass);
1443 addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1444 : &X86::VR256RegClass);
1445 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1446 : &X86::VR256RegClass);
1447 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1448 : &X86::VR256RegClass);
1449 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1450 : &X86::VR256RegClass);
1451 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1452 : &X86::VR256RegClass);
1454 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1455 setOperationAction(ISD::FFLOOR, VT, Legal);
1456 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
1457 setOperationAction(ISD::FCEIL, VT, Legal);
1458 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
1459 setOperationAction(ISD::FTRUNC, VT, Legal);
1460 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
1461 setOperationAction(ISD::FRINT, VT, Legal);
1462 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
1463 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1464 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1465 setOperationAction(ISD::FROUNDEVEN, VT, Legal);
1466 setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1468 setOperationAction(ISD::FROUND, VT, Custom);
1470 setOperationAction(ISD::FNEG, VT, Custom);
1471 setOperationAction(ISD::FABS, VT, Custom);
1472 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1474 setOperationAction(ISD::FMAXIMUM, VT, Custom);
1475 setOperationAction(ISD::FMINIMUM, VT, Custom);
1476 setOperationAction(ISD::FCANONICALIZE, VT, Custom);
1479 setOperationAction(ISD::LRINT, MVT::v8f32, Custom);
1480 setOperationAction(ISD::LRINT, MVT::v4f64, Custom);
1482 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1483 // even though v8i16 is a legal type.
1484 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1485 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1486 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1487 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1488 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Custom);
1489 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Custom);
1490 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i32, Custom);
1492 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Custom);
1493 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i32, Custom);
1494 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Expand);
1495 setOperationAction(ISD::FP_ROUND, MVT::v8f16, Expand);
1496 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Custom);
1497 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v4f64, Custom);
1499 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v4f32, Legal);
1500 setOperationAction(ISD::STRICT_FADD, MVT::v8f32, Legal);
1501 setOperationAction(ISD::STRICT_FADD, MVT::v4f64, Legal);
1502 setOperationAction(ISD::STRICT_FSUB, MVT::v8f32, Legal);
1503 setOperationAction(ISD::STRICT_FSUB, MVT::v4f64, Legal);
1504 setOperationAction(ISD::STRICT_FMUL, MVT::v8f32, Legal);
1505 setOperationAction(ISD::STRICT_FMUL, MVT::v4f64, Legal);
1506 setOperationAction(ISD::STRICT_FDIV, MVT::v8f32, Legal);
1507 setOperationAction(ISD::STRICT_FDIV, MVT::v4f64, Legal);
1508 setOperationAction(ISD::STRICT_FSQRT, MVT::v8f32, Legal);
1509 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f64, Legal);
1511 if (!Subtarget.hasAVX512())
1512 setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1514 // In the customized shift lowering, the legal v8i32/v4i64 cases
1515 // in AVX2 will be recognized.
1516 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1517 setOperationAction(ISD::SRL, VT, Custom);
1518 setOperationAction(ISD::SHL, VT, Custom);
1519 setOperationAction(ISD::SRA, VT, Custom);
1520 setOperationAction(ISD::ABDS, VT, Custom);
1521 setOperationAction(ISD::ABDU, VT, Custom);
1522 if (VT == MVT::v4i64) continue;
1523 setOperationAction(ISD::ROTL, VT, Custom);
1524 setOperationAction(ISD::ROTR, VT, Custom);
1525 setOperationAction(ISD::FSHL, VT, Custom);
1526 setOperationAction(ISD::FSHR, VT, Custom);
1529 // These types need custom splitting if their input is a 128-bit vector.
1530 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1531 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1532 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1533 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1535 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1536 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1537 setOperationAction(ISD::SELECT, MVT::v8i32, Custom);
1538 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1539 setOperationAction(ISD::SELECT, MVT::v16f16, Custom);
1540 setOperationAction(ISD::SELECT, MVT::v32i8, Custom);
1541 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1543 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1544 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1545 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1546 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1549 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1550 setOperationAction(ISD::TRUNCATE, MVT::v32i16, Custom);
1551 setOperationAction(ISD::TRUNCATE, MVT::v32i32, Custom);
1552 setOperationAction(ISD::TRUNCATE, MVT::v32i64, Custom);
1554 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1555 setOperationAction(ISD::SETCC, VT, Custom);
1556 setOperationAction(ISD::CTPOP, VT, Custom);
1557 setOperationAction(ISD::CTLZ, VT, Custom);
1558 setOperationAction(ISD::BITREVERSE, VT, Custom);
1560 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1561 // setcc all the way to isel and prefer SETGT in some isel patterns.
1562 setCondCodeAction(ISD::SETLT, VT, Custom);
1563 setCondCodeAction(ISD::SETLE, VT, Custom);
1566 setOperationAction(ISD::SETCC, MVT::v4f64, Custom);
1567 setOperationAction(ISD::SETCC, MVT::v8f32, Custom);
1568 setOperationAction(ISD::STRICT_FSETCC, MVT::v4f64, Custom);
1569 setOperationAction(ISD::STRICT_FSETCC, MVT::v8f32, Custom);
1570 setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f64, Custom);
1571 setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f32, Custom);
1573 if (Subtarget.hasAnyFMA()) {
1574 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1575 MVT::v2f64, MVT::v4f64 }) {
1576 setOperationAction(ISD::FMA, VT, Legal);
1577 setOperationAction(ISD::STRICT_FMA, VT, Legal);
1581 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1582 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1583 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1586 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1587 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1588 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1589 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1591 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1592 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1593 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1594 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1595 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1596 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1597 setOperationAction(ISD::AVGCEILU, MVT::v16i16, HasInt256 ? Legal : Custom);
1598 setOperationAction(ISD::AVGCEILU, MVT::v32i8, HasInt256 ? Legal : Custom);
1600 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1601 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1603 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1604 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1605 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1606 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1607 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1609 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1610 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1611 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1612 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1613 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1614 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1615 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1616 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1617 setOperationAction(ISD::UADDSAT, MVT::v8i32, Custom);
1618 setOperationAction(ISD::USUBSAT, MVT::v8i32, Custom);
1619 setOperationAction(ISD::UADDSAT, MVT::v4i64, Custom);
1620 setOperationAction(ISD::USUBSAT, MVT::v4i64, Custom);
1622 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1623 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1624 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1625 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1626 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1627 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1630 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1631 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1632 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1635 if (HasInt256) {
1636 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1637 // when we have a 256bit-wide blend with immediate.
1638 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1639 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1641 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1642 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1643 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1644 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1645 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1646 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1647 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1648 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1652 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1653 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1654 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1655 setOperationAction(ISD::MSTORE, VT, Legal);
1658 // Extract subvector is special because the value type
1659 // (result) is 128-bit but the source is 256-bit wide.
1660 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1661 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1662 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1665 // Custom lower several nodes for 256-bit types.
1666 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1667 MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1668 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1669 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1670 setOperationAction(ISD::VSELECT, VT, Custom);
1671 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1673 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1674 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1675 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1676 setOperationAction(ISD::STORE, VT, Custom);
1678 setF16Action(MVT::v16f16, Expand);
1679 setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1680 setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1681 setOperationAction(ISD::FCOPYSIGN, MVT::v16f16, Custom);
1682 setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1683 setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1684 setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1685 setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1687 if (HasInt256) {
1688 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1690 // Custom legalize 2x32 to get a little better code.
1691 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1692 setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1694 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1695 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1696 setOperationAction(ISD::MGATHER, VT, Custom);
1700 if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1701 Subtarget.hasF16C()) {
1702 for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1703 setOperationAction(ISD::FP_ROUND, VT, Custom);
1704 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1706 for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1707 setOperationAction(ISD::FP_EXTEND, VT, Custom);
1708 setOperationAction(ISD::STRICT_FP_EXTEND, VT, Custom);
1710 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1711 setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1712 setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1716 // This block controls legalization of the mask vector sizes that are
1717 // available with AVX512. 512-bit vectors are in a separate block controlled
1718 // by useAVX512Regs.
1719 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1720 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1721 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1722 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1723 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1724 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1726 setOperationAction(ISD::SELECT, MVT::v1i1, Custom);
1727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1728 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1730 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1731 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1732 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1733 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1734 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1735 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1736 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1737 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1738 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Custom);
1739 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Custom);
1740 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i1, Custom);
1741 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i1, Custom);
1742 setOperationAction(ISD::FCANONICALIZE, MVT::v8f16, Custom);
1743 setOperationAction(ISD::FCANONICALIZE, MVT::v16f16, Custom);
1744 setOperationAction(ISD::FCANONICALIZE, MVT::v32f16, Custom);
1746 // There is no byte sized k-register load or store without AVX512DQ.
1747 if (!Subtarget.hasDQI()) {
1748 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1749 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1750 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1751 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1753 setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1754 setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1755 setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1756 setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1759 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1760 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1761 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1762 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1763 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1766 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1767 setOperationAction(ISD::VSELECT, VT, Expand);
1769 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1770 setOperationAction(ISD::SETCC, VT, Custom);
1771 setOperationAction(ISD::SELECT, VT, Custom);
1772 setOperationAction(ISD::TRUNCATE, VT, Custom);
1774 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1775 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1777 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1778 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1779 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1782 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1783 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1785 if (Subtarget.hasDQI() && Subtarget.hasVLX()) {
1786 for (MVT VT : {MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1787 setOperationAction(ISD::LRINT, VT, Legal);
1788 setOperationAction(ISD::LLRINT, VT, Legal);
1792 // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1793 // elements. 512-bits can be disabled based on prefer-vector-width and
1794 // required-vector-width function attributes.
1795 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1796 bool HasBWI = Subtarget.hasBWI();
1798 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1799 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1800 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1801 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1802 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1803 addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1804 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1806 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1807 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1808 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1809 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1810 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1811 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1812 if (HasBWI)
1813 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1816 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1817 setOperationAction(ISD::FMAXIMUM, VT, Custom);
1818 setOperationAction(ISD::FMINIMUM, VT, Custom);
1819 setOperationAction(ISD::FNEG, VT, Custom);
1820 setOperationAction(ISD::FABS, VT, Custom);
1821 setOperationAction(ISD::FMA, VT, Legal);
1822 setOperationAction(ISD::STRICT_FMA, VT, Legal);
1823 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1824 setOperationAction(ISD::FCANONICALIZE, VT, Custom);
1826 setOperationAction(ISD::LRINT, MVT::v16f32,
1827 Subtarget.hasDQI() ? Legal : Custom);
1828 setOperationAction(ISD::LRINT, MVT::v8f64,
1829 Subtarget.hasDQI() ? Legal : Custom);
1830 if (Subtarget.hasDQI())
1831 setOperationAction(ISD::LLRINT, MVT::v8f64, Legal);
1833 for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1834 setOperationPromotedToType(ISD::FP_TO_SINT , VT, MVT::v16i32);
1835 setOperationPromotedToType(ISD::FP_TO_UINT , VT, MVT::v16i32);
1836 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1837 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1840 for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1841 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1842 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1843 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1844 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1847 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Custom);
1848 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Custom);
1849 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Custom);
1850 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Custom);
1851 setOperationAction(ISD::FP_EXTEND, MVT::v8f64, Custom);
1852 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64, Custom);
1854 setOperationAction(ISD::STRICT_FADD, MVT::v16f32, Legal);
1855 setOperationAction(ISD::STRICT_FADD, MVT::v8f64, Legal);
1856 setOperationAction(ISD::STRICT_FSUB, MVT::v16f32, Legal);
1857 setOperationAction(ISD::STRICT_FSUB, MVT::v8f64, Legal);
1858 setOperationAction(ISD::STRICT_FMUL, MVT::v16f32, Legal);
1859 setOperationAction(ISD::STRICT_FMUL, MVT::v8f64, Legal);
1860 setOperationAction(ISD::STRICT_FDIV, MVT::v16f32, Legal);
1861 setOperationAction(ISD::STRICT_FDIV, MVT::v8f64, Legal);
1862 setOperationAction(ISD::STRICT_FSQRT, MVT::v16f32, Legal);
1863 setOperationAction(ISD::STRICT_FSQRT, MVT::v8f64, Legal);
1864 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v8f32, Legal);
1866 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1867 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1868 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1869 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1870 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1871 if (HasBWI)
1872 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1874 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1875 // to 512-bit rather than use the AVX2 instructions so that we can use
1876 // k-masks.
1877 if (!Subtarget.hasVLX()) {
1878 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1879 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1880 setOperationAction(ISD::MLOAD, VT, Custom);
1881 setOperationAction(ISD::MSTORE, VT, Custom);
1885 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Legal);
1886 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1887 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
1888 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1889 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1890 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1891 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1892 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1893 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1894 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1895 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1896 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1898 if (HasBWI) {
1899 // Extends from v64i1 masks to 512-bit vectors.
1900 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1901 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1902 setOperationAction(ISD::ANY_EXTEND, MVT::v64i8, Custom);
1905 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1906 setOperationAction(ISD::FFLOOR, VT, Legal);
1907 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
1908 setOperationAction(ISD::FCEIL, VT, Legal);
1909 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
1910 setOperationAction(ISD::FTRUNC, VT, Legal);
1911 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
1912 setOperationAction(ISD::FRINT, VT, Legal);
1913 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
1914 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1915 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1916 setOperationAction(ISD::FROUNDEVEN, VT, Legal);
1917 setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1919 setOperationAction(ISD::FROUND, VT, Custom);
1922 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1923 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1924 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1927 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1928 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1929 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
1930 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
1932 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1933 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1934 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1935 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1937 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1938 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1939 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1940 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1941 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1942 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1943 setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1944 setOperationAction(ISD::AVGCEILU, MVT::v64i8, HasBWI ? Legal : Custom);
1946 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1947 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1949 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1950 setOperationAction(ISD::SRL, VT, Custom);
1951 setOperationAction(ISD::SHL, VT, Custom);
1952 setOperationAction(ISD::SRA, VT, Custom);
1953 setOperationAction(ISD::ROTL, VT, Custom);
1954 setOperationAction(ISD::ROTR, VT, Custom);
1955 setOperationAction(ISD::SETCC, VT, Custom);
1956 setOperationAction(ISD::ABDS, VT, Custom);
1957 setOperationAction(ISD::ABDU, VT, Custom);
1958 setOperationAction(ISD::BITREVERSE, VT, Custom);
1960 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1961 // setcc all the way to isel and prefer SETGT in some isel patterns.
1962 setCondCodeAction(ISD::SETLT, VT, Custom);
1963 setCondCodeAction(ISD::SETLE, VT, Custom);
1966 setOperationAction(ISD::SETCC, MVT::v8f64, Custom);
1967 setOperationAction(ISD::SETCC, MVT::v16f32, Custom);
1968 setOperationAction(ISD::STRICT_FSETCC, MVT::v8f64, Custom);
1969 setOperationAction(ISD::STRICT_FSETCC, MVT::v16f32, Custom);
1970 setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f64, Custom);
1971 setOperationAction(ISD::STRICT_FSETCCS, MVT::v16f32, Custom);
1973 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1974 setOperationAction(ISD::SMAX, VT, Legal);
1975 setOperationAction(ISD::UMAX, VT, Legal);
1976 setOperationAction(ISD::SMIN, VT, Legal);
1977 setOperationAction(ISD::UMIN, VT, Legal);
1978 setOperationAction(ISD::ABS, VT, Legal);
1979 setOperationAction(ISD::CTPOP, VT, Custom);
1982 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1983 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
1984 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
1985 setOperationAction(ISD::CTLZ, VT, Custom);
1986 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
1987 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
1988 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
1989 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
1990 setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1991 setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1992 setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1993 setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1996 setOperationAction(ISD::FSHL, MVT::v64i8, Custom);
1997 setOperationAction(ISD::FSHR, MVT::v64i8, Custom);
1998 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
1999 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
2000 setOperationAction(ISD::FSHL, MVT::v16i32, Custom);
2001 setOperationAction(ISD::FSHR, MVT::v16i32, Custom);
2003 if (Subtarget.hasDQI()) {
2004 for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
2005 ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
2006 ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT})
2007 setOperationAction(Opc, MVT::v8i64, Custom);
2008 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
2011 if (Subtarget.hasCDI()) {
2012 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
2013 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
2014 setOperationAction(ISD::CTLZ, VT, Legal);
2016 } // Subtarget.hasCDI()
2018 if (Subtarget.hasVPOPCNTDQ()) {
2019 for (auto VT : { MVT::v16i32, MVT::v8i64 })
2020 setOperationAction(ISD::CTPOP, VT, Legal);
2023 // Extract subvector is special because the value type
2024 // (result) is 256-bit but the source is 512-bit wide.
2025 // 128-bit was made Legal under AVX1.
2026 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
2027 MVT::v16f16, MVT::v8f32, MVT::v4f64 })
2028 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
2030 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
2031 MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
2032 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
2033 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
2034 setOperationAction(ISD::SELECT, VT, Custom);
2035 setOperationAction(ISD::VSELECT, VT, Custom);
2036 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2037 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2038 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2039 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
2040 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
2042 setF16Action(MVT::v32f16, Expand);
2043 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Custom);
2044 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f16, Custom);
2045 setOperationAction(ISD::FP_EXTEND, MVT::v16f32, Custom);
2046 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v16f32, Custom);
2047 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2048 setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
2050 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
2051 setOperationAction(ISD::MLOAD, VT, Legal);
2052 setOperationAction(ISD::MSTORE, VT, Legal);
2053 setOperationAction(ISD::MGATHER, VT, Custom);
2054 setOperationAction(ISD::MSCATTER, VT, Custom);
2056 if (HasBWI) {
2057 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2058 setOperationAction(ISD::MLOAD, VT, Legal);
2059 setOperationAction(ISD::MSTORE, VT, Legal);
2061 } else {
2062 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
2063 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
2066 if (Subtarget.hasVBMI2()) {
2067 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2068 setOperationAction(ISD::FSHL, VT, Custom);
2069 setOperationAction(ISD::FSHR, VT, Custom);
2072 setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
2073 setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
2076 setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2077 setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2078 setOperationAction(ISD::FCOPYSIGN, MVT::v32f16, Custom);
2079 }// useAVX512Regs
2081 if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
2082 for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
2083 MVT::v4i64}) {
2084 setOperationAction(ISD::FSHL, VT, Custom);
2085 setOperationAction(ISD::FSHR, VT, Custom);
2089 // This block controls legalization for operations that don't have
2090 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2091 // narrower widths.
2092 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2093 // These operations are handled on non-VLX by artificially widening in
2094 // isel patterns.
2096 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32, Custom);
2097 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Custom);
2098 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i32, Custom);
2100 if (Subtarget.hasDQI()) {
2101 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2102 // v2f32 UINT_TO_FP is already custom under SSE2.
2103 assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
2104 isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
2105 "Unexpected operation action!");
2106 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2107 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
2108 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
2109 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
2110 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
2113 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2114 setOperationAction(ISD::SMAX, VT, Legal);
2115 setOperationAction(ISD::UMAX, VT, Legal);
2116 setOperationAction(ISD::SMIN, VT, Legal);
2117 setOperationAction(ISD::UMIN, VT, Legal);
2118 setOperationAction(ISD::ABS, VT, Legal);
2121 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2122 setOperationAction(ISD::ROTL, VT, Custom);
2123 setOperationAction(ISD::ROTR, VT, Custom);
2126 // Custom legalize 2x32 to get a little better code.
2127 setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
2128 setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
2130 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2131 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2132 setOperationAction(ISD::MSCATTER, VT, Custom);
2134 if (Subtarget.hasDQI()) {
2135 for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
2136 ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
2137 ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT}) {
2138 setOperationAction(Opc, MVT::v2i64, Custom);
2139 setOperationAction(Opc, MVT::v4i64, Custom);
2141 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2142 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2145 if (Subtarget.hasCDI()) {
2146 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2147 setOperationAction(ISD::CTLZ, VT, Legal);
2149 } // Subtarget.hasCDI()
2151 if (Subtarget.hasVPOPCNTDQ()) {
2152 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
2153 setOperationAction(ISD::CTPOP, VT, Legal);
2156 // We can try to convert vectors to different sizes to leverage legal
2157 // `vpcompress` cases. So we mark these supported vector sizes as Custom and
2158 // then specialize to Legal below.
2159 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2160 MVT::v4f64, MVT::v2i64, MVT::v2f64, MVT::v16i8, MVT::v8i16,
2161 MVT::v16i16, MVT::v8i8})
2162 setOperationAction(ISD::VECTOR_COMPRESS, VT, Custom);
2164 // Legal vpcompress depends on various AVX512 extensions.
2165 // Legal in AVX512F
2166 for (MVT VT : {MVT::v16i32, MVT::v16f32, MVT::v8i64, MVT::v8f64})
2167 setOperationAction(ISD::VECTOR_COMPRESS, VT, Legal);
2169 // Legal in AVX512F + AVX512VL
2170 if (Subtarget.hasVLX())
2171 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2172 MVT::v4f64, MVT::v2i64, MVT::v2f64})
2173 setOperationAction(ISD::VECTOR_COMPRESS, VT, Legal);
2175 // Legal in AVX512F + AVX512VBMI2
2176 if (Subtarget.hasVBMI2())
2177 for (MVT VT : {MVT::v32i16, MVT::v64i8})
2178 setOperationAction(ISD::VECTOR_COMPRESS, VT, Legal);
2180 // Legal in AVX512F + AVX512VL + AVX512VBMI2
2181 if (Subtarget.hasVBMI2() && Subtarget.hasVLX())
2182 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v32i8, MVT::v16i16})
2183 setOperationAction(ISD::VECTOR_COMPRESS, VT, Legal);
2186 // This block control legalization of v32i1/v64i1 which are available with
2187 // AVX512BW..
2188 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2189 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
2190 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
2192 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2193 setOperationAction(ISD::VSELECT, VT, Expand);
2194 setOperationAction(ISD::TRUNCATE, VT, Custom);
2195 setOperationAction(ISD::SETCC, VT, Custom);
2196 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2197 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
2198 setOperationAction(ISD::SELECT, VT, Custom);
2199 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2200 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2201 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
2202 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
2205 for (auto VT : { MVT::v16i1, MVT::v32i1 })
2206 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
2208 // Extends from v32i1 masks to 256-bit vectors.
2209 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
2210 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
2211 setOperationAction(ISD::ANY_EXTEND, MVT::v32i8, Custom);
2213 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
2214 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
2215 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2218 // These operations are handled on non-VLX by artificially widening in
2219 // isel patterns.
2220 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2222 if (Subtarget.hasBITALG()) {
2223 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2224 setOperationAction(ISD::CTPOP, VT, Legal);
2228 if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2229 auto setGroup = [&] (MVT VT) {
2230 setOperationAction(ISD::FADD, VT, Legal);
2231 setOperationAction(ISD::STRICT_FADD, VT, Legal);
2232 setOperationAction(ISD::FSUB, VT, Legal);
2233 setOperationAction(ISD::STRICT_FSUB, VT, Legal);
2234 setOperationAction(ISD::FMUL, VT, Legal);
2235 setOperationAction(ISD::STRICT_FMUL, VT, Legal);
2236 setOperationAction(ISD::FDIV, VT, Legal);
2237 setOperationAction(ISD::STRICT_FDIV, VT, Legal);
2238 setOperationAction(ISD::FSQRT, VT, Legal);
2239 setOperationAction(ISD::STRICT_FSQRT, VT, Legal);
2241 setOperationAction(ISD::FFLOOR, VT, Legal);
2242 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
2243 setOperationAction(ISD::FCEIL, VT, Legal);
2244 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
2245 setOperationAction(ISD::FTRUNC, VT, Legal);
2246 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
2247 setOperationAction(ISD::FRINT, VT, Legal);
2248 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
2249 setOperationAction(ISD::FNEARBYINT, VT, Legal);
2250 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
2251 setOperationAction(ISD::FROUNDEVEN, VT, Legal);
2252 setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
2254 setOperationAction(ISD::FROUND, VT, Custom);
2256 setOperationAction(ISD::LOAD, VT, Legal);
2257 setOperationAction(ISD::STORE, VT, Legal);
2259 setOperationAction(ISD::FMA, VT, Legal);
2260 setOperationAction(ISD::STRICT_FMA, VT, Legal);
2261 setOperationAction(ISD::VSELECT, VT, Legal);
2262 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2263 setOperationAction(ISD::SELECT, VT, Custom);
2265 setOperationAction(ISD::FNEG, VT, Custom);
2266 setOperationAction(ISD::FABS, VT, Custom);
2267 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
2268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2269 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2271 setOperationAction(ISD::SETCC, VT, Custom);
2272 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
2273 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
2276 // AVX512_FP16 scalar operations
2277 setGroup(MVT::f16);
2278 setOperationAction(ISD::FREM, MVT::f16, Promote);
2279 setOperationAction(ISD::STRICT_FREM, MVT::f16, Promote);
2280 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
2281 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
2282 setOperationAction(ISD::STRICT_FROUND, MVT::f16, Promote);
2283 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Legal);
2284 setOperationAction(ISD::STRICT_FROUNDEVEN, MVT::f16, Legal);
2285 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
2286 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
2287 setOperationAction(ISD::FMAXIMUM, MVT::f16, Custom);
2288 setOperationAction(ISD::FMINIMUM, MVT::f16, Custom);
2289 setOperationAction(ISD::FP_EXTEND, MVT::f32, Legal);
2290 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
2292 setCondCodeAction(ISD::SETOEQ, MVT::f16, Expand);
2293 setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);
2295 if (Subtarget.useAVX512Regs()) {
2296 setGroup(MVT::v32f16);
2297 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32f16, Custom);
2298 setOperationAction(ISD::SINT_TO_FP, MVT::v32i16, Legal);
2299 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v32i16, Legal);
2300 setOperationAction(ISD::UINT_TO_FP, MVT::v32i16, Legal);
2301 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v32i16, Legal);
2302 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Legal);
2303 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f16, Legal);
2304 setOperationAction(ISD::FP_EXTEND, MVT::v16f32, Custom);
2305 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v16f32, Legal);
2306 setOperationAction(ISD::FP_EXTEND, MVT::v8f64, Custom);
2307 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64, Legal);
2308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32f16, Custom);
2310 setOperationAction(ISD::FP_TO_SINT, MVT::v32i16, Custom);
2311 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v32i16, Custom);
2312 setOperationAction(ISD::FP_TO_UINT, MVT::v32i16, Custom);
2313 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v32i16, Custom);
2314 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i8, MVT::v32i16);
2315 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i8,
2316 MVT::v32i16);
2317 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i8, MVT::v32i16);
2318 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i8,
2319 MVT::v32i16);
2320 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i1, MVT::v32i16);
2321 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i1,
2322 MVT::v32i16);
2323 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i1, MVT::v32i16);
2324 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i1,
2325 MVT::v32i16);
2327 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16f16, Legal);
2328 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32f16, Legal);
2329 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32f16, Custom);
2331 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Legal);
2332 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2335 if (Subtarget.hasVLX()) {
2336 setGroup(MVT::v8f16);
2337 setGroup(MVT::v16f16);
2339 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8f16, Legal);
2340 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16f16, Custom);
2341 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Legal);
2342 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i16, Legal);
2343 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Legal);
2344 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i16, Legal);
2345 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Legal);
2346 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i16, Legal);
2347 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Legal);
2348 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i16, Legal);
2350 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
2351 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i16, Custom);
2352 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
2353 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i16, Custom);
2354 setOperationAction(ISD::FP_ROUND, MVT::v8f16, Legal);
2355 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v8f16, Legal);
2356 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Custom);
2357 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f32, Legal);
2358 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Custom);
2359 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v4f64, Legal);
2361 // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2362 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f16, Custom);
2363 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16f16, Custom);
2365 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f16, Legal);
2366 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16f16, Legal);
2367 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f16, Custom);
2369 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2370 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2371 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2372 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2374 // Need to custom widen these to prevent scalarization.
2375 setOperationAction(ISD::LOAD, MVT::v4f16, Custom);
2376 setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2380 if (!Subtarget.useSoftFloat() &&
2381 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2382 addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2383 : &X86::VR128RegClass);
2384 addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2385 : &X86::VR256RegClass);
2386 // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2387 // provide the method to promote BUILD_VECTOR and INSERT_VECTOR_ELT.
2388 // Set the operation action Custom to do the customization later.
2389 setOperationAction(ISD::BUILD_VECTOR, MVT::bf16, Custom);
2390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::bf16, Custom);
2391 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2392 setF16Action(VT, Expand);
2393 if (!Subtarget.hasBF16())
2394 setOperationAction(ISD::VSELECT, VT, Custom);
2395 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2396 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2397 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
2398 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
2400 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
2401 setOperationPromotedToType(Opc, MVT::v8bf16, MVT::v8f32);
2402 setOperationPromotedToType(Opc, MVT::v16bf16, MVT::v16f32);
2404 setOperationAction(ISD::FP_ROUND, MVT::v8bf16, Custom);
2405 addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2408 if (!Subtarget.useSoftFloat() && Subtarget.hasBF16() &&
2409 Subtarget.useAVX512Regs()) {
2410 addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2411 setF16Action(MVT::v32bf16, Expand);
2412 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2413 setOperationPromotedToType(Opc, MVT::v32bf16, MVT::v32f32);
2414 setOperationAction(ISD::BUILD_VECTOR, MVT::v32bf16, Custom);
2415 setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2416 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32bf16, Custom);
2417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32bf16, Legal);
2418 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32bf16, Custom);
2421 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX10_2()) {
2422 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2423 setOperationAction(ISD::FADD, VT, Legal);
2424 setOperationAction(ISD::FSUB, VT, Legal);
2425 setOperationAction(ISD::FMUL, VT, Legal);
2426 setOperationAction(ISD::FDIV, VT, Legal);
2427 setOperationAction(ISD::FSQRT, VT, Legal);
2428 setOperationAction(ISD::FMA, VT, Legal);
2429 setOperationAction(ISD::SETCC, VT, Custom);
2431 if (Subtarget.hasAVX10_2_512()) {
2432 setOperationAction(ISD::FADD, MVT::v32bf16, Legal);
2433 setOperationAction(ISD::FSUB, MVT::v32bf16, Legal);
2434 setOperationAction(ISD::FMUL, MVT::v32bf16, Legal);
2435 setOperationAction(ISD::FDIV, MVT::v32bf16, Legal);
2436 setOperationAction(ISD::FSQRT, MVT::v32bf16, Legal);
2437 setOperationAction(ISD::FMA, MVT::v32bf16, Legal);
2438 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2440 for (auto VT : {MVT::f16, MVT::f32, MVT::f64}) {
2441 setCondCodeAction(ISD::SETOEQ, VT, Custom);
2442 setCondCodeAction(ISD::SETUNE, VT, Custom);
2446 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2447 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
2448 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2449 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2450 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
2451 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2453 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
2454 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2455 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2456 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
2457 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2459 if (Subtarget.hasBWI()) {
2460 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
2461 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
2464 if (Subtarget.hasFP16()) {
2465 // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2466 setOperationAction(ISD::FP_TO_SINT, MVT::v2f16, Custom);
2467 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f16, Custom);
2468 setOperationAction(ISD::FP_TO_UINT, MVT::v2f16, Custom);
2469 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f16, Custom);
2470 setOperationAction(ISD::FP_TO_SINT, MVT::v4f16, Custom);
2471 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f16, Custom);
2472 setOperationAction(ISD::FP_TO_UINT, MVT::v4f16, Custom);
2473 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f16, Custom);
2474 // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2475 setOperationAction(ISD::SINT_TO_FP, MVT::v2f16, Custom);
2476 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f16, Custom);
2477 setOperationAction(ISD::UINT_TO_FP, MVT::v2f16, Custom);
2478 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f16, Custom);
2479 setOperationAction(ISD::SINT_TO_FP, MVT::v4f16, Custom);
2480 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f16, Custom);
2481 setOperationAction(ISD::UINT_TO_FP, MVT::v4f16, Custom);
2482 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f16, Custom);
2483 // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2484 setOperationAction(ISD::FP_ROUND, MVT::v2f16, Custom);
2485 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v2f16, Custom);
2486 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
2487 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v4f16, Custom);
2488 // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2489 setOperationAction(ISD::FP_EXTEND, MVT::v2f16, Custom);
2490 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v2f16, Custom);
2491 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Custom);
2492 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v4f16, Custom);
2496 if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2497 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2500 // We want to custom lower some of our intrinsics.
2501 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
2502 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
2503 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
2504 if (!Subtarget.is64Bit()) {
2505 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
2508 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2509 // handle type legalization for these operations here.
2511 // FIXME: We really should do custom legalization for addition and
2512 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
2513 // than generic legalization for 64-bit multiplication-with-overflow, though.
2514 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2515 if (VT == MVT::i64 && !Subtarget.is64Bit())
2516 continue;
2517 // Add/Sub/Mul with overflow operations are custom lowered.
2518 setOperationAction(ISD::SADDO, VT, Custom);
2519 setOperationAction(ISD::UADDO, VT, Custom);
2520 setOperationAction(ISD::SSUBO, VT, Custom);
2521 setOperationAction(ISD::USUBO, VT, Custom);
2522 setOperationAction(ISD::SMULO, VT, Custom);
2523 setOperationAction(ISD::UMULO, VT, Custom);
2525 // Support carry in as value rather than glue.
2526 setOperationAction(ISD::UADDO_CARRY, VT, Custom);
2527 setOperationAction(ISD::USUBO_CARRY, VT, Custom);
2528 setOperationAction(ISD::SETCCCARRY, VT, Custom);
2529 setOperationAction(ISD::SADDO_CARRY, VT, Custom);
2530 setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
2533 // Combine sin / cos into _sincos_stret if it is available.
2534 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
2535 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
2536 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
2537 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
2540 if (Subtarget.isTargetWin64()) {
2541 setOperationAction(ISD::SDIV, MVT::i128, Custom);
2542 setOperationAction(ISD::UDIV, MVT::i128, Custom);
2543 setOperationAction(ISD::SREM, MVT::i128, Custom);
2544 setOperationAction(ISD::UREM, MVT::i128, Custom);
2545 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
2546 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
2547 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
2548 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
2549 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
2550 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
2551 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
2552 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
2555 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2556 // is. We should promote the value to 64-bits to solve this.
2557 // This is what the CRT headers do - `fmodf` is an inline header
2558 // function casting to f64 and calling `fmod`.
2559 if (Subtarget.is32Bit() &&
2560 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2561 // clang-format off
2562 for (ISD::NodeType Op :
2563 {ISD::FACOS, ISD::STRICT_FACOS,
2564 ISD::FASIN, ISD::STRICT_FASIN,
2565 ISD::FATAN, ISD::STRICT_FATAN,
2566 ISD::FATAN2, ISD::STRICT_FATAN2,
2567 ISD::FCEIL, ISD::STRICT_FCEIL,
2568 ISD::FCOS, ISD::STRICT_FCOS,
2569 ISD::FCOSH, ISD::STRICT_FCOSH,
2570 ISD::FEXP, ISD::STRICT_FEXP,
2571 ISD::FFLOOR, ISD::STRICT_FFLOOR,
2572 ISD::FREM, ISD::STRICT_FREM,
2573 ISD::FLOG, ISD::STRICT_FLOG,
2574 ISD::FLOG10, ISD::STRICT_FLOG10,
2575 ISD::FPOW, ISD::STRICT_FPOW,
2576 ISD::FSIN, ISD::STRICT_FSIN,
2577 ISD::FSINH, ISD::STRICT_FSINH,
2578 ISD::FTAN, ISD::STRICT_FTAN,
2579 ISD::FTANH, ISD::STRICT_FTANH})
2580 if (isOperationExpand(Op, MVT::f32))
2581 setOperationAction(Op, MVT::f32, Promote);
2582 // clang-format on
2584 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
2585 // it, but it's just a wrapper around ldexp.
2586 if (Subtarget.isOSWindows()) {
2587 for (ISD::NodeType Op : {ISD::FLDEXP, ISD::STRICT_FLDEXP, ISD::FFREXP})
2588 if (isOperationExpand(Op, MVT::f32))
2589 setOperationAction(Op, MVT::f32, Promote);
2592 // We have target-specific dag combine patterns for the following nodes:
2593 setTargetDAGCombine({ISD::VECTOR_SHUFFLE,
2594 ISD::SCALAR_TO_VECTOR,
2595 ISD::INSERT_VECTOR_ELT,
2596 ISD::EXTRACT_VECTOR_ELT,
2597 ISD::CONCAT_VECTORS,
2598 ISD::INSERT_SUBVECTOR,
2599 ISD::EXTRACT_SUBVECTOR,
2600 ISD::BITCAST,
2601 ISD::VSELECT,
2602 ISD::SELECT,
2603 ISD::SHL,
2604 ISD::SRA,
2605 ISD::SRL,
2606 ISD::OR,
2607 ISD::AND,
2608 ISD::AVGCEILS,
2609 ISD::AVGCEILU,
2610 ISD::AVGFLOORS,
2611 ISD::AVGFLOORU,
2612 ISD::BITREVERSE,
2613 ISD::ADD,
2614 ISD::FADD,
2615 ISD::FSUB,
2616 ISD::FNEG,
2617 ISD::FMA,
2618 ISD::STRICT_FMA,
2619 ISD::FMINNUM,
2620 ISD::FMAXNUM,
2621 ISD::SUB,
2622 ISD::LOAD,
2623 ISD::LRINT,
2624 ISD::LLRINT,
2625 ISD::MLOAD,
2626 ISD::STORE,
2627 ISD::MSTORE,
2628 ISD::TRUNCATE,
2629 ISD::ZERO_EXTEND,
2630 ISD::ANY_EXTEND,
2631 ISD::SIGN_EXTEND,
2632 ISD::SIGN_EXTEND_INREG,
2633 ISD::ANY_EXTEND_VECTOR_INREG,
2634 ISD::SIGN_EXTEND_VECTOR_INREG,
2635 ISD::ZERO_EXTEND_VECTOR_INREG,
2636 ISD::SINT_TO_FP,
2637 ISD::UINT_TO_FP,
2638 ISD::STRICT_SINT_TO_FP,
2639 ISD::STRICT_UINT_TO_FP,
2640 ISD::SETCC,
2641 ISD::MUL,
2642 ISD::XOR,
2643 ISD::MSCATTER,
2644 ISD::MGATHER,
2645 ISD::FP16_TO_FP,
2646 ISD::FP_EXTEND,
2647 ISD::STRICT_FP_EXTEND,
2648 ISD::FP_ROUND,
2649 ISD::STRICT_FP_ROUND,
2650 ISD::INTRINSIC_VOID,
2651 ISD::INTRINSIC_WO_CHAIN,
2652 ISD::INTRINSIC_W_CHAIN});
2654 computeRegisterProperties(Subtarget.getRegisterInfo());
2656 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2657 MaxStoresPerMemsetOptSize = 8;
2658 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2659 MaxStoresPerMemcpyOptSize = 4;
2660 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2661 MaxStoresPerMemmoveOptSize = 4;
2663 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2664 // that needs to benchmarked and balanced with the potential use of vector
2665 // load/store types (PR33329, PR33914).
2666 MaxLoadsPerMemcmp = 2;
2667 MaxLoadsPerMemcmpOptSize = 2;
2669 // Default loop alignment, which can be overridden by -align-loops.
2670 setPrefLoopAlignment(Align(16));
2672 // An out-of-order CPU can speculatively execute past a predictable branch,
2673 // but a conditional move could be stalled by an expensive earlier operation.
2674 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2675 EnableExtLdPromotion = true;
2676 setPrefFunctionAlignment(Align(16));
2678 verifyIntrinsicTables();
2680 // Default to having -disable-strictnode-mutation on
2681 IsStrictFPEnabled = true;
2684 // This has so far only been implemented for 64-bit MachO.
2685 bool X86TargetLowering::useLoadStackGuardNode(const Module &M) const {
2686 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2689 bool X86TargetLowering::useStackGuardXorFP() const {
2690 // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2691 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2694 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2695 const SDLoc &DL) const {
2696 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2697 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2698 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2699 return SDValue(Node, 0);
2702 TargetLoweringBase::LegalizeTypeAction
2703 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2704 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2705 !Subtarget.hasBWI())
2706 return TypeSplitVector;
2708 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2709 !Subtarget.hasF16C() && VT.getVectorElementType() == MVT::f16)
2710 return TypeSplitVector;
2712 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2713 VT.getVectorElementType() != MVT::i1)
2714 return TypeWidenVector;
2716 return TargetLoweringBase::getPreferredVectorAction(VT);
2719 FastISel *
2720 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2721 const TargetLibraryInfo *libInfo) const {
2722 return X86::createFastISel(funcInfo, libInfo);
2725 //===----------------------------------------------------------------------===//
2726 // Other Lowering Hooks
2727 //===----------------------------------------------------------------------===//
2729 bool X86::mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget,
2730 bool AssumeSingleUse) {
2731 if (!AssumeSingleUse && !Op.hasOneUse())
2732 return false;
2733 if (!ISD::isNormalLoad(Op.getNode()))
2734 return false;
2736 // If this is an unaligned vector, make sure the target supports folding it.
2737 auto *Ld = cast<LoadSDNode>(Op.getNode());
2738 if (!Subtarget.hasAVX() && !Subtarget.hasSSEUnalignedMem() &&
2739 Ld->getValueSizeInBits(0) == 128 && Ld->getAlign() < Align(16))
2740 return false;
2742 // TODO: If this is a non-temporal load and the target has an instruction
2743 // for it, it should not be folded. See "useNonTemporalLoad()".
2745 return true;
2748 bool X86::mayFoldLoadIntoBroadcastFromMem(SDValue Op, MVT EltVT,
2749 const X86Subtarget &Subtarget,
2750 bool AssumeSingleUse) {
2751 assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2752 if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2753 return false;
2755 // We can not replace a wide volatile load with a broadcast-from-memory,
2756 // because that would narrow the load, which isn't legal for volatiles.
2757 auto *Ld = cast<LoadSDNode>(Op.getNode());
2758 return !Ld->isVolatile() ||
2759 Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
2762 bool X86::mayFoldIntoStore(SDValue Op) {
2763 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2766 bool X86::mayFoldIntoZeroExtend(SDValue Op) {
2767 if (Op.hasOneUse()) {
2768 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
2769 return (ISD::ZERO_EXTEND == Opcode);
2771 return false;
2774 static bool isLogicOp(unsigned Opcode) {
2775 // TODO: Add support for X86ISD::FAND/FOR/FXOR/FANDN with test coverage.
2776 return ISD::isBitwiseLogicOp(Opcode) || X86ISD::ANDNP == Opcode;
2779 static bool isTargetShuffle(unsigned Opcode) {
2780 switch(Opcode) {
2781 default: return false;
2782 case X86ISD::BLENDI:
2783 case X86ISD::PSHUFB:
2784 case X86ISD::PSHUFD:
2785 case X86ISD::PSHUFHW:
2786 case X86ISD::PSHUFLW:
2787 case X86ISD::SHUFP:
2788 case X86ISD::INSERTPS:
2789 case X86ISD::EXTRQI:
2790 case X86ISD::INSERTQI:
2791 case X86ISD::VALIGN:
2792 case X86ISD::PALIGNR:
2793 case X86ISD::VSHLDQ:
2794 case X86ISD::VSRLDQ:
2795 case X86ISD::MOVLHPS:
2796 case X86ISD::MOVHLPS:
2797 case X86ISD::MOVSHDUP:
2798 case X86ISD::MOVSLDUP:
2799 case X86ISD::MOVDDUP:
2800 case X86ISD::MOVSS:
2801 case X86ISD::MOVSD:
2802 case X86ISD::MOVSH:
2803 case X86ISD::UNPCKL:
2804 case X86ISD::UNPCKH:
2805 case X86ISD::VBROADCAST:
2806 case X86ISD::VPERMILPI:
2807 case X86ISD::VPERMILPV:
2808 case X86ISD::VPERM2X128:
2809 case X86ISD::SHUF128:
2810 case X86ISD::VPERMIL2:
2811 case X86ISD::VPERMI:
2812 case X86ISD::VPPERM:
2813 case X86ISD::VPERMV:
2814 case X86ISD::VPERMV3:
2815 case X86ISD::VZEXT_MOVL:
2816 return true;
2820 static bool isTargetShuffleVariableMask(unsigned Opcode) {
2821 switch (Opcode) {
2822 default: return false;
2823 // Target Shuffles.
2824 case X86ISD::PSHUFB:
2825 case X86ISD::VPERMILPV:
2826 case X86ISD::VPERMIL2:
2827 case X86ISD::VPPERM:
2828 case X86ISD::VPERMV:
2829 case X86ISD::VPERMV3:
2830 return true;
2831 // 'Faux' Target Shuffles.
2832 case ISD::OR:
2833 case ISD::AND:
2834 case X86ISD::ANDNP:
2835 return true;
2839 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2840 MachineFunction &MF = DAG.getMachineFunction();
2841 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2842 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2843 int ReturnAddrIndex = FuncInfo->getRAIndex();
2845 if (ReturnAddrIndex == 0) {
2846 // Set up a frame object for the return address.
2847 unsigned SlotSize = RegInfo->getSlotSize();
2848 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
2849 -(int64_t)SlotSize,
2850 false);
2851 FuncInfo->setRAIndex(ReturnAddrIndex);
2854 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
2857 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model CM,
2858 bool HasSymbolicDisplacement) {
2859 // Offset should fit into 32 bit immediate field.
2860 if (!isInt<32>(Offset))
2861 return false;
2863 // If we don't have a symbolic displacement - we don't have any extra
2864 // restrictions.
2865 if (!HasSymbolicDisplacement)
2866 return true;
2868 // We can fold large offsets in the large code model because we always use
2869 // 64-bit offsets.
2870 if (CM == CodeModel::Large)
2871 return true;
2873 // For kernel code model we know that all object resist in the negative half
2874 // of 32bits address space. We may not accept negative offsets, since they may
2875 // be just off and we may accept pretty large positive ones.
2876 if (CM == CodeModel::Kernel)
2877 return Offset >= 0;
2879 // For other non-large code models we assume that latest small object is 16MB
2880 // before end of 31 bits boundary. We may also accept pretty large negative
2881 // constants knowing that all objects are in the positive half of address
2882 // space.
2883 return Offset < 16 * 1024 * 1024;
2886 /// Return true if the condition is an signed comparison operation.
2887 static bool isX86CCSigned(unsigned X86CC) {
2888 switch (X86CC) {
2889 default:
2890 llvm_unreachable("Invalid integer condition!");
2891 case X86::COND_E:
2892 case X86::COND_NE:
2893 case X86::COND_B:
2894 case X86::COND_A:
2895 case X86::COND_BE:
2896 case X86::COND_AE:
2897 return false;
2898 case X86::COND_G:
2899 case X86::COND_GE:
2900 case X86::COND_L:
2901 case X86::COND_LE:
2902 return true;
2906 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
2907 switch (SetCCOpcode) {
2908 // clang-format off
2909 default: llvm_unreachable("Invalid integer condition!");
2910 case ISD::SETEQ: return X86::COND_E;
2911 case ISD::SETGT: return X86::COND_G;
2912 case ISD::SETGE: return X86::COND_GE;
2913 case ISD::SETLT: return X86::COND_L;
2914 case ISD::SETLE: return X86::COND_LE;
2915 case ISD::SETNE: return X86::COND_NE;
2916 case ISD::SETULT: return X86::COND_B;
2917 case ISD::SETUGT: return X86::COND_A;
2918 case ISD::SETULE: return X86::COND_BE;
2919 case ISD::SETUGE: return X86::COND_AE;
2920 // clang-format on
2924 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
2925 /// condition code, returning the condition code and the LHS/RHS of the
2926 /// comparison to make.
2927 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
2928 bool isFP, SDValue &LHS, SDValue &RHS,
2929 SelectionDAG &DAG) {
2930 if (!isFP) {
2931 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2932 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
2933 // X > -1 -> X == 0, jump !sign.
2934 RHS = DAG.getConstant(0, DL, RHS.getValueType());
2935 return X86::COND_NS;
2937 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
2938 // X < 0 -> X == 0, jump on sign.
2939 return X86::COND_S;
2941 if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
2942 // X >= 0 -> X == 0, jump on !sign.
2943 return X86::COND_NS;
2945 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
2946 // X < 1 -> X <= 0
2947 RHS = DAG.getConstant(0, DL, RHS.getValueType());
2948 return X86::COND_LE;
2952 return TranslateIntegerX86CC(SetCCOpcode);
2955 // First determine if it is required or is profitable to flip the operands.
2957 // If LHS is a foldable load, but RHS is not, flip the condition.
2958 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2959 !ISD::isNON_EXTLoad(RHS.getNode())) {
2960 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2961 std::swap(LHS, RHS);
2964 switch (SetCCOpcode) {
2965 default: break;
2966 case ISD::SETOLT:
2967 case ISD::SETOLE:
2968 case ISD::SETUGT:
2969 case ISD::SETUGE:
2970 std::swap(LHS, RHS);
2971 break;
2974 // On a floating point condition, the flags are set as follows:
2975 // ZF PF CF op
2976 // 0 | 0 | 0 | X > Y
2977 // 0 | 0 | 1 | X < Y
2978 // 1 | 0 | 0 | X == Y
2979 // 1 | 1 | 1 | unordered
2980 switch (SetCCOpcode) {
2981 // clang-format off
2982 default: llvm_unreachable("Condcode should be pre-legalized away");
2983 case ISD::SETUEQ:
2984 case ISD::SETEQ: return X86::COND_E;
2985 case ISD::SETOLT: // flipped
2986 case ISD::SETOGT:
2987 case ISD::SETGT: return X86::COND_A;
2988 case ISD::SETOLE: // flipped
2989 case ISD::SETOGE:
2990 case ISD::SETGE: return X86::COND_AE;
2991 case ISD::SETUGT: // flipped
2992 case ISD::SETULT:
2993 case ISD::SETLT: return X86::COND_B;
2994 case ISD::SETUGE: // flipped
2995 case ISD::SETULE:
2996 case ISD::SETLE: return X86::COND_BE;
2997 case ISD::SETONE:
2998 case ISD::SETNE: return X86::COND_NE;
2999 case ISD::SETUO: return X86::COND_P;
3000 case ISD::SETO: return X86::COND_NP;
3001 case ISD::SETOEQ:
3002 case ISD::SETUNE: return X86::COND_INVALID;
3003 // clang-format on
3007 /// Is there a floating point cmov for the specific X86 condition code?
3008 /// Current x86 isa includes the following FP cmov instructions:
3009 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3010 static bool hasFPCMov(unsigned X86CC) {
3011 switch (X86CC) {
3012 default:
3013 return false;
3014 case X86::COND_B:
3015 case X86::COND_BE:
3016 case X86::COND_E:
3017 case X86::COND_P:
3018 case X86::COND_A:
3019 case X86::COND_AE:
3020 case X86::COND_NE:
3021 case X86::COND_NP:
3022 return true;
3026 static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
3027 return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
3028 VT.is512BitVector();
3031 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
3032 const CallInst &I,
3033 MachineFunction &MF,
3034 unsigned Intrinsic) const {
3035 Info.flags = MachineMemOperand::MONone;
3036 Info.offset = 0;
3038 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
3039 if (!IntrData) {
3040 switch (Intrinsic) {
3041 case Intrinsic::x86_aesenc128kl:
3042 case Intrinsic::x86_aesdec128kl:
3043 Info.opc = ISD::INTRINSIC_W_CHAIN;
3044 Info.ptrVal = I.getArgOperand(1);
3045 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3046 Info.align = Align(1);
3047 Info.flags |= MachineMemOperand::MOLoad;
3048 return true;
3049 case Intrinsic::x86_aesenc256kl:
3050 case Intrinsic::x86_aesdec256kl:
3051 Info.opc = ISD::INTRINSIC_W_CHAIN;
3052 Info.ptrVal = I.getArgOperand(1);
3053 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3054 Info.align = Align(1);
3055 Info.flags |= MachineMemOperand::MOLoad;
3056 return true;
3057 case Intrinsic::x86_aesencwide128kl:
3058 case Intrinsic::x86_aesdecwide128kl:
3059 Info.opc = ISD::INTRINSIC_W_CHAIN;
3060 Info.ptrVal = I.getArgOperand(0);
3061 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3062 Info.align = Align(1);
3063 Info.flags |= MachineMemOperand::MOLoad;
3064 return true;
3065 case Intrinsic::x86_aesencwide256kl:
3066 case Intrinsic::x86_aesdecwide256kl:
3067 Info.opc = ISD::INTRINSIC_W_CHAIN;
3068 Info.ptrVal = I.getArgOperand(0);
3069 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3070 Info.align = Align(1);
3071 Info.flags |= MachineMemOperand::MOLoad;
3072 return true;
3073 case Intrinsic::x86_cmpccxadd32:
3074 case Intrinsic::x86_cmpccxadd64:
3075 case Intrinsic::x86_atomic_bts:
3076 case Intrinsic::x86_atomic_btc:
3077 case Intrinsic::x86_atomic_btr: {
3078 Info.opc = ISD::INTRINSIC_W_CHAIN;
3079 Info.ptrVal = I.getArgOperand(0);
3080 unsigned Size = I.getType()->getScalarSizeInBits();
3081 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3082 Info.align = Align(Size);
3083 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
3084 MachineMemOperand::MOVolatile;
3085 return true;
3087 case Intrinsic::x86_atomic_bts_rm:
3088 case Intrinsic::x86_atomic_btc_rm:
3089 case Intrinsic::x86_atomic_btr_rm: {
3090 Info.opc = ISD::INTRINSIC_W_CHAIN;
3091 Info.ptrVal = I.getArgOperand(0);
3092 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3093 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3094 Info.align = Align(Size);
3095 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
3096 MachineMemOperand::MOVolatile;
3097 return true;
3099 case Intrinsic::x86_aadd32:
3100 case Intrinsic::x86_aadd64:
3101 case Intrinsic::x86_aand32:
3102 case Intrinsic::x86_aand64:
3103 case Intrinsic::x86_aor32:
3104 case Intrinsic::x86_aor64:
3105 case Intrinsic::x86_axor32:
3106 case Intrinsic::x86_axor64:
3107 case Intrinsic::x86_atomic_add_cc:
3108 case Intrinsic::x86_atomic_sub_cc:
3109 case Intrinsic::x86_atomic_or_cc:
3110 case Intrinsic::x86_atomic_and_cc:
3111 case Intrinsic::x86_atomic_xor_cc: {
3112 Info.opc = ISD::INTRINSIC_W_CHAIN;
3113 Info.ptrVal = I.getArgOperand(0);
3114 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3115 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3116 Info.align = Align(Size);
3117 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
3118 MachineMemOperand::MOVolatile;
3119 return true;
3122 return false;
3125 switch (IntrData->Type) {
3126 case TRUNCATE_TO_MEM_VI8:
3127 case TRUNCATE_TO_MEM_VI16:
3128 case TRUNCATE_TO_MEM_VI32: {
3129 Info.opc = ISD::INTRINSIC_VOID;
3130 Info.ptrVal = I.getArgOperand(0);
3131 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
3132 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
3133 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
3134 ScalarVT = MVT::i8;
3135 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
3136 ScalarVT = MVT::i16;
3137 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
3138 ScalarVT = MVT::i32;
3140 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
3141 Info.align = Align(1);
3142 Info.flags |= MachineMemOperand::MOStore;
3143 break;
3145 case GATHER:
3146 case GATHER_AVX2: {
3147 Info.opc = ISD::INTRINSIC_W_CHAIN;
3148 Info.ptrVal = nullptr;
3149 MVT DataVT = MVT::getVT(I.getType());
3150 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3151 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3152 IndexVT.getVectorNumElements());
3153 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3154 Info.align = Align(1);
3155 Info.flags |= MachineMemOperand::MOLoad;
3156 break;
3158 case SCATTER: {
3159 Info.opc = ISD::INTRINSIC_VOID;
3160 Info.ptrVal = nullptr;
3161 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
3162 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3163 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3164 IndexVT.getVectorNumElements());
3165 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3166 Info.align = Align(1);
3167 Info.flags |= MachineMemOperand::MOStore;
3168 break;
3170 default:
3171 return false;
3174 return true;
3177 /// Returns true if the target can instruction select the
3178 /// specified FP immediate natively. If false, the legalizer will
3179 /// materialize the FP immediate as a load from a constant pool.
3180 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
3181 bool ForCodeSize) const {
3182 for (const APFloat &FPImm : LegalFPImmediates)
3183 if (Imm.bitwiseIsEqual(FPImm))
3184 return true;
3185 return false;
3188 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3189 ISD::LoadExtType ExtTy,
3190 EVT NewVT) const {
3191 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3193 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3194 // relocation target a movq or addq instruction: don't let the load shrink.
3195 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3196 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3197 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3198 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3200 // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
3201 // those uses are extracted directly into a store, then the extract + store
3202 // can be store-folded. Therefore, it's probably not worth splitting the load.
3203 EVT VT = Load->getValueType(0);
3204 if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
3205 for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
3206 // Skip uses of the chain value. Result 0 of the node is the load value.
3207 if (UI.getUse().getResNo() != 0)
3208 continue;
3210 // If this use is not an extract + store, it's probably worth splitting.
3211 if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
3212 UI->use_begin()->getOpcode() != ISD::STORE)
3213 return true;
3215 // All non-chain uses are extract + store.
3216 return false;
3219 return true;
3222 /// Returns true if it is beneficial to convert a load of a constant
3223 /// to just the constant itself.
3224 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3225 Type *Ty) const {
3226 assert(Ty->isIntegerTy());
3228 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3229 if (BitSize == 0 || BitSize > 64)
3230 return false;
3231 return true;
3234 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
3235 // If we are using XMM registers in the ABI and the condition of the select is
3236 // a floating-point compare and we have blendv or conditional move, then it is
3237 // cheaper to select instead of doing a cross-register move and creating a
3238 // load that depends on the compare result.
3239 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3240 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3243 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
3244 // TODO: It might be a win to ease or lift this restriction, but the generic
3245 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3246 if (VT.isVector() && Subtarget.hasAVX512())
3247 return false;
3249 return true;
3252 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
3253 SDValue C) const {
3254 // TODO: We handle scalars using custom code, but generic combining could make
3255 // that unnecessary.
3256 APInt MulC;
3257 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3258 return false;
3260 // Find the type this will be legalized too. Otherwise we might prematurely
3261 // convert this to shl+add/sub and then still have to type legalize those ops.
3262 // Another choice would be to defer the decision for illegal types until
3263 // after type legalization. But constant splat vectors of i64 can't make it
3264 // through type legalization on 32-bit targets so we would need to special
3265 // case vXi64.
3266 while (getTypeAction(Context, VT) != TypeLegal)
3267 VT = getTypeToTransformTo(Context, VT);
3269 // If vector multiply is legal, assume that's faster than shl + add/sub.
3270 // Multiply is a complex op with higher latency and lower throughput in
3271 // most implementations, sub-vXi32 vector multiplies are always fast,
3272 // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3273 // is always going to be slow.
3274 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3275 if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3276 (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3277 return false;
3279 // shl+add, shl+sub, shl+add+neg
3280 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3281 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3284 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
3285 unsigned Index) const {
3286 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3287 return false;
3289 // Mask vectors support all subregister combinations and operations that
3290 // extract half of vector.
3291 if (ResVT.getVectorElementType() == MVT::i1)
3292 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
3293 (Index == ResVT.getVectorNumElements()));
3295 return (Index % ResVT.getVectorNumElements()) == 0;
3298 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
3299 unsigned Opc = VecOp.getOpcode();
3301 // Assume target opcodes can't be scalarized.
3302 // TODO - do we have any exceptions?
3303 if (Opc >= ISD::BUILTIN_OP_END)
3304 return false;
3306 // If the vector op is not supported, try to convert to scalar.
3307 EVT VecVT = VecOp.getValueType();
3308 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
3309 return true;
3311 // If the vector op is supported, but the scalar op is not, the transform may
3312 // not be worthwhile.
3313 EVT ScalarVT = VecVT.getScalarType();
3314 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3317 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
3318 bool) const {
3319 // TODO: Allow vectors?
3320 if (VT.isVector())
3321 return false;
3322 return VT.isSimple() || !isOperationExpand(Opcode, VT);
3325 bool X86TargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
3326 // Speculate cttz only if we can directly use TZCNT or can promote to i32/i64.
3327 return Subtarget.hasBMI() || Subtarget.canUseCMOV() ||
3328 (!Ty->isVectorTy() &&
3329 Ty->getScalarSizeInBits() < (Subtarget.is64Bit() ? 64u : 32u));
3332 bool X86TargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
3333 // Speculate ctlz only if we can directly use LZCNT.
3334 return Subtarget.hasLZCNT() || Subtarget.canUseCMOV();
3337 bool X86TargetLowering::ShouldShrinkFPConstant(EVT VT) const {
3338 // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3339 // expensive than a straight movsd. On the other hand, it's important to
3340 // shrink long double fp constant since fldt is very slow.
3341 return !Subtarget.hasSSE2() || VT == MVT::f80;
3344 bool X86TargetLowering::isScalarFPTypeInSSEReg(EVT VT) const {
3345 return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3346 (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3349 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
3350 const SelectionDAG &DAG,
3351 const MachineMemOperand &MMO) const {
3352 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3353 BitcastVT.getVectorElementType() == MVT::i1)
3354 return false;
3356 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3357 return false;
3359 // If both types are legal vectors, it's always ok to convert them.
3360 if (LoadVT.isVector() && BitcastVT.isVector() &&
3361 isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
3362 return true;
3364 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3367 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
3368 const MachineFunction &MF) const {
3369 // Do not merge to float value size (128 bytes) if no implicit
3370 // float attribute is set.
3371 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3373 if (NoFloat) {
3374 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3375 return (MemVT.getSizeInBits() <= MaxIntSize);
3377 // Make sure we don't merge greater than our preferred vector
3378 // width.
3379 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3380 return false;
3382 return true;
3385 bool X86TargetLowering::isCtlzFast() const {
3386 return Subtarget.hasFastLZCNT();
3389 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
3390 const Instruction &AndI) const {
3391 return true;
3394 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
3395 EVT VT = Y.getValueType();
3397 if (VT.isVector())
3398 return false;
3400 if (!Subtarget.hasBMI())
3401 return false;
3403 // There are only 32-bit and 64-bit forms for 'andn'.
3404 if (VT != MVT::i32 && VT != MVT::i64)
3405 return false;
3407 return !isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque();
3410 bool X86TargetLowering::hasAndNot(SDValue Y) const {
3411 EVT VT = Y.getValueType();
3413 if (!VT.isVector())
3414 return hasAndNotCompare(Y);
3416 // Vector.
3418 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3419 return false;
3421 if (VT == MVT::v4i32)
3422 return true;
3424 return Subtarget.hasSSE2();
3427 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
3428 return X.getValueType().isScalarInteger(); // 'bt'
3431 bool X86TargetLowering::
3432 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3433 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
3434 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3435 SelectionDAG &DAG) const {
3436 // Does baseline recommend not to perform the fold by default?
3437 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3438 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3439 return false;
3440 // For scalars this transform is always beneficial.
3441 if (X.getValueType().isScalarInteger())
3442 return true;
3443 // If all the shift amounts are identical, then transform is beneficial even
3444 // with rudimentary SSE2 shifts.
3445 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3446 return true;
3447 // If we have AVX2 with it's powerful shift operations, then it's also good.
3448 if (Subtarget.hasAVX2())
3449 return true;
3450 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3451 return NewShiftOpcode == ISD::SHL;
3454 unsigned X86TargetLowering::preferedOpcodeForCmpEqPiecesOfOperand(
3455 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3456 const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3457 if (!VT.isInteger())
3458 return ShiftOpc;
3460 bool PreferRotate = false;
3461 if (VT.isVector()) {
3462 // For vectors, if we have rotate instruction support, then its definetly
3463 // best. Otherwise its not clear what the best so just don't make changed.
3464 PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3465 VT.getScalarType() == MVT::i64);
3466 } else {
3467 // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3468 // rotate unless we have a zext mask+shr.
3469 PreferRotate = Subtarget.hasBMI2();
3470 if (!PreferRotate) {
3471 unsigned MaskBits =
3472 VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3473 PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3477 if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3478 assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3480 if (PreferRotate && MayTransformRotate)
3481 return ISD::ROTL;
3483 // If vector we don't really get much benefit swapping around constants.
3484 // Maybe we could check if the DAG has the flipped node already in the
3485 // future.
3486 if (VT.isVector())
3487 return ShiftOpc;
3489 // See if the beneficial to swap shift type.
3490 if (ShiftOpc == ISD::SHL) {
3491 // If the current setup has imm64 mask, then inverse will have
3492 // at least imm32 mask (or be zext i32 -> i64).
3493 if (VT == MVT::i64)
3494 return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3495 : ShiftOpc;
3497 // We can only benefit if req at least 7-bit for the mask. We
3498 // don't want to replace shl of 1,2,3 as they can be implemented
3499 // with lea/add.
3500 return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3503 if (VT == MVT::i64)
3504 // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3505 // extremely efficient.
3506 return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3508 // Keep small shifts as shl so we can generate add/lea.
3509 return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3512 // We prefer rotate for vectors of if we won't get a zext mask with SRL
3513 // (PreferRotate will be set in the latter case).
3514 if (PreferRotate || !MayTransformRotate || VT.isVector())
3515 return ShiftOpc;
3517 // Non-vector type and we have a zext mask with SRL.
3518 return ISD::SRL;
3521 TargetLoweringBase::CondMergingParams
3522 X86TargetLowering::getJumpConditionMergingParams(Instruction::BinaryOps Opc,
3523 const Value *Lhs,
3524 const Value *Rhs) const {
3525 using namespace llvm::PatternMatch;
3526 int BaseCost = BrMergingBaseCostThresh.getValue();
3527 // With CCMP, branches can be merged in a more efficient way.
3528 if (BaseCost >= 0 && Subtarget.hasCCMP())
3529 BaseCost += BrMergingCcmpBias;
3530 // a == b && a == c is a fast pattern on x86.
3531 if (BaseCost >= 0 && Opc == Instruction::And &&
3532 match(Lhs, m_SpecificICmp(ICmpInst::ICMP_EQ, m_Value(), m_Value())) &&
3533 match(Rhs, m_SpecificICmp(ICmpInst::ICMP_EQ, m_Value(), m_Value())))
3534 BaseCost += 1;
3535 return {BaseCost, BrMergingLikelyBias.getValue(),
3536 BrMergingUnlikelyBias.getValue()};
3539 bool X86TargetLowering::preferScalarizeSplat(SDNode *N) const {
3540 return N->getOpcode() != ISD::FP_EXTEND;
3543 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
3544 const SDNode *N, CombineLevel Level) const {
3545 assert(((N->getOpcode() == ISD::SHL &&
3546 N->getOperand(0).getOpcode() == ISD::SRL) ||
3547 (N->getOpcode() == ISD::SRL &&
3548 N->getOperand(0).getOpcode() == ISD::SHL)) &&
3549 "Expected shift-shift mask");
3550 // TODO: Should we always create i64 masks? Or only folded immediates?
3551 EVT VT = N->getValueType(0);
3552 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3553 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3554 // Only fold if the shift values are equal - so it folds to AND.
3555 // TODO - we should fold if either is a non-uniform vector but we don't do
3556 // the fold for non-splats yet.
3557 return N->getOperand(1) == N->getOperand(0).getOperand(1);
3559 return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
3562 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
3563 EVT VT = Y.getValueType();
3565 // For vectors, we don't have a preference, but we probably want a mask.
3566 if (VT.isVector())
3567 return false;
3569 // 64-bit shifts on 32-bit targets produce really bad bloated code.
3570 if (VT == MVT::i64 && !Subtarget.is64Bit())
3571 return false;
3573 return true;
3576 TargetLowering::ShiftLegalizationStrategy
3577 X86TargetLowering::preferredShiftLegalizationStrategy(
3578 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3579 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
3580 !Subtarget.isOSWindows())
3581 return ShiftLegalizationStrategy::LowerToLibcall;
3582 return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
3583 ExpansionFactor);
3586 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
3587 // Any legal vector type can be splatted more efficiently than
3588 // loading/spilling from memory.
3589 return isTypeLegal(VT);
3592 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
3593 MVT VT = MVT::getIntegerVT(NumBits);
3594 if (isTypeLegal(VT))
3595 return VT;
3597 // PMOVMSKB can handle this.
3598 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
3599 return MVT::v16i8;
3601 // VPMOVMSKB can handle this.
3602 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
3603 return MVT::v32i8;
3605 // TODO: Allow 64-bit type for 32-bit target.
3606 // TODO: 512-bit types should be allowed, but make sure that those
3607 // cases are handled in combineVectorSizedSetCCEquality().
3609 return MVT::INVALID_SIMPLE_VALUE_TYPE;
3612 /// Val is the undef sentinel value or equal to the specified value.
3613 static bool isUndefOrEqual(int Val, int CmpVal) {
3614 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
3617 /// Return true if every element in Mask is the undef sentinel value or equal to
3618 /// the specified value.
3619 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
3620 return llvm::all_of(Mask, [CmpVal](int M) {
3621 return (M == SM_SentinelUndef) || (M == CmpVal);
3625 /// Return true if every element in Mask, beginning from position Pos and ending
3626 /// in Pos+Size is the undef sentinel value or equal to the specified value.
3627 static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
3628 unsigned Size) {
3629 return llvm::all_of(Mask.slice(Pos, Size),
3630 [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
3633 /// Val is either the undef or zero sentinel value.
3634 static bool isUndefOrZero(int Val) {
3635 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
3638 /// Return true if every element in Mask, beginning from position Pos and ending
3639 /// in Pos+Size is the undef sentinel value.
3640 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3641 return llvm::all_of(Mask.slice(Pos, Size),
3642 [](int M) { return M == SM_SentinelUndef; });
3645 /// Return true if the mask creates a vector whose lower half is undefined.
3646 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
3647 unsigned NumElts = Mask.size();
3648 return isUndefInRange(Mask, 0, NumElts / 2);
3651 /// Return true if the mask creates a vector whose upper half is undefined.
3652 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
3653 unsigned NumElts = Mask.size();
3654 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
3657 /// Return true if Val falls within the specified range (L, H].
3658 static bool isInRange(int Val, int Low, int Hi) {
3659 return (Val >= Low && Val < Hi);
3662 /// Return true if the value of any element in Mask falls within the specified
3663 /// range (L, H].
3664 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
3665 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
3668 /// Return true if the value of any element in Mask is the zero sentinel value.
3669 static bool isAnyZero(ArrayRef<int> Mask) {
3670 return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
3673 /// Return true if Val is undef or if its value falls within the
3674 /// specified range (L, H].
3675 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3676 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
3679 /// Return true if every element in Mask is undef or if its value
3680 /// falls within the specified range (L, H].
3681 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
3682 return llvm::all_of(
3683 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
3686 /// Return true if Val is undef, zero or if its value falls within the
3687 /// specified range (L, H].
3688 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
3689 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
3692 /// Return true if every element in Mask is undef, zero or if its value
3693 /// falls within the specified range (L, H].
3694 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
3695 return llvm::all_of(
3696 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
3699 /// Return true if every element in Mask, is an in-place blend/select mask or is
3700 /// undef.
3701 LLVM_ATTRIBUTE_UNUSED static bool isBlendOrUndef(ArrayRef<int> Mask) {
3702 unsigned NumElts = Mask.size();
3703 for (auto [I, M] : enumerate(Mask))
3704 if (!isUndefOrEqual(M, I) && !isUndefOrEqual(M, I + NumElts))
3705 return false;
3706 return true;
3709 /// Return true if every element in Mask, beginning
3710 /// from position Pos and ending in Pos + Size, falls within the specified
3711 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
3712 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
3713 unsigned Size, int Low, int Step = 1) {
3714 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
3715 if (!isUndefOrEqual(Mask[i], Low))
3716 return false;
3717 return true;
3720 /// Return true if every element in Mask, beginning
3721 /// from position Pos and ending in Pos+Size, falls within the specified
3722 /// sequential range (Low, Low+Size], or is undef or is zero.
3723 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
3724 unsigned Size, int Low,
3725 int Step = 1) {
3726 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
3727 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
3728 return false;
3729 return true;
3732 /// Return true if every element in Mask, beginning
3733 /// from position Pos and ending in Pos+Size is undef or is zero.
3734 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
3735 unsigned Size) {
3736 return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
3739 /// Return true if every element of a single input is referenced by the shuffle
3740 /// mask. i.e. it just permutes them all.
3741 static bool isCompletePermute(ArrayRef<int> Mask) {
3742 unsigned NumElts = Mask.size();
3743 APInt DemandedElts = APInt::getZero(NumElts);
3744 for (int M : Mask)
3745 if (isInRange(M, 0, NumElts))
3746 DemandedElts.setBit(M);
3747 return DemandedElts.isAllOnes();
3750 /// Helper function to test whether a shuffle mask could be
3751 /// simplified by widening the elements being shuffled.
3753 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
3754 /// leaves it in an unspecified state.
3756 /// NOTE: This must handle normal vector shuffle masks and *target* vector
3757 /// shuffle masks. The latter have the special property of a '-2' representing
3758 /// a zero-ed lane of a vector.
3759 static bool canWidenShuffleElements(ArrayRef<int> Mask,
3760 SmallVectorImpl<int> &WidenedMask) {
3761 WidenedMask.assign(Mask.size() / 2, 0);
3762 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
3763 int M0 = Mask[i];
3764 int M1 = Mask[i + 1];
3766 // If both elements are undef, its trivial.
3767 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
3768 WidenedMask[i / 2] = SM_SentinelUndef;
3769 continue;
3772 // Check for an undef mask and a mask value properly aligned to fit with
3773 // a pair of values. If we find such a case, use the non-undef mask's value.
3774 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
3775 WidenedMask[i / 2] = M1 / 2;
3776 continue;
3778 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
3779 WidenedMask[i / 2] = M0 / 2;
3780 continue;
3783 // When zeroing, we need to spread the zeroing across both lanes to widen.
3784 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
3785 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
3786 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
3787 WidenedMask[i / 2] = SM_SentinelZero;
3788 continue;
3790 return false;
3793 // Finally check if the two mask values are adjacent and aligned with
3794 // a pair.
3795 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
3796 WidenedMask[i / 2] = M0 / 2;
3797 continue;
3800 // Otherwise we can't safely widen the elements used in this shuffle.
3801 return false;
3803 assert(WidenedMask.size() == Mask.size() / 2 &&
3804 "Incorrect size of mask after widening the elements!");
3806 return true;
3809 static bool canWidenShuffleElements(ArrayRef<int> Mask,
3810 const APInt &Zeroable,
3811 bool V2IsZero,
3812 SmallVectorImpl<int> &WidenedMask) {
3813 // Create an alternative mask with info about zeroable elements.
3814 // Here we do not set undef elements as zeroable.
3815 SmallVector<int, 64> ZeroableMask(Mask);
3816 if (V2IsZero) {
3817 assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
3818 for (int i = 0, Size = Mask.size(); i != Size; ++i)
3819 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
3820 ZeroableMask[i] = SM_SentinelZero;
3822 return canWidenShuffleElements(ZeroableMask, WidenedMask);
3825 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
3826 SmallVector<int, 32> WidenedMask;
3827 return canWidenShuffleElements(Mask, WidenedMask);
3830 // Attempt to narrow/widen shuffle mask until it matches the target number of
3831 // elements.
3832 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
3833 SmallVectorImpl<int> &ScaledMask) {
3834 unsigned NumSrcElts = Mask.size();
3835 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
3836 "Illegal shuffle scale factor");
3838 // Narrowing is guaranteed to work.
3839 if (NumDstElts >= NumSrcElts) {
3840 int Scale = NumDstElts / NumSrcElts;
3841 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
3842 return true;
3845 // We have to repeat the widening until we reach the target size, but we can
3846 // split out the first widening as it sets up ScaledMask for us.
3847 if (canWidenShuffleElements(Mask, ScaledMask)) {
3848 while (ScaledMask.size() > NumDstElts) {
3849 SmallVector<int, 16> WidenedMask;
3850 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
3851 return false;
3852 ScaledMask = std::move(WidenedMask);
3854 return true;
3857 return false;
3860 static bool canScaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts) {
3861 SmallVector<int, 32> ScaledMask;
3862 return scaleShuffleElements(Mask, NumDstElts, ScaledMask);
3865 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
3866 bool X86::isZeroNode(SDValue Elt) {
3867 return isNullConstant(Elt) || isNullFPConstant(Elt);
3870 // Build a vector of constants.
3871 // Use an UNDEF node if MaskElt == -1.
3872 // Split 64-bit constants in the 32-bit mode.
3873 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
3874 const SDLoc &dl, bool IsMask = false) {
3876 SmallVector<SDValue, 32> Ops;
3877 bool Split = false;
3879 MVT ConstVecVT = VT;
3880 unsigned NumElts = VT.getVectorNumElements();
3881 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
3882 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
3883 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
3884 Split = true;
3887 MVT EltVT = ConstVecVT.getVectorElementType();
3888 for (unsigned i = 0; i < NumElts; ++i) {
3889 bool IsUndef = Values[i] < 0 && IsMask;
3890 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
3891 DAG.getConstant(Values[i], dl, EltVT);
3892 Ops.push_back(OpNode);
3893 if (Split)
3894 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
3895 DAG.getConstant(0, dl, EltVT));
3897 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
3898 if (Split)
3899 ConstsNode = DAG.getBitcast(VT, ConstsNode);
3900 return ConstsNode;
3903 static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
3904 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
3905 assert(Bits.size() == Undefs.getBitWidth() &&
3906 "Unequal constant and undef arrays");
3907 SmallVector<SDValue, 32> Ops;
3908 bool Split = false;
3910 MVT ConstVecVT = VT;
3911 unsigned NumElts = VT.getVectorNumElements();
3912 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
3913 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
3914 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
3915 Split = true;
3918 MVT EltVT = ConstVecVT.getVectorElementType();
3919 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
3920 if (Undefs[i]) {
3921 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
3922 continue;
3924 const APInt &V = Bits[i];
3925 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
3926 if (Split) {
3927 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
3928 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
3929 } else if (EltVT == MVT::f32) {
3930 APFloat FV(APFloat::IEEEsingle(), V);
3931 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
3932 } else if (EltVT == MVT::f64) {
3933 APFloat FV(APFloat::IEEEdouble(), V);
3934 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
3935 } else {
3936 Ops.push_back(DAG.getConstant(V, dl, EltVT));
3940 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
3941 return DAG.getBitcast(VT, ConstsNode);
3944 static SDValue getConstVector(ArrayRef<APInt> Bits, MVT VT,
3945 SelectionDAG &DAG, const SDLoc &dl) {
3946 APInt Undefs = APInt::getZero(Bits.size());
3947 return getConstVector(Bits, Undefs, VT, DAG, dl);
3950 /// Returns a vector of specified type with all zero elements.
3951 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
3952 SelectionDAG &DAG, const SDLoc &dl) {
3953 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
3954 VT.getVectorElementType() == MVT::i1) &&
3955 "Unexpected vector type");
3957 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
3958 // type. This ensures they get CSE'd. But if the integer type is not
3959 // available, use a floating-point +0.0 instead.
3960 SDValue Vec;
3961 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3962 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
3963 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
3964 } else if (VT.isFloatingPoint() &&
3965 TLI.isTypeLegal(VT.getVectorElementType())) {
3966 Vec = DAG.getConstantFP(+0.0, dl, VT);
3967 } else if (VT.getVectorElementType() == MVT::i1) {
3968 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
3969 "Unexpected vector type");
3970 Vec = DAG.getConstant(0, dl, VT);
3971 } else {
3972 unsigned Num32BitElts = VT.getSizeInBits() / 32;
3973 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
3975 return DAG.getBitcast(VT, Vec);
3978 // Helper to determine if the ops are all the extracted subvectors come from a
3979 // single source. If we allow commute they don't have to be in order (Lo/Hi).
3980 static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
3981 if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
3982 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
3983 LHS.getValueType() != RHS.getValueType() ||
3984 LHS.getOperand(0) != RHS.getOperand(0))
3985 return SDValue();
3987 SDValue Src = LHS.getOperand(0);
3988 if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
3989 return SDValue();
3991 unsigned NumElts = LHS.getValueType().getVectorNumElements();
3992 if ((LHS.getConstantOperandAPInt(1) == 0 &&
3993 RHS.getConstantOperandAPInt(1) == NumElts) ||
3994 (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
3995 LHS.getConstantOperandAPInt(1) == NumElts))
3996 return Src;
3998 return SDValue();
4001 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4002 const SDLoc &dl, unsigned vectorWidth) {
4003 EVT VT = Vec.getValueType();
4004 EVT ElVT = VT.getVectorElementType();
4005 unsigned Factor = VT.getSizeInBits() / vectorWidth;
4006 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4007 VT.getVectorNumElements() / Factor);
4009 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4010 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4011 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4013 // This is the index of the first element of the vectorWidth-bit chunk
4014 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4015 IdxVal &= ~(ElemsPerChunk - 1);
4017 // If the input is a buildvector just emit a smaller one.
4018 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4019 return DAG.getBuildVector(ResultVT, dl,
4020 Vec->ops().slice(IdxVal, ElemsPerChunk));
4022 // Check if we're extracting the upper undef of a widening pattern.
4023 if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
4024 Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
4025 isNullConstant(Vec.getOperand(2)))
4026 return DAG.getUNDEF(ResultVT);
4028 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4029 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4032 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4033 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4034 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4035 /// instructions or a simple subregister reference. Idx is an index in the
4036 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4037 /// lowering EXTRACT_VECTOR_ELT operations easier.
4038 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4039 SelectionDAG &DAG, const SDLoc &dl) {
4040 assert((Vec.getValueType().is256BitVector() ||
4041 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4042 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4045 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4046 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4047 SelectionDAG &DAG, const SDLoc &dl) {
4048 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4049 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4052 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4053 SelectionDAG &DAG, const SDLoc &dl,
4054 unsigned vectorWidth) {
4055 assert((vectorWidth == 128 || vectorWidth == 256) &&
4056 "Unsupported vector width");
4057 // Inserting UNDEF is Result
4058 if (Vec.isUndef())
4059 return Result;
4060 EVT VT = Vec.getValueType();
4061 EVT ElVT = VT.getVectorElementType();
4062 EVT ResultVT = Result.getValueType();
4064 // Insert the relevant vectorWidth bits.
4065 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4066 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4068 // This is the index of the first element of the vectorWidth-bit chunk
4069 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4070 IdxVal &= ~(ElemsPerChunk - 1);
4072 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4073 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4076 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4077 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4078 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4079 /// simple superregister reference. Idx is an index in the 128 bits
4080 /// we want. It need not be aligned to a 128-bit boundary. That makes
4081 /// lowering INSERT_VECTOR_ELT operations easier.
4082 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4083 SelectionDAG &DAG, const SDLoc &dl) {
4084 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4085 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4088 /// Widen a vector to a larger size with the same scalar type, with the new
4089 /// elements either zero or undef.
4090 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
4091 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4092 const SDLoc &dl) {
4093 assert(Vec.getValueSizeInBits().getFixedValue() <= VT.getFixedSizeInBits() &&
4094 Vec.getValueType().getScalarType() == VT.getScalarType() &&
4095 "Unsupported vector widening type");
4096 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
4097 : DAG.getUNDEF(VT);
4098 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
4099 DAG.getIntPtrConstant(0, dl));
4102 /// Widen a vector to a larger size with the same scalar type, with the new
4103 /// elements either zero or undef.
4104 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
4105 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4106 const SDLoc &dl, unsigned WideSizeInBits) {
4107 assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
4108 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
4109 "Unsupported vector widening type");
4110 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
4111 MVT SVT = Vec.getSimpleValueType().getScalarType();
4112 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
4113 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4116 /// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
4117 /// and bitcast with integer types.
4118 static MVT widenMaskVectorType(MVT VT, const X86Subtarget &Subtarget) {
4119 assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
4120 unsigned NumElts = VT.getVectorNumElements();
4121 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
4122 return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4123 return VT;
4126 /// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
4127 /// bitcast with integer types.
4128 static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
4129 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4130 const SDLoc &dl) {
4131 MVT VT = widenMaskVectorType(Vec.getSimpleValueType(), Subtarget);
4132 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4135 // Helper function to collect subvector ops that are concatenated together,
4136 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
4137 // The subvectors in Ops are guaranteed to be the same type.
4138 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops,
4139 SelectionDAG &DAG) {
4140 assert(Ops.empty() && "Expected an empty ops vector");
4142 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
4143 Ops.append(N->op_begin(), N->op_end());
4144 return true;
4147 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
4148 SDValue Src = N->getOperand(0);
4149 SDValue Sub = N->getOperand(1);
4150 const APInt &Idx = N->getConstantOperandAPInt(2);
4151 EVT VT = Src.getValueType();
4152 EVT SubVT = Sub.getValueType();
4154 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
4155 // insert_subvector(undef, x, lo)
4156 if (Idx == 0 && Src.isUndef()) {
4157 Ops.push_back(Sub);
4158 Ops.push_back(DAG.getUNDEF(SubVT));
4159 return true;
4161 if (Idx == (VT.getVectorNumElements() / 2)) {
4162 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
4163 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
4164 Src.getOperand(1).getValueType() == SubVT &&
4165 isNullConstant(Src.getOperand(2))) {
4166 // Attempt to recurse into inner (matching) concats.
4167 SDValue Lo = Src.getOperand(1);
4168 SDValue Hi = Sub;
4169 SmallVector<SDValue, 2> LoOps, HiOps;
4170 if (collectConcatOps(Lo.getNode(), LoOps, DAG) &&
4171 collectConcatOps(Hi.getNode(), HiOps, DAG) &&
4172 LoOps.size() == HiOps.size()) {
4173 Ops.append(LoOps);
4174 Ops.append(HiOps);
4175 return true;
4177 Ops.push_back(Lo);
4178 Ops.push_back(Hi);
4179 return true;
4181 // insert_subvector(x, extract_subvector(x, lo), hi)
4182 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4183 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
4184 Ops.append(2, Sub);
4185 return true;
4187 // insert_subvector(undef, x, hi)
4188 if (Src.isUndef()) {
4189 Ops.push_back(DAG.getUNDEF(SubVT));
4190 Ops.push_back(Sub);
4191 return true;
4197 return false;
4200 // Helper to check if \p V can be split into subvectors and the upper subvectors
4201 // are all undef. In which case return the lower subvector.
4202 static SDValue isUpperSubvectorUndef(SDValue V, const SDLoc &DL,
4203 SelectionDAG &DAG) {
4204 SmallVector<SDValue> SubOps;
4205 if (!collectConcatOps(V.getNode(), SubOps, DAG))
4206 return SDValue();
4208 unsigned NumSubOps = SubOps.size();
4209 unsigned HalfNumSubOps = NumSubOps / 2;
4210 assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
4212 ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
4213 if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
4214 return SDValue();
4216 EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
4217 ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
4218 return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
4221 // Helper to check if we can access all the constituent subvectors without any
4222 // extract ops.
4223 static bool isFreeToSplitVector(SDNode *N, SelectionDAG &DAG) {
4224 SmallVector<SDValue> Ops;
4225 return collectConcatOps(N, Ops, DAG);
4228 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4229 const SDLoc &dl) {
4230 EVT VT = Op.getValueType();
4231 unsigned NumElems = VT.getVectorNumElements();
4232 unsigned SizeInBits = VT.getSizeInBits();
4233 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4234 "Can't split odd sized vector");
4236 // If this is a splat value (with no-undefs) then use the lower subvector,
4237 // which should be a free extraction.
4238 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4239 if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4240 return std::make_pair(Lo, Lo);
4242 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4243 return std::make_pair(Lo, Hi);
4246 /// Break an operation into 2 half sized ops and then concatenate the results.
4247 static SDValue splitVectorOp(SDValue Op, SelectionDAG &DAG, const SDLoc &dl) {
4248 unsigned NumOps = Op.getNumOperands();
4249 EVT VT = Op.getValueType();
4251 // Extract the LHS Lo/Hi vectors
4252 SmallVector<SDValue> LoOps(NumOps, SDValue());
4253 SmallVector<SDValue> HiOps(NumOps, SDValue());
4254 for (unsigned I = 0; I != NumOps; ++I) {
4255 SDValue SrcOp = Op.getOperand(I);
4256 if (!SrcOp.getValueType().isVector()) {
4257 LoOps[I] = HiOps[I] = SrcOp;
4258 continue;
4260 std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4263 EVT LoVT, HiVT;
4264 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4265 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4266 DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4267 DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4270 /// Break an unary integer operation into 2 half sized ops and then
4271 /// concatenate the result back.
4272 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG,
4273 const SDLoc &dl) {
4274 // Make sure we only try to split 256/512-bit types to avoid creating
4275 // narrow vectors.
4276 [[maybe_unused]] EVT VT = Op.getValueType();
4277 assert((Op.getOperand(0).getValueType().is256BitVector() ||
4278 Op.getOperand(0).getValueType().is512BitVector()) &&
4279 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4280 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4281 VT.getVectorNumElements() &&
4282 "Unexpected VTs!");
4283 return splitVectorOp(Op, DAG, dl);
4286 /// Break a binary integer operation into 2 half sized ops and then
4287 /// concatenate the result back.
4288 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG,
4289 const SDLoc &dl) {
4290 // Assert that all the types match.
4291 [[maybe_unused]] EVT VT = Op.getValueType();
4292 assert(Op.getOperand(0).getValueType() == VT &&
4293 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4294 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4295 return splitVectorOp(Op, DAG, dl);
4298 // Helper for splitting operands of an operation to legal target size and
4299 // apply a function on each part.
4300 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4301 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4302 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4303 // The argument Builder is a function that will be applied on each split part:
4304 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4305 template <typename F>
4306 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
4307 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4308 F Builder, bool CheckBWI = true) {
4309 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4310 unsigned NumSubs = 1;
4311 if ((CheckBWI && Subtarget.useBWIRegs()) ||
4312 (!CheckBWI && Subtarget.useAVX512Regs())) {
4313 if (VT.getSizeInBits() > 512) {
4314 NumSubs = VT.getSizeInBits() / 512;
4315 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4317 } else if (Subtarget.hasAVX2()) {
4318 if (VT.getSizeInBits() > 256) {
4319 NumSubs = VT.getSizeInBits() / 256;
4320 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4322 } else {
4323 if (VT.getSizeInBits() > 128) {
4324 NumSubs = VT.getSizeInBits() / 128;
4325 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4329 if (NumSubs == 1)
4330 return Builder(DAG, DL, Ops);
4332 SmallVector<SDValue, 4> Subs;
4333 for (unsigned i = 0; i != NumSubs; ++i) {
4334 SmallVector<SDValue, 2> SubOps;
4335 for (SDValue Op : Ops) {
4336 EVT OpVT = Op.getValueType();
4337 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4338 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4339 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4341 Subs.push_back(Builder(DAG, DL, SubOps));
4343 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4346 // Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4347 // targets.
4348 static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4349 ArrayRef<SDValue> Ops, SelectionDAG &DAG,
4350 const X86Subtarget &Subtarget) {
4351 assert(Subtarget.hasAVX512() && "AVX512 target expected");
4352 MVT SVT = VT.getScalarType();
4354 // If we have a 32/64 splatted constant, splat it to DstTy to
4355 // encourage a foldable broadcast'd operand.
4356 auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4357 unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4358 // AVX512 broadcasts 32/64-bit operands.
4359 // TODO: Support float once getAVX512Node is used by fp-ops.
4360 if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4361 !DAG.getTargetLoweringInfo().isTypeLegal(SVT))
4362 return SDValue();
4363 // If we're not widening, don't bother if we're not bitcasting.
4364 if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4365 return SDValue();
4366 if (auto *BV = dyn_cast<BuildVectorSDNode>(peekThroughBitcasts(Op))) {
4367 APInt SplatValue, SplatUndef;
4368 unsigned SplatBitSize;
4369 bool HasAnyUndefs;
4370 if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4371 HasAnyUndefs, OpEltSizeInBits) &&
4372 !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4373 return DAG.getConstant(SplatValue, DL, DstVT);
4375 return SDValue();
4378 bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4380 MVT DstVT = VT;
4381 if (Widen)
4382 DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4384 // Canonicalize src operands.
4385 SmallVector<SDValue> SrcOps(Ops);
4386 for (SDValue &Op : SrcOps) {
4387 MVT OpVT = Op.getSimpleValueType();
4388 // Just pass through scalar operands.
4389 if (!OpVT.isVector())
4390 continue;
4391 assert(OpVT == VT && "Vector type mismatch");
4393 if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4394 Op = BroadcastOp;
4395 continue;
4398 // Just widen the subvector by inserting into an undef wide vector.
4399 if (Widen)
4400 Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4403 SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4405 // Perform the 512-bit op then extract the bottom subvector.
4406 if (Widen)
4407 Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4408 return Res;
4411 /// Insert i1-subvector to i1-vector.
4412 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
4413 const X86Subtarget &Subtarget) {
4415 SDLoc dl(Op);
4416 SDValue Vec = Op.getOperand(0);
4417 SDValue SubVec = Op.getOperand(1);
4418 SDValue Idx = Op.getOperand(2);
4419 unsigned IdxVal = Op.getConstantOperandVal(2);
4421 // Inserting undef is a nop. We can just return the original vector.
4422 if (SubVec.isUndef())
4423 return Vec;
4425 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4426 return Op;
4428 MVT OpVT = Op.getSimpleValueType();
4429 unsigned NumElems = OpVT.getVectorNumElements();
4430 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4432 // Extend to natively supported kshift.
4433 MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4435 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4436 // if necessary.
4437 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4438 // May need to promote to a legal type.
4439 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4440 DAG.getConstant(0, dl, WideOpVT),
4441 SubVec, Idx);
4442 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4445 MVT SubVecVT = SubVec.getSimpleValueType();
4446 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4447 assert(IdxVal + SubVecNumElems <= NumElems &&
4448 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4449 "Unexpected index value in INSERT_SUBVECTOR");
4451 SDValue Undef = DAG.getUNDEF(WideOpVT);
4453 if (IdxVal == 0) {
4454 // Zero lower bits of the Vec
4455 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4456 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4457 ZeroIdx);
4458 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4459 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4460 // Merge them together, SubVec should be zero extended.
4461 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4462 DAG.getConstant(0, dl, WideOpVT),
4463 SubVec, ZeroIdx);
4464 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4465 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4468 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4469 Undef, SubVec, ZeroIdx);
4471 if (Vec.isUndef()) {
4472 assert(IdxVal != 0 && "Unexpected index");
4473 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4474 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4475 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4478 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4479 assert(IdxVal != 0 && "Unexpected index");
4480 // If upper elements of Vec are known undef, then just shift into place.
4481 if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4482 [](SDValue V) { return V.isUndef(); })) {
4483 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4484 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4485 } else {
4486 NumElems = WideOpVT.getVectorNumElements();
4487 unsigned ShiftLeft = NumElems - SubVecNumElems;
4488 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4489 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4490 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4491 if (ShiftRight != 0)
4492 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4493 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4495 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4498 // Simple case when we put subvector in the upper part
4499 if (IdxVal + SubVecNumElems == NumElems) {
4500 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4501 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4502 if (SubVecNumElems * 2 == NumElems) {
4503 // Special case, use legal zero extending insert_subvector. This allows
4504 // isel to optimize when bits are known zero.
4505 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4506 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4507 DAG.getConstant(0, dl, WideOpVT),
4508 Vec, ZeroIdx);
4509 } else {
4510 // Otherwise use explicit shifts to zero the bits.
4511 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4512 Undef, Vec, ZeroIdx);
4513 NumElems = WideOpVT.getVectorNumElements();
4514 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4515 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4516 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4518 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4519 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4522 // Inserting into the middle is more complicated.
4524 NumElems = WideOpVT.getVectorNumElements();
4526 // Widen the vector if needed.
4527 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4529 unsigned ShiftLeft = NumElems - SubVecNumElems;
4530 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4532 // Do an optimization for the most frequently used types.
4533 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4534 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4535 Mask0.flipAllBits();
4536 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4537 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4538 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4539 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4540 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4541 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4542 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4543 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4545 // Reduce to original width if needed.
4546 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4549 // Clear the upper bits of the subvector and move it to its insert position.
4550 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4551 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4552 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4553 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4555 // Isolate the bits below the insertion point.
4556 unsigned LowShift = NumElems - IdxVal;
4557 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
4558 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4559 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
4560 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4562 // Isolate the bits after the last inserted bit.
4563 unsigned HighShift = IdxVal + SubVecNumElems;
4564 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
4565 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4566 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
4567 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4569 // Now OR all 3 pieces together.
4570 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
4571 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
4573 // Reduce to original width if needed.
4574 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4577 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
4578 const SDLoc &dl) {
4579 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
4580 EVT SubVT = V1.getValueType();
4581 EVT SubSVT = SubVT.getScalarType();
4582 unsigned SubNumElts = SubVT.getVectorNumElements();
4583 unsigned SubVectorWidth = SubVT.getSizeInBits();
4584 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
4585 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
4586 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
4589 /// Returns a vector of specified type with all bits set.
4590 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
4591 /// Then bitcast to their original type, ensuring they get CSE'd.
4592 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4593 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4594 "Expected a 128/256/512-bit vector type");
4595 unsigned NumElts = VT.getSizeInBits() / 32;
4596 SDValue Vec = DAG.getAllOnesConstant(dl, MVT::getVectorVT(MVT::i32, NumElts));
4597 return DAG.getBitcast(VT, Vec);
4600 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
4601 SDValue In, SelectionDAG &DAG) {
4602 EVT InVT = In.getValueType();
4603 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
4604 assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
4605 ISD::ZERO_EXTEND == Opcode) &&
4606 "Unknown extension opcode");
4608 // For 256-bit vectors, we only need the lower (128-bit) input half.
4609 // For 512-bit vectors, we only need the lower input half or quarter.
4610 if (InVT.getSizeInBits() > 128) {
4611 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
4612 "Expected VTs to be the same size!");
4613 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
4614 In = extractSubVector(In, 0, DAG, DL,
4615 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
4616 InVT = In.getValueType();
4619 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
4620 Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
4622 return DAG.getNode(Opcode, DL, VT, In);
4625 // Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
4626 static SDValue getBitSelect(const SDLoc &DL, MVT VT, SDValue LHS, SDValue RHS,
4627 SDValue Mask, SelectionDAG &DAG) {
4628 LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
4629 RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
4630 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
4633 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
4634 bool Lo, bool Unary) {
4635 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
4636 "Illegal vector type to unpack");
4637 assert(Mask.empty() && "Expected an empty shuffle mask vector");
4638 int NumElts = VT.getVectorNumElements();
4639 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
4640 for (int i = 0; i < NumElts; ++i) {
4641 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
4642 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
4643 Pos += (Unary ? 0 : NumElts * (i % 2));
4644 Pos += (Lo ? 0 : NumEltsInLane / 2);
4645 Mask.push_back(Pos);
4649 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
4650 /// imposed by AVX and specific to the unary pattern. Example:
4651 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
4652 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
4653 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
4654 bool Lo) {
4655 assert(Mask.empty() && "Expected an empty shuffle mask vector");
4656 int NumElts = VT.getVectorNumElements();
4657 for (int i = 0; i < NumElts; ++i) {
4658 int Pos = i / 2;
4659 Pos += (Lo ? 0 : NumElts / 2);
4660 Mask.push_back(Pos);
4664 // Attempt to constant fold, else just create a VECTOR_SHUFFLE.
4665 static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
4666 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
4667 if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
4668 (ISD::isBuildVectorOfConstantSDNodes(V2.getNode()) || V2.isUndef())) {
4669 SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
4670 for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
4671 int M = Mask[I];
4672 if (M < 0)
4673 continue;
4674 SDValue V = (M < NumElts) ? V1 : V2;
4675 if (V.isUndef())
4676 continue;
4677 Ops[I] = V.getOperand(M % NumElts);
4679 return DAG.getBuildVector(VT, dl, Ops);
4682 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4685 /// Returns a vector_shuffle node for an unpackl operation.
4686 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
4687 SDValue V1, SDValue V2) {
4688 SmallVector<int, 8> Mask;
4689 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
4690 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
4693 /// Returns a vector_shuffle node for an unpackh operation.
4694 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
4695 SDValue V1, SDValue V2) {
4696 SmallVector<int, 8> Mask;
4697 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
4698 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
4701 /// Returns a node that packs the LHS + RHS nodes together at half width.
4702 /// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
4703 /// TODO: Add subvector splitting if/when we have a need for it.
4704 static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
4705 const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
4706 bool PackHiHalf = false) {
4707 MVT OpVT = LHS.getSimpleValueType();
4708 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4709 bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
4710 assert(OpVT == RHS.getSimpleValueType() &&
4711 VT.getSizeInBits() == OpVT.getSizeInBits() &&
4712 (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
4713 "Unexpected PACK operand types");
4714 assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
4715 "Unexpected PACK result type");
4717 // Rely on vector shuffles for vXi64 -> vXi32 packing.
4718 if (EltSizeInBits == 32) {
4719 SmallVector<int> PackMask;
4720 int Offset = PackHiHalf ? 1 : 0;
4721 int NumElts = VT.getVectorNumElements();
4722 for (int I = 0; I != NumElts; I += 4) {
4723 PackMask.push_back(I + Offset);
4724 PackMask.push_back(I + Offset + 2);
4725 PackMask.push_back(I + Offset + NumElts);
4726 PackMask.push_back(I + Offset + NumElts + 2);
4728 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
4729 DAG.getBitcast(VT, RHS), PackMask);
4732 // See if we already have sufficient leading bits for PACKSS/PACKUS.
4733 if (!PackHiHalf) {
4734 if (UsePackUS &&
4735 DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
4736 DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
4737 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
4739 if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
4740 DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
4741 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
4744 // Fallback to sign/zero extending the requested half and pack.
4745 SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
4746 if (UsePackUS) {
4747 if (PackHiHalf) {
4748 LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
4749 RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
4750 } else {
4751 SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
4752 LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
4753 RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
4755 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
4758 if (!PackHiHalf) {
4759 LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
4760 RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
4762 LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
4763 RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
4764 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
4767 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4768 /// This produces a shuffle where the low element of V2 is swizzled into the
4769 /// zero/undef vector, landing at element Idx.
4770 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4771 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
4772 bool IsZero,
4773 const X86Subtarget &Subtarget,
4774 SelectionDAG &DAG) {
4775 MVT VT = V2.getSimpleValueType();
4776 SDValue V1 = IsZero
4777 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4778 int NumElems = VT.getVectorNumElements();
4779 SmallVector<int, 16> MaskVec(NumElems);
4780 for (int i = 0; i != NumElems; ++i)
4781 // If this is the insertion idx, put the low elt of V2 here.
4782 MaskVec[i] = (i == Idx) ? NumElems : i;
4783 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
4786 static ConstantPoolSDNode *getTargetConstantPoolFromBasePtr(SDValue Ptr) {
4787 if (Ptr.getOpcode() == X86ISD::Wrapper ||
4788 Ptr.getOpcode() == X86ISD::WrapperRIP)
4789 Ptr = Ptr.getOperand(0);
4790 return dyn_cast<ConstantPoolSDNode>(Ptr);
4793 // TODO: Add support for non-zero offsets.
4794 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
4795 ConstantPoolSDNode *CNode = getTargetConstantPoolFromBasePtr(Ptr);
4796 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
4797 return nullptr;
4798 return CNode->getConstVal();
4801 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
4802 if (!Load || !ISD::isNormalLoad(Load))
4803 return nullptr;
4804 return getTargetConstantFromBasePtr(Load->getBasePtr());
4807 static const Constant *getTargetConstantFromNode(SDValue Op) {
4808 Op = peekThroughBitcasts(Op);
4809 return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
4812 const Constant *
4813 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
4814 assert(LD && "Unexpected null LoadSDNode");
4815 return getTargetConstantFromNode(LD);
4818 // Extract raw constant bits from constant pools.
4819 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
4820 APInt &UndefElts,
4821 SmallVectorImpl<APInt> &EltBits,
4822 bool AllowWholeUndefs = true,
4823 bool AllowPartialUndefs = false) {
4824 assert(EltBits.empty() && "Expected an empty EltBits vector");
4826 Op = peekThroughBitcasts(Op);
4828 EVT VT = Op.getValueType();
4829 unsigned SizeInBits = VT.getSizeInBits();
4830 assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
4831 unsigned NumElts = SizeInBits / EltSizeInBits;
4833 // Bitcast a source array of element bits to the target size.
4834 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
4835 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
4836 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
4837 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
4838 "Constant bit sizes don't match");
4840 // Don't split if we don't allow undef bits.
4841 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
4842 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
4843 return false;
4845 // If we're already the right size, don't bother bitcasting.
4846 if (NumSrcElts == NumElts) {
4847 UndefElts = UndefSrcElts;
4848 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
4849 return true;
4852 // Extract all the undef/constant element data and pack into single bitsets.
4853 APInt UndefBits(SizeInBits, 0);
4854 APInt MaskBits(SizeInBits, 0);
4856 for (unsigned i = 0; i != NumSrcElts; ++i) {
4857 unsigned BitOffset = i * SrcEltSizeInBits;
4858 if (UndefSrcElts[i])
4859 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
4860 MaskBits.insertBits(SrcEltBits[i], BitOffset);
4863 // Split the undef/constant single bitset data into the target elements.
4864 UndefElts = APInt(NumElts, 0);
4865 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
4867 for (unsigned i = 0; i != NumElts; ++i) {
4868 unsigned BitOffset = i * EltSizeInBits;
4869 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
4871 // Only treat an element as UNDEF if all bits are UNDEF.
4872 if (UndefEltBits.isAllOnes()) {
4873 if (!AllowWholeUndefs)
4874 return false;
4875 UndefElts.setBit(i);
4876 continue;
4879 // If only some bits are UNDEF then treat them as zero (or bail if not
4880 // supported).
4881 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
4882 return false;
4884 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
4886 return true;
4889 // Collect constant bits and insert into mask/undef bit masks.
4890 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
4891 unsigned UndefBitIndex) {
4892 if (!Cst)
4893 return false;
4894 if (isa<UndefValue>(Cst)) {
4895 Undefs.setBit(UndefBitIndex);
4896 return true;
4898 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4899 Mask = CInt->getValue();
4900 return true;
4902 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4903 Mask = CFP->getValueAPF().bitcastToAPInt();
4904 return true;
4906 if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
4907 Type *Ty = CDS->getType();
4908 Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
4909 Type *EltTy = CDS->getElementType();
4910 bool IsInteger = EltTy->isIntegerTy();
4911 bool IsFP =
4912 EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
4913 if (!IsInteger && !IsFP)
4914 return false;
4915 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
4916 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
4917 if (IsInteger)
4918 Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
4919 else
4920 Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
4921 I * EltBits);
4922 return true;
4924 return false;
4927 // Handle UNDEFs.
4928 if (Op.isUndef()) {
4929 APInt UndefSrcElts = APInt::getAllOnes(NumElts);
4930 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
4931 return CastBitData(UndefSrcElts, SrcEltBits);
4934 // Extract scalar constant bits.
4935 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
4936 APInt UndefSrcElts = APInt::getZero(1);
4937 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
4938 return CastBitData(UndefSrcElts, SrcEltBits);
4940 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
4941 APInt UndefSrcElts = APInt::getZero(1);
4942 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
4943 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
4944 return CastBitData(UndefSrcElts, SrcEltBits);
4947 // Extract constant bits from build vector.
4948 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
4949 BitVector Undefs;
4950 SmallVector<APInt> SrcEltBits;
4951 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4952 if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
4953 APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
4954 for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
4955 if (Undefs[I])
4956 UndefSrcElts.setBit(I);
4957 return CastBitData(UndefSrcElts, SrcEltBits);
4961 // Extract constant bits from constant pool vector.
4962 if (auto *Cst = getTargetConstantFromNode(Op)) {
4963 Type *CstTy = Cst->getType();
4964 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
4965 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
4966 return false;
4968 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
4969 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
4970 if ((SizeInBits % SrcEltSizeInBits) != 0)
4971 return false;
4973 APInt UndefSrcElts(NumSrcElts, 0);
4974 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
4975 for (unsigned i = 0; i != NumSrcElts; ++i)
4976 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
4977 UndefSrcElts, i))
4978 return false;
4980 return CastBitData(UndefSrcElts, SrcEltBits);
4983 // Extract constant bits from a broadcasted constant pool scalar.
4984 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
4985 EltSizeInBits <= VT.getScalarSizeInBits()) {
4986 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
4987 if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
4988 return false;
4990 SDValue Ptr = MemIntr->getBasePtr();
4991 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
4992 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4993 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
4995 APInt UndefSrcElts(NumSrcElts, 0);
4996 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
4997 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
4998 if (UndefSrcElts[0])
4999 UndefSrcElts.setBits(0, NumSrcElts);
5000 if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
5001 SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
5002 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5003 return CastBitData(UndefSrcElts, SrcEltBits);
5008 // Extract constant bits from a subvector broadcast.
5009 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
5010 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5011 SDValue Ptr = MemIntr->getBasePtr();
5012 // The source constant may be larger than the subvector broadcast,
5013 // ensure we extract the correct subvector constants.
5014 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
5015 Type *CstTy = Cst->getType();
5016 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5017 unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
5018 if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
5019 (SizeInBits % SubVecSizeInBits) != 0)
5020 return false;
5021 unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
5022 unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
5023 unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
5024 APInt UndefSubElts(NumSubElts, 0);
5025 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
5026 APInt(CstEltSizeInBits, 0));
5027 for (unsigned i = 0; i != NumSubElts; ++i) {
5028 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
5029 UndefSubElts, i))
5030 return false;
5031 for (unsigned j = 1; j != NumSubVecs; ++j)
5032 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
5034 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
5035 UndefSubElts);
5036 return CastBitData(UndefSubElts, SubEltBits);
5040 // Extract a rematerialized scalar constant insertion.
5041 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5042 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5043 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5044 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5045 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5047 APInt UndefSrcElts(NumSrcElts, 0);
5048 SmallVector<APInt, 64> SrcEltBits;
5049 const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
5050 SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
5051 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5052 return CastBitData(UndefSrcElts, SrcEltBits);
5055 // Insert constant bits from a base and sub vector sources.
5056 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
5057 // If bitcasts to larger elements we might lose track of undefs - don't
5058 // allow any to be safe.
5059 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5060 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
5062 APInt UndefSrcElts, UndefSubElts;
5063 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
5064 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
5065 UndefSubElts, EltSubBits,
5066 AllowWholeUndefs && AllowUndefs,
5067 AllowPartialUndefs && AllowUndefs) &&
5068 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
5069 UndefSrcElts, EltSrcBits,
5070 AllowWholeUndefs && AllowUndefs,
5071 AllowPartialUndefs && AllowUndefs)) {
5072 unsigned BaseIdx = Op.getConstantOperandVal(2);
5073 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
5074 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
5075 EltSrcBits[BaseIdx + i] = EltSubBits[i];
5076 return CastBitData(UndefSrcElts, EltSrcBits);
5080 // Extract constant bits from a subvector's source.
5081 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5082 // TODO - support extract_subvector through bitcasts.
5083 if (EltSizeInBits != VT.getScalarSizeInBits())
5084 return false;
5086 if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5087 UndefElts, EltBits, AllowWholeUndefs,
5088 AllowPartialUndefs)) {
5089 EVT SrcVT = Op.getOperand(0).getValueType();
5090 unsigned NumSrcElts = SrcVT.getVectorNumElements();
5091 unsigned NumSubElts = VT.getVectorNumElements();
5092 unsigned BaseIdx = Op.getConstantOperandVal(1);
5093 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5094 if ((BaseIdx + NumSubElts) != NumSrcElts)
5095 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5096 if (BaseIdx != 0)
5097 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5098 return true;
5102 // Extract constant bits from shuffle node sources.
5103 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5104 // TODO - support shuffle through bitcasts.
5105 if (EltSizeInBits != VT.getScalarSizeInBits())
5106 return false;
5108 ArrayRef<int> Mask = SVN->getMask();
5109 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5110 llvm::any_of(Mask, [](int M) { return M < 0; }))
5111 return false;
5113 APInt UndefElts0, UndefElts1;
5114 SmallVector<APInt, 32> EltBits0, EltBits1;
5115 if (isAnyInRange(Mask, 0, NumElts) &&
5116 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5117 UndefElts0, EltBits0, AllowWholeUndefs,
5118 AllowPartialUndefs))
5119 return false;
5120 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5121 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5122 UndefElts1, EltBits1, AllowWholeUndefs,
5123 AllowPartialUndefs))
5124 return false;
5126 UndefElts = APInt::getZero(NumElts);
5127 for (int i = 0; i != (int)NumElts; ++i) {
5128 int M = Mask[i];
5129 if (M < 0) {
5130 UndefElts.setBit(i);
5131 EltBits.push_back(APInt::getZero(EltSizeInBits));
5132 } else if (M < (int)NumElts) {
5133 if (UndefElts0[M])
5134 UndefElts.setBit(i);
5135 EltBits.push_back(EltBits0[M]);
5136 } else {
5137 if (UndefElts1[M - NumElts])
5138 UndefElts.setBit(i);
5139 EltBits.push_back(EltBits1[M - NumElts]);
5142 return true;
5145 return false;
5148 namespace llvm {
5149 namespace X86 {
5150 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
5151 APInt UndefElts;
5152 SmallVector<APInt, 16> EltBits;
5153 if (getTargetConstantBitsFromNode(
5154 Op, Op.getScalarValueSizeInBits(), UndefElts, EltBits,
5155 /*AllowWholeUndefs*/ true, AllowPartialUndefs)) {
5156 int SplatIndex = -1;
5157 for (int i = 0, e = EltBits.size(); i != e; ++i) {
5158 if (UndefElts[i])
5159 continue;
5160 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5161 SplatIndex = -1;
5162 break;
5164 SplatIndex = i;
5166 if (0 <= SplatIndex) {
5167 SplatVal = EltBits[SplatIndex];
5168 return true;
5172 return false;
5174 } // namespace X86
5175 } // namespace llvm
5177 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
5178 unsigned MaskEltSizeInBits,
5179 SmallVectorImpl<uint64_t> &RawMask,
5180 APInt &UndefElts) {
5181 // Extract the raw target constant bits.
5182 SmallVector<APInt, 64> EltBits;
5183 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5184 EltBits, /* AllowWholeUndefs */ true,
5185 /* AllowPartialUndefs */ false))
5186 return false;
5188 // Insert the extracted elements into the mask.
5189 for (const APInt &Elt : EltBits)
5190 RawMask.push_back(Elt.getZExtValue());
5192 return true;
5195 static bool isConstantPowerOf2(SDValue V, unsigned EltSizeInBIts,
5196 bool AllowUndefs) {
5197 APInt UndefElts;
5198 SmallVector<APInt, 64> EltBits;
5199 if (!getTargetConstantBitsFromNode(V, EltSizeInBIts, UndefElts, EltBits,
5200 /*AllowWholeUndefs*/ AllowUndefs,
5201 /*AllowPartialUndefs*/ false))
5202 return false;
5204 bool IsPow2OrUndef = true;
5205 for (unsigned I = 0, E = EltBits.size(); I != E; ++I)
5206 IsPow2OrUndef &= UndefElts[I] || EltBits[I].isPowerOf2();
5207 return IsPow2OrUndef;
5210 // Match not(xor X, -1) -> X.
5211 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
5212 // Match not(extract_subvector(xor X, -1)) -> extract_subvector(X).
5213 // Match not(concat_vectors(xor X, -1, xor Y, -1)) -> concat_vectors(X, Y).
5214 // Match or(not(X),not(Y)) -> and(X, Y).
5215 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
5216 V = peekThroughBitcasts(V);
5217 EVT VT = V.getValueType();
5218 if (V.getOpcode() == ISD::XOR &&
5219 (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
5220 isAllOnesConstant(V.getOperand(1))))
5221 return V.getOperand(0);
5222 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5223 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5224 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5225 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5226 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
5227 V.getOperand(1));
5230 if (V.getOpcode() == X86ISD::PCMPGT &&
5231 !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
5232 !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
5233 V.getOperand(0).hasOneUse()) {
5234 APInt UndefElts;
5235 SmallVector<APInt> EltBits;
5236 if (getTargetConstantBitsFromNode(V.getOperand(0),
5237 V.getScalarValueSizeInBits(), UndefElts,
5238 EltBits)) {
5239 // Don't fold min_signed_value -> (min_signed_value - 1)
5240 bool MinSigned = false;
5241 for (APInt &Elt : EltBits) {
5242 MinSigned |= Elt.isMinSignedValue();
5243 Elt -= 1;
5245 if (!MinSigned) {
5246 SDLoc DL(V);
5247 MVT VT = V.getSimpleValueType();
5248 return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5249 getConstVector(EltBits, UndefElts, VT, DAG, DL));
5253 SmallVector<SDValue, 2> CatOps;
5254 if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5255 for (SDValue &CatOp : CatOps) {
5256 SDValue NotCat = IsNOT(CatOp, DAG);
5257 if (!NotCat) return SDValue();
5258 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5260 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), VT, CatOps);
5262 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
5263 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
5264 // TODO: Handle cases with single NOT operand -> ANDNP
5265 if (SDValue Op1 = IsNOT(V.getOperand(1), DAG))
5266 if (SDValue Op0 = IsNOT(V.getOperand(0), DAG))
5267 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
5268 DAG.getBitcast(VT, Op1));
5270 return SDValue();
5273 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5274 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5275 /// Note: This ignores saturation, so inputs must be checked first.
5276 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
5277 bool Unary, unsigned NumStages = 1) {
5278 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5279 unsigned NumElts = VT.getVectorNumElements();
5280 unsigned NumLanes = VT.getSizeInBits() / 128;
5281 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5282 unsigned Offset = Unary ? 0 : NumElts;
5283 unsigned Repetitions = 1u << (NumStages - 1);
5284 unsigned Increment = 1u << NumStages;
5285 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5287 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5288 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5289 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5290 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5291 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5292 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5297 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
5298 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5299 APInt &DemandedLHS, APInt &DemandedRHS) {
5300 int NumLanes = VT.getSizeInBits() / 128;
5301 int NumElts = DemandedElts.getBitWidth();
5302 int NumInnerElts = NumElts / 2;
5303 int NumEltsPerLane = NumElts / NumLanes;
5304 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5306 DemandedLHS = APInt::getZero(NumInnerElts);
5307 DemandedRHS = APInt::getZero(NumInnerElts);
5309 // Map DemandedElts to the packed operands.
5310 for (int Lane = 0; Lane != NumLanes; ++Lane) {
5311 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5312 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
5313 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
5314 if (DemandedElts[OuterIdx])
5315 DemandedLHS.setBit(InnerIdx);
5316 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
5317 DemandedRHS.setBit(InnerIdx);
5322 // Split the demanded elts of a HADD/HSUB node between its operands.
5323 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
5324 APInt &DemandedLHS, APInt &DemandedRHS) {
5325 getHorizDemandedEltsForFirstOperand(VT.getSizeInBits(), DemandedElts,
5326 DemandedLHS, DemandedRHS);
5327 DemandedLHS |= DemandedLHS << 1;
5328 DemandedRHS |= DemandedRHS << 1;
5331 /// Calculates the shuffle mask corresponding to the target-specific opcode.
5332 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5333 /// operands in \p Ops, and returns true.
5334 /// Sets \p IsUnary to true if only one source is used. Note that this will set
5335 /// IsUnary for shuffles which use a single input multiple times, and in those
5336 /// cases it will adjust the mask to only have indices within that single input.
5337 /// It is an error to call this with non-empty Mask/Ops vectors.
5338 static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
5339 SmallVectorImpl<SDValue> &Ops,
5340 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5341 if (!isTargetShuffle(N.getOpcode()))
5342 return false;
5344 MVT VT = N.getSimpleValueType();
5345 unsigned NumElems = VT.getVectorNumElements();
5346 unsigned MaskEltSize = VT.getScalarSizeInBits();
5347 SmallVector<uint64_t, 32> RawMask;
5348 APInt RawUndefs;
5349 uint64_t ImmN;
5351 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
5352 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
5354 IsUnary = false;
5355 bool IsFakeUnary = false;
5356 switch (N.getOpcode()) {
5357 case X86ISD::BLENDI:
5358 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5359 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5360 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5361 DecodeBLENDMask(NumElems, ImmN, Mask);
5362 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5363 break;
5364 case X86ISD::SHUFP:
5365 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5366 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5367 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5368 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
5369 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5370 break;
5371 case X86ISD::INSERTPS:
5372 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5373 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5374 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5375 DecodeINSERTPSMask(ImmN, Mask, /*SrcIsMem=*/false);
5376 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5377 break;
5378 case X86ISD::EXTRQI:
5379 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5380 if (isa<ConstantSDNode>(N.getOperand(1)) &&
5381 isa<ConstantSDNode>(N.getOperand(2))) {
5382 int BitLen = N.getConstantOperandVal(1);
5383 int BitIdx = N.getConstantOperandVal(2);
5384 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
5385 IsUnary = true;
5387 break;
5388 case X86ISD::INSERTQI:
5389 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5390 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5391 if (isa<ConstantSDNode>(N.getOperand(2)) &&
5392 isa<ConstantSDNode>(N.getOperand(3))) {
5393 int BitLen = N.getConstantOperandVal(2);
5394 int BitIdx = N.getConstantOperandVal(3);
5395 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
5396 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5398 break;
5399 case X86ISD::UNPCKH:
5400 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5401 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5402 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
5403 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5404 break;
5405 case X86ISD::UNPCKL:
5406 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5407 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5408 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
5409 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5410 break;
5411 case X86ISD::MOVHLPS:
5412 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5413 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5414 DecodeMOVHLPSMask(NumElems, Mask);
5415 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5416 break;
5417 case X86ISD::MOVLHPS:
5418 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5419 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5420 DecodeMOVLHPSMask(NumElems, Mask);
5421 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5422 break;
5423 case X86ISD::VALIGN:
5424 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
5425 "Only 32-bit and 64-bit elements are supported!");
5426 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5427 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5428 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5429 DecodeVALIGNMask(NumElems, ImmN, Mask);
5430 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5431 Ops.push_back(N.getOperand(1));
5432 Ops.push_back(N.getOperand(0));
5433 break;
5434 case X86ISD::PALIGNR:
5435 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5436 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5437 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5438 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5439 DecodePALIGNRMask(NumElems, ImmN, Mask);
5440 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5441 Ops.push_back(N.getOperand(1));
5442 Ops.push_back(N.getOperand(0));
5443 break;
5444 case X86ISD::VSHLDQ:
5445 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5446 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5447 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5448 DecodePSLLDQMask(NumElems, ImmN, Mask);
5449 IsUnary = true;
5450 break;
5451 case X86ISD::VSRLDQ:
5452 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5453 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5454 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5455 DecodePSRLDQMask(NumElems, ImmN, Mask);
5456 IsUnary = true;
5457 break;
5458 case X86ISD::PSHUFD:
5459 case X86ISD::VPERMILPI:
5460 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5461 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5462 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
5463 IsUnary = true;
5464 break;
5465 case X86ISD::PSHUFHW:
5466 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5467 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5468 DecodePSHUFHWMask(NumElems, ImmN, Mask);
5469 IsUnary = true;
5470 break;
5471 case X86ISD::PSHUFLW:
5472 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5473 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5474 DecodePSHUFLWMask(NumElems, ImmN, Mask);
5475 IsUnary = true;
5476 break;
5477 case X86ISD::VZEXT_MOVL:
5478 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5479 DecodeZeroMoveLowMask(NumElems, Mask);
5480 IsUnary = true;
5481 break;
5482 case X86ISD::VBROADCAST:
5483 // We only decode broadcasts of same-sized vectors, peeking through to
5484 // extracted subvectors is likely to cause hasOneUse issues with
5485 // SimplifyDemandedBits etc.
5486 if (N.getOperand(0).getValueType() == VT) {
5487 DecodeVectorBroadcast(NumElems, Mask);
5488 IsUnary = true;
5489 break;
5491 return false;
5492 case X86ISD::VPERMILPV: {
5493 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5494 IsUnary = true;
5495 SDValue MaskNode = N.getOperand(1);
5496 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5497 RawUndefs)) {
5498 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
5499 break;
5501 return false;
5503 case X86ISD::PSHUFB: {
5504 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5505 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5506 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5507 IsUnary = true;
5508 SDValue MaskNode = N.getOperand(1);
5509 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
5510 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
5511 break;
5513 return false;
5515 case X86ISD::VPERMI:
5516 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5517 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5518 DecodeVPERMMask(NumElems, ImmN, Mask);
5519 IsUnary = true;
5520 break;
5521 case X86ISD::MOVSS:
5522 case X86ISD::MOVSD:
5523 case X86ISD::MOVSH:
5524 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5525 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5526 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
5527 break;
5528 case X86ISD::VPERM2X128:
5529 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5530 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5531 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5532 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
5533 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5534 break;
5535 case X86ISD::SHUF128:
5536 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5537 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5538 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5539 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
5540 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5541 break;
5542 case X86ISD::MOVSLDUP:
5543 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5544 DecodeMOVSLDUPMask(NumElems, Mask);
5545 IsUnary = true;
5546 break;
5547 case X86ISD::MOVSHDUP:
5548 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5549 DecodeMOVSHDUPMask(NumElems, Mask);
5550 IsUnary = true;
5551 break;
5552 case X86ISD::MOVDDUP:
5553 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5554 DecodeMOVDDUPMask(NumElems, Mask);
5555 IsUnary = true;
5556 break;
5557 case X86ISD::VPERMIL2: {
5558 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5559 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5560 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5561 SDValue MaskNode = N.getOperand(2);
5562 SDValue CtrlNode = N.getOperand(3);
5563 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
5564 unsigned CtrlImm = CtrlOp->getZExtValue();
5565 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5566 RawUndefs)) {
5567 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
5568 Mask);
5569 break;
5572 return false;
5574 case X86ISD::VPPERM: {
5575 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5576 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5577 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5578 SDValue MaskNode = N.getOperand(2);
5579 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
5580 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
5581 break;
5583 return false;
5585 case X86ISD::VPERMV: {
5586 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5587 IsUnary = true;
5588 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
5589 Ops.push_back(N.getOperand(1));
5590 SDValue MaskNode = N.getOperand(0);
5591 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5592 RawUndefs)) {
5593 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
5594 break;
5596 return false;
5598 case X86ISD::VPERMV3: {
5599 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5600 assert(N.getOperand(2).getValueType() == VT && "Unexpected value type");
5601 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(2);
5602 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
5603 Ops.push_back(N.getOperand(0));
5604 Ops.push_back(N.getOperand(2));
5605 SDValue MaskNode = N.getOperand(1);
5606 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5607 RawUndefs)) {
5608 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
5609 break;
5611 return false;
5613 default:
5614 llvm_unreachable("unknown target shuffle node");
5617 // Empty mask indicates the decode failed.
5618 if (Mask.empty())
5619 return false;
5621 // Check if we're getting a shuffle mask with zero'd elements.
5622 if (!AllowSentinelZero && isAnyZero(Mask))
5623 return false;
5625 // If we have a fake unary shuffle, the shuffle mask is spread across two
5626 // inputs that are actually the same node. Re-map the mask to always point
5627 // into the first input.
5628 if (IsFakeUnary)
5629 for (int &M : Mask)
5630 if (M >= (int)Mask.size())
5631 M -= Mask.size();
5633 // If we didn't already add operands in the opcode-specific code, default to
5634 // adding 1 or 2 operands starting at 0.
5635 if (Ops.empty()) {
5636 Ops.push_back(N.getOperand(0));
5637 if (!IsUnary || IsFakeUnary)
5638 Ops.push_back(N.getOperand(1));
5641 return true;
5644 // Wrapper for getTargetShuffleMask with InUnary;
5645 static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
5646 SmallVectorImpl<SDValue> &Ops,
5647 SmallVectorImpl<int> &Mask) {
5648 bool IsUnary;
5649 return getTargetShuffleMask(N, AllowSentinelZero, Ops, Mask, IsUnary);
5652 /// Compute whether each element of a shuffle is zeroable.
5654 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
5655 /// Either it is an undef element in the shuffle mask, the element of the input
5656 /// referenced is undef, or the element of the input referenced is known to be
5657 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
5658 /// as many lanes with this technique as possible to simplify the remaining
5659 /// shuffle.
5660 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
5661 SDValue V1, SDValue V2,
5662 APInt &KnownUndef, APInt &KnownZero) {
5663 int Size = Mask.size();
5664 KnownUndef = KnownZero = APInt::getZero(Size);
5666 V1 = peekThroughBitcasts(V1);
5667 V2 = peekThroughBitcasts(V2);
5669 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
5670 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
5672 int VectorSizeInBits = V1.getValueSizeInBits();
5673 int ScalarSizeInBits = VectorSizeInBits / Size;
5674 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
5676 for (int i = 0; i < Size; ++i) {
5677 int M = Mask[i];
5678 // Handle the easy cases.
5679 if (M < 0) {
5680 KnownUndef.setBit(i);
5681 continue;
5683 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
5684 KnownZero.setBit(i);
5685 continue;
5688 // Determine shuffle input and normalize the mask.
5689 SDValue V = M < Size ? V1 : V2;
5690 M %= Size;
5692 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
5693 if (V.getOpcode() != ISD::BUILD_VECTOR)
5694 continue;
5696 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
5697 // the (larger) source element must be UNDEF/ZERO.
5698 if ((Size % V.getNumOperands()) == 0) {
5699 int Scale = Size / V->getNumOperands();
5700 SDValue Op = V.getOperand(M / Scale);
5701 if (Op.isUndef())
5702 KnownUndef.setBit(i);
5703 if (X86::isZeroNode(Op))
5704 KnownZero.setBit(i);
5705 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
5706 APInt Val = Cst->getAPIntValue();
5707 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
5708 if (Val == 0)
5709 KnownZero.setBit(i);
5710 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5711 APInt Val = Cst->getValueAPF().bitcastToAPInt();
5712 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
5713 if (Val == 0)
5714 KnownZero.setBit(i);
5716 continue;
5719 // If the BUILD_VECTOR has more elements then all the (smaller) source
5720 // elements must be UNDEF or ZERO.
5721 if ((V.getNumOperands() % Size) == 0) {
5722 int Scale = V->getNumOperands() / Size;
5723 bool AllUndef = true;
5724 bool AllZero = true;
5725 for (int j = 0; j < Scale; ++j) {
5726 SDValue Op = V.getOperand((M * Scale) + j);
5727 AllUndef &= Op.isUndef();
5728 AllZero &= X86::isZeroNode(Op);
5730 if (AllUndef)
5731 KnownUndef.setBit(i);
5732 if (AllZero)
5733 KnownZero.setBit(i);
5734 continue;
5739 /// Decode a target shuffle mask and inputs and see if any values are
5740 /// known to be undef or zero from their inputs.
5741 /// Returns true if the target shuffle mask was decoded.
5742 /// FIXME: Merge this with computeZeroableShuffleElements?
5743 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
5744 SmallVectorImpl<SDValue> &Ops,
5745 APInt &KnownUndef, APInt &KnownZero) {
5746 bool IsUnary;
5747 if (!isTargetShuffle(N.getOpcode()))
5748 return false;
5750 MVT VT = N.getSimpleValueType();
5751 if (!getTargetShuffleMask(N, true, Ops, Mask, IsUnary))
5752 return false;
5754 int Size = Mask.size();
5755 SDValue V1 = Ops[0];
5756 SDValue V2 = IsUnary ? V1 : Ops[1];
5757 KnownUndef = KnownZero = APInt::getZero(Size);
5759 V1 = peekThroughBitcasts(V1);
5760 V2 = peekThroughBitcasts(V2);
5762 assert((VT.getSizeInBits() % Size) == 0 &&
5763 "Illegal split of shuffle value type");
5764 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
5766 // Extract known constant input data.
5767 APInt UndefSrcElts[2];
5768 SmallVector<APInt, 32> SrcEltBits[2];
5769 bool IsSrcConstant[2] = {
5770 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
5771 SrcEltBits[0], /*AllowWholeUndefs*/ true,
5772 /*AllowPartialUndefs*/ false),
5773 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
5774 SrcEltBits[1], /*AllowWholeUndefs*/ true,
5775 /*AllowPartialUndefs*/ false)};
5777 for (int i = 0; i < Size; ++i) {
5778 int M = Mask[i];
5780 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
5781 if (M < 0) {
5782 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
5783 if (SM_SentinelUndef == M)
5784 KnownUndef.setBit(i);
5785 if (SM_SentinelZero == M)
5786 KnownZero.setBit(i);
5787 continue;
5790 // Determine shuffle input and normalize the mask.
5791 unsigned SrcIdx = M / Size;
5792 SDValue V = M < Size ? V1 : V2;
5793 M %= Size;
5795 // We are referencing an UNDEF input.
5796 if (V.isUndef()) {
5797 KnownUndef.setBit(i);
5798 continue;
5801 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
5802 // TODO: We currently only set UNDEF for integer types - floats use the same
5803 // registers as vectors and many of the scalar folded loads rely on the
5804 // SCALAR_TO_VECTOR pattern.
5805 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5806 (Size % V.getValueType().getVectorNumElements()) == 0) {
5807 int Scale = Size / V.getValueType().getVectorNumElements();
5808 int Idx = M / Scale;
5809 if (Idx != 0 && !VT.isFloatingPoint())
5810 KnownUndef.setBit(i);
5811 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
5812 KnownZero.setBit(i);
5813 continue;
5816 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
5817 // base vectors.
5818 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
5819 SDValue Vec = V.getOperand(0);
5820 int NumVecElts = Vec.getValueType().getVectorNumElements();
5821 if (Vec.isUndef() && Size == NumVecElts) {
5822 int Idx = V.getConstantOperandVal(2);
5823 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
5824 if (M < Idx || (Idx + NumSubElts) <= M)
5825 KnownUndef.setBit(i);
5827 continue;
5830 // Attempt to extract from the source's constant bits.
5831 if (IsSrcConstant[SrcIdx]) {
5832 if (UndefSrcElts[SrcIdx][M])
5833 KnownUndef.setBit(i);
5834 else if (SrcEltBits[SrcIdx][M] == 0)
5835 KnownZero.setBit(i);
5839 assert(VT.getVectorNumElements() == (unsigned)Size &&
5840 "Different mask size from vector size!");
5841 return true;
5844 // Replace target shuffle mask elements with known undef/zero sentinels.
5845 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
5846 const APInt &KnownUndef,
5847 const APInt &KnownZero,
5848 bool ResolveKnownZeros= true) {
5849 unsigned NumElts = Mask.size();
5850 assert(KnownUndef.getBitWidth() == NumElts &&
5851 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
5853 for (unsigned i = 0; i != NumElts; ++i) {
5854 if (KnownUndef[i])
5855 Mask[i] = SM_SentinelUndef;
5856 else if (ResolveKnownZeros && KnownZero[i])
5857 Mask[i] = SM_SentinelZero;
5861 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
5862 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
5863 APInt &KnownUndef,
5864 APInt &KnownZero) {
5865 unsigned NumElts = Mask.size();
5866 KnownUndef = KnownZero = APInt::getZero(NumElts);
5868 for (unsigned i = 0; i != NumElts; ++i) {
5869 int M = Mask[i];
5870 if (SM_SentinelUndef == M)
5871 KnownUndef.setBit(i);
5872 if (SM_SentinelZero == M)
5873 KnownZero.setBit(i);
5877 // Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
5878 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
5879 SDValue Cond, bool IsBLENDV = false) {
5880 EVT CondVT = Cond.getValueType();
5881 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
5882 unsigned NumElts = CondVT.getVectorNumElements();
5884 APInt UndefElts;
5885 SmallVector<APInt, 32> EltBits;
5886 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
5887 /*AllowWholeUndefs*/ true,
5888 /*AllowPartialUndefs*/ false))
5889 return false;
5891 Mask.resize(NumElts, SM_SentinelUndef);
5893 for (int i = 0; i != (int)NumElts; ++i) {
5894 Mask[i] = i;
5895 // Arbitrarily choose from the 2nd operand if the select condition element
5896 // is undef.
5897 // TODO: Can we do better by matching patterns such as even/odd?
5898 if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
5899 (IsBLENDV && EltBits[i].isNonNegative()))
5900 Mask[i] += NumElts;
5903 return true;
5906 // Forward declaration (for getFauxShuffleMask recursive check).
5907 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
5908 SmallVectorImpl<SDValue> &Inputs,
5909 SmallVectorImpl<int> &Mask,
5910 const SelectionDAG &DAG, unsigned Depth,
5911 bool ResolveKnownElts);
5913 // Attempt to decode ops that could be represented as a shuffle mask.
5914 // The decoded shuffle mask may contain a different number of elements to the
5915 // destination value type.
5916 // TODO: Merge into getTargetShuffleInputs()
5917 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
5918 SmallVectorImpl<int> &Mask,
5919 SmallVectorImpl<SDValue> &Ops,
5920 const SelectionDAG &DAG, unsigned Depth,
5921 bool ResolveKnownElts) {
5922 Mask.clear();
5923 Ops.clear();
5925 MVT VT = N.getSimpleValueType();
5926 unsigned NumElts = VT.getVectorNumElements();
5927 unsigned NumSizeInBits = VT.getSizeInBits();
5928 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
5929 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
5930 return false;
5931 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
5932 unsigned NumSizeInBytes = NumSizeInBits / 8;
5933 unsigned NumBytesPerElt = NumBitsPerElt / 8;
5935 unsigned Opcode = N.getOpcode();
5936 switch (Opcode) {
5937 case ISD::VECTOR_SHUFFLE: {
5938 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
5939 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
5940 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
5941 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
5942 Ops.push_back(N.getOperand(0));
5943 Ops.push_back(N.getOperand(1));
5944 return true;
5946 return false;
5948 case ISD::AND:
5949 case X86ISD::ANDNP: {
5950 // Attempt to decode as a per-byte mask.
5951 APInt UndefElts;
5952 SmallVector<APInt, 32> EltBits;
5953 SDValue N0 = N.getOperand(0);
5954 SDValue N1 = N.getOperand(1);
5955 bool IsAndN = (X86ISD::ANDNP == Opcode);
5956 uint64_t ZeroMask = IsAndN ? 255 : 0;
5957 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits,
5958 /*AllowWholeUndefs*/ false,
5959 /*AllowPartialUndefs*/ false))
5960 return false;
5961 // We can't assume an undef src element gives an undef dst - the other src
5962 // might be zero.
5963 assert(UndefElts.isZero() && "Unexpected UNDEF element in AND/ANDNP mask");
5964 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
5965 const APInt &ByteBits = EltBits[i];
5966 if (ByteBits != 0 && ByteBits != 255)
5967 return false;
5968 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
5970 Ops.push_back(IsAndN ? N1 : N0);
5971 return true;
5973 case ISD::OR: {
5974 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
5975 // is a valid shuffle index.
5976 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
5977 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
5978 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
5979 return false;
5981 SmallVector<int, 64> SrcMask0, SrcMask1;
5982 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
5983 APInt Demand0 = APInt::getAllOnes(N0.getValueType().getVectorNumElements());
5984 APInt Demand1 = APInt::getAllOnes(N1.getValueType().getVectorNumElements());
5985 if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
5986 Depth + 1, true) ||
5987 !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
5988 Depth + 1, true))
5989 return false;
5991 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
5992 SmallVector<int, 64> Mask0, Mask1;
5993 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
5994 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
5995 for (int i = 0; i != (int)MaskSize; ++i) {
5996 // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
5997 // loops converting between OR and BLEND shuffles due to
5998 // canWidenShuffleElements merging away undef elements, meaning we
5999 // fail to recognise the OR as the undef element isn't known zero.
6000 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6001 Mask.push_back(SM_SentinelZero);
6002 else if (Mask1[i] == SM_SentinelZero)
6003 Mask.push_back(i);
6004 else if (Mask0[i] == SM_SentinelZero)
6005 Mask.push_back(i + MaskSize);
6006 else
6007 return false;
6009 Ops.push_back(N0);
6010 Ops.push_back(N1);
6011 return true;
6013 case ISD::INSERT_SUBVECTOR: {
6014 SDValue Src = N.getOperand(0);
6015 SDValue Sub = N.getOperand(1);
6016 EVT SubVT = Sub.getValueType();
6017 unsigned NumSubElts = SubVT.getVectorNumElements();
6018 if (!N->isOnlyUserOf(Sub.getNode()))
6019 return false;
6020 SDValue SubBC = peekThroughBitcasts(Sub);
6021 uint64_t InsertIdx = N.getConstantOperandVal(2);
6022 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
6023 if (SubBC.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6024 SubBC.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6025 uint64_t ExtractIdx = SubBC.getConstantOperandVal(1);
6026 SDValue SubBCSrc = SubBC.getOperand(0);
6027 unsigned NumSubSrcBCElts = SubBCSrc.getValueType().getVectorNumElements();
6028 unsigned MaxElts = std::max(NumElts, NumSubSrcBCElts);
6029 assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcBCElts) == 0 &&
6030 "Subvector valuetype mismatch");
6031 InsertIdx *= (MaxElts / NumElts);
6032 ExtractIdx *= (MaxElts / NumSubSrcBCElts);
6033 NumSubElts *= (MaxElts / NumElts);
6034 bool SrcIsUndef = Src.isUndef();
6035 for (int i = 0; i != (int)MaxElts; ++i)
6036 Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
6037 for (int i = 0; i != (int)NumSubElts; ++i)
6038 Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
6039 if (!SrcIsUndef)
6040 Ops.push_back(Src);
6041 Ops.push_back(SubBCSrc);
6042 return true;
6044 // Handle CONCAT(SUB0, SUB1).
6045 // Limit this to vXi64 512-bit vector cases to make the most of AVX512
6046 // cross lane shuffles.
6047 if (Depth > 0 && InsertIdx == NumSubElts && NumElts == (2 * NumSubElts) &&
6048 NumBitsPerElt == 64 && NumSizeInBits == 512 &&
6049 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6050 Src.getOperand(0).isUndef() &&
6051 Src.getOperand(1).getValueType() == SubVT &&
6052 Src.getConstantOperandVal(2) == 0) {
6053 for (int i = 0; i != (int)NumSubElts; ++i)
6054 Mask.push_back(i);
6055 for (int i = 0; i != (int)NumSubElts; ++i)
6056 Mask.push_back(i + NumElts);
6057 Ops.push_back(Src.getOperand(1));
6058 Ops.push_back(Sub);
6059 return true;
6061 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6062 SmallVector<int, 64> SubMask;
6063 SmallVector<SDValue, 2> SubInputs;
6064 SDValue SubSrc = peekThroughOneUseBitcasts(Sub);
6065 EVT SubSrcVT = SubSrc.getValueType();
6066 if (!SubSrcVT.isVector())
6067 return false;
6069 APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
6070 if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
6071 Depth + 1, ResolveKnownElts))
6072 return false;
6074 // Subvector shuffle inputs must not be larger than the subvector.
6075 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
6076 return SubVT.getFixedSizeInBits() <
6077 SubInput.getValueSizeInBits().getFixedValue();
6079 return false;
6081 if (SubMask.size() != NumSubElts) {
6082 assert(((SubMask.size() % NumSubElts) == 0 ||
6083 (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
6084 if ((NumSubElts % SubMask.size()) == 0) {
6085 int Scale = NumSubElts / SubMask.size();
6086 SmallVector<int,64> ScaledSubMask;
6087 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
6088 SubMask = ScaledSubMask;
6089 } else {
6090 int Scale = SubMask.size() / NumSubElts;
6091 NumSubElts = SubMask.size();
6092 NumElts *= Scale;
6093 InsertIdx *= Scale;
6096 Ops.push_back(Src);
6097 Ops.append(SubInputs.begin(), SubInputs.end());
6098 if (ISD::isBuildVectorAllZeros(Src.getNode()))
6099 Mask.append(NumElts, SM_SentinelZero);
6100 else
6101 for (int i = 0; i != (int)NumElts; ++i)
6102 Mask.push_back(i);
6103 for (int i = 0; i != (int)NumSubElts; ++i) {
6104 int M = SubMask[i];
6105 if (0 <= M) {
6106 int InputIdx = M / NumSubElts;
6107 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6109 Mask[i + InsertIdx] = M;
6111 return true;
6113 case X86ISD::PINSRB:
6114 case X86ISD::PINSRW:
6115 case ISD::SCALAR_TO_VECTOR:
6116 case ISD::INSERT_VECTOR_ELT: {
6117 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
6118 // vector, for matching src/dst vector types.
6119 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
6121 unsigned DstIdx = 0;
6122 if (Opcode != ISD::SCALAR_TO_VECTOR) {
6123 // Check we have an in-range constant insertion index.
6124 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6125 N.getConstantOperandAPInt(2).uge(NumElts))
6126 return false;
6127 DstIdx = N.getConstantOperandVal(2);
6129 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
6130 if (X86::isZeroNode(Scl)) {
6131 Ops.push_back(N.getOperand(0));
6132 for (unsigned i = 0; i != NumElts; ++i)
6133 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
6134 return true;
6138 // Peek through trunc/aext/zext/bitcast.
6139 // TODO: aext shouldn't require SM_SentinelZero padding.
6140 // TODO: handle shift of scalars.
6141 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
6142 while (Scl.getOpcode() == ISD::TRUNCATE ||
6143 Scl.getOpcode() == ISD::ANY_EXTEND ||
6144 Scl.getOpcode() == ISD::ZERO_EXTEND ||
6145 (Scl.getOpcode() == ISD::BITCAST &&
6146 Scl.getScalarValueSizeInBits() ==
6147 Scl.getOperand(0).getScalarValueSizeInBits())) {
6148 Scl = Scl.getOperand(0);
6149 MinBitsPerElt =
6150 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
6152 if ((MinBitsPerElt % 8) != 0)
6153 return false;
6155 // Attempt to find the source vector the scalar was extracted from.
6156 SDValue SrcExtract;
6157 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
6158 Scl.getOpcode() == X86ISD::PEXTRW ||
6159 Scl.getOpcode() == X86ISD::PEXTRB) &&
6160 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6161 SrcExtract = Scl;
6163 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6164 return false;
6166 SDValue SrcVec = SrcExtract.getOperand(0);
6167 EVT SrcVT = SrcVec.getValueType();
6168 if (!SrcVT.getScalarType().isByteSized())
6169 return false;
6170 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6171 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
6172 unsigned DstByte = DstIdx * NumBytesPerElt;
6173 MinBitsPerElt =
6174 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
6176 // Create 'identity' byte level shuffle mask and then add inserted bytes.
6177 if (Opcode == ISD::SCALAR_TO_VECTOR) {
6178 Ops.push_back(SrcVec);
6179 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6180 } else {
6181 Ops.push_back(SrcVec);
6182 Ops.push_back(N.getOperand(0));
6183 for (int i = 0; i != (int)NumSizeInBytes; ++i)
6184 Mask.push_back(NumSizeInBytes + i);
6187 unsigned MinBytesPerElts = MinBitsPerElt / 8;
6188 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
6189 for (unsigned i = 0; i != MinBytesPerElts; ++i)
6190 Mask[DstByte + i] = SrcByte + i;
6191 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
6192 Mask[DstByte + i] = SM_SentinelZero;
6193 return true;
6195 case X86ISD::PACKSS:
6196 case X86ISD::PACKUS: {
6197 SDValue N0 = N.getOperand(0);
6198 SDValue N1 = N.getOperand(1);
6199 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6200 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6201 "Unexpected input value type");
6203 APInt EltsLHS, EltsRHS;
6204 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
6206 // If we know input saturation won't happen (or we don't care for particular
6207 // lanes), we can treat this as a truncation shuffle.
6208 bool Offset0 = false, Offset1 = false;
6209 if (Opcode == X86ISD::PACKSS) {
6210 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6211 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
6212 (!(N1.isUndef() || EltsRHS.isZero()) &&
6213 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
6214 return false;
6215 // We can't easily fold ASHR into a shuffle, but if it was feeding a
6216 // PACKSS then it was likely being used for sign-extension for a
6217 // truncation, so just peek through and adjust the mask accordingly.
6218 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
6219 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
6220 Offset0 = true;
6221 N0 = N0.getOperand(0);
6223 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
6224 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
6225 Offset1 = true;
6226 N1 = N1.getOperand(0);
6228 } else {
6229 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6230 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6231 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
6232 (!(N1.isUndef() || EltsRHS.isZero()) &&
6233 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
6234 return false;
6237 bool IsUnary = (N0 == N1);
6239 Ops.push_back(N0);
6240 if (!IsUnary)
6241 Ops.push_back(N1);
6243 createPackShuffleMask(VT, Mask, IsUnary);
6245 if (Offset0 || Offset1) {
6246 for (int &M : Mask)
6247 if ((Offset0 && isInRange(M, 0, NumElts)) ||
6248 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
6249 ++M;
6251 return true;
6253 case ISD::VSELECT:
6254 case X86ISD::BLENDV: {
6255 SDValue Cond = N.getOperand(0);
6256 if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
6257 Ops.push_back(N.getOperand(1));
6258 Ops.push_back(N.getOperand(2));
6259 return true;
6261 return false;
6263 case X86ISD::VTRUNC: {
6264 SDValue Src = N.getOperand(0);
6265 EVT SrcVT = Src.getValueType();
6266 // Truncated source must be a simple vector.
6267 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6268 (SrcVT.getScalarSizeInBits() % 8) != 0)
6269 return false;
6270 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6271 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6272 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
6273 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
6274 for (unsigned i = 0; i != NumSrcElts; ++i)
6275 Mask.push_back(i * Scale);
6276 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
6277 Ops.push_back(Src);
6278 return true;
6280 case ISD::SHL:
6281 case ISD::SRL: {
6282 // We can only decode 'whole byte' bit shifts as shuffles.
6283 std::optional<uint64_t> Amt = DAG.getValidShiftAmount(N, DemandedElts);
6284 if (!Amt || (*Amt % 8) != 0)
6285 return false;
6287 uint64_t ByteShift = *Amt / 8;
6288 Ops.push_back(N.getOperand(0));
6290 // Clear mask to all zeros and insert the shifted byte indices.
6291 Mask.append(NumSizeInBytes, SM_SentinelZero);
6293 if (ISD::SHL == Opcode) {
6294 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6295 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6296 Mask[i + j] = i + j - ByteShift;
6297 } else {
6298 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6299 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6300 Mask[i + j - ByteShift] = i + j;
6302 return true;
6304 case X86ISD::VSHLI:
6305 case X86ISD::VSRLI: {
6306 uint64_t ShiftVal = N.getConstantOperandVal(1);
6307 // Out of range bit shifts are guaranteed to be zero.
6308 if (NumBitsPerElt <= ShiftVal) {
6309 Mask.append(NumElts, SM_SentinelZero);
6310 return true;
6313 // We can only decode 'whole byte' bit shifts as shuffles.
6314 if ((ShiftVal % 8) != 0)
6315 break;
6317 uint64_t ByteShift = ShiftVal / 8;
6318 Ops.push_back(N.getOperand(0));
6320 // Clear mask to all zeros and insert the shifted byte indices.
6321 Mask.append(NumSizeInBytes, SM_SentinelZero);
6323 if (X86ISD::VSHLI == Opcode) {
6324 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6325 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6326 Mask[i + j] = i + j - ByteShift;
6327 } else {
6328 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6329 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6330 Mask[i + j - ByteShift] = i + j;
6332 return true;
6334 case X86ISD::VROTLI:
6335 case X86ISD::VROTRI: {
6336 // We can only decode 'whole byte' bit rotates as shuffles.
6337 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
6338 if ((RotateVal % 8) != 0)
6339 return false;
6340 Ops.push_back(N.getOperand(0));
6341 int Offset = RotateVal / 8;
6342 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
6343 for (int i = 0; i != (int)NumElts; ++i) {
6344 int BaseIdx = i * NumBytesPerElt;
6345 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
6346 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
6349 return true;
6351 case X86ISD::VBROADCAST: {
6352 SDValue Src = N.getOperand(0);
6353 if (!Src.getSimpleValueType().isVector()) {
6354 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6355 !isNullConstant(Src.getOperand(1)) ||
6356 Src.getOperand(0).getValueType().getScalarType() !=
6357 VT.getScalarType())
6358 return false;
6359 Src = Src.getOperand(0);
6361 Ops.push_back(Src);
6362 Mask.append(NumElts, 0);
6363 return true;
6365 case ISD::SIGN_EXTEND_VECTOR_INREG: {
6366 SDValue Src = N.getOperand(0);
6367 EVT SrcVT = Src.getValueType();
6368 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6370 // Extended source must be a simple vector.
6371 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6372 (NumBitsPerSrcElt % 8) != 0)
6373 return false;
6375 // We can only handle all-signbits extensions.
6376 APInt DemandedSrcElts =
6377 DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
6378 if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
6379 return false;
6381 assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
6382 unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
6383 for (unsigned I = 0; I != NumElts; ++I)
6384 Mask.append(Scale, I);
6385 Ops.push_back(Src);
6386 return true;
6388 case ISD::ZERO_EXTEND:
6389 case ISD::ANY_EXTEND:
6390 case ISD::ZERO_EXTEND_VECTOR_INREG:
6391 case ISD::ANY_EXTEND_VECTOR_INREG: {
6392 SDValue Src = N.getOperand(0);
6393 EVT SrcVT = Src.getValueType();
6395 // Extended source must be a simple vector.
6396 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6397 (SrcVT.getScalarSizeInBits() % 8) != 0)
6398 return false;
6400 bool IsAnyExtend =
6401 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
6402 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
6403 IsAnyExtend, Mask);
6404 Ops.push_back(Src);
6405 return true;
6409 return false;
6412 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
6413 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
6414 SmallVectorImpl<int> &Mask) {
6415 int MaskWidth = Mask.size();
6416 SmallVector<SDValue, 16> UsedInputs;
6417 for (int i = 0, e = Inputs.size(); i < e; ++i) {
6418 int lo = UsedInputs.size() * MaskWidth;
6419 int hi = lo + MaskWidth;
6421 // Strip UNDEF input usage.
6422 if (Inputs[i].isUndef())
6423 for (int &M : Mask)
6424 if ((lo <= M) && (M < hi))
6425 M = SM_SentinelUndef;
6427 // Check for unused inputs.
6428 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
6429 for (int &M : Mask)
6430 if (lo <= M)
6431 M -= MaskWidth;
6432 continue;
6435 // Check for repeated inputs.
6436 bool IsRepeat = false;
6437 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
6438 if (UsedInputs[j] != Inputs[i])
6439 continue;
6440 for (int &M : Mask)
6441 if (lo <= M)
6442 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
6443 IsRepeat = true;
6444 break;
6446 if (IsRepeat)
6447 continue;
6449 UsedInputs.push_back(Inputs[i]);
6451 Inputs = UsedInputs;
6454 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
6455 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
6456 /// Returns true if the target shuffle mask was decoded.
6457 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6458 SmallVectorImpl<SDValue> &Inputs,
6459 SmallVectorImpl<int> &Mask,
6460 APInt &KnownUndef, APInt &KnownZero,
6461 const SelectionDAG &DAG, unsigned Depth,
6462 bool ResolveKnownElts) {
6463 if (Depth >= SelectionDAG::MaxRecursionDepth)
6464 return false; // Limit search depth.
6466 EVT VT = Op.getValueType();
6467 if (!VT.isSimple() || !VT.isVector())
6468 return false;
6470 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
6471 if (ResolveKnownElts)
6472 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
6473 return true;
6475 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
6476 ResolveKnownElts)) {
6477 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
6478 return true;
6480 return false;
6483 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6484 SmallVectorImpl<SDValue> &Inputs,
6485 SmallVectorImpl<int> &Mask,
6486 const SelectionDAG &DAG, unsigned Depth,
6487 bool ResolveKnownElts) {
6488 APInt KnownUndef, KnownZero;
6489 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
6490 KnownZero, DAG, Depth, ResolveKnownElts);
6493 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
6494 SmallVectorImpl<int> &Mask,
6495 const SelectionDAG &DAG, unsigned Depth = 0,
6496 bool ResolveKnownElts = true) {
6497 EVT VT = Op.getValueType();
6498 if (!VT.isSimple() || !VT.isVector())
6499 return false;
6501 unsigned NumElts = Op.getValueType().getVectorNumElements();
6502 APInt DemandedElts = APInt::getAllOnes(NumElts);
6503 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
6504 ResolveKnownElts);
6507 // Attempt to create a scalar/subvector broadcast from the base MemSDNode.
6508 static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
6509 EVT MemVT, MemSDNode *Mem, unsigned Offset,
6510 SelectionDAG &DAG) {
6511 assert((Opcode == X86ISD::VBROADCAST_LOAD ||
6512 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
6513 "Unknown broadcast load type");
6515 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
6516 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
6517 return SDValue();
6519 SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
6520 TypeSize::getFixed(Offset), DL);
6521 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
6522 SDValue Ops[] = {Mem->getChain(), Ptr};
6523 SDValue BcstLd = DAG.getMemIntrinsicNode(
6524 Opcode, DL, Tys, Ops, MemVT,
6525 DAG.getMachineFunction().getMachineMemOperand(
6526 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
6527 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
6528 return BcstLd;
6531 /// Returns the scalar element that will make up the i'th
6532 /// element of the result of the vector shuffle.
6533 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
6534 SelectionDAG &DAG, unsigned Depth) {
6535 if (Depth >= SelectionDAG::MaxRecursionDepth)
6536 return SDValue(); // Limit search depth.
6538 EVT VT = Op.getValueType();
6539 unsigned Opcode = Op.getOpcode();
6540 unsigned NumElems = VT.getVectorNumElements();
6542 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
6543 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
6544 int Elt = SV->getMaskElt(Index);
6546 if (Elt < 0)
6547 return DAG.getUNDEF(VT.getVectorElementType());
6549 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
6550 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
6553 // Recurse into target specific vector shuffles to find scalars.
6554 if (isTargetShuffle(Opcode)) {
6555 MVT ShufVT = VT.getSimpleVT();
6556 MVT ShufSVT = ShufVT.getVectorElementType();
6557 int NumElems = (int)ShufVT.getVectorNumElements();
6558 SmallVector<int, 16> ShuffleMask;
6559 SmallVector<SDValue, 16> ShuffleOps;
6560 if (!getTargetShuffleMask(Op, true, ShuffleOps, ShuffleMask))
6561 return SDValue();
6563 int Elt = ShuffleMask[Index];
6564 if (Elt == SM_SentinelZero)
6565 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
6566 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
6567 if (Elt == SM_SentinelUndef)
6568 return DAG.getUNDEF(ShufSVT);
6570 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
6571 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
6572 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
6575 // Recurse into insert_subvector base/sub vector to find scalars.
6576 if (Opcode == ISD::INSERT_SUBVECTOR) {
6577 SDValue Vec = Op.getOperand(0);
6578 SDValue Sub = Op.getOperand(1);
6579 uint64_t SubIdx = Op.getConstantOperandVal(2);
6580 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
6582 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
6583 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
6584 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
6587 // Recurse into concat_vectors sub vector to find scalars.
6588 if (Opcode == ISD::CONCAT_VECTORS) {
6589 EVT SubVT = Op.getOperand(0).getValueType();
6590 unsigned NumSubElts = SubVT.getVectorNumElements();
6591 uint64_t SubIdx = Index / NumSubElts;
6592 uint64_t SubElt = Index % NumSubElts;
6593 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
6596 // Recurse into extract_subvector src vector to find scalars.
6597 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
6598 SDValue Src = Op.getOperand(0);
6599 uint64_t SrcIdx = Op.getConstantOperandVal(1);
6600 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
6603 // We only peek through bitcasts of the same vector width.
6604 if (Opcode == ISD::BITCAST) {
6605 SDValue Src = Op.getOperand(0);
6606 EVT SrcVT = Src.getValueType();
6607 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
6608 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
6609 return SDValue();
6612 // Actual nodes that may contain scalar elements
6614 // For insert_vector_elt - either return the index matching scalar or recurse
6615 // into the base vector.
6616 if (Opcode == ISD::INSERT_VECTOR_ELT &&
6617 isa<ConstantSDNode>(Op.getOperand(2))) {
6618 if (Op.getConstantOperandAPInt(2) == Index)
6619 return Op.getOperand(1);
6620 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
6623 if (Opcode == ISD::SCALAR_TO_VECTOR)
6624 return (Index == 0) ? Op.getOperand(0)
6625 : DAG.getUNDEF(VT.getVectorElementType());
6627 if (Opcode == ISD::BUILD_VECTOR)
6628 return Op.getOperand(Index);
6630 return SDValue();
6633 // Use PINSRB/PINSRW/PINSRD to create a build vector.
6634 static SDValue LowerBuildVectorAsInsert(SDValue Op, const SDLoc &DL,
6635 const APInt &NonZeroMask,
6636 unsigned NumNonZero, unsigned NumZero,
6637 SelectionDAG &DAG,
6638 const X86Subtarget &Subtarget) {
6639 MVT VT = Op.getSimpleValueType();
6640 unsigned NumElts = VT.getVectorNumElements();
6641 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
6642 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
6643 "Illegal vector insertion");
6645 SDValue V;
6646 bool First = true;
6648 for (unsigned i = 0; i < NumElts; ++i) {
6649 bool IsNonZero = NonZeroMask[i];
6650 if (!IsNonZero)
6651 continue;
6653 // If the build vector contains zeros or our first insertion is not the
6654 // first index then insert into zero vector to break any register
6655 // dependency else use SCALAR_TO_VECTOR.
6656 if (First) {
6657 First = false;
6658 if (NumZero || 0 != i)
6659 V = getZeroVector(VT, Subtarget, DAG, DL);
6660 else {
6661 assert(0 == i && "Expected insertion into zero-index");
6662 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
6663 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
6664 V = DAG.getBitcast(VT, V);
6665 continue;
6668 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, V, Op.getOperand(i),
6669 DAG.getIntPtrConstant(i, DL));
6672 return V;
6675 /// Custom lower build_vector of v16i8.
6676 static SDValue LowerBuildVectorv16i8(SDValue Op, const SDLoc &DL,
6677 const APInt &NonZeroMask,
6678 unsigned NumNonZero, unsigned NumZero,
6679 SelectionDAG &DAG,
6680 const X86Subtarget &Subtarget) {
6681 if (NumNonZero > 8 && !Subtarget.hasSSE41())
6682 return SDValue();
6684 // SSE4.1 - use PINSRB to insert each byte directly.
6685 if (Subtarget.hasSSE41())
6686 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero,
6687 DAG, Subtarget);
6689 SDValue V;
6691 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
6692 // If both the lowest 16-bits are non-zero, then convert to MOVD.
6693 if (!NonZeroMask.extractBits(2, 0).isZero() &&
6694 !NonZeroMask.extractBits(2, 2).isZero()) {
6695 for (unsigned I = 0; I != 4; ++I) {
6696 if (!NonZeroMask[I])
6697 continue;
6698 SDValue Elt = DAG.getZExtOrTrunc(Op.getOperand(I), DL, MVT::i32);
6699 if (I != 0)
6700 Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt,
6701 DAG.getConstant(I * 8, DL, MVT::i8));
6702 V = V ? DAG.getNode(ISD::OR, DL, MVT::i32, V, Elt) : Elt;
6704 assert(V && "Failed to fold v16i8 vector to zero");
6705 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
6706 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32, V);
6707 V = DAG.getBitcast(MVT::v8i16, V);
6709 for (unsigned i = V ? 4 : 0; i < 16; i += 2) {
6710 bool ThisIsNonZero = NonZeroMask[i];
6711 bool NextIsNonZero = NonZeroMask[i + 1];
6712 if (!ThisIsNonZero && !NextIsNonZero)
6713 continue;
6715 SDValue Elt;
6716 if (ThisIsNonZero) {
6717 if (NumZero || NextIsNonZero)
6718 Elt = DAG.getZExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
6719 else
6720 Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
6723 if (NextIsNonZero) {
6724 SDValue NextElt = Op.getOperand(i + 1);
6725 if (i == 0 && NumZero)
6726 NextElt = DAG.getZExtOrTrunc(NextElt, DL, MVT::i32);
6727 else
6728 NextElt = DAG.getAnyExtOrTrunc(NextElt, DL, MVT::i32);
6729 NextElt = DAG.getNode(ISD::SHL, DL, MVT::i32, NextElt,
6730 DAG.getConstant(8, DL, MVT::i8));
6731 if (ThisIsNonZero)
6732 Elt = DAG.getNode(ISD::OR, DL, MVT::i32, NextElt, Elt);
6733 else
6734 Elt = NextElt;
6737 // If our first insertion is not the first index or zeros are needed, then
6738 // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
6739 // elements undefined).
6740 if (!V) {
6741 if (i != 0 || NumZero)
6742 V = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
6743 else {
6744 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, Elt);
6745 V = DAG.getBitcast(MVT::v8i16, V);
6746 continue;
6749 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
6750 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16, V, Elt,
6751 DAG.getIntPtrConstant(i / 2, DL));
6754 return DAG.getBitcast(MVT::v16i8, V);
6757 /// Custom lower build_vector of v8i16.
6758 static SDValue LowerBuildVectorv8i16(SDValue Op, const SDLoc &DL,
6759 const APInt &NonZeroMask,
6760 unsigned NumNonZero, unsigned NumZero,
6761 SelectionDAG &DAG,
6762 const X86Subtarget &Subtarget) {
6763 if (NumNonZero > 4 && !Subtarget.hasSSE41())
6764 return SDValue();
6766 // Use PINSRW to insert each byte directly.
6767 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero, DAG,
6768 Subtarget);
6771 /// Custom lower build_vector of v4i32 or v4f32.
6772 static SDValue LowerBuildVectorv4x32(SDValue Op, const SDLoc &DL,
6773 SelectionDAG &DAG,
6774 const X86Subtarget &Subtarget) {
6775 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
6776 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
6777 // Because we're creating a less complicated build vector here, we may enable
6778 // further folding of the MOVDDUP via shuffle transforms.
6779 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
6780 Op.getOperand(0) == Op.getOperand(2) &&
6781 Op.getOperand(1) == Op.getOperand(3) &&
6782 Op.getOperand(0) != Op.getOperand(1)) {
6783 MVT VT = Op.getSimpleValueType();
6784 MVT EltVT = VT.getVectorElementType();
6785 // Create a new build vector with the first 2 elements followed by undef
6786 // padding, bitcast to v2f64, duplicate, and bitcast back.
6787 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
6788 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
6789 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
6790 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
6791 return DAG.getBitcast(VT, Dup);
6794 // Find all zeroable elements.
6795 std::bitset<4> Zeroable, Undefs;
6796 for (int i = 0; i < 4; ++i) {
6797 SDValue Elt = Op.getOperand(i);
6798 Undefs[i] = Elt.isUndef();
6799 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
6801 assert(Zeroable.size() - Zeroable.count() > 1 &&
6802 "We expect at least two non-zero elements!");
6804 // We only know how to deal with build_vector nodes where elements are either
6805 // zeroable or extract_vector_elt with constant index.
6806 SDValue FirstNonZero;
6807 unsigned FirstNonZeroIdx;
6808 for (unsigned i = 0; i < 4; ++i) {
6809 if (Zeroable[i])
6810 continue;
6811 SDValue Elt = Op.getOperand(i);
6812 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6813 !isa<ConstantSDNode>(Elt.getOperand(1)))
6814 return SDValue();
6815 // Make sure that this node is extracting from a 128-bit vector.
6816 MVT VT = Elt.getOperand(0).getSimpleValueType();
6817 if (!VT.is128BitVector())
6818 return SDValue();
6819 if (!FirstNonZero.getNode()) {
6820 FirstNonZero = Elt;
6821 FirstNonZeroIdx = i;
6825 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
6826 SDValue V1 = FirstNonZero.getOperand(0);
6827 MVT VT = V1.getSimpleValueType();
6829 // See if this build_vector can be lowered as a blend with zero.
6830 SDValue Elt;
6831 unsigned EltMaskIdx, EltIdx;
6832 int Mask[4];
6833 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
6834 if (Zeroable[EltIdx]) {
6835 // The zero vector will be on the right hand side.
6836 Mask[EltIdx] = EltIdx+4;
6837 continue;
6840 Elt = Op->getOperand(EltIdx);
6841 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
6842 EltMaskIdx = Elt.getConstantOperandVal(1);
6843 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
6844 break;
6845 Mask[EltIdx] = EltIdx;
6848 if (EltIdx == 4) {
6849 // Let the shuffle legalizer deal with blend operations.
6850 SDValue VZeroOrUndef = (Zeroable == Undefs)
6851 ? DAG.getUNDEF(VT)
6852 : getZeroVector(VT, Subtarget, DAG, DL);
6853 if (V1.getSimpleValueType() != VT)
6854 V1 = DAG.getBitcast(VT, V1);
6855 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
6858 // See if we can lower this build_vector to a INSERTPS.
6859 if (!Subtarget.hasSSE41())
6860 return SDValue();
6862 SDValue V2 = Elt.getOperand(0);
6863 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
6864 V1 = SDValue();
6866 bool CanFold = true;
6867 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
6868 if (Zeroable[i])
6869 continue;
6871 SDValue Current = Op->getOperand(i);
6872 SDValue SrcVector = Current->getOperand(0);
6873 if (!V1.getNode())
6874 V1 = SrcVector;
6875 CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
6878 if (!CanFold)
6879 return SDValue();
6881 assert(V1.getNode() && "Expected at least two non-zero elements!");
6882 if (V1.getSimpleValueType() != MVT::v4f32)
6883 V1 = DAG.getBitcast(MVT::v4f32, V1);
6884 if (V2.getSimpleValueType() != MVT::v4f32)
6885 V2 = DAG.getBitcast(MVT::v4f32, V2);
6887 // Ok, we can emit an INSERTPS instruction.
6888 unsigned ZMask = Zeroable.to_ulong();
6890 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
6891 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
6892 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
6893 DAG.getIntPtrConstant(InsertPSMask, DL, true));
6894 return DAG.getBitcast(VT, Result);
6897 /// Return a vector logical shift node.
6898 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
6899 SelectionDAG &DAG, const TargetLowering &TLI,
6900 const SDLoc &dl) {
6901 assert(VT.is128BitVector() && "Unknown type for VShift");
6902 MVT ShVT = MVT::v16i8;
6903 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
6904 SrcOp = DAG.getBitcast(ShVT, SrcOp);
6905 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
6906 SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
6907 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
6910 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
6911 SelectionDAG &DAG) {
6913 // Check if the scalar load can be widened into a vector load. And if
6914 // the address is "base + cst" see if the cst can be "absorbed" into
6915 // the shuffle mask.
6916 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
6917 SDValue Ptr = LD->getBasePtr();
6918 if (!ISD::isNormalLoad(LD) || !LD->isSimple())
6919 return SDValue();
6920 EVT PVT = LD->getValueType(0);
6921 if (PVT != MVT::i32 && PVT != MVT::f32)
6922 return SDValue();
6924 int FI = -1;
6925 int64_t Offset = 0;
6926 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
6927 FI = FINode->getIndex();
6928 Offset = 0;
6929 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
6930 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6931 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6932 Offset = Ptr.getConstantOperandVal(1);
6933 Ptr = Ptr.getOperand(0);
6934 } else {
6935 return SDValue();
6938 // FIXME: 256-bit vector instructions don't require a strict alignment,
6939 // improve this code to support it better.
6940 Align RequiredAlign(VT.getSizeInBits() / 8);
6941 SDValue Chain = LD->getChain();
6942 // Make sure the stack object alignment is at least 16 or 32.
6943 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6944 MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
6945 if (!InferredAlign || *InferredAlign < RequiredAlign) {
6946 if (MFI.isFixedObjectIndex(FI)) {
6947 // Can't change the alignment. FIXME: It's possible to compute
6948 // the exact stack offset and reference FI + adjust offset instead.
6949 // If someone *really* cares about this. That's the way to implement it.
6950 return SDValue();
6951 } else {
6952 MFI.setObjectAlignment(FI, RequiredAlign);
6956 // (Offset % 16 or 32) must be multiple of 4. Then address is then
6957 // Ptr + (Offset & ~15).
6958 if (Offset < 0)
6959 return SDValue();
6960 if ((Offset % RequiredAlign.value()) & 3)
6961 return SDValue();
6962 int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
6963 if (StartOffset) {
6964 SDLoc DL(Ptr);
6965 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6966 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
6969 int EltNo = (Offset - StartOffset) >> 2;
6970 unsigned NumElems = VT.getVectorNumElements();
6972 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
6973 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
6974 LD->getPointerInfo().getWithOffset(StartOffset));
6976 SmallVector<int, 8> Mask(NumElems, EltNo);
6978 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
6981 return SDValue();
6984 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
6985 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
6986 if (ISD::isNON_EXTLoad(Elt.getNode())) {
6987 auto *BaseLd = cast<LoadSDNode>(Elt);
6988 if (!BaseLd->isSimple())
6989 return false;
6990 Ld = BaseLd;
6991 ByteOffset = 0;
6992 return true;
6995 switch (Elt.getOpcode()) {
6996 case ISD::BITCAST:
6997 case ISD::TRUNCATE:
6998 case ISD::SCALAR_TO_VECTOR:
6999 return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
7000 case ISD::SRL:
7001 if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7002 uint64_t Amt = AmtC->getZExtValue();
7003 if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
7004 ByteOffset += Amt / 8;
7005 return true;
7008 break;
7009 case ISD::EXTRACT_VECTOR_ELT:
7010 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7011 SDValue Src = Elt.getOperand(0);
7012 unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
7013 unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
7014 if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
7015 findEltLoadSrc(Src, Ld, ByteOffset)) {
7016 uint64_t Idx = IdxC->getZExtValue();
7017 ByteOffset += Idx * (SrcSizeInBits / 8);
7018 return true;
7021 break;
7024 return false;
7027 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7028 /// elements can be replaced by a single large load which has the same value as
7029 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7031 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
7032 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
7033 const SDLoc &DL, SelectionDAG &DAG,
7034 const X86Subtarget &Subtarget,
7035 bool IsAfterLegalize) {
7036 if ((VT.getScalarSizeInBits() % 8) != 0)
7037 return SDValue();
7039 unsigned NumElems = Elts.size();
7041 int LastLoadedElt = -1;
7042 APInt LoadMask = APInt::getZero(NumElems);
7043 APInt ZeroMask = APInt::getZero(NumElems);
7044 APInt UndefMask = APInt::getZero(NumElems);
7046 SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
7047 SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
7049 // For each element in the initializer, see if we've found a load, zero or an
7050 // undef.
7051 for (unsigned i = 0; i < NumElems; ++i) {
7052 SDValue Elt = peekThroughBitcasts(Elts[i]);
7053 if (!Elt.getNode())
7054 return SDValue();
7055 if (Elt.isUndef()) {
7056 UndefMask.setBit(i);
7057 continue;
7059 if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
7060 ZeroMask.setBit(i);
7061 continue;
7064 // Each loaded element must be the correct fractional portion of the
7065 // requested vector load.
7066 unsigned EltSizeInBits = Elt.getValueSizeInBits();
7067 if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
7068 return SDValue();
7070 if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
7071 return SDValue();
7072 unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
7073 if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
7074 return SDValue();
7076 LoadMask.setBit(i);
7077 LastLoadedElt = i;
7079 assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
7080 NumElems &&
7081 "Incomplete element masks");
7083 // Handle Special Cases - all undef or undef/zero.
7084 if (UndefMask.popcount() == NumElems)
7085 return DAG.getUNDEF(VT);
7086 if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
7087 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7088 : DAG.getConstantFP(0.0, DL, VT);
7090 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7091 int FirstLoadedElt = LoadMask.countr_zero();
7092 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7093 EVT EltBaseVT = EltBase.getValueType();
7094 assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
7095 "Register/Memory size mismatch");
7096 LoadSDNode *LDBase = Loads[FirstLoadedElt];
7097 assert(LDBase && "Did not find base load for merging consecutive loads");
7098 unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
7099 unsigned BaseSizeInBytes = BaseSizeInBits / 8;
7100 int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
7101 int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
7102 assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
7104 // TODO: Support offsetting the base load.
7105 if (ByteOffsets[FirstLoadedElt] != 0)
7106 return SDValue();
7108 // Check to see if the element's load is consecutive to the base load
7109 // or offset from a previous (already checked) load.
7110 auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
7111 LoadSDNode *Ld = Loads[EltIdx];
7112 int64_t ByteOffset = ByteOffsets[EltIdx];
7113 if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
7114 int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
7115 return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
7116 Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
7118 return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
7119 EltIdx - FirstLoadedElt);
7122 // Consecutive loads can contain UNDEFS but not ZERO elements.
7123 // Consecutive loads with UNDEFs and ZEROs elements require a
7124 // an additional shuffle stage to clear the ZERO elements.
7125 bool IsConsecutiveLoad = true;
7126 bool IsConsecutiveLoadWithZeros = true;
7127 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7128 if (LoadMask[i]) {
7129 if (!CheckConsecutiveLoad(LDBase, i)) {
7130 IsConsecutiveLoad = false;
7131 IsConsecutiveLoadWithZeros = false;
7132 break;
7134 } else if (ZeroMask[i]) {
7135 IsConsecutiveLoad = false;
7139 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7140 auto MMOFlags = LDBase->getMemOperand()->getFlags();
7141 assert(LDBase->isSimple() &&
7142 "Cannot merge volatile or atomic loads.");
7143 SDValue NewLd =
7144 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7145 LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
7146 MMOFlags);
7147 for (auto *LD : Loads)
7148 if (LD)
7149 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
7150 return NewLd;
7153 // Check if the base load is entirely dereferenceable.
7154 bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
7155 VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
7157 // LOAD - all consecutive load/undefs (must start/end with a load or be
7158 // entirely dereferenceable). If we have found an entire vector of loads and
7159 // undefs, then return a large load of the entire vector width starting at the
7160 // base pointer. If the vector contains zeros, then attempt to shuffle those
7161 // elements.
7162 if (FirstLoadedElt == 0 &&
7163 (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
7164 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
7165 if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
7166 return SDValue();
7168 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
7169 // will lower to regular temporal loads and use the cache.
7170 if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
7171 VT.is256BitVector() && !Subtarget.hasInt256())
7172 return SDValue();
7174 if (NumElems == 1)
7175 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
7177 if (!ZeroMask)
7178 return CreateLoad(VT, LDBase);
7180 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
7181 // vector and a zero vector to clear out the zero elements.
7182 if (!IsAfterLegalize && VT.isVector()) {
7183 unsigned NumMaskElts = VT.getVectorNumElements();
7184 if ((NumMaskElts % NumElems) == 0) {
7185 unsigned Scale = NumMaskElts / NumElems;
7186 SmallVector<int, 4> ClearMask(NumMaskElts, -1);
7187 for (unsigned i = 0; i < NumElems; ++i) {
7188 if (UndefMask[i])
7189 continue;
7190 int Offset = ZeroMask[i] ? NumMaskElts : 0;
7191 for (unsigned j = 0; j != Scale; ++j)
7192 ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
7194 SDValue V = CreateLoad(VT, LDBase);
7195 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
7196 : DAG.getConstantFP(0.0, DL, VT);
7197 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
7202 // If the upper half of a ymm/zmm load is undef then just load the lower half.
7203 if (VT.is256BitVector() || VT.is512BitVector()) {
7204 unsigned HalfNumElems = NumElems / 2;
7205 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
7206 EVT HalfVT =
7207 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
7208 SDValue HalfLD =
7209 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
7210 DAG, Subtarget, IsAfterLegalize);
7211 if (HalfLD)
7212 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
7213 HalfLD, DAG.getIntPtrConstant(0, DL));
7217 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
7218 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
7219 ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
7220 LoadSizeInBits == 64) &&
7221 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
7222 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
7223 : MVT::getIntegerVT(LoadSizeInBits);
7224 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
7225 // Allow v4f32 on SSE1 only targets.
7226 // FIXME: Add more isel patterns so we can just use VT directly.
7227 if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
7228 VecVT = MVT::v4f32;
7229 if (TLI.isTypeLegal(VecVT)) {
7230 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
7231 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
7232 SDValue ResNode = DAG.getMemIntrinsicNode(
7233 X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
7234 LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
7235 for (auto *LD : Loads)
7236 if (LD)
7237 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
7238 return DAG.getBitcast(VT, ResNode);
7242 // BROADCAST - match the smallest possible repetition pattern, load that
7243 // scalar/subvector element and then broadcast to the entire vector.
7244 if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
7245 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
7246 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
7247 unsigned RepeatSize = SubElems * BaseSizeInBits;
7248 unsigned ScalarSize = std::min(RepeatSize, 64u);
7249 if (!Subtarget.hasAVX2() && ScalarSize < 32)
7250 continue;
7252 // Don't attempt a 1:N subvector broadcast - it should be caught by
7253 // combineConcatVectorOps, else will cause infinite loops.
7254 if (RepeatSize > ScalarSize && SubElems == 1)
7255 continue;
7257 bool Match = true;
7258 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
7259 for (unsigned i = 0; i != NumElems && Match; ++i) {
7260 if (!LoadMask[i])
7261 continue;
7262 SDValue Elt = peekThroughBitcasts(Elts[i]);
7263 if (RepeatedLoads[i % SubElems].isUndef())
7264 RepeatedLoads[i % SubElems] = Elt;
7265 else
7266 Match &= (RepeatedLoads[i % SubElems] == Elt);
7269 // We must have loads at both ends of the repetition.
7270 Match &= !RepeatedLoads.front().isUndef();
7271 Match &= !RepeatedLoads.back().isUndef();
7272 if (!Match)
7273 continue;
7275 EVT RepeatVT =
7276 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
7277 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
7278 : EVT::getFloatingPointVT(ScalarSize);
7279 if (RepeatSize > ScalarSize)
7280 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
7281 RepeatSize / ScalarSize);
7282 EVT BroadcastVT =
7283 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
7284 VT.getSizeInBits() / ScalarSize);
7285 if (TLI.isTypeLegal(BroadcastVT)) {
7286 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
7287 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
7288 SDValue Broadcast = RepeatLoad;
7289 if (RepeatSize > ScalarSize) {
7290 while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
7291 Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
7292 } else {
7293 if (!Subtarget.hasAVX2() &&
7294 !X86::mayFoldLoadIntoBroadcastFromMem(
7295 RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
7296 Subtarget,
7297 /*AssumeSingleUse=*/true))
7298 return SDValue();
7299 Broadcast =
7300 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
7302 return DAG.getBitcast(VT, Broadcast);
7308 return SDValue();
7311 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
7312 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
7313 // are consecutive, non-overlapping, and in the right order.
7314 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
7315 SelectionDAG &DAG,
7316 const X86Subtarget &Subtarget,
7317 bool IsAfterLegalize) {
7318 SmallVector<SDValue, 64> Elts;
7319 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7320 if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
7321 Elts.push_back(Elt);
7322 continue;
7324 return SDValue();
7326 assert(Elts.size() == VT.getVectorNumElements());
7327 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
7328 IsAfterLegalize);
7331 static Constant *getConstantVector(MVT VT, ArrayRef<APInt> Bits,
7332 const APInt &Undefs, LLVMContext &C) {
7333 unsigned ScalarSize = VT.getScalarSizeInBits();
7334 Type *Ty = EVT(VT.getScalarType()).getTypeForEVT(C);
7336 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
7337 if (VT.isFloatingPoint()) {
7338 if (ScalarSize == 16)
7339 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
7340 if (ScalarSize == 32)
7341 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7342 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
7343 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7345 return Constant::getIntegerValue(Ty, Val);
7348 SmallVector<Constant *, 32> ConstantVec;
7349 for (unsigned I = 0, E = Bits.size(); I != E; ++I)
7350 ConstantVec.push_back(Undefs[I] ? UndefValue::get(Ty)
7351 : getConstantScalar(Bits[I]));
7353 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7356 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
7357 unsigned SplatBitSize, LLVMContext &C) {
7358 unsigned ScalarSize = VT.getScalarSizeInBits();
7360 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
7361 if (VT.isFloatingPoint()) {
7362 if (ScalarSize == 16)
7363 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
7364 if (ScalarSize == 32)
7365 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7366 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
7367 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7369 return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
7372 if (ScalarSize == SplatBitSize)
7373 return getConstantScalar(SplatValue);
7375 unsigned NumElm = SplatBitSize / ScalarSize;
7376 SmallVector<Constant *, 32> ConstantVec;
7377 for (unsigned I = 0; I != NumElm; ++I) {
7378 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
7379 ConstantVec.push_back(getConstantScalar(Val));
7381 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7384 static bool isFoldableUseOfShuffle(SDNode *N) {
7385 for (auto *U : N->uses()) {
7386 unsigned Opc = U->getOpcode();
7387 // VPERMV/VPERMV3 shuffles can never fold their index operands.
7388 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
7389 return false;
7390 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
7391 return false;
7392 if (isTargetShuffle(Opc))
7393 return true;
7394 if (Opc == ISD::BITCAST) // Ignore bitcasts
7395 return isFoldableUseOfShuffle(U);
7396 if (N->hasOneUse()) {
7397 // TODO, there may be some general way to know if a SDNode can
7398 // be folded. We now only know whether an MI is foldable.
7399 if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
7400 return false;
7401 return true;
7404 return false;
7407 /// Attempt to use the vbroadcast instruction to generate a splat value
7408 /// from a splat BUILD_VECTOR which uses:
7409 /// a. A single scalar load, or a constant.
7410 /// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
7412 /// The VBROADCAST node is returned when a pattern is found,
7413 /// or SDValue() otherwise.
7414 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
7415 const SDLoc &dl,
7416 const X86Subtarget &Subtarget,
7417 SelectionDAG &DAG) {
7418 // VBROADCAST requires AVX.
7419 // TODO: Splats could be generated for non-AVX CPUs using SSE
7420 // instructions, but there's less potential gain for only 128-bit vectors.
7421 if (!Subtarget.hasAVX())
7422 return SDValue();
7424 MVT VT = BVOp->getSimpleValueType(0);
7425 unsigned NumElts = VT.getVectorNumElements();
7426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7427 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
7428 "Unsupported vector type for broadcast.");
7430 // See if the build vector is a repeating sequence of scalars (inc. splat).
7431 SDValue Ld;
7432 BitVector UndefElements;
7433 SmallVector<SDValue, 16> Sequence;
7434 if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
7435 assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
7436 if (Sequence.size() == 1)
7437 Ld = Sequence[0];
7440 // Attempt to use VBROADCASTM
7441 // From this pattern:
7442 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
7443 // b. t1 = (build_vector t0 t0)
7445 // Create (VBROADCASTM v2i1 X)
7446 if (!Sequence.empty() && Subtarget.hasCDI()) {
7447 // If not a splat, are the upper sequence values zeroable?
7448 unsigned SeqLen = Sequence.size();
7449 bool UpperZeroOrUndef =
7450 SeqLen == 1 ||
7451 llvm::all_of(ArrayRef(Sequence).drop_front(),
7452 [](SDValue V) { return !V || isNullConstantOrUndef(V); });
7453 SDValue Op0 = Sequence[0];
7454 if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
7455 (Op0.getOpcode() == ISD::ZERO_EXTEND &&
7456 Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
7457 SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
7458 ? Op0.getOperand(0)
7459 : Op0.getOperand(0).getOperand(0);
7460 MVT MaskVT = BOperand.getSimpleValueType();
7461 MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
7462 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
7463 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
7464 MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
7465 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
7466 unsigned Scale = 512 / VT.getSizeInBits();
7467 BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
7469 SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
7470 if (BcstVT.getSizeInBits() != VT.getSizeInBits())
7471 Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
7472 return DAG.getBitcast(VT, Bcst);
7477 unsigned NumUndefElts = UndefElements.count();
7478 if (!Ld || (NumElts - NumUndefElts) <= 1) {
7479 APInt SplatValue, Undef;
7480 unsigned SplatBitSize;
7481 bool HasUndef;
7482 // Check if this is a repeated constant pattern suitable for broadcasting.
7483 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
7484 SplatBitSize > VT.getScalarSizeInBits() &&
7485 SplatBitSize < VT.getSizeInBits()) {
7486 // Avoid replacing with broadcast when it's a use of a shuffle
7487 // instruction to preserve the present custom lowering of shuffles.
7488 if (isFoldableUseOfShuffle(BVOp))
7489 return SDValue();
7490 // replace BUILD_VECTOR with broadcast of the repeated constants.
7491 LLVMContext *Ctx = DAG.getContext();
7492 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
7493 if (SplatBitSize == 32 || SplatBitSize == 64 ||
7494 (SplatBitSize < 32 && Subtarget.hasAVX2())) {
7495 // Load the constant scalar/subvector and broadcast it.
7496 MVT CVT = MVT::getIntegerVT(SplatBitSize);
7497 Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
7498 SDValue CP = DAG.getConstantPool(C, PVT);
7499 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7501 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
7502 SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
7503 SDValue Ops[] = {DAG.getEntryNode(), CP};
7504 MachinePointerInfo MPI =
7505 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7506 SDValue Brdcst =
7507 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
7508 MPI, Alignment, MachineMemOperand::MOLoad);
7509 return DAG.getBitcast(VT, Brdcst);
7511 if (SplatBitSize > 64) {
7512 // Load the vector of constants and broadcast it.
7513 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
7514 SDValue VCP = DAG.getConstantPool(VecC, PVT);
7515 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
7516 MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
7517 Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
7518 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7519 SDValue Ops[] = {DAG.getEntryNode(), VCP};
7520 MachinePointerInfo MPI =
7521 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7522 return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
7523 Ops, VVT, MPI, Alignment,
7524 MachineMemOperand::MOLoad);
7528 // If we are moving a scalar into a vector (Ld must be set and all elements
7529 // but 1 are undef) and that operation is not obviously supported by
7530 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
7531 // That's better than general shuffling and may eliminate a load to GPR and
7532 // move from scalar to vector register.
7533 if (!Ld || NumElts - NumUndefElts != 1)
7534 return SDValue();
7535 unsigned ScalarSize = Ld.getValueSizeInBits();
7536 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
7537 return SDValue();
7540 bool ConstSplatVal =
7541 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
7542 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
7544 // TODO: Handle broadcasts of non-constant sequences.
7546 // Make sure that all of the users of a non-constant load are from the
7547 // BUILD_VECTOR node.
7548 // FIXME: Is the use count needed for non-constant, non-load case?
7549 if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
7550 return SDValue();
7552 unsigned ScalarSize = Ld.getValueSizeInBits();
7553 bool IsGE256 = (VT.getSizeInBits() >= 256);
7555 // When optimizing for size, generate up to 5 extra bytes for a broadcast
7556 // instruction to save 8 or more bytes of constant pool data.
7557 // TODO: If multiple splats are generated to load the same constant,
7558 // it may be detrimental to overall size. There needs to be a way to detect
7559 // that condition to know if this is truly a size win.
7560 bool OptForSize = DAG.shouldOptForSize();
7562 // Handle broadcasting a single constant scalar from the constant pool
7563 // into a vector.
7564 // On Sandybridge (no AVX2), it is still better to load a constant vector
7565 // from the constant pool and not to broadcast it from a scalar.
7566 // But override that restriction when optimizing for size.
7567 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
7568 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
7569 EVT CVT = Ld.getValueType();
7570 assert(!CVT.isVector() && "Must not broadcast a vector type");
7572 // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
7573 // For size optimization, also splat v2f64 and v2i64, and for size opt
7574 // with AVX2, also splat i8 and i16.
7575 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
7576 if (ScalarSize == 32 ||
7577 (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
7578 (CVT == MVT::f16 && Subtarget.hasAVX2()) ||
7579 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
7580 const Constant *C = nullptr;
7581 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
7582 C = CI->getConstantIntValue();
7583 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
7584 C = CF->getConstantFPValue();
7586 assert(C && "Invalid constant type");
7588 SDValue CP =
7589 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
7590 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
7592 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7593 SDValue Ops[] = {DAG.getEntryNode(), CP};
7594 MachinePointerInfo MPI =
7595 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7596 return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
7597 MPI, Alignment, MachineMemOperand::MOLoad);
7601 // Handle AVX2 in-register broadcasts.
7602 if (!IsLoad && Subtarget.hasInt256() &&
7603 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
7604 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7606 // The scalar source must be a normal load.
7607 if (!IsLoad)
7608 return SDValue();
7610 // Make sure the non-chain result is only used by this build vector.
7611 if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
7612 return SDValue();
7614 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7615 (Subtarget.hasVLX() && ScalarSize == 64)) {
7616 auto *LN = cast<LoadSDNode>(Ld);
7617 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7618 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
7619 SDValue BCast =
7620 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
7621 LN->getMemoryVT(), LN->getMemOperand());
7622 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
7623 return BCast;
7626 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
7627 // double since there is no vbroadcastsd xmm
7628 if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
7629 (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
7630 auto *LN = cast<LoadSDNode>(Ld);
7631 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7632 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
7633 SDValue BCast =
7634 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
7635 LN->getMemoryVT(), LN->getMemOperand());
7636 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
7637 return BCast;
7640 if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
7641 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7643 // Unsupported broadcast.
7644 return SDValue();
7647 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
7648 /// underlying vector and index.
7650 /// Modifies \p ExtractedFromVec to the real vector and returns the real
7651 /// index.
7652 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
7653 SDValue ExtIdx) {
7654 int Idx = ExtIdx->getAsZExtVal();
7655 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
7656 return Idx;
7658 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
7659 // lowered this:
7660 // (extract_vector_elt (v8f32 %1), Constant<6>)
7661 // to:
7662 // (extract_vector_elt (vector_shuffle<2,u,u,u>
7663 // (extract_subvector (v8f32 %0), Constant<4>),
7664 // undef)
7665 // Constant<0>)
7666 // In this case the vector is the extract_subvector expression and the index
7667 // is 2, as specified by the shuffle.
7668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
7669 SDValue ShuffleVec = SVOp->getOperand(0);
7670 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
7671 assert(ShuffleVecVT.getVectorElementType() ==
7672 ExtractedFromVec.getSimpleValueType().getVectorElementType());
7674 int ShuffleIdx = SVOp->getMaskElt(Idx);
7675 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
7676 ExtractedFromVec = ShuffleVec;
7677 return ShuffleIdx;
7679 return Idx;
7682 static SDValue buildFromShuffleMostly(SDValue Op, const SDLoc &DL,
7683 SelectionDAG &DAG) {
7684 MVT VT = Op.getSimpleValueType();
7686 // Skip if insert_vec_elt is not supported.
7687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7688 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
7689 return SDValue();
7691 unsigned NumElems = Op.getNumOperands();
7692 SDValue VecIn1;
7693 SDValue VecIn2;
7694 SmallVector<unsigned, 4> InsertIndices;
7695 SmallVector<int, 8> Mask(NumElems, -1);
7697 for (unsigned i = 0; i != NumElems; ++i) {
7698 unsigned Opc = Op.getOperand(i).getOpcode();
7700 if (Opc == ISD::UNDEF)
7701 continue;
7703 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
7704 // Quit if more than 1 elements need inserting.
7705 if (InsertIndices.size() > 1)
7706 return SDValue();
7708 InsertIndices.push_back(i);
7709 continue;
7712 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
7713 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
7715 // Quit if non-constant index.
7716 if (!isa<ConstantSDNode>(ExtIdx))
7717 return SDValue();
7718 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
7720 // Quit if extracted from vector of different type.
7721 if (ExtractedFromVec.getValueType() != VT)
7722 return SDValue();
7724 if (!VecIn1.getNode())
7725 VecIn1 = ExtractedFromVec;
7726 else if (VecIn1 != ExtractedFromVec) {
7727 if (!VecIn2.getNode())
7728 VecIn2 = ExtractedFromVec;
7729 else if (VecIn2 != ExtractedFromVec)
7730 // Quit if more than 2 vectors to shuffle
7731 return SDValue();
7734 if (ExtractedFromVec == VecIn1)
7735 Mask[i] = Idx;
7736 else if (ExtractedFromVec == VecIn2)
7737 Mask[i] = Idx + NumElems;
7740 if (!VecIn1.getNode())
7741 return SDValue();
7743 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7744 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
7746 for (unsigned Idx : InsertIndices)
7747 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
7748 DAG.getIntPtrConstant(Idx, DL));
7750 return NV;
7753 // Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
7754 static SDValue LowerBUILD_VECTORvXbf16(SDValue Op, SelectionDAG &DAG,
7755 const X86Subtarget &Subtarget) {
7756 MVT VT = Op.getSimpleValueType();
7757 MVT IVT =
7758 VT.changeVectorElementType(Subtarget.hasFP16() ? MVT::f16 : MVT::i16);
7759 SmallVector<SDValue, 16> NewOps;
7760 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
7761 NewOps.push_back(DAG.getBitcast(Subtarget.hasFP16() ? MVT::f16 : MVT::i16,
7762 Op.getOperand(I)));
7763 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
7764 return DAG.getBitcast(VT, Res);
7767 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
7768 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, const SDLoc &dl,
7769 SelectionDAG &DAG,
7770 const X86Subtarget &Subtarget) {
7772 MVT VT = Op.getSimpleValueType();
7773 assert((VT.getVectorElementType() == MVT::i1) &&
7774 "Unexpected type in LowerBUILD_VECTORvXi1!");
7775 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
7776 ISD::isBuildVectorAllOnes(Op.getNode()))
7777 return Op;
7779 uint64_t Immediate = 0;
7780 SmallVector<unsigned, 16> NonConstIdx;
7781 bool IsSplat = true;
7782 bool HasConstElts = false;
7783 int SplatIdx = -1;
7784 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7785 SDValue In = Op.getOperand(idx);
7786 if (In.isUndef())
7787 continue;
7788 if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
7789 Immediate |= (InC->getZExtValue() & 0x1) << idx;
7790 HasConstElts = true;
7791 } else {
7792 NonConstIdx.push_back(idx);
7794 if (SplatIdx < 0)
7795 SplatIdx = idx;
7796 else if (In != Op.getOperand(SplatIdx))
7797 IsSplat = false;
7800 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
7801 if (IsSplat) {
7802 // The build_vector allows the scalar element to be larger than the vector
7803 // element type. We need to mask it to use as a condition unless we know
7804 // the upper bits are zero.
7805 // FIXME: Use computeKnownBits instead of checking specific opcode?
7806 SDValue Cond = Op.getOperand(SplatIdx);
7807 assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
7808 if (Cond.getOpcode() != ISD::SETCC)
7809 Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
7810 DAG.getConstant(1, dl, MVT::i8));
7812 // Perform the select in the scalar domain so we can use cmov.
7813 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7814 SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
7815 DAG.getAllOnesConstant(dl, MVT::i32),
7816 DAG.getConstant(0, dl, MVT::i32));
7817 Select = DAG.getBitcast(MVT::v32i1, Select);
7818 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
7819 } else {
7820 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
7821 SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
7822 DAG.getAllOnesConstant(dl, ImmVT),
7823 DAG.getConstant(0, dl, ImmVT));
7824 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
7825 Select = DAG.getBitcast(VecVT, Select);
7826 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
7827 DAG.getIntPtrConstant(0, dl));
7831 // insert elements one by one
7832 SDValue DstVec;
7833 if (HasConstElts) {
7834 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7835 SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
7836 SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
7837 ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
7838 ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
7839 DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
7840 } else {
7841 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
7842 SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
7843 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
7844 DstVec = DAG.getBitcast(VecVT, Imm);
7845 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
7846 DAG.getIntPtrConstant(0, dl));
7848 } else
7849 DstVec = DAG.getUNDEF(VT);
7851 for (unsigned InsertIdx : NonConstIdx) {
7852 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7853 Op.getOperand(InsertIdx),
7854 DAG.getIntPtrConstant(InsertIdx, dl));
7856 return DstVec;
7859 LLVM_ATTRIBUTE_UNUSED static bool isHorizOp(unsigned Opcode) {
7860 switch (Opcode) {
7861 case X86ISD::PACKSS:
7862 case X86ISD::PACKUS:
7863 case X86ISD::FHADD:
7864 case X86ISD::FHSUB:
7865 case X86ISD::HADD:
7866 case X86ISD::HSUB:
7867 return true;
7869 return false;
7872 /// This is a helper function of LowerToHorizontalOp().
7873 /// This function checks that the build_vector \p N in input implements a
7874 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
7875 /// may not match the layout of an x86 256-bit horizontal instruction.
7876 /// In other words, if this returns true, then some extraction/insertion will
7877 /// be required to produce a valid horizontal instruction.
7879 /// Parameter \p Opcode defines the kind of horizontal operation to match.
7880 /// For example, if \p Opcode is equal to ISD::ADD, then this function
7881 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
7882 /// is equal to ISD::SUB, then this function checks if this is a horizontal
7883 /// arithmetic sub.
7885 /// This function only analyzes elements of \p N whose indices are
7886 /// in range [BaseIdx, LastIdx).
7888 /// TODO: This function was originally used to match both real and fake partial
7889 /// horizontal operations, but the index-matching logic is incorrect for that.
7890 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
7891 /// code because it is only used for partial h-op matching now?
7892 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
7893 const SDLoc &DL, SelectionDAG &DAG,
7894 unsigned BaseIdx, unsigned LastIdx,
7895 SDValue &V0, SDValue &V1) {
7896 EVT VT = N->getValueType(0);
7897 assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
7898 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
7899 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
7900 "Invalid Vector in input!");
7902 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
7903 bool CanFold = true;
7904 unsigned ExpectedVExtractIdx = BaseIdx;
7905 unsigned NumElts = LastIdx - BaseIdx;
7906 V0 = DAG.getUNDEF(VT);
7907 V1 = DAG.getUNDEF(VT);
7909 // Check if N implements a horizontal binop.
7910 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
7911 SDValue Op = N->getOperand(i + BaseIdx);
7913 // Skip UNDEFs.
7914 if (Op->isUndef()) {
7915 // Update the expected vector extract index.
7916 if (i * 2 == NumElts)
7917 ExpectedVExtractIdx = BaseIdx;
7918 ExpectedVExtractIdx += 2;
7919 continue;
7922 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
7924 if (!CanFold)
7925 break;
7927 SDValue Op0 = Op.getOperand(0);
7928 SDValue Op1 = Op.getOperand(1);
7930 // Try to match the following pattern:
7931 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
7932 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7933 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7934 Op0.getOperand(0) == Op1.getOperand(0) &&
7935 isa<ConstantSDNode>(Op0.getOperand(1)) &&
7936 isa<ConstantSDNode>(Op1.getOperand(1)));
7937 if (!CanFold)
7938 break;
7940 unsigned I0 = Op0.getConstantOperandVal(1);
7941 unsigned I1 = Op1.getConstantOperandVal(1);
7943 if (i * 2 < NumElts) {
7944 if (V0.isUndef()) {
7945 V0 = Op0.getOperand(0);
7946 if (V0.getValueType() != VT)
7947 return false;
7949 } else {
7950 if (V1.isUndef()) {
7951 V1 = Op0.getOperand(0);
7952 if (V1.getValueType() != VT)
7953 return false;
7955 if (i * 2 == NumElts)
7956 ExpectedVExtractIdx = BaseIdx;
7959 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
7960 if (I0 == ExpectedVExtractIdx)
7961 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
7962 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
7963 // Try to match the following dag sequence:
7964 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
7965 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
7966 } else
7967 CanFold = false;
7969 ExpectedVExtractIdx += 2;
7972 return CanFold;
7975 /// Emit a sequence of two 128-bit horizontal add/sub followed by
7976 /// a concat_vector.
7978 /// This is a helper function of LowerToHorizontalOp().
7979 /// This function expects two 256-bit vectors called V0 and V1.
7980 /// At first, each vector is split into two separate 128-bit vectors.
7981 /// Then, the resulting 128-bit vectors are used to implement two
7982 /// horizontal binary operations.
7984 /// The kind of horizontal binary operation is defined by \p X86Opcode.
7986 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
7987 /// the two new horizontal binop.
7988 /// When Mode is set, the first horizontal binop dag node would take as input
7989 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
7990 /// horizontal binop dag node would take as input the lower 128-bit of V1
7991 /// and the upper 128-bit of V1.
7992 /// Example:
7993 /// HADD V0_LO, V0_HI
7994 /// HADD V1_LO, V1_HI
7996 /// Otherwise, the first horizontal binop dag node takes as input the lower
7997 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
7998 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
7999 /// Example:
8000 /// HADD V0_LO, V1_LO
8001 /// HADD V0_HI, V1_HI
8003 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
8004 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
8005 /// the upper 128-bits of the result.
8006 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
8007 const SDLoc &DL, SelectionDAG &DAG,
8008 unsigned X86Opcode, bool Mode,
8009 bool isUndefLO, bool isUndefHI) {
8010 MVT VT = V0.getSimpleValueType();
8011 assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
8012 "Invalid nodes in input!");
8014 unsigned NumElts = VT.getVectorNumElements();
8015 SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
8016 SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
8017 SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
8018 SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
8019 MVT NewVT = V0_LO.getSimpleValueType();
8021 SDValue LO = DAG.getUNDEF(NewVT);
8022 SDValue HI = DAG.getUNDEF(NewVT);
8024 if (Mode) {
8025 // Don't emit a horizontal binop if the result is expected to be UNDEF.
8026 if (!isUndefLO && !V0->isUndef())
8027 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
8028 if (!isUndefHI && !V1->isUndef())
8029 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
8030 } else {
8031 // Don't emit a horizontal binop if the result is expected to be UNDEF.
8032 if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
8033 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
8035 if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
8036 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
8039 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
8042 /// Returns true iff \p BV builds a vector with the result equivalent to
8043 /// the result of ADDSUB/SUBADD operation.
8044 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
8045 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
8046 /// \p Opnd0 and \p Opnd1.
8047 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
8048 const X86Subtarget &Subtarget, SelectionDAG &DAG,
8049 SDValue &Opnd0, SDValue &Opnd1,
8050 unsigned &NumExtracts,
8051 bool &IsSubAdd) {
8053 MVT VT = BV->getSimpleValueType(0);
8054 if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
8055 return false;
8057 unsigned NumElts = VT.getVectorNumElements();
8058 SDValue InVec0 = DAG.getUNDEF(VT);
8059 SDValue InVec1 = DAG.getUNDEF(VT);
8061 NumExtracts = 0;
8063 // Odd-numbered elements in the input build vector are obtained from
8064 // adding/subtracting two integer/float elements.
8065 // Even-numbered elements in the input build vector are obtained from
8066 // subtracting/adding two integer/float elements.
8067 unsigned Opc[2] = {0, 0};
8068 for (unsigned i = 0, e = NumElts; i != e; ++i) {
8069 SDValue Op = BV->getOperand(i);
8071 // Skip 'undef' values.
8072 unsigned Opcode = Op.getOpcode();
8073 if (Opcode == ISD::UNDEF)
8074 continue;
8076 // Early exit if we found an unexpected opcode.
8077 if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
8078 return false;
8080 SDValue Op0 = Op.getOperand(0);
8081 SDValue Op1 = Op.getOperand(1);
8083 // Try to match the following pattern:
8084 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
8085 // Early exit if we cannot match that sequence.
8086 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8087 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8088 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8089 Op0.getOperand(1) != Op1.getOperand(1))
8090 return false;
8092 unsigned I0 = Op0.getConstantOperandVal(1);
8093 if (I0 != i)
8094 return false;
8096 // We found a valid add/sub node, make sure its the same opcode as previous
8097 // elements for this parity.
8098 if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
8099 return false;
8100 Opc[i % 2] = Opcode;
8102 // Update InVec0 and InVec1.
8103 if (InVec0.isUndef()) {
8104 InVec0 = Op0.getOperand(0);
8105 if (InVec0.getSimpleValueType() != VT)
8106 return false;
8108 if (InVec1.isUndef()) {
8109 InVec1 = Op1.getOperand(0);
8110 if (InVec1.getSimpleValueType() != VT)
8111 return false;
8114 // Make sure that operands in input to each add/sub node always
8115 // come from a same pair of vectors.
8116 if (InVec0 != Op0.getOperand(0)) {
8117 if (Opcode == ISD::FSUB)
8118 return false;
8120 // FADD is commutable. Try to commute the operands
8121 // and then test again.
8122 std::swap(Op0, Op1);
8123 if (InVec0 != Op0.getOperand(0))
8124 return false;
8127 if (InVec1 != Op1.getOperand(0))
8128 return false;
8130 // Increment the number of extractions done.
8131 ++NumExtracts;
8134 // Ensure we have found an opcode for both parities and that they are
8135 // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
8136 // inputs are undef.
8137 if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
8138 InVec0.isUndef() || InVec1.isUndef())
8139 return false;
8141 IsSubAdd = Opc[0] == ISD::FADD;
8143 Opnd0 = InVec0;
8144 Opnd1 = InVec1;
8145 return true;
8148 /// Returns true if is possible to fold MUL and an idiom that has already been
8149 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8150 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8151 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8153 /// Prior to calling this function it should be known that there is some
8154 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8155 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8156 /// before replacement of such SDNode with ADDSUB operation. Thus the number
8157 /// of \p Opnd0 uses is expected to be equal to 2.
8158 /// For example, this function may be called for the following IR:
8159 /// %AB = fmul fast <2 x double> %A, %B
8160 /// %Sub = fsub fast <2 x double> %AB, %C
8161 /// %Add = fadd fast <2 x double> %AB, %C
8162 /// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8163 /// <2 x i32> <i32 0, i32 3>
8164 /// There is a def for %Addsub here, which potentially can be replaced by
8165 /// X86ISD::ADDSUB operation:
8166 /// %Addsub = X86ISD::ADDSUB %AB, %C
8167 /// and such ADDSUB can further be replaced with FMADDSUB:
8168 /// %Addsub = FMADDSUB %A, %B, %C.
8170 /// The main reason why this method is called before the replacement of the
8171 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8172 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8173 /// FMADDSUB is.
8174 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
8175 SelectionDAG &DAG,
8176 SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
8177 unsigned ExpectedUses) {
8178 if (Opnd0.getOpcode() != ISD::FMUL ||
8179 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8180 return false;
8182 // FIXME: These checks must match the similar ones in
8183 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8184 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8185 // or MUL + ADDSUB to FMADDSUB.
8186 const TargetOptions &Options = DAG.getTarget().Options;
8187 bool AllowFusion =
8188 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8189 if (!AllowFusion)
8190 return false;
8192 Opnd2 = Opnd1;
8193 Opnd1 = Opnd0.getOperand(1);
8194 Opnd0 = Opnd0.getOperand(0);
8196 return true;
8199 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
8200 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
8201 /// X86ISD::FMSUBADD node.
8202 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
8203 const SDLoc &DL,
8204 const X86Subtarget &Subtarget,
8205 SelectionDAG &DAG) {
8206 SDValue Opnd0, Opnd1;
8207 unsigned NumExtracts;
8208 bool IsSubAdd;
8209 if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
8210 IsSubAdd))
8211 return SDValue();
8213 MVT VT = BV->getSimpleValueType(0);
8215 // Try to generate X86ISD::FMADDSUB node here.
8216 SDValue Opnd2;
8217 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
8218 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
8219 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
8222 // We only support ADDSUB.
8223 if (IsSubAdd)
8224 return SDValue();
8226 // There are no known X86 targets with 512-bit ADDSUB instructions!
8227 // Convert to blend(fsub,fadd).
8228 if (VT.is512BitVector()) {
8229 SmallVector<int> Mask;
8230 for (int I = 0, E = VT.getVectorNumElements(); I != E; I += 2) {
8231 Mask.push_back(I);
8232 Mask.push_back(I + E + 1);
8234 SDValue Sub = DAG.getNode(ISD::FSUB, DL, VT, Opnd0, Opnd1);
8235 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, Opnd0, Opnd1);
8236 return DAG.getVectorShuffle(VT, DL, Sub, Add, Mask);
8239 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
8242 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
8243 unsigned &HOpcode, SDValue &V0, SDValue &V1) {
8244 // Initialize outputs to known values.
8245 MVT VT = BV->getSimpleValueType(0);
8246 HOpcode = ISD::DELETED_NODE;
8247 V0 = DAG.getUNDEF(VT);
8248 V1 = DAG.getUNDEF(VT);
8250 // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
8251 // half of the result is calculated independently from the 128-bit halves of
8252 // the inputs, so that makes the index-checking logic below more complicated.
8253 unsigned NumElts = VT.getVectorNumElements();
8254 unsigned GenericOpcode = ISD::DELETED_NODE;
8255 unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
8256 unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
8257 unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
8258 for (unsigned i = 0; i != Num128BitChunks; ++i) {
8259 for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
8260 // Ignore undef elements.
8261 SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
8262 if (Op.isUndef())
8263 continue;
8265 // If there's an opcode mismatch, we're done.
8266 if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
8267 return false;
8269 // Initialize horizontal opcode.
8270 if (HOpcode == ISD::DELETED_NODE) {
8271 GenericOpcode = Op.getOpcode();
8272 switch (GenericOpcode) {
8273 // clang-format off
8274 case ISD::ADD: HOpcode = X86ISD::HADD; break;
8275 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
8276 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
8277 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
8278 default: return false;
8279 // clang-format on
8283 SDValue Op0 = Op.getOperand(0);
8284 SDValue Op1 = Op.getOperand(1);
8285 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8286 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8287 Op0.getOperand(0) != Op1.getOperand(0) ||
8288 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8289 !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
8290 return false;
8292 // The source vector is chosen based on which 64-bit half of the
8293 // destination vector is being calculated.
8294 if (j < NumEltsIn64Bits) {
8295 if (V0.isUndef())
8296 V0 = Op0.getOperand(0);
8297 } else {
8298 if (V1.isUndef())
8299 V1 = Op0.getOperand(0);
8302 SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
8303 if (SourceVec != Op0.getOperand(0))
8304 return false;
8306 // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
8307 unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
8308 unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
8309 unsigned ExpectedIndex = i * NumEltsIn128Bits +
8310 (j % NumEltsIn64Bits) * 2;
8311 if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
8312 continue;
8314 // If this is not a commutative op, this does not match.
8315 if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
8316 return false;
8318 // Addition is commutative, so try swapping the extract indexes.
8319 // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
8320 if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
8321 continue;
8323 // Extract indexes do not match horizontal requirement.
8324 return false;
8327 // We matched. Opcode and operands are returned by reference as arguments.
8328 return true;
8331 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
8332 const SDLoc &DL, SelectionDAG &DAG,
8333 unsigned HOpcode, SDValue V0, SDValue V1) {
8334 // If either input vector is not the same size as the build vector,
8335 // extract/insert the low bits to the correct size.
8336 // This is free (examples: zmm --> xmm, xmm --> ymm).
8337 MVT VT = BV->getSimpleValueType(0);
8338 unsigned Width = VT.getSizeInBits();
8339 if (V0.getValueSizeInBits() > Width)
8340 V0 = extractSubVector(V0, 0, DAG, DL, Width);
8341 else if (V0.getValueSizeInBits() < Width)
8342 V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, DL, Width);
8344 if (V1.getValueSizeInBits() > Width)
8345 V1 = extractSubVector(V1, 0, DAG, DL, Width);
8346 else if (V1.getValueSizeInBits() < Width)
8347 V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, DL, Width);
8349 unsigned NumElts = VT.getVectorNumElements();
8350 APInt DemandedElts = APInt::getAllOnes(NumElts);
8351 for (unsigned i = 0; i != NumElts; ++i)
8352 if (BV->getOperand(i).isUndef())
8353 DemandedElts.clearBit(i);
8355 // If we don't need the upper xmm, then perform as a xmm hop.
8356 unsigned HalfNumElts = NumElts / 2;
8357 if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
8358 MVT HalfVT = VT.getHalfNumVectorElementsVT();
8359 V0 = extractSubVector(V0, 0, DAG, DL, 128);
8360 V1 = extractSubVector(V1, 0, DAG, DL, 128);
8361 SDValue Half = DAG.getNode(HOpcode, DL, HalfVT, V0, V1);
8362 return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, DL, 256);
8365 return DAG.getNode(HOpcode, DL, VT, V0, V1);
8368 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
8369 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV, const SDLoc &DL,
8370 const X86Subtarget &Subtarget,
8371 SelectionDAG &DAG) {
8372 // We need at least 2 non-undef elements to make this worthwhile by default.
8373 unsigned NumNonUndefs =
8374 count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
8375 if (NumNonUndefs < 2)
8376 return SDValue();
8378 // There are 4 sets of horizontal math operations distinguished by type:
8379 // int/FP at 128-bit/256-bit. Each type was introduced with a different
8380 // subtarget feature. Try to match those "native" patterns first.
8381 MVT VT = BV->getSimpleValueType(0);
8382 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
8383 ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
8384 ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
8385 ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
8386 unsigned HOpcode;
8387 SDValue V0, V1;
8388 if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8389 return getHopForBuildVector(BV, DL, DAG, HOpcode, V0, V1);
8392 // Try harder to match 256-bit ops by using extract/concat.
8393 if (!Subtarget.hasAVX() || !VT.is256BitVector())
8394 return SDValue();
8396 // Count the number of UNDEF operands in the build_vector in input.
8397 unsigned NumElts = VT.getVectorNumElements();
8398 unsigned Half = NumElts / 2;
8399 unsigned NumUndefsLO = 0;
8400 unsigned NumUndefsHI = 0;
8401 for (unsigned i = 0, e = Half; i != e; ++i)
8402 if (BV->getOperand(i)->isUndef())
8403 NumUndefsLO++;
8405 for (unsigned i = Half, e = NumElts; i != e; ++i)
8406 if (BV->getOperand(i)->isUndef())
8407 NumUndefsHI++;
8409 SDValue InVec0, InVec1;
8410 if (VT == MVT::v8i32 || VT == MVT::v16i16) {
8411 SDValue InVec2, InVec3;
8412 unsigned X86Opcode;
8413 bool CanFold = true;
8415 if (isHorizontalBinOpPart(BV, ISD::ADD, DL, DAG, 0, Half, InVec0, InVec1) &&
8416 isHorizontalBinOpPart(BV, ISD::ADD, DL, DAG, Half, NumElts, InVec2,
8417 InVec3) &&
8418 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8419 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8420 X86Opcode = X86ISD::HADD;
8421 else if (isHorizontalBinOpPart(BV, ISD::SUB, DL, DAG, 0, Half, InVec0,
8422 InVec1) &&
8423 isHorizontalBinOpPart(BV, ISD::SUB, DL, DAG, Half, NumElts, InVec2,
8424 InVec3) &&
8425 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8426 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8427 X86Opcode = X86ISD::HSUB;
8428 else
8429 CanFold = false;
8431 if (CanFold) {
8432 // Do not try to expand this build_vector into a pair of horizontal
8433 // add/sub if we can emit a pair of scalar add/sub.
8434 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8435 return SDValue();
8437 // Convert this build_vector into a pair of horizontal binops followed by
8438 // a concat vector. We must adjust the outputs from the partial horizontal
8439 // matching calls above to account for undefined vector halves.
8440 SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
8441 SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
8442 assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
8443 bool isUndefLO = NumUndefsLO == Half;
8444 bool isUndefHI = NumUndefsHI == Half;
8445 return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
8446 isUndefHI);
8450 if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
8451 VT == MVT::v16i16) {
8452 unsigned X86Opcode;
8453 if (isHorizontalBinOpPart(BV, ISD::ADD, DL, DAG, 0, NumElts, InVec0,
8454 InVec1))
8455 X86Opcode = X86ISD::HADD;
8456 else if (isHorizontalBinOpPart(BV, ISD::SUB, DL, DAG, 0, NumElts, InVec0,
8457 InVec1))
8458 X86Opcode = X86ISD::HSUB;
8459 else if (isHorizontalBinOpPart(BV, ISD::FADD, DL, DAG, 0, NumElts, InVec0,
8460 InVec1))
8461 X86Opcode = X86ISD::FHADD;
8462 else if (isHorizontalBinOpPart(BV, ISD::FSUB, DL, DAG, 0, NumElts, InVec0,
8463 InVec1))
8464 X86Opcode = X86ISD::FHSUB;
8465 else
8466 return SDValue();
8468 // Don't try to expand this build_vector into a pair of horizontal add/sub
8469 // if we can simply emit a pair of scalar add/sub.
8470 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8471 return SDValue();
8473 // Convert this build_vector into two horizontal add/sub followed by
8474 // a concat vector.
8475 bool isUndefLO = NumUndefsLO == Half;
8476 bool isUndefHI = NumUndefsHI == Half;
8477 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
8478 isUndefLO, isUndefHI);
8481 return SDValue();
8484 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
8485 SelectionDAG &DAG);
8487 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
8488 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8489 /// just apply the bit to the vectors.
8490 /// NOTE: Its not in our interest to start make a general purpose vectorizer
8491 /// from this, but enough scalar bit operations are created from the later
8492 /// legalization + scalarization stages to need basic support.
8493 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op, const SDLoc &DL,
8494 const X86Subtarget &Subtarget,
8495 SelectionDAG &DAG) {
8496 MVT VT = Op->getSimpleValueType(0);
8497 unsigned NumElems = VT.getVectorNumElements();
8498 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8500 // Check that all elements have the same opcode.
8501 // TODO: Should we allow UNDEFS and if so how many?
8502 unsigned Opcode = Op->getOperand(0).getOpcode();
8503 for (unsigned i = 1; i < NumElems; ++i)
8504 if (Opcode != Op->getOperand(i).getOpcode())
8505 return SDValue();
8507 // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
8508 bool IsShift = false;
8509 switch (Opcode) {
8510 default:
8511 return SDValue();
8512 case ISD::SHL:
8513 case ISD::SRL:
8514 case ISD::SRA:
8515 IsShift = true;
8516 break;
8517 case ISD::AND:
8518 case ISD::XOR:
8519 case ISD::OR:
8520 // Don't do this if the buildvector is a splat - we'd replace one
8521 // constant with an entire vector.
8522 if (Op->getSplatValue())
8523 return SDValue();
8524 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8525 return SDValue();
8526 break;
8529 SmallVector<SDValue, 4> LHSElts, RHSElts;
8530 for (SDValue Elt : Op->ops()) {
8531 SDValue LHS = Elt.getOperand(0);
8532 SDValue RHS = Elt.getOperand(1);
8534 // We expect the canonicalized RHS operand to be the constant.
8535 if (!isa<ConstantSDNode>(RHS))
8536 return SDValue();
8538 // Extend shift amounts.
8539 if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
8540 if (!IsShift)
8541 return SDValue();
8542 RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
8545 LHSElts.push_back(LHS);
8546 RHSElts.push_back(RHS);
8549 // Limit to shifts by uniform immediates.
8550 // TODO: Only accept vXi8/vXi64 special cases?
8551 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
8552 if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
8553 return SDValue();
8555 SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
8556 SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
8557 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
8559 if (!IsShift)
8560 return Res;
8562 // Immediately lower the shift to ensure the constant build vector doesn't
8563 // get converted to a constant pool before the shift is lowered.
8564 return LowerShift(Res, Subtarget, DAG);
8567 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
8568 /// functionality to do this, so it's all zeros, all ones, or some derivation
8569 /// that is cheap to calculate.
8570 static SDValue materializeVectorConstant(SDValue Op, const SDLoc &DL,
8571 SelectionDAG &DAG,
8572 const X86Subtarget &Subtarget) {
8573 MVT VT = Op.getSimpleValueType();
8575 // Vectors containing all zeros can be matched by pxor and xorps.
8576 if (ISD::isBuildVectorAllZeros(Op.getNode()))
8577 return Op;
8579 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
8580 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
8581 // vpcmpeqd on 256-bit vectors.
8582 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
8583 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
8584 return Op;
8586 return getOnesVector(VT, DAG, DL);
8589 return SDValue();
8592 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
8593 /// from a vector of source values and a vector of extraction indices.
8594 /// The vectors might be manipulated to match the type of the permute op.
8595 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
8596 const SDLoc &DL, SelectionDAG &DAG,
8597 const X86Subtarget &Subtarget) {
8598 MVT ShuffleVT = VT;
8599 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8600 unsigned NumElts = VT.getVectorNumElements();
8601 unsigned SizeInBits = VT.getSizeInBits();
8603 // Adjust IndicesVec to match VT size.
8604 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
8605 "Illegal variable permute mask size");
8606 if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
8607 // Narrow/widen the indices vector to the correct size.
8608 if (IndicesVec.getValueSizeInBits() > SizeInBits)
8609 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
8610 NumElts * VT.getScalarSizeInBits());
8611 else if (IndicesVec.getValueSizeInBits() < SizeInBits)
8612 IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
8613 SDLoc(IndicesVec), SizeInBits);
8614 // Zero-extend the index elements within the vector.
8615 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
8616 IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
8617 IndicesVT, IndicesVec);
8619 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
8621 // Handle SrcVec that don't match VT type.
8622 if (SrcVec.getValueSizeInBits() != SizeInBits) {
8623 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
8624 // Handle larger SrcVec by treating it as a larger permute.
8625 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
8626 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
8627 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8628 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
8629 Subtarget, DAG, SDLoc(IndicesVec));
8630 SDValue NewSrcVec =
8631 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
8632 if (NewSrcVec)
8633 return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
8634 return SDValue();
8635 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
8636 // Widen smaller SrcVec to match VT.
8637 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
8638 } else
8639 return SDValue();
8642 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
8643 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
8644 EVT SrcVT = Idx.getValueType();
8645 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
8646 uint64_t IndexScale = 0;
8647 uint64_t IndexOffset = 0;
8649 // If we're scaling a smaller permute op, then we need to repeat the
8650 // indices, scaling and offsetting them as well.
8651 // e.g. v4i32 -> v16i8 (Scale = 4)
8652 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
8653 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
8654 for (uint64_t i = 0; i != Scale; ++i) {
8655 IndexScale |= Scale << (i * NumDstBits);
8656 IndexOffset |= i << (i * NumDstBits);
8659 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
8660 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
8661 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
8662 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
8663 return Idx;
8666 unsigned Opcode = 0;
8667 switch (VT.SimpleTy) {
8668 default:
8669 break;
8670 case MVT::v16i8:
8671 if (Subtarget.hasSSSE3())
8672 Opcode = X86ISD::PSHUFB;
8673 break;
8674 case MVT::v8i16:
8675 if (Subtarget.hasVLX() && Subtarget.hasBWI())
8676 Opcode = X86ISD::VPERMV;
8677 else if (Subtarget.hasSSSE3()) {
8678 Opcode = X86ISD::PSHUFB;
8679 ShuffleVT = MVT::v16i8;
8681 break;
8682 case MVT::v4f32:
8683 case MVT::v4i32:
8684 if (Subtarget.hasAVX()) {
8685 Opcode = X86ISD::VPERMILPV;
8686 ShuffleVT = MVT::v4f32;
8687 } else if (Subtarget.hasSSSE3()) {
8688 Opcode = X86ISD::PSHUFB;
8689 ShuffleVT = MVT::v16i8;
8691 break;
8692 case MVT::v2f64:
8693 case MVT::v2i64:
8694 if (Subtarget.hasAVX()) {
8695 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
8696 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8697 Opcode = X86ISD::VPERMILPV;
8698 ShuffleVT = MVT::v2f64;
8699 } else if (Subtarget.hasSSE41()) {
8700 // SSE41 can compare v2i64 - select between indices 0 and 1.
8701 return DAG.getSelectCC(
8702 DL, IndicesVec,
8703 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
8704 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
8705 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
8706 ISD::CondCode::SETEQ);
8708 break;
8709 case MVT::v32i8:
8710 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
8711 Opcode = X86ISD::VPERMV;
8712 else if (Subtarget.hasXOP()) {
8713 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
8714 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
8715 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
8716 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
8717 return DAG.getNode(
8718 ISD::CONCAT_VECTORS, DL, VT,
8719 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
8720 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
8721 } else if (Subtarget.hasAVX()) {
8722 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
8723 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
8724 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
8725 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
8726 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
8727 ArrayRef<SDValue> Ops) {
8728 // Permute Lo and Hi and then select based on index range.
8729 // This works as SHUFB uses bits[3:0] to permute elements and we don't
8730 // care about the bit[7] as its just an index vector.
8731 SDValue Idx = Ops[2];
8732 EVT VT = Idx.getValueType();
8733 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
8734 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
8735 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
8736 ISD::CondCode::SETGT);
8738 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
8739 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
8740 PSHUFBBuilder);
8742 break;
8743 case MVT::v16i16:
8744 if (Subtarget.hasVLX() && Subtarget.hasBWI())
8745 Opcode = X86ISD::VPERMV;
8746 else if (Subtarget.hasAVX()) {
8747 // Scale to v32i8 and perform as v32i8.
8748 IndicesVec = ScaleIndices(IndicesVec, 2);
8749 return DAG.getBitcast(
8750 VT, createVariablePermute(
8751 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
8752 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
8754 break;
8755 case MVT::v8f32:
8756 case MVT::v8i32:
8757 if (Subtarget.hasAVX2())
8758 Opcode = X86ISD::VPERMV;
8759 else if (Subtarget.hasAVX()) {
8760 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
8761 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8762 {0, 1, 2, 3, 0, 1, 2, 3});
8763 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8764 {4, 5, 6, 7, 4, 5, 6, 7});
8765 if (Subtarget.hasXOP())
8766 return DAG.getBitcast(
8767 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
8768 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
8769 // Permute Lo and Hi and then select based on index range.
8770 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
8771 SDValue Res = DAG.getSelectCC(
8772 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
8773 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
8774 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
8775 ISD::CondCode::SETGT);
8776 return DAG.getBitcast(VT, Res);
8778 break;
8779 case MVT::v4i64:
8780 case MVT::v4f64:
8781 if (Subtarget.hasAVX512()) {
8782 if (!Subtarget.hasVLX()) {
8783 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
8784 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
8785 SDLoc(SrcVec));
8786 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
8787 DAG, SDLoc(IndicesVec));
8788 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
8789 DAG, Subtarget);
8790 return extract256BitVector(Res, 0, DAG, DL);
8792 Opcode = X86ISD::VPERMV;
8793 } else if (Subtarget.hasAVX()) {
8794 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
8795 SDValue LoLo =
8796 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
8797 SDValue HiHi =
8798 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
8799 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
8800 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8801 if (Subtarget.hasXOP())
8802 return DAG.getBitcast(
8803 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
8804 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
8805 // Permute Lo and Hi and then select based on index range.
8806 // This works as VPERMILPD only uses index bit[1] to permute elements.
8807 SDValue Res = DAG.getSelectCC(
8808 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
8809 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
8810 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
8811 ISD::CondCode::SETGT);
8812 return DAG.getBitcast(VT, Res);
8814 break;
8815 case MVT::v64i8:
8816 if (Subtarget.hasVBMI())
8817 Opcode = X86ISD::VPERMV;
8818 break;
8819 case MVT::v32i16:
8820 if (Subtarget.hasBWI())
8821 Opcode = X86ISD::VPERMV;
8822 break;
8823 case MVT::v16f32:
8824 case MVT::v16i32:
8825 case MVT::v8f64:
8826 case MVT::v8i64:
8827 if (Subtarget.hasAVX512())
8828 Opcode = X86ISD::VPERMV;
8829 break;
8831 if (!Opcode)
8832 return SDValue();
8834 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
8835 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
8836 "Illegal variable permute shuffle type");
8838 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
8839 if (Scale > 1)
8840 IndicesVec = ScaleIndices(IndicesVec, Scale);
8842 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
8843 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
8845 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
8846 SDValue Res = Opcode == X86ISD::VPERMV
8847 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
8848 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
8849 return DAG.getBitcast(VT, Res);
8852 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
8853 // reasoned to be a permutation of a vector by indices in a non-constant vector.
8854 // (build_vector (extract_elt V, (extract_elt I, 0)),
8855 // (extract_elt V, (extract_elt I, 1)),
8856 // ...
8857 // ->
8858 // (vpermv I, V)
8860 // TODO: Handle undefs
8861 // TODO: Utilize pshufb and zero mask blending to support more efficient
8862 // construction of vectors with constant-0 elements.
8863 static SDValue
8864 LowerBUILD_VECTORAsVariablePermute(SDValue V, const SDLoc &DL,
8865 SelectionDAG &DAG,
8866 const X86Subtarget &Subtarget) {
8867 SDValue SrcVec, IndicesVec;
8868 // Check for a match of the permute source vector and permute index elements.
8869 // This is done by checking that the i-th build_vector operand is of the form:
8870 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
8871 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
8872 SDValue Op = V.getOperand(Idx);
8873 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8874 return SDValue();
8876 // If this is the first extract encountered in V, set the source vector,
8877 // otherwise verify the extract is from the previously defined source
8878 // vector.
8879 if (!SrcVec)
8880 SrcVec = Op.getOperand(0);
8881 else if (SrcVec != Op.getOperand(0))
8882 return SDValue();
8883 SDValue ExtractedIndex = Op->getOperand(1);
8884 // Peek through extends.
8885 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
8886 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
8887 ExtractedIndex = ExtractedIndex.getOperand(0);
8888 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8889 return SDValue();
8891 // If this is the first extract from the index vector candidate, set the
8892 // indices vector, otherwise verify the extract is from the previously
8893 // defined indices vector.
8894 if (!IndicesVec)
8895 IndicesVec = ExtractedIndex.getOperand(0);
8896 else if (IndicesVec != ExtractedIndex.getOperand(0))
8897 return SDValue();
8899 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
8900 if (!PermIdx || PermIdx->getAPIntValue() != Idx)
8901 return SDValue();
8904 MVT VT = V.getSimpleValueType();
8905 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
8908 SDValue
8909 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
8910 SDLoc dl(Op);
8912 MVT VT = Op.getSimpleValueType();
8913 MVT EltVT = VT.getVectorElementType();
8914 MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
8915 unsigned NumElems = Op.getNumOperands();
8917 // Generate vectors for predicate vectors.
8918 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
8919 return LowerBUILD_VECTORvXi1(Op, dl, DAG, Subtarget);
8921 if (VT.getVectorElementType() == MVT::bf16 &&
8922 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16()))
8923 return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
8925 if (SDValue VectorCst = materializeVectorConstant(Op, dl, DAG, Subtarget))
8926 return VectorCst;
8928 unsigned EVTBits = EltVT.getSizeInBits();
8929 APInt UndefMask = APInt::getZero(NumElems);
8930 APInt FrozenUndefMask = APInt::getZero(NumElems);
8931 APInt ZeroMask = APInt::getZero(NumElems);
8932 APInt NonZeroMask = APInt::getZero(NumElems);
8933 bool IsAllConstants = true;
8934 bool OneUseFrozenUndefs = true;
8935 SmallSet<SDValue, 8> Values;
8936 unsigned NumConstants = NumElems;
8937 for (unsigned i = 0; i < NumElems; ++i) {
8938 SDValue Elt = Op.getOperand(i);
8939 if (Elt.isUndef()) {
8940 UndefMask.setBit(i);
8941 continue;
8943 if (ISD::isFreezeUndef(Elt.getNode())) {
8944 OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
8945 FrozenUndefMask.setBit(i);
8946 continue;
8948 Values.insert(Elt);
8949 if (!isIntOrFPConstant(Elt)) {
8950 IsAllConstants = false;
8951 NumConstants--;
8953 if (X86::isZeroNode(Elt)) {
8954 ZeroMask.setBit(i);
8955 } else {
8956 NonZeroMask.setBit(i);
8960 // All undef vector. Return an UNDEF.
8961 if (UndefMask.isAllOnes())
8962 return DAG.getUNDEF(VT);
8964 // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
8965 if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
8966 return DAG.getFreeze(DAG.getUNDEF(VT));
8968 // All undef/freeze(undef)/zero vector. Return a zero vector.
8969 if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
8970 return getZeroVector(VT, Subtarget, DAG, dl);
8972 // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
8973 // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
8974 // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
8975 // and blend the FREEZE-UNDEF operands back in.
8976 // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
8977 if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
8978 NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
8979 SmallVector<int, 16> BlendMask(NumElems, -1);
8980 SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
8981 for (unsigned i = 0; i < NumElems; ++i) {
8982 if (UndefMask[i]) {
8983 BlendMask[i] = -1;
8984 continue;
8986 BlendMask[i] = i;
8987 if (!FrozenUndefMask[i])
8988 Elts[i] = Op.getOperand(i);
8989 else
8990 BlendMask[i] += NumElems;
8992 SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
8993 SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
8994 SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
8995 return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
8998 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9000 // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
9001 // be better off lowering to a smaller build vector and padding with
9002 // undef/zero.
9003 if ((VT.is256BitVector() || VT.is512BitVector()) &&
9004 !isFoldableUseOfShuffle(BV)) {
9005 unsigned UpperElems = NumElems / 2;
9006 APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
9007 unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
9008 if (NumUpperUndefsOrZeros >= UpperElems) {
9009 if (VT.is512BitVector() &&
9010 NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
9011 UpperElems = NumElems - (NumElems / 4);
9012 // If freeze(undef) is in any upper elements, force to zero.
9013 bool UndefUpper = UndefMask.countl_one() >= UpperElems;
9014 MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
9015 SDValue NewBV =
9016 DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
9017 return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
9021 if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, dl, Subtarget, DAG))
9022 return AddSub;
9023 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, dl, Subtarget, DAG))
9024 return HorizontalOp;
9025 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, dl, Subtarget, DAG))
9026 return Broadcast;
9027 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, dl, Subtarget, DAG))
9028 return BitOp;
9030 unsigned NumZero = ZeroMask.popcount();
9031 unsigned NumNonZero = NonZeroMask.popcount();
9033 // If we are inserting one variable into a vector of non-zero constants, try
9034 // to avoid loading each constant element as a scalar. Load the constants as a
9035 // vector and then insert the variable scalar element. If insertion is not
9036 // supported, fall back to a shuffle to get the scalar blended with the
9037 // constants. Insertion into a zero vector is handled as a special-case
9038 // somewhere below here.
9039 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9040 FrozenUndefMask.isZero() &&
9041 (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
9042 isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
9043 // Create an all-constant vector. The variable element in the old
9044 // build vector is replaced by undef in the constant vector. Save the
9045 // variable scalar element and its index for use in the insertelement.
9046 LLVMContext &Context = *DAG.getContext();
9047 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9048 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9049 SDValue VarElt;
9050 SDValue InsIndex;
9051 for (unsigned i = 0; i != NumElems; ++i) {
9052 SDValue Elt = Op.getOperand(i);
9053 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9054 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9055 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9056 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9057 else if (!Elt.isUndef()) {
9058 assert(!VarElt.getNode() && !InsIndex.getNode() &&
9059 "Expected one variable element in this vector");
9060 VarElt = Elt;
9061 InsIndex = DAG.getVectorIdxConstant(i, dl);
9064 Constant *CV = ConstantVector::get(ConstVecOps);
9065 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9067 // The constants we just created may not be legal (eg, floating point). We
9068 // must lower the vector right here because we can not guarantee that we'll
9069 // legalize it before loading it. This is also why we could not just create
9070 // a new build vector here. If the build vector contains illegal constants,
9071 // it could get split back up into a series of insert elements.
9072 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9073 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9074 MachineFunction &MF = DAG.getMachineFunction();
9075 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9076 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9077 unsigned InsertC = InsIndex->getAsZExtVal();
9078 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9079 if (InsertC < NumEltsInLow128Bits)
9080 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9082 // There's no good way to insert into the high elements of a >128-bit
9083 // vector, so use shuffles to avoid an extract/insert sequence.
9084 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
9085 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
9086 SmallVector<int, 8> ShuffleMask;
9087 unsigned NumElts = VT.getVectorNumElements();
9088 for (unsigned i = 0; i != NumElts; ++i)
9089 ShuffleMask.push_back(i == InsertC ? NumElts : i);
9090 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9091 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9094 // Special case for single non-zero, non-undef, element.
9095 if (NumNonZero == 1) {
9096 unsigned Idx = NonZeroMask.countr_zero();
9097 SDValue Item = Op.getOperand(Idx);
9099 // If we have a constant or non-constant insertion into the low element of
9100 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9101 // the rest of the elements. This will be matched as movd/movq/movss/movsd
9102 // depending on what the source datatype is.
9103 if (Idx == 0) {
9104 if (NumZero == 0)
9105 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9107 if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
9108 EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
9109 (EltVT == MVT::i16 && Subtarget.hasFP16())) {
9110 assert((VT.is128BitVector() || VT.is256BitVector() ||
9111 VT.is512BitVector()) &&
9112 "Expected an SSE value type!");
9113 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9114 // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
9115 // zero vector.
9116 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9119 // We can't directly insert an i8 or i16 into a vector, so zero extend
9120 // it to i32 first.
9121 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9122 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9123 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
9124 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9125 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9126 return DAG.getBitcast(VT, Item);
9130 // Is it a vector logical left shift?
9131 if (NumElems == 2 && Idx == 1 &&
9132 X86::isZeroNode(Op.getOperand(0)) &&
9133 !X86::isZeroNode(Op.getOperand(1))) {
9134 unsigned NumBits = VT.getSizeInBits();
9135 return getVShift(true, VT,
9136 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9137 VT, Op.getOperand(1)),
9138 NumBits/2, DAG, *this, dl);
9141 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9142 return SDValue();
9144 // Otherwise, if this is a vector with i32 or f32 elements, and the element
9145 // is a non-constant being inserted into an element other than the low one,
9146 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
9147 // movd/movss) to move this into the low element, then shuffle it into
9148 // place.
9149 if (EVTBits == 32) {
9150 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9151 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9155 // Splat is obviously ok. Let legalizer expand it to a shuffle.
9156 if (Values.size() == 1) {
9157 if (EVTBits == 32) {
9158 // Instead of a shuffle like this:
9159 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9160 // Check if it's possible to issue this instead.
9161 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9162 unsigned Idx = NonZeroMask.countr_zero();
9163 SDValue Item = Op.getOperand(Idx);
9164 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9165 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9167 return SDValue();
9170 // A vector full of immediates; various special cases are already
9171 // handled, so this is best done with a single constant-pool load.
9172 if (IsAllConstants)
9173 return SDValue();
9175 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, dl, DAG, Subtarget))
9176 return V;
9178 // See if we can use a vector load to get all of the elements.
9180 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
9181 if (SDValue LD =
9182 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9183 return LD;
9186 // If this is a splat of pairs of 32-bit elements, we can use a narrower
9187 // build_vector and broadcast it.
9188 // TODO: We could probably generalize this more.
9189 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9190 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9191 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9192 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9193 // Make sure all the even/odd operands match.
9194 for (unsigned i = 2; i != NumElems; ++i)
9195 if (Ops[i % 2] != Op.getOperand(i))
9196 return false;
9197 return true;
9199 if (CanSplat(Op, NumElems, Ops)) {
9200 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9201 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9202 // Create a new build vector and cast to v2i64/v2f64.
9203 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9204 DAG.getBuildVector(NarrowVT, dl, Ops));
9205 // Broadcast from v2i64/v2f64 and cast to final VT.
9206 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
9207 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9208 NewBV));
9212 // For AVX-length vectors, build the individual 128-bit pieces and use
9213 // shuffles to put them in place.
9214 if (VT.getSizeInBits() > 128) {
9215 MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
9217 // Build both the lower and upper subvector.
9218 SDValue Lower =
9219 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9220 SDValue Upper = DAG.getBuildVector(
9221 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9223 // Recreate the wider vector with the lower and upper part.
9224 return concatSubVectors(Lower, Upper, DAG, dl);
9227 // Let legalizer expand 2-wide build_vectors.
9228 if (EVTBits == 64) {
9229 if (NumNonZero == 1) {
9230 // One half is zero or undef.
9231 unsigned Idx = NonZeroMask.countr_zero();
9232 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9233 Op.getOperand(Idx));
9234 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9236 return SDValue();
9239 // If element VT is < 32 bits, convert it to inserts into a zero vector.
9240 if (EVTBits == 8 && NumElems == 16)
9241 if (SDValue V = LowerBuildVectorv16i8(Op, dl, NonZeroMask, NumNonZero,
9242 NumZero, DAG, Subtarget))
9243 return V;
9245 if (EltVT == MVT::i16 && NumElems == 8)
9246 if (SDValue V = LowerBuildVectorv8i16(Op, dl, NonZeroMask, NumNonZero,
9247 NumZero, DAG, Subtarget))
9248 return V;
9250 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9251 if (EVTBits == 32 && NumElems == 4)
9252 if (SDValue V = LowerBuildVectorv4x32(Op, dl, DAG, Subtarget))
9253 return V;
9255 // If element VT is == 32 bits, turn it into a number of shuffles.
9256 if (NumElems == 4 && NumZero > 0) {
9257 SmallVector<SDValue, 8> Ops(NumElems);
9258 for (unsigned i = 0; i < 4; ++i) {
9259 bool isZero = !NonZeroMask[i];
9260 if (isZero)
9261 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9262 else
9263 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9266 for (unsigned i = 0; i < 2; ++i) {
9267 switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
9268 default: llvm_unreachable("Unexpected NonZero count");
9269 case 0:
9270 Ops[i] = Ops[i*2]; // Must be a zero vector.
9271 break;
9272 case 1:
9273 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9274 break;
9275 case 2:
9276 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9277 break;
9278 case 3:
9279 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9280 break;
9284 bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
9285 bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
9286 int MaskVec[] = {
9287 Reverse1 ? 1 : 0,
9288 Reverse1 ? 0 : 1,
9289 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9290 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
9292 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9295 assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9297 // Check for a build vector from mostly shuffle plus few inserting.
9298 if (SDValue Sh = buildFromShuffleMostly(Op, dl, DAG))
9299 return Sh;
9301 // For SSE 4.1, use insertps to put the high elements into the low element.
9302 if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
9303 SDValue Result;
9304 if (!Op.getOperand(0).isUndef())
9305 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9306 else
9307 Result = DAG.getUNDEF(VT);
9309 for (unsigned i = 1; i < NumElems; ++i) {
9310 if (Op.getOperand(i).isUndef()) continue;
9311 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9312 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
9314 return Result;
9317 // Otherwise, expand into a number of unpckl*, start by extending each of
9318 // our (non-undef) elements to the full vector width with the element in the
9319 // bottom slot of the vector (which generates no code for SSE).
9320 SmallVector<SDValue, 8> Ops(NumElems);
9321 for (unsigned i = 0; i < NumElems; ++i) {
9322 if (!Op.getOperand(i).isUndef())
9323 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9324 else
9325 Ops[i] = DAG.getUNDEF(VT);
9328 // Next, we iteratively mix elements, e.g. for v4f32:
9329 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9330 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9331 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
9332 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9333 // Generate scaled UNPCKL shuffle mask.
9334 SmallVector<int, 16> Mask;
9335 for(unsigned i = 0; i != Scale; ++i)
9336 Mask.push_back(i);
9337 for (unsigned i = 0; i != Scale; ++i)
9338 Mask.push_back(NumElems+i);
9339 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9341 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9342 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9344 return Ops[0];
9347 // 256-bit AVX can use the vinsertf128 instruction
9348 // to create 256-bit vectors from two other 128-bit ones.
9349 // TODO: Detect subvector broadcast here instead of DAG combine?
9350 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9351 const X86Subtarget &Subtarget) {
9352 SDLoc dl(Op);
9353 MVT ResVT = Op.getSimpleValueType();
9355 assert((ResVT.is256BitVector() ||
9356 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
9358 unsigned NumOperands = Op.getNumOperands();
9359 unsigned NumFreezeUndef = 0;
9360 unsigned NumZero = 0;
9361 unsigned NumNonZero = 0;
9362 unsigned NonZeros = 0;
9363 for (unsigned i = 0; i != NumOperands; ++i) {
9364 SDValue SubVec = Op.getOperand(i);
9365 if (SubVec.isUndef())
9366 continue;
9367 if (ISD::isFreezeUndef(SubVec.getNode())) {
9368 // If the freeze(undef) has multiple uses then we must fold to zero.
9369 if (SubVec.hasOneUse())
9370 ++NumFreezeUndef;
9371 else
9372 ++NumZero;
9374 else if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9375 ++NumZero;
9376 else {
9377 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9378 NonZeros |= 1 << i;
9379 ++NumNonZero;
9383 // If we have more than 2 non-zeros, build each half separately.
9384 if (NumNonZero > 2) {
9385 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9386 ArrayRef<SDUse> Ops = Op->ops();
9387 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9388 Ops.slice(0, NumOperands/2));
9389 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9390 Ops.slice(NumOperands/2));
9391 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9394 // Otherwise, build it up through insert_subvectors.
9395 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9396 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
9397 : DAG.getUNDEF(ResVT));
9399 MVT SubVT = Op.getOperand(0).getSimpleValueType();
9400 unsigned NumSubElems = SubVT.getVectorNumElements();
9401 for (unsigned i = 0; i != NumOperands; ++i) {
9402 if ((NonZeros & (1 << i)) == 0)
9403 continue;
9405 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
9406 Op.getOperand(i),
9407 DAG.getIntPtrConstant(i * NumSubElems, dl));
9410 return Vec;
9413 // Returns true if the given node is a type promotion (by concatenating i1
9414 // zeros) of the result of a node that already zeros all upper bits of
9415 // k-register.
9416 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
9417 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
9418 const X86Subtarget &Subtarget,
9419 SelectionDAG & DAG) {
9420 SDLoc dl(Op);
9421 MVT ResVT = Op.getSimpleValueType();
9422 unsigned NumOperands = Op.getNumOperands();
9424 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9425 "Unexpected number of operands in CONCAT_VECTORS");
9427 uint64_t Zeros = 0;
9428 uint64_t NonZeros = 0;
9429 for (unsigned i = 0; i != NumOperands; ++i) {
9430 SDValue SubVec = Op.getOperand(i);
9431 if (SubVec.isUndef())
9432 continue;
9433 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9434 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9435 Zeros |= (uint64_t)1 << i;
9436 else
9437 NonZeros |= (uint64_t)1 << i;
9440 unsigned NumElems = ResVT.getVectorNumElements();
9442 // If we are inserting non-zero vector and there are zeros in LSBs and undef
9443 // in the MSBs we need to emit a KSHIFTL. The generic lowering to
9444 // insert_subvector will give us two kshifts.
9445 if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
9446 Log2_64(NonZeros) != NumOperands - 1) {
9447 unsigned Idx = Log2_64(NonZeros);
9448 SDValue SubVec = Op.getOperand(Idx);
9449 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9450 MVT ShiftVT = widenMaskVectorType(ResVT, Subtarget);
9451 Op = widenSubVector(ShiftVT, SubVec, false, Subtarget, DAG, dl);
9452 Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, Op,
9453 DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
9454 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
9455 DAG.getIntPtrConstant(0, dl));
9458 // If there are zero or one non-zeros we can handle this very simply.
9459 if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
9460 SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
9461 if (!NonZeros)
9462 return Vec;
9463 unsigned Idx = Log2_64(NonZeros);
9464 SDValue SubVec = Op.getOperand(Idx);
9465 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9466 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9467 DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
9470 if (NumOperands > 2) {
9471 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9472 ArrayRef<SDUse> Ops = Op->ops();
9473 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9474 Ops.slice(0, NumOperands/2));
9475 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9476 Ops.slice(NumOperands/2));
9477 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9480 assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
9482 if (ResVT.getVectorNumElements() >= 16)
9483 return Op; // The operation is legal with KUNPCK
9485 SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
9486 DAG.getUNDEF(ResVT), Op.getOperand(0),
9487 DAG.getIntPtrConstant(0, dl));
9488 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
9489 DAG.getIntPtrConstant(NumElems/2, dl));
9492 static SDValue LowerCONCAT_VECTORS(SDValue Op,
9493 const X86Subtarget &Subtarget,
9494 SelectionDAG &DAG) {
9495 MVT VT = Op.getSimpleValueType();
9496 if (VT.getVectorElementType() == MVT::i1)
9497 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
9499 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
9500 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
9501 Op.getNumOperands() == 4)));
9503 // AVX can use the vinsertf128 instruction to create 256-bit vectors
9504 // from two other 128-bit ones.
9506 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
9507 return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
9510 //===----------------------------------------------------------------------===//
9511 // Vector shuffle lowering
9513 // This is an experimental code path for lowering vector shuffles on x86. It is
9514 // designed to handle arbitrary vector shuffles and blends, gracefully
9515 // degrading performance as necessary. It works hard to recognize idiomatic
9516 // shuffles and lower them to optimal instruction patterns without leaving
9517 // a framework that allows reasonably efficient handling of all vector shuffle
9518 // patterns.
9519 //===----------------------------------------------------------------------===//
9521 /// Tiny helper function to identify a no-op mask.
9523 /// This is a somewhat boring predicate function. It checks whether the mask
9524 /// array input, which is assumed to be a single-input shuffle mask of the kind
9525 /// used by the X86 shuffle instructions (not a fully general
9526 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
9527 /// in-place shuffle are 'no-op's.
9528 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
9529 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9530 assert(Mask[i] >= -1 && "Out of bound mask element!");
9531 if (Mask[i] >= 0 && Mask[i] != i)
9532 return false;
9534 return true;
9537 /// Test whether there are elements crossing LaneSizeInBits lanes in this
9538 /// shuffle mask.
9540 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
9541 /// and we routinely test for these.
9542 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
9543 unsigned ScalarSizeInBits,
9544 ArrayRef<int> Mask) {
9545 assert(LaneSizeInBits && ScalarSizeInBits &&
9546 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
9547 "Illegal shuffle lane size");
9548 int LaneSize = LaneSizeInBits / ScalarSizeInBits;
9549 int Size = Mask.size();
9550 for (int i = 0; i < Size; ++i)
9551 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9552 return true;
9553 return false;
9556 /// Test whether there are elements crossing 128-bit lanes in this
9557 /// shuffle mask.
9558 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
9559 return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
9562 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
9563 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
9564 /// better support 'repeated mask + lane permute' style shuffles.
9565 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
9566 unsigned ScalarSizeInBits,
9567 ArrayRef<int> Mask) {
9568 assert(LaneSizeInBits && ScalarSizeInBits &&
9569 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
9570 "Illegal shuffle lane size");
9571 int NumElts = Mask.size();
9572 int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
9573 int NumLanes = NumElts / NumEltsPerLane;
9574 if (NumLanes > 1) {
9575 for (int i = 0; i != NumLanes; ++i) {
9576 int SrcLane = -1;
9577 for (int j = 0; j != NumEltsPerLane; ++j) {
9578 int M = Mask[(i * NumEltsPerLane) + j];
9579 if (M < 0)
9580 continue;
9581 int Lane = (M % NumElts) / NumEltsPerLane;
9582 if (SrcLane >= 0 && SrcLane != Lane)
9583 return true;
9584 SrcLane = Lane;
9588 return false;
9591 /// Test whether a shuffle mask is equivalent within each sub-lane.
9593 /// This checks a shuffle mask to see if it is performing the same
9594 /// lane-relative shuffle in each sub-lane. This trivially implies
9595 /// that it is also not lane-crossing. It may however involve a blend from the
9596 /// same lane of a second vector.
9598 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
9599 /// non-trivial to compute in the face of undef lanes. The representation is
9600 /// suitable for use with existing 128-bit shuffles as entries from the second
9601 /// vector have been remapped to [LaneSize, 2*LaneSize).
9602 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
9603 ArrayRef<int> Mask,
9604 SmallVectorImpl<int> &RepeatedMask) {
9605 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9606 RepeatedMask.assign(LaneSize, -1);
9607 int Size = Mask.size();
9608 for (int i = 0; i < Size; ++i) {
9609 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
9610 if (Mask[i] < 0)
9611 continue;
9612 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9613 // This entry crosses lanes, so there is no way to model this shuffle.
9614 return false;
9616 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9617 // Adjust second vector indices to start at LaneSize instead of Size.
9618 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
9619 : Mask[i] % LaneSize + LaneSize;
9620 if (RepeatedMask[i % LaneSize] < 0)
9621 // This is the first non-undef entry in this slot of a 128-bit lane.
9622 RepeatedMask[i % LaneSize] = LocalM;
9623 else if (RepeatedMask[i % LaneSize] != LocalM)
9624 // Found a mismatch with the repeated mask.
9625 return false;
9627 return true;
9630 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
9631 static bool
9632 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9633 SmallVectorImpl<int> &RepeatedMask) {
9634 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9637 static bool
9638 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
9639 SmallVector<int, 32> RepeatedMask;
9640 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9643 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
9644 static bool
9645 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9646 SmallVectorImpl<int> &RepeatedMask) {
9647 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
9650 /// Test whether a target shuffle mask is equivalent within each sub-lane.
9651 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
9652 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
9653 unsigned EltSizeInBits,
9654 ArrayRef<int> Mask,
9655 SmallVectorImpl<int> &RepeatedMask) {
9656 int LaneSize = LaneSizeInBits / EltSizeInBits;
9657 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
9658 int Size = Mask.size();
9659 for (int i = 0; i < Size; ++i) {
9660 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
9661 if (Mask[i] == SM_SentinelUndef)
9662 continue;
9663 if (Mask[i] == SM_SentinelZero) {
9664 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
9665 return false;
9666 RepeatedMask[i % LaneSize] = SM_SentinelZero;
9667 continue;
9669 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9670 // This entry crosses lanes, so there is no way to model this shuffle.
9671 return false;
9673 // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
9674 // later vector indices to start at multiples of LaneSize instead of Size.
9675 int LaneM = Mask[i] / Size;
9676 int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
9677 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
9678 // This is the first non-undef entry in this slot of a 128-bit lane.
9679 RepeatedMask[i % LaneSize] = LocalM;
9680 else if (RepeatedMask[i % LaneSize] != LocalM)
9681 // Found a mismatch with the repeated mask.
9682 return false;
9684 return true;
9687 /// Test whether a target shuffle mask is equivalent within each sub-lane.
9688 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
9689 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
9690 ArrayRef<int> Mask,
9691 SmallVectorImpl<int> &RepeatedMask) {
9692 return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
9693 Mask, RepeatedMask);
9696 /// Checks whether the vector elements referenced by two shuffle masks are
9697 /// equivalent.
9698 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
9699 int Idx, int ExpectedIdx) {
9700 assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
9701 ExpectedIdx < MaskSize && "Out of range element index");
9702 if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
9703 return false;
9705 switch (Op.getOpcode()) {
9706 case ISD::BUILD_VECTOR:
9707 // If the values are build vectors, we can look through them to find
9708 // equivalent inputs that make the shuffles equivalent.
9709 // TODO: Handle MaskSize != Op.getNumOperands()?
9710 if (MaskSize == (int)Op.getNumOperands() &&
9711 MaskSize == (int)ExpectedOp.getNumOperands())
9712 return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
9713 break;
9714 case X86ISD::VBROADCAST:
9715 case X86ISD::VBROADCAST_LOAD:
9716 // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
9717 return (Op == ExpectedOp &&
9718 (int)Op.getValueType().getVectorNumElements() == MaskSize);
9719 case X86ISD::HADD:
9720 case X86ISD::HSUB:
9721 case X86ISD::FHADD:
9722 case X86ISD::FHSUB:
9723 case X86ISD::PACKSS:
9724 case X86ISD::PACKUS:
9725 // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
9726 // TODO: Handle MaskSize != NumElts?
9727 // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
9728 if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
9729 MVT VT = Op.getSimpleValueType();
9730 int NumElts = VT.getVectorNumElements();
9731 if (MaskSize == NumElts) {
9732 int NumLanes = VT.getSizeInBits() / 128;
9733 int NumEltsPerLane = NumElts / NumLanes;
9734 int NumHalfEltsPerLane = NumEltsPerLane / 2;
9735 bool SameLane =
9736 (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
9737 bool SameElt =
9738 (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
9739 return SameLane && SameElt;
9742 break;
9745 return false;
9748 /// Checks whether a shuffle mask is equivalent to an explicit list of
9749 /// arguments.
9751 /// This is a fast way to test a shuffle mask against a fixed pattern:
9753 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
9755 /// It returns true if the mask is exactly as wide as the argument list, and
9756 /// each element of the mask is either -1 (signifying undef) or the value given
9757 /// in the argument.
9758 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
9759 SDValue V1 = SDValue(),
9760 SDValue V2 = SDValue()) {
9761 int Size = Mask.size();
9762 if (Size != (int)ExpectedMask.size())
9763 return false;
9765 for (int i = 0; i < Size; ++i) {
9766 assert(Mask[i] >= -1 && "Out of bound mask element!");
9767 int MaskIdx = Mask[i];
9768 int ExpectedIdx = ExpectedMask[i];
9769 if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
9770 SDValue MaskV = MaskIdx < Size ? V1 : V2;
9771 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9772 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
9773 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9774 if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
9775 return false;
9778 return true;
9781 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
9783 /// The masks must be exactly the same width.
9785 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
9786 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
9788 /// SM_SentinelZero is accepted as a valid negative index but must match in
9789 /// both, or via a known bits test.
9790 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
9791 ArrayRef<int> ExpectedMask,
9792 const SelectionDAG &DAG,
9793 SDValue V1 = SDValue(),
9794 SDValue V2 = SDValue()) {
9795 int Size = Mask.size();
9796 if (Size != (int)ExpectedMask.size())
9797 return false;
9798 assert(llvm::all_of(ExpectedMask,
9799 [Size](int M) { return isInRange(M, 0, 2 * Size); }) &&
9800 "Illegal target shuffle mask");
9802 // Check for out-of-range target shuffle mask indices.
9803 if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
9804 return false;
9806 // Don't use V1/V2 if they're not the same size as the shuffle mask type.
9807 if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
9808 !V1.getValueType().isVector()))
9809 V1 = SDValue();
9810 if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
9811 !V2.getValueType().isVector()))
9812 V2 = SDValue();
9814 APInt ZeroV1 = APInt::getZero(Size);
9815 APInt ZeroV2 = APInt::getZero(Size);
9817 for (int i = 0; i < Size; ++i) {
9818 int MaskIdx = Mask[i];
9819 int ExpectedIdx = ExpectedMask[i];
9820 if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
9821 continue;
9822 if (MaskIdx == SM_SentinelZero) {
9823 // If we need this expected index to be a zero element, then update the
9824 // relevant zero mask and perform the known bits at the end to minimize
9825 // repeated computes.
9826 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9827 if (ExpectedV &&
9828 Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
9829 int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9830 APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
9831 ZeroMask.setBit(BitIdx);
9832 continue;
9835 if (MaskIdx >= 0) {
9836 SDValue MaskV = MaskIdx < Size ? V1 : V2;
9837 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9838 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
9839 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9840 if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
9841 continue;
9843 return false;
9845 return (ZeroV1.isZero() || DAG.MaskedVectorIsZero(V1, ZeroV1)) &&
9846 (ZeroV2.isZero() || DAG.MaskedVectorIsZero(V2, ZeroV2));
9849 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
9850 // instructions.
9851 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT,
9852 const SelectionDAG &DAG) {
9853 if (VT != MVT::v8i32 && VT != MVT::v8f32)
9854 return false;
9856 SmallVector<int, 8> Unpcklwd;
9857 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
9858 /* Unary = */ false);
9859 SmallVector<int, 8> Unpckhwd;
9860 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
9861 /* Unary = */ false);
9862 bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
9863 isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
9864 return IsUnpackwdMask;
9867 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask,
9868 const SelectionDAG &DAG) {
9869 // Create 128-bit vector type based on mask size.
9870 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
9871 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
9873 // We can't assume a canonical shuffle mask, so try the commuted version too.
9874 SmallVector<int, 4> CommutedMask(Mask);
9875 ShuffleVectorSDNode::commuteMask(CommutedMask);
9877 // Match any of unary/binary or low/high.
9878 for (unsigned i = 0; i != 4; ++i) {
9879 SmallVector<int, 16> UnpackMask;
9880 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
9881 if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
9882 isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
9883 return true;
9885 return false;
9888 /// Return true if a shuffle mask chooses elements identically in its top and
9889 /// bottom halves. For example, any splat mask has the same top and bottom
9890 /// halves. If an element is undefined in only one half of the mask, the halves
9891 /// are not considered identical.
9892 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
9893 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
9894 unsigned HalfSize = Mask.size() / 2;
9895 for (unsigned i = 0; i != HalfSize; ++i) {
9896 if (Mask[i] != Mask[i + HalfSize])
9897 return false;
9899 return true;
9902 /// Get a 4-lane 8-bit shuffle immediate for a mask.
9904 /// This helper function produces an 8-bit shuffle immediate corresponding to
9905 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
9906 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
9907 /// example.
9909 /// NB: We rely heavily on "undef" masks preserving the input lane.
9910 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
9911 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
9912 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
9913 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
9914 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
9915 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
9917 // If the mask only uses one non-undef element, then fully 'splat' it to
9918 // improve later broadcast matching.
9919 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
9920 assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
9922 int FirstElt = Mask[FirstIndex];
9923 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
9924 return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
9926 unsigned Imm = 0;
9927 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
9928 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
9929 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
9930 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
9931 return Imm;
9934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
9935 SelectionDAG &DAG) {
9936 return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
9939 // Canonicalize SHUFPD mask to improve chances of further folding.
9940 // Mask elements are assumed to be -1, 0 or 1 to match the SHUFPD lo/hi pattern.
9941 static unsigned getSHUFPDImm(ArrayRef<int> Mask) {
9942 assert((Mask.size() == 2 || Mask.size() == 4 || Mask.size() == 8) &&
9943 "Unexpected SHUFPD mask size");
9944 assert(all_of(Mask, [](int M) { return -1 <= M && M <= 1; }) &&
9945 "Unexpected SHUFPD mask elements");
9947 // If the mask only uses one non-undef element, then fully 'splat' it to
9948 // improve later broadcast matching.
9949 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
9950 assert(0 <= FirstIndex && FirstIndex < (int)Mask.size() &&
9951 "All undef shuffle mask");
9953 int FirstElt = Mask[FirstIndex];
9954 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }) &&
9955 count_if(Mask, [FirstElt](int M) { return M == FirstElt; }) > 1) {
9956 unsigned Imm = 0;
9957 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
9958 Imm |= FirstElt << I;
9959 return Imm;
9962 // Attempt to keep any undef elements in place to improve chances of the
9963 // shuffle becoming a (commutative) blend.
9964 unsigned Imm = 0;
9965 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
9966 Imm |= (Mask[I] < 0 ? (I & 1) : Mask[I]) << I;
9968 return Imm;
9971 static SDValue getSHUFPDImmForMask(ArrayRef<int> Mask, const SDLoc &DL,
9972 SelectionDAG &DAG) {
9973 return DAG.getTargetConstant(getSHUFPDImm(Mask), DL, MVT::i8);
9976 // The Shuffle result is as follow:
9977 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
9978 // Each Zeroable's element correspond to a particular Mask's element.
9979 // As described in computeZeroableShuffleElements function.
9981 // The function looks for a sub-mask that the nonzero elements are in
9982 // increasing order. If such sub-mask exist. The function returns true.
9983 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
9984 ArrayRef<int> Mask, const EVT &VectorType,
9985 bool &IsZeroSideLeft) {
9986 int NextElement = -1;
9987 // Check if the Mask's nonzero elements are in increasing order.
9988 for (int i = 0, e = Mask.size(); i < e; i++) {
9989 // Checks if the mask's zeros elements are built from only zeros.
9990 assert(Mask[i] >= -1 && "Out of bound mask element!");
9991 if (Mask[i] < 0)
9992 return false;
9993 if (Zeroable[i])
9994 continue;
9995 // Find the lowest non zero element
9996 if (NextElement < 0) {
9997 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
9998 IsZeroSideLeft = NextElement != 0;
10000 // Exit if the mask's non zero elements are not in increasing order.
10001 if (NextElement != Mask[i])
10002 return false;
10003 NextElement++;
10005 return true;
10008 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
10009 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
10010 ArrayRef<int> Mask, SDValue V1,
10011 SDValue V2, const APInt &Zeroable,
10012 const X86Subtarget &Subtarget,
10013 SelectionDAG &DAG) {
10014 int Size = Mask.size();
10015 int LaneSize = 128 / VT.getScalarSizeInBits();
10016 const int NumBytes = VT.getSizeInBits() / 8;
10017 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10019 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
10020 (Subtarget.hasAVX2() && VT.is256BitVector()) ||
10021 (Subtarget.hasBWI() && VT.is512BitVector()));
10023 SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
10024 // Sign bit set in i8 mask means zero element.
10025 SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
10027 SDValue V;
10028 for (int i = 0; i < NumBytes; ++i) {
10029 int M = Mask[i / NumEltBytes];
10030 if (M < 0) {
10031 PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
10032 continue;
10034 if (Zeroable[i / NumEltBytes]) {
10035 PSHUFBMask[i] = ZeroMask;
10036 continue;
10039 // We can only use a single input of V1 or V2.
10040 SDValue SrcV = (M >= Size ? V2 : V1);
10041 if (V && V != SrcV)
10042 return SDValue();
10043 V = SrcV;
10044 M %= Size;
10046 // PSHUFB can't cross lanes, ensure this doesn't happen.
10047 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10048 return SDValue();
10050 M = M % LaneSize;
10051 M = M * NumEltBytes + (i % NumEltBytes);
10052 PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
10054 assert(V && "Failed to find a source input");
10056 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10057 return DAG.getBitcast(
10058 VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
10059 DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
10062 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10063 const X86Subtarget &Subtarget, SelectionDAG &DAG,
10064 const SDLoc &dl);
10066 // X86 has dedicated shuffle that can be lowered to VEXPAND
10067 static SDValue lowerShuffleWithEXPAND(const SDLoc &DL, MVT VT, SDValue V1,
10068 SDValue V2, ArrayRef<int> Mask,
10069 const APInt &Zeroable,
10070 const X86Subtarget &Subtarget,
10071 SelectionDAG &DAG) {
10072 bool IsLeftZeroSide = true;
10073 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10074 IsLeftZeroSide))
10075 return SDValue();
10076 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10077 MVT IntegerType =
10078 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10079 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10080 unsigned NumElts = VT.getVectorNumElements();
10081 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
10082 "Unexpected number of vector elements");
10083 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10084 Subtarget, DAG, DL);
10085 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10086 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10087 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10090 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
10091 unsigned &UnpackOpcode, bool IsUnary,
10092 ArrayRef<int> TargetMask, const SDLoc &DL,
10093 SelectionDAG &DAG,
10094 const X86Subtarget &Subtarget) {
10095 int NumElts = VT.getVectorNumElements();
10097 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10098 for (int i = 0; i != NumElts; i += 2) {
10099 int M1 = TargetMask[i + 0];
10100 int M2 = TargetMask[i + 1];
10101 Undef1 &= (SM_SentinelUndef == M1);
10102 Undef2 &= (SM_SentinelUndef == M2);
10103 Zero1 &= isUndefOrZero(M1);
10104 Zero2 &= isUndefOrZero(M2);
10106 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
10107 "Zeroable shuffle detected");
10109 // Attempt to match the target mask against the unpack lo/hi mask patterns.
10110 SmallVector<int, 64> Unpckl, Unpckh;
10111 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10112 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
10113 (IsUnary ? V1 : V2))) {
10114 UnpackOpcode = X86ISD::UNPCKL;
10115 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10116 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10117 return true;
10120 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10121 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
10122 (IsUnary ? V1 : V2))) {
10123 UnpackOpcode = X86ISD::UNPCKH;
10124 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10125 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10126 return true;
10129 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10130 if (IsUnary && (Zero1 || Zero2)) {
10131 // Don't bother if we can blend instead.
10132 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10133 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10134 return false;
10136 bool MatchLo = true, MatchHi = true;
10137 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10138 int M = TargetMask[i];
10140 // Ignore if the input is known to be zero or the index is undef.
10141 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10142 (M == SM_SentinelUndef))
10143 continue;
10145 MatchLo &= (M == Unpckl[i]);
10146 MatchHi &= (M == Unpckh[i]);
10149 if (MatchLo || MatchHi) {
10150 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10151 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10152 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10153 return true;
10157 // If a binary shuffle, commute and try again.
10158 if (!IsUnary) {
10159 ShuffleVectorSDNode::commuteMask(Unpckl);
10160 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
10161 UnpackOpcode = X86ISD::UNPCKL;
10162 std::swap(V1, V2);
10163 return true;
10166 ShuffleVectorSDNode::commuteMask(Unpckh);
10167 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
10168 UnpackOpcode = X86ISD::UNPCKH;
10169 std::swap(V1, V2);
10170 return true;
10174 return false;
10177 // X86 has dedicated unpack instructions that can handle specific blend
10178 // operations: UNPCKH and UNPCKL.
10179 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT, SDValue V1,
10180 SDValue V2, ArrayRef<int> Mask,
10181 SelectionDAG &DAG) {
10182 SmallVector<int, 8> Unpckl;
10183 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10184 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10185 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10187 SmallVector<int, 8> Unpckh;
10188 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10189 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10190 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10192 // Commute and try again.
10193 ShuffleVectorSDNode::commuteMask(Unpckl);
10194 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10195 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10197 ShuffleVectorSDNode::commuteMask(Unpckh);
10198 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10199 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10201 return SDValue();
10204 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
10205 /// followed by unpack 256-bit.
10206 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT, SDValue V1,
10207 SDValue V2, ArrayRef<int> Mask,
10208 SelectionDAG &DAG) {
10209 SmallVector<int, 32> Unpckl, Unpckh;
10210 createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
10211 createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
10213 unsigned UnpackOpcode;
10214 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10215 UnpackOpcode = X86ISD::UNPCKL;
10216 else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10217 UnpackOpcode = X86ISD::UNPCKH;
10218 else
10219 return SDValue();
10221 // This is a "natural" unpack operation (rather than the 128-bit sectored
10222 // operation implemented by AVX). We need to rearrange 64-bit chunks of the
10223 // input in order to use the x86 instruction.
10224 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
10225 DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
10226 V1 = DAG.getBitcast(VT, V1);
10227 return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
10230 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
10231 // source into the lower elements and zeroing the upper elements.
10232 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
10233 ArrayRef<int> Mask, const APInt &Zeroable,
10234 const X86Subtarget &Subtarget) {
10235 if (!VT.is512BitVector() && !Subtarget.hasVLX())
10236 return false;
10238 unsigned NumElts = Mask.size();
10239 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10240 unsigned MaxScale = 64 / EltSizeInBits;
10242 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10243 unsigned SrcEltBits = EltSizeInBits * Scale;
10244 if (SrcEltBits < 32 && !Subtarget.hasBWI())
10245 continue;
10246 unsigned NumSrcElts = NumElts / Scale;
10247 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
10248 continue;
10249 unsigned UpperElts = NumElts - NumSrcElts;
10250 if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10251 continue;
10252 SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
10253 SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
10254 DstVT = MVT::getIntegerVT(EltSizeInBits);
10255 if ((NumSrcElts * EltSizeInBits) >= 128) {
10256 // ISD::TRUNCATE
10257 DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
10258 } else {
10259 // X86ISD::VTRUNC
10260 DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
10262 return true;
10265 return false;
10268 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
10269 // element padding to the final DstVT.
10270 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
10271 const X86Subtarget &Subtarget,
10272 SelectionDAG &DAG, bool ZeroUppers) {
10273 MVT SrcVT = Src.getSimpleValueType();
10274 MVT DstSVT = DstVT.getScalarType();
10275 unsigned NumDstElts = DstVT.getVectorNumElements();
10276 unsigned NumSrcElts = SrcVT.getVectorNumElements();
10277 unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
10279 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
10280 return SDValue();
10282 // Perform a direct ISD::TRUNCATE if possible.
10283 if (NumSrcElts == NumDstElts)
10284 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
10286 if (NumSrcElts > NumDstElts) {
10287 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10289 return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
10292 if ((NumSrcElts * DstEltSizeInBits) >= 128) {
10293 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10294 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10295 return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10296 DstVT.getSizeInBits());
10299 // Non-VLX targets must truncate from a 512-bit type, so we need to
10300 // widen, truncate and then possibly extract the original subvector.
10301 if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
10302 SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
10303 return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
10306 // Fallback to a X86ISD::VTRUNC, padding if necessary.
10307 MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
10308 SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
10309 if (DstVT != TruncVT)
10310 Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10311 DstVT.getSizeInBits());
10312 return Trunc;
10315 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10317 // An example is the following:
10319 // t0: ch = EntryToken
10320 // t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10321 // t25: v4i32 = truncate t2
10322 // t41: v8i16 = bitcast t25
10323 // t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10324 // Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10325 // t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10326 // t18: v2i64 = bitcast t51
10328 // One can just use a single vpmovdw instruction, without avx512vl we need to
10329 // use the zmm variant and extract the lower subvector, padding with zeroes.
10330 // TODO: Merge with lowerShuffleAsVTRUNC.
10331 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
10332 SDValue V2, ArrayRef<int> Mask,
10333 const APInt &Zeroable,
10334 const X86Subtarget &Subtarget,
10335 SelectionDAG &DAG) {
10336 assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
10337 if (!Subtarget.hasAVX512())
10338 return SDValue();
10340 unsigned NumElts = VT.getVectorNumElements();
10341 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10342 unsigned MaxScale = 64 / EltSizeInBits;
10343 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10344 unsigned SrcEltBits = EltSizeInBits * Scale;
10345 unsigned NumSrcElts = NumElts / Scale;
10346 unsigned UpperElts = NumElts - NumSrcElts;
10347 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
10348 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10349 continue;
10351 // Attempt to find a matching source truncation, but as a fall back VLX
10352 // cases can use the VPMOV directly.
10353 SDValue Src = peekThroughBitcasts(V1);
10354 if (Src.getOpcode() == ISD::TRUNCATE &&
10355 Src.getScalarValueSizeInBits() == SrcEltBits) {
10356 Src = Src.getOperand(0);
10357 } else if (Subtarget.hasVLX()) {
10358 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10359 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10360 Src = DAG.getBitcast(SrcVT, Src);
10361 // Don't do this if PACKSS/PACKUS could perform it cheaper.
10362 if (Scale == 2 &&
10363 ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
10364 (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
10365 return SDValue();
10366 } else
10367 return SDValue();
10369 // VPMOVWB is only available with avx512bw.
10370 if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
10371 return SDValue();
10373 bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
10374 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
10377 return SDValue();
10380 // Attempt to match binary shuffle patterns as a truncate.
10381 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
10382 SDValue V2, ArrayRef<int> Mask,
10383 const APInt &Zeroable,
10384 const X86Subtarget &Subtarget,
10385 SelectionDAG &DAG) {
10386 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10387 "Unexpected VTRUNC type");
10388 if (!Subtarget.hasAVX512())
10389 return SDValue();
10391 unsigned NumElts = VT.getVectorNumElements();
10392 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10393 unsigned MaxScale = 64 / EltSizeInBits;
10394 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10395 // TODO: Support non-BWI VPMOVWB truncations?
10396 unsigned SrcEltBits = EltSizeInBits * Scale;
10397 if (SrcEltBits < 32 && !Subtarget.hasBWI())
10398 continue;
10400 // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
10401 // Bail if the V2 elements are undef.
10402 unsigned NumHalfSrcElts = NumElts / Scale;
10403 unsigned NumSrcElts = 2 * NumHalfSrcElts;
10404 for (unsigned Offset = 0; Offset != Scale; ++Offset) {
10405 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
10406 isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
10407 continue;
10409 // The elements beyond the truncation must be undef/zero.
10410 unsigned UpperElts = NumElts - NumSrcElts;
10411 if (UpperElts > 0 &&
10412 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10413 continue;
10414 bool UndefUppers =
10415 UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
10417 // For offset truncations, ensure that the concat is cheap.
10418 if (Offset) {
10419 auto IsCheapConcat = [&](SDValue Lo, SDValue Hi) {
10420 if (Lo.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
10421 Hi.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10422 return Lo.getOperand(0) == Hi.getOperand(0);
10423 if (ISD::isNormalLoad(Lo.getNode()) &&
10424 ISD::isNormalLoad(Hi.getNode())) {
10425 auto *LDLo = cast<LoadSDNode>(Lo);
10426 auto *LDHi = cast<LoadSDNode>(Hi);
10427 return DAG.areNonVolatileConsecutiveLoads(
10428 LDHi, LDLo, Lo.getValueType().getStoreSize(), 1);
10430 return false;
10432 if (!IsCheapConcat(peekThroughBitcasts(V1), peekThroughBitcasts(V2)))
10433 continue;
10436 // As we're using both sources then we need to concat them together
10437 // and truncate from the double-sized src.
10438 MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
10439 SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
10441 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10442 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10443 Src = DAG.getBitcast(SrcVT, Src);
10445 // Shift the offset'd elements into place for the truncation.
10446 // TODO: Use getTargetVShiftByConstNode.
10447 if (Offset)
10448 Src = DAG.getNode(
10449 X86ISD::VSRLI, DL, SrcVT, Src,
10450 DAG.getTargetConstant(Offset * EltSizeInBits, DL, MVT::i8));
10452 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
10456 return SDValue();
10459 /// Check whether a compaction lowering can be done by dropping even/odd
10460 /// elements and compute how many times even/odd elements must be dropped.
10462 /// This handles shuffles which take every Nth element where N is a power of
10463 /// two. Example shuffle masks:
10465 /// (even)
10466 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
10467 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
10468 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
10469 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
10470 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
10471 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
10473 /// (odd)
10474 /// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 14
10475 /// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
10477 /// Any of these lanes can of course be undef.
10479 /// This routine only supports N <= 3.
10480 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
10481 /// for larger N.
10483 /// \returns N above, or the number of times even/odd elements must be dropped
10484 /// if there is such a number. Otherwise returns zero.
10485 static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
10486 bool IsSingleInput) {
10487 // The modulus for the shuffle vector entries is based on whether this is
10488 // a single input or not.
10489 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
10490 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
10491 "We should only be called with masks with a power-of-2 size!");
10493 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
10494 int Offset = MatchEven ? 0 : 1;
10496 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
10497 // and 2^3 simultaneously. This is because we may have ambiguity with
10498 // partially undef inputs.
10499 bool ViableForN[3] = {true, true, true};
10501 for (int i = 0, e = Mask.size(); i < e; ++i) {
10502 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
10503 // want.
10504 if (Mask[i] < 0)
10505 continue;
10507 bool IsAnyViable = false;
10508 for (unsigned j = 0; j != std::size(ViableForN); ++j)
10509 if (ViableForN[j]) {
10510 uint64_t N = j + 1;
10512 // The shuffle mask must be equal to (i * 2^N) % M.
10513 if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
10514 IsAnyViable = true;
10515 else
10516 ViableForN[j] = false;
10518 // Early exit if we exhaust the possible powers of two.
10519 if (!IsAnyViable)
10520 break;
10523 for (unsigned j = 0; j != std::size(ViableForN); ++j)
10524 if (ViableForN[j])
10525 return j + 1;
10527 // Return 0 as there is no viable power of two.
10528 return 0;
10531 // X86 has dedicated pack instructions that can handle specific truncation
10532 // operations: PACKSS and PACKUS.
10533 // Checks for compaction shuffle masks if MaxStages > 1.
10534 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
10535 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
10536 unsigned &PackOpcode, ArrayRef<int> TargetMask,
10537 const SelectionDAG &DAG,
10538 const X86Subtarget &Subtarget,
10539 unsigned MaxStages = 1) {
10540 unsigned NumElts = VT.getVectorNumElements();
10541 unsigned BitSize = VT.getScalarSizeInBits();
10542 assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
10543 "Illegal maximum compaction");
10545 auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
10546 unsigned NumSrcBits = PackVT.getScalarSizeInBits();
10547 unsigned NumPackedBits = NumSrcBits - BitSize;
10548 N1 = peekThroughBitcasts(N1);
10549 N2 = peekThroughBitcasts(N2);
10550 unsigned NumBits1 = N1.getScalarValueSizeInBits();
10551 unsigned NumBits2 = N2.getScalarValueSizeInBits();
10552 bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
10553 bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
10554 if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
10555 (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
10556 return false;
10557 if (Subtarget.hasSSE41() || BitSize == 8) {
10558 APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
10559 if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
10560 (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
10561 V1 = N1;
10562 V2 = N2;
10563 SrcVT = PackVT;
10564 PackOpcode = X86ISD::PACKUS;
10565 return true;
10568 bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
10569 bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
10570 if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
10571 DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
10572 (N2.isUndef() || IsZero2 || IsAllOnes2 ||
10573 DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
10574 V1 = N1;
10575 V2 = N2;
10576 SrcVT = PackVT;
10577 PackOpcode = X86ISD::PACKSS;
10578 return true;
10580 return false;
10583 // Attempt to match against wider and wider compaction patterns.
10584 for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
10585 MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
10586 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
10588 // Try binary shuffle.
10589 SmallVector<int, 32> BinaryMask;
10590 createPackShuffleMask(VT, BinaryMask, false, NumStages);
10591 if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
10592 if (MatchPACK(V1, V2, PackVT))
10593 return true;
10595 // Try unary shuffle.
10596 SmallVector<int, 32> UnaryMask;
10597 createPackShuffleMask(VT, UnaryMask, true, NumStages);
10598 if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
10599 if (MatchPACK(V1, V1, PackVT))
10600 return true;
10603 return false;
10606 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, SDValue V1,
10607 SDValue V2, ArrayRef<int> Mask,
10608 const X86Subtarget &Subtarget,
10609 SelectionDAG &DAG) {
10610 MVT PackVT;
10611 unsigned PackOpcode;
10612 unsigned SizeBits = VT.getSizeInBits();
10613 unsigned EltBits = VT.getScalarSizeInBits();
10614 unsigned MaxStages = Log2_32(64 / EltBits);
10615 if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
10616 Subtarget, MaxStages))
10617 return SDValue();
10619 unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
10620 unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
10622 // Don't lower multi-stage packs on AVX512, truncation is better.
10623 if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
10624 return SDValue();
10626 // Pack to the largest type possible:
10627 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
10628 unsigned MaxPackBits = 16;
10629 if (CurrentEltBits > 16 &&
10630 (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
10631 MaxPackBits = 32;
10633 // Repeatedly pack down to the target size.
10634 SDValue Res;
10635 for (unsigned i = 0; i != NumStages; ++i) {
10636 unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
10637 unsigned NumSrcElts = SizeBits / SrcEltBits;
10638 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10639 MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
10640 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10641 MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
10642 Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
10643 DAG.getBitcast(SrcVT, V2));
10644 V1 = V2 = Res;
10645 CurrentEltBits /= 2;
10647 assert(Res && Res.getValueType() == VT &&
10648 "Failed to lower compaction shuffle");
10649 return Res;
10652 /// Try to emit a bitmask instruction for a shuffle.
10654 /// This handles cases where we can model a blend exactly as a bitmask due to
10655 /// one of the inputs being zeroable.
10656 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
10657 SDValue V2, ArrayRef<int> Mask,
10658 const APInt &Zeroable,
10659 const X86Subtarget &Subtarget,
10660 SelectionDAG &DAG) {
10661 MVT MaskVT = VT;
10662 MVT EltVT = VT.getVectorElementType();
10663 SDValue Zero, AllOnes;
10664 // Use f64 if i64 isn't legal.
10665 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
10666 EltVT = MVT::f64;
10667 MaskVT = MVT::getVectorVT(EltVT, Mask.size());
10670 MVT LogicVT = VT;
10671 if (EltVT == MVT::f32 || EltVT == MVT::f64) {
10672 Zero = DAG.getConstantFP(0.0, DL, EltVT);
10673 APFloat AllOnesValue = APFloat::getAllOnesValue(EltVT.getFltSemantics());
10674 AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
10675 LogicVT =
10676 MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
10677 } else {
10678 Zero = DAG.getConstant(0, DL, EltVT);
10679 AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10682 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
10683 SDValue V;
10684 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10685 if (Zeroable[i])
10686 continue;
10687 if (Mask[i] % Size != i)
10688 return SDValue(); // Not a blend.
10689 if (!V)
10690 V = Mask[i] < Size ? V1 : V2;
10691 else if (V != (Mask[i] < Size ? V1 : V2))
10692 return SDValue(); // Can only let one input through the mask.
10694 VMaskOps[i] = AllOnes;
10696 if (!V)
10697 return SDValue(); // No non-zeroable elements!
10699 SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
10700 VMask = DAG.getBitcast(LogicVT, VMask);
10701 V = DAG.getBitcast(LogicVT, V);
10702 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
10703 return DAG.getBitcast(VT, And);
10706 /// Try to emit a blend instruction for a shuffle using bit math.
10708 /// This is used as a fallback approach when first class blend instructions are
10709 /// unavailable. Currently it is only suitable for integer vectors, but could
10710 /// be generalized for floating point vectors if desirable.
10711 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
10712 SDValue V2, ArrayRef<int> Mask,
10713 SelectionDAG &DAG) {
10714 assert(VT.isInteger() && "Only supports integer vector types!");
10715 MVT EltVT = VT.getVectorElementType();
10716 SDValue Zero = DAG.getConstant(0, DL, EltVT);
10717 SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10718 SmallVector<SDValue, 16> MaskOps;
10719 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10720 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
10721 return SDValue(); // Shuffled input!
10722 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
10725 SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
10726 return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
10729 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
10730 SDValue PreservedSrc,
10731 const X86Subtarget &Subtarget,
10732 SelectionDAG &DAG);
10734 static bool matchShuffleAsBlend(MVT VT, SDValue V1, SDValue V2,
10735 MutableArrayRef<int> Mask,
10736 const APInt &Zeroable, bool &ForceV1Zero,
10737 bool &ForceV2Zero, uint64_t &BlendMask) {
10738 bool V1IsZeroOrUndef =
10739 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
10740 bool V2IsZeroOrUndef =
10741 V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
10743 BlendMask = 0;
10744 ForceV1Zero = false, ForceV2Zero = false;
10745 assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
10747 int NumElts = Mask.size();
10748 int NumLanes = VT.getSizeInBits() / 128;
10749 int NumEltsPerLane = NumElts / NumLanes;
10750 assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
10752 // For 32/64-bit elements, if we only reference one input (plus any undefs),
10753 // then ensure the blend mask part for that lane just references that input.
10754 bool ForceWholeLaneMasks =
10755 VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
10757 // Attempt to generate the binary blend mask. If an input is zero then
10758 // we can use any lane.
10759 for (int Lane = 0; Lane != NumLanes; ++Lane) {
10760 // Keep track of the inputs used per lane.
10761 bool LaneV1InUse = false;
10762 bool LaneV2InUse = false;
10763 uint64_t LaneBlendMask = 0;
10764 for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
10765 int Elt = (Lane * NumEltsPerLane) + LaneElt;
10766 int M = Mask[Elt];
10767 if (M == SM_SentinelUndef)
10768 continue;
10769 if (M == Elt || (0 <= M && M < NumElts &&
10770 IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
10771 Mask[Elt] = Elt;
10772 LaneV1InUse = true;
10773 continue;
10775 if (M == (Elt + NumElts) ||
10776 (NumElts <= M &&
10777 IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
10778 LaneBlendMask |= 1ull << LaneElt;
10779 Mask[Elt] = Elt + NumElts;
10780 LaneV2InUse = true;
10781 continue;
10783 if (Zeroable[Elt]) {
10784 if (V1IsZeroOrUndef) {
10785 ForceV1Zero = true;
10786 Mask[Elt] = Elt;
10787 LaneV1InUse = true;
10788 continue;
10790 if (V2IsZeroOrUndef) {
10791 ForceV2Zero = true;
10792 LaneBlendMask |= 1ull << LaneElt;
10793 Mask[Elt] = Elt + NumElts;
10794 LaneV2InUse = true;
10795 continue;
10798 return false;
10801 // If we only used V2 then splat the lane blend mask to avoid any demanded
10802 // elts from V1 in this lane (the V1 equivalent is implicit with a zero
10803 // blend mask bit).
10804 if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
10805 LaneBlendMask = (1ull << NumEltsPerLane) - 1;
10807 BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
10809 return true;
10812 /// Try to emit a blend instruction for a shuffle.
10814 /// This doesn't do any checks for the availability of instructions for blending
10815 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
10816 /// be matched in the backend with the type given. What it does check for is
10817 /// that the shuffle mask is a blend, or convertible into a blend with zero.
10818 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
10819 SDValue V2, ArrayRef<int> Original,
10820 const APInt &Zeroable,
10821 const X86Subtarget &Subtarget,
10822 SelectionDAG &DAG) {
10823 uint64_t BlendMask = 0;
10824 bool ForceV1Zero = false, ForceV2Zero = false;
10825 SmallVector<int, 64> Mask(Original);
10826 if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
10827 BlendMask))
10828 return SDValue();
10830 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
10831 if (ForceV1Zero)
10832 V1 = getZeroVector(VT, Subtarget, DAG, DL);
10833 if (ForceV2Zero)
10834 V2 = getZeroVector(VT, Subtarget, DAG, DL);
10836 unsigned NumElts = VT.getVectorNumElements();
10838 switch (VT.SimpleTy) {
10839 case MVT::v4i64:
10840 case MVT::v8i32:
10841 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
10842 [[fallthrough]];
10843 case MVT::v4f64:
10844 case MVT::v8f32:
10845 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
10846 [[fallthrough]];
10847 case MVT::v2f64:
10848 case MVT::v2i64:
10849 case MVT::v4f32:
10850 case MVT::v4i32:
10851 case MVT::v8i16:
10852 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
10853 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
10854 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
10855 case MVT::v16i16: {
10856 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
10857 SmallVector<int, 8> RepeatedMask;
10858 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10859 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
10860 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
10861 BlendMask = 0;
10862 for (int i = 0; i < 8; ++i)
10863 if (RepeatedMask[i] >= 8)
10864 BlendMask |= 1ull << i;
10865 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10866 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
10868 // Use PBLENDW for lower/upper lanes and then blend lanes.
10869 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
10870 // merge to VSELECT where useful.
10871 uint64_t LoMask = BlendMask & 0xFF;
10872 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
10873 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
10874 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10875 DAG.getTargetConstant(LoMask, DL, MVT::i8));
10876 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10877 DAG.getTargetConstant(HiMask, DL, MVT::i8));
10878 return DAG.getVectorShuffle(
10879 MVT::v16i16, DL, Lo, Hi,
10880 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
10882 [[fallthrough]];
10884 case MVT::v32i8:
10885 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
10886 [[fallthrough]];
10887 case MVT::v16i8: {
10888 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
10890 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
10891 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10892 Subtarget, DAG))
10893 return Masked;
10895 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
10896 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
10897 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10898 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10901 // If we have VPTERNLOG, we can use that as a bit blend.
10902 if (Subtarget.hasVLX())
10903 if (SDValue BitBlend =
10904 lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
10905 return BitBlend;
10907 // Scale the blend by the number of bytes per element.
10908 int Scale = VT.getScalarSizeInBits() / 8;
10910 // This form of blend is always done on bytes. Compute the byte vector
10911 // type.
10912 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10914 // x86 allows load folding with blendvb from the 2nd source operand. But
10915 // we are still using LLVM select here (see comment below), so that's V1.
10916 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
10917 // allow that load-folding possibility.
10918 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
10919 ShuffleVectorSDNode::commuteMask(Mask);
10920 std::swap(V1, V2);
10923 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
10924 // mix of LLVM's code generator and the x86 backend. We tell the code
10925 // generator that boolean values in the elements of an x86 vector register
10926 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
10927 // mapping a select to operand #1, and 'false' mapping to operand #2. The
10928 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
10929 // of the element (the remaining are ignored) and 0 in that high bit would
10930 // mean operand #1 while 1 in the high bit would mean operand #2. So while
10931 // the LLVM model for boolean values in vector elements gets the relevant
10932 // bit set, it is set backwards and over constrained relative to x86's
10933 // actual model.
10934 SmallVector<SDValue, 32> VSELECTMask;
10935 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10936 for (int j = 0; j < Scale; ++j)
10937 VSELECTMask.push_back(
10938 Mask[i] < 0
10939 ? DAG.getUNDEF(MVT::i8)
10940 : DAG.getSignedConstant(Mask[i] < Size ? -1 : 0, DL, MVT::i8));
10942 V1 = DAG.getBitcast(BlendVT, V1);
10943 V2 = DAG.getBitcast(BlendVT, V2);
10944 return DAG.getBitcast(
10946 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
10947 V1, V2));
10949 case MVT::v16f32:
10950 case MVT::v8f64:
10951 case MVT::v8i64:
10952 case MVT::v16i32:
10953 case MVT::v32i16:
10954 case MVT::v64i8: {
10955 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
10956 bool OptForSize = DAG.shouldOptForSize();
10957 if (!OptForSize) {
10958 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10959 Subtarget, DAG))
10960 return Masked;
10963 // Otherwise load an immediate into a GPR, cast to k-register, and use a
10964 // masked move.
10965 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
10966 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10967 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10969 default:
10970 llvm_unreachable("Not a supported integer vector type!");
10974 /// Try to lower as a blend of elements from two inputs followed by
10975 /// a single-input permutation.
10977 /// This matches the pattern where we can blend elements from two inputs and
10978 /// then reduce the shuffle to a single-input permutation.
10979 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
10980 SDValue V1, SDValue V2,
10981 ArrayRef<int> Mask,
10982 SelectionDAG &DAG,
10983 bool ImmBlends = false) {
10984 // We build up the blend mask while checking whether a blend is a viable way
10985 // to reduce the shuffle.
10986 SmallVector<int, 32> BlendMask(Mask.size(), -1);
10987 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
10989 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10990 if (Mask[i] < 0)
10991 continue;
10993 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
10995 if (BlendMask[Mask[i] % Size] < 0)
10996 BlendMask[Mask[i] % Size] = Mask[i];
10997 else if (BlendMask[Mask[i] % Size] != Mask[i])
10998 return SDValue(); // Can't blend in the needed input!
11000 PermuteMask[i] = Mask[i] % Size;
11003 // If only immediate blends, then bail if the blend mask can't be widened to
11004 // i16.
11005 unsigned EltSize = VT.getScalarSizeInBits();
11006 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11007 return SDValue();
11009 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11010 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11013 /// Try to lower as an unpack of elements from two inputs followed by
11014 /// a single-input permutation.
11016 /// This matches the pattern where we can unpack elements from two inputs and
11017 /// then reduce the shuffle to a single-input (wider) permutation.
11018 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
11019 SDValue V1, SDValue V2,
11020 ArrayRef<int> Mask,
11021 SelectionDAG &DAG) {
11022 int NumElts = Mask.size();
11023 int NumLanes = VT.getSizeInBits() / 128;
11024 int NumLaneElts = NumElts / NumLanes;
11025 int NumHalfLaneElts = NumLaneElts / 2;
11027 bool MatchLo = true, MatchHi = true;
11028 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11030 // Determine UNPCKL/UNPCKH type and operand order.
11031 for (int Elt = 0; Elt != NumElts; ++Elt) {
11032 int M = Mask[Elt];
11033 if (M < 0)
11034 continue;
11036 // Normalize the mask value depending on whether it's V1 or V2.
11037 int NormM = M;
11038 SDValue &Op = Ops[Elt & 1];
11039 if (M < NumElts && (Op.isUndef() || Op == V1))
11040 Op = V1;
11041 else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
11042 Op = V2;
11043 NormM -= NumElts;
11044 } else
11045 return SDValue();
11047 bool MatchLoAnyLane = false, MatchHiAnyLane = false;
11048 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11049 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11050 MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
11051 MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
11052 if (MatchLoAnyLane || MatchHiAnyLane) {
11053 assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
11054 "Failed to match UNPCKLO/UNPCKHI");
11055 break;
11058 MatchLo &= MatchLoAnyLane;
11059 MatchHi &= MatchHiAnyLane;
11060 if (!MatchLo && !MatchHi)
11061 return SDValue();
11063 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11065 // Element indices have changed after unpacking. Calculate permute mask
11066 // so that they will be put back to the position as dictated by the
11067 // original shuffle mask indices.
11068 SmallVector<int, 32> PermuteMask(NumElts, -1);
11069 for (int Elt = 0; Elt != NumElts; ++Elt) {
11070 int M = Mask[Elt];
11071 if (M < 0)
11072 continue;
11073 int NormM = M;
11074 if (NumElts <= M)
11075 NormM -= NumElts;
11076 bool IsFirstOp = M < NumElts;
11077 int BaseMaskElt =
11078 NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
11079 if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
11080 PermuteMask[Elt] = BaseMaskElt;
11081 else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
11082 PermuteMask[Elt] = BaseMaskElt + 1;
11083 assert(PermuteMask[Elt] != -1 &&
11084 "Input mask element is defined but failed to assign permute mask");
11087 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11088 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11089 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11092 /// Try to lower a shuffle as a permute of the inputs followed by an
11093 /// UNPCK instruction.
11095 /// This specifically targets cases where we end up with alternating between
11096 /// the two inputs, and so can permute them into something that feeds a single
11097 /// UNPCK instruction. Note that this routine only targets integer vectors
11098 /// because for floating point vectors we have a generalized SHUFPS lowering
11099 /// strategy that handles everything that doesn't *exactly* match an unpack,
11100 /// making this clever lowering unnecessary.
11101 static SDValue lowerShuffleAsPermuteAndUnpack(const SDLoc &DL, MVT VT,
11102 SDValue V1, SDValue V2,
11103 ArrayRef<int> Mask,
11104 const X86Subtarget &Subtarget,
11105 SelectionDAG &DAG) {
11106 int Size = Mask.size();
11107 assert(Mask.size() >= 2 && "Single element masks are invalid.");
11109 // This routine only supports 128-bit integer dual input vectors.
11110 if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
11111 return SDValue();
11113 int NumLoInputs =
11114 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
11115 int NumHiInputs =
11116 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
11118 bool UnpackLo = NumLoInputs >= NumHiInputs;
11120 auto TryUnpack = [&](int ScalarSize, int Scale) {
11121 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
11122 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
11124 for (int i = 0; i < Size; ++i) {
11125 if (Mask[i] < 0)
11126 continue;
11128 // Each element of the unpack contains Scale elements from this mask.
11129 int UnpackIdx = i / Scale;
11131 // We only handle the case where V1 feeds the first slots of the unpack.
11132 // We rely on canonicalization to ensure this is the case.
11133 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
11134 return SDValue();
11136 // Setup the mask for this input. The indexing is tricky as we have to
11137 // handle the unpack stride.
11138 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
11139 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
11140 Mask[i] % Size;
11143 // If we will have to shuffle both inputs to use the unpack, check whether
11144 // we can just unpack first and shuffle the result. If so, skip this unpack.
11145 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
11146 !isNoopShuffleMask(V2Mask))
11147 return SDValue();
11149 // Shuffle the inputs into place.
11150 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11151 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11153 // Cast the inputs to the type we will use to unpack them.
11154 MVT UnpackVT =
11155 MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
11156 V1 = DAG.getBitcast(UnpackVT, V1);
11157 V2 = DAG.getBitcast(UnpackVT, V2);
11159 // Unpack the inputs and cast the result back to the desired type.
11160 return DAG.getBitcast(
11161 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
11162 UnpackVT, V1, V2));
11165 // We try each unpack from the largest to the smallest to try and find one
11166 // that fits this mask.
11167 int OrigScalarSize = VT.getScalarSizeInBits();
11168 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
11169 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
11170 return Unpack;
11172 // If we're shuffling with a zero vector then we're better off not doing
11173 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
11174 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
11175 ISD::isBuildVectorAllZeros(V2.getNode()))
11176 return SDValue();
11178 // If none of the unpack-rooted lowerings worked (or were profitable) try an
11179 // initial unpack.
11180 if (NumLoInputs == 0 || NumHiInputs == 0) {
11181 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
11182 "We have to have *some* inputs!");
11183 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
11185 // FIXME: We could consider the total complexity of the permute of each
11186 // possible unpacking. Or at the least we should consider how many
11187 // half-crossings are created.
11188 // FIXME: We could consider commuting the unpacks.
11190 SmallVector<int, 32> PermMask((unsigned)Size, -1);
11191 for (int i = 0; i < Size; ++i) {
11192 if (Mask[i] < 0)
11193 continue;
11195 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
11197 PermMask[i] =
11198 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
11200 return DAG.getVectorShuffle(
11201 VT, DL,
11202 DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
11203 V1, V2),
11204 DAG.getUNDEF(VT), PermMask);
11207 return SDValue();
11210 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11211 /// permuting the elements of the result in place.
11212 static SDValue lowerShuffleAsByteRotateAndPermute(
11213 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11214 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11215 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11216 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11217 (VT.is512BitVector() && !Subtarget.hasBWI()))
11218 return SDValue();
11220 // We don't currently support lane crossing permutes.
11221 if (is128BitLaneCrossingShuffleMask(VT, Mask))
11222 return SDValue();
11224 int Scale = VT.getScalarSizeInBits() / 8;
11225 int NumLanes = VT.getSizeInBits() / 128;
11226 int NumElts = VT.getVectorNumElements();
11227 int NumEltsPerLane = NumElts / NumLanes;
11229 // Determine range of mask elts.
11230 bool Blend1 = true;
11231 bool Blend2 = true;
11232 std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11233 std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11234 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11235 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11236 int M = Mask[Lane + Elt];
11237 if (M < 0)
11238 continue;
11239 if (M < NumElts) {
11240 Blend1 &= (M == (Lane + Elt));
11241 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11242 M = M % NumEltsPerLane;
11243 Range1.first = std::min(Range1.first, M);
11244 Range1.second = std::max(Range1.second, M);
11245 } else {
11246 M -= NumElts;
11247 Blend2 &= (M == (Lane + Elt));
11248 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11249 M = M % NumEltsPerLane;
11250 Range2.first = std::min(Range2.first, M);
11251 Range2.second = std::max(Range2.second, M);
11256 // Bail if we don't need both elements.
11257 // TODO - it might be worth doing this for unary shuffles if the permute
11258 // can be widened.
11259 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11260 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11261 return SDValue();
11263 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11264 return SDValue();
11266 // Rotate the 2 ops so we can access both ranges, then permute the result.
11267 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11268 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11269 SDValue Rotate = DAG.getBitcast(
11270 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11271 DAG.getBitcast(ByteVT, Lo),
11272 DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11273 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11274 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11275 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11276 int M = Mask[Lane + Elt];
11277 if (M < 0)
11278 continue;
11279 if (M < NumElts)
11280 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11281 else
11282 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
11285 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
11288 // Check if the ranges are small enough to rotate from either direction.
11289 if (Range2.second < Range1.first)
11290 return RotateAndPermute(V1, V2, Range1.first, 0);
11291 if (Range1.second < Range2.first)
11292 return RotateAndPermute(V2, V1, Range2.first, NumElts);
11293 return SDValue();
11296 static bool isBroadcastShuffleMask(ArrayRef<int> Mask) {
11297 return isUndefOrEqual(Mask, 0);
11300 static bool isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask) {
11301 return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
11304 /// Check if the Mask consists of the same element repeated multiple times.
11305 static bool isSingleElementRepeatedMask(ArrayRef<int> Mask) {
11306 size_t NumUndefs = 0;
11307 std::optional<int> UniqueElt;
11308 for (int Elt : Mask) {
11309 if (Elt == SM_SentinelUndef) {
11310 NumUndefs++;
11311 continue;
11313 if (UniqueElt.has_value() && UniqueElt.value() != Elt)
11314 return false;
11315 UniqueElt = Elt;
11317 // Make sure the element is repeated enough times by checking the number of
11318 // undefs is small.
11319 return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
11322 /// Generic routine to decompose a shuffle and blend into independent
11323 /// blends and permutes.
11325 /// This matches the extremely common pattern for handling combined
11326 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11327 /// operations. It will try to pick the best arrangement of shuffles and
11328 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
11329 static SDValue lowerShuffleAsDecomposedShuffleMerge(
11330 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11331 const APInt &Zeroable, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11332 int NumElts = Mask.size();
11333 int NumLanes = VT.getSizeInBits() / 128;
11334 int NumEltsPerLane = NumElts / NumLanes;
11336 // Shuffle the input elements into the desired positions in V1 and V2 and
11337 // unpack/blend them together.
11338 bool IsAlternating = true;
11339 bool V1Zero = true, V2Zero = true;
11340 SmallVector<int, 32> V1Mask(NumElts, -1);
11341 SmallVector<int, 32> V2Mask(NumElts, -1);
11342 SmallVector<int, 32> FinalMask(NumElts, -1);
11343 for (int i = 0; i < NumElts; ++i) {
11344 int M = Mask[i];
11345 if (M >= 0 && M < NumElts) {
11346 V1Mask[i] = M;
11347 FinalMask[i] = i;
11348 V1Zero &= Zeroable[i];
11349 IsAlternating &= (i & 1) == 0;
11350 } else if (M >= NumElts) {
11351 V2Mask[i] = M - NumElts;
11352 FinalMask[i] = i + NumElts;
11353 V2Zero &= Zeroable[i];
11354 IsAlternating &= (i & 1) == 1;
11358 // If we effectively only demand the 0'th element of \p Input, and not only
11359 // as 0'th element, then broadcast said input,
11360 // and change \p InputMask to be a no-op (identity) mask.
11361 auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
11362 &DAG](SDValue &Input,
11363 MutableArrayRef<int> InputMask) {
11364 unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
11365 if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
11366 !X86::mayFoldLoad(Input, Subtarget)))
11367 return;
11368 if (isNoopShuffleMask(InputMask))
11369 return;
11370 assert(isBroadcastShuffleMask(InputMask) &&
11371 "Expected to demand only the 0'th element.");
11372 Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
11373 for (auto I : enumerate(InputMask)) {
11374 int &InputMaskElt = I.value();
11375 if (InputMaskElt >= 0)
11376 InputMaskElt = I.index();
11380 // Currently, we may need to produce one shuffle per input, and blend results.
11381 // It is possible that the shuffle for one of the inputs is already a no-op.
11382 // See if we can simplify non-no-op shuffles into broadcasts,
11383 // which we consider to be strictly better than an arbitrary shuffle.
11384 if (isNoopOrBroadcastShuffleMask(V1Mask) &&
11385 isNoopOrBroadcastShuffleMask(V2Mask)) {
11386 canonicalizeBroadcastableInput(V1, V1Mask);
11387 canonicalizeBroadcastableInput(V2, V2Mask);
11390 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
11391 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
11392 // the shuffle may be able to fold with a load or other benefit. However, when
11393 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
11394 // pre-shuffle first is a better strategy.
11395 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
11396 // Only prefer immediate blends to unpack/rotate.
11397 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11398 DAG, true))
11399 return BlendPerm;
11400 // If either input vector provides only a single element which is repeated
11401 // multiple times, unpacking from both input vectors would generate worse
11402 // code. e.g. for
11403 // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
11404 // it is better to process t4 first to create a vector of t4[0], then unpack
11405 // that vector with t2.
11406 if (!V1Zero && !V2Zero && !isSingleElementRepeatedMask(V1Mask) &&
11407 !isSingleElementRepeatedMask(V2Mask))
11408 if (SDValue UnpackPerm =
11409 lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
11410 return UnpackPerm;
11411 if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
11412 DL, VT, V1, V2, Mask, Subtarget, DAG))
11413 return RotatePerm;
11414 // Unpack/rotate failed - try again with variable blends.
11415 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11416 DAG))
11417 return BlendPerm;
11418 if (VT.getScalarSizeInBits() >= 32)
11419 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
11420 DL, VT, V1, V2, Mask, Subtarget, DAG))
11421 return PermUnpack;
11424 // If the final mask is an alternating blend of vXi8/vXi16, convert to an
11425 // UNPCKL(SHUFFLE, SHUFFLE) pattern.
11426 // TODO: It doesn't have to be alternating - but each lane mustn't have more
11427 // than half the elements coming from each source.
11428 if (IsAlternating && VT.getScalarSizeInBits() < 32) {
11429 V1Mask.assign(NumElts, -1);
11430 V2Mask.assign(NumElts, -1);
11431 FinalMask.assign(NumElts, -1);
11432 for (int i = 0; i != NumElts; i += NumEltsPerLane)
11433 for (int j = 0; j != NumEltsPerLane; ++j) {
11434 int M = Mask[i + j];
11435 if (M >= 0 && M < NumElts) {
11436 V1Mask[i + (j / 2)] = M;
11437 FinalMask[i + j] = i + (j / 2);
11438 } else if (M >= NumElts) {
11439 V2Mask[i + (j / 2)] = M - NumElts;
11440 FinalMask[i + j] = i + (j / 2) + NumElts;
11445 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11446 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11447 return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
11450 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
11451 const X86Subtarget &Subtarget,
11452 ArrayRef<int> Mask) {
11453 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11454 assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
11456 // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
11457 int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
11458 int MaxSubElts = 64 / EltSizeInBits;
11459 unsigned RotateAmt, NumSubElts;
11460 if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, MinSubElts,
11461 MaxSubElts, NumSubElts, RotateAmt))
11462 return -1;
11463 unsigned NumElts = Mask.size();
11464 MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
11465 RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
11466 return RotateAmt;
11469 /// Lower shuffle using X86ISD::VROTLI rotations.
11470 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
11471 ArrayRef<int> Mask,
11472 const X86Subtarget &Subtarget,
11473 SelectionDAG &DAG) {
11474 // Only XOP + AVX512 targets have bit rotation instructions.
11475 // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
11476 bool IsLegal =
11477 (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
11478 if (!IsLegal && Subtarget.hasSSE3())
11479 return SDValue();
11481 MVT RotateVT;
11482 int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
11483 Subtarget, Mask);
11484 if (RotateAmt < 0)
11485 return SDValue();
11487 // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
11488 // expanded to OR(SRL,SHL), will be more efficient, but if they can
11489 // widen to vXi16 or more then existing lowering should will be better.
11490 if (!IsLegal) {
11491 if ((RotateAmt % 16) == 0)
11492 return SDValue();
11493 // TODO: Use getTargetVShiftByConstNode.
11494 unsigned ShlAmt = RotateAmt;
11495 unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
11496 V1 = DAG.getBitcast(RotateVT, V1);
11497 SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
11498 DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
11499 SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
11500 DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
11501 SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
11502 return DAG.getBitcast(VT, Rot);
11505 SDValue Rot =
11506 DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
11507 DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
11508 return DAG.getBitcast(VT, Rot);
11511 /// Try to match a vector shuffle as an element rotation.
11513 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
11514 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
11515 ArrayRef<int> Mask) {
11516 int NumElts = Mask.size();
11518 // We need to detect various ways of spelling a rotation:
11519 // [11, 12, 13, 14, 15, 0, 1, 2]
11520 // [-1, 12, 13, 14, -1, -1, 1, -1]
11521 // [-1, -1, -1, -1, -1, -1, 1, 2]
11522 // [ 3, 4, 5, 6, 7, 8, 9, 10]
11523 // [-1, 4, 5, 6, -1, -1, 9, -1]
11524 // [-1, 4, 5, 6, -1, -1, -1, -1]
11525 int Rotation = 0;
11526 SDValue Lo, Hi;
11527 for (int i = 0; i < NumElts; ++i) {
11528 int M = Mask[i];
11529 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
11530 "Unexpected mask index.");
11531 if (M < 0)
11532 continue;
11534 // Determine where a rotated vector would have started.
11535 int StartIdx = i - (M % NumElts);
11536 if (StartIdx == 0)
11537 // The identity rotation isn't interesting, stop.
11538 return -1;
11540 // If we found the tail of a vector the rotation must be the missing
11541 // front. If we found the head of a vector, it must be how much of the
11542 // head.
11543 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
11545 if (Rotation == 0)
11546 Rotation = CandidateRotation;
11547 else if (Rotation != CandidateRotation)
11548 // The rotations don't match, so we can't match this mask.
11549 return -1;
11551 // Compute which value this mask is pointing at.
11552 SDValue MaskV = M < NumElts ? V1 : V2;
11554 // Compute which of the two target values this index should be assigned
11555 // to. This reflects whether the high elements are remaining or the low
11556 // elements are remaining.
11557 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
11559 // Either set up this value if we've not encountered it before, or check
11560 // that it remains consistent.
11561 if (!TargetV)
11562 TargetV = MaskV;
11563 else if (TargetV != MaskV)
11564 // This may be a rotation, but it pulls from the inputs in some
11565 // unsupported interleaving.
11566 return -1;
11569 // Check that we successfully analyzed the mask, and normalize the results.
11570 assert(Rotation != 0 && "Failed to locate a viable rotation!");
11571 assert((Lo || Hi) && "Failed to find a rotated input vector!");
11572 if (!Lo)
11573 Lo = Hi;
11574 else if (!Hi)
11575 Hi = Lo;
11577 V1 = Lo;
11578 V2 = Hi;
11580 return Rotation;
11583 /// Try to lower a vector shuffle as a byte rotation.
11585 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
11586 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
11587 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
11588 /// try to generically lower a vector shuffle through such an pattern. It
11589 /// does not check for the profitability of lowering either as PALIGNR or
11590 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
11591 /// This matches shuffle vectors that look like:
11593 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
11595 /// Essentially it concatenates V1 and V2, shifts right by some number of
11596 /// elements, and takes the low elements as the result. Note that while this is
11597 /// specified as a *right shift* because x86 is little-endian, it is a *left
11598 /// rotate* of the vector lanes.
11599 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
11600 ArrayRef<int> Mask) {
11601 // Don't accept any shuffles with zero elements.
11602 if (isAnyZero(Mask))
11603 return -1;
11605 // PALIGNR works on 128-bit lanes.
11606 SmallVector<int, 16> RepeatedMask;
11607 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
11608 return -1;
11610 int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
11611 if (Rotation <= 0)
11612 return -1;
11614 // PALIGNR rotates bytes, so we need to scale the
11615 // rotation based on how many bytes are in the vector lane.
11616 int NumElts = RepeatedMask.size();
11617 int Scale = 16 / NumElts;
11618 return Rotation * Scale;
11621 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
11622 SDValue V2, ArrayRef<int> Mask,
11623 const X86Subtarget &Subtarget,
11624 SelectionDAG &DAG) {
11625 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11627 SDValue Lo = V1, Hi = V2;
11628 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
11629 if (ByteRotation <= 0)
11630 return SDValue();
11632 // Cast the inputs to i8 vector of correct length to match PALIGNR or
11633 // PSLLDQ/PSRLDQ.
11634 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11635 Lo = DAG.getBitcast(ByteVT, Lo);
11636 Hi = DAG.getBitcast(ByteVT, Hi);
11638 // SSSE3 targets can use the palignr instruction.
11639 if (Subtarget.hasSSSE3()) {
11640 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
11641 "512-bit PALIGNR requires BWI instructions");
11642 return DAG.getBitcast(
11643 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
11644 DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
11647 assert(VT.is128BitVector() &&
11648 "Rotate-based lowering only supports 128-bit lowering!");
11649 assert(Mask.size() <= 16 &&
11650 "Can shuffle at most 16 bytes in a 128-bit vector!");
11651 assert(ByteVT == MVT::v16i8 &&
11652 "SSE2 rotate lowering only needed for v16i8!");
11654 // Default SSE2 implementation
11655 int LoByteShift = 16 - ByteRotation;
11656 int HiByteShift = ByteRotation;
11658 SDValue LoShift =
11659 DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
11660 DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
11661 SDValue HiShift =
11662 DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
11663 DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
11664 return DAG.getBitcast(VT,
11665 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
11668 /// Try to lower a vector shuffle as a dword/qword rotation.
11670 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
11671 /// rotation of the concatenation of two vectors; This routine will
11672 /// try to generically lower a vector shuffle through such an pattern.
11674 /// Essentially it concatenates V1 and V2, shifts right by some number of
11675 /// elements, and takes the low elements as the result. Note that while this is
11676 /// specified as a *right shift* because x86 is little-endian, it is a *left
11677 /// rotate* of the vector lanes.
11678 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
11679 SDValue V2, ArrayRef<int> Mask,
11680 const APInt &Zeroable,
11681 const X86Subtarget &Subtarget,
11682 SelectionDAG &DAG) {
11683 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
11684 "Only 32-bit and 64-bit elements are supported!");
11686 // 128/256-bit vectors are only supported with VLX.
11687 assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
11688 && "VLX required for 128/256-bit vectors");
11690 SDValue Lo = V1, Hi = V2;
11691 int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
11692 if (0 < Rotation)
11693 return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
11694 DAG.getTargetConstant(Rotation, DL, MVT::i8));
11696 // See if we can use VALIGN as a cross-lane version of VSHLDQ/VSRLDQ.
11697 // TODO: Pull this out as a matchShuffleAsElementShift helper?
11698 // TODO: We can probably make this more aggressive and use shift-pairs like
11699 // lowerShuffleAsByteShiftMask.
11700 unsigned NumElts = Mask.size();
11701 unsigned ZeroLo = Zeroable.countr_one();
11702 unsigned ZeroHi = Zeroable.countl_one();
11703 assert((ZeroLo + ZeroHi) < NumElts && "Zeroable shuffle detected");
11704 if (!ZeroLo && !ZeroHi)
11705 return SDValue();
11707 if (ZeroLo) {
11708 SDValue Src = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11709 int Low = Mask[ZeroLo] < (int)NumElts ? 0 : NumElts;
11710 if (isSequentialOrUndefInRange(Mask, ZeroLo, NumElts - ZeroLo, Low))
11711 return DAG.getNode(X86ISD::VALIGN, DL, VT, Src,
11712 getZeroVector(VT, Subtarget, DAG, DL),
11713 DAG.getTargetConstant(NumElts - ZeroLo, DL, MVT::i8));
11716 if (ZeroHi) {
11717 SDValue Src = Mask[0] < (int)NumElts ? V1 : V2;
11718 int Low = Mask[0] < (int)NumElts ? 0 : NumElts;
11719 if (isSequentialOrUndefInRange(Mask, 0, NumElts - ZeroHi, Low + ZeroHi))
11720 return DAG.getNode(X86ISD::VALIGN, DL, VT,
11721 getZeroVector(VT, Subtarget, DAG, DL), Src,
11722 DAG.getTargetConstant(ZeroHi, DL, MVT::i8));
11725 return SDValue();
11728 /// Try to lower a vector shuffle as a byte shift sequence.
11729 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
11730 SDValue V2, ArrayRef<int> Mask,
11731 const APInt &Zeroable,
11732 const X86Subtarget &Subtarget,
11733 SelectionDAG &DAG) {
11734 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11735 assert(VT.is128BitVector() && "Only 128-bit vectors supported");
11737 // We need a shuffle that has zeros at one/both ends and a sequential
11738 // shuffle from one source within.
11739 unsigned ZeroLo = Zeroable.countr_one();
11740 unsigned ZeroHi = Zeroable.countl_one();
11741 if (!ZeroLo && !ZeroHi)
11742 return SDValue();
11744 unsigned NumElts = Mask.size();
11745 unsigned Len = NumElts - (ZeroLo + ZeroHi);
11746 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
11747 return SDValue();
11749 unsigned Scale = VT.getScalarSizeInBits() / 8;
11750 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
11751 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
11752 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
11753 return SDValue();
11755 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11756 Res = DAG.getBitcast(MVT::v16i8, Res);
11758 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
11759 // inner sequential set of elements, possibly offset:
11760 // 01234567 --> zzzzzz01 --> 1zzzzzzz
11761 // 01234567 --> 4567zzzz --> zzzzz456
11762 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
11763 if (ZeroLo == 0) {
11764 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11765 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11766 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11767 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11768 DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
11769 } else if (ZeroHi == 0) {
11770 unsigned Shift = Mask[ZeroLo] % NumElts;
11771 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11772 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11773 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11774 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11775 } else if (!Subtarget.hasSSSE3()) {
11776 // If we don't have PSHUFB then its worth avoiding an AND constant mask
11777 // by performing 3 byte shifts. Shuffle combining can kick in above that.
11778 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
11779 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11780 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11781 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11782 Shift += Mask[ZeroLo] % NumElts;
11783 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11784 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11785 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11786 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11787 } else
11788 return SDValue();
11790 return DAG.getBitcast(VT, Res);
11793 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
11795 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
11796 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
11797 /// matches elements from one of the input vectors shuffled to the left or
11798 /// right with zeroable elements 'shifted in'. It handles both the strictly
11799 /// bit-wise element shifts and the byte shift across an entire 128-bit double
11800 /// quad word lane.
11802 /// PSHL : (little-endian) left bit shift.
11803 /// [ zz, 0, zz, 2 ]
11804 /// [ -1, 4, zz, -1 ]
11805 /// PSRL : (little-endian) right bit shift.
11806 /// [ 1, zz, 3, zz]
11807 /// [ -1, -1, 7, zz]
11808 /// PSLLDQ : (little-endian) left byte shift
11809 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
11810 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
11811 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
11812 /// PSRLDQ : (little-endian) right byte shift
11813 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
11814 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
11815 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
11816 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
11817 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
11818 int MaskOffset, const APInt &Zeroable,
11819 const X86Subtarget &Subtarget) {
11820 int Size = Mask.size();
11821 unsigned SizeInBits = Size * ScalarSizeInBits;
11823 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
11824 for (int i = 0; i < Size; i += Scale)
11825 for (int j = 0; j < Shift; ++j)
11826 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
11827 return false;
11829 return true;
11832 auto MatchShift = [&](int Shift, int Scale, bool Left) {
11833 for (int i = 0; i != Size; i += Scale) {
11834 unsigned Pos = Left ? i + Shift : i;
11835 unsigned Low = Left ? i : i + Shift;
11836 unsigned Len = Scale - Shift;
11837 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
11838 return -1;
11841 int ShiftEltBits = ScalarSizeInBits * Scale;
11842 bool ByteShift = ShiftEltBits > 64;
11843 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
11844 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
11845 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
11847 // Normalize the scale for byte shifts to still produce an i64 element
11848 // type.
11849 Scale = ByteShift ? Scale / 2 : Scale;
11851 // We need to round trip through the appropriate type for the shift.
11852 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
11853 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
11854 : MVT::getVectorVT(ShiftSVT, Size / Scale);
11855 return (int)ShiftAmt;
11858 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
11859 // keep doubling the size of the integer elements up to that. We can
11860 // then shift the elements of the integer vector by whole multiples of
11861 // their width within the elements of the larger integer vector. Test each
11862 // multiple to see if we can find a match with the moved element indices
11863 // and that the shifted in elements are all zeroable.
11864 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
11865 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
11866 for (int Shift = 1; Shift != Scale; ++Shift)
11867 for (bool Left : {true, false})
11868 if (CheckZeros(Shift, Scale, Left)) {
11869 int ShiftAmt = MatchShift(Shift, Scale, Left);
11870 if (0 < ShiftAmt)
11871 return ShiftAmt;
11874 // no match
11875 return -1;
11878 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
11879 SDValue V2, ArrayRef<int> Mask,
11880 const APInt &Zeroable,
11881 const X86Subtarget &Subtarget,
11882 SelectionDAG &DAG, bool BitwiseOnly) {
11883 int Size = Mask.size();
11884 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11886 MVT ShiftVT;
11887 SDValue V = V1;
11888 unsigned Opcode;
11890 // Try to match shuffle against V1 shift.
11891 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11892 Mask, 0, Zeroable, Subtarget);
11894 // If V1 failed, try to match shuffle against V2 shift.
11895 if (ShiftAmt < 0) {
11896 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11897 Mask, Size, Zeroable, Subtarget);
11898 V = V2;
11901 if (ShiftAmt < 0)
11902 return SDValue();
11904 if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
11905 return SDValue();
11907 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
11908 "Illegal integer vector type");
11909 V = DAG.getBitcast(ShiftVT, V);
11910 V = DAG.getNode(Opcode, DL, ShiftVT, V,
11911 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
11912 return DAG.getBitcast(VT, V);
11915 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
11916 // Remainder of lower half result is zero and upper half is all undef.
11917 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
11918 ArrayRef<int> Mask, uint64_t &BitLen,
11919 uint64_t &BitIdx, const APInt &Zeroable) {
11920 int Size = Mask.size();
11921 int HalfSize = Size / 2;
11922 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11923 assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
11925 // Upper half must be undefined.
11926 if (!isUndefUpperHalf(Mask))
11927 return false;
11929 // Determine the extraction length from the part of the
11930 // lower half that isn't zeroable.
11931 int Len = HalfSize;
11932 for (; Len > 0; --Len)
11933 if (!Zeroable[Len - 1])
11934 break;
11935 assert(Len > 0 && "Zeroable shuffle mask");
11937 // Attempt to match first Len sequential elements from the lower half.
11938 SDValue Src;
11939 int Idx = -1;
11940 for (int i = 0; i != Len; ++i) {
11941 int M = Mask[i];
11942 if (M == SM_SentinelUndef)
11943 continue;
11944 SDValue &V = (M < Size ? V1 : V2);
11945 M = M % Size;
11947 // The extracted elements must start at a valid index and all mask
11948 // elements must be in the lower half.
11949 if (i > M || M >= HalfSize)
11950 return false;
11952 if (Idx < 0 || (Src == V && Idx == (M - i))) {
11953 Src = V;
11954 Idx = M - i;
11955 continue;
11957 return false;
11960 if (!Src || Idx < 0)
11961 return false;
11963 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
11964 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11965 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11966 V1 = Src;
11967 return true;
11970 // INSERTQ: Extract lowest Len elements from lower half of second source and
11971 // insert over first source, starting at Idx.
11972 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
11973 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
11974 ArrayRef<int> Mask, uint64_t &BitLen,
11975 uint64_t &BitIdx) {
11976 int Size = Mask.size();
11977 int HalfSize = Size / 2;
11978 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11980 // Upper half must be undefined.
11981 if (!isUndefUpperHalf(Mask))
11982 return false;
11984 for (int Idx = 0; Idx != HalfSize; ++Idx) {
11985 SDValue Base;
11987 // Attempt to match first source from mask before insertion point.
11988 if (isUndefInRange(Mask, 0, Idx)) {
11989 /* EMPTY */
11990 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
11991 Base = V1;
11992 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
11993 Base = V2;
11994 } else {
11995 continue;
11998 // Extend the extraction length looking to match both the insertion of
11999 // the second source and the remaining elements of the first.
12000 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12001 SDValue Insert;
12002 int Len = Hi - Idx;
12004 // Match insertion.
12005 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12006 Insert = V1;
12007 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12008 Insert = V2;
12009 } else {
12010 continue;
12013 // Match the remaining elements of the lower half.
12014 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12015 /* EMPTY */
12016 } else if ((!Base || (Base == V1)) &&
12017 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12018 Base = V1;
12019 } else if ((!Base || (Base == V2)) &&
12020 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12021 Size + Hi)) {
12022 Base = V2;
12023 } else {
12024 continue;
12027 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12028 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12029 V1 = Base;
12030 V2 = Insert;
12031 return true;
12035 return false;
12038 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
12039 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
12040 SDValue V2, ArrayRef<int> Mask,
12041 const APInt &Zeroable, SelectionDAG &DAG) {
12042 uint64_t BitLen, BitIdx;
12043 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12044 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12045 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12046 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12048 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12049 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12050 V2 ? V2 : DAG.getUNDEF(VT),
12051 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12052 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12054 return SDValue();
12057 /// Lower a vector shuffle as a zero or any extension.
12059 /// Given a specific number of elements, element bit width, and extension
12060 /// stride, produce either a zero or any extension based on the available
12061 /// features of the subtarget. The extended elements are consecutive and
12062 /// begin and can start from an offsetted element index in the input; to
12063 /// avoid excess shuffling the offset must either being in the bottom lane
12064 /// or at the start of a higher lane. All extended elements must be from
12065 /// the same lane.
12066 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
12067 const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
12068 ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12069 assert(Scale > 1 && "Need a scale to extend.");
12070 int EltBits = VT.getScalarSizeInBits();
12071 int NumElements = VT.getVectorNumElements();
12072 int NumEltsPerLane = 128 / EltBits;
12073 int OffsetLane = Offset / NumEltsPerLane;
12074 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12075 "Only 8, 16, and 32 bit elements can be extended.");
12076 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12077 assert(0 <= Offset && "Extension offset must be positive.");
12078 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12079 "Extension offset must be in the first lane or start an upper lane.");
12081 // Check that an index is in same lane as the base offset.
12082 auto SafeOffset = [&](int Idx) {
12083 return OffsetLane == (Idx / NumEltsPerLane);
12086 // Shift along an input so that the offset base moves to the first element.
12087 auto ShuffleOffset = [&](SDValue V) {
12088 if (!Offset)
12089 return V;
12091 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12092 for (int i = 0; i * Scale < NumElements; ++i) {
12093 int SrcIdx = i + Offset;
12094 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12096 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12099 // Found a valid a/zext mask! Try various lowering strategies based on the
12100 // input type and available ISA extensions.
12101 if (Subtarget.hasSSE41()) {
12102 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12103 // PUNPCK will catch this in a later shuffle match.
12104 if (Offset && Scale == 2 && VT.is128BitVector())
12105 return SDValue();
12106 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12107 NumElements / Scale);
12108 InputV = DAG.getBitcast(VT, InputV);
12109 InputV = ShuffleOffset(InputV);
12110 InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
12111 DL, ExtVT, InputV, DAG);
12112 return DAG.getBitcast(VT, InputV);
12115 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12116 InputV = DAG.getBitcast(VT, InputV);
12118 // For any extends we can cheat for larger element sizes and use shuffle
12119 // instructions that can fold with a load and/or copy.
12120 if (AnyExt && EltBits == 32) {
12121 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12122 -1};
12123 return DAG.getBitcast(
12124 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12125 DAG.getBitcast(MVT::v4i32, InputV),
12126 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12128 if (AnyExt && EltBits == 16 && Scale > 2) {
12129 int PSHUFDMask[4] = {Offset / 2, -1,
12130 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12131 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12132 DAG.getBitcast(MVT::v4i32, InputV),
12133 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12134 int PSHUFWMask[4] = {1, -1, -1, -1};
12135 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12136 return DAG.getBitcast(
12137 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12138 DAG.getBitcast(MVT::v8i16, InputV),
12139 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12142 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12143 // to 64-bits.
12144 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12145 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12146 assert(VT.is128BitVector() && "Unexpected vector width!");
12148 int LoIdx = Offset * EltBits;
12149 SDValue Lo = DAG.getBitcast(
12150 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12151 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12152 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12154 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12155 return DAG.getBitcast(VT, Lo);
12157 int HiIdx = (Offset + 1) * EltBits;
12158 SDValue Hi = DAG.getBitcast(
12159 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12160 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12161 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12162 return DAG.getBitcast(VT,
12163 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12166 // If this would require more than 2 unpack instructions to expand, use
12167 // pshufb when available. We can only use more than 2 unpack instructions
12168 // when zero extending i8 elements which also makes it easier to use pshufb.
12169 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12170 assert(NumElements == 16 && "Unexpected byte vector width!");
12171 SDValue PSHUFBMask[16];
12172 for (int i = 0; i < 16; ++i) {
12173 int Idx = Offset + (i / Scale);
12174 if ((i % Scale == 0 && SafeOffset(Idx))) {
12175 PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12176 continue;
12178 PSHUFBMask[i] =
12179 AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12181 InputV = DAG.getBitcast(MVT::v16i8, InputV);
12182 return DAG.getBitcast(
12183 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12184 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12187 // If we are extending from an offset, ensure we start on a boundary that
12188 // we can unpack from.
12189 int AlignToUnpack = Offset % (NumElements / Scale);
12190 if (AlignToUnpack) {
12191 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12192 for (int i = AlignToUnpack; i < NumElements; ++i)
12193 ShMask[i - AlignToUnpack] = i;
12194 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12195 Offset -= AlignToUnpack;
12198 // Otherwise emit a sequence of unpacks.
12199 do {
12200 unsigned UnpackLoHi = X86ISD::UNPCKL;
12201 if (Offset >= (NumElements / 2)) {
12202 UnpackLoHi = X86ISD::UNPCKH;
12203 Offset -= (NumElements / 2);
12206 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12207 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12208 : getZeroVector(InputVT, Subtarget, DAG, DL);
12209 InputV = DAG.getBitcast(InputVT, InputV);
12210 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12211 Scale /= 2;
12212 EltBits *= 2;
12213 NumElements /= 2;
12214 } while (Scale > 1);
12215 return DAG.getBitcast(VT, InputV);
12218 /// Try to lower a vector shuffle as a zero extension on any microarch.
12220 /// This routine will try to do everything in its power to cleverly lower
12221 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
12222 /// check for the profitability of this lowering, it tries to aggressively
12223 /// match this pattern. It will use all of the micro-architectural details it
12224 /// can to emit an efficient lowering. It handles both blends with all-zero
12225 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12226 /// masking out later).
12228 /// The reason we have dedicated lowering for zext-style shuffles is that they
12229 /// are both incredibly common and often quite performance sensitive.
12230 static SDValue lowerShuffleAsZeroOrAnyExtend(
12231 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12232 const APInt &Zeroable, const X86Subtarget &Subtarget,
12233 SelectionDAG &DAG) {
12234 int Bits = VT.getSizeInBits();
12235 int NumLanes = Bits / 128;
12236 int NumElements = VT.getVectorNumElements();
12237 int NumEltsPerLane = NumElements / NumLanes;
12238 assert(VT.getScalarSizeInBits() <= 32 &&
12239 "Exceeds 32-bit integer zero extension limit");
12240 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12242 // Define a helper function to check a particular ext-scale and lower to it if
12243 // valid.
12244 auto Lower = [&](int Scale) -> SDValue {
12245 SDValue InputV;
12246 bool AnyExt = true;
12247 int Offset = 0;
12248 int Matches = 0;
12249 for (int i = 0; i < NumElements; ++i) {
12250 int M = Mask[i];
12251 if (M < 0)
12252 continue; // Valid anywhere but doesn't tell us anything.
12253 if (i % Scale != 0) {
12254 // Each of the extended elements need to be zeroable.
12255 if (!Zeroable[i])
12256 return SDValue();
12258 // We no longer are in the anyext case.
12259 AnyExt = false;
12260 continue;
12263 // Each of the base elements needs to be consecutive indices into the
12264 // same input vector.
12265 SDValue V = M < NumElements ? V1 : V2;
12266 M = M % NumElements;
12267 if (!InputV) {
12268 InputV = V;
12269 Offset = M - (i / Scale);
12270 } else if (InputV != V)
12271 return SDValue(); // Flip-flopping inputs.
12273 // Offset must start in the lowest 128-bit lane or at the start of an
12274 // upper lane.
12275 // FIXME: Is it ever worth allowing a negative base offset?
12276 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12277 (Offset % NumEltsPerLane) == 0))
12278 return SDValue();
12280 // If we are offsetting, all referenced entries must come from the same
12281 // lane.
12282 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12283 return SDValue();
12285 if ((M % NumElements) != (Offset + (i / Scale)))
12286 return SDValue(); // Non-consecutive strided elements.
12287 Matches++;
12290 // If we fail to find an input, we have a zero-shuffle which should always
12291 // have already been handled.
12292 // FIXME: Maybe handle this here in case during blending we end up with one?
12293 if (!InputV)
12294 return SDValue();
12296 // If we are offsetting, don't extend if we only match a single input, we
12297 // can always do better by using a basic PSHUF or PUNPCK.
12298 if (Offset != 0 && Matches < 2)
12299 return SDValue();
12301 return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
12302 InputV, Mask, Subtarget, DAG);
12305 // The widest scale possible for extending is to a 64-bit integer.
12306 assert(Bits % 64 == 0 &&
12307 "The number of bits in a vector must be divisible by 64 on x86!");
12308 int NumExtElements = Bits / 64;
12310 // Each iteration, try extending the elements half as much, but into twice as
12311 // many elements.
12312 for (; NumExtElements < NumElements; NumExtElements *= 2) {
12313 assert(NumElements % NumExtElements == 0 &&
12314 "The input vector size must be divisible by the extended size.");
12315 if (SDValue V = Lower(NumElements / NumExtElements))
12316 return V;
12319 // General extends failed, but 128-bit vectors may be able to use MOVQ.
12320 if (Bits != 128)
12321 return SDValue();
12323 // Returns one of the source operands if the shuffle can be reduced to a
12324 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
12325 auto CanZExtLowHalf = [&]() {
12326 for (int i = NumElements / 2; i != NumElements; ++i)
12327 if (!Zeroable[i])
12328 return SDValue();
12329 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
12330 return V1;
12331 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
12332 return V2;
12333 return SDValue();
12336 if (SDValue V = CanZExtLowHalf()) {
12337 V = DAG.getBitcast(MVT::v2i64, V);
12338 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
12339 return DAG.getBitcast(VT, V);
12342 // No viable ext lowering found.
12343 return SDValue();
12346 /// Try to get a scalar value for a specific element of a vector.
12348 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
12349 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
12350 SelectionDAG &DAG) {
12351 MVT VT = V.getSimpleValueType();
12352 MVT EltVT = VT.getVectorElementType();
12353 V = peekThroughBitcasts(V);
12355 // If the bitcasts shift the element size, we can't extract an equivalent
12356 // element from it.
12357 MVT NewVT = V.getSimpleValueType();
12358 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
12359 return SDValue();
12361 if (V.getOpcode() == ISD::BUILD_VECTOR ||
12362 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
12363 // Ensure the scalar operand is the same size as the destination.
12364 // FIXME: Add support for scalar truncation where possible.
12365 SDValue S = V.getOperand(Idx);
12366 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
12367 return DAG.getBitcast(EltVT, S);
12370 return SDValue();
12373 /// Helper to test for a load that can be folded with x86 shuffles.
12375 /// This is particularly important because the set of instructions varies
12376 /// significantly based on whether the operand is a load or not.
12377 static bool isShuffleFoldableLoad(SDValue V) {
12378 return V->hasOneUse() &&
12379 ISD::isNON_EXTLoad(peekThroughOneUseBitcasts(V).getNode());
12382 template<typename T>
12383 static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
12384 T EltVT = VT.getScalarType();
12385 return (EltVT == MVT::bf16 && !Subtarget.hasAVX10_2()) ||
12386 (EltVT == MVT::f16 && !Subtarget.hasFP16());
12389 /// Try to lower insertion of a single element into a zero vector.
12391 /// This is a common pattern that we have especially efficient patterns to lower
12392 /// across all subtarget feature sets.
12393 static SDValue lowerShuffleAsElementInsertion(
12394 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12395 const APInt &Zeroable, const X86Subtarget &Subtarget,
12396 SelectionDAG &DAG) {
12397 MVT ExtVT = VT;
12398 MVT EltVT = VT.getVectorElementType();
12399 unsigned NumElts = VT.getVectorNumElements();
12400 unsigned EltBits = VT.getScalarSizeInBits();
12402 if (isSoftF16(EltVT, Subtarget))
12403 return SDValue();
12405 int V2Index =
12406 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
12407 Mask.begin();
12408 bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
12409 bool IsV1Zeroable = true;
12410 for (int i = 0, Size = Mask.size(); i < Size; ++i)
12411 if (i != V2Index && !Zeroable[i]) {
12412 IsV1Zeroable = false;
12413 break;
12416 // Bail if a non-zero V1 isn't used in place.
12417 if (!IsV1Zeroable) {
12418 SmallVector<int, 8> V1Mask(Mask);
12419 V1Mask[V2Index] = -1;
12420 if (!isNoopShuffleMask(V1Mask))
12421 return SDValue();
12424 // Check for a single input from a SCALAR_TO_VECTOR node.
12425 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
12426 // all the smarts here sunk into that routine. However, the current
12427 // lowering of BUILD_VECTOR makes that nearly impossible until the old
12428 // vector shuffle lowering is dead.
12429 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
12430 DAG);
12431 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
12432 // We need to zext the scalar if it is smaller than an i32.
12433 V2S = DAG.getBitcast(EltVT, V2S);
12434 if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
12435 // Using zext to expand a narrow element won't work for non-zero
12436 // insertions. But we can use a masked constant vector if we're
12437 // inserting V2 into the bottom of V1.
12438 if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
12439 return SDValue();
12441 // Zero-extend directly to i32.
12442 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
12443 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
12445 // If we're inserting into a constant, mask off the inserted index
12446 // and OR with the zero-extended scalar.
12447 if (!IsV1Zeroable) {
12448 SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
12449 Bits[V2Index] = APInt::getZero(EltBits);
12450 SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
12451 V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
12452 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
12453 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
12454 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
12457 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
12458 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
12459 (EltVT == MVT::i16 && !Subtarget.hasAVX10_2())) {
12460 // Either not inserting from the low element of the input or the input
12461 // element size is too small to use VZEXT_MOVL to clear the high bits.
12462 return SDValue();
12465 if (!IsV1Zeroable) {
12466 // If V1 can't be treated as a zero vector we have fewer options to lower
12467 // this. We can't support integer vectors or non-zero targets cheaply.
12468 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
12469 if (!VT.isFloatingPoint() || V2Index != 0)
12470 return SDValue();
12471 if (!VT.is128BitVector())
12472 return SDValue();
12474 // Otherwise, use MOVSD, MOVSS or MOVSH.
12475 unsigned MovOpc = 0;
12476 if (EltVT == MVT::f16)
12477 MovOpc = X86ISD::MOVSH;
12478 else if (EltVT == MVT::f32)
12479 MovOpc = X86ISD::MOVSS;
12480 else if (EltVT == MVT::f64)
12481 MovOpc = X86ISD::MOVSD;
12482 else
12483 llvm_unreachable("Unsupported floating point element type to handle!");
12484 return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
12487 // This lowering only works for the low element with floating point vectors.
12488 if (VT.isFloatingPoint() && V2Index != 0)
12489 return SDValue();
12491 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
12492 if (ExtVT != VT)
12493 V2 = DAG.getBitcast(VT, V2);
12495 if (V2Index != 0) {
12496 // If we have 4 or fewer lanes we can cheaply shuffle the element into
12497 // the desired position. Otherwise it is more efficient to do a vector
12498 // shift left. We know that we can do a vector shift left because all
12499 // the inputs are zero.
12500 if (VT.isFloatingPoint() || NumElts <= 4) {
12501 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
12502 V2Shuffle[V2Index] = 0;
12503 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
12504 } else {
12505 V2 = DAG.getBitcast(MVT::v16i8, V2);
12506 V2 = DAG.getNode(
12507 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
12508 DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
12509 V2 = DAG.getBitcast(VT, V2);
12512 return V2;
12515 /// Try to lower broadcast of a single - truncated - integer element,
12516 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
12518 /// This assumes we have AVX2.
12519 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
12520 int BroadcastIdx,
12521 const X86Subtarget &Subtarget,
12522 SelectionDAG &DAG) {
12523 assert(Subtarget.hasAVX2() &&
12524 "We can only lower integer broadcasts with AVX2!");
12526 MVT EltVT = VT.getVectorElementType();
12527 MVT V0VT = V0.getSimpleValueType();
12529 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
12530 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
12532 MVT V0EltVT = V0VT.getVectorElementType();
12533 if (!V0EltVT.isInteger())
12534 return SDValue();
12536 const unsigned EltSize = EltVT.getSizeInBits();
12537 const unsigned V0EltSize = V0EltVT.getSizeInBits();
12539 // This is only a truncation if the original element type is larger.
12540 if (V0EltSize <= EltSize)
12541 return SDValue();
12543 assert(((V0EltSize % EltSize) == 0) &&
12544 "Scalar type sizes must all be powers of 2 on x86!");
12546 const unsigned V0Opc = V0.getOpcode();
12547 const unsigned Scale = V0EltSize / EltSize;
12548 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
12550 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
12551 V0Opc != ISD::BUILD_VECTOR)
12552 return SDValue();
12554 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
12556 // If we're extracting non-least-significant bits, shift so we can truncate.
12557 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
12558 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
12559 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
12560 if (const int OffsetIdx = BroadcastIdx % Scale)
12561 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
12562 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
12564 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
12565 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
12568 /// Test whether this can be lowered with a single SHUFPS instruction.
12570 /// This is used to disable more specialized lowerings when the shufps lowering
12571 /// will happen to be efficient.
12572 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
12573 // This routine only handles 128-bit shufps.
12574 assert(Mask.size() == 4 && "Unsupported mask size!");
12575 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
12576 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
12577 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
12578 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
12580 // To lower with a single SHUFPS we need to have the low half and high half
12581 // each requiring a single input.
12582 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
12583 return false;
12584 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
12585 return false;
12587 return true;
12590 /// Test whether the specified input (0 or 1) is in-place blended by the
12591 /// given mask.
12593 /// This returns true if the elements from a particular input are already in the
12594 /// slot required by the given mask and require no permutation.
12595 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
12596 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
12597 int Size = Mask.size();
12598 for (int i = 0; i < Size; ++i)
12599 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
12600 return false;
12602 return true;
12605 /// If we are extracting two 128-bit halves of a vector and shuffling the
12606 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
12607 /// multi-shuffle lowering.
12608 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
12609 SDValue N1, ArrayRef<int> Mask,
12610 SelectionDAG &DAG) {
12611 MVT VT = N0.getSimpleValueType();
12612 assert((VT.is128BitVector() &&
12613 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
12614 "VPERM* family of shuffles requires 32-bit or 64-bit elements");
12616 // Check that both sources are extracts of the same source vector.
12617 if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12618 N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12619 N0.getOperand(0) != N1.getOperand(0) ||
12620 !N0.hasOneUse() || !N1.hasOneUse())
12621 return SDValue();
12623 SDValue WideVec = N0.getOperand(0);
12624 MVT WideVT = WideVec.getSimpleValueType();
12625 if (!WideVT.is256BitVector())
12626 return SDValue();
12628 // Match extracts of each half of the wide source vector. Commute the shuffle
12629 // if the extract of the low half is N1.
12630 unsigned NumElts = VT.getVectorNumElements();
12631 SmallVector<int, 4> NewMask(Mask);
12632 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
12633 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
12634 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
12635 ShuffleVectorSDNode::commuteMask(NewMask);
12636 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
12637 return SDValue();
12639 // Final bailout: if the mask is simple, we are better off using an extract
12640 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
12641 // because that avoids a constant load from memory.
12642 if (NumElts == 4 &&
12643 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
12644 return SDValue();
12646 // Extend the shuffle mask with undef elements.
12647 NewMask.append(NumElts, -1);
12649 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
12650 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
12651 NewMask);
12652 // This is free: ymm -> xmm.
12653 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
12654 DAG.getIntPtrConstant(0, DL));
12657 /// Try to lower broadcast of a single element.
12659 /// For convenience, this code also bundles all of the subtarget feature set
12660 /// filtering. While a little annoying to re-dispatch on type here, there isn't
12661 /// a convenient way to factor it out.
12662 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
12663 SDValue V2, ArrayRef<int> Mask,
12664 const X86Subtarget &Subtarget,
12665 SelectionDAG &DAG) {
12666 MVT EltVT = VT.getVectorElementType();
12667 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
12668 (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
12669 (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
12670 return SDValue();
12672 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
12673 // we can only broadcast from a register with AVX2.
12674 unsigned NumEltBits = VT.getScalarSizeInBits();
12675 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
12676 ? X86ISD::MOVDDUP
12677 : X86ISD::VBROADCAST;
12678 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
12680 // Check that the mask is a broadcast.
12681 int BroadcastIdx = getSplatIndex(Mask);
12682 if (BroadcastIdx < 0)
12683 return SDValue();
12684 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
12685 "a sorted mask where the broadcast "
12686 "comes from V1.");
12687 int NumActiveElts = count_if(Mask, [](int M) { return M >= 0; });
12689 // Go up the chain of (vector) values to find a scalar load that we can
12690 // combine with the broadcast.
12691 // TODO: Combine this logic with findEltLoadSrc() used by
12692 // EltsFromConsecutiveLoads().
12693 int BitOffset = BroadcastIdx * NumEltBits;
12694 SDValue V = V1;
12695 for (;;) {
12696 switch (V.getOpcode()) {
12697 case ISD::BITCAST: {
12698 V = V.getOperand(0);
12699 continue;
12701 case ISD::CONCAT_VECTORS: {
12702 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
12703 int OpIdx = BitOffset / OpBitWidth;
12704 V = V.getOperand(OpIdx);
12705 BitOffset %= OpBitWidth;
12706 continue;
12708 case ISD::EXTRACT_SUBVECTOR: {
12709 // The extraction index adds to the existing offset.
12710 unsigned EltBitWidth = V.getScalarValueSizeInBits();
12711 unsigned Idx = V.getConstantOperandVal(1);
12712 unsigned BeginOffset = Idx * EltBitWidth;
12713 BitOffset += BeginOffset;
12714 V = V.getOperand(0);
12715 continue;
12717 case ISD::INSERT_SUBVECTOR: {
12718 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
12719 int EltBitWidth = VOuter.getScalarValueSizeInBits();
12720 int Idx = (int)V.getConstantOperandVal(2);
12721 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
12722 int BeginOffset = Idx * EltBitWidth;
12723 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
12724 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
12725 BitOffset -= BeginOffset;
12726 V = VInner;
12727 } else {
12728 V = VOuter;
12730 continue;
12733 break;
12735 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
12736 BroadcastIdx = BitOffset / NumEltBits;
12738 // Do we need to bitcast the source to retrieve the original broadcast index?
12739 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
12741 // Check if this is a broadcast of a scalar. We special case lowering
12742 // for scalars so that we can more effectively fold with loads.
12743 // If the original value has a larger element type than the shuffle, the
12744 // broadcast element is in essence truncated. Make that explicit to ease
12745 // folding.
12746 if (BitCastSrc && VT.isInteger())
12747 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
12748 DL, VT, V, BroadcastIdx, Subtarget, DAG))
12749 return TruncBroadcast;
12751 // Also check the simpler case, where we can directly reuse the scalar.
12752 if (!BitCastSrc &&
12753 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
12754 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
12755 V = V.getOperand(BroadcastIdx);
12757 // If we can't broadcast from a register, check that the input is a load.
12758 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
12759 return SDValue();
12760 } else if (ISD::isNormalLoad(V.getNode()) &&
12761 cast<LoadSDNode>(V)->isSimple()) {
12762 // We do not check for one-use of the vector load because a broadcast load
12763 // is expected to be a win for code size, register pressure, and possibly
12764 // uops even if the original vector load is not eliminated.
12766 // Reduce the vector load and shuffle to a broadcasted scalar load.
12767 LoadSDNode *Ld = cast<LoadSDNode>(V);
12768 SDValue BaseAddr = Ld->getOperand(1);
12769 MVT SVT = VT.getScalarType();
12770 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
12771 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
12772 SDValue NewAddr =
12773 DAG.getMemBasePlusOffset(BaseAddr, TypeSize::getFixed(Offset), DL);
12775 // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
12776 // than MOVDDUP.
12777 // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
12778 if (Opcode == X86ISD::VBROADCAST) {
12779 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
12780 SDValue Ops[] = {Ld->getChain(), NewAddr};
12781 V = DAG.getMemIntrinsicNode(
12782 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
12783 DAG.getMachineFunction().getMachineMemOperand(
12784 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12785 DAG.makeEquivalentMemoryOrdering(Ld, V);
12786 return DAG.getBitcast(VT, V);
12788 assert(SVT == MVT::f64 && "Unexpected VT!");
12789 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
12790 DAG.getMachineFunction().getMachineMemOperand(
12791 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12792 DAG.makeEquivalentMemoryOrdering(Ld, V);
12793 } else if (!BroadcastFromReg) {
12794 // We can't broadcast from a vector register.
12795 return SDValue();
12796 } else if (BitOffset != 0) {
12797 // We can only broadcast from the zero-element of a vector register,
12798 // but it can be advantageous to broadcast from the zero-element of a
12799 // subvector.
12800 if (!VT.is256BitVector() && !VT.is512BitVector())
12801 return SDValue();
12803 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
12804 if (VT == MVT::v4f64 || VT == MVT::v4i64)
12805 return SDValue();
12807 // If we are broadcasting an element from the lowest 128-bit subvector, try
12808 // to move the element in position.
12809 if (BitOffset < 128 && NumActiveElts > 1 &&
12810 V.getScalarValueSizeInBits() == NumEltBits) {
12811 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
12812 "Unexpected bit-offset");
12813 SmallVector<int, 16> ExtractMask(128 / NumEltBits, SM_SentinelUndef);
12814 ExtractMask[0] = BitOffset / V.getScalarValueSizeInBits();
12815 V = extractSubVector(V, 0, DAG, DL, 128);
12816 V = DAG.getVectorShuffle(V.getValueType(), DL, V, V, ExtractMask);
12817 } else {
12818 // Only broadcast the zero-element of a 128-bit subvector.
12819 if ((BitOffset % 128) != 0)
12820 return SDValue();
12822 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
12823 "Unexpected bit-offset");
12824 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
12825 "Unexpected vector size");
12826 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
12827 V = extract128BitVector(V, ExtractIdx, DAG, DL);
12831 // On AVX we can use VBROADCAST directly for scalar sources.
12832 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
12833 V = DAG.getBitcast(MVT::f64, V);
12834 if (Subtarget.hasAVX()) {
12835 V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
12836 return DAG.getBitcast(VT, V);
12838 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
12841 // If this is a scalar, do the broadcast on this type and bitcast.
12842 if (!V.getValueType().isVector()) {
12843 assert(V.getScalarValueSizeInBits() == NumEltBits &&
12844 "Unexpected scalar size");
12845 MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
12846 VT.getVectorNumElements());
12847 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
12850 // We only support broadcasting from 128-bit vectors to minimize the
12851 // number of patterns we need to deal with in isel. So extract down to
12852 // 128-bits, removing as many bitcasts as possible.
12853 if (V.getValueSizeInBits() > 128)
12854 V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
12856 // Otherwise cast V to a vector with the same element type as VT, but
12857 // possibly narrower than VT. Then perform the broadcast.
12858 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
12859 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
12860 return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
12863 // Check for whether we can use INSERTPS to perform the shuffle. We only use
12864 // INSERTPS when the V1 elements are already in the correct locations
12865 // because otherwise we can just always use two SHUFPS instructions which
12866 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
12867 // perform INSERTPS if a single V1 element is out of place and all V2
12868 // elements are zeroable.
12869 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
12870 unsigned &InsertPSMask,
12871 const APInt &Zeroable,
12872 ArrayRef<int> Mask, SelectionDAG &DAG) {
12873 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
12874 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
12875 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12877 // Attempt to match INSERTPS with one element from VA or VB being
12878 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
12879 // are updated.
12880 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
12881 ArrayRef<int> CandidateMask) {
12882 unsigned ZMask = 0;
12883 int VADstIndex = -1;
12884 int VBDstIndex = -1;
12885 bool VAUsedInPlace = false;
12887 for (int i = 0; i < 4; ++i) {
12888 // Synthesize a zero mask from the zeroable elements (includes undefs).
12889 if (Zeroable[i]) {
12890 ZMask |= 1 << i;
12891 continue;
12894 // Flag if we use any VA inputs in place.
12895 if (i == CandidateMask[i]) {
12896 VAUsedInPlace = true;
12897 continue;
12900 // We can only insert a single non-zeroable element.
12901 if (VADstIndex >= 0 || VBDstIndex >= 0)
12902 return false;
12904 if (CandidateMask[i] < 4) {
12905 // VA input out of place for insertion.
12906 VADstIndex = i;
12907 } else {
12908 // VB input for insertion.
12909 VBDstIndex = i;
12913 // Don't bother if we have no (non-zeroable) element for insertion.
12914 if (VADstIndex < 0 && VBDstIndex < 0)
12915 return false;
12917 // Determine element insertion src/dst indices. The src index is from the
12918 // start of the inserted vector, not the start of the concatenated vector.
12919 unsigned VBSrcIndex = 0;
12920 if (VADstIndex >= 0) {
12921 // If we have a VA input out of place, we use VA as the V2 element
12922 // insertion and don't use the original V2 at all.
12923 VBSrcIndex = CandidateMask[VADstIndex];
12924 VBDstIndex = VADstIndex;
12925 VB = VA;
12926 } else {
12927 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
12930 // If no V1 inputs are used in place, then the result is created only from
12931 // the zero mask and the V2 insertion - so remove V1 dependency.
12932 if (!VAUsedInPlace)
12933 VA = DAG.getUNDEF(MVT::v4f32);
12935 // Update V1, V2 and InsertPSMask accordingly.
12936 V1 = VA;
12937 V2 = VB;
12939 // Insert the V2 element into the desired position.
12940 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
12941 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
12942 return true;
12945 if (matchAsInsertPS(V1, V2, Mask))
12946 return true;
12948 // Commute and try again.
12949 SmallVector<int, 4> CommutedMask(Mask);
12950 ShuffleVectorSDNode::commuteMask(CommutedMask);
12951 if (matchAsInsertPS(V2, V1, CommutedMask))
12952 return true;
12954 return false;
12957 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
12958 ArrayRef<int> Mask, const APInt &Zeroable,
12959 SelectionDAG &DAG) {
12960 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12961 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12963 // Attempt to match the insertps pattern.
12964 unsigned InsertPSMask = 0;
12965 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
12966 return SDValue();
12968 // Insert the V2 element into the desired position.
12969 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
12970 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
12973 /// Handle lowering of 2-lane 64-bit floating point shuffles.
12975 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
12976 /// support for floating point shuffles but not integer shuffles. These
12977 /// instructions will incur a domain crossing penalty on some chips though so
12978 /// it is better to avoid lowering through this for integer vectors where
12979 /// possible.
12980 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12981 const APInt &Zeroable, SDValue V1, SDValue V2,
12982 const X86Subtarget &Subtarget,
12983 SelectionDAG &DAG) {
12984 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12985 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12986 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
12988 if (V2.isUndef()) {
12989 // Check for being able to broadcast a single element.
12990 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
12991 Mask, Subtarget, DAG))
12992 return Broadcast;
12994 // Straight shuffle of a single input vector. Simulate this by using the
12995 // single input as both of the "inputs" to this instruction..
12996 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
12998 if (Subtarget.hasAVX()) {
12999 // If we have AVX, we can use VPERMILPS which will allow folding a load
13000 // into the shuffle.
13001 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13002 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13005 return DAG.getNode(
13006 X86ISD::SHUFP, DL, MVT::v2f64,
13007 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13008 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13009 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13011 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13012 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13013 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13014 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13016 if (Subtarget.hasAVX2())
13017 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13018 return Extract;
13020 // When loading a scalar and then shuffling it into a vector we can often do
13021 // the insertion cheaply.
13022 if (SDValue Insertion = lowerShuffleAsElementInsertion(
13023 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13024 return Insertion;
13025 // Try inverting the insertion since for v2 masks it is easy to do and we
13026 // can't reliably sort the mask one way or the other.
13027 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13028 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13029 if (SDValue Insertion = lowerShuffleAsElementInsertion(
13030 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13031 return Insertion;
13033 // Try to use one of the special instruction patterns to handle two common
13034 // blend patterns if a zero-blend above didn't work.
13035 if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
13036 isShuffleEquivalent(Mask, {1, 3}, V1, V2))
13037 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13038 // We can either use a special instruction to load over the low double or
13039 // to move just the low double.
13040 return DAG.getNode(
13041 X86ISD::MOVSD, DL, MVT::v2f64, V2,
13042 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13044 if (Subtarget.hasSSE41())
13045 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13046 Zeroable, Subtarget, DAG))
13047 return Blend;
13049 // Use dedicated unpack instructions for masks that match their pattern.
13050 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, V1, V2, Mask, DAG))
13051 return V;
13053 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13054 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13055 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13058 /// Handle lowering of 2-lane 64-bit integer shuffles.
13060 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13061 /// the integer unit to minimize domain crossing penalties. However, for blends
13062 /// it falls back to the floating point shuffle operation with appropriate bit
13063 /// casting.
13064 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13065 const APInt &Zeroable, SDValue V1, SDValue V2,
13066 const X86Subtarget &Subtarget,
13067 SelectionDAG &DAG) {
13068 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13069 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13070 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13072 if (V2.isUndef()) {
13073 // Check for being able to broadcast a single element.
13074 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13075 Mask, Subtarget, DAG))
13076 return Broadcast;
13078 // Straight shuffle of a single input vector. For everything from SSE2
13079 // onward this has a single fast instruction with no scary immediates.
13080 // We have to map the mask as it is actually a v4i32 shuffle instruction.
13081 V1 = DAG.getBitcast(MVT::v4i32, V1);
13082 int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
13083 Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
13084 Mask[1] < 0 ? -1 : (Mask[1] * 2),
13085 Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
13086 return DAG.getBitcast(
13087 MVT::v2i64,
13088 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13089 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13091 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13092 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13093 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13094 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13096 if (Subtarget.hasAVX2())
13097 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13098 return Extract;
13100 // Try to use shift instructions.
13101 if (SDValue Shift =
13102 lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
13103 DAG, /*BitwiseOnly*/ false))
13104 return Shift;
13106 // When loading a scalar and then shuffling it into a vector we can often do
13107 // the insertion cheaply.
13108 if (SDValue Insertion = lowerShuffleAsElementInsertion(
13109 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13110 return Insertion;
13111 // Try inverting the insertion since for v2 masks it is easy to do and we
13112 // can't reliably sort the mask one way or the other.
13113 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13114 if (SDValue Insertion = lowerShuffleAsElementInsertion(
13115 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13116 return Insertion;
13118 // We have different paths for blend lowering, but they all must use the
13119 // *exact* same predicate.
13120 bool IsBlendSupported = Subtarget.hasSSE41();
13121 if (IsBlendSupported)
13122 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13123 Zeroable, Subtarget, DAG))
13124 return Blend;
13126 // Use dedicated unpack instructions for masks that match their pattern.
13127 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, V1, V2, Mask, DAG))
13128 return V;
13130 // Try to use byte rotation instructions.
13131 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13132 if (Subtarget.hasSSSE3()) {
13133 if (Subtarget.hasVLX())
13134 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
13135 Zeroable, Subtarget, DAG))
13136 return Rotate;
13138 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13139 Subtarget, DAG))
13140 return Rotate;
13143 // If we have direct support for blends, we should lower by decomposing into
13144 // a permute. That will be faster than the domain cross.
13145 if (IsBlendSupported)
13146 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
13147 Zeroable, Subtarget, DAG);
13149 // We implement this with SHUFPD which is pretty lame because it will likely
13150 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13151 // However, all the alternatives are still more cycles and newer chips don't
13152 // have this problem. It would be really nice if x86 had better shuffles here.
13153 V1 = DAG.getBitcast(MVT::v2f64, V1);
13154 V2 = DAG.getBitcast(MVT::v2f64, V2);
13155 return DAG.getBitcast(MVT::v2i64,
13156 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13159 /// Lower a vector shuffle using the SHUFPS instruction.
13161 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13162 /// It makes no assumptions about whether this is the *best* lowering, it simply
13163 /// uses it.
13164 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
13165 ArrayRef<int> Mask, SDValue V1,
13166 SDValue V2, SelectionDAG &DAG) {
13167 SDValue LowV = V1, HighV = V2;
13168 SmallVector<int, 4> NewMask(Mask);
13169 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13171 if (NumV2Elements == 1) {
13172 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13174 // Compute the index adjacent to V2Index and in the same half by toggling
13175 // the low bit.
13176 int V2AdjIndex = V2Index ^ 1;
13178 if (Mask[V2AdjIndex] < 0) {
13179 // Handles all the cases where we have a single V2 element and an undef.
13180 // This will only ever happen in the high lanes because we commute the
13181 // vector otherwise.
13182 if (V2Index < 2)
13183 std::swap(LowV, HighV);
13184 NewMask[V2Index] -= 4;
13185 } else {
13186 // Handle the case where the V2 element ends up adjacent to a V1 element.
13187 // To make this work, blend them together as the first step.
13188 int V1Index = V2AdjIndex;
13189 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13190 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13191 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13193 // Now proceed to reconstruct the final blend as we have the necessary
13194 // high or low half formed.
13195 if (V2Index < 2) {
13196 LowV = V2;
13197 HighV = V1;
13198 } else {
13199 HighV = V2;
13201 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13202 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13204 } else if (NumV2Elements == 2) {
13205 if (Mask[0] < 4 && Mask[1] < 4) {
13206 // Handle the easy case where we have V1 in the low lanes and V2 in the
13207 // high lanes.
13208 NewMask[2] -= 4;
13209 NewMask[3] -= 4;
13210 } else if (Mask[2] < 4 && Mask[3] < 4) {
13211 // We also handle the reversed case because this utility may get called
13212 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13213 // arrange things in the right direction.
13214 NewMask[0] -= 4;
13215 NewMask[1] -= 4;
13216 HighV = V1;
13217 LowV = V2;
13218 } else {
13219 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13220 // trying to place elements directly, just blend them and set up the final
13221 // shuffle to place them.
13223 // The first two blend mask elements are for V1, the second two are for
13224 // V2.
13225 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13226 Mask[2] < 4 ? Mask[2] : Mask[3],
13227 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13228 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13229 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13230 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13232 // Now we do a normal shuffle of V1 by giving V1 as both operands to
13233 // a blend.
13234 LowV = HighV = V1;
13235 NewMask[0] = Mask[0] < 4 ? 0 : 2;
13236 NewMask[1] = Mask[0] < 4 ? 2 : 0;
13237 NewMask[2] = Mask[2] < 4 ? 1 : 3;
13238 NewMask[3] = Mask[2] < 4 ? 3 : 1;
13240 } else if (NumV2Elements == 3) {
13241 // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
13242 // we can get here due to other paths (e.g repeated mask matching) that we
13243 // don't want to do another round of lowerVECTOR_SHUFFLE.
13244 ShuffleVectorSDNode::commuteMask(NewMask);
13245 return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
13247 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13248 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13251 /// Lower 4-lane 32-bit floating point shuffles.
13253 /// Uses instructions exclusively from the floating point unit to minimize
13254 /// domain crossing penalties, as these are sufficient to implement all v4f32
13255 /// shuffles.
13256 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13257 const APInt &Zeroable, SDValue V1, SDValue V2,
13258 const X86Subtarget &Subtarget,
13259 SelectionDAG &DAG) {
13260 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13261 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13262 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13264 if (Subtarget.hasSSE41())
13265 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13266 Zeroable, Subtarget, DAG))
13267 return Blend;
13269 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13271 if (NumV2Elements == 0) {
13272 // Check for being able to broadcast a single element.
13273 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
13274 Mask, Subtarget, DAG))
13275 return Broadcast;
13277 // Use even/odd duplicate instructions for masks that match their pattern.
13278 if (Subtarget.hasSSE3()) {
13279 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
13280 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
13281 if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
13282 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
13285 if (Subtarget.hasAVX()) {
13286 // If we have AVX, we can use VPERMILPS which will allow folding a load
13287 // into the shuffle.
13288 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
13289 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13292 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
13293 // in SSE1 because otherwise they are widened to v2f64 and never get here.
13294 if (!Subtarget.hasSSE2()) {
13295 if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
13296 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
13297 if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
13298 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
13301 // Otherwise, use a straight shuffle of a single input vector. We pass the
13302 // input vector to both operands to simulate this with a SHUFPS.
13303 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
13304 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13307 if (Subtarget.hasSSE2())
13308 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
13309 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
13310 ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
13311 return ZExt;
13314 if (Subtarget.hasAVX2())
13315 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13316 return Extract;
13318 // There are special ways we can lower some single-element blends. However, we
13319 // have custom ways we can lower more complex single-element blends below that
13320 // we defer to if both this and BLENDPS fail to match, so restrict this to
13321 // when the V2 input is targeting element 0 of the mask -- that is the fast
13322 // case here.
13323 if (NumV2Elements == 1 && Mask[0] >= 4)
13324 if (SDValue V = lowerShuffleAsElementInsertion(
13325 DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13326 return V;
13328 if (Subtarget.hasSSE41()) {
13329 // Use INSERTPS if we can complete the shuffle efficiently.
13330 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
13331 return V;
13333 if (!isSingleSHUFPSMask(Mask))
13334 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
13335 V2, Mask, DAG))
13336 return BlendPerm;
13339 // Use low/high mov instructions. These are only valid in SSE1 because
13340 // otherwise they are widened to v2f64 and never get here.
13341 if (!Subtarget.hasSSE2()) {
13342 if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
13343 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
13344 if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
13345 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
13348 // Use dedicated unpack instructions for masks that match their pattern.
13349 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, V1, V2, Mask, DAG))
13350 return V;
13352 // Otherwise fall back to a SHUFPS lowering strategy.
13353 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
13356 /// Lower 4-lane i32 vector shuffles.
13358 /// We try to handle these with integer-domain shuffles where we can, but for
13359 /// blends we use the floating point domain blend instructions.
13360 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13361 const APInt &Zeroable, SDValue V1, SDValue V2,
13362 const X86Subtarget &Subtarget,
13363 SelectionDAG &DAG) {
13364 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13365 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13366 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13368 // Whenever we can lower this as a zext, that instruction is strictly faster
13369 // than any alternative. It also allows us to fold memory operands into the
13370 // shuffle in many cases.
13371 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
13372 Zeroable, Subtarget, DAG))
13373 return ZExt;
13375 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13377 // Try to use shift instructions if fast.
13378 if (Subtarget.preferLowerShuffleAsShift()) {
13379 if (SDValue Shift =
13380 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
13381 Subtarget, DAG, /*BitwiseOnly*/ true))
13382 return Shift;
13383 if (NumV2Elements == 0)
13384 if (SDValue Rotate =
13385 lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
13386 return Rotate;
13389 if (NumV2Elements == 0) {
13390 // Try to use broadcast unless the mask only has one non-undef element.
13391 if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
13392 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
13393 Mask, Subtarget, DAG))
13394 return Broadcast;
13397 // Straight shuffle of a single input vector. For everything from SSE2
13398 // onward this has a single fast instruction with no scary immediates.
13399 // We coerce the shuffle pattern to be compatible with UNPCK instructions
13400 // but we aren't actually going to use the UNPCK instruction because doing
13401 // so prevents folding a load into this instruction or making a copy.
13402 const int UnpackLoMask[] = {0, 0, 1, 1};
13403 const int UnpackHiMask[] = {2, 2, 3, 3};
13404 if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
13405 Mask = UnpackLoMask;
13406 else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
13407 Mask = UnpackHiMask;
13409 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13410 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13413 if (Subtarget.hasAVX2())
13414 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13415 return Extract;
13417 // Try to use shift instructions.
13418 if (SDValue Shift =
13419 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
13420 DAG, /*BitwiseOnly*/ false))
13421 return Shift;
13423 // There are special ways we can lower some single-element blends.
13424 if (NumV2Elements == 1)
13425 if (SDValue V = lowerShuffleAsElementInsertion(
13426 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13427 return V;
13429 // We have different paths for blend lowering, but they all must use the
13430 // *exact* same predicate.
13431 bool IsBlendSupported = Subtarget.hasSSE41();
13432 if (IsBlendSupported)
13433 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
13434 Zeroable, Subtarget, DAG))
13435 return Blend;
13437 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
13438 Zeroable, Subtarget, DAG))
13439 return Masked;
13441 // Use dedicated unpack instructions for masks that match their pattern.
13442 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, V1, V2, Mask, DAG))
13443 return V;
13445 // Try to use byte rotation instructions.
13446 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13447 if (Subtarget.hasSSSE3()) {
13448 if (Subtarget.hasVLX())
13449 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
13450 Zeroable, Subtarget, DAG))
13451 return Rotate;
13453 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
13454 Subtarget, DAG))
13455 return Rotate;
13458 // Assume that a single SHUFPS is faster than an alternative sequence of
13459 // multiple instructions (even if the CPU has a domain penalty).
13460 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
13461 if (!isSingleSHUFPSMask(Mask)) {
13462 // If we have direct support for blends, we should lower by decomposing into
13463 // a permute. That will be faster than the domain cross.
13464 if (IsBlendSupported)
13465 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
13466 Zeroable, Subtarget, DAG);
13468 // Try to lower by permuting the inputs into an unpack instruction.
13469 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
13470 Mask, Subtarget, DAG))
13471 return Unpack;
13474 // We implement this with SHUFPS because it can blend from two vectors.
13475 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
13476 // up the inputs, bypassing domain shift penalties that we would incur if we
13477 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
13478 // relevant.
13479 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
13480 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
13481 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
13482 return DAG.getBitcast(MVT::v4i32, ShufPS);
13485 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
13486 /// shuffle lowering, and the most complex part.
13488 /// The lowering strategy is to try to form pairs of input lanes which are
13489 /// targeted at the same half of the final vector, and then use a dword shuffle
13490 /// to place them onto the right half, and finally unpack the paired lanes into
13491 /// their final position.
13493 /// The exact breakdown of how to form these dword pairs and align them on the
13494 /// correct sides is really tricky. See the comments within the function for
13495 /// more of the details.
13497 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
13498 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
13499 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
13500 /// vector, form the analogous 128-bit 8-element Mask.
13501 static SDValue lowerV8I16GeneralSingleInputShuffle(
13502 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
13503 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13504 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
13505 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
13507 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
13508 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
13509 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
13511 // Attempt to directly match PSHUFLW or PSHUFHW.
13512 if (isUndefOrInRange(LoMask, 0, 4) &&
13513 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
13514 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13515 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13517 if (isUndefOrInRange(HiMask, 4, 8) &&
13518 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
13519 for (int i = 0; i != 4; ++i)
13520 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
13521 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13522 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13525 SmallVector<int, 4> LoInputs;
13526 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
13527 array_pod_sort(LoInputs.begin(), LoInputs.end());
13528 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
13529 SmallVector<int, 4> HiInputs;
13530 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
13531 array_pod_sort(HiInputs.begin(), HiInputs.end());
13532 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
13533 int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
13534 int NumHToL = LoInputs.size() - NumLToL;
13535 int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
13536 int NumHToH = HiInputs.size() - NumLToH;
13537 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
13538 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
13539 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
13540 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
13542 // If we are shuffling values from one half - check how many different DWORD
13543 // pairs we need to create. If only 1 or 2 then we can perform this as a
13544 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
13545 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
13546 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
13547 V = DAG.getNode(ShufWOp, DL, VT, V,
13548 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13549 V = DAG.getBitcast(PSHUFDVT, V);
13550 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
13551 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13552 return DAG.getBitcast(VT, V);
13555 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
13556 int PSHUFDMask[4] = { -1, -1, -1, -1 };
13557 SmallVector<std::pair<int, int>, 4> DWordPairs;
13558 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
13560 // Collect the different DWORD pairs.
13561 for (int DWord = 0; DWord != 4; ++DWord) {
13562 int M0 = Mask[2 * DWord + 0];
13563 int M1 = Mask[2 * DWord + 1];
13564 M0 = (M0 >= 0 ? M0 % 4 : M0);
13565 M1 = (M1 >= 0 ? M1 % 4 : M1);
13566 if (M0 < 0 && M1 < 0)
13567 continue;
13569 bool Match = false;
13570 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
13571 auto &DWordPair = DWordPairs[j];
13572 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
13573 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
13574 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
13575 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
13576 PSHUFDMask[DWord] = DOffset + j;
13577 Match = true;
13578 break;
13581 if (!Match) {
13582 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
13583 DWordPairs.push_back(std::make_pair(M0, M1));
13587 if (DWordPairs.size() <= 2) {
13588 DWordPairs.resize(2, std::make_pair(-1, -1));
13589 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
13590 DWordPairs[1].first, DWordPairs[1].second};
13591 if ((NumHToL + NumHToH) == 0)
13592 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
13593 if ((NumLToL + NumLToH) == 0)
13594 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
13598 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
13599 // such inputs we can swap two of the dwords across the half mark and end up
13600 // with <=2 inputs to each half in each half. Once there, we can fall through
13601 // to the generic code below. For example:
13603 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13604 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
13606 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
13607 // and an existing 2-into-2 on the other half. In this case we may have to
13608 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
13609 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
13610 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
13611 // because any other situation (including a 3-into-1 or 1-into-3 in the other
13612 // half than the one we target for fixing) will be fixed when we re-enter this
13613 // path. We will also combine away any sequence of PSHUFD instructions that
13614 // result into a single instruction. Here is an example of the tricky case:
13616 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13617 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
13619 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
13621 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
13622 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
13624 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
13625 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
13627 // The result is fine to be handled by the generic logic.
13628 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
13629 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
13630 int AOffset, int BOffset) {
13631 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
13632 "Must call this with A having 3 or 1 inputs from the A half.");
13633 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
13634 "Must call this with B having 1 or 3 inputs from the B half.");
13635 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
13636 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
13638 bool ThreeAInputs = AToAInputs.size() == 3;
13640 // Compute the index of dword with only one word among the three inputs in
13641 // a half by taking the sum of the half with three inputs and subtracting
13642 // the sum of the actual three inputs. The difference is the remaining
13643 // slot.
13644 int ADWord = 0, BDWord = 0;
13645 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
13646 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
13647 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
13648 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
13649 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
13650 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
13651 int TripleNonInputIdx =
13652 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
13653 TripleDWord = TripleNonInputIdx / 2;
13655 // We use xor with one to compute the adjacent DWord to whichever one the
13656 // OneInput is in.
13657 OneInputDWord = (OneInput / 2) ^ 1;
13659 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
13660 // and BToA inputs. If there is also such a problem with the BToB and AToB
13661 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
13662 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
13663 // is essential that we don't *create* a 3<-1 as then we might oscillate.
13664 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
13665 // Compute how many inputs will be flipped by swapping these DWords. We
13666 // need
13667 // to balance this to ensure we don't form a 3-1 shuffle in the other
13668 // half.
13669 int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
13670 llvm::count(AToBInputs, 2 * ADWord + 1);
13671 int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
13672 llvm::count(BToBInputs, 2 * BDWord + 1);
13673 if ((NumFlippedAToBInputs == 1 &&
13674 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
13675 (NumFlippedBToBInputs == 1 &&
13676 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
13677 // We choose whether to fix the A half or B half based on whether that
13678 // half has zero flipped inputs. At zero, we may not be able to fix it
13679 // with that half. We also bias towards fixing the B half because that
13680 // will more commonly be the high half, and we have to bias one way.
13681 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
13682 ArrayRef<int> Inputs) {
13683 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
13684 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
13685 // Determine whether the free index is in the flipped dword or the
13686 // unflipped dword based on where the pinned index is. We use this bit
13687 // in an xor to conditionally select the adjacent dword.
13688 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
13689 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13690 if (IsFixIdxInput == IsFixFreeIdxInput)
13691 FixFreeIdx += 1;
13692 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13693 assert(IsFixIdxInput != IsFixFreeIdxInput &&
13694 "We need to be changing the number of flipped inputs!");
13695 int PSHUFHalfMask[] = {0, 1, 2, 3};
13696 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
13697 V = DAG.getNode(
13698 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
13699 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
13700 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13702 for (int &M : Mask)
13703 if (M >= 0 && M == FixIdx)
13704 M = FixFreeIdx;
13705 else if (M >= 0 && M == FixFreeIdx)
13706 M = FixIdx;
13708 if (NumFlippedBToBInputs != 0) {
13709 int BPinnedIdx =
13710 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
13711 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
13712 } else {
13713 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
13714 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
13715 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
13720 int PSHUFDMask[] = {0, 1, 2, 3};
13721 PSHUFDMask[ADWord] = BDWord;
13722 PSHUFDMask[BDWord] = ADWord;
13723 V = DAG.getBitcast(
13725 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13726 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13728 // Adjust the mask to match the new locations of A and B.
13729 for (int &M : Mask)
13730 if (M >= 0 && M/2 == ADWord)
13731 M = 2 * BDWord + M % 2;
13732 else if (M >= 0 && M/2 == BDWord)
13733 M = 2 * ADWord + M % 2;
13735 // Recurse back into this routine to re-compute state now that this isn't
13736 // a 3 and 1 problem.
13737 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
13739 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
13740 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
13741 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
13742 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
13744 // At this point there are at most two inputs to the low and high halves from
13745 // each half. That means the inputs can always be grouped into dwords and
13746 // those dwords can then be moved to the correct half with a dword shuffle.
13747 // We use at most one low and one high word shuffle to collect these paired
13748 // inputs into dwords, and finally a dword shuffle to place them.
13749 int PSHUFLMask[4] = {-1, -1, -1, -1};
13750 int PSHUFHMask[4] = {-1, -1, -1, -1};
13751 int PSHUFDMask[4] = {-1, -1, -1, -1};
13753 // First fix the masks for all the inputs that are staying in their
13754 // original halves. This will then dictate the targets of the cross-half
13755 // shuffles.
13756 auto fixInPlaceInputs =
13757 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
13758 MutableArrayRef<int> SourceHalfMask,
13759 MutableArrayRef<int> HalfMask, int HalfOffset) {
13760 if (InPlaceInputs.empty())
13761 return;
13762 if (InPlaceInputs.size() == 1) {
13763 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13764 InPlaceInputs[0] - HalfOffset;
13765 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
13766 return;
13768 if (IncomingInputs.empty()) {
13769 // Just fix all of the in place inputs.
13770 for (int Input : InPlaceInputs) {
13771 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
13772 PSHUFDMask[Input / 2] = Input / 2;
13774 return;
13777 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
13778 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13779 InPlaceInputs[0] - HalfOffset;
13780 // Put the second input next to the first so that they are packed into
13781 // a dword. We find the adjacent index by toggling the low bit.
13782 int AdjIndex = InPlaceInputs[0] ^ 1;
13783 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
13784 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
13785 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
13787 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
13788 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
13790 // Now gather the cross-half inputs and place them into a free dword of
13791 // their target half.
13792 // FIXME: This operation could almost certainly be simplified dramatically to
13793 // look more like the 3-1 fixing operation.
13794 auto moveInputsToRightHalf = [&PSHUFDMask](
13795 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
13796 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
13797 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
13798 int DestOffset) {
13799 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
13800 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
13802 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
13803 int Word) {
13804 int LowWord = Word & ~1;
13805 int HighWord = Word | 1;
13806 return isWordClobbered(SourceHalfMask, LowWord) ||
13807 isWordClobbered(SourceHalfMask, HighWord);
13810 if (IncomingInputs.empty())
13811 return;
13813 if (ExistingInputs.empty()) {
13814 // Map any dwords with inputs from them into the right half.
13815 for (int Input : IncomingInputs) {
13816 // If the source half mask maps over the inputs, turn those into
13817 // swaps and use the swapped lane.
13818 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
13819 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
13820 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
13821 Input - SourceOffset;
13822 // We have to swap the uses in our half mask in one sweep.
13823 for (int &M : HalfMask)
13824 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
13825 M = Input;
13826 else if (M == Input)
13827 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13828 } else {
13829 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
13830 Input - SourceOffset &&
13831 "Previous placement doesn't match!");
13833 // Note that this correctly re-maps both when we do a swap and when
13834 // we observe the other side of the swap above. We rely on that to
13835 // avoid swapping the members of the input list directly.
13836 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13839 // Map the input's dword into the correct half.
13840 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
13841 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
13842 else
13843 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
13844 Input / 2 &&
13845 "Previous placement doesn't match!");
13848 // And just directly shift any other-half mask elements to be same-half
13849 // as we will have mirrored the dword containing the element into the
13850 // same position within that half.
13851 for (int &M : HalfMask)
13852 if (M >= SourceOffset && M < SourceOffset + 4) {
13853 M = M - SourceOffset + DestOffset;
13854 assert(M >= 0 && "This should never wrap below zero!");
13856 return;
13859 // Ensure we have the input in a viable dword of its current half. This
13860 // is particularly tricky because the original position may be clobbered
13861 // by inputs being moved and *staying* in that half.
13862 if (IncomingInputs.size() == 1) {
13863 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13864 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
13865 SourceOffset;
13866 SourceHalfMask[InputFixed - SourceOffset] =
13867 IncomingInputs[0] - SourceOffset;
13868 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
13869 InputFixed);
13870 IncomingInputs[0] = InputFixed;
13872 } else if (IncomingInputs.size() == 2) {
13873 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
13874 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13875 // We have two non-adjacent or clobbered inputs we need to extract from
13876 // the source half. To do this, we need to map them into some adjacent
13877 // dword slot in the source mask.
13878 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
13879 IncomingInputs[1] - SourceOffset};
13881 // If there is a free slot in the source half mask adjacent to one of
13882 // the inputs, place the other input in it. We use (Index XOR 1) to
13883 // compute an adjacent index.
13884 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
13885 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
13886 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
13887 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13888 InputsFixed[1] = InputsFixed[0] ^ 1;
13889 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
13890 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
13891 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
13892 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
13893 InputsFixed[0] = InputsFixed[1] ^ 1;
13894 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
13895 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
13896 // The two inputs are in the same DWord but it is clobbered and the
13897 // adjacent DWord isn't used at all. Move both inputs to the free
13898 // slot.
13899 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
13900 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
13901 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
13902 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
13903 } else {
13904 // The only way we hit this point is if there is no clobbering
13905 // (because there are no off-half inputs to this half) and there is no
13906 // free slot adjacent to one of the inputs. In this case, we have to
13907 // swap an input with a non-input.
13908 for (int i = 0; i < 4; ++i)
13909 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
13910 "We can't handle any clobbers here!");
13911 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
13912 "Cannot have adjacent inputs here!");
13914 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13915 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
13917 // We also have to update the final source mask in this case because
13918 // it may need to undo the above swap.
13919 for (int &M : FinalSourceHalfMask)
13920 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
13921 M = InputsFixed[1] + SourceOffset;
13922 else if (M == InputsFixed[1] + SourceOffset)
13923 M = (InputsFixed[0] ^ 1) + SourceOffset;
13925 InputsFixed[1] = InputsFixed[0] ^ 1;
13928 // Point everything at the fixed inputs.
13929 for (int &M : HalfMask)
13930 if (M == IncomingInputs[0])
13931 M = InputsFixed[0] + SourceOffset;
13932 else if (M == IncomingInputs[1])
13933 M = InputsFixed[1] + SourceOffset;
13935 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
13936 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
13938 } else {
13939 llvm_unreachable("Unhandled input size!");
13942 // Now hoist the DWord down to the right half.
13943 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
13944 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
13945 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
13946 for (int &M : HalfMask)
13947 for (int Input : IncomingInputs)
13948 if (M == Input)
13949 M = FreeDWord * 2 + Input % 2;
13951 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
13952 /*SourceOffset*/ 4, /*DestOffset*/ 0);
13953 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
13954 /*SourceOffset*/ 0, /*DestOffset*/ 4);
13956 // Now enact all the shuffles we've computed to move the inputs into their
13957 // target half.
13958 if (!isNoopShuffleMask(PSHUFLMask))
13959 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13960 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
13961 if (!isNoopShuffleMask(PSHUFHMask))
13962 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13963 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
13964 if (!isNoopShuffleMask(PSHUFDMask))
13965 V = DAG.getBitcast(
13967 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13968 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13970 // At this point, each half should contain all its inputs, and we can then
13971 // just shuffle them into their final position.
13972 assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
13973 "Failed to lift all the high half inputs to the low mask!");
13974 assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
13975 "Failed to lift all the low half inputs to the high mask!");
13977 // Do a half shuffle for the low mask.
13978 if (!isNoopShuffleMask(LoMask))
13979 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13980 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13982 // Do a half shuffle with the high mask after shifting its values down.
13983 for (int &M : HiMask)
13984 if (M >= 0)
13985 M -= 4;
13986 if (!isNoopShuffleMask(HiMask))
13987 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13988 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13990 return V;
13993 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
13994 /// blend if only one input is used.
13995 static SDValue lowerShuffleAsBlendOfPSHUFBs(
13996 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13997 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
13998 assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
13999 "Lane crossing shuffle masks not supported");
14001 int NumBytes = VT.getSizeInBits() / 8;
14002 int Size = Mask.size();
14003 int Scale = NumBytes / Size;
14005 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14006 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14007 V1InUse = false;
14008 V2InUse = false;
14010 for (int i = 0; i < NumBytes; ++i) {
14011 int M = Mask[i / Scale];
14012 if (M < 0)
14013 continue;
14015 const int ZeroMask = 0x80;
14016 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14017 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14018 if (Zeroable[i / Scale])
14019 V1Idx = V2Idx = ZeroMask;
14021 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14022 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14023 V1InUse |= (ZeroMask != V1Idx);
14024 V2InUse |= (ZeroMask != V2Idx);
14027 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14028 if (V1InUse)
14029 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14030 DAG.getBuildVector(ShufVT, DL, V1Mask));
14031 if (V2InUse)
14032 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14033 DAG.getBuildVector(ShufVT, DL, V2Mask));
14035 // If we need shuffled inputs from both, blend the two.
14036 SDValue V;
14037 if (V1InUse && V2InUse)
14038 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14039 else
14040 V = V1InUse ? V1 : V2;
14042 // Cast the result back to the correct type.
14043 return DAG.getBitcast(VT, V);
14046 /// Generic lowering of 8-lane i16 shuffles.
14048 /// This handles both single-input shuffles and combined shuffle/blends with
14049 /// two inputs. The single input shuffles are immediately delegated to
14050 /// a dedicated lowering routine.
14052 /// The blends are lowered in one of three fundamental ways. If there are few
14053 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14054 /// of the input is significantly cheaper when lowered as an interleaving of
14055 /// the two inputs, try to interleave them. Otherwise, blend the low and high
14056 /// halves of the inputs separately (making them have relatively few inputs)
14057 /// and then concatenate them.
14058 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14059 const APInt &Zeroable, SDValue V1, SDValue V2,
14060 const X86Subtarget &Subtarget,
14061 SelectionDAG &DAG) {
14062 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14063 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14064 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14066 // Whenever we can lower this as a zext, that instruction is strictly faster
14067 // than any alternative.
14068 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14069 Zeroable, Subtarget, DAG))
14070 return ZExt;
14072 // Try to use lower using a truncation.
14073 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14074 Subtarget, DAG))
14075 return V;
14077 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14079 if (NumV2Inputs == 0) {
14080 // Try to use shift instructions.
14081 if (SDValue Shift =
14082 lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
14083 Subtarget, DAG, /*BitwiseOnly*/ false))
14084 return Shift;
14086 // Check for being able to broadcast a single element.
14087 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14088 Mask, Subtarget, DAG))
14089 return Broadcast;
14091 // Try to use bit rotation instructions.
14092 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
14093 Subtarget, DAG))
14094 return Rotate;
14096 // Use dedicated unpack instructions for masks that match their pattern.
14097 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14098 return V;
14100 // Use dedicated pack instructions for masks that match their pattern.
14101 if (SDValue V =
14102 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14103 return V;
14105 // Try to use byte rotation instructions.
14106 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14107 Subtarget, DAG))
14108 return Rotate;
14110 // Make a copy of the mask so it can be modified.
14111 SmallVector<int, 8> MutableMask(Mask);
14112 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14113 Subtarget, DAG);
14116 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14117 "All single-input shuffles should be canonicalized to be V1-input "
14118 "shuffles.");
14120 // Try to use shift instructions.
14121 if (SDValue Shift =
14122 lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
14123 DAG, /*BitwiseOnly*/ false))
14124 return Shift;
14126 // See if we can use SSE4A Extraction / Insertion.
14127 if (Subtarget.hasSSE4A())
14128 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14129 Zeroable, DAG))
14130 return V;
14132 // There are special ways we can lower some single-element blends.
14133 if (NumV2Inputs == 1)
14134 if (SDValue V = lowerShuffleAsElementInsertion(
14135 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14136 return V;
14138 // We have different paths for blend lowering, but they all must use the
14139 // *exact* same predicate.
14140 bool IsBlendSupported = Subtarget.hasSSE41();
14141 if (IsBlendSupported)
14142 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14143 Zeroable, Subtarget, DAG))
14144 return Blend;
14146 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
14147 Zeroable, Subtarget, DAG))
14148 return Masked;
14150 // Use dedicated unpack instructions for masks that match their pattern.
14151 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14152 return V;
14154 // Use dedicated pack instructions for masks that match their pattern.
14155 if (SDValue V =
14156 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14157 return V;
14159 // Try to use lower using a truncation.
14160 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14161 Subtarget, DAG))
14162 return V;
14164 // Try to use byte rotation instructions.
14165 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14166 Subtarget, DAG))
14167 return Rotate;
14169 if (SDValue BitBlend =
14170 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14171 return BitBlend;
14173 // Try to use byte shift instructions to mask.
14174 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14175 Zeroable, Subtarget, DAG))
14176 return V;
14178 // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
14179 int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
14180 if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
14181 !Subtarget.hasVLX()) {
14182 // Check if this is part of a 256-bit vector truncation.
14183 unsigned PackOpc = 0;
14184 if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
14185 peekThroughBitcasts(V1).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
14186 peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
14187 SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
14188 V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
14189 getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
14190 DAG.getTargetConstant(0xEE, DL, MVT::i8));
14191 V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
14192 V1 = extract128BitVector(V1V2, 0, DAG, DL);
14193 V2 = extract128BitVector(V1V2, 4, DAG, DL);
14194 PackOpc = X86ISD::PACKUS;
14195 } else if (Subtarget.hasSSE41()) {
14196 SmallVector<SDValue, 4> DWordClearOps(4,
14197 DAG.getConstant(0, DL, MVT::i32));
14198 for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
14199 DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
14200 SDValue DWordClearMask =
14201 DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
14202 V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
14203 DWordClearMask);
14204 V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
14205 DWordClearMask);
14206 PackOpc = X86ISD::PACKUS;
14207 } else if (!Subtarget.hasSSSE3()) {
14208 SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
14209 V1 = DAG.getBitcast(MVT::v4i32, V1);
14210 V2 = DAG.getBitcast(MVT::v4i32, V2);
14211 V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
14212 V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
14213 V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
14214 V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
14215 PackOpc = X86ISD::PACKSS;
14217 if (PackOpc) {
14218 // Now pack things back together.
14219 SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
14220 if (NumEvenDrops == 2) {
14221 Result = DAG.getBitcast(MVT::v4i32, Result);
14222 Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
14224 return Result;
14228 // When compacting odd (upper) elements, use PACKSS pre-SSE41.
14229 int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
14230 if (NumOddDrops == 1) {
14231 bool HasSSE41 = Subtarget.hasSSE41();
14232 V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14233 DAG.getBitcast(MVT::v4i32, V1),
14234 DAG.getTargetConstant(16, DL, MVT::i8));
14235 V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14236 DAG.getBitcast(MVT::v4i32, V2),
14237 DAG.getTargetConstant(16, DL, MVT::i8));
14238 return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
14239 MVT::v8i16, V1, V2);
14242 // Try to lower by permuting the inputs into an unpack instruction.
14243 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14244 Mask, Subtarget, DAG))
14245 return Unpack;
14247 // If we can't directly blend but can use PSHUFB, that will be better as it
14248 // can both shuffle and set up the inefficient blend.
14249 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14250 bool V1InUse, V2InUse;
14251 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14252 Zeroable, DAG, V1InUse, V2InUse);
14255 // We can always bit-blend if we have to so the fallback strategy is to
14256 // decompose into single-input permutes and blends/unpacks.
14257 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2, Mask,
14258 Zeroable, Subtarget, DAG);
14261 /// Lower 8-lane 16-bit floating point shuffles.
14262 static SDValue lowerV8F16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14263 const APInt &Zeroable, SDValue V1, SDValue V2,
14264 const X86Subtarget &Subtarget,
14265 SelectionDAG &DAG) {
14266 assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14267 assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14268 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14269 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
14271 if (Subtarget.hasFP16()) {
14272 if (NumV2Elements == 0) {
14273 // Check for being able to broadcast a single element.
14274 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
14275 Mask, Subtarget, DAG))
14276 return Broadcast;
14278 if (NumV2Elements == 1 && Mask[0] >= 8)
14279 if (SDValue V = lowerShuffleAsElementInsertion(
14280 DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14281 return V;
14284 V1 = DAG.getBitcast(MVT::v8i16, V1);
14285 V2 = DAG.getBitcast(MVT::v8i16, V2);
14286 return DAG.getBitcast(MVT::v8f16,
14287 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
14290 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
14291 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
14292 // the active subvector is extracted.
14293 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
14294 ArrayRef<int> Mask, SDValue V1, SDValue V2,
14295 const X86Subtarget &Subtarget,
14296 SelectionDAG &DAG) {
14297 MVT MaskVT = VT.changeTypeToInteger();
14298 SDValue MaskNode;
14299 MVT ShuffleVT = VT;
14300 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
14301 V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
14302 V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
14303 ShuffleVT = V1.getSimpleValueType();
14305 // Adjust mask to correct indices for the second input.
14306 int NumElts = VT.getVectorNumElements();
14307 unsigned Scale = 512 / VT.getSizeInBits();
14308 SmallVector<int, 32> AdjustedMask(Mask);
14309 for (int &M : AdjustedMask)
14310 if (NumElts <= M)
14311 M += (Scale - 1) * NumElts;
14312 MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
14313 MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
14314 } else {
14315 MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
14318 SDValue Result;
14319 if (V2.isUndef())
14320 Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
14321 else
14322 Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
14324 if (VT != ShuffleVT)
14325 Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
14327 return Result;
14330 /// Generic lowering of v16i8 shuffles.
14332 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
14333 /// detect any complexity reducing interleaving. If that doesn't help, it uses
14334 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
14335 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
14336 /// back together.
14337 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14338 const APInt &Zeroable, SDValue V1, SDValue V2,
14339 const X86Subtarget &Subtarget,
14340 SelectionDAG &DAG) {
14341 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14342 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14343 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
14345 // Try to use shift instructions.
14346 if (SDValue Shift =
14347 lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
14348 DAG, /*BitwiseOnly*/ false))
14349 return Shift;
14351 // Try to use byte rotation instructions.
14352 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
14353 Subtarget, DAG))
14354 return Rotate;
14356 // Use dedicated pack instructions for masks that match their pattern.
14357 if (SDValue V =
14358 lowerShuffleWithPACK(DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14359 return V;
14361 // Try to use a zext lowering.
14362 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
14363 Zeroable, Subtarget, DAG))
14364 return ZExt;
14366 // Try to use lower using a truncation.
14367 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
14368 Subtarget, DAG))
14369 return V;
14371 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
14372 Subtarget, DAG))
14373 return V;
14375 // See if we can use SSE4A Extraction / Insertion.
14376 if (Subtarget.hasSSE4A())
14377 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
14378 Zeroable, DAG))
14379 return V;
14381 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
14383 // For single-input shuffles, there are some nicer lowering tricks we can use.
14384 if (NumV2Elements == 0) {
14385 // Check for being able to broadcast a single element.
14386 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
14387 Mask, Subtarget, DAG))
14388 return Broadcast;
14390 // Try to use bit rotation instructions.
14391 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
14392 Subtarget, DAG))
14393 return Rotate;
14395 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
14396 return V;
14398 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
14399 // Notably, this handles splat and partial-splat shuffles more efficiently.
14400 // However, it only makes sense if the pre-duplication shuffle simplifies
14401 // things significantly. Currently, this means we need to be able to
14402 // express the pre-duplication shuffle as an i16 shuffle.
14404 // FIXME: We should check for other patterns which can be widened into an
14405 // i16 shuffle as well.
14406 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
14407 for (int i = 0; i < 16; i += 2)
14408 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
14409 return false;
14411 return true;
14413 auto tryToWidenViaDuplication = [&]() -> SDValue {
14414 if (!canWidenViaDuplication(Mask))
14415 return SDValue();
14416 SmallVector<int, 4> LoInputs;
14417 copy_if(Mask, std::back_inserter(LoInputs),
14418 [](int M) { return M >= 0 && M < 8; });
14419 array_pod_sort(LoInputs.begin(), LoInputs.end());
14420 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
14421 SmallVector<int, 4> HiInputs;
14422 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
14423 array_pod_sort(HiInputs.begin(), HiInputs.end());
14424 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
14426 bool TargetLo = LoInputs.size() >= HiInputs.size();
14427 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
14428 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
14430 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
14431 SmallDenseMap<int, int, 8> LaneMap;
14432 for (int I : InPlaceInputs) {
14433 PreDupI16Shuffle[I/2] = I/2;
14434 LaneMap[I] = I;
14436 int j = TargetLo ? 0 : 4, je = j + 4;
14437 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
14438 // Check if j is already a shuffle of this input. This happens when
14439 // there are two adjacent bytes after we move the low one.
14440 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
14441 // If we haven't yet mapped the input, search for a slot into which
14442 // we can map it.
14443 while (j < je && PreDupI16Shuffle[j] >= 0)
14444 ++j;
14446 if (j == je)
14447 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
14448 return SDValue();
14450 // Map this input with the i16 shuffle.
14451 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
14454 // Update the lane map based on the mapping we ended up with.
14455 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
14457 V1 = DAG.getBitcast(
14458 MVT::v16i8,
14459 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14460 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
14462 // Unpack the bytes to form the i16s that will be shuffled into place.
14463 bool EvenInUse = false, OddInUse = false;
14464 for (int i = 0; i < 16; i += 2) {
14465 EvenInUse |= (Mask[i + 0] >= 0);
14466 OddInUse |= (Mask[i + 1] >= 0);
14467 if (EvenInUse && OddInUse)
14468 break;
14470 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14471 MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
14472 OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
14474 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
14475 for (int i = 0; i < 16; ++i)
14476 if (Mask[i] >= 0) {
14477 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
14478 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
14479 if (PostDupI16Shuffle[i / 2] < 0)
14480 PostDupI16Shuffle[i / 2] = MappedMask;
14481 else
14482 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
14483 "Conflicting entries in the original shuffle!");
14485 return DAG.getBitcast(
14486 MVT::v16i8,
14487 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14488 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
14490 if (SDValue V = tryToWidenViaDuplication())
14491 return V;
14494 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
14495 Zeroable, Subtarget, DAG))
14496 return Masked;
14498 // Use dedicated unpack instructions for masks that match their pattern.
14499 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
14500 return V;
14502 // Try to use byte shift instructions to mask.
14503 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
14504 Zeroable, Subtarget, DAG))
14505 return V;
14507 // Check for compaction patterns.
14508 bool IsSingleInput = V2.isUndef();
14509 int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
14511 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
14512 // with PSHUFB. It is important to do this before we attempt to generate any
14513 // blends but after all of the single-input lowerings. If the single input
14514 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
14515 // want to preserve that and we can DAG combine any longer sequences into
14516 // a PSHUFB in the end. But once we start blending from multiple inputs,
14517 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
14518 // and there are *very* few patterns that would actually be faster than the
14519 // PSHUFB approach because of its ability to zero lanes.
14521 // If the mask is a binary compaction, we can more efficiently perform this
14522 // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
14524 // FIXME: The only exceptions to the above are blends which are exact
14525 // interleavings with direct instructions supporting them. We currently don't
14526 // handle those well here.
14527 if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
14528 bool V1InUse = false;
14529 bool V2InUse = false;
14531 SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
14532 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
14534 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
14535 // do so. This avoids using them to handle blends-with-zero which is
14536 // important as a single pshufb is significantly faster for that.
14537 if (V1InUse && V2InUse) {
14538 if (Subtarget.hasSSE41())
14539 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
14540 Zeroable, Subtarget, DAG))
14541 return Blend;
14543 // We can use an unpack to do the blending rather than an or in some
14544 // cases. Even though the or may be (very minorly) more efficient, we
14545 // preference this lowering because there are common cases where part of
14546 // the complexity of the shuffles goes away when we do the final blend as
14547 // an unpack.
14548 // FIXME: It might be worth trying to detect if the unpack-feeding
14549 // shuffles will both be pshufb, in which case we shouldn't bother with
14550 // this.
14551 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
14552 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14553 return Unpack;
14555 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
14556 if (Subtarget.hasVBMI())
14557 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
14558 DAG);
14560 // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
14561 if (Subtarget.hasXOP()) {
14562 SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
14563 return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
14566 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
14567 // PALIGNR will be cheaper than the second PSHUFB+OR.
14568 if (SDValue V = lowerShuffleAsByteRotateAndPermute(
14569 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14570 return V;
14573 return PSHUFB;
14576 // There are special ways we can lower some single-element blends.
14577 if (NumV2Elements == 1)
14578 if (SDValue V = lowerShuffleAsElementInsertion(
14579 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
14580 return V;
14582 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
14583 return Blend;
14585 // Check whether a compaction lowering can be done. This handles shuffles
14586 // which take every Nth element for some even N. See the helper function for
14587 // details.
14589 // We special case these as they can be particularly efficiently handled with
14590 // the PACKUSB instruction on x86 and they show up in common patterns of
14591 // rearranging bytes to truncate wide elements.
14592 if (NumEvenDrops) {
14593 // NumEvenDrops is the power of two stride of the elements. Another way of
14594 // thinking about it is that we need to drop the even elements this many
14595 // times to get the original input.
14597 // First we need to zero all the dropped bytes.
14598 assert(NumEvenDrops <= 3 &&
14599 "No support for dropping even elements more than 3 times.");
14600 SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
14601 for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
14602 WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
14603 SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
14604 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
14605 WordClearMask);
14606 if (!IsSingleInput)
14607 V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
14608 WordClearMask);
14610 // Now pack things back together.
14611 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
14612 IsSingleInput ? V1 : V2);
14613 for (int i = 1; i < NumEvenDrops; ++i) {
14614 Result = DAG.getBitcast(MVT::v8i16, Result);
14615 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
14617 return Result;
14620 int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
14621 if (NumOddDrops == 1) {
14622 V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
14623 DAG.getBitcast(MVT::v8i16, V1),
14624 DAG.getTargetConstant(8, DL, MVT::i8));
14625 if (!IsSingleInput)
14626 V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
14627 DAG.getBitcast(MVT::v8i16, V2),
14628 DAG.getTargetConstant(8, DL, MVT::i8));
14629 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
14630 IsSingleInput ? V1 : V2);
14633 // Handle multi-input cases by blending/unpacking single-input shuffles.
14634 if (NumV2Elements > 0)
14635 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
14636 Zeroable, Subtarget, DAG);
14638 // The fallback path for single-input shuffles widens this into two v8i16
14639 // vectors with unpacks, shuffles those, and then pulls them back together
14640 // with a pack.
14641 SDValue V = V1;
14643 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14644 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14645 for (int i = 0; i < 16; ++i)
14646 if (Mask[i] >= 0)
14647 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
14649 SDValue VLoHalf, VHiHalf;
14650 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
14651 // them out and avoid using UNPCK{L,H} to extract the elements of V as
14652 // i16s.
14653 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
14654 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
14655 // Use a mask to drop the high bytes.
14656 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
14657 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
14658 DAG.getConstant(0x00FF, DL, MVT::v8i16));
14660 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
14661 VHiHalf = DAG.getUNDEF(MVT::v8i16);
14663 // Squash the masks to point directly into VLoHalf.
14664 for (int &M : LoBlendMask)
14665 if (M >= 0)
14666 M /= 2;
14667 for (int &M : HiBlendMask)
14668 if (M >= 0)
14669 M /= 2;
14670 } else {
14671 // Otherwise just unpack the low half of V into VLoHalf and the high half into
14672 // VHiHalf so that we can blend them as i16s.
14673 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
14675 VLoHalf = DAG.getBitcast(
14676 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
14677 VHiHalf = DAG.getBitcast(
14678 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
14681 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
14682 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
14684 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
14687 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
14689 /// This routine breaks down the specific type of 128-bit shuffle and
14690 /// dispatches to the lowering routines accordingly.
14691 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14692 MVT VT, SDValue V1, SDValue V2,
14693 const APInt &Zeroable,
14694 const X86Subtarget &Subtarget,
14695 SelectionDAG &DAG) {
14696 if (VT == MVT::v8bf16) {
14697 V1 = DAG.getBitcast(MVT::v8i16, V1);
14698 V2 = DAG.getBitcast(MVT::v8i16, V2);
14699 return DAG.getBitcast(VT,
14700 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
14703 switch (VT.SimpleTy) {
14704 case MVT::v2i64:
14705 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14706 case MVT::v2f64:
14707 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14708 case MVT::v4i32:
14709 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14710 case MVT::v4f32:
14711 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14712 case MVT::v8i16:
14713 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14714 case MVT::v8f16:
14715 return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14716 case MVT::v16i8:
14717 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14719 default:
14720 llvm_unreachable("Unimplemented!");
14724 /// Generic routine to split vector shuffle into half-sized shuffles.
14726 /// This routine just extracts two subvectors, shuffles them independently, and
14727 /// then concatenates them back together. This should work effectively with all
14728 /// AVX vector shuffle types.
14729 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
14730 SDValue V2, ArrayRef<int> Mask,
14731 SelectionDAG &DAG, bool SimpleOnly) {
14732 assert(VT.getSizeInBits() >= 256 &&
14733 "Only for 256-bit or wider vector shuffles!");
14734 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
14735 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
14737 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
14738 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
14740 int NumElements = VT.getVectorNumElements();
14741 int SplitNumElements = NumElements / 2;
14742 MVT ScalarVT = VT.getVectorElementType();
14743 MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
14745 // Use splitVector/extractSubVector so that split build-vectors just build two
14746 // narrower build vectors. This helps shuffling with splats and zeros.
14747 auto SplitVector = [&](SDValue V) {
14748 SDValue LoV, HiV;
14749 std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
14750 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
14751 DAG.getBitcast(SplitVT, HiV));
14754 SDValue LoV1, HiV1, LoV2, HiV2;
14755 std::tie(LoV1, HiV1) = SplitVector(V1);
14756 std::tie(LoV2, HiV2) = SplitVector(V2);
14758 // Now create two 4-way blends of these half-width vectors.
14759 auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
14760 bool &UseHiV1, bool &UseLoV2,
14761 bool &UseHiV2) {
14762 UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
14763 for (int i = 0; i < SplitNumElements; ++i) {
14764 int M = HalfMask[i];
14765 if (M >= NumElements) {
14766 if (M >= NumElements + SplitNumElements)
14767 UseHiV2 = true;
14768 else
14769 UseLoV2 = true;
14770 } else if (M >= 0) {
14771 if (M >= SplitNumElements)
14772 UseHiV1 = true;
14773 else
14774 UseLoV1 = true;
14779 auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
14780 if (!SimpleOnly)
14781 return true;
14783 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
14784 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
14786 return !(UseHiV1 || UseHiV2);
14789 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
14790 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
14791 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
14792 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
14793 for (int i = 0; i < SplitNumElements; ++i) {
14794 int M = HalfMask[i];
14795 if (M >= NumElements) {
14796 V2BlendMask[i] = M - NumElements;
14797 BlendMask[i] = SplitNumElements + i;
14798 } else if (M >= 0) {
14799 V1BlendMask[i] = M;
14800 BlendMask[i] = i;
14804 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
14805 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
14807 // Because the lowering happens after all combining takes place, we need to
14808 // manually combine these blend masks as much as possible so that we create
14809 // a minimal number of high-level vector shuffle nodes.
14810 assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
14812 // First try just blending the halves of V1 or V2.
14813 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
14814 return DAG.getUNDEF(SplitVT);
14815 if (!UseLoV2 && !UseHiV2)
14816 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14817 if (!UseLoV1 && !UseHiV1)
14818 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14820 SDValue V1Blend, V2Blend;
14821 if (UseLoV1 && UseHiV1) {
14822 V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14823 } else {
14824 // We only use half of V1 so map the usage down into the final blend mask.
14825 V1Blend = UseLoV1 ? LoV1 : HiV1;
14826 for (int i = 0; i < SplitNumElements; ++i)
14827 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
14828 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
14830 if (UseLoV2 && UseHiV2) {
14831 V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14832 } else {
14833 // We only use half of V2 so map the usage down into the final blend mask.
14834 V2Blend = UseLoV2 ? LoV2 : HiV2;
14835 for (int i = 0; i < SplitNumElements; ++i)
14836 if (BlendMask[i] >= SplitNumElements)
14837 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
14839 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
14842 if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
14843 return SDValue();
14845 SDValue Lo = HalfBlend(LoMask);
14846 SDValue Hi = HalfBlend(HiMask);
14847 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
14850 /// Either split a vector in halves or decompose the shuffles and the
14851 /// blend/unpack.
14853 /// This is provided as a good fallback for many lowerings of non-single-input
14854 /// shuffles with more than one 128-bit lane. In those cases, we want to select
14855 /// between splitting the shuffle into 128-bit components and stitching those
14856 /// back together vs. extracting the single-input shuffles and blending those
14857 /// results.
14858 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
14859 SDValue V2, ArrayRef<int> Mask,
14860 const APInt &Zeroable,
14861 const X86Subtarget &Subtarget,
14862 SelectionDAG &DAG) {
14863 assert(!V2.isUndef() && "This routine must not be used to lower single-input "
14864 "shuffles as it could then recurse on itself.");
14865 int Size = Mask.size();
14867 // If this can be modeled as a broadcast of two elements followed by a blend,
14868 // prefer that lowering. This is especially important because broadcasts can
14869 // often fold with memory operands.
14870 auto DoBothBroadcast = [&] {
14871 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
14872 for (int M : Mask)
14873 if (M >= Size) {
14874 if (V2BroadcastIdx < 0)
14875 V2BroadcastIdx = M - Size;
14876 else if (M - Size != V2BroadcastIdx)
14877 return false;
14878 } else if (M >= 0) {
14879 if (V1BroadcastIdx < 0)
14880 V1BroadcastIdx = M;
14881 else if (M != V1BroadcastIdx)
14882 return false;
14884 return true;
14886 if (DoBothBroadcast())
14887 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
14888 Subtarget, DAG);
14890 // If the inputs all stem from a single 128-bit lane of each input, then we
14891 // split them rather than blending because the split will decompose to
14892 // unusually few instructions.
14893 int LaneCount = VT.getSizeInBits() / 128;
14894 int LaneSize = Size / LaneCount;
14895 SmallBitVector LaneInputs[2];
14896 LaneInputs[0].resize(LaneCount, false);
14897 LaneInputs[1].resize(LaneCount, false);
14898 for (int i = 0; i < Size; ++i)
14899 if (Mask[i] >= 0)
14900 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
14901 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
14902 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
14903 /*SimpleOnly*/ false);
14905 // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
14906 // requires that the decomposed single-input shuffles don't end up here.
14907 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
14908 Subtarget, DAG);
14911 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
14912 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
14913 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
14914 SDValue V1, SDValue V2,
14915 ArrayRef<int> Mask,
14916 SelectionDAG &DAG) {
14917 assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
14919 int LHSMask[4] = {-1, -1, -1, -1};
14920 int RHSMask[4] = {-1, -1, -1, -1};
14921 int SHUFPDMask[4] = {-1, -1, -1, -1};
14923 // As SHUFPD uses a single LHS/RHS element per lane, we can always
14924 // perform the shuffle once the lanes have been shuffled in place.
14925 for (int i = 0; i != 4; ++i) {
14926 int M = Mask[i];
14927 if (M < 0)
14928 continue;
14929 int LaneBase = i & ~1;
14930 auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
14931 LaneMask[LaneBase + (M & 1)] = M;
14932 SHUFPDMask[i] = M & 1;
14935 SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
14936 SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
14937 return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
14938 getSHUFPDImmForMask(SHUFPDMask, DL, DAG));
14941 /// Lower a vector shuffle crossing multiple 128-bit lanes as
14942 /// a lane permutation followed by a per-lane permutation.
14944 /// This is mainly for cases where we can have non-repeating permutes
14945 /// in each lane.
14947 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
14948 /// we should investigate merging them.
14949 static SDValue lowerShuffleAsLanePermuteAndPermute(
14950 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14951 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14952 int NumElts = VT.getVectorNumElements();
14953 int NumLanes = VT.getSizeInBits() / 128;
14954 int NumEltsPerLane = NumElts / NumLanes;
14955 bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
14957 /// Attempts to find a sublane permute with the given size
14958 /// that gets all elements into their target lanes.
14960 /// If successful, fills CrossLaneMask and InLaneMask and returns true.
14961 /// If unsuccessful, returns false and may overwrite InLaneMask.
14962 auto getSublanePermute = [&](int NumSublanes) -> SDValue {
14963 int NumSublanesPerLane = NumSublanes / NumLanes;
14964 int NumEltsPerSublane = NumElts / NumSublanes;
14966 SmallVector<int, 16> CrossLaneMask;
14967 SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
14968 // CrossLaneMask but one entry == one sublane.
14969 SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
14970 APInt DemandedCrossLane = APInt::getZero(NumElts);
14972 for (int i = 0; i != NumElts; ++i) {
14973 int M = Mask[i];
14974 if (M < 0)
14975 continue;
14977 int SrcSublane = M / NumEltsPerSublane;
14978 int DstLane = i / NumEltsPerLane;
14980 // We only need to get the elements into the right lane, not sublane.
14981 // So search all sublanes that make up the destination lane.
14982 bool Found = false;
14983 int DstSubStart = DstLane * NumSublanesPerLane;
14984 int DstSubEnd = DstSubStart + NumSublanesPerLane;
14985 for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
14986 if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
14987 continue;
14989 Found = true;
14990 CrossLaneMaskLarge[DstSublane] = SrcSublane;
14991 int DstSublaneOffset = DstSublane * NumEltsPerSublane;
14992 InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
14993 DemandedCrossLane.setBit(InLaneMask[i]);
14994 break;
14996 if (!Found)
14997 return SDValue();
15000 // Fill CrossLaneMask using CrossLaneMaskLarge.
15001 narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15003 if (!CanUseSublanes) {
15004 // If we're only shuffling a single lowest lane and the rest are identity
15005 // then don't bother.
15006 // TODO - isShuffleMaskInputInPlace could be extended to something like
15007 // this.
15008 int NumIdentityLanes = 0;
15009 bool OnlyShuffleLowestLane = true;
15010 for (int i = 0; i != NumLanes; ++i) {
15011 int LaneOffset = i * NumEltsPerLane;
15012 if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15013 i * NumEltsPerLane))
15014 NumIdentityLanes++;
15015 else if (CrossLaneMask[LaneOffset] != 0)
15016 OnlyShuffleLowestLane = false;
15018 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15019 return SDValue();
15022 // Avoid returning the same shuffle operation. For example,
15023 // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
15024 // undef:v16i16
15025 if (CrossLaneMask == Mask || InLaneMask == Mask)
15026 return SDValue();
15028 // Simplify CrossLaneMask based on the actual demanded elements.
15029 if (V1.hasOneUse())
15030 for (int i = 0; i != NumElts; ++i)
15031 if (!DemandedCrossLane[i])
15032 CrossLaneMask[i] = SM_SentinelUndef;
15034 SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15035 return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15036 InLaneMask);
15039 // First attempt a solution with full lanes.
15040 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
15041 return V;
15043 // The rest of the solutions use sublanes.
15044 if (!CanUseSublanes)
15045 return SDValue();
15047 // Then attempt a solution with 64-bit sublanes (vpermq).
15048 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
15049 return V;
15051 // If that doesn't work and we have fast variable cross-lane shuffle,
15052 // attempt 32-bit sublanes (vpermd).
15053 if (!Subtarget.hasFastVariableCrossLaneShuffle())
15054 return SDValue();
15056 return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
15059 /// Helper to get compute inlane shuffle mask for a complete shuffle mask.
15060 static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
15061 SmallVector<int> &InLaneMask) {
15062 int Size = Mask.size();
15063 InLaneMask.assign(Mask.begin(), Mask.end());
15064 for (int i = 0; i < Size; ++i) {
15065 int &M = InLaneMask[i];
15066 if (M < 0)
15067 continue;
15068 if (((M % Size) / LaneSize) != (i / LaneSize))
15069 M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15073 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15074 /// source with a lane permutation.
15076 /// This lowering strategy results in four instructions in the worst case for a
15077 /// single-input cross lane shuffle which is lower than any other fully general
15078 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15079 /// shuffle pattern should be handled prior to trying this lowering.
15080 static SDValue lowerShuffleAsLanePermuteAndShuffle(
15081 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15082 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15083 // FIXME: This should probably be generalized for 512-bit vectors as well.
15084 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15085 int Size = Mask.size();
15086 int LaneSize = Size / 2;
15088 // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15089 // Only do this if the elements aren't all from the lower lane,
15090 // otherwise we're (probably) better off doing a split.
15091 if (VT == MVT::v4f64 &&
15092 !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15093 return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
15095 // If there are only inputs from one 128-bit lane, splitting will in fact be
15096 // less expensive. The flags track whether the given lane contains an element
15097 // that crosses to another lane.
15098 bool AllLanes;
15099 if (!Subtarget.hasAVX2()) {
15100 bool LaneCrossing[2] = {false, false};
15101 for (int i = 0; i < Size; ++i)
15102 if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15103 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15104 AllLanes = LaneCrossing[0] && LaneCrossing[1];
15105 } else {
15106 bool LaneUsed[2] = {false, false};
15107 for (int i = 0; i < Size; ++i)
15108 if (Mask[i] >= 0)
15109 LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15110 AllLanes = LaneUsed[0] && LaneUsed[1];
15113 // TODO - we could support shuffling V2 in the Flipped input.
15114 assert(V2.isUndef() &&
15115 "This last part of this routine only works on single input shuffles");
15117 SmallVector<int> InLaneMask;
15118 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
15120 assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15121 "In-lane shuffle mask expected");
15123 // If we're not using both lanes in each lane and the inlane mask is not
15124 // repeating, then we're better off splitting.
15125 if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
15126 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15127 /*SimpleOnly*/ false);
15129 // Flip the lanes, and shuffle the results which should now be in-lane.
15130 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15131 SDValue Flipped = DAG.getBitcast(PVT, V1);
15132 Flipped =
15133 DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15134 Flipped = DAG.getBitcast(VT, Flipped);
15135 return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15138 /// Handle lowering 2-lane 128-bit shuffles.
15139 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
15140 SDValue V2, ArrayRef<int> Mask,
15141 const APInt &Zeroable,
15142 const X86Subtarget &Subtarget,
15143 SelectionDAG &DAG) {
15144 if (V2.isUndef()) {
15145 // Attempt to match VBROADCAST*128 subvector broadcast load.
15146 bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
15147 bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
15148 if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
15149 X86::mayFoldLoad(peekThroughOneUseBitcasts(V1), Subtarget)) {
15150 MVT MemVT = VT.getHalfNumVectorElementsVT();
15151 unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
15152 auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
15153 if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
15154 VT, MemVT, Ld, Ofs, DAG))
15155 return BcstLd;
15158 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15159 if (Subtarget.hasAVX2())
15160 return SDValue();
15163 bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15165 SmallVector<int, 4> WidenedMask;
15166 if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15167 return SDValue();
15169 bool IsLowZero = (Zeroable & 0x3) == 0x3;
15170 bool IsHighZero = (Zeroable & 0xc) == 0xc;
15172 // Try to use an insert into a zero vector.
15173 if (WidenedMask[0] == 0 && IsHighZero) {
15174 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15175 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15176 DAG.getIntPtrConstant(0, DL));
15177 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15178 getZeroVector(VT, Subtarget, DAG, DL), LoV,
15179 DAG.getIntPtrConstant(0, DL));
15182 // TODO: If minimizing size and one of the inputs is a zero vector and the
15183 // the zero vector has only one use, we could use a VPERM2X128 to save the
15184 // instruction bytes needed to explicitly generate the zero vector.
15186 // Blends are faster and handle all the non-lane-crossing cases.
15187 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15188 Subtarget, DAG))
15189 return Blend;
15191 // If either input operand is a zero vector, use VPERM2X128 because its mask
15192 // allows us to replace the zero input with an implicit zero.
15193 if (!IsLowZero && !IsHighZero) {
15194 // Check for patterns which can be matched with a single insert of a 128-bit
15195 // subvector.
15196 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
15197 if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
15199 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15200 // this will likely become vinsertf128 which can't fold a 256-bit memop.
15201 if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
15202 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15203 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
15204 OnlyUsesV1 ? V1 : V2,
15205 DAG.getIntPtrConstant(0, DL));
15206 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15207 DAG.getIntPtrConstant(2, DL));
15211 // Try to use SHUF128 if possible.
15212 if (Subtarget.hasVLX()) {
15213 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15214 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15215 ((WidenedMask[1] % 2) << 1);
15216 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
15217 DAG.getTargetConstant(PermMask, DL, MVT::i8));
15222 // Otherwise form a 128-bit permutation. After accounting for undefs,
15223 // convert the 64-bit shuffle mask selection values into 128-bit
15224 // selection bits by dividing the indexes by 2 and shifting into positions
15225 // defined by a vperm2*128 instruction's immediate control byte.
15227 // The immediate permute control byte looks like this:
15228 // [1:0] - select 128 bits from sources for low half of destination
15229 // [2] - ignore
15230 // [3] - zero low half of destination
15231 // [5:4] - select 128 bits from sources for high half of destination
15232 // [6] - ignore
15233 // [7] - zero high half of destination
15235 assert((WidenedMask[0] >= 0 || IsLowZero) &&
15236 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
15238 unsigned PermMask = 0;
15239 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
15240 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
15242 // Check the immediate mask and replace unused sources with undef.
15243 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
15244 V1 = DAG.getUNDEF(VT);
15245 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
15246 V2 = DAG.getUNDEF(VT);
15248 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
15249 DAG.getTargetConstant(PermMask, DL, MVT::i8));
15252 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
15253 /// shuffling each lane.
15255 /// This attempts to create a repeated lane shuffle where each lane uses one
15256 /// or two of the lanes of the inputs. The lanes of the input vectors are
15257 /// shuffled in one or two independent shuffles to get the lanes into the
15258 /// position needed by the final shuffle.
15259 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
15260 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15261 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15262 assert(!V2.isUndef() && "This is only useful with multiple inputs.");
15264 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
15265 return SDValue();
15267 int NumElts = Mask.size();
15268 int NumLanes = VT.getSizeInBits() / 128;
15269 int NumLaneElts = 128 / VT.getScalarSizeInBits();
15270 SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
15271 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
15273 // First pass will try to fill in the RepeatMask from lanes that need two
15274 // sources.
15275 for (int Lane = 0; Lane != NumLanes; ++Lane) {
15276 int Srcs[2] = {-1, -1};
15277 SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
15278 for (int i = 0; i != NumLaneElts; ++i) {
15279 int M = Mask[(Lane * NumLaneElts) + i];
15280 if (M < 0)
15281 continue;
15282 // Determine which of the possible input lanes (NumLanes from each source)
15283 // this element comes from. Assign that as one of the sources for this
15284 // lane. We can assign up to 2 sources for this lane. If we run out
15285 // sources we can't do anything.
15286 int LaneSrc = M / NumLaneElts;
15287 int Src;
15288 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
15289 Src = 0;
15290 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
15291 Src = 1;
15292 else
15293 return SDValue();
15295 Srcs[Src] = LaneSrc;
15296 InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
15299 // If this lane has two sources, see if it fits with the repeat mask so far.
15300 if (Srcs[1] < 0)
15301 continue;
15303 LaneSrcs[Lane][0] = Srcs[0];
15304 LaneSrcs[Lane][1] = Srcs[1];
15306 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
15307 assert(M1.size() == M2.size() && "Unexpected mask size");
15308 for (int i = 0, e = M1.size(); i != e; ++i)
15309 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
15310 return false;
15311 return true;
15314 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
15315 assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
15316 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
15317 int M = Mask[i];
15318 if (M < 0)
15319 continue;
15320 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
15321 "Unexpected mask element");
15322 MergedMask[i] = M;
15326 if (MatchMasks(InLaneMask, RepeatMask)) {
15327 // Merge this lane mask into the final repeat mask.
15328 MergeMasks(InLaneMask, RepeatMask);
15329 continue;
15332 // Didn't find a match. Swap the operands and try again.
15333 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
15334 ShuffleVectorSDNode::commuteMask(InLaneMask);
15336 if (MatchMasks(InLaneMask, RepeatMask)) {
15337 // Merge this lane mask into the final repeat mask.
15338 MergeMasks(InLaneMask, RepeatMask);
15339 continue;
15342 // Couldn't find a match with the operands in either order.
15343 return SDValue();
15346 // Now handle any lanes with only one source.
15347 for (int Lane = 0; Lane != NumLanes; ++Lane) {
15348 // If this lane has already been processed, skip it.
15349 if (LaneSrcs[Lane][0] >= 0)
15350 continue;
15352 for (int i = 0; i != NumLaneElts; ++i) {
15353 int M = Mask[(Lane * NumLaneElts) + i];
15354 if (M < 0)
15355 continue;
15357 // If RepeatMask isn't defined yet we can define it ourself.
15358 if (RepeatMask[i] < 0)
15359 RepeatMask[i] = M % NumLaneElts;
15361 if (RepeatMask[i] < NumElts) {
15362 if (RepeatMask[i] != M % NumLaneElts)
15363 return SDValue();
15364 LaneSrcs[Lane][0] = M / NumLaneElts;
15365 } else {
15366 if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
15367 return SDValue();
15368 LaneSrcs[Lane][1] = M / NumLaneElts;
15372 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
15373 return SDValue();
15376 SmallVector<int, 16> NewMask(NumElts, -1);
15377 for (int Lane = 0; Lane != NumLanes; ++Lane) {
15378 int Src = LaneSrcs[Lane][0];
15379 for (int i = 0; i != NumLaneElts; ++i) {
15380 int M = -1;
15381 if (Src >= 0)
15382 M = Src * NumLaneElts + i;
15383 NewMask[Lane * NumLaneElts + i] = M;
15386 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15387 // Ensure we didn't get back the shuffle we started with.
15388 // FIXME: This is a hack to make up for some splat handling code in
15389 // getVectorShuffle.
15390 if (isa<ShuffleVectorSDNode>(NewV1) &&
15391 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
15392 return SDValue();
15394 for (int Lane = 0; Lane != NumLanes; ++Lane) {
15395 int Src = LaneSrcs[Lane][1];
15396 for (int i = 0; i != NumLaneElts; ++i) {
15397 int M = -1;
15398 if (Src >= 0)
15399 M = Src * NumLaneElts + i;
15400 NewMask[Lane * NumLaneElts + i] = M;
15403 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15404 // Ensure we didn't get back the shuffle we started with.
15405 // FIXME: This is a hack to make up for some splat handling code in
15406 // getVectorShuffle.
15407 if (isa<ShuffleVectorSDNode>(NewV2) &&
15408 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
15409 return SDValue();
15411 for (int i = 0; i != NumElts; ++i) {
15412 if (Mask[i] < 0) {
15413 NewMask[i] = -1;
15414 continue;
15416 NewMask[i] = RepeatMask[i % NumLaneElts];
15417 if (NewMask[i] < 0)
15418 continue;
15420 NewMask[i] += (i / NumLaneElts) * NumLaneElts;
15422 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
15425 /// If the input shuffle mask results in a vector that is undefined in all upper
15426 /// or lower half elements and that mask accesses only 2 halves of the
15427 /// shuffle's operands, return true. A mask of half the width with mask indexes
15428 /// adjusted to access the extracted halves of the original shuffle operands is
15429 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
15430 /// lower half of each input operand is accessed.
15431 static bool
15432 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
15433 int &HalfIdx1, int &HalfIdx2) {
15434 assert((Mask.size() == HalfMask.size() * 2) &&
15435 "Expected input mask to be twice as long as output");
15437 // Exactly one half of the result must be undef to allow narrowing.
15438 bool UndefLower = isUndefLowerHalf(Mask);
15439 bool UndefUpper = isUndefUpperHalf(Mask);
15440 if (UndefLower == UndefUpper)
15441 return false;
15443 unsigned HalfNumElts = HalfMask.size();
15444 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
15445 HalfIdx1 = -1;
15446 HalfIdx2 = -1;
15447 for (unsigned i = 0; i != HalfNumElts; ++i) {
15448 int M = Mask[i + MaskIndexOffset];
15449 if (M < 0) {
15450 HalfMask[i] = M;
15451 continue;
15454 // Determine which of the 4 half vectors this element is from.
15455 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
15456 int HalfIdx = M / HalfNumElts;
15458 // Determine the element index into its half vector source.
15459 int HalfElt = M % HalfNumElts;
15461 // We can shuffle with up to 2 half vectors, set the new 'half'
15462 // shuffle mask accordingly.
15463 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
15464 HalfMask[i] = HalfElt;
15465 HalfIdx1 = HalfIdx;
15466 continue;
15468 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
15469 HalfMask[i] = HalfElt + HalfNumElts;
15470 HalfIdx2 = HalfIdx;
15471 continue;
15474 // Too many half vectors referenced.
15475 return false;
15478 return true;
15481 /// Given the output values from getHalfShuffleMask(), create a half width
15482 /// shuffle of extracted vectors followed by an insert back to full width.
15483 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
15484 ArrayRef<int> HalfMask, int HalfIdx1,
15485 int HalfIdx2, bool UndefLower,
15486 SelectionDAG &DAG, bool UseConcat = false) {
15487 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
15488 assert(V1.getValueType().isSimple() && "Expecting only simple types");
15490 MVT VT = V1.getSimpleValueType();
15491 MVT HalfVT = VT.getHalfNumVectorElementsVT();
15492 unsigned HalfNumElts = HalfVT.getVectorNumElements();
15494 auto getHalfVector = [&](int HalfIdx) {
15495 if (HalfIdx < 0)
15496 return DAG.getUNDEF(HalfVT);
15497 SDValue V = (HalfIdx < 2 ? V1 : V2);
15498 HalfIdx = (HalfIdx % 2) * HalfNumElts;
15499 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
15500 DAG.getIntPtrConstant(HalfIdx, DL));
15503 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
15504 SDValue Half1 = getHalfVector(HalfIdx1);
15505 SDValue Half2 = getHalfVector(HalfIdx2);
15506 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
15507 if (UseConcat) {
15508 SDValue Op0 = V;
15509 SDValue Op1 = DAG.getUNDEF(HalfVT);
15510 if (UndefLower)
15511 std::swap(Op0, Op1);
15512 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
15515 unsigned Offset = UndefLower ? HalfNumElts : 0;
15516 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
15517 DAG.getIntPtrConstant(Offset, DL));
15520 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
15521 /// This allows for fast cases such as subvector extraction/insertion
15522 /// or shuffling smaller vector types which can lower more efficiently.
15523 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
15524 SDValue V2, ArrayRef<int> Mask,
15525 const X86Subtarget &Subtarget,
15526 SelectionDAG &DAG) {
15527 assert((VT.is256BitVector() || VT.is512BitVector()) &&
15528 "Expected 256-bit or 512-bit vector");
15530 bool UndefLower = isUndefLowerHalf(Mask);
15531 if (!UndefLower && !isUndefUpperHalf(Mask))
15532 return SDValue();
15534 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
15535 "Completely undef shuffle mask should have been simplified already");
15537 // Upper half is undef and lower half is whole upper subvector.
15538 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15539 MVT HalfVT = VT.getHalfNumVectorElementsVT();
15540 unsigned HalfNumElts = HalfVT.getVectorNumElements();
15541 if (!UndefLower &&
15542 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
15543 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15544 DAG.getIntPtrConstant(HalfNumElts, DL));
15545 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15546 DAG.getIntPtrConstant(0, DL));
15549 // Lower half is undef and upper half is whole lower subvector.
15550 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15551 if (UndefLower &&
15552 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
15553 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15554 DAG.getIntPtrConstant(0, DL));
15555 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15556 DAG.getIntPtrConstant(HalfNumElts, DL));
15559 int HalfIdx1, HalfIdx2;
15560 SmallVector<int, 8> HalfMask(HalfNumElts);
15561 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
15562 return SDValue();
15564 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
15566 // Only shuffle the halves of the inputs when useful.
15567 unsigned NumLowerHalves =
15568 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
15569 unsigned NumUpperHalves =
15570 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
15571 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
15573 // Determine the larger pattern of undef/halves, then decide if it's worth
15574 // splitting the shuffle based on subtarget capabilities and types.
15575 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
15576 if (!UndefLower) {
15577 // XXXXuuuu: no insert is needed.
15578 // Always extract lowers when setting lower - these are all free subreg ops.
15579 if (NumUpperHalves == 0)
15580 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15581 UndefLower, DAG);
15583 if (NumUpperHalves == 1) {
15584 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
15585 if (Subtarget.hasAVX2()) {
15586 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
15587 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
15588 !is128BitUnpackShuffleMask(HalfMask, DAG) &&
15589 (!isSingleSHUFPSMask(HalfMask) ||
15590 Subtarget.hasFastVariableCrossLaneShuffle()))
15591 return SDValue();
15592 // If this is a unary shuffle (assume that the 2nd operand is
15593 // canonicalized to undef), then we can use vpermpd. Otherwise, we
15594 // are better off extracting the upper half of 1 operand and using a
15595 // narrow shuffle.
15596 if (EltWidth == 64 && V2.isUndef())
15597 return SDValue();
15599 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15600 if (Subtarget.hasAVX512() && VT.is512BitVector())
15601 return SDValue();
15602 // Extract + narrow shuffle is better than the wide alternative.
15603 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15604 UndefLower, DAG);
15607 // Don't extract both uppers, instead shuffle and then extract.
15608 assert(NumUpperHalves == 2 && "Half vector count went wrong");
15609 return SDValue();
15612 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
15613 if (NumUpperHalves == 0) {
15614 // AVX2 has efficient 64-bit element cross-lane shuffles.
15615 // TODO: Refine to account for unary shuffle, splat, and other masks?
15616 if (Subtarget.hasAVX2() && EltWidth == 64)
15617 return SDValue();
15618 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15619 if (Subtarget.hasAVX512() && VT.is512BitVector())
15620 return SDValue();
15621 // Narrow shuffle + insert is better than the wide alternative.
15622 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15623 UndefLower, DAG);
15626 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
15627 return SDValue();
15630 /// Handle case where shuffle sources are coming from the same 128-bit lane and
15631 /// every lane can be represented as the same repeating mask - allowing us to
15632 /// shuffle the sources with the repeating shuffle and then permute the result
15633 /// to the destination lanes.
15634 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
15635 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15636 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15637 int NumElts = VT.getVectorNumElements();
15638 int NumLanes = VT.getSizeInBits() / 128;
15639 int NumLaneElts = NumElts / NumLanes;
15641 // On AVX2 we may be able to just shuffle the lowest elements and then
15642 // broadcast the result.
15643 if (Subtarget.hasAVX2()) {
15644 for (unsigned BroadcastSize : {16, 32, 64}) {
15645 if (BroadcastSize <= VT.getScalarSizeInBits())
15646 continue;
15647 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
15649 // Attempt to match a repeating pattern every NumBroadcastElts,
15650 // accounting for UNDEFs but only references the lowest 128-bit
15651 // lane of the inputs.
15652 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
15653 for (int i = 0; i != NumElts; i += NumBroadcastElts)
15654 for (int j = 0; j != NumBroadcastElts; ++j) {
15655 int M = Mask[i + j];
15656 if (M < 0)
15657 continue;
15658 int &R = RepeatMask[j];
15659 if (0 != ((M % NumElts) / NumLaneElts))
15660 return false;
15661 if (0 <= R && R != M)
15662 return false;
15663 R = M;
15665 return true;
15668 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
15669 if (!FindRepeatingBroadcastMask(RepeatMask))
15670 continue;
15672 // Shuffle the (lowest) repeated elements in place for broadcast.
15673 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
15675 // Shuffle the actual broadcast.
15676 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
15677 for (int i = 0; i != NumElts; i += NumBroadcastElts)
15678 for (int j = 0; j != NumBroadcastElts; ++j)
15679 BroadcastMask[i + j] = j;
15681 // Avoid returning the same shuffle operation. For example,
15682 // v8i32 = vector_shuffle<0,1,0,1,0,1,0,1> t5, undef:v8i32
15683 if (BroadcastMask == Mask)
15684 return SDValue();
15686 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
15687 BroadcastMask);
15691 // Bail if the shuffle mask doesn't cross 128-bit lanes.
15692 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
15693 return SDValue();
15695 // Bail if we already have a repeated lane shuffle mask.
15696 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
15697 return SDValue();
15699 // Helper to look for repeated mask in each split sublane, and that those
15700 // sublanes can then be permuted into place.
15701 auto ShuffleSubLanes = [&](int SubLaneScale) {
15702 int NumSubLanes = NumLanes * SubLaneScale;
15703 int NumSubLaneElts = NumLaneElts / SubLaneScale;
15705 // Check that all the sources are coming from the same lane and see if we
15706 // can form a repeating shuffle mask (local to each sub-lane). At the same
15707 // time, determine the source sub-lane for each destination sub-lane.
15708 int TopSrcSubLane = -1;
15709 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
15710 SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
15711 SubLaneScale,
15712 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
15714 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
15715 // Extract the sub-lane mask, check that it all comes from the same lane
15716 // and normalize the mask entries to come from the first lane.
15717 int SrcLane = -1;
15718 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
15719 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15720 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
15721 if (M < 0)
15722 continue;
15723 int Lane = (M % NumElts) / NumLaneElts;
15724 if ((0 <= SrcLane) && (SrcLane != Lane))
15725 return SDValue();
15726 SrcLane = Lane;
15727 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
15728 SubLaneMask[Elt] = LocalM;
15731 // Whole sub-lane is UNDEF.
15732 if (SrcLane < 0)
15733 continue;
15735 // Attempt to match against the candidate repeated sub-lane masks.
15736 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
15737 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
15738 for (int i = 0; i != NumSubLaneElts; ++i) {
15739 if (M1[i] < 0 || M2[i] < 0)
15740 continue;
15741 if (M1[i] != M2[i])
15742 return false;
15744 return true;
15747 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
15748 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
15749 continue;
15751 // Merge the sub-lane mask into the matching repeated sub-lane mask.
15752 for (int i = 0; i != NumSubLaneElts; ++i) {
15753 int M = SubLaneMask[i];
15754 if (M < 0)
15755 continue;
15756 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
15757 "Unexpected mask element");
15758 RepeatedSubLaneMask[i] = M;
15761 // Track the top most source sub-lane - by setting the remaining to
15762 // UNDEF we can greatly simplify shuffle matching.
15763 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
15764 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
15765 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
15766 break;
15769 // Bail if we failed to find a matching repeated sub-lane mask.
15770 if (Dst2SrcSubLanes[DstSubLane] < 0)
15771 return SDValue();
15773 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
15774 "Unexpected source lane");
15776 // Create a repeating shuffle mask for the entire vector.
15777 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
15778 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
15779 int Lane = SubLane / SubLaneScale;
15780 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
15781 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15782 int M = RepeatedSubLaneMask[Elt];
15783 if (M < 0)
15784 continue;
15785 int Idx = (SubLane * NumSubLaneElts) + Elt;
15786 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
15790 // Shuffle each source sub-lane to its destination.
15791 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
15792 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
15793 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
15794 if (SrcSubLane < 0)
15795 continue;
15796 for (int j = 0; j != NumSubLaneElts; ++j)
15797 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
15800 // Avoid returning the same shuffle operation.
15801 // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
15802 if (RepeatedMask == Mask || SubLaneMask == Mask)
15803 return SDValue();
15805 SDValue RepeatedShuffle =
15806 DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
15808 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
15809 SubLaneMask);
15812 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
15813 // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
15814 // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
15815 // Otherwise we can only permute whole 128-bit lanes.
15816 int MinSubLaneScale = 1, MaxSubLaneScale = 1;
15817 if (Subtarget.hasAVX2() && VT.is256BitVector()) {
15818 bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
15819 MinSubLaneScale = 2;
15820 MaxSubLaneScale =
15821 (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
15823 if (Subtarget.hasBWI() && VT == MVT::v64i8)
15824 MinSubLaneScale = MaxSubLaneScale = 4;
15826 for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
15827 if (SDValue Shuffle = ShuffleSubLanes(Scale))
15828 return Shuffle;
15830 return SDValue();
15833 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
15834 bool &ForceV1Zero, bool &ForceV2Zero,
15835 unsigned &ShuffleImm, ArrayRef<int> Mask,
15836 const APInt &Zeroable) {
15837 int NumElts = VT.getVectorNumElements();
15838 assert(VT.getScalarSizeInBits() == 64 &&
15839 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
15840 "Unexpected data type for VSHUFPD");
15841 assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
15842 "Illegal shuffle mask");
15844 bool ZeroLane[2] = { true, true };
15845 for (int i = 0; i < NumElts; ++i)
15846 ZeroLane[i & 1] &= Zeroable[i];
15848 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
15849 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
15850 bool IsSHUFPD = true;
15851 bool IsCommutable = true;
15852 SmallVector<int, 8> SHUFPDMask(NumElts, -1);
15853 for (int i = 0; i < NumElts; ++i) {
15854 if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
15855 continue;
15856 if (Mask[i] < 0)
15857 return false;
15858 int Val = (i & 6) + NumElts * (i & 1);
15859 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
15860 if (Mask[i] < Val || Mask[i] > Val + 1)
15861 IsSHUFPD = false;
15862 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
15863 IsCommutable = false;
15864 SHUFPDMask[i] = Mask[i] % 2;
15867 if (!IsSHUFPD && !IsCommutable)
15868 return false;
15870 if (!IsSHUFPD && IsCommutable)
15871 std::swap(V1, V2);
15873 ForceV1Zero = ZeroLane[0];
15874 ForceV2Zero = ZeroLane[1];
15875 ShuffleImm = getSHUFPDImm(SHUFPDMask);
15876 return true;
15879 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
15880 SDValue V2, ArrayRef<int> Mask,
15881 const APInt &Zeroable,
15882 const X86Subtarget &Subtarget,
15883 SelectionDAG &DAG) {
15884 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
15885 "Unexpected data type for VSHUFPD");
15887 unsigned Immediate = 0;
15888 bool ForceV1Zero = false, ForceV2Zero = false;
15889 if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
15890 Mask, Zeroable))
15891 return SDValue();
15893 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
15894 if (ForceV1Zero)
15895 V1 = getZeroVector(VT, Subtarget, DAG, DL);
15896 if (ForceV2Zero)
15897 V2 = getZeroVector(VT, Subtarget, DAG, DL);
15899 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15900 DAG.getTargetConstant(Immediate, DL, MVT::i8));
15903 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
15904 // by zeroable elements in the remaining 24 elements. Turn this into two
15905 // vmovqb instructions shuffled together.
15906 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
15907 SDValue V1, SDValue V2,
15908 ArrayRef<int> Mask,
15909 const APInt &Zeroable,
15910 SelectionDAG &DAG) {
15911 assert(VT == MVT::v32i8 && "Unexpected type!");
15913 // The first 8 indices should be every 8th element.
15914 if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
15915 return SDValue();
15917 // Remaining elements need to be zeroable.
15918 if (Zeroable.countl_one() < (Mask.size() - 8))
15919 return SDValue();
15921 V1 = DAG.getBitcast(MVT::v4i64, V1);
15922 V2 = DAG.getBitcast(MVT::v4i64, V2);
15924 V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
15925 V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
15927 // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
15928 // the upper bits of the result using an unpckldq.
15929 SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
15930 { 0, 1, 2, 3, 16, 17, 18, 19,
15931 4, 5, 6, 7, 20, 21, 22, 23 });
15932 // Insert the unpckldq into a zero vector to widen to v32i8.
15933 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
15934 DAG.getConstant(0, DL, MVT::v32i8), Unpack,
15935 DAG.getIntPtrConstant(0, DL));
15938 // a = shuffle v1, v2, mask1 ; interleaving lower lanes of v1 and v2
15939 // b = shuffle v1, v2, mask2 ; interleaving higher lanes of v1 and v2
15940 // =>
15941 // ul = unpckl v1, v2
15942 // uh = unpckh v1, v2
15943 // a = vperm ul, uh
15944 // b = vperm ul, uh
15946 // Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
15947 // and permute. We cannot directly match v3 because it is split into two
15948 // 256-bit vectors in earlier isel stages. Therefore, this function matches a
15949 // pair of 256-bit shuffles and makes sure the masks are consecutive.
15951 // Once unpck and permute nodes are created, the permute corresponding to this
15952 // shuffle is returned, while the other permute replaces the other half of the
15953 // shuffle in the selection dag.
15954 static SDValue lowerShufflePairAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
15955 SDValue V1, SDValue V2,
15956 ArrayRef<int> Mask,
15957 SelectionDAG &DAG) {
15958 if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
15959 VT != MVT::v32i8)
15960 return SDValue();
15961 // <B0, B1, B0+1, B1+1, ..., >
15962 auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
15963 unsigned Begin1) {
15964 size_t Size = Mask.size();
15965 assert(Size % 2 == 0 && "Expected even mask size");
15966 for (unsigned I = 0; I < Size; I += 2) {
15967 if (Mask[I] != (int)(Begin0 + I / 2) ||
15968 Mask[I + 1] != (int)(Begin1 + I / 2))
15969 return false;
15971 return true;
15973 // Check which half is this shuffle node
15974 int NumElts = VT.getVectorNumElements();
15975 size_t FirstQtr = NumElts / 2;
15976 size_t ThirdQtr = NumElts + NumElts / 2;
15977 bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
15978 bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
15979 if (!IsFirstHalf && !IsSecondHalf)
15980 return SDValue();
15982 // Find the intersection between shuffle users of V1 and V2.
15983 SmallVector<SDNode *, 2> Shuffles;
15984 for (SDNode *User : V1->uses())
15985 if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
15986 User->getOperand(1) == V2)
15987 Shuffles.push_back(User);
15988 // Limit user size to two for now.
15989 if (Shuffles.size() != 2)
15990 return SDValue();
15991 // Find out which half of the 512-bit shuffles is each smaller shuffle
15992 auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
15993 auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
15994 SDNode *FirstHalf;
15995 SDNode *SecondHalf;
15996 if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
15997 IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
15998 FirstHalf = Shuffles[0];
15999 SecondHalf = Shuffles[1];
16000 } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
16001 IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
16002 FirstHalf = Shuffles[1];
16003 SecondHalf = Shuffles[0];
16004 } else {
16005 return SDValue();
16007 // Lower into unpck and perm. Return the perm of this shuffle and replace
16008 // the other.
16009 SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
16010 SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
16011 SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16012 DAG.getTargetConstant(0x20, DL, MVT::i8));
16013 SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16014 DAG.getTargetConstant(0x31, DL, MVT::i8));
16015 if (IsFirstHalf) {
16016 DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
16017 return Perm1;
16019 DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
16020 return Perm2;
16023 /// Handle lowering of 4-lane 64-bit floating point shuffles.
16025 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16026 /// isn't available.
16027 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16028 const APInt &Zeroable, SDValue V1, SDValue V2,
16029 const X86Subtarget &Subtarget,
16030 SelectionDAG &DAG) {
16031 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16032 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16033 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16035 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16036 Subtarget, DAG))
16037 return V;
16039 if (V2.isUndef()) {
16040 // Check for being able to broadcast a single element.
16041 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16042 Mask, Subtarget, DAG))
16043 return Broadcast;
16045 // Use low duplicate instructions for masks that match their pattern.
16046 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16047 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16049 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16050 // Non-half-crossing single input shuffles can be lowered with an
16051 // interleaved permutation.
16052 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16053 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16054 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16055 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16058 // With AVX2 we have direct support for this permutation.
16059 if (Subtarget.hasAVX2())
16060 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16061 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16063 // Try to create an in-lane repeating shuffle mask and then shuffle the
16064 // results into the target lanes.
16065 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16066 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16067 return V;
16069 // Try to permute the lanes and then use a per-lane permute.
16070 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16071 Mask, DAG, Subtarget))
16072 return V;
16074 // Otherwise, fall back.
16075 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16076 DAG, Subtarget);
16079 // Use dedicated unpack instructions for masks that match their pattern.
16080 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, V1, V2, Mask, DAG))
16081 return V;
16083 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16084 Zeroable, Subtarget, DAG))
16085 return Blend;
16087 // Check if the blend happens to exactly fit that of SHUFPD.
16088 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16089 Zeroable, Subtarget, DAG))
16090 return Op;
16092 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16093 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16095 // If we have lane crossing shuffles AND they don't all come from the lower
16096 // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16097 // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16098 // canonicalize to a blend of splat which isn't necessary for this combine.
16099 if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16100 !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16101 (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16102 (V2.getOpcode() != ISD::BUILD_VECTOR))
16103 return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
16105 // If we have one input in place, then we can permute the other input and
16106 // blend the result.
16107 if (V1IsInPlace || V2IsInPlace)
16108 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16109 Zeroable, Subtarget, DAG);
16111 // Try to create an in-lane repeating shuffle mask and then shuffle the
16112 // results into the target lanes.
16113 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16114 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16115 return V;
16117 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16118 // shuffle. However, if we have AVX2 and either inputs are already in place,
16119 // we will be able to shuffle even across lanes the other input in a single
16120 // instruction so skip this pattern.
16121 if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
16122 if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
16123 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16124 return V;
16126 // If we have VLX support, we can use VEXPAND.
16127 if (Subtarget.hasVLX())
16128 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4f64, V1, V2, Mask,
16129 Zeroable, Subtarget, DAG))
16130 return V;
16132 // If we have AVX2 then we always want to lower with a blend because an v4 we
16133 // can fully permute the elements.
16134 if (Subtarget.hasAVX2())
16135 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16136 Zeroable, Subtarget, DAG);
16138 // Otherwise fall back on generic lowering.
16139 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16140 Subtarget, DAG);
16143 /// Handle lowering of 4-lane 64-bit integer shuffles.
16145 /// This routine is only called when we have AVX2 and thus a reasonable
16146 /// instruction set for v4i64 shuffling..
16147 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16148 const APInt &Zeroable, SDValue V1, SDValue V2,
16149 const X86Subtarget &Subtarget,
16150 SelectionDAG &DAG) {
16151 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16152 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16153 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16154 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16156 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16157 Subtarget, DAG))
16158 return V;
16160 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16161 Zeroable, Subtarget, DAG))
16162 return Blend;
16164 // Check for being able to broadcast a single element.
16165 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16166 Subtarget, DAG))
16167 return Broadcast;
16169 // Try to use shift instructions if fast.
16170 if (Subtarget.preferLowerShuffleAsShift())
16171 if (SDValue Shift =
16172 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16173 Subtarget, DAG, /*BitwiseOnly*/ true))
16174 return Shift;
16176 if (V2.isUndef()) {
16177 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16178 // can use lower latency instructions that will operate on both lanes.
16179 SmallVector<int, 2> RepeatedMask;
16180 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16181 SmallVector<int, 4> PSHUFDMask;
16182 narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16183 return DAG.getBitcast(
16184 MVT::v4i64,
16185 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16186 DAG.getBitcast(MVT::v8i32, V1),
16187 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16190 // AVX2 provides a direct instruction for permuting a single input across
16191 // lanes.
16192 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16193 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16196 // Try to use shift instructions.
16197 if (SDValue Shift =
16198 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
16199 DAG, /*BitwiseOnly*/ false))
16200 return Shift;
16202 // If we have VLX support, we can use VALIGN or VEXPAND.
16203 if (Subtarget.hasVLX()) {
16204 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16205 Zeroable, Subtarget, DAG))
16206 return Rotate;
16208 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4i64, V1, V2, Mask,
16209 Zeroable, Subtarget, DAG))
16210 return V;
16213 // Try to use PALIGNR.
16214 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16215 Subtarget, DAG))
16216 return Rotate;
16218 // Use dedicated unpack instructions for masks that match their pattern.
16219 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, V1, V2, Mask, DAG))
16220 return V;
16222 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16223 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16225 // If we have one input in place, then we can permute the other input and
16226 // blend the result.
16227 if (V1IsInPlace || V2IsInPlace)
16228 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
16229 Zeroable, Subtarget, DAG);
16231 // Try to create an in-lane repeating shuffle mask and then shuffle the
16232 // results into the target lanes.
16233 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16234 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16235 return V;
16237 // Try to lower to PERMQ(BLENDD(V1,V2)).
16238 if (SDValue V =
16239 lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
16240 return V;
16242 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16243 // shuffle. However, if we have AVX2 and either inputs are already in place,
16244 // we will be able to shuffle even across lanes the other input in a single
16245 // instruction so skip this pattern.
16246 if (!V1IsInPlace && !V2IsInPlace)
16247 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16248 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16249 return Result;
16251 // Otherwise fall back on generic blend lowering.
16252 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
16253 Zeroable, Subtarget, DAG);
16256 /// Handle lowering of 8-lane 32-bit floating point shuffles.
16258 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
16259 /// isn't available.
16260 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16261 const APInt &Zeroable, SDValue V1, SDValue V2,
16262 const X86Subtarget &Subtarget,
16263 SelectionDAG &DAG) {
16264 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16265 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16266 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16268 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
16269 Zeroable, Subtarget, DAG))
16270 return Blend;
16272 // Check for being able to broadcast a single element.
16273 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
16274 Subtarget, DAG))
16275 return Broadcast;
16277 if (!Subtarget.hasAVX2()) {
16278 SmallVector<int> InLaneMask;
16279 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
16281 if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
16282 if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
16283 /*SimpleOnly*/ true))
16284 return R;
16286 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
16287 Zeroable, Subtarget, DAG))
16288 return DAG.getBitcast(MVT::v8f32, ZExt);
16290 // If the shuffle mask is repeated in each 128-bit lane, we have many more
16291 // options to efficiently lower the shuffle.
16292 SmallVector<int, 4> RepeatedMask;
16293 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
16294 assert(RepeatedMask.size() == 4 &&
16295 "Repeated masks must be half the mask width!");
16297 // Use even/odd duplicate instructions for masks that match their pattern.
16298 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
16299 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
16300 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
16301 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
16303 if (V2.isUndef())
16304 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
16305 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16307 // Use dedicated unpack instructions for masks that match their pattern.
16308 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, V1, V2, Mask, DAG))
16309 return V;
16311 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
16312 // have already handled any direct blends.
16313 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
16316 // Try to create an in-lane repeating shuffle mask and then shuffle the
16317 // results into the target lanes.
16318 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16319 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16320 return V;
16322 // If we have a single input shuffle with different shuffle patterns in the
16323 // two 128-bit lanes use the variable mask to VPERMILPS.
16324 if (V2.isUndef()) {
16325 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
16326 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16327 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
16329 if (Subtarget.hasAVX2()) {
16330 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16331 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
16333 // Otherwise, fall back.
16334 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
16335 DAG, Subtarget);
16338 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16339 // shuffle.
16340 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16341 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16342 return Result;
16344 // If we have VLX support, we can use VEXPAND.
16345 if (Subtarget.hasVLX())
16346 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f32, V1, V2, Mask,
16347 Zeroable, Subtarget, DAG))
16348 return V;
16350 // Try to match an interleave of two v8f32s and lower them as unpck and
16351 // permutes using ymms. This needs to go before we try to split the vectors.
16353 // TODO: Expand this to AVX1. Currently v8i32 is casted to v8f32 and hits
16354 // this path inadvertently.
16355 if (Subtarget.hasAVX2() && !Subtarget.hasAVX512())
16356 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
16357 Mask, DAG))
16358 return V;
16360 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16361 // since after split we get a more efficient code using vpunpcklwd and
16362 // vpunpckhwd instrs than vblend.
16363 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
16364 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
16365 Subtarget, DAG);
16367 // If we have AVX2 then we always want to lower with a blend because at v8 we
16368 // can fully permute the elements.
16369 if (Subtarget.hasAVX2())
16370 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
16371 Zeroable, Subtarget, DAG);
16373 // Otherwise fall back on generic lowering.
16374 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
16375 Subtarget, DAG);
16378 /// Handle lowering of 8-lane 32-bit integer shuffles.
16380 /// This routine is only called when we have AVX2 and thus a reasonable
16381 /// instruction set for v8i32 shuffling..
16382 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16383 const APInt &Zeroable, SDValue V1, SDValue V2,
16384 const X86Subtarget &Subtarget,
16385 SelectionDAG &DAG) {
16386 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16387 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16388 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16389 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
16391 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
16393 // Whenever we can lower this as a zext, that instruction is strictly faster
16394 // than any alternative. It also allows us to fold memory operands into the
16395 // shuffle in many cases.
16396 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
16397 Zeroable, Subtarget, DAG))
16398 return ZExt;
16400 // Try to match an interleave of two v8i32s and lower them as unpck and
16401 // permutes using ymms. This needs to go before we try to split the vectors.
16402 if (!Subtarget.hasAVX512())
16403 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
16404 Mask, DAG))
16405 return V;
16407 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16408 // since after split we get a more efficient code than vblend by using
16409 // vpunpcklwd and vpunpckhwd instrs.
16410 if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
16411 !Subtarget.hasAVX512())
16412 return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
16413 Subtarget, DAG);
16415 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
16416 Zeroable, Subtarget, DAG))
16417 return Blend;
16419 // Check for being able to broadcast a single element.
16420 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
16421 Subtarget, DAG))
16422 return Broadcast;
16424 // Try to use shift instructions if fast.
16425 if (Subtarget.preferLowerShuffleAsShift()) {
16426 if (SDValue Shift =
16427 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
16428 Subtarget, DAG, /*BitwiseOnly*/ true))
16429 return Shift;
16430 if (NumV2Elements == 0)
16431 if (SDValue Rotate =
16432 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
16433 return Rotate;
16436 // If the shuffle mask is repeated in each 128-bit lane we can use more
16437 // efficient instructions that mirror the shuffles across the two 128-bit
16438 // lanes.
16439 SmallVector<int, 4> RepeatedMask;
16440 bool Is128BitLaneRepeatedShuffle =
16441 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
16442 if (Is128BitLaneRepeatedShuffle) {
16443 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16444 if (V2.isUndef())
16445 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
16446 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16448 // Use dedicated unpack instructions for masks that match their pattern.
16449 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, V1, V2, Mask, DAG))
16450 return V;
16453 // Try to use shift instructions.
16454 if (SDValue Shift =
16455 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
16456 DAG, /*BitwiseOnly*/ false))
16457 return Shift;
16459 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
16460 if (SDValue Rotate =
16461 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
16462 return Rotate;
16464 // If we have VLX support, we can use VALIGN or EXPAND.
16465 if (Subtarget.hasVLX()) {
16466 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
16467 Zeroable, Subtarget, DAG))
16468 return Rotate;
16470 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i32, V1, V2, Mask,
16471 Zeroable, Subtarget, DAG))
16472 return V;
16475 // Try to use byte rotation instructions.
16476 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
16477 Subtarget, DAG))
16478 return Rotate;
16480 // Try to create an in-lane repeating shuffle mask and then shuffle the
16481 // results into the target lanes.
16482 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16483 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16484 return V;
16486 if (V2.isUndef()) {
16487 // Try to produce a fixed cross-128-bit lane permute followed by unpack
16488 // because that should be faster than the variable permute alternatives.
16489 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, V1, V2, Mask, DAG))
16490 return V;
16492 // If the shuffle patterns aren't repeated but it's a single input, directly
16493 // generate a cross-lane VPERMD instruction.
16494 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16495 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
16498 // Assume that a single SHUFPS is faster than an alternative sequence of
16499 // multiple instructions (even if the CPU has a domain penalty).
16500 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16501 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16502 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
16503 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
16504 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
16505 CastV1, CastV2, DAG);
16506 return DAG.getBitcast(MVT::v8i32, ShufPS);
16509 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16510 // shuffle.
16511 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16512 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16513 return Result;
16515 // Otherwise fall back on generic blend lowering.
16516 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
16517 Zeroable, Subtarget, DAG);
16520 /// Handle lowering of 16-lane 16-bit integer shuffles.
16522 /// This routine is only called when we have AVX2 and thus a reasonable
16523 /// instruction set for v16i16 shuffling..
16524 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16525 const APInt &Zeroable, SDValue V1, SDValue V2,
16526 const X86Subtarget &Subtarget,
16527 SelectionDAG &DAG) {
16528 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16529 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16530 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16531 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
16533 // Whenever we can lower this as a zext, that instruction is strictly faster
16534 // than any alternative. It also allows us to fold memory operands into the
16535 // shuffle in many cases.
16536 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16537 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16538 return ZExt;
16540 // Check for being able to broadcast a single element.
16541 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
16542 Subtarget, DAG))
16543 return Broadcast;
16545 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
16546 Zeroable, Subtarget, DAG))
16547 return Blend;
16549 // Use dedicated unpack instructions for masks that match their pattern.
16550 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, V1, V2, Mask, DAG))
16551 return V;
16553 // Use dedicated pack instructions for masks that match their pattern.
16554 if (SDValue V =
16555 lowerShuffleWithPACK(DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16556 return V;
16558 // Try to use lower using a truncation.
16559 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
16560 Subtarget, DAG))
16561 return V;
16563 // Try to use shift instructions.
16564 if (SDValue Shift =
16565 lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
16566 Subtarget, DAG, /*BitwiseOnly*/ false))
16567 return Shift;
16569 // Try to use byte rotation instructions.
16570 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
16571 Subtarget, DAG))
16572 return Rotate;
16574 // Try to create an in-lane repeating shuffle mask and then shuffle the
16575 // results into the target lanes.
16576 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16577 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16578 return V;
16580 if (V2.isUndef()) {
16581 // Try to use bit rotation instructions.
16582 if (SDValue Rotate =
16583 lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
16584 return Rotate;
16586 // Try to produce a fixed cross-128-bit lane permute followed by unpack
16587 // because that should be faster than the variable permute alternatives.
16588 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, V1, V2, Mask, DAG))
16589 return V;
16591 // There are no generalized cross-lane shuffle operations available on i16
16592 // element types.
16593 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
16594 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16595 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16596 return V;
16598 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
16599 DAG, Subtarget);
16602 SmallVector<int, 8> RepeatedMask;
16603 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
16604 // As this is a single-input shuffle, the repeated mask should be
16605 // a strictly valid v8i16 mask that we can pass through to the v8i16
16606 // lowering to handle even the v16 case.
16607 return lowerV8I16GeneralSingleInputShuffle(
16608 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
16612 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
16613 Zeroable, Subtarget, DAG))
16614 return PSHUFB;
16616 // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
16617 if (Subtarget.hasBWI())
16618 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
16620 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16621 // shuffle.
16622 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16623 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16624 return Result;
16626 // Try to permute the lanes and then use a per-lane permute.
16627 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16628 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16629 return V;
16631 // Try to match an interleave of two v16i16s and lower them as unpck and
16632 // permutes using ymms.
16633 if (!Subtarget.hasAVX512())
16634 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
16635 Mask, DAG))
16636 return V;
16638 // Otherwise fall back on generic lowering.
16639 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
16640 Subtarget, DAG);
16643 /// Handle lowering of 32-lane 8-bit integer shuffles.
16645 /// This routine is only called when we have AVX2 and thus a reasonable
16646 /// instruction set for v32i8 shuffling..
16647 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16648 const APInt &Zeroable, SDValue V1, SDValue V2,
16649 const X86Subtarget &Subtarget,
16650 SelectionDAG &DAG) {
16651 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16652 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16653 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16654 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
16656 // Whenever we can lower this as a zext, that instruction is strictly faster
16657 // than any alternative. It also allows us to fold memory operands into the
16658 // shuffle in many cases.
16659 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
16660 Zeroable, Subtarget, DAG))
16661 return ZExt;
16663 // Check for being able to broadcast a single element.
16664 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
16665 Subtarget, DAG))
16666 return Broadcast;
16668 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
16669 Zeroable, Subtarget, DAG))
16670 return Blend;
16672 // Use dedicated unpack instructions for masks that match their pattern.
16673 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, V1, V2, Mask, DAG))
16674 return V;
16676 // Use dedicated pack instructions for masks that match their pattern.
16677 if (SDValue V =
16678 lowerShuffleWithPACK(DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16679 return V;
16681 // Try to use lower using a truncation.
16682 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
16683 Subtarget, DAG))
16684 return V;
16686 // Try to use shift instructions.
16687 if (SDValue Shift =
16688 lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
16689 DAG, /*BitwiseOnly*/ false))
16690 return Shift;
16692 // Try to use byte rotation instructions.
16693 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
16694 Subtarget, DAG))
16695 return Rotate;
16697 // Try to use bit rotation instructions.
16698 if (V2.isUndef())
16699 if (SDValue Rotate =
16700 lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
16701 return Rotate;
16703 // Try to create an in-lane repeating shuffle mask and then shuffle the
16704 // results into the target lanes.
16705 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16706 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16707 return V;
16709 // There are no generalized cross-lane shuffle operations available on i8
16710 // element types.
16711 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
16712 // Try to produce a fixed cross-128-bit lane permute followed by unpack
16713 // because that should be faster than the variable permute alternatives.
16714 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, V1, V2, Mask, DAG))
16715 return V;
16717 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16718 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16719 return V;
16721 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
16722 DAG, Subtarget);
16725 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
16726 Zeroable, Subtarget, DAG))
16727 return PSHUFB;
16729 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
16730 if (Subtarget.hasVBMI())
16731 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
16733 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16734 // shuffle.
16735 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16736 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16737 return Result;
16739 // Try to permute the lanes and then use a per-lane permute.
16740 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16741 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16742 return V;
16744 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16745 // by zeroable elements in the remaining 24 elements. Turn this into two
16746 // vmovqb instructions shuffled together.
16747 if (Subtarget.hasVLX())
16748 if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
16749 Mask, Zeroable, DAG))
16750 return V;
16752 // Try to match an interleave of two v32i8s and lower them as unpck and
16753 // permutes using ymms.
16754 if (!Subtarget.hasAVX512())
16755 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
16756 Mask, DAG))
16757 return V;
16759 // Otherwise fall back on generic lowering.
16760 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
16761 Subtarget, DAG);
16764 /// High-level routine to lower various 256-bit x86 vector shuffles.
16766 /// This routine either breaks down the specific type of a 256-bit x86 vector
16767 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
16768 /// together based on the available instructions.
16769 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
16770 SDValue V1, SDValue V2, const APInt &Zeroable,
16771 const X86Subtarget &Subtarget,
16772 SelectionDAG &DAG) {
16773 // If we have a single input to the zero element, insert that into V1 if we
16774 // can do so cheaply.
16775 int NumElts = VT.getVectorNumElements();
16776 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16778 if (NumV2Elements == 1 && Mask[0] >= NumElts)
16779 if (SDValue Insertion = lowerShuffleAsElementInsertion(
16780 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16781 return Insertion;
16783 // Handle special cases where the lower or upper half is UNDEF.
16784 if (SDValue V =
16785 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16786 return V;
16788 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
16789 // can check for those subtargets here and avoid much of the subtarget
16790 // querying in the per-vector-type lowering routines. With AVX1 we have
16791 // essentially *zero* ability to manipulate a 256-bit vector with integer
16792 // types. Since we'll use floating point types there eventually, just
16793 // immediately cast everything to a float and operate entirely in that domain.
16794 if (VT.isInteger() && !Subtarget.hasAVX2()) {
16795 int ElementBits = VT.getScalarSizeInBits();
16796 if (ElementBits < 32) {
16797 // No floating point type available, if we can't use the bit operations
16798 // for masking/blending then decompose into 128-bit vectors.
16799 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
16800 Subtarget, DAG))
16801 return V;
16802 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
16803 return V;
16804 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
16807 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
16808 VT.getVectorNumElements());
16809 V1 = DAG.getBitcast(FpVT, V1);
16810 V2 = DAG.getBitcast(FpVT, V2);
16811 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
16814 if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
16815 V1 = DAG.getBitcast(MVT::v16i16, V1);
16816 V2 = DAG.getBitcast(MVT::v16i16, V2);
16817 return DAG.getBitcast(VT,
16818 DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
16821 switch (VT.SimpleTy) {
16822 case MVT::v4f64:
16823 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16824 case MVT::v4i64:
16825 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16826 case MVT::v8f32:
16827 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16828 case MVT::v8i32:
16829 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16830 case MVT::v16i16:
16831 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16832 case MVT::v32i8:
16833 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16835 default:
16836 llvm_unreachable("Not a valid 256-bit x86 vector type!");
16840 /// Try to lower a vector shuffle as a 128-bit shuffles.
16841 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
16842 const APInt &Zeroable, SDValue V1, SDValue V2,
16843 const X86Subtarget &Subtarget,
16844 SelectionDAG &DAG) {
16845 assert(VT.getScalarSizeInBits() == 64 &&
16846 "Unexpected element type size for 128bit shuffle.");
16848 // To handle 256 bit vector requires VLX and most probably
16849 // function lowerV2X128VectorShuffle() is better solution.
16850 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
16852 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
16853 SmallVector<int, 4> Widened128Mask;
16854 if (!canWidenShuffleElements(Mask, Widened128Mask))
16855 return SDValue();
16856 assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
16858 // Try to use an insert into a zero vector.
16859 if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
16860 (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
16861 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
16862 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
16863 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16864 DAG.getIntPtrConstant(0, DL));
16865 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16866 getZeroVector(VT, Subtarget, DAG, DL), LoV,
16867 DAG.getIntPtrConstant(0, DL));
16870 // Check for patterns which can be matched with a single insert of a 256-bit
16871 // subvector.
16872 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
16873 if (OnlyUsesV1 ||
16874 isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
16875 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
16876 SDValue SubVec =
16877 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
16878 DAG.getIntPtrConstant(0, DL));
16879 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16880 DAG.getIntPtrConstant(4, DL));
16883 // See if this is an insertion of the lower 128-bits of V2 into V1.
16884 bool IsInsert = true;
16885 int V2Index = -1;
16886 for (int i = 0; i < 4; ++i) {
16887 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
16888 if (Widened128Mask[i] < 0)
16889 continue;
16891 // Make sure all V1 subvectors are in place.
16892 if (Widened128Mask[i] < 4) {
16893 if (Widened128Mask[i] != i) {
16894 IsInsert = false;
16895 break;
16897 } else {
16898 // Make sure we only have a single V2 index and its the lowest 128-bits.
16899 if (V2Index >= 0 || Widened128Mask[i] != 4) {
16900 IsInsert = false;
16901 break;
16903 V2Index = i;
16906 if (IsInsert && V2Index >= 0) {
16907 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16908 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
16909 DAG.getIntPtrConstant(0, DL));
16910 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
16913 // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
16914 // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
16915 // possible we at least ensure the lanes stay sequential to help later
16916 // combines.
16917 SmallVector<int, 2> Widened256Mask;
16918 if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
16919 Widened128Mask.clear();
16920 narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
16923 // Try to lower to vshuf64x2/vshuf32x4.
16924 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
16925 int PermMask[4] = {-1, -1, -1, -1};
16926 // Ensure elements came from the same Op.
16927 for (int i = 0; i < 4; ++i) {
16928 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
16929 if (Widened128Mask[i] < 0)
16930 continue;
16932 SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
16933 unsigned OpIndex = i / 2;
16934 if (Ops[OpIndex].isUndef())
16935 Ops[OpIndex] = Op;
16936 else if (Ops[OpIndex] != Op)
16937 return SDValue();
16939 PermMask[i] = Widened128Mask[i] % 4;
16942 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
16943 getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
16946 /// Handle lowering of 8-lane 64-bit floating point shuffles.
16947 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16948 const APInt &Zeroable, SDValue V1, SDValue V2,
16949 const X86Subtarget &Subtarget,
16950 SelectionDAG &DAG) {
16951 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16952 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16953 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16955 if (V2.isUndef()) {
16956 // Use low duplicate instructions for masks that match their pattern.
16957 if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
16958 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
16960 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
16961 // Non-half-crossing single input shuffles can be lowered with an
16962 // interleaved permutation.
16963 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16964 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
16965 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
16966 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
16967 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
16968 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16971 SmallVector<int, 4> RepeatedMask;
16972 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
16973 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
16974 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16977 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
16978 V2, Subtarget, DAG))
16979 return Shuf128;
16981 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, V1, V2, Mask, DAG))
16982 return Unpck;
16984 // Check if the blend happens to exactly fit that of SHUFPD.
16985 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
16986 Zeroable, Subtarget, DAG))
16987 return Op;
16989 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f64, V1, V2, Mask, Zeroable,
16990 Subtarget, DAG))
16991 return V;
16993 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
16994 Zeroable, Subtarget, DAG))
16995 return Blend;
16997 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17000 /// Handle lowering of 16-lane 32-bit floating point shuffles.
17001 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17002 const APInt &Zeroable, SDValue V1, SDValue V2,
17003 const X86Subtarget &Subtarget,
17004 SelectionDAG &DAG) {
17005 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17006 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17007 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17009 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17010 // options to efficiently lower the shuffle.
17011 SmallVector<int, 4> RepeatedMask;
17012 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17013 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17015 // Use even/odd duplicate instructions for masks that match their pattern.
17016 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17017 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17018 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17019 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17021 if (V2.isUndef())
17022 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17023 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17025 // Use dedicated unpack instructions for masks that match their pattern.
17026 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, V1, V2, Mask, DAG))
17027 return V;
17029 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17030 Zeroable, Subtarget, DAG))
17031 return Blend;
17033 // Otherwise, fall back to a SHUFPS sequence.
17034 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17037 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17038 Zeroable, Subtarget, DAG))
17039 return Blend;
17041 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17042 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17043 return DAG.getBitcast(MVT::v16f32, ZExt);
17045 // Try to create an in-lane repeating shuffle mask and then shuffle the
17046 // results into the target lanes.
17047 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17048 DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17049 return V;
17051 // If we have a single input shuffle with different shuffle patterns in the
17052 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17053 if (V2.isUndef() &&
17054 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17055 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17056 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17059 // If we have AVX512F support, we can use VEXPAND.
17060 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16f32, V1, V2, Mask,
17061 Zeroable, Subtarget, DAG))
17062 return V;
17064 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17067 /// Handle lowering of 8-lane 64-bit integer shuffles.
17068 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17069 const APInt &Zeroable, SDValue V1, SDValue V2,
17070 const X86Subtarget &Subtarget,
17071 SelectionDAG &DAG) {
17072 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17073 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17074 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17076 // Try to use shift instructions if fast.
17077 if (Subtarget.preferLowerShuffleAsShift())
17078 if (SDValue Shift =
17079 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17080 Subtarget, DAG, /*BitwiseOnly*/ true))
17081 return Shift;
17083 if (V2.isUndef()) {
17084 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17085 // can use lower latency instructions that will operate on all four
17086 // 128-bit lanes.
17087 SmallVector<int, 2> Repeated128Mask;
17088 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17089 SmallVector<int, 4> PSHUFDMask;
17090 narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17091 return DAG.getBitcast(
17092 MVT::v8i64,
17093 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17094 DAG.getBitcast(MVT::v16i32, V1),
17095 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17098 SmallVector<int, 4> Repeated256Mask;
17099 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17100 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17101 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17104 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17105 V2, Subtarget, DAG))
17106 return Shuf128;
17108 // Try to use shift instructions.
17109 if (SDValue Shift =
17110 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
17111 DAG, /*BitwiseOnly*/ false))
17112 return Shift;
17114 // Try to use VALIGN.
17115 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17116 Zeroable, Subtarget, DAG))
17117 return Rotate;
17119 // Try to use PALIGNR.
17120 if (Subtarget.hasBWI())
17121 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17122 Subtarget, DAG))
17123 return Rotate;
17125 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, V1, V2, Mask, DAG))
17126 return Unpck;
17128 // If we have AVX512F support, we can use VEXPAND.
17129 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17130 Subtarget, DAG))
17131 return V;
17133 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17134 Zeroable, Subtarget, DAG))
17135 return Blend;
17137 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17140 /// Handle lowering of 16-lane 32-bit integer shuffles.
17141 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17142 const APInt &Zeroable, SDValue V1, SDValue V2,
17143 const X86Subtarget &Subtarget,
17144 SelectionDAG &DAG) {
17145 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17146 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17147 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17149 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
17151 // Whenever we can lower this as a zext, that instruction is strictly faster
17152 // than any alternative. It also allows us to fold memory operands into the
17153 // shuffle in many cases.
17154 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17155 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17156 return ZExt;
17158 // Try to use shift instructions if fast.
17159 if (Subtarget.preferLowerShuffleAsShift()) {
17160 if (SDValue Shift =
17161 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17162 Subtarget, DAG, /*BitwiseOnly*/ true))
17163 return Shift;
17164 if (NumV2Elements == 0)
17165 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
17166 Subtarget, DAG))
17167 return Rotate;
17170 // If the shuffle mask is repeated in each 128-bit lane we can use more
17171 // efficient instructions that mirror the shuffles across the four 128-bit
17172 // lanes.
17173 SmallVector<int, 4> RepeatedMask;
17174 bool Is128BitLaneRepeatedShuffle =
17175 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17176 if (Is128BitLaneRepeatedShuffle) {
17177 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17178 if (V2.isUndef())
17179 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17180 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17182 // Use dedicated unpack instructions for masks that match their pattern.
17183 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, V1, V2, Mask, DAG))
17184 return V;
17187 // Try to use shift instructions.
17188 if (SDValue Shift =
17189 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17190 Subtarget, DAG, /*BitwiseOnly*/ false))
17191 return Shift;
17193 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
17194 if (SDValue Rotate =
17195 lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
17196 return Rotate;
17198 // Try to use VALIGN.
17199 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17200 Zeroable, Subtarget, DAG))
17201 return Rotate;
17203 // Try to use byte rotation instructions.
17204 if (Subtarget.hasBWI())
17205 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17206 Subtarget, DAG))
17207 return Rotate;
17209 // Assume that a single SHUFPS is faster than using a permv shuffle.
17210 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17211 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17212 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
17213 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
17214 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
17215 CastV1, CastV2, DAG);
17216 return DAG.getBitcast(MVT::v16i32, ShufPS);
17219 // Try to create an in-lane repeating shuffle mask and then shuffle the
17220 // results into the target lanes.
17221 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17222 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
17223 return V;
17225 // If we have AVX512F support, we can use VEXPAND.
17226 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16i32, V1, V2, Mask,
17227 Zeroable, Subtarget, DAG))
17228 return V;
17230 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
17231 Zeroable, Subtarget, DAG))
17232 return Blend;
17234 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
17237 /// Handle lowering of 32-lane 16-bit integer shuffles.
17238 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17239 const APInt &Zeroable, SDValue V1, SDValue V2,
17240 const X86Subtarget &Subtarget,
17241 SelectionDAG &DAG) {
17242 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17243 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17244 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17245 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
17247 // Whenever we can lower this as a zext, that instruction is strictly faster
17248 // than any alternative. It also allows us to fold memory operands into the
17249 // shuffle in many cases.
17250 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17251 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17252 return ZExt;
17254 // Use dedicated unpack instructions for masks that match their pattern.
17255 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, V1, V2, Mask, DAG))
17256 return V;
17258 // Use dedicated pack instructions for masks that match their pattern.
17259 if (SDValue V =
17260 lowerShuffleWithPACK(DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
17261 return V;
17263 // Try to use shift instructions.
17264 if (SDValue Shift =
17265 lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
17266 Subtarget, DAG, /*BitwiseOnly*/ false))
17267 return Shift;
17269 // Try to use byte rotation instructions.
17270 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
17271 Subtarget, DAG))
17272 return Rotate;
17274 if (V2.isUndef()) {
17275 // Try to use bit rotation instructions.
17276 if (SDValue Rotate =
17277 lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
17278 return Rotate;
17280 SmallVector<int, 8> RepeatedMask;
17281 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
17282 // As this is a single-input shuffle, the repeated mask should be
17283 // a strictly valid v8i16 mask that we can pass through to the v8i16
17284 // lowering to handle even the v32 case.
17285 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
17286 RepeatedMask, Subtarget, DAG);
17290 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
17291 Zeroable, Subtarget, DAG))
17292 return Blend;
17294 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
17295 Zeroable, Subtarget, DAG))
17296 return PSHUFB;
17298 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
17301 /// Handle lowering of 64-lane 8-bit integer shuffles.
17302 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17303 const APInt &Zeroable, SDValue V1, SDValue V2,
17304 const X86Subtarget &Subtarget,
17305 SelectionDAG &DAG) {
17306 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17307 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17308 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
17309 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
17311 // Whenever we can lower this as a zext, that instruction is strictly faster
17312 // than any alternative. It also allows us to fold memory operands into the
17313 // shuffle in many cases.
17314 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17315 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
17316 return ZExt;
17318 // Use dedicated unpack instructions for masks that match their pattern.
17319 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, V1, V2, Mask, DAG))
17320 return V;
17322 // Use dedicated pack instructions for masks that match their pattern.
17323 if (SDValue V =
17324 lowerShuffleWithPACK(DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17325 return V;
17327 // Try to use shift instructions.
17328 if (SDValue Shift =
17329 lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
17330 DAG, /*BitwiseOnly*/ false))
17331 return Shift;
17333 // Try to use byte rotation instructions.
17334 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
17335 Subtarget, DAG))
17336 return Rotate;
17338 // Try to use bit rotation instructions.
17339 if (V2.isUndef())
17340 if (SDValue Rotate =
17341 lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
17342 return Rotate;
17344 // Lower as AND if possible.
17345 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
17346 Zeroable, Subtarget, DAG))
17347 return Masked;
17349 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
17350 Zeroable, Subtarget, DAG))
17351 return PSHUFB;
17353 // Try to create an in-lane repeating shuffle mask and then shuffle the
17354 // results into the target lanes.
17355 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17356 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17357 return V;
17359 if (SDValue Result = lowerShuffleAsLanePermuteAndPermute(
17360 DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
17361 return Result;
17363 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
17364 Zeroable, Subtarget, DAG))
17365 return Blend;
17367 if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
17368 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
17369 // PALIGNR will be cheaper than the second PSHUFB+OR.
17370 if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
17371 Mask, Subtarget, DAG))
17372 return V;
17374 // If we can't directly blend but can use PSHUFB, that will be better as it
17375 // can both shuffle and set up the inefficient blend.
17376 bool V1InUse, V2InUse;
17377 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
17378 DAG, V1InUse, V2InUse);
17381 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17382 // shuffle.
17383 if (!V2.isUndef())
17384 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17385 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17386 return Result;
17388 // VBMI can use VPERMV/VPERMV3 byte shuffles.
17389 if (Subtarget.hasVBMI())
17390 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
17392 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17395 /// High-level routine to lower various 512-bit x86 vector shuffles.
17397 /// This routine either breaks down the specific type of a 512-bit x86 vector
17398 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
17399 /// together based on the available instructions.
17400 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17401 MVT VT, SDValue V1, SDValue V2,
17402 const APInt &Zeroable,
17403 const X86Subtarget &Subtarget,
17404 SelectionDAG &DAG) {
17405 assert(Subtarget.hasAVX512() &&
17406 "Cannot lower 512-bit vectors w/ basic ISA!");
17408 // If we have a single input to the zero element, insert that into V1 if we
17409 // can do so cheaply.
17410 int NumElts = Mask.size();
17411 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17413 if (NumV2Elements == 1 && Mask[0] >= NumElts)
17414 if (SDValue Insertion = lowerShuffleAsElementInsertion(
17415 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17416 return Insertion;
17418 // Handle special cases where the lower or upper half is UNDEF.
17419 if (SDValue V =
17420 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17421 return V;
17423 // Check for being able to broadcast a single element.
17424 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
17425 Subtarget, DAG))
17426 return Broadcast;
17428 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
17429 // Try using bit ops for masking and blending before falling back to
17430 // splitting.
17431 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17432 Subtarget, DAG))
17433 return V;
17434 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17435 return V;
17437 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17440 if (VT == MVT::v32f16 || VT == MVT::v32bf16) {
17441 if (!Subtarget.hasBWI())
17442 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
17443 /*SimpleOnly*/ false);
17445 V1 = DAG.getBitcast(MVT::v32i16, V1);
17446 V2 = DAG.getBitcast(MVT::v32i16, V2);
17447 return DAG.getBitcast(VT,
17448 DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
17451 // Dispatch to each element type for lowering. If we don't have support for
17452 // specific element type shuffles at 512 bits, immediately split them and
17453 // lower them. Each lowering routine of a given type is allowed to assume that
17454 // the requisite ISA extensions for that element type are available.
17455 switch (VT.SimpleTy) {
17456 case MVT::v8f64:
17457 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17458 case MVT::v16f32:
17459 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17460 case MVT::v8i64:
17461 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17462 case MVT::v16i32:
17463 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17464 case MVT::v32i16:
17465 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17466 case MVT::v64i8:
17467 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17469 default:
17470 llvm_unreachable("Not a valid 512-bit x86 vector type!");
17474 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
17475 MVT VT, SDValue V1, SDValue V2,
17476 const X86Subtarget &Subtarget,
17477 SelectionDAG &DAG) {
17478 // Shuffle should be unary.
17479 if (!V2.isUndef())
17480 return SDValue();
17482 int ShiftAmt = -1;
17483 int NumElts = Mask.size();
17484 for (int i = 0; i != NumElts; ++i) {
17485 int M = Mask[i];
17486 assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
17487 "Unexpected mask index.");
17488 if (M < 0)
17489 continue;
17491 // The first non-undef element determines our shift amount.
17492 if (ShiftAmt < 0) {
17493 ShiftAmt = M - i;
17494 // Need to be shifting right.
17495 if (ShiftAmt <= 0)
17496 return SDValue();
17498 // All non-undef elements must shift by the same amount.
17499 if (ShiftAmt != M - i)
17500 return SDValue();
17502 assert(ShiftAmt >= 0 && "All undef?");
17504 // Great we found a shift right.
17505 SDValue Res = widenMaskVector(V1, false, Subtarget, DAG, DL);
17506 Res = DAG.getNode(X86ISD::KSHIFTR, DL, Res.getValueType(), Res,
17507 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17508 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17509 DAG.getIntPtrConstant(0, DL));
17512 // Determine if this shuffle can be implemented with a KSHIFT instruction.
17513 // Returns the shift amount if possible or -1 if not. This is a simplified
17514 // version of matchShuffleAsShift.
17515 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
17516 int MaskOffset, const APInt &Zeroable) {
17517 int Size = Mask.size();
17519 auto CheckZeros = [&](int Shift, bool Left) {
17520 for (int j = 0; j < Shift; ++j)
17521 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
17522 return false;
17524 return true;
17527 auto MatchShift = [&](int Shift, bool Left) {
17528 unsigned Pos = Left ? Shift : 0;
17529 unsigned Low = Left ? 0 : Shift;
17530 unsigned Len = Size - Shift;
17531 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
17534 for (int Shift = 1; Shift != Size; ++Shift)
17535 for (bool Left : {true, false})
17536 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
17537 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
17538 return Shift;
17541 return -1;
17545 // Lower vXi1 vector shuffles.
17546 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
17547 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
17548 // vector, shuffle and then truncate it back.
17549 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17550 MVT VT, SDValue V1, SDValue V2,
17551 const APInt &Zeroable,
17552 const X86Subtarget &Subtarget,
17553 SelectionDAG &DAG) {
17554 assert(Subtarget.hasAVX512() &&
17555 "Cannot lower 512-bit vectors w/o basic ISA!");
17557 int NumElts = Mask.size();
17558 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17560 // Try to recognize shuffles that are just padding a subvector with zeros.
17561 int SubvecElts = 0;
17562 int Src = -1;
17563 for (int i = 0; i != NumElts; ++i) {
17564 if (Mask[i] >= 0) {
17565 // Grab the source from the first valid mask. All subsequent elements need
17566 // to use this same source.
17567 if (Src < 0)
17568 Src = Mask[i] / NumElts;
17569 if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
17570 break;
17573 ++SubvecElts;
17575 assert(SubvecElts != NumElts && "Identity shuffle?");
17577 // Clip to a power 2.
17578 SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
17580 // Make sure the number of zeroable bits in the top at least covers the bits
17581 // not covered by the subvector.
17582 if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
17583 assert(Src >= 0 && "Expected a source!");
17584 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
17585 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
17586 Src == 0 ? V1 : V2,
17587 DAG.getIntPtrConstant(0, DL));
17588 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17589 DAG.getConstant(0, DL, VT),
17590 Extract, DAG.getIntPtrConstant(0, DL));
17593 // Try a simple shift right with undef elements. Later we'll try with zeros.
17594 if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
17595 DAG))
17596 return Shift;
17598 // Try to match KSHIFTs.
17599 unsigned Offset = 0;
17600 for (SDValue V : { V1, V2 }) {
17601 unsigned Opcode;
17602 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
17603 if (ShiftAmt >= 0) {
17604 SDValue Res = widenMaskVector(V, false, Subtarget, DAG, DL);
17605 MVT WideVT = Res.getSimpleValueType();
17606 // Widened right shifts need two shifts to ensure we shift in zeroes.
17607 if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
17608 int WideElts = WideVT.getVectorNumElements();
17609 // Shift left to put the original vector in the MSBs of the new size.
17610 Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
17611 DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
17612 // Increase the shift amount to account for the left shift.
17613 ShiftAmt += WideElts - NumElts;
17616 Res = DAG.getNode(Opcode, DL, WideVT, Res,
17617 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17618 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17619 DAG.getIntPtrConstant(0, DL));
17621 Offset += NumElts; // Increment for next iteration.
17624 // If we're performing an unary shuffle on a SETCC result, try to shuffle the
17625 // ops instead.
17626 // TODO: What other unary shuffles would benefit from this?
17627 if (NumV2Elements == 0 && V1.getOpcode() == ISD::SETCC && V1->hasOneUse()) {
17628 SDValue Op0 = V1.getOperand(0);
17629 SDValue Op1 = V1.getOperand(1);
17630 ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
17631 EVT OpVT = Op0.getValueType();
17632 if (OpVT.getScalarSizeInBits() >= 32 || isBroadcastShuffleMask(Mask))
17633 return DAG.getSetCC(
17634 DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
17635 DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
17638 MVT ExtVT;
17639 switch (VT.SimpleTy) {
17640 default:
17641 llvm_unreachable("Expected a vector of i1 elements");
17642 case MVT::v2i1:
17643 ExtVT = MVT::v2i64;
17644 break;
17645 case MVT::v4i1:
17646 ExtVT = MVT::v4i32;
17647 break;
17648 case MVT::v8i1:
17649 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
17650 // shuffle.
17651 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
17652 break;
17653 case MVT::v16i1:
17654 // Take 512-bit type, unless we are avoiding 512-bit types and have the
17655 // 256-bit operation available.
17656 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
17657 break;
17658 case MVT::v32i1:
17659 // Take 512-bit type, unless we are avoiding 512-bit types and have the
17660 // 256-bit operation available.
17661 assert(Subtarget.hasBWI() && "Expected AVX512BW support");
17662 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
17663 break;
17664 case MVT::v64i1:
17665 // Fall back to scalarization. FIXME: We can do better if the shuffle
17666 // can be partitioned cleanly.
17667 if (!Subtarget.useBWIRegs())
17668 return SDValue();
17669 ExtVT = MVT::v64i8;
17670 break;
17673 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
17674 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
17676 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
17677 // i1 was sign extended we can use X86ISD::CVT2MASK.
17678 int NumElems = VT.getVectorNumElements();
17679 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
17680 (Subtarget.hasDQI() && (NumElems < 32)))
17681 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
17682 Shuffle, ISD::SETGT);
17684 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
17687 /// Helper function that returns true if the shuffle mask should be
17688 /// commuted to improve canonicalization.
17689 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
17690 int NumElements = Mask.size();
17692 int NumV1Elements = 0, NumV2Elements = 0;
17693 for (int M : Mask)
17694 if (M < 0)
17695 continue;
17696 else if (M < NumElements)
17697 ++NumV1Elements;
17698 else
17699 ++NumV2Elements;
17701 // Commute the shuffle as needed such that more elements come from V1 than
17702 // V2. This allows us to match the shuffle pattern strictly on how many
17703 // elements come from V1 without handling the symmetric cases.
17704 if (NumV2Elements > NumV1Elements)
17705 return true;
17707 assert(NumV1Elements > 0 && "No V1 indices");
17709 if (NumV2Elements == 0)
17710 return false;
17712 // When the number of V1 and V2 elements are the same, try to minimize the
17713 // number of uses of V2 in the low half of the vector. When that is tied,
17714 // ensure that the sum of indices for V1 is equal to or lower than the sum
17715 // indices for V2. When those are equal, try to ensure that the number of odd
17716 // indices for V1 is lower than the number of odd indices for V2.
17717 if (NumV1Elements == NumV2Elements) {
17718 int LowV1Elements = 0, LowV2Elements = 0;
17719 for (int M : Mask.slice(0, NumElements / 2))
17720 if (M >= NumElements)
17721 ++LowV2Elements;
17722 else if (M >= 0)
17723 ++LowV1Elements;
17724 if (LowV2Elements > LowV1Elements)
17725 return true;
17726 if (LowV2Elements == LowV1Elements) {
17727 int SumV1Indices = 0, SumV2Indices = 0;
17728 for (int i = 0, Size = Mask.size(); i < Size; ++i)
17729 if (Mask[i] >= NumElements)
17730 SumV2Indices += i;
17731 else if (Mask[i] >= 0)
17732 SumV1Indices += i;
17733 if (SumV2Indices < SumV1Indices)
17734 return true;
17735 if (SumV2Indices == SumV1Indices) {
17736 int NumV1OddIndices = 0, NumV2OddIndices = 0;
17737 for (int i = 0, Size = Mask.size(); i < Size; ++i)
17738 if (Mask[i] >= NumElements)
17739 NumV2OddIndices += i % 2;
17740 else if (Mask[i] >= 0)
17741 NumV1OddIndices += i % 2;
17742 if (NumV2OddIndices < NumV1OddIndices)
17743 return true;
17748 return false;
17751 static bool canCombineAsMaskOperation(SDValue V,
17752 const X86Subtarget &Subtarget) {
17753 if (!Subtarget.hasAVX512())
17754 return false;
17756 if (!V.getValueType().isSimple())
17757 return false;
17759 MVT VT = V.getSimpleValueType().getScalarType();
17760 if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
17761 return false;
17763 // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
17764 // are preferable to blendw/blendvb/masked-mov.
17765 if ((VT == MVT::i16 || VT == MVT::i8) &&
17766 V.getSimpleValueType().getSizeInBits() < 512)
17767 return false;
17769 auto HasMaskOperation = [&](SDValue V) {
17770 // TODO: Currently we only check limited opcode. We probably extend
17771 // it to all binary operation by checking TLI.isBinOp().
17772 switch (V->getOpcode()) {
17773 default:
17774 return false;
17775 case ISD::ADD:
17776 case ISD::SUB:
17777 case ISD::AND:
17778 case ISD::XOR:
17779 case ISD::OR:
17780 case ISD::SMAX:
17781 case ISD::SMIN:
17782 case ISD::UMAX:
17783 case ISD::UMIN:
17784 case ISD::ABS:
17785 case ISD::SHL:
17786 case ISD::SRL:
17787 case ISD::SRA:
17788 case ISD::MUL:
17789 break;
17791 if (!V->hasOneUse())
17792 return false;
17794 return true;
17797 if (HasMaskOperation(V))
17798 return true;
17800 return false;
17803 // Forward declaration.
17804 static SDValue canonicalizeShuffleMaskWithHorizOp(
17805 MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
17806 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
17807 const X86Subtarget &Subtarget);
17809 /// Top-level lowering for x86 vector shuffles.
17811 /// This handles decomposition, canonicalization, and lowering of all x86
17812 /// vector shuffles. Most of the specific lowering strategies are encapsulated
17813 /// above in helper routines. The canonicalization attempts to widen shuffles
17814 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
17815 /// s.t. only one of the two inputs needs to be tested, etc.
17816 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
17817 SelectionDAG &DAG) {
17818 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
17819 ArrayRef<int> OrigMask = SVOp->getMask();
17820 SDValue V1 = Op.getOperand(0);
17821 SDValue V2 = Op.getOperand(1);
17822 MVT VT = Op.getSimpleValueType();
17823 int NumElements = VT.getVectorNumElements();
17824 SDLoc DL(Op);
17825 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
17827 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
17828 "Can't lower MMX shuffles");
17830 bool V1IsUndef = V1.isUndef();
17831 bool V2IsUndef = V2.isUndef();
17832 if (V1IsUndef && V2IsUndef)
17833 return DAG.getUNDEF(VT);
17835 // When we create a shuffle node we put the UNDEF node to second operand,
17836 // but in some cases the first operand may be transformed to UNDEF.
17837 // In this case we should just commute the node.
17838 if (V1IsUndef)
17839 return DAG.getCommutedVectorShuffle(*SVOp);
17841 // Check for non-undef masks pointing at an undef vector and make the masks
17842 // undef as well. This makes it easier to match the shuffle based solely on
17843 // the mask.
17844 if (V2IsUndef &&
17845 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
17846 SmallVector<int, 8> NewMask(OrigMask);
17847 for (int &M : NewMask)
17848 if (M >= NumElements)
17849 M = -1;
17850 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17853 // Check for illegal shuffle mask element index values.
17854 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
17855 (void)MaskUpperLimit;
17856 assert(llvm::all_of(OrigMask,
17857 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
17858 "Out of bounds shuffle index");
17860 // We actually see shuffles that are entirely re-arrangements of a set of
17861 // zero inputs. This mostly happens while decomposing complex shuffles into
17862 // simple ones. Directly lower these as a buildvector of zeros.
17863 APInt KnownUndef, KnownZero;
17864 computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
17866 APInt Zeroable = KnownUndef | KnownZero;
17867 if (Zeroable.isAllOnes())
17868 return getZeroVector(VT, Subtarget, DAG, DL);
17870 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
17872 // Try to collapse shuffles into using a vector type with fewer elements but
17873 // wider element types. We cap this to not form integers or floating point
17874 // elements wider than 64 bits. It does not seem beneficial to form i128
17875 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
17876 SmallVector<int, 16> WidenedMask;
17877 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
17878 !canCombineAsMaskOperation(V1, Subtarget) &&
17879 !canCombineAsMaskOperation(V2, Subtarget) &&
17880 canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
17881 // Shuffle mask widening should not interfere with a broadcast opportunity
17882 // by obfuscating the operands with bitcasts.
17883 // TODO: Avoid lowering directly from this top-level function: make this
17884 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
17885 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
17886 Subtarget, DAG))
17887 return Broadcast;
17889 MVT NewEltVT = VT.isFloatingPoint()
17890 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
17891 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
17892 int NewNumElts = NumElements / 2;
17893 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
17894 // Make sure that the new vector type is legal. For example, v2f64 isn't
17895 // legal on SSE1.
17896 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
17897 if (V2IsZero) {
17898 // Modify the new Mask to take all zeros from the all-zero vector.
17899 // Choose indices that are blend-friendly.
17900 bool UsedZeroVector = false;
17901 assert(is_contained(WidenedMask, SM_SentinelZero) &&
17902 "V2's non-undef elements are used?!");
17903 for (int i = 0; i != NewNumElts; ++i)
17904 if (WidenedMask[i] == SM_SentinelZero) {
17905 WidenedMask[i] = i + NewNumElts;
17906 UsedZeroVector = true;
17908 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
17909 // some elements to be undef.
17910 if (UsedZeroVector)
17911 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
17913 V1 = DAG.getBitcast(NewVT, V1);
17914 V2 = DAG.getBitcast(NewVT, V2);
17915 return DAG.getBitcast(
17916 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
17920 SmallVector<SDValue> Ops = {V1, V2};
17921 SmallVector<int> Mask(OrigMask);
17923 // Canonicalize the shuffle with any horizontal ops inputs.
17924 // NOTE: This may update Ops and Mask.
17925 if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
17926 Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
17927 return DAG.getBitcast(VT, HOp);
17929 V1 = DAG.getBitcast(VT, Ops[0]);
17930 V2 = DAG.getBitcast(VT, Ops[1]);
17931 assert(NumElements == (int)Mask.size() &&
17932 "canonicalizeShuffleMaskWithHorizOp "
17933 "shouldn't alter the shuffle mask size");
17935 // Commute the shuffle if it will improve canonicalization.
17936 if (canonicalizeShuffleMaskWithCommute(Mask)) {
17937 ShuffleVectorSDNode::commuteMask(Mask);
17938 std::swap(V1, V2);
17941 // For each vector width, delegate to a specialized lowering routine.
17942 if (VT.is128BitVector())
17943 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17945 if (VT.is256BitVector())
17946 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17948 if (VT.is512BitVector())
17949 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17951 if (Is1BitVector)
17952 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17954 llvm_unreachable("Unimplemented!");
17957 // As legal vpcompress instructions depend on various AVX512 extensions, try to
17958 // convert illegal vector sizes to legal ones to avoid expansion.
17959 static SDValue lowerVECTOR_COMPRESS(SDValue Op, const X86Subtarget &Subtarget,
17960 SelectionDAG &DAG) {
17961 assert(Subtarget.hasAVX512() &&
17962 "Need AVX512 for custom VECTOR_COMPRESS lowering.");
17964 SDLoc DL(Op);
17965 SDValue Vec = Op.getOperand(0);
17966 SDValue Mask = Op.getOperand(1);
17967 SDValue Passthru = Op.getOperand(2);
17969 EVT VecVT = Vec.getValueType();
17970 EVT ElementVT = VecVT.getVectorElementType();
17971 unsigned NumElements = VecVT.getVectorNumElements();
17972 unsigned NumVecBits = VecVT.getFixedSizeInBits();
17973 unsigned NumElementBits = ElementVT.getFixedSizeInBits();
17975 // 128- and 256-bit vectors with <= 16 elements can be converted to and
17976 // compressed as 512-bit vectors in AVX512F.
17977 if (NumVecBits != 128 && NumVecBits != 256)
17978 return SDValue();
17980 if (NumElementBits == 32 || NumElementBits == 64) {
17981 unsigned NumLargeElements = 512 / NumElementBits;
17982 MVT LargeVecVT =
17983 MVT::getVectorVT(ElementVT.getSimpleVT(), NumLargeElements);
17984 MVT LargeMaskVT = MVT::getVectorVT(MVT::i1, NumLargeElements);
17986 Vec = widenSubVector(LargeVecVT, Vec, /*ZeroNewElements=*/false, Subtarget,
17987 DAG, DL);
17988 Mask = widenSubVector(LargeMaskVT, Mask, /*ZeroNewElements=*/true,
17989 Subtarget, DAG, DL);
17990 Passthru = Passthru.isUndef() ? DAG.getUNDEF(LargeVecVT)
17991 : widenSubVector(LargeVecVT, Passthru,
17992 /*ZeroNewElements=*/false,
17993 Subtarget, DAG, DL);
17995 SDValue Compressed =
17996 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
17997 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VecVT, Compressed,
17998 DAG.getConstant(0, DL, MVT::i64));
18001 if (VecVT == MVT::v8i16 || VecVT == MVT::v8i8 || VecVT == MVT::v16i8 ||
18002 VecVT == MVT::v16i16) {
18003 MVT LageElementVT = MVT::getIntegerVT(512 / NumElements);
18004 EVT LargeVecVT = MVT::getVectorVT(LageElementVT, NumElements);
18006 Vec = DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Vec);
18007 Passthru = Passthru.isUndef()
18008 ? DAG.getUNDEF(LargeVecVT)
18009 : DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Passthru);
18011 SDValue Compressed =
18012 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18013 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Compressed);
18016 return SDValue();
18019 /// Try to lower a VSELECT instruction to a vector shuffle.
18020 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
18021 const X86Subtarget &Subtarget,
18022 SelectionDAG &DAG) {
18023 SDValue Cond = Op.getOperand(0);
18024 SDValue LHS = Op.getOperand(1);
18025 SDValue RHS = Op.getOperand(2);
18026 MVT VT = Op.getSimpleValueType();
18028 // Only non-legal VSELECTs reach this lowering, convert those into generic
18029 // shuffles and re-use the shuffle lowering path for blends.
18030 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
18031 SmallVector<int, 32> Mask;
18032 if (createShuffleMaskFromVSELECT(Mask, Cond))
18033 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18036 return SDValue();
18039 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18040 SDValue Cond = Op.getOperand(0);
18041 SDValue LHS = Op.getOperand(1);
18042 SDValue RHS = Op.getOperand(2);
18044 SDLoc dl(Op);
18045 MVT VT = Op.getSimpleValueType();
18046 if (isSoftF16(VT, Subtarget)) {
18047 MVT NVT = VT.changeVectorElementTypeToInteger();
18048 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
18049 DAG.getBitcast(NVT, LHS),
18050 DAG.getBitcast(NVT, RHS)));
18053 // A vselect where all conditions and data are constants can be optimized into
18054 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18055 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
18056 ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
18057 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
18058 return SDValue();
18060 // Try to lower this to a blend-style vector shuffle. This can handle all
18061 // constant condition cases.
18062 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18063 return BlendOp;
18065 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18066 // with patterns on the mask registers on AVX-512.
18067 MVT CondVT = Cond.getSimpleValueType();
18068 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18069 if (CondEltSize == 1)
18070 return Op;
18072 // Variable blends are only legal from SSE4.1 onward.
18073 if (!Subtarget.hasSSE41())
18074 return SDValue();
18076 unsigned EltSize = VT.getScalarSizeInBits();
18077 unsigned NumElts = VT.getVectorNumElements();
18079 // Expand v32i16/v64i8 without BWI.
18080 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18081 return SDValue();
18083 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18084 // into an i1 condition so that we can use the mask-based 512-bit blend
18085 // instructions.
18086 if (VT.getSizeInBits() == 512) {
18087 // Build a mask by testing the condition against zero.
18088 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18089 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18090 DAG.getConstant(0, dl, CondVT),
18091 ISD::SETNE);
18092 // Now return a new VSELECT using the mask.
18093 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18096 // SEXT/TRUNC cases where the mask doesn't match the destination size.
18097 if (CondEltSize != EltSize) {
18098 // If we don't have a sign splat, rely on the expansion.
18099 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18100 return SDValue();
18102 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18103 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18104 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18105 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18108 // v16i16/v32i8 selects without AVX2, if the condition and another operand
18109 // are free to split, then better to split before expanding the
18110 // select. Don't bother with XOP as it has the fast VPCMOV instruction.
18111 // TODO: This is very similar to narrowVectorSelect.
18112 // TODO: Add Load splitting to isFreeToSplitVector ?
18113 if (EltSize < 32 && VT.is256BitVector() && !Subtarget.hasAVX2() &&
18114 !Subtarget.hasXOP()) {
18115 bool FreeCond = isFreeToSplitVector(Cond.getNode(), DAG);
18116 bool FreeLHS = isFreeToSplitVector(LHS.getNode(), DAG) ||
18117 (ISD::isNormalLoad(LHS.getNode()) && LHS.hasOneUse());
18118 bool FreeRHS = isFreeToSplitVector(RHS.getNode(), DAG) ||
18119 (ISD::isNormalLoad(RHS.getNode()) && RHS.hasOneUse());
18120 if (FreeCond && (FreeLHS || FreeRHS))
18121 return splitVectorOp(Op, DAG, dl);
18124 // Only some types will be legal on some subtargets. If we can emit a legal
18125 // VSELECT-matching blend, return Op, and but if we need to expand, return
18126 // a null value.
18127 switch (VT.SimpleTy) {
18128 default:
18129 // Most of the vector types have blends past SSE4.1.
18130 return Op;
18132 case MVT::v32i8:
18133 // The byte blends for AVX vectors were introduced only in AVX2.
18134 if (Subtarget.hasAVX2())
18135 return Op;
18137 return SDValue();
18139 case MVT::v8i16:
18140 case MVT::v16i16: {
18141 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18142 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18143 Cond = DAG.getBitcast(CastVT, Cond);
18144 LHS = DAG.getBitcast(CastVT, LHS);
18145 RHS = DAG.getBitcast(CastVT, RHS);
18146 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18147 return DAG.getBitcast(VT, Select);
18152 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
18153 MVT VT = Op.getSimpleValueType();
18154 SDValue Vec = Op.getOperand(0);
18155 SDValue Idx = Op.getOperand(1);
18156 assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
18157 SDLoc dl(Op);
18159 if (!Vec.getSimpleValueType().is128BitVector())
18160 return SDValue();
18162 if (VT.getSizeInBits() == 8) {
18163 // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
18164 // we're going to zero extend the register or fold the store.
18165 if (llvm::isNullConstant(Idx) && !X86::mayFoldIntoZeroExtend(Op) &&
18166 !X86::mayFoldIntoStore(Op))
18167 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
18168 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18169 DAG.getBitcast(MVT::v4i32, Vec), Idx));
18171 unsigned IdxVal = Idx->getAsZExtVal();
18172 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
18173 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18174 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18177 if (VT == MVT::f32) {
18178 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
18179 // the result back to FR32 register. It's only worth matching if the
18180 // result has a single use which is a store or a bitcast to i32. And in
18181 // the case of a store, it's not worth it if the index is a constant 0,
18182 // because a MOVSSmr can be used instead, which is smaller and faster.
18183 if (!Op.hasOneUse())
18184 return SDValue();
18185 SDNode *User = *Op.getNode()->use_begin();
18186 if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
18187 (User->getOpcode() != ISD::BITCAST ||
18188 User->getValueType(0) != MVT::i32))
18189 return SDValue();
18190 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18191 DAG.getBitcast(MVT::v4i32, Vec), Idx);
18192 return DAG.getBitcast(MVT::f32, Extract);
18195 if (VT == MVT::i32 || VT == MVT::i64)
18196 return Op;
18198 return SDValue();
18201 /// Extract one bit from mask vector, like v16i1 or v8i1.
18202 /// AVX-512 feature.
18203 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
18204 const X86Subtarget &Subtarget) {
18205 SDValue Vec = Op.getOperand(0);
18206 SDLoc dl(Vec);
18207 MVT VecVT = Vec.getSimpleValueType();
18208 SDValue Idx = Op.getOperand(1);
18209 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18210 MVT EltVT = Op.getSimpleValueType();
18212 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
18213 "Unexpected vector type in ExtractBitFromMaskVector");
18215 // variable index can't be handled in mask registers,
18216 // extend vector to VR512/128
18217 if (!IdxC) {
18218 unsigned NumElts = VecVT.getVectorNumElements();
18219 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
18220 // than extending to 128/256bit.
18221 if (NumElts == 1) {
18222 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
18223 MVT IntVT = MVT::getIntegerVT(Vec.getValueType().getVectorNumElements());
18224 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, DAG.getBitcast(IntVT, Vec));
18226 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18227 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18228 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
18229 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
18230 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
18233 unsigned IdxVal = IdxC->getZExtValue();
18234 if (IdxVal == 0) // the operation is legal
18235 return Op;
18237 // Extend to natively supported kshift.
18238 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
18240 // Use kshiftr instruction to move to the lower element.
18241 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
18242 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18244 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18245 DAG.getIntPtrConstant(0, dl));
18248 // Helper to find all the extracted elements from a vector.
18249 static APInt getExtractedDemandedElts(SDNode *N) {
18250 MVT VT = N->getSimpleValueType(0);
18251 unsigned NumElts = VT.getVectorNumElements();
18252 APInt DemandedElts = APInt::getZero(NumElts);
18253 for (SDNode *User : N->uses()) {
18254 switch (User->getOpcode()) {
18255 case X86ISD::PEXTRB:
18256 case X86ISD::PEXTRW:
18257 case ISD::EXTRACT_VECTOR_ELT:
18258 if (!isa<ConstantSDNode>(User->getOperand(1))) {
18259 DemandedElts.setAllBits();
18260 return DemandedElts;
18262 DemandedElts.setBit(User->getConstantOperandVal(1));
18263 break;
18264 case ISD::BITCAST: {
18265 if (!User->getValueType(0).isSimple() ||
18266 !User->getValueType(0).isVector()) {
18267 DemandedElts.setAllBits();
18268 return DemandedElts;
18270 APInt DemandedSrcElts = getExtractedDemandedElts(User);
18271 DemandedElts |= APIntOps::ScaleBitMask(DemandedSrcElts, NumElts);
18272 break;
18274 default:
18275 DemandedElts.setAllBits();
18276 return DemandedElts;
18279 return DemandedElts;
18282 SDValue
18283 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
18284 SelectionDAG &DAG) const {
18285 SDLoc dl(Op);
18286 SDValue Vec = Op.getOperand(0);
18287 MVT VecVT = Vec.getSimpleValueType();
18288 SDValue Idx = Op.getOperand(1);
18289 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18291 if (VecVT.getVectorElementType() == MVT::i1)
18292 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
18294 if (!IdxC) {
18295 // Its more profitable to go through memory (1 cycles throughput)
18296 // than using VMOVD + VPERMV/PSHUFB sequence (2/3 cycles throughput)
18297 // IACA tool was used to get performance estimation
18298 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
18300 // example : extractelement <16 x i8> %a, i32 %i
18302 // Block Throughput: 3.00 Cycles
18303 // Throughput Bottleneck: Port5
18305 // | Num Of | Ports pressure in cycles | |
18306 // | Uops | 0 - DV | 5 | 6 | 7 | |
18307 // ---------------------------------------------
18308 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
18309 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
18310 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
18311 // Total Num Of Uops: 4
18314 // Block Throughput: 1.00 Cycles
18315 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
18317 // | | Ports pressure in cycles | |
18318 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
18319 // ---------------------------------------------------------
18320 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
18321 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
18322 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
18323 // Total Num Of Uops: 4
18325 return SDValue();
18328 unsigned IdxVal = IdxC->getZExtValue();
18330 // If this is a 256-bit vector result, first extract the 128-bit vector and
18331 // then extract the element from the 128-bit vector.
18332 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
18333 // Get the 128-bit vector.
18334 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
18335 MVT EltVT = VecVT.getVectorElementType();
18337 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
18338 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
18340 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
18341 // this can be done with a mask.
18342 IdxVal &= ElemsPerChunk - 1;
18343 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18344 DAG.getIntPtrConstant(IdxVal, dl));
18347 assert(VecVT.is128BitVector() && "Unexpected vector length");
18349 MVT VT = Op.getSimpleValueType();
18351 if (VT == MVT::i16) {
18352 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
18353 // we're going to zero extend the register or fold the store (SSE41 only).
18354 if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
18355 !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
18356 if (Subtarget.hasFP16())
18357 return Op;
18359 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
18360 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18361 DAG.getBitcast(MVT::v4i32, Vec), Idx));
18364 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
18365 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18366 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18369 if (Subtarget.hasSSE41())
18370 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
18371 return Res;
18373 // Only extract a single element from a v16i8 source - determine the common
18374 // DWORD/WORD that all extractions share, and extract the sub-byte.
18375 // TODO: Add QWORD MOVQ extraction?
18376 if (VT == MVT::i8) {
18377 APInt DemandedElts = getExtractedDemandedElts(Vec.getNode());
18378 assert(DemandedElts.getBitWidth() == 16 && "Vector width mismatch");
18380 // Extract either the lowest i32 or any i16, and extract the sub-byte.
18381 int DWordIdx = IdxVal / 4;
18382 if (DWordIdx == 0 && DemandedElts == (DemandedElts & 15)) {
18383 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18384 DAG.getBitcast(MVT::v4i32, Vec),
18385 DAG.getIntPtrConstant(DWordIdx, dl));
18386 int ShiftVal = (IdxVal % 4) * 8;
18387 if (ShiftVal != 0)
18388 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
18389 DAG.getConstant(ShiftVal, dl, MVT::i8));
18390 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18393 int WordIdx = IdxVal / 2;
18394 if (DemandedElts == (DemandedElts & (3 << (WordIdx * 2)))) {
18395 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
18396 DAG.getBitcast(MVT::v8i16, Vec),
18397 DAG.getIntPtrConstant(WordIdx, dl));
18398 int ShiftVal = (IdxVal % 2) * 8;
18399 if (ShiftVal != 0)
18400 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
18401 DAG.getConstant(ShiftVal, dl, MVT::i8));
18402 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18406 if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
18407 if (IdxVal == 0)
18408 return Op;
18410 // Shuffle the element to the lowest element, then movss or movsh.
18411 SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
18412 Mask[0] = static_cast<int>(IdxVal);
18413 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18414 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18415 DAG.getIntPtrConstant(0, dl));
18418 if (VT.getSizeInBits() == 64) {
18419 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
18420 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
18421 // to match extract_elt for f64.
18422 if (IdxVal == 0)
18423 return Op;
18425 // UNPCKHPD the element to the lowest double word, then movsd.
18426 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
18427 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
18428 int Mask[2] = { 1, -1 };
18429 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18430 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18431 DAG.getIntPtrConstant(0, dl));
18434 return SDValue();
18437 /// Insert one bit to mask vector, like v16i1 or v8i1.
18438 /// AVX-512 feature.
18439 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
18440 const X86Subtarget &Subtarget) {
18441 SDLoc dl(Op);
18442 SDValue Vec = Op.getOperand(0);
18443 SDValue Elt = Op.getOperand(1);
18444 SDValue Idx = Op.getOperand(2);
18445 MVT VecVT = Vec.getSimpleValueType();
18447 if (!isa<ConstantSDNode>(Idx)) {
18448 // Non constant index. Extend source and destination,
18449 // insert element and then truncate the result.
18450 unsigned NumElts = VecVT.getVectorNumElements();
18451 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18452 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18453 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
18454 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
18455 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
18456 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
18459 // Copy into a k-register, extract to v1i1 and insert_subvector.
18460 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
18461 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
18464 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
18465 SelectionDAG &DAG) const {
18466 MVT VT = Op.getSimpleValueType();
18467 MVT EltVT = VT.getVectorElementType();
18468 unsigned NumElts = VT.getVectorNumElements();
18469 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
18471 if (EltVT == MVT::i1)
18472 return InsertBitToMaskVector(Op, DAG, Subtarget);
18474 SDLoc dl(Op);
18475 SDValue N0 = Op.getOperand(0);
18476 SDValue N1 = Op.getOperand(1);
18477 SDValue N2 = Op.getOperand(2);
18478 auto *N2C = dyn_cast<ConstantSDNode>(N2);
18480 if (EltVT == MVT::bf16) {
18481 MVT IVT = VT.changeVectorElementTypeToInteger();
18482 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVT,
18483 DAG.getBitcast(IVT, N0),
18484 DAG.getBitcast(MVT::i16, N1), N2);
18485 return DAG.getBitcast(VT, Res);
18488 if (!N2C) {
18489 // Variable insertion indices, usually we're better off spilling to stack,
18490 // but AVX512 can use a variable compare+select by comparing against all
18491 // possible vector indices, and FP insertion has less gpr->simd traffic.
18492 if (!(Subtarget.hasBWI() ||
18493 (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
18494 (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
18495 return SDValue();
18497 MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
18498 MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
18499 if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
18500 return SDValue();
18502 SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
18503 SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
18504 SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
18506 SmallVector<SDValue, 16> RawIndices;
18507 for (unsigned I = 0; I != NumElts; ++I)
18508 RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
18509 SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
18511 // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
18512 return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
18513 ISD::CondCode::SETEQ);
18516 if (N2C->getAPIntValue().uge(NumElts))
18517 return SDValue();
18518 uint64_t IdxVal = N2C->getZExtValue();
18520 bool IsZeroElt = X86::isZeroNode(N1);
18521 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
18523 if (IsZeroElt || IsAllOnesElt) {
18524 // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
18525 // We don't deal with i8 0 since it appears to be handled elsewhere.
18526 if (IsAllOnesElt &&
18527 ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
18528 ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
18529 SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
18530 SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
18531 SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
18532 CstVectorElts[IdxVal] = OnesCst;
18533 SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
18534 return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
18536 // See if we can do this more efficiently with a blend shuffle with a
18537 // rematerializable vector.
18538 if (Subtarget.hasSSE41() &&
18539 (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
18540 SmallVector<int, 8> BlendMask;
18541 for (unsigned i = 0; i != NumElts; ++i)
18542 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18543 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
18544 : getOnesVector(VT, DAG, dl);
18545 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
18549 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
18550 // into that, and then insert the subvector back into the result.
18551 if (VT.is256BitVector() || VT.is512BitVector()) {
18552 // With a 256-bit vector, we can insert into the zero element efficiently
18553 // using a blend if we have AVX or AVX2 and the right data type.
18554 if (VT.is256BitVector() && IdxVal == 0) {
18555 // TODO: It is worthwhile to cast integer to floating point and back
18556 // and incur a domain crossing penalty if that's what we'll end up
18557 // doing anyway after extracting to a 128-bit vector.
18558 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
18559 (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
18560 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18561 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
18562 DAG.getTargetConstant(1, dl, MVT::i8));
18566 unsigned NumEltsIn128 = 128 / EltSizeInBits;
18567 assert(isPowerOf2_32(NumEltsIn128) &&
18568 "Vectors will always have power-of-two number of elements.");
18570 // If we are not inserting into the low 128-bit vector chunk,
18571 // then prefer the broadcast+blend sequence.
18572 // FIXME: relax the profitability check iff all N1 uses are insertions.
18573 if (IdxVal >= NumEltsIn128 &&
18574 ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
18575 (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
18576 X86::mayFoldLoad(N1, Subtarget)))) {
18577 SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
18578 SmallVector<int, 8> BlendMask;
18579 for (unsigned i = 0; i != NumElts; ++i)
18580 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18581 return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
18584 // Get the desired 128-bit vector chunk.
18585 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
18587 // Insert the element into the desired chunk.
18588 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
18589 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
18591 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
18592 DAG.getIntPtrConstant(IdxIn128, dl));
18594 // Insert the changed part back into the bigger vector
18595 return insert128BitVector(N0, V, IdxVal, DAG, dl);
18597 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
18599 // This will be just movw/movd/movq/movsh/movss/movsd.
18600 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
18601 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
18602 EltVT == MVT::f16 || EltVT == MVT::i64) {
18603 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18604 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18607 // We can't directly insert an i8 or i16 into a vector, so zero extend
18608 // it to i32 first.
18609 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
18610 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
18611 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
18612 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
18613 N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18614 return DAG.getBitcast(VT, N1);
18618 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
18619 // argument. SSE41 required for pinsrb.
18620 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
18621 unsigned Opc;
18622 if (VT == MVT::v8i16) {
18623 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
18624 Opc = X86ISD::PINSRW;
18625 } else {
18626 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
18627 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
18628 Opc = X86ISD::PINSRB;
18631 assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
18632 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
18633 N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
18634 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
18637 if (Subtarget.hasSSE41()) {
18638 if (EltVT == MVT::f32) {
18639 // Bits [7:6] of the constant are the source select. This will always be
18640 // zero here. The DAG Combiner may combine an extract_elt index into
18641 // these bits. For example (insert (extract, 3), 2) could be matched by
18642 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
18643 // Bits [5:4] of the constant are the destination select. This is the
18644 // value of the incoming immediate.
18645 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
18646 // combine either bitwise AND or insert of float 0.0 to set these bits.
18648 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
18649 if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
18650 // If this is an insertion of 32-bits into the low 32-bits of
18651 // a vector, we prefer to generate a blend with immediate rather
18652 // than an insertps. Blends are simpler operations in hardware and so
18653 // will always have equal or better performance than insertps.
18654 // But if optimizing for size and there's a load folding opportunity,
18655 // generate insertps because blendps does not have a 32-bit memory
18656 // operand form.
18657 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18658 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
18659 DAG.getTargetConstant(1, dl, MVT::i8));
18661 // Create this as a scalar to vector..
18662 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18663 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
18664 DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
18667 // PINSR* works with constant index.
18668 if (EltVT == MVT::i32 || EltVT == MVT::i64)
18669 return Op;
18672 return SDValue();
18675 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
18676 SelectionDAG &DAG) {
18677 SDLoc dl(Op);
18678 MVT OpVT = Op.getSimpleValueType();
18680 // It's always cheaper to replace a xor+movd with xorps and simplifies further
18681 // combines.
18682 if (X86::isZeroNode(Op.getOperand(0)))
18683 return getZeroVector(OpVT, Subtarget, DAG, dl);
18685 // If this is a 256-bit vector result, first insert into a 128-bit
18686 // vector and then insert into the 256-bit vector.
18687 if (!OpVT.is128BitVector()) {
18688 // Insert into a 128-bit vector.
18689 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
18690 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
18691 OpVT.getVectorNumElements() / SizeFactor);
18693 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
18695 // Insert the 128-bit vector.
18696 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
18698 assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
18699 "Expected an SSE type!");
18701 // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
18702 // tblgen.
18703 if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
18704 return Op;
18706 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
18707 return DAG.getBitcast(
18708 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
18711 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
18712 // simple superregister reference or explicit instructions to insert
18713 // the upper bits of a vector.
18714 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18715 SelectionDAG &DAG) {
18716 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
18718 return insert1BitVector(Op, DAG, Subtarget);
18721 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18722 SelectionDAG &DAG) {
18723 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
18724 "Only vXi1 extract_subvectors need custom lowering");
18726 SDLoc dl(Op);
18727 SDValue Vec = Op.getOperand(0);
18728 uint64_t IdxVal = Op.getConstantOperandVal(1);
18730 if (IdxVal == 0) // the operation is legal
18731 return Op;
18733 // Extend to natively supported kshift.
18734 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
18736 // Shift to the LSB.
18737 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
18738 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18740 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
18741 DAG.getIntPtrConstant(0, dl));
18744 // Returns the appropriate wrapper opcode for a global reference.
18745 unsigned X86TargetLowering::getGlobalWrapperKind(
18746 const GlobalValue *GV, const unsigned char OpFlags) const {
18747 // References to absolute symbols are never PC-relative.
18748 if (GV && GV->isAbsoluteSymbolRef())
18749 return X86ISD::Wrapper;
18751 // The following OpFlags under RIP-rel PIC use RIP.
18752 if (Subtarget.isPICStyleRIPRel() &&
18753 (OpFlags == X86II::MO_NO_FLAG || OpFlags == X86II::MO_COFFSTUB ||
18754 OpFlags == X86II::MO_DLLIMPORT))
18755 return X86ISD::WrapperRIP;
18757 // GOTPCREL references must always use RIP.
18758 if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
18759 return X86ISD::WrapperRIP;
18761 return X86ISD::Wrapper;
18764 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
18765 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
18766 // one of the above mentioned nodes. It has to be wrapped because otherwise
18767 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
18768 // be used to form addressing mode. These wrapped nodes will be selected
18769 // into MOV32ri.
18770 SDValue
18771 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
18772 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
18774 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18775 // global base reg.
18776 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18778 auto PtrVT = getPointerTy(DAG.getDataLayout());
18779 SDValue Result = DAG.getTargetConstantPool(
18780 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
18781 SDLoc DL(CP);
18782 Result =
18783 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
18784 // With PIC, the address is actually $g + Offset.
18785 if (OpFlag) {
18786 Result =
18787 DAG.getNode(ISD::ADD, DL, PtrVT,
18788 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18791 return Result;
18794 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
18795 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
18797 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18798 // global base reg.
18799 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18801 auto PtrVT = getPointerTy(DAG.getDataLayout());
18802 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
18803 SDLoc DL(JT);
18804 Result =
18805 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
18807 // With PIC, the address is actually $g + Offset.
18808 if (OpFlag)
18809 Result =
18810 DAG.getNode(ISD::ADD, DL, PtrVT,
18811 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18813 return Result;
18816 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
18817 SelectionDAG &DAG) const {
18818 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18821 SDValue
18822 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
18823 // Create the TargetBlockAddressAddress node.
18824 unsigned char OpFlags =
18825 Subtarget.classifyBlockAddressReference();
18826 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
18827 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
18828 SDLoc dl(Op);
18829 auto PtrVT = getPointerTy(DAG.getDataLayout());
18830 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
18831 Result =
18832 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlags), dl, PtrVT, Result);
18834 // With PIC, the address is actually $g + Offset.
18835 if (isGlobalRelativeToPICBase(OpFlags)) {
18836 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18837 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18840 return Result;
18843 /// Creates target global address or external symbol nodes for calls or
18844 /// other uses.
18845 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
18846 bool ForCall) const {
18847 // Unpack the global address or external symbol.
18848 SDLoc dl(Op);
18849 const GlobalValue *GV = nullptr;
18850 int64_t Offset = 0;
18851 const char *ExternalSym = nullptr;
18852 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
18853 GV = G->getGlobal();
18854 Offset = G->getOffset();
18855 } else {
18856 const auto *ES = cast<ExternalSymbolSDNode>(Op);
18857 ExternalSym = ES->getSymbol();
18860 // Calculate some flags for address lowering.
18861 const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
18862 unsigned char OpFlags;
18863 if (ForCall)
18864 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
18865 else
18866 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
18867 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
18868 bool NeedsLoad = isGlobalStubReference(OpFlags);
18870 CodeModel::Model M = DAG.getTarget().getCodeModel();
18871 auto PtrVT = getPointerTy(DAG.getDataLayout());
18872 SDValue Result;
18874 if (GV) {
18875 // Create a target global address if this is a global. If possible, fold the
18876 // offset into the global address reference. Otherwise, ADD it on later.
18877 // Suppress the folding if Offset is negative: movl foo-1, %eax is not
18878 // allowed because if the address of foo is 0, the ELF R_X86_64_32
18879 // relocation will compute to a negative value, which is invalid.
18880 int64_t GlobalOffset = 0;
18881 if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
18882 X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
18883 std::swap(GlobalOffset, Offset);
18885 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
18886 } else {
18887 // If this is not a global address, this must be an external symbol.
18888 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
18891 // If this is a direct call, avoid the wrapper if we don't need to do any
18892 // loads or adds. This allows SDAG ISel to match direct calls.
18893 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
18894 return Result;
18896 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
18898 // With PIC, the address is actually $g + Offset.
18899 if (HasPICReg) {
18900 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18901 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18904 // For globals that require a load from a stub to get the address, emit the
18905 // load.
18906 if (NeedsLoad)
18907 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
18908 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18910 // If there was a non-zero offset that we didn't fold, create an explicit
18911 // addition for it.
18912 if (Offset != 0)
18913 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
18914 DAG.getSignedConstant(Offset, dl, PtrVT));
18916 return Result;
18919 SDValue
18920 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
18921 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18924 static SDValue GetTLSADDR(SelectionDAG &DAG, GlobalAddressSDNode *GA,
18925 const EVT PtrVT, unsigned ReturnReg,
18926 unsigned char OperandFlags,
18927 bool LoadGlobalBaseReg = false,
18928 bool LocalDynamic = false) {
18929 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18930 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18931 SDLoc dl(GA);
18932 SDValue TGA;
18933 bool UseTLSDESC = DAG.getTarget().useTLSDESC();
18934 SDValue Chain = DAG.getEntryNode();
18935 SDValue Ret;
18936 if (LocalDynamic && UseTLSDESC) {
18937 TGA = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, OperandFlags);
18938 auto UI = TGA->use_begin();
18939 // Reuse existing GetTLSADDR node if we can find it.
18940 if (UI != TGA->use_end()) {
18941 // TLSDESC uses TGA.
18942 auto TLSDescOp = UI;
18943 assert(TLSDescOp->getOpcode() == X86ISD::TLSDESC &&
18944 "Unexpected TLSDESC DAG");
18945 // CALLSEQ_END uses TGA via a chain and glue.
18946 auto *CallSeqEndOp = TLSDescOp->getGluedUser();
18947 assert(CallSeqEndOp && CallSeqEndOp->getOpcode() == ISD::CALLSEQ_END &&
18948 "Unexpected TLSDESC DAG");
18949 // CopyFromReg uses CALLSEQ_END via a chain and glue.
18950 auto *CopyFromRegOp = CallSeqEndOp->getGluedUser();
18951 assert(CopyFromRegOp && CopyFromRegOp->getOpcode() == ISD::CopyFromReg &&
18952 "Unexpected TLSDESC DAG");
18953 Ret = SDValue(CopyFromRegOp, 0);
18955 } else {
18956 TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
18957 GA->getOffset(), OperandFlags);
18960 if (!Ret) {
18961 X86ISD::NodeType CallType = UseTLSDESC ? X86ISD::TLSDESC
18962 : LocalDynamic ? X86ISD::TLSBASEADDR
18963 : X86ISD::TLSADDR;
18965 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
18966 if (LoadGlobalBaseReg) {
18967 SDValue InGlue;
18968 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
18969 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT),
18970 InGlue);
18971 InGlue = Chain.getValue(1);
18972 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA, InGlue});
18973 } else {
18974 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA});
18976 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), dl);
18978 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
18979 MFI.setHasCalls(true);
18981 SDValue Glue = Chain.getValue(1);
18982 Ret = DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
18985 if (!UseTLSDESC)
18986 return Ret;
18988 const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
18989 unsigned Seg = Subtarget.is64Bit() ? X86AS::FS : X86AS::GS;
18991 Value *Ptr = Constant::getNullValue(PointerType::get(*DAG.getContext(), Seg));
18992 SDValue Offset =
18993 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
18994 MachinePointerInfo(Ptr));
18995 return DAG.getNode(ISD::ADD, dl, PtrVT, Ret, Offset);
18998 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
18999 static SDValue
19000 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19001 const EVT PtrVT) {
19002 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD,
19003 /*LoadGlobalBaseReg=*/true);
19006 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19007 static SDValue
19008 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19009 const EVT PtrVT) {
19010 return GetTLSADDR(DAG, GA, PtrVT, X86::RAX, X86II::MO_TLSGD);
19013 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19014 static SDValue
19015 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19016 const EVT PtrVT) {
19017 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD);
19020 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
19021 SelectionDAG &DAG, const EVT PtrVT,
19022 bool Is64Bit, bool Is64BitLP64) {
19023 SDLoc dl(GA);
19025 // Get the start address of the TLS block for this module.
19026 X86MachineFunctionInfo *MFI =
19027 DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
19028 MFI->incNumLocalDynamicTLSAccesses();
19030 SDValue Base;
19031 if (Is64Bit) {
19032 unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19033 Base = GetTLSADDR(DAG, GA, PtrVT, ReturnReg, X86II::MO_TLSLD,
19034 /*LoadGlobalBaseReg=*/false,
19035 /*LocalDynamic=*/true);
19036 } else {
19037 Base = GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSLDM,
19038 /*LoadGlobalBaseReg=*/true,
19039 /*LocalDynamic=*/true);
19042 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19043 // of Base.
19045 // Build x@dtpoff.
19046 unsigned char OperandFlags = X86II::MO_DTPOFF;
19047 unsigned WrapperKind = X86ISD::Wrapper;
19048 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19049 GA->getValueType(0),
19050 GA->getOffset(), OperandFlags);
19051 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19053 // Add x@dtpoff with the base.
19054 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19057 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19058 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19059 const EVT PtrVT, TLSModel::Model model,
19060 bool is64Bit, bool isPIC) {
19061 SDLoc dl(GA);
19063 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
19064 Value *Ptr = Constant::getNullValue(
19065 PointerType::get(*DAG.getContext(), is64Bit ? X86AS::FS : X86AS::GS));
19067 SDValue ThreadPointer =
19068 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19069 MachinePointerInfo(Ptr));
19071 unsigned char OperandFlags = 0;
19072 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
19073 // initialexec.
19074 unsigned WrapperKind = X86ISD::Wrapper;
19075 if (model == TLSModel::LocalExec) {
19076 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
19077 } else if (model == TLSModel::InitialExec) {
19078 if (is64Bit) {
19079 OperandFlags = X86II::MO_GOTTPOFF;
19080 WrapperKind = X86ISD::WrapperRIP;
19081 } else {
19082 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
19084 } else {
19085 llvm_unreachable("Unexpected model");
19088 // emit "addl x@ntpoff,%eax" (local exec)
19089 // or "addl x@indntpoff,%eax" (initial exec)
19090 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
19091 SDValue TGA =
19092 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19093 GA->getOffset(), OperandFlags);
19094 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19096 if (model == TLSModel::InitialExec) {
19097 if (isPIC && !is64Bit) {
19098 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
19099 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19100 Offset);
19103 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
19104 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19107 // The address of the thread local variable is the add of the thread
19108 // pointer with the offset of the variable.
19109 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
19112 SDValue
19113 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
19115 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
19117 if (DAG.getTarget().useEmulatedTLS())
19118 return LowerToTLSEmulatedModel(GA, DAG);
19120 const GlobalValue *GV = GA->getGlobal();
19121 auto PtrVT = getPointerTy(DAG.getDataLayout());
19122 bool PositionIndependent = isPositionIndependent();
19124 if (Subtarget.isTargetELF()) {
19125 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
19126 switch (model) {
19127 case TLSModel::GeneralDynamic:
19128 if (Subtarget.is64Bit()) {
19129 if (Subtarget.isTarget64BitLP64())
19130 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
19131 return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
19133 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
19134 case TLSModel::LocalDynamic:
19135 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
19136 Subtarget.isTarget64BitLP64());
19137 case TLSModel::InitialExec:
19138 case TLSModel::LocalExec:
19139 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
19140 PositionIndependent);
19142 llvm_unreachable("Unknown TLS model.");
19145 if (Subtarget.isTargetDarwin()) {
19146 // Darwin only has one model of TLS. Lower to that.
19147 unsigned char OpFlag = 0;
19148 unsigned WrapperKind = 0;
19150 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19151 // global base reg.
19152 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
19153 if (PIC32) {
19154 OpFlag = X86II::MO_TLVP_PIC_BASE;
19155 WrapperKind = X86ISD::Wrapper;
19156 } else {
19157 OpFlag = X86II::MO_TLVP;
19158 WrapperKind = X86ISD::WrapperRIP;
19160 SDLoc DL(Op);
19161 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
19162 GA->getValueType(0),
19163 GA->getOffset(), OpFlag);
19164 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
19166 // With PIC32, the address is actually $g + Offset.
19167 if (PIC32)
19168 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
19169 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19170 Offset);
19172 // Lowering the machine isd will make sure everything is in the right
19173 // location.
19174 SDValue Chain = DAG.getEntryNode();
19175 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19176 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
19177 SDValue Args[] = { Chain, Offset };
19178 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
19179 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
19181 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
19182 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19183 MFI.setAdjustsStack(true);
19185 // And our return value (tls address) is in the standard call return value
19186 // location.
19187 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
19188 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
19191 if (Subtarget.isOSWindows()) {
19192 // Just use the implicit TLS architecture
19193 // Need to generate something similar to:
19194 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
19195 // ; from TEB
19196 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
19197 // mov rcx, qword [rdx+rcx*8]
19198 // mov eax, .tls$:tlsvar
19199 // [rax+rcx] contains the address
19200 // Windows 64bit: gs:0x58
19201 // Windows 32bit: fs:__tls_array
19203 SDLoc dl(GA);
19204 SDValue Chain = DAG.getEntryNode();
19206 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
19207 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
19208 // use its literal value of 0x2C.
19209 Value *Ptr = Constant::getNullValue(
19210 Subtarget.is64Bit() ? PointerType::get(*DAG.getContext(), X86AS::GS)
19211 : PointerType::get(*DAG.getContext(), X86AS::FS));
19213 SDValue TlsArray = Subtarget.is64Bit()
19214 ? DAG.getIntPtrConstant(0x58, dl)
19215 : (Subtarget.isTargetWindowsGNU()
19216 ? DAG.getIntPtrConstant(0x2C, dl)
19217 : DAG.getExternalSymbol("_tls_array", PtrVT));
19219 SDValue ThreadPointer =
19220 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
19222 SDValue res;
19223 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
19224 res = ThreadPointer;
19225 } else {
19226 // Load the _tls_index variable
19227 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
19228 if (Subtarget.is64Bit())
19229 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
19230 MachinePointerInfo(), MVT::i32);
19231 else
19232 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
19234 const DataLayout &DL = DAG.getDataLayout();
19235 SDValue Scale =
19236 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
19237 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
19239 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
19242 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
19244 // Get the offset of start of .tls section
19245 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19246 GA->getValueType(0),
19247 GA->getOffset(), X86II::MO_SECREL);
19248 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
19250 // The address of the thread local variable is the add of the thread
19251 // pointer with the offset of the variable.
19252 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
19255 llvm_unreachable("TLS not implemented for this target.");
19258 bool X86TargetLowering::addressingModeSupportsTLS(const GlobalValue &GV) const {
19259 if (Subtarget.is64Bit() && Subtarget.isTargetELF()) {
19260 const TargetMachine &TM = getTargetMachine();
19261 TLSModel::Model Model = TM.getTLSModel(&GV);
19262 switch (Model) {
19263 case TLSModel::LocalExec:
19264 case TLSModel::InitialExec:
19265 // We can include the %fs segment register in addressing modes.
19266 return true;
19267 case TLSModel::LocalDynamic:
19268 case TLSModel::GeneralDynamic:
19269 // These models do not result in %fs relative addresses unless
19270 // TLS descriptior are used.
19272 // Even in the case of TLS descriptors we currently have no way to model
19273 // the difference between %fs access and the computations needed for the
19274 // offset and returning `true` for TLS-desc currently duplicates both
19275 // which is detrimental :-/
19276 return false;
19279 return false;
19282 /// Lower SRA_PARTS and friends, which return two i32 values
19283 /// and take a 2 x i32 value to shift plus a shift amount.
19284 /// TODO: Can this be moved to general expansion code?
19285 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
19286 SDValue Lo, Hi;
19287 DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
19288 return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
19291 // Try to use a packed vector operation to handle i64 on 32-bit targets when
19292 // AVX512DQ is enabled.
19293 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, const SDLoc &dl,
19294 SelectionDAG &DAG,
19295 const X86Subtarget &Subtarget) {
19296 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
19297 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
19298 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
19299 Op.getOpcode() == ISD::UINT_TO_FP) &&
19300 "Unexpected opcode!");
19301 bool IsStrict = Op->isStrictFPOpcode();
19302 unsigned OpNo = IsStrict ? 1 : 0;
19303 SDValue Src = Op.getOperand(OpNo);
19304 MVT SrcVT = Src.getSimpleValueType();
19305 MVT VT = Op.getSimpleValueType();
19307 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
19308 (VT != MVT::f32 && VT != MVT::f64))
19309 return SDValue();
19311 // Pack the i64 into a vector, do the operation and extract.
19313 // Using 256-bit to ensure result is 128-bits for f32 case.
19314 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
19315 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
19316 MVT VecVT = MVT::getVectorVT(VT, NumElts);
19318 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
19319 if (IsStrict) {
19320 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
19321 {Op.getOperand(0), InVec});
19322 SDValue Chain = CvtVec.getValue(1);
19323 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19324 DAG.getIntPtrConstant(0, dl));
19325 return DAG.getMergeValues({Value, Chain}, dl);
19328 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
19330 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19331 DAG.getIntPtrConstant(0, dl));
19334 // Try to use a packed vector operation to handle i64 on 32-bit targets.
19335 static SDValue LowerI64IntToFP16(SDValue Op, const SDLoc &dl, SelectionDAG &DAG,
19336 const X86Subtarget &Subtarget) {
19337 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
19338 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
19339 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
19340 Op.getOpcode() == ISD::UINT_TO_FP) &&
19341 "Unexpected opcode!");
19342 bool IsStrict = Op->isStrictFPOpcode();
19343 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
19344 MVT SrcVT = Src.getSimpleValueType();
19345 MVT VT = Op.getSimpleValueType();
19347 if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
19348 return SDValue();
19350 // Pack the i64 into a vector, do the operation and extract.
19352 assert(Subtarget.hasFP16() && "Expected FP16");
19354 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
19355 if (IsStrict) {
19356 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
19357 {Op.getOperand(0), InVec});
19358 SDValue Chain = CvtVec.getValue(1);
19359 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19360 DAG.getIntPtrConstant(0, dl));
19361 return DAG.getMergeValues({Value, Chain}, dl);
19364 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
19366 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19367 DAG.getIntPtrConstant(0, dl));
19370 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
19371 const X86Subtarget &Subtarget) {
19372 switch (Opcode) {
19373 case ISD::SINT_TO_FP:
19374 // TODO: Handle wider types with AVX/AVX512.
19375 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
19376 return false;
19377 // CVTDQ2PS or (V)CVTDQ2PD
19378 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
19380 case ISD::UINT_TO_FP:
19381 // TODO: Handle wider types and i64 elements.
19382 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
19383 return false;
19384 // VCVTUDQ2PS or VCVTUDQ2PD
19385 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
19387 default:
19388 return false;
19392 /// Given a scalar cast operation that is extracted from a vector, try to
19393 /// vectorize the cast op followed by extraction. This will avoid an expensive
19394 /// round-trip between XMM and GPR.
19395 static SDValue vectorizeExtractedCast(SDValue Cast, const SDLoc &DL,
19396 SelectionDAG &DAG,
19397 const X86Subtarget &Subtarget) {
19398 // TODO: This could be enhanced to handle smaller integer types by peeking
19399 // through an extend.
19400 SDValue Extract = Cast.getOperand(0);
19401 MVT DestVT = Cast.getSimpleValueType();
19402 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19403 !isa<ConstantSDNode>(Extract.getOperand(1)))
19404 return SDValue();
19406 // See if we have a 128-bit vector cast op for this type of cast.
19407 SDValue VecOp = Extract.getOperand(0);
19408 MVT FromVT = VecOp.getSimpleValueType();
19409 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
19410 MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
19411 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
19412 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
19413 return SDValue();
19415 // If we are extracting from a non-zero element, first shuffle the source
19416 // vector to allow extracting from element zero.
19417 if (!isNullConstant(Extract.getOperand(1))) {
19418 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
19419 Mask[0] = Extract.getConstantOperandVal(1);
19420 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
19422 // If the source vector is wider than 128-bits, extract the low part. Do not
19423 // create an unnecessarily wide vector cast op.
19424 if (FromVT != Vec128VT)
19425 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
19427 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
19428 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
19429 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
19430 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
19431 DAG.getIntPtrConstant(0, DL));
19434 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
19435 /// try to vectorize the cast ops. This will avoid an expensive round-trip
19436 /// between XMM and GPR.
19437 static SDValue lowerFPToIntToFP(SDValue CastToFP, const SDLoc &DL,
19438 SelectionDAG &DAG,
19439 const X86Subtarget &Subtarget) {
19440 // TODO: Allow FP_TO_UINT.
19441 SDValue CastToInt = CastToFP.getOperand(0);
19442 MVT VT = CastToFP.getSimpleValueType();
19443 if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
19444 return SDValue();
19446 MVT IntVT = CastToInt.getSimpleValueType();
19447 SDValue X = CastToInt.getOperand(0);
19448 MVT SrcVT = X.getSimpleValueType();
19449 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
19450 return SDValue();
19452 // See if we have 128-bit vector cast instructions for this type of cast.
19453 // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
19454 if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
19455 IntVT != MVT::i32)
19456 return SDValue();
19458 unsigned SrcSize = SrcVT.getSizeInBits();
19459 unsigned IntSize = IntVT.getSizeInBits();
19460 unsigned VTSize = VT.getSizeInBits();
19461 MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
19462 MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
19463 MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
19465 // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
19466 unsigned ToIntOpcode =
19467 SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
19468 unsigned ToFPOpcode =
19469 IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
19471 // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
19473 // We are not defining the high elements (for example, zero them) because
19474 // that could nullify any performance advantage that we hoped to gain from
19475 // this vector op hack. We do not expect any adverse effects (like denorm
19476 // penalties) with cast ops.
19477 SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
19478 SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
19479 SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
19480 SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
19481 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
19484 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, const SDLoc &DL,
19485 SelectionDAG &DAG,
19486 const X86Subtarget &Subtarget) {
19487 bool IsStrict = Op->isStrictFPOpcode();
19488 MVT VT = Op->getSimpleValueType(0);
19489 SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
19491 if (Subtarget.hasDQI()) {
19492 assert(!Subtarget.hasVLX() && "Unexpected features");
19494 assert((Src.getSimpleValueType() == MVT::v2i64 ||
19495 Src.getSimpleValueType() == MVT::v4i64) &&
19496 "Unsupported custom type");
19498 // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
19499 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
19500 "Unexpected VT!");
19501 MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
19503 // Need to concat with zero vector for strict fp to avoid spurious
19504 // exceptions.
19505 SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
19506 : DAG.getUNDEF(MVT::v8i64);
19507 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
19508 DAG.getIntPtrConstant(0, DL));
19509 SDValue Res, Chain;
19510 if (IsStrict) {
19511 Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
19512 {Op->getOperand(0), Src});
19513 Chain = Res.getValue(1);
19514 } else {
19515 Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
19518 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19519 DAG.getIntPtrConstant(0, DL));
19521 if (IsStrict)
19522 return DAG.getMergeValues({Res, Chain}, DL);
19523 return Res;
19526 bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
19527 Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
19528 if (VT != MVT::v4f32 || IsSigned)
19529 return SDValue();
19531 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
19532 SDValue One = DAG.getConstant(1, DL, MVT::v4i64);
19533 SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
19534 DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
19535 DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
19536 SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
19537 SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
19538 SmallVector<SDValue, 4> SignCvts(4);
19539 SmallVector<SDValue, 4> Chains(4);
19540 for (int i = 0; i != 4; ++i) {
19541 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
19542 DAG.getIntPtrConstant(i, DL));
19543 if (IsStrict) {
19544 SignCvts[i] =
19545 DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
19546 {Op.getOperand(0), Elt});
19547 Chains[i] = SignCvts[i].getValue(1);
19548 } else {
19549 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
19552 SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
19554 SDValue Slow, Chain;
19555 if (IsStrict) {
19556 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19557 Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
19558 {Chain, SignCvt, SignCvt});
19559 Chain = Slow.getValue(1);
19560 } else {
19561 Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
19564 IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
19565 SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
19567 if (IsStrict)
19568 return DAG.getMergeValues({Cvt, Chain}, DL);
19570 return Cvt;
19573 static SDValue promoteXINT_TO_FP(SDValue Op, const SDLoc &dl,
19574 SelectionDAG &DAG) {
19575 bool IsStrict = Op->isStrictFPOpcode();
19576 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
19577 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19578 MVT VT = Op.getSimpleValueType();
19579 MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
19581 SDValue Rnd = DAG.getIntPtrConstant(0, dl);
19582 if (IsStrict)
19583 return DAG.getNode(
19584 ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
19585 {Chain,
19586 DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
19587 Rnd});
19588 return DAG.getNode(ISD::FP_ROUND, dl, VT,
19589 DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
19592 static bool isLegalConversion(MVT VT, bool IsSigned,
19593 const X86Subtarget &Subtarget) {
19594 if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
19595 return true;
19596 if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
19597 return true;
19598 if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
19599 return true;
19600 if (Subtarget.useAVX512Regs()) {
19601 if (VT == MVT::v16i32)
19602 return true;
19603 if (VT == MVT::v8i64 && Subtarget.hasDQI())
19604 return true;
19606 if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
19607 (VT == MVT::v2i64 || VT == MVT::v4i64))
19608 return true;
19609 return false;
19612 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
19613 SelectionDAG &DAG) const {
19614 bool IsStrict = Op->isStrictFPOpcode();
19615 unsigned OpNo = IsStrict ? 1 : 0;
19616 SDValue Src = Op.getOperand(OpNo);
19617 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19618 MVT SrcVT = Src.getSimpleValueType();
19619 MVT VT = Op.getSimpleValueType();
19620 SDLoc dl(Op);
19622 if (isSoftF16(VT, Subtarget))
19623 return promoteXINT_TO_FP(Op, dl, DAG);
19624 else if (isLegalConversion(SrcVT, true, Subtarget))
19625 return Op;
19627 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
19628 return LowerWin64_INT128_TO_FP(Op, DAG);
19630 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
19631 return Extract;
19633 if (SDValue R = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
19634 return R;
19636 if (SrcVT.isVector()) {
19637 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
19638 // Note: Since v2f64 is a legal type. We don't need to zero extend the
19639 // source for strict FP.
19640 if (IsStrict)
19641 return DAG.getNode(
19642 X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
19643 {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19644 DAG.getUNDEF(SrcVT))});
19645 return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
19646 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19647 DAG.getUNDEF(SrcVT)));
19649 if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
19650 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
19652 return SDValue();
19655 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
19656 "Unknown SINT_TO_FP to lower!");
19658 bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
19660 // These are really Legal; return the operand so the caller accepts it as
19661 // Legal.
19662 if (SrcVT == MVT::i32 && UseSSEReg)
19663 return Op;
19664 if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
19665 return Op;
19667 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
19668 return V;
19669 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
19670 return V;
19672 // SSE doesn't have an i16 conversion so we need to promote.
19673 if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
19674 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
19675 if (IsStrict)
19676 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
19677 {Chain, Ext});
19679 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
19682 if (VT == MVT::f128 || !Subtarget.hasX87())
19683 return SDValue();
19685 SDValue ValueToStore = Src;
19686 if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
19687 // Bitcasting to f64 here allows us to do a single 64-bit store from
19688 // an SSE register, avoiding the store forwarding penalty that would come
19689 // with two 32-bit stores.
19690 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19692 unsigned Size = SrcVT.getStoreSize();
19693 Align Alignment(Size);
19694 MachineFunction &MF = DAG.getMachineFunction();
19695 auto PtrVT = getPointerTy(MF.getDataLayout());
19696 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
19697 MachinePointerInfo MPI =
19698 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19699 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19700 Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
19701 std::pair<SDValue, SDValue> Tmp =
19702 BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
19704 if (IsStrict)
19705 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19707 return Tmp.first;
19710 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
19711 EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
19712 MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
19713 // Build the FILD
19714 SDVTList Tys;
19715 bool useSSE = isScalarFPTypeInSSEReg(DstVT);
19716 if (useSSE)
19717 Tys = DAG.getVTList(MVT::f80, MVT::Other);
19718 else
19719 Tys = DAG.getVTList(DstVT, MVT::Other);
19721 SDValue FILDOps[] = {Chain, Pointer};
19722 SDValue Result =
19723 DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
19724 Alignment, MachineMemOperand::MOLoad);
19725 Chain = Result.getValue(1);
19727 if (useSSE) {
19728 MachineFunction &MF = DAG.getMachineFunction();
19729 unsigned SSFISize = DstVT.getStoreSize();
19730 int SSFI =
19731 MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
19732 auto PtrVT = getPointerTy(MF.getDataLayout());
19733 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19734 Tys = DAG.getVTList(MVT::Other);
19735 SDValue FSTOps[] = {Chain, Result, StackSlot};
19736 MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
19737 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
19738 MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
19740 Chain =
19741 DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
19742 Result = DAG.getLoad(
19743 DstVT, DL, Chain, StackSlot,
19744 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
19745 Chain = Result.getValue(1);
19748 return { Result, Chain };
19751 /// Horizontal vector math instructions may be slower than normal math with
19752 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
19753 /// implementation, and likely shuffle complexity of the alternate sequence.
19754 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
19755 const X86Subtarget &Subtarget) {
19756 bool IsOptimizingSize = DAG.shouldOptForSize();
19757 bool HasFastHOps = Subtarget.hasFastHorizontalOps();
19758 return !IsSingleSource || IsOptimizingSize || HasFastHOps;
19761 /// 64-bit unsigned integer to double expansion.
19762 static SDValue LowerUINT_TO_FP_i64(SDValue Op, const SDLoc &dl,
19763 SelectionDAG &DAG,
19764 const X86Subtarget &Subtarget) {
19765 // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
19766 // when converting 0 when rounding toward negative infinity. Caller will
19767 // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
19768 assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
19769 // This algorithm is not obvious. Here it is what we're trying to output:
19771 movq %rax, %xmm0
19772 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
19773 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
19774 #ifdef __SSE3__
19775 haddpd %xmm0, %xmm0
19776 #else
19777 pshufd $0x4e, %xmm0, %xmm1
19778 addpd %xmm1, %xmm0
19779 #endif
19782 LLVMContext *Context = DAG.getContext();
19784 // Build some magic constants.
19785 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
19786 Constant *C0 = ConstantDataVector::get(*Context, CV0);
19787 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19788 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
19790 SmallVector<Constant*,2> CV1;
19791 CV1.push_back(
19792 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19793 APInt(64, 0x4330000000000000ULL))));
19794 CV1.push_back(
19795 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19796 APInt(64, 0x4530000000000000ULL))));
19797 Constant *C1 = ConstantVector::get(CV1);
19798 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
19800 // Load the 64-bit value into an XMM register.
19801 SDValue XR1 =
19802 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
19803 SDValue CLod0 = DAG.getLoad(
19804 MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
19805 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
19806 SDValue Unpck1 =
19807 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
19809 SDValue CLod1 = DAG.getLoad(
19810 MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
19811 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
19812 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
19813 // TODO: Are there any fast-math-flags to propagate here?
19814 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
19815 SDValue Result;
19817 if (Subtarget.hasSSE3() &&
19818 shouldUseHorizontalOp(true, DAG, Subtarget)) {
19819 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
19820 } else {
19821 SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
19822 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
19824 Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
19825 DAG.getIntPtrConstant(0, dl));
19826 return Result;
19829 /// 32-bit unsigned integer to float expansion.
19830 static SDValue LowerUINT_TO_FP_i32(SDValue Op, const SDLoc &dl,
19831 SelectionDAG &DAG,
19832 const X86Subtarget &Subtarget) {
19833 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19834 // FP constant to bias correct the final result.
19835 SDValue Bias = DAG.getConstantFP(
19836 llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::f64);
19838 // Load the 32-bit value into an XMM register.
19839 SDValue Load =
19840 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
19842 // Zero out the upper parts of the register.
19843 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
19845 // Or the load with the bias.
19846 SDValue Or = DAG.getNode(
19847 ISD::OR, dl, MVT::v2i64,
19848 DAG.getBitcast(MVT::v2i64, Load),
19849 DAG.getBitcast(MVT::v2i64,
19850 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
19851 Or =
19852 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
19853 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
19855 if (Op.getNode()->isStrictFPOpcode()) {
19856 // Subtract the bias.
19857 // TODO: Are there any fast-math-flags to propagate here?
19858 SDValue Chain = Op.getOperand(0);
19859 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
19860 {Chain, Or, Bias});
19862 if (Op.getValueType() == Sub.getValueType())
19863 return Sub;
19865 // Handle final rounding.
19866 std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
19867 Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
19869 return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
19872 // Subtract the bias.
19873 // TODO: Are there any fast-math-flags to propagate here?
19874 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
19876 // Handle final rounding.
19877 return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
19880 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, const SDLoc &DL,
19881 SelectionDAG &DAG,
19882 const X86Subtarget &Subtarget) {
19883 if (Op.getSimpleValueType() != MVT::v2f64)
19884 return SDValue();
19886 bool IsStrict = Op->isStrictFPOpcode();
19888 SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
19889 assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
19891 if (Subtarget.hasAVX512()) {
19892 if (!Subtarget.hasVLX()) {
19893 // Let generic type legalization widen this.
19894 if (!IsStrict)
19895 return SDValue();
19896 // Otherwise pad the integer input with 0s and widen the operation.
19897 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19898 DAG.getConstant(0, DL, MVT::v2i32));
19899 SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
19900 {Op.getOperand(0), N0});
19901 SDValue Chain = Res.getValue(1);
19902 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
19903 DAG.getIntPtrConstant(0, DL));
19904 return DAG.getMergeValues({Res, Chain}, DL);
19907 // Legalize to v4i32 type.
19908 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19909 DAG.getUNDEF(MVT::v2i32));
19910 if (IsStrict)
19911 return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
19912 {Op.getOperand(0), N0});
19913 return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
19916 // Zero extend to 2i64, OR with the floating point representation of 2^52.
19917 // This gives us the floating point equivalent of 2^52 + the i32 integer
19918 // since double has 52-bits of mantissa. Then subtract 2^52 in floating
19919 // point leaving just our i32 integers in double format.
19920 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
19921 SDValue VBias = DAG.getConstantFP(
19922 llvm::bit_cast<double>(0x4330000000000000ULL), DL, MVT::v2f64);
19923 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
19924 DAG.getBitcast(MVT::v2i64, VBias));
19925 Or = DAG.getBitcast(MVT::v2f64, Or);
19927 if (IsStrict)
19928 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
19929 {Op.getOperand(0), Or, VBias});
19930 return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
19933 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, const SDLoc &DL,
19934 SelectionDAG &DAG,
19935 const X86Subtarget &Subtarget) {
19936 bool IsStrict = Op->isStrictFPOpcode();
19937 SDValue V = Op->getOperand(IsStrict ? 1 : 0);
19938 MVT VecIntVT = V.getSimpleValueType();
19939 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
19940 "Unsupported custom type");
19942 if (Subtarget.hasAVX512()) {
19943 // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19944 assert(!Subtarget.hasVLX() && "Unexpected features");
19945 MVT VT = Op->getSimpleValueType(0);
19947 // v8i32->v8f64 is legal with AVX512 so just return it.
19948 if (VT == MVT::v8f64)
19949 return Op;
19951 assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
19952 "Unexpected VT!");
19953 MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
19954 MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
19955 // Need to concat with zero vector for strict fp to avoid spurious
19956 // exceptions.
19957 SDValue Tmp =
19958 IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
19959 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
19960 DAG.getIntPtrConstant(0, DL));
19961 SDValue Res, Chain;
19962 if (IsStrict) {
19963 Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
19964 {Op->getOperand(0), V});
19965 Chain = Res.getValue(1);
19966 } else {
19967 Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
19970 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19971 DAG.getIntPtrConstant(0, DL));
19973 if (IsStrict)
19974 return DAG.getMergeValues({Res, Chain}, DL);
19975 return Res;
19978 if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
19979 Op->getSimpleValueType(0) == MVT::v4f64) {
19980 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
19981 Constant *Bias = ConstantFP::get(
19982 *DAG.getContext(),
19983 APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
19984 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19985 SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
19986 SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
19987 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
19988 SDValue VBias = DAG.getMemIntrinsicNode(
19989 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
19990 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
19991 MachineMemOperand::MOLoad);
19993 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
19994 DAG.getBitcast(MVT::v4i64, VBias));
19995 Or = DAG.getBitcast(MVT::v4f64, Or);
19997 if (IsStrict)
19998 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
19999 {Op.getOperand(0), Or, VBias});
20000 return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20003 // The algorithm is the following:
20004 // #ifdef __SSE4_1__
20005 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20006 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20007 // (uint4) 0x53000000, 0xaa);
20008 // #else
20009 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20010 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20011 // #endif
20012 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20013 // return (float4) lo + fhi;
20015 bool Is128 = VecIntVT == MVT::v4i32;
20016 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
20017 // If we convert to something else than the supported type, e.g., to v4f64,
20018 // abort early.
20019 if (VecFloatVT != Op->getSimpleValueType(0))
20020 return SDValue();
20022 // In the #idef/#else code, we have in common:
20023 // - The vector of constants:
20024 // -- 0x4b000000
20025 // -- 0x53000000
20026 // - A shift:
20027 // -- v >> 16
20029 // Create the splat vector for 0x4b000000.
20030 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
20031 // Create the splat vector for 0x53000000.
20032 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
20034 // Create the right shift.
20035 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
20036 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
20038 SDValue Low, High;
20039 if (Subtarget.hasSSE41()) {
20040 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
20041 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20042 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
20043 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
20044 // Low will be bitcasted right away, so do not bother bitcasting back to its
20045 // original type.
20046 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
20047 VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20048 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20049 // (uint4) 0x53000000, 0xaa);
20050 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
20051 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
20052 // High will be bitcasted right away, so do not bother bitcasting back to
20053 // its original type.
20054 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
20055 VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20056 } else {
20057 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
20058 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20059 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
20060 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
20062 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20063 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
20066 // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
20067 SDValue VecCstFSub = DAG.getConstantFP(
20068 APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
20070 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20071 // NOTE: By using fsub of a positive constant instead of fadd of a negative
20072 // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
20073 // enabled. See PR24512.
20074 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
20075 // TODO: Are there any fast-math-flags to propagate here?
20076 // (float4) lo;
20077 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
20078 // return (float4) lo + fhi;
20079 if (IsStrict) {
20080 SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
20081 {Op.getOperand(0), HighBitcast, VecCstFSub});
20082 return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
20083 {FHigh.getValue(1), LowBitcast, FHigh});
20086 SDValue FHigh =
20087 DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
20088 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
20091 static SDValue lowerUINT_TO_FP_vec(SDValue Op, const SDLoc &dl, SelectionDAG &DAG,
20092 const X86Subtarget &Subtarget) {
20093 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20094 SDValue N0 = Op.getOperand(OpNo);
20095 MVT SrcVT = N0.getSimpleValueType();
20097 switch (SrcVT.SimpleTy) {
20098 default:
20099 llvm_unreachable("Custom UINT_TO_FP is not supported!");
20100 case MVT::v2i32:
20101 return lowerUINT_TO_FP_v2i32(Op, dl, DAG, Subtarget);
20102 case MVT::v4i32:
20103 case MVT::v8i32:
20104 return lowerUINT_TO_FP_vXi32(Op, dl, DAG, Subtarget);
20105 case MVT::v2i64:
20106 case MVT::v4i64:
20107 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
20111 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
20112 SelectionDAG &DAG) const {
20113 bool IsStrict = Op->isStrictFPOpcode();
20114 unsigned OpNo = IsStrict ? 1 : 0;
20115 SDValue Src = Op.getOperand(OpNo);
20116 SDLoc dl(Op);
20117 auto PtrVT = getPointerTy(DAG.getDataLayout());
20118 MVT SrcVT = Src.getSimpleValueType();
20119 MVT DstVT = Op->getSimpleValueType(0);
20120 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20122 // Bail out when we don't have native conversion instructions.
20123 if (DstVT == MVT::f128)
20124 return SDValue();
20126 if (isSoftF16(DstVT, Subtarget))
20127 return promoteXINT_TO_FP(Op, dl, DAG);
20128 else if (isLegalConversion(SrcVT, false, Subtarget))
20129 return Op;
20131 if (DstVT.isVector())
20132 return lowerUINT_TO_FP_vec(Op, dl, DAG, Subtarget);
20134 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
20135 return LowerWin64_INT128_TO_FP(Op, DAG);
20137 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
20138 return Extract;
20140 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
20141 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
20142 // Conversions from unsigned i32 to f32/f64 are legal,
20143 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
20144 return Op;
20147 // Promote i32 to i64 and use a signed conversion on 64-bit targets.
20148 if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
20149 Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
20150 if (IsStrict)
20151 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
20152 {Chain, Src});
20153 return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
20156 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
20157 return V;
20158 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
20159 return V;
20161 // The transform for i64->f64 isn't correct for 0 when rounding to negative
20162 // infinity. It produces -0.0, so disable under strictfp.
20163 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
20164 !IsStrict)
20165 return LowerUINT_TO_FP_i64(Op, dl, DAG, Subtarget);
20166 // The transform for i32->f64/f32 isn't correct for 0 when rounding to
20167 // negative infinity. So disable under strictfp. Using FILD instead.
20168 if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
20169 !IsStrict)
20170 return LowerUINT_TO_FP_i32(Op, dl, DAG, Subtarget);
20171 if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
20172 (DstVT == MVT::f32 || DstVT == MVT::f64))
20173 return SDValue();
20175 // Make a 64-bit buffer, and use it to build an FILD.
20176 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
20177 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
20178 Align SlotAlign(8);
20179 MachinePointerInfo MPI =
20180 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
20181 if (SrcVT == MVT::i32) {
20182 SDValue OffsetSlot =
20183 DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
20184 SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
20185 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
20186 OffsetSlot, MPI.getWithOffset(4), SlotAlign);
20187 std::pair<SDValue, SDValue> Tmp =
20188 BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
20189 if (IsStrict)
20190 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20192 return Tmp.first;
20195 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
20196 SDValue ValueToStore = Src;
20197 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
20198 // Bitcasting to f64 here allows us to do a single 64-bit store from
20199 // an SSE register, avoiding the store forwarding penalty that would come
20200 // with two 32-bit stores.
20201 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20203 SDValue Store =
20204 DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
20205 // For i64 source, we need to add the appropriate power of 2 if the input
20206 // was negative. We must be careful to do the computation in x87 extended
20207 // precision, not in SSE.
20208 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20209 SDValue Ops[] = {Store, StackSlot};
20210 SDValue Fild =
20211 DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
20212 SlotAlign, MachineMemOperand::MOLoad);
20213 Chain = Fild.getValue(1);
20215 // Check whether the sign bit is set.
20216 SDValue SignSet = DAG.getSetCC(
20217 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
20218 Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
20220 // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
20221 APInt FF(64, 0x5F80000000000000ULL);
20222 SDValue FudgePtr =
20223 DAG.getConstantPool(ConstantInt::get(*DAG.getContext(), FF), PtrVT);
20224 Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
20226 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
20227 SDValue Zero = DAG.getIntPtrConstant(0, dl);
20228 SDValue Four = DAG.getIntPtrConstant(4, dl);
20229 SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
20230 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
20232 // Load the value out, extending it from f32 to f80.
20233 SDValue Fudge = DAG.getExtLoad(
20234 ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
20235 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
20236 CPAlignment);
20237 Chain = Fudge.getValue(1);
20238 // Extend everything to 80 bits to force it to be done on x87.
20239 // TODO: Are there any fast-math-flags to propagate here?
20240 if (IsStrict) {
20241 unsigned Opc = ISD::STRICT_FADD;
20242 // Windows needs the precision control changed to 80bits around this add.
20243 if (Subtarget.isOSWindows() && DstVT == MVT::f32)
20244 Opc = X86ISD::STRICT_FP80_ADD;
20246 SDValue Add =
20247 DAG.getNode(Opc, dl, {MVT::f80, MVT::Other}, {Chain, Fild, Fudge});
20248 // STRICT_FP_ROUND can't handle equal types.
20249 if (DstVT == MVT::f80)
20250 return Add;
20251 return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
20252 {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
20254 unsigned Opc = ISD::FADD;
20255 // Windows needs the precision control changed to 80bits around this add.
20256 if (Subtarget.isOSWindows() && DstVT == MVT::f32)
20257 Opc = X86ISD::FP80_ADD;
20259 SDValue Add = DAG.getNode(Opc, dl, MVT::f80, Fild, Fudge);
20260 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
20261 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
20264 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
20265 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
20266 // just return an SDValue().
20267 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
20268 // to i16, i32 or i64, and we lower it to a legal sequence and return the
20269 // result.
20270 SDValue X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
20271 bool IsSigned,
20272 SDValue &Chain) const {
20273 bool IsStrict = Op->isStrictFPOpcode();
20274 SDLoc DL(Op);
20276 EVT DstTy = Op.getValueType();
20277 SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
20278 EVT TheVT = Value.getValueType();
20279 auto PtrVT = getPointerTy(DAG.getDataLayout());
20281 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
20282 // f16 must be promoted before using the lowering in this routine.
20283 // fp128 does not use this lowering.
20284 return SDValue();
20287 // If using FIST to compute an unsigned i64, we'll need some fixup
20288 // to handle values above the maximum signed i64. A FIST is always
20289 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
20290 bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
20292 // FIXME: This does not generate an invalid exception if the input does not
20293 // fit in i32. PR44019
20294 if (!IsSigned && DstTy != MVT::i64) {
20295 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
20296 // The low 32 bits of the fist result will have the correct uint32 result.
20297 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
20298 DstTy = MVT::i64;
20301 assert(DstTy.getSimpleVT() <= MVT::i64 &&
20302 DstTy.getSimpleVT() >= MVT::i16 &&
20303 "Unknown FP_TO_INT to lower!");
20305 // We lower FP->int64 into FISTP64 followed by a load from a temporary
20306 // stack slot.
20307 MachineFunction &MF = DAG.getMachineFunction();
20308 unsigned MemSize = DstTy.getStoreSize();
20309 int SSFI =
20310 MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
20311 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20313 Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20315 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
20317 if (UnsignedFixup) {
20319 // Conversion to unsigned i64 is implemented with a select,
20320 // depending on whether the source value fits in the range
20321 // of a signed i64. Let Thresh be the FP equivalent of
20322 // 0x8000000000000000ULL.
20324 // Adjust = (Value >= Thresh) ? 0x80000000 : 0;
20325 // FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
20326 // FistSrc = (Value - FltOfs);
20327 // Fist-to-mem64 FistSrc
20328 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
20329 // to XOR'ing the high 32 bits with Adjust.
20331 // Being a power of 2, Thresh is exactly representable in all FP formats.
20332 // For X87 we'd like to use the smallest FP type for this constant, but
20333 // for DAG type consistency we have to match the FP operand type.
20335 APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
20336 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
20337 bool LosesInfo = false;
20338 if (TheVT == MVT::f64)
20339 // The rounding mode is irrelevant as the conversion should be exact.
20340 Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
20341 &LosesInfo);
20342 else if (TheVT == MVT::f80)
20343 Status = Thresh.convert(APFloat::x87DoubleExtended(),
20344 APFloat::rmNearestTiesToEven, &LosesInfo);
20346 assert(Status == APFloat::opOK && !LosesInfo &&
20347 "FP conversion should have been exact");
20349 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
20351 EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
20352 *DAG.getContext(), TheVT);
20353 SDValue Cmp;
20354 if (IsStrict) {
20355 Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
20356 /*IsSignaling*/ true);
20357 Chain = Cmp.getValue(1);
20358 } else {
20359 Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
20362 // Our preferred lowering of
20364 // (Value >= Thresh) ? 0x8000000000000000ULL : 0
20366 // is
20368 // (Value >= Thresh) << 63
20370 // but since we can get here after LegalOperations, DAGCombine might do the
20371 // wrong thing if we create a select. So, directly create the preferred
20372 // version.
20373 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
20374 SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
20375 Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
20377 SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
20378 DAG.getConstantFP(0.0, DL, TheVT));
20380 if (IsStrict) {
20381 Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
20382 { Chain, Value, FltOfs });
20383 Chain = Value.getValue(1);
20384 } else
20385 Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
20388 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
20390 // FIXME This causes a redundant load/store if the SSE-class value is already
20391 // in memory, such as if it is on the callstack.
20392 if (isScalarFPTypeInSSEReg(TheVT)) {
20393 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
20394 Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
20395 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20396 SDValue Ops[] = { Chain, StackSlot };
20398 unsigned FLDSize = TheVT.getStoreSize();
20399 assert(FLDSize <= MemSize && "Stack slot not big enough");
20400 MachineMemOperand *MMO = MF.getMachineMemOperand(
20401 MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
20402 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
20403 Chain = Value.getValue(1);
20406 // Build the FP_TO_INT*_IN_MEM
20407 MachineMemOperand *MMO = MF.getMachineMemOperand(
20408 MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
20409 SDValue Ops[] = { Chain, Value, StackSlot };
20410 SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
20411 DAG.getVTList(MVT::Other),
20412 Ops, DstTy, MMO);
20414 SDValue Res = DAG.getLoad(Op.getValueType(), DL, FIST, StackSlot, MPI);
20415 Chain = Res.getValue(1);
20417 // If we need an unsigned fixup, XOR the result with adjust.
20418 if (UnsignedFixup)
20419 Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
20421 return Res;
20424 static SDValue LowerAVXExtend(SDValue Op, const SDLoc &dl, SelectionDAG &DAG,
20425 const X86Subtarget &Subtarget) {
20426 MVT VT = Op.getSimpleValueType();
20427 SDValue In = Op.getOperand(0);
20428 MVT InVT = In.getSimpleValueType();
20429 unsigned Opc = Op.getOpcode();
20431 assert(VT.isVector() && InVT.isVector() && "Expected vector type");
20432 assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
20433 "Unexpected extension opcode");
20434 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20435 "Expected same number of elements");
20436 assert((VT.getVectorElementType() == MVT::i16 ||
20437 VT.getVectorElementType() == MVT::i32 ||
20438 VT.getVectorElementType() == MVT::i64) &&
20439 "Unexpected element type");
20440 assert((InVT.getVectorElementType() == MVT::i8 ||
20441 InVT.getVectorElementType() == MVT::i16 ||
20442 InVT.getVectorElementType() == MVT::i32) &&
20443 "Unexpected element type");
20445 unsigned ExtendInVecOpc = DAG.getOpcode_EXTEND_VECTOR_INREG(Opc);
20447 if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
20448 assert(InVT == MVT::v32i8 && "Unexpected VT!");
20449 return splitVectorIntUnary(Op, DAG, dl);
20452 if (Subtarget.hasInt256())
20453 return Op;
20455 // Optimize vectors in AVX mode:
20457 // v8i16 -> v8i32
20458 // Use vpmovzwd for 4 lower elements v8i16 -> v4i32.
20459 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
20460 // Concat upper and lower parts.
20462 // v4i32 -> v4i64
20463 // Use vpmovzdq for 4 lower elements v4i32 -> v2i64.
20464 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
20465 // Concat upper and lower parts.
20467 MVT HalfVT = VT.getHalfNumVectorElementsVT();
20468 SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
20470 // Short-circuit if we can determine that each 128-bit half is the same value.
20471 // Otherwise, this is difficult to match and optimize.
20472 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
20473 if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
20474 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
20476 SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
20477 SDValue Undef = DAG.getUNDEF(InVT);
20478 bool NeedZero = Opc == ISD::ZERO_EXTEND;
20479 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
20480 OpHi = DAG.getBitcast(HalfVT, OpHi);
20482 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20485 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
20486 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
20487 const SDLoc &dl, SelectionDAG &DAG) {
20488 assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
20489 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20490 DAG.getIntPtrConstant(0, dl));
20491 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20492 DAG.getIntPtrConstant(8, dl));
20493 Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
20494 Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
20495 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
20496 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20499 static SDValue LowerZERO_EXTEND_Mask(SDValue Op, const SDLoc &DL,
20500 const X86Subtarget &Subtarget,
20501 SelectionDAG &DAG) {
20502 MVT VT = Op->getSimpleValueType(0);
20503 SDValue In = Op->getOperand(0);
20504 MVT InVT = In.getSimpleValueType();
20505 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
20506 unsigned NumElts = VT.getVectorNumElements();
20508 // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
20509 // avoids a constant pool load.
20510 if (VT.getVectorElementType() != MVT::i8) {
20511 SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
20512 return DAG.getNode(ISD::SRL, DL, VT, Extend,
20513 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
20516 // Extend VT if BWI is not supported.
20517 MVT ExtVT = VT;
20518 if (!Subtarget.hasBWI()) {
20519 // If v16i32 is to be avoided, we'll need to split and concatenate.
20520 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20521 return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
20523 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20526 // Widen to 512-bits if VLX is not supported.
20527 MVT WideVT = ExtVT;
20528 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20529 NumElts *= 512 / ExtVT.getSizeInBits();
20530 InVT = MVT::getVectorVT(MVT::i1, NumElts);
20531 In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
20532 In, DAG.getIntPtrConstant(0, DL));
20533 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
20534 NumElts);
20537 SDValue One = DAG.getConstant(1, DL, WideVT);
20538 SDValue Zero = DAG.getConstant(0, DL, WideVT);
20540 SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
20542 // Truncate if we had to extend above.
20543 if (VT != ExtVT) {
20544 WideVT = MVT::getVectorVT(MVT::i8, NumElts);
20545 SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
20548 // Extract back to 128/256-bit if we widened.
20549 if (WideVT != VT)
20550 SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
20551 DAG.getIntPtrConstant(0, DL));
20553 return SelectedVal;
20556 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20557 SelectionDAG &DAG) {
20558 SDValue In = Op.getOperand(0);
20559 MVT SVT = In.getSimpleValueType();
20560 SDLoc DL(Op);
20562 if (SVT.getVectorElementType() == MVT::i1)
20563 return LowerZERO_EXTEND_Mask(Op, DL, Subtarget, DAG);
20565 assert(Subtarget.hasAVX() && "Expected AVX support");
20566 return LowerAVXExtend(Op, DL, DAG, Subtarget);
20569 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
20570 /// It makes use of the fact that vectors with enough leading sign/zero bits
20571 /// prevent the PACKSS/PACKUS from saturating the results.
20572 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
20573 /// within each 128-bit lane.
20574 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
20575 const SDLoc &DL, SelectionDAG &DAG,
20576 const X86Subtarget &Subtarget) {
20577 assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
20578 "Unexpected PACK opcode");
20579 assert(DstVT.isVector() && "VT not a vector?");
20581 // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
20582 if (!Subtarget.hasSSE2())
20583 return SDValue();
20585 EVT SrcVT = In.getValueType();
20587 // No truncation required, we might get here due to recursive calls.
20588 if (SrcVT == DstVT)
20589 return In;
20591 unsigned NumElems = SrcVT.getVectorNumElements();
20592 if (NumElems < 2 || !isPowerOf2_32(NumElems) )
20593 return SDValue();
20595 unsigned DstSizeInBits = DstVT.getSizeInBits();
20596 unsigned SrcSizeInBits = SrcVT.getSizeInBits();
20597 assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
20598 assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
20600 LLVMContext &Ctx = *DAG.getContext();
20601 EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
20602 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20604 // Pack to the largest type possible:
20605 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
20606 EVT InVT = MVT::i16, OutVT = MVT::i8;
20607 if (SrcVT.getScalarSizeInBits() > 16 &&
20608 (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
20609 InVT = MVT::i32;
20610 OutVT = MVT::i16;
20613 // Sub-128-bit truncation - widen to 128-bit src and pack in the lower half.
20614 // On pre-AVX512, pack the src in both halves to help value tracking.
20615 if (SrcSizeInBits <= 128) {
20616 InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
20617 OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
20618 In = widenSubVector(In, false, Subtarget, DAG, DL, 128);
20619 SDValue LHS = DAG.getBitcast(InVT, In);
20620 SDValue RHS = Subtarget.hasAVX512() ? DAG.getUNDEF(InVT) : LHS;
20621 SDValue Res = DAG.getNode(Opcode, DL, OutVT, LHS, RHS);
20622 Res = extractSubVector(Res, 0, DAG, DL, SrcSizeInBits / 2);
20623 Res = DAG.getBitcast(PackedVT, Res);
20624 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20627 // Split lower/upper subvectors.
20628 SDValue Lo, Hi;
20629 std::tie(Lo, Hi) = splitVector(In, DAG, DL);
20631 // If Hi is undef, then don't bother packing it and widen the result instead.
20632 if (Hi.isUndef()) {
20633 EVT DstHalfVT = DstVT.getHalfNumVectorElementsVT(Ctx);
20634 if (SDValue Res =
20635 truncateVectorWithPACK(Opcode, DstHalfVT, Lo, DL, DAG, Subtarget))
20636 return widenSubVector(Res, false, Subtarget, DAG, DL, DstSizeInBits);
20639 unsigned SubSizeInBits = SrcSizeInBits / 2;
20640 InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
20641 OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
20643 // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
20644 if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
20645 Lo = DAG.getBitcast(InVT, Lo);
20646 Hi = DAG.getBitcast(InVT, Hi);
20647 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20648 return DAG.getBitcast(DstVT, Res);
20651 // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
20652 // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
20653 if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
20654 Lo = DAG.getBitcast(InVT, Lo);
20655 Hi = DAG.getBitcast(InVT, Hi);
20656 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20658 // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
20659 // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
20660 // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
20661 SmallVector<int, 64> Mask;
20662 int Scale = 64 / OutVT.getScalarSizeInBits();
20663 narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
20664 Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
20666 if (DstVT.is256BitVector())
20667 return DAG.getBitcast(DstVT, Res);
20669 // If 512bit -> 128bit truncate another stage.
20670 Res = DAG.getBitcast(PackedVT, Res);
20671 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20674 // Recursively pack lower/upper subvectors, concat result and pack again.
20675 assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
20677 if (PackedVT.is128BitVector()) {
20678 // Avoid CONCAT_VECTORS on sub-128bit nodes as these can fail after
20679 // type legalization.
20680 SDValue Res =
20681 truncateVectorWithPACK(Opcode, PackedVT, In, DL, DAG, Subtarget);
20682 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20685 EVT HalfPackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
20686 Lo = truncateVectorWithPACK(Opcode, HalfPackedVT, Lo, DL, DAG, Subtarget);
20687 Hi = truncateVectorWithPACK(Opcode, HalfPackedVT, Hi, DL, DAG, Subtarget);
20688 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
20689 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20692 /// Truncate using inreg zero extension (AND mask) and X86ISD::PACKUS.
20693 /// e.g. trunc <8 x i32> X to <8 x i16> -->
20694 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
20695 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
20696 static SDValue truncateVectorWithPACKUS(EVT DstVT, SDValue In, const SDLoc &DL,
20697 const X86Subtarget &Subtarget,
20698 SelectionDAG &DAG) {
20699 In = DAG.getZeroExtendInReg(In, DL, DstVT);
20700 return truncateVectorWithPACK(X86ISD::PACKUS, DstVT, In, DL, DAG, Subtarget);
20703 /// Truncate using inreg sign extension and X86ISD::PACKSS.
20704 static SDValue truncateVectorWithPACKSS(EVT DstVT, SDValue In, const SDLoc &DL,
20705 const X86Subtarget &Subtarget,
20706 SelectionDAG &DAG) {
20707 EVT SrcVT = In.getValueType();
20708 In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, SrcVT, In,
20709 DAG.getValueType(DstVT));
20710 return truncateVectorWithPACK(X86ISD::PACKSS, DstVT, In, DL, DAG, Subtarget);
20713 /// Helper to determine if \p In truncated to \p DstVT has the necessary
20714 /// signbits / leading zero bits to be truncated with PACKSS / PACKUS,
20715 /// possibly by converting a SRL node to SRA for sign extension.
20716 static SDValue matchTruncateWithPACK(unsigned &PackOpcode, EVT DstVT,
20717 SDValue In, const SDLoc &DL,
20718 SelectionDAG &DAG,
20719 const X86Subtarget &Subtarget) {
20720 // Requires SSE2.
20721 if (!Subtarget.hasSSE2())
20722 return SDValue();
20724 EVT SrcVT = In.getValueType();
20725 EVT DstSVT = DstVT.getVectorElementType();
20726 EVT SrcSVT = SrcVT.getVectorElementType();
20727 unsigned NumDstEltBits = DstSVT.getSizeInBits();
20728 unsigned NumSrcEltBits = SrcSVT.getSizeInBits();
20730 // Check we have a truncation suited for PACKSS/PACKUS.
20731 if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20732 (DstSVT == MVT::i8 || DstSVT == MVT::i16 || DstSVT == MVT::i32)))
20733 return SDValue();
20735 assert(NumSrcEltBits > NumDstEltBits && "Bad truncation");
20736 unsigned NumStages = Log2_32(NumSrcEltBits / NumDstEltBits);
20738 // Truncation from 128-bit to vXi32 can be better handled with PSHUFD.
20739 // Truncation to sub-64-bit vXi16 can be better handled with PSHUFD/PSHUFLW.
20740 // Truncation from v2i64 to v2i8 can be better handled with PSHUFB.
20741 if ((DstSVT == MVT::i32 && SrcVT.getSizeInBits() <= 128) ||
20742 (DstSVT == MVT::i16 && SrcVT.getSizeInBits() <= (64 * NumStages)) ||
20743 (DstVT == MVT::v2i8 && SrcVT == MVT::v2i64 && Subtarget.hasSSSE3()))
20744 return SDValue();
20746 // Prefer to lower v4i64 -> v4i32 as a shuffle unless we can cheaply
20747 // split this for packing.
20748 if (SrcVT == MVT::v4i64 && DstVT == MVT::v4i32 &&
20749 !isFreeToSplitVector(In.getNode(), DAG) &&
20750 (!Subtarget.hasAVX() || DAG.ComputeNumSignBits(In) != 64))
20751 return SDValue();
20753 // Don't truncate AVX512 targets as multiple PACK nodes stages.
20754 if (Subtarget.hasAVX512() && NumStages > 1)
20755 return SDValue();
20757 unsigned NumPackedSignBits = std::min<unsigned>(NumDstEltBits, 16);
20758 unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
20760 // Truncate with PACKUS if we are truncating a vector with leading zero
20761 // bits that extend all the way to the packed/truncated value.
20762 // e.g. Masks, zext_in_reg, etc.
20763 // Pre-SSE41 we can only use PACKUSWB.
20764 KnownBits Known = DAG.computeKnownBits(In);
20765 if ((NumSrcEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros()) {
20766 PackOpcode = X86ISD::PACKUS;
20767 return In;
20770 // Truncate with PACKSS if we are truncating a vector with sign-bits
20771 // that extend all the way to the packed/truncated value.
20772 // e.g. Comparison result, sext_in_reg, etc.
20773 unsigned NumSignBits = DAG.ComputeNumSignBits(In);
20775 // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
20776 // a sign splat (or AVX512 VPSRAQ support). ComputeNumSignBits struggles to
20777 // see through BITCASTs later on and combines/simplifications can't then use
20778 // it.
20779 if (DstSVT == MVT::i32 && NumSignBits != NumSrcEltBits &&
20780 !Subtarget.hasAVX512())
20781 return SDValue();
20783 unsigned MinSignBits = NumSrcEltBits - NumPackedSignBits;
20784 if (MinSignBits < NumSignBits) {
20785 PackOpcode = X86ISD::PACKSS;
20786 return In;
20789 // If we have a srl that only generates signbits that we will discard in
20790 // the truncation then we can use PACKSS by converting the srl to a sra.
20791 // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
20792 if (In.getOpcode() == ISD::SRL && In->hasOneUse())
20793 if (std::optional<uint64_t> ShAmt = DAG.getValidShiftAmount(In)) {
20794 if (*ShAmt == MinSignBits) {
20795 PackOpcode = X86ISD::PACKSS;
20796 return DAG.getNode(ISD::SRA, DL, SrcVT, In->ops());
20800 return SDValue();
20803 /// This function lowers a vector truncation of 'extended sign-bits' or
20804 /// 'extended zero-bits' values.
20805 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
20806 static SDValue LowerTruncateVecPackWithSignBits(MVT DstVT, SDValue In,
20807 const SDLoc &DL,
20808 const X86Subtarget &Subtarget,
20809 SelectionDAG &DAG) {
20810 MVT SrcVT = In.getSimpleValueType();
20811 MVT DstSVT = DstVT.getVectorElementType();
20812 MVT SrcSVT = SrcVT.getVectorElementType();
20813 if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20814 (DstSVT == MVT::i8 || DstSVT == MVT::i16 || DstSVT == MVT::i32)))
20815 return SDValue();
20817 // If the upper half of the source is undef, then attempt to split and
20818 // only truncate the lower half.
20819 if (DstVT.getSizeInBits() >= 128) {
20820 SmallVector<SDValue> LowerOps;
20821 if (SDValue Lo = isUpperSubvectorUndef(In, DL, DAG)) {
20822 MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
20823 if (SDValue Res = LowerTruncateVecPackWithSignBits(DstHalfVT, Lo, DL,
20824 Subtarget, DAG))
20825 return widenSubVector(Res, false, Subtarget, DAG, DL,
20826 DstVT.getSizeInBits());
20830 unsigned PackOpcode;
20831 if (SDValue Src =
20832 matchTruncateWithPACK(PackOpcode, DstVT, In, DL, DAG, Subtarget))
20833 return truncateVectorWithPACK(PackOpcode, DstVT, Src, DL, DAG, Subtarget);
20835 return SDValue();
20838 /// This function lowers a vector truncation from vXi32/vXi64 to vXi8/vXi16 into
20839 /// X86ISD::PACKUS/X86ISD::PACKSS operations.
20840 static SDValue LowerTruncateVecPack(MVT DstVT, SDValue In, const SDLoc &DL,
20841 const X86Subtarget &Subtarget,
20842 SelectionDAG &DAG) {
20843 MVT SrcVT = In.getSimpleValueType();
20844 MVT DstSVT = DstVT.getVectorElementType();
20845 MVT SrcSVT = SrcVT.getVectorElementType();
20846 unsigned NumElems = DstVT.getVectorNumElements();
20847 if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20848 (DstSVT == MVT::i8 || DstSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
20849 NumElems >= 8))
20850 return SDValue();
20852 // SSSE3's pshufb results in less instructions in the cases below.
20853 if (Subtarget.hasSSSE3() && NumElems == 8) {
20854 if (SrcSVT == MVT::i16)
20855 return SDValue();
20856 if (SrcSVT == MVT::i32 && (DstSVT == MVT::i8 || !Subtarget.hasSSE41()))
20857 return SDValue();
20860 // If the upper half of the source is undef, then attempt to split and
20861 // only truncate the lower half.
20862 if (DstVT.getSizeInBits() >= 128) {
20863 SmallVector<SDValue> LowerOps;
20864 if (SDValue Lo = isUpperSubvectorUndef(In, DL, DAG)) {
20865 MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
20866 if (SDValue Res = LowerTruncateVecPack(DstHalfVT, Lo, DL, Subtarget, DAG))
20867 return widenSubVector(Res, false, Subtarget, DAG, DL,
20868 DstVT.getSizeInBits());
20872 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
20873 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
20874 // truncate 2 x v4i32 to v8i16.
20875 if (Subtarget.hasSSE41() || DstSVT == MVT::i8)
20876 return truncateVectorWithPACKUS(DstVT, In, DL, Subtarget, DAG);
20878 if (SrcSVT == MVT::i16 || SrcSVT == MVT::i32)
20879 return truncateVectorWithPACKSS(DstVT, In, DL, Subtarget, DAG);
20881 // Special case vXi64 -> vXi16, shuffle to vXi32 and then use PACKSS.
20882 if (DstSVT == MVT::i16 && SrcSVT == MVT::i64) {
20883 MVT TruncVT = MVT::getVectorVT(MVT::i32, NumElems);
20884 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, In);
20885 return truncateVectorWithPACKSS(DstVT, Trunc, DL, Subtarget, DAG);
20888 return SDValue();
20891 static SDValue LowerTruncateVecI1(SDValue Op, const SDLoc &DL,
20892 SelectionDAG &DAG,
20893 const X86Subtarget &Subtarget) {
20894 MVT VT = Op.getSimpleValueType();
20895 SDValue In = Op.getOperand(0);
20896 MVT InVT = In.getSimpleValueType();
20897 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
20899 // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
20900 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
20901 if (InVT.getScalarSizeInBits() <= 16) {
20902 if (Subtarget.hasBWI()) {
20903 // legal, will go to VPMOVB2M, VPMOVW2M
20904 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20905 // We need to shift to get the lsb into sign position.
20906 // Shift packed bytes not supported natively, bitcast to word
20907 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
20908 In = DAG.getNode(ISD::SHL, DL, ExtVT,
20909 DAG.getBitcast(ExtVT, In),
20910 DAG.getConstant(ShiftInx, DL, ExtVT));
20911 In = DAG.getBitcast(InVT, In);
20913 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
20914 In, ISD::SETGT);
20916 // Use TESTD/Q, extended vector to packed dword/qword.
20917 assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
20918 "Unexpected vector type.");
20919 unsigned NumElts = InVT.getVectorNumElements();
20920 assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
20921 // We need to change to a wider element type that we have support for.
20922 // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
20923 // For 16 element vectors we extend to v16i32 unless we are explicitly
20924 // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
20925 // we need to split into two 8 element vectors which we can extend to v8i32,
20926 // truncate and concat the results. There's an additional complication if
20927 // the original type is v16i8. In that case we can't split the v16i8
20928 // directly, so we need to shuffle high elements to low and use
20929 // sign_extend_vector_inreg.
20930 if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
20931 SDValue Lo, Hi;
20932 if (InVT == MVT::v16i8) {
20933 Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
20934 Hi = DAG.getVectorShuffle(
20935 InVT, DL, In, In,
20936 {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
20937 Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
20938 } else {
20939 assert(InVT == MVT::v16i16 && "Unexpected VT!");
20940 Lo = extract128BitVector(In, 0, DAG, DL);
20941 Hi = extract128BitVector(In, 8, DAG, DL);
20943 // We're split now, just emit two truncates and a concat. The two
20944 // truncates will trigger legalization to come back to this function.
20945 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
20946 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
20947 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20949 // We either have 8 elements or we're allowed to use 512-bit vectors.
20950 // If we have VLX, we want to use the narrowest vector that can get the
20951 // job done so we use vXi32.
20952 MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
20953 MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
20954 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
20955 InVT = ExtVT;
20956 ShiftInx = InVT.getScalarSizeInBits() - 1;
20959 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20960 // We need to shift to get the lsb into sign position.
20961 In = DAG.getNode(ISD::SHL, DL, InVT, In,
20962 DAG.getConstant(ShiftInx, DL, InVT));
20964 // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
20965 if (Subtarget.hasDQI())
20966 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
20967 return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
20970 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
20971 SDLoc DL(Op);
20972 MVT VT = Op.getSimpleValueType();
20973 SDValue In = Op.getOperand(0);
20974 MVT InVT = In.getSimpleValueType();
20975 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20976 "Invalid TRUNCATE operation");
20978 // If we're called by the type legalizer, handle a few cases.
20979 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20980 if (!TLI.isTypeLegal(VT) || !TLI.isTypeLegal(InVT)) {
20981 if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
20982 VT.is128BitVector() && Subtarget.hasAVX512()) {
20983 assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
20984 "Unexpected subtarget!");
20985 // The default behavior is to truncate one step, concatenate, and then
20986 // truncate the remainder. We'd rather produce two 64-bit results and
20987 // concatenate those.
20988 SDValue Lo, Hi;
20989 std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
20991 EVT LoVT, HiVT;
20992 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
20994 Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
20995 Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
20996 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20999 // Pre-AVX512 (or prefer-256bit) see if we can make use of PACKSS/PACKUS.
21000 if (!Subtarget.hasAVX512() ||
21001 (InVT.is512BitVector() && VT.is256BitVector()))
21002 if (SDValue SignPack =
21003 LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
21004 return SignPack;
21006 // Pre-AVX512 see if we can make use of PACKSS/PACKUS.
21007 if (!Subtarget.hasAVX512())
21008 return LowerTruncateVecPack(VT, In, DL, Subtarget, DAG);
21010 // Otherwise let default legalization handle it.
21011 return SDValue();
21014 if (VT.getVectorElementType() == MVT::i1)
21015 return LowerTruncateVecI1(Op, DL, DAG, Subtarget);
21017 // Attempt to truncate with PACKUS/PACKSS even on AVX512 if we'd have to
21018 // concat from subvectors to use VPTRUNC etc.
21019 if (!Subtarget.hasAVX512() || isFreeToSplitVector(In.getNode(), DAG))
21020 if (SDValue SignPack =
21021 LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
21022 return SignPack;
21024 // vpmovqb/w/d, vpmovdb/w, vpmovwb
21025 if (Subtarget.hasAVX512()) {
21026 if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
21027 assert(VT == MVT::v32i8 && "Unexpected VT!");
21028 return splitVectorIntUnary(Op, DAG, DL);
21031 // word to byte only under BWI. Otherwise we have to promoted to v16i32
21032 // and then truncate that. But we should only do that if we haven't been
21033 // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
21034 // handled by isel patterns.
21035 if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
21036 Subtarget.canExtendTo512DQ())
21037 return Op;
21040 // Handle truncation of V256 to V128 using shuffles.
21041 assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
21043 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
21044 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
21045 if (Subtarget.hasInt256()) {
21046 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
21047 In = DAG.getBitcast(MVT::v8i32, In);
21048 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
21049 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
21050 DAG.getIntPtrConstant(0, DL));
21053 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
21054 DAG.getIntPtrConstant(0, DL));
21055 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
21056 DAG.getIntPtrConstant(2, DL));
21057 static const int ShufMask[] = {0, 2, 4, 6};
21058 return DAG.getVectorShuffle(VT, DL, DAG.getBitcast(MVT::v4i32, OpLo),
21059 DAG.getBitcast(MVT::v4i32, OpHi), ShufMask);
21062 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
21063 // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
21064 if (Subtarget.hasInt256()) {
21065 // The PSHUFB mask:
21066 static const int ShufMask1[] = { 0, 1, 4, 5, 8, 9, 12, 13,
21067 -1, -1, -1, -1, -1, -1, -1, -1,
21068 16, 17, 20, 21, 24, 25, 28, 29,
21069 -1, -1, -1, -1, -1, -1, -1, -1 };
21070 In = DAG.getBitcast(MVT::v32i8, In);
21071 In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
21072 In = DAG.getBitcast(MVT::v4i64, In);
21074 static const int ShufMask2[] = {0, 2, -1, -1};
21075 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
21076 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
21077 DAG.getIntPtrConstant(0, DL));
21078 return DAG.getBitcast(MVT::v8i16, In);
21081 return Subtarget.hasSSE41()
21082 ? truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG)
21083 : truncateVectorWithPACKSS(VT, In, DL, Subtarget, DAG);
21086 if (VT == MVT::v16i8 && InVT == MVT::v16i16)
21087 return truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG);
21089 llvm_unreachable("All 256->128 cases should have been handled above!");
21092 // We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
21093 // behaves on out of range inputs to generate optimized conversions.
21094 static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
21095 SelectionDAG &DAG,
21096 const X86Subtarget &Subtarget) {
21097 MVT SrcVT = Src.getSimpleValueType();
21098 unsigned DstBits = VT.getScalarSizeInBits();
21099 assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported");
21101 // Calculate the converted result for values in the range 0 to
21102 // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
21103 SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
21104 SDValue Big =
21105 DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
21106 DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
21107 DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
21109 // The "CVTTP2SI" instruction conveniently sets the sign bit if
21110 // and only if the value was out of range. So we can use that
21111 // as our indicator that we rather use "Big" instead of "Small".
21113 // Use "Small" if "IsOverflown" has all bits cleared
21114 // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
21116 // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
21117 // use the slightly slower blendv select instead.
21118 if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
21119 SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
21120 return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
21123 SDValue IsOverflown =
21124 DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
21125 DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
21126 return DAG.getNode(ISD::OR, dl, VT, Small,
21127 DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
21130 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
21131 bool IsStrict = Op->isStrictFPOpcode();
21132 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
21133 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
21134 MVT VT = Op->getSimpleValueType(0);
21135 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21136 SDValue Chain = IsStrict ? Op->getOperand(0) : SDValue();
21137 MVT SrcVT = Src.getSimpleValueType();
21138 SDLoc dl(Op);
21140 SDValue Res;
21141 if (isSoftF16(SrcVT, Subtarget)) {
21142 MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
21143 if (IsStrict)
21144 return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
21145 {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
21146 {NVT, MVT::Other}, {Chain, Src})});
21147 return DAG.getNode(Op.getOpcode(), dl, VT,
21148 DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
21149 } else if (isTypeLegal(SrcVT) && isLegalConversion(VT, IsSigned, Subtarget)) {
21150 return Op;
21153 if (VT.isVector()) {
21154 if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
21155 MVT ResVT = MVT::v4i32;
21156 MVT TruncVT = MVT::v4i1;
21157 unsigned Opc;
21158 if (IsStrict)
21159 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
21160 else
21161 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21163 if (!IsSigned && !Subtarget.hasVLX()) {
21164 assert(Subtarget.useAVX512Regs() && "Unexpected features!");
21165 // Widen to 512-bits.
21166 ResVT = MVT::v8i32;
21167 TruncVT = MVT::v8i1;
21168 Opc = Op.getOpcode();
21169 // Need to concat with zero vector for strict fp to avoid spurious
21170 // exceptions.
21171 // TODO: Should we just do this for non-strict as well?
21172 SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
21173 : DAG.getUNDEF(MVT::v8f64);
21174 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
21175 DAG.getIntPtrConstant(0, dl));
21177 if (IsStrict) {
21178 Res = DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Chain, Src});
21179 Chain = Res.getValue(1);
21180 } else {
21181 Res = DAG.getNode(Opc, dl, ResVT, Src);
21184 Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
21185 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
21186 DAG.getIntPtrConstant(0, dl));
21187 if (IsStrict)
21188 return DAG.getMergeValues({Res, Chain}, dl);
21189 return Res;
21192 if (Subtarget.hasFP16() && SrcVT.getVectorElementType() == MVT::f16) {
21193 if (VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16)
21194 return Op;
21196 MVT ResVT = VT;
21197 MVT EleVT = VT.getVectorElementType();
21198 if (EleVT != MVT::i64)
21199 ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
21201 if (SrcVT != MVT::v8f16) {
21202 SDValue Tmp =
21203 IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
21204 SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
21205 Ops[0] = Src;
21206 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
21209 if (IsStrict) {
21210 Res = DAG.getNode(IsSigned ? X86ISD::STRICT_CVTTP2SI
21211 : X86ISD::STRICT_CVTTP2UI,
21212 dl, {ResVT, MVT::Other}, {Chain, Src});
21213 Chain = Res.getValue(1);
21214 } else {
21215 Res = DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl,
21216 ResVT, Src);
21219 // TODO: Need to add exception check code for strict FP.
21220 if (EleVT.getSizeInBits() < 16) {
21221 ResVT = MVT::getVectorVT(EleVT, 8);
21222 Res = DAG.getNode(ISD::TRUNCATE, dl, ResVT, Res);
21225 if (ResVT != VT)
21226 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21227 DAG.getIntPtrConstant(0, dl));
21229 if (IsStrict)
21230 return DAG.getMergeValues({Res, Chain}, dl);
21231 return Res;
21234 // v8f32/v16f32/v8f64->v8i16/v16i16 need to widen first.
21235 if (VT.getVectorElementType() == MVT::i16) {
21236 assert((SrcVT.getVectorElementType() == MVT::f32 ||
21237 SrcVT.getVectorElementType() == MVT::f64) &&
21238 "Expected f32/f64 vector!");
21239 MVT NVT = VT.changeVectorElementType(MVT::i32);
21240 if (IsStrict) {
21241 Res = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
21242 : ISD::STRICT_FP_TO_UINT,
21243 dl, {NVT, MVT::Other}, {Chain, Src});
21244 Chain = Res.getValue(1);
21245 } else {
21246 Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl,
21247 NVT, Src);
21250 // TODO: Need to add exception check code for strict FP.
21251 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21253 if (IsStrict)
21254 return DAG.getMergeValues({Res, Chain}, dl);
21255 return Res;
21258 // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
21259 if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
21260 assert(!IsSigned && "Expected unsigned conversion!");
21261 assert(Subtarget.useAVX512Regs() && "Requires avx512f");
21262 return Op;
21265 // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
21266 if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
21267 (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
21268 Subtarget.useAVX512Regs()) {
21269 assert(!IsSigned && "Expected unsigned conversion!");
21270 assert(!Subtarget.hasVLX() && "Unexpected features!");
21271 MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
21272 MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
21273 // Need to concat with zero vector for strict fp to avoid spurious
21274 // exceptions.
21275 // TODO: Should we just do this for non-strict as well?
21276 SDValue Tmp =
21277 IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21278 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21279 DAG.getIntPtrConstant(0, dl));
21281 if (IsStrict) {
21282 Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
21283 {Chain, Src});
21284 Chain = Res.getValue(1);
21285 } else {
21286 Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
21289 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21290 DAG.getIntPtrConstant(0, dl));
21292 if (IsStrict)
21293 return DAG.getMergeValues({Res, Chain}, dl);
21294 return Res;
21297 // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
21298 if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
21299 (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
21300 Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
21301 assert(!Subtarget.hasVLX() && "Unexpected features!");
21302 MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
21303 // Need to concat with zero vector for strict fp to avoid spurious
21304 // exceptions.
21305 // TODO: Should we just do this for non-strict as well?
21306 SDValue Tmp =
21307 IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21308 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21309 DAG.getIntPtrConstant(0, dl));
21311 if (IsStrict) {
21312 Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21313 {Chain, Src});
21314 Chain = Res.getValue(1);
21315 } else {
21316 Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
21319 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21320 DAG.getIntPtrConstant(0, dl));
21322 if (IsStrict)
21323 return DAG.getMergeValues({Res, Chain}, dl);
21324 return Res;
21327 if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
21328 if (!Subtarget.hasVLX()) {
21329 // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
21330 // legalizer and then widened again by vector op legalization.
21331 if (!IsStrict)
21332 return SDValue();
21334 SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
21335 SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
21336 {Src, Zero, Zero, Zero});
21337 Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21338 {Chain, Tmp});
21339 SDValue Chain = Tmp.getValue(1);
21340 Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
21341 DAG.getIntPtrConstant(0, dl));
21342 return DAG.getMergeValues({Tmp, Chain}, dl);
21345 assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
21346 SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
21347 DAG.getUNDEF(MVT::v2f32));
21348 if (IsStrict) {
21349 unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
21350 : X86ISD::STRICT_CVTTP2UI;
21351 return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
21353 unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21354 return DAG.getNode(Opc, dl, VT, Tmp);
21357 // Generate optimized instructions for pre AVX512 unsigned conversions from
21358 // vXf32 to vXi32.
21359 if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
21360 (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
21361 (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
21362 assert(!IsSigned && "Expected unsigned conversion!");
21363 return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
21366 return SDValue();
21369 assert(!VT.isVector());
21371 bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
21373 if (!IsSigned && UseSSEReg) {
21374 // Conversions from f32/f64 with AVX512 should be legal.
21375 if (Subtarget.hasAVX512())
21376 return Op;
21378 // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
21379 // behaves on out of range inputs to generate optimized conversions.
21380 if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
21381 (VT == MVT::i64 && Subtarget.is64Bit()))) {
21382 unsigned DstBits = VT.getScalarSizeInBits();
21383 APInt UIntLimit = APInt::getSignMask(DstBits);
21384 SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
21385 DAG.getConstant(UIntLimit, dl, VT));
21386 MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
21388 // Calculate the converted result for values in the range:
21389 // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
21390 // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
21391 SDValue Small =
21392 DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
21393 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
21394 SDValue Big = DAG.getNode(
21395 X86ISD::CVTTS2SI, dl, VT,
21396 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
21397 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
21399 // The "CVTTS2SI" instruction conveniently sets the sign bit if
21400 // and only if the value was out of range. So we can use that
21401 // as our indicator that we rather use "Big" instead of "Small".
21403 // Use "Small" if "IsOverflown" has all bits cleared
21404 // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
21405 SDValue IsOverflown = DAG.getNode(
21406 ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
21407 return DAG.getNode(ISD::OR, dl, VT, Small,
21408 DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
21411 // Use default expansion for i64.
21412 if (VT == MVT::i64)
21413 return SDValue();
21415 assert(VT == MVT::i32 && "Unexpected VT!");
21417 // Promote i32 to i64 and use a signed operation on 64-bit targets.
21418 // FIXME: This does not generate an invalid exception if the input does not
21419 // fit in i32. PR44019
21420 if (Subtarget.is64Bit()) {
21421 if (IsStrict) {
21422 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i64, MVT::Other},
21423 {Chain, Src});
21424 Chain = Res.getValue(1);
21425 } else
21426 Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
21428 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21429 if (IsStrict)
21430 return DAG.getMergeValues({Res, Chain}, dl);
21431 return Res;
21434 // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
21435 // use fisttp which will be handled later.
21436 if (!Subtarget.hasSSE3())
21437 return SDValue();
21440 // Promote i16 to i32 if we can use a SSE operation or the type is f128.
21441 // FIXME: This does not generate an invalid exception if the input does not
21442 // fit in i16. PR44019
21443 if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
21444 assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
21445 if (IsStrict) {
21446 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i32, MVT::Other},
21447 {Chain, Src});
21448 Chain = Res.getValue(1);
21449 } else
21450 Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
21452 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21453 if (IsStrict)
21454 return DAG.getMergeValues({Res, Chain}, dl);
21455 return Res;
21458 // If this is a FP_TO_SINT using SSEReg we're done.
21459 if (UseSSEReg && IsSigned)
21460 return Op;
21462 // fp128 needs to use a libcall.
21463 if (SrcVT == MVT::f128) {
21464 RTLIB::Libcall LC;
21465 if (IsSigned)
21466 LC = RTLIB::getFPTOSINT(SrcVT, VT);
21467 else
21468 LC = RTLIB::getFPTOUINT(SrcVT, VT);
21470 MakeLibCallOptions CallOptions;
21471 std::pair<SDValue, SDValue> Tmp =
21472 makeLibCall(DAG, LC, VT, Src, CallOptions, dl, Chain);
21474 if (IsStrict)
21475 return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
21477 return Tmp.first;
21480 // Fall back to X87.
21481 if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
21482 if (IsStrict)
21483 return DAG.getMergeValues({V, Chain}, dl);
21484 return V;
21487 llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
21490 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
21491 SelectionDAG &DAG) const {
21492 SDValue Src = Op.getOperand(0);
21493 EVT DstVT = Op.getSimpleValueType();
21494 MVT SrcVT = Src.getSimpleValueType();
21496 if (SrcVT.isVector())
21497 return DstVT.getScalarType() == MVT::i32 ? Op : SDValue();
21499 if (SrcVT == MVT::f16)
21500 return SDValue();
21502 // If the source is in an SSE register, the node is Legal.
21503 if (isScalarFPTypeInSSEReg(SrcVT))
21504 return Op;
21506 return LRINT_LLRINTHelper(Op.getNode(), DAG);
21509 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
21510 SelectionDAG &DAG) const {
21511 EVT DstVT = N->getValueType(0);
21512 SDValue Src = N->getOperand(0);
21513 EVT SrcVT = Src.getValueType();
21515 if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
21516 // f16 must be promoted before using the lowering in this routine.
21517 // fp128 does not use this lowering.
21518 return SDValue();
21521 SDLoc DL(N);
21522 SDValue Chain = DAG.getEntryNode();
21524 bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
21526 // If we're converting from SSE, the stack slot needs to hold both types.
21527 // Otherwise it only needs to hold the DstVT.
21528 EVT OtherVT = UseSSE ? SrcVT : DstVT;
21529 SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
21530 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
21531 MachinePointerInfo MPI =
21532 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
21534 if (UseSSE) {
21535 assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
21536 Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
21537 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21538 SDValue Ops[] = { Chain, StackPtr };
21540 Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
21541 /*Align*/ std::nullopt,
21542 MachineMemOperand::MOLoad);
21543 Chain = Src.getValue(1);
21546 SDValue StoreOps[] = { Chain, Src, StackPtr };
21547 Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
21548 StoreOps, DstVT, MPI, /*Align*/ std::nullopt,
21549 MachineMemOperand::MOStore);
21551 return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
21554 SDValue
21555 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
21556 // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
21557 // but making use of X86 specifics to produce better instruction sequences.
21558 SDNode *Node = Op.getNode();
21559 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
21560 unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
21561 SDLoc dl(SDValue(Node, 0));
21562 SDValue Src = Node->getOperand(0);
21564 // There are three types involved here: SrcVT is the source floating point
21565 // type, DstVT is the type of the result, and TmpVT is the result of the
21566 // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
21567 // DstVT).
21568 EVT SrcVT = Src.getValueType();
21569 EVT DstVT = Node->getValueType(0);
21570 EVT TmpVT = DstVT;
21572 // This code is only for floats and doubles. Fall back to generic code for
21573 // anything else.
21574 if (!isScalarFPTypeInSSEReg(SrcVT) || isSoftF16(SrcVT, Subtarget))
21575 return SDValue();
21577 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
21578 unsigned SatWidth = SatVT.getScalarSizeInBits();
21579 unsigned DstWidth = DstVT.getScalarSizeInBits();
21580 unsigned TmpWidth = TmpVT.getScalarSizeInBits();
21581 assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
21582 "Expected saturation width smaller than result width");
21584 // Promote result of FP_TO_*INT to at least 32 bits.
21585 if (TmpWidth < 32) {
21586 TmpVT = MVT::i32;
21587 TmpWidth = 32;
21590 // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
21591 // us to use a native signed conversion instead.
21592 if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
21593 TmpVT = MVT::i64;
21594 TmpWidth = 64;
21597 // If the saturation width is smaller than the size of the temporary result,
21598 // we can always use signed conversion, which is native.
21599 if (SatWidth < TmpWidth)
21600 FpToIntOpcode = ISD::FP_TO_SINT;
21602 // Determine minimum and maximum integer values and their corresponding
21603 // floating-point values.
21604 APInt MinInt, MaxInt;
21605 if (IsSigned) {
21606 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
21607 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
21608 } else {
21609 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
21610 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
21613 const fltSemantics &Sem = SrcVT.getFltSemantics();
21614 APFloat MinFloat(Sem);
21615 APFloat MaxFloat(Sem);
21617 APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
21618 MinInt, IsSigned, APFloat::rmTowardZero);
21619 APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
21620 MaxInt, IsSigned, APFloat::rmTowardZero);
21621 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
21622 && !(MaxStatus & APFloat::opStatus::opInexact);
21624 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
21625 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
21627 // If the integer bounds are exactly representable as floats, emit a
21628 // min+max+fptoi sequence. Otherwise use comparisons and selects.
21629 if (AreExactFloatBounds) {
21630 if (DstVT != TmpVT) {
21631 // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
21632 SDValue MinClamped = DAG.getNode(
21633 X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
21634 // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
21635 SDValue BothClamped = DAG.getNode(
21636 X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
21637 // Convert clamped value to integer.
21638 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
21640 // NaN will become INDVAL, with the top bit set and the rest zero.
21641 // Truncation will discard the top bit, resulting in zero.
21642 return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21645 // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
21646 SDValue MinClamped = DAG.getNode(
21647 X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
21648 // Clamp by MaxFloat from above. NaN cannot occur.
21649 SDValue BothClamped = DAG.getNode(
21650 X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
21651 // Convert clamped value to integer.
21652 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
21654 if (!IsSigned) {
21655 // In the unsigned case we're done, because we mapped NaN to MinFloat,
21656 // which is zero.
21657 return FpToInt;
21660 // Otherwise, select zero if Src is NaN.
21661 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21662 return DAG.getSelectCC(
21663 dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
21666 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
21667 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
21669 // Result of direct conversion, which may be selected away.
21670 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
21672 if (DstVT != TmpVT) {
21673 // NaN will become INDVAL, with the top bit set and the rest zero.
21674 // Truncation will discard the top bit, resulting in zero.
21675 FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21678 SDValue Select = FpToInt;
21679 // For signed conversions where we saturate to the same size as the
21680 // result type of the fptoi instructions, INDVAL coincides with integer
21681 // minimum, so we don't need to explicitly check it.
21682 if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
21683 // If Src ULT MinFloat, select MinInt. In particular, this also selects
21684 // MinInt if Src is NaN.
21685 Select = DAG.getSelectCC(
21686 dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
21689 // If Src OGT MaxFloat, select MaxInt.
21690 Select = DAG.getSelectCC(
21691 dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
21693 // In the unsigned case we are done, because we mapped NaN to MinInt, which
21694 // is already zero. The promoted case was already handled above.
21695 if (!IsSigned || DstVT != TmpVT) {
21696 return Select;
21699 // Otherwise, select 0 if Src is NaN.
21700 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21701 return DAG.getSelectCC(
21702 dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
21705 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
21706 bool IsStrict = Op->isStrictFPOpcode();
21708 SDLoc DL(Op);
21709 MVT VT = Op.getSimpleValueType();
21710 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21711 SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21712 MVT SVT = In.getSimpleValueType();
21714 // Let f16->f80 get lowered to a libcall, except for darwin, where we should
21715 // lower it to an fp_extend via f32 (as only f16<>f32 libcalls are available)
21716 if (VT == MVT::f128 || (SVT == MVT::f16 && VT == MVT::f80 &&
21717 !Subtarget.getTargetTriple().isOSDarwin()))
21718 return SDValue();
21720 if ((SVT == MVT::v8f16 && Subtarget.hasF16C()) ||
21721 (SVT == MVT::v16f16 && Subtarget.useAVX512Regs()))
21722 return Op;
21724 if (SVT == MVT::f16) {
21725 if (Subtarget.hasFP16())
21726 return Op;
21728 if (VT != MVT::f32) {
21729 if (IsStrict)
21730 return DAG.getNode(
21731 ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other},
21732 {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, DL,
21733 {MVT::f32, MVT::Other}, {Chain, In})});
21735 return DAG.getNode(ISD::FP_EXTEND, DL, VT,
21736 DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, In));
21739 if (!Subtarget.hasF16C()) {
21740 if (!Subtarget.getTargetTriple().isOSDarwin())
21741 return SDValue();
21743 assert(VT == MVT::f32 && SVT == MVT::f16 && "unexpected extend libcall");
21745 // Need a libcall, but ABI for f16 is soft-float on MacOS.
21746 TargetLowering::CallLoweringInfo CLI(DAG);
21747 Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21749 In = DAG.getBitcast(MVT::i16, In);
21750 TargetLowering::ArgListTy Args;
21751 TargetLowering::ArgListEntry Entry;
21752 Entry.Node = In;
21753 Entry.Ty = EVT(MVT::i16).getTypeForEVT(*DAG.getContext());
21754 Entry.IsSExt = false;
21755 Entry.IsZExt = true;
21756 Args.push_back(Entry);
21758 SDValue Callee = DAG.getExternalSymbol(
21759 getLibcallName(RTLIB::FPEXT_F16_F32),
21760 getPointerTy(DAG.getDataLayout()));
21761 CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
21762 CallingConv::C, EVT(VT).getTypeForEVT(*DAG.getContext()), Callee,
21763 std::move(Args));
21765 SDValue Res;
21766 std::tie(Res,Chain) = LowerCallTo(CLI);
21767 if (IsStrict)
21768 Res = DAG.getMergeValues({Res, Chain}, DL);
21770 return Res;
21773 In = DAG.getBitcast(MVT::i16, In);
21774 In = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16,
21775 getZeroVector(MVT::v8i16, Subtarget, DAG, DL), In,
21776 DAG.getIntPtrConstant(0, DL));
21777 SDValue Res;
21778 if (IsStrict) {
21779 Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, DL, {MVT::v4f32, MVT::Other},
21780 {Chain, In});
21781 Chain = Res.getValue(1);
21782 } else {
21783 Res = DAG.getNode(X86ISD::CVTPH2PS, DL, MVT::v4f32, In,
21784 DAG.getTargetConstant(4, DL, MVT::i32));
21786 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Res,
21787 DAG.getIntPtrConstant(0, DL));
21788 if (IsStrict)
21789 return DAG.getMergeValues({Res, Chain}, DL);
21790 return Res;
21793 if (!SVT.isVector() || SVT.getVectorElementType() == MVT::bf16)
21794 return Op;
21796 if (SVT.getVectorElementType() == MVT::f16) {
21797 if (Subtarget.hasFP16() && isTypeLegal(SVT))
21798 return Op;
21799 assert(Subtarget.hasF16C() && "Unexpected features!");
21800 if (SVT == MVT::v2f16)
21801 In = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f16, In,
21802 DAG.getUNDEF(MVT::v2f16));
21803 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f16, In,
21804 DAG.getUNDEF(MVT::v4f16));
21805 if (IsStrict)
21806 return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21807 {Op->getOperand(0), Res});
21808 return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21809 } else if (VT == MVT::v4f64 || VT == MVT::v8f64) {
21810 return Op;
21813 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
21815 SDValue Res =
21816 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
21817 if (IsStrict)
21818 return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21819 {Op->getOperand(0), Res});
21820 return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21823 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21824 bool IsStrict = Op->isStrictFPOpcode();
21826 SDLoc DL(Op);
21827 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21828 SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21829 MVT VT = Op.getSimpleValueType();
21830 MVT SVT = In.getSimpleValueType();
21832 if (SVT == MVT::f128 || (VT == MVT::f16 && SVT == MVT::f80))
21833 return SDValue();
21835 if (VT == MVT::f16 && (SVT == MVT::f64 || SVT == MVT::f32) &&
21836 !Subtarget.hasFP16() && (SVT == MVT::f64 || !Subtarget.hasF16C())) {
21837 if (!Subtarget.getTargetTriple().isOSDarwin())
21838 return SDValue();
21840 // We need a libcall but the ABI for f16 libcalls on MacOS is soft.
21841 TargetLowering::CallLoweringInfo CLI(DAG);
21842 Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21844 TargetLowering::ArgListTy Args;
21845 TargetLowering::ArgListEntry Entry;
21846 Entry.Node = In;
21847 Entry.Ty = EVT(SVT).getTypeForEVT(*DAG.getContext());
21848 Entry.IsSExt = false;
21849 Entry.IsZExt = true;
21850 Args.push_back(Entry);
21852 SDValue Callee = DAG.getExternalSymbol(
21853 getLibcallName(SVT == MVT::f64 ? RTLIB::FPROUND_F64_F16
21854 : RTLIB::FPROUND_F32_F16),
21855 getPointerTy(DAG.getDataLayout()));
21856 CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
21857 CallingConv::C, EVT(MVT::i16).getTypeForEVT(*DAG.getContext()), Callee,
21858 std::move(Args));
21860 SDValue Res;
21861 std::tie(Res, Chain) = LowerCallTo(CLI);
21863 Res = DAG.getBitcast(MVT::f16, Res);
21865 if (IsStrict)
21866 Res = DAG.getMergeValues({Res, Chain}, DL);
21868 return Res;
21871 if (VT.getScalarType() == MVT::bf16) {
21872 if (SVT.getScalarType() == MVT::f32 &&
21873 ((Subtarget.hasBF16() && Subtarget.hasVLX()) ||
21874 Subtarget.hasAVXNECONVERT()))
21875 return Op;
21876 return SDValue();
21879 if (VT.getScalarType() == MVT::f16 && !Subtarget.hasFP16()) {
21880 if (!Subtarget.hasF16C() || SVT.getScalarType() != MVT::f32)
21881 return SDValue();
21883 if (VT.isVector())
21884 return Op;
21886 SDValue Res;
21887 SDValue Rnd = DAG.getTargetConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, DL,
21888 MVT::i32);
21889 if (IsStrict) {
21890 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4f32,
21891 DAG.getConstantFP(0, DL, MVT::v4f32), In,
21892 DAG.getIntPtrConstant(0, DL));
21893 Res = DAG.getNode(X86ISD::STRICT_CVTPS2PH, DL, {MVT::v8i16, MVT::Other},
21894 {Chain, Res, Rnd});
21895 Chain = Res.getValue(1);
21896 } else {
21897 // FIXME: Should we use zeros for upper elements for non-strict?
21898 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, In);
21899 Res = DAG.getNode(X86ISD::CVTPS2PH, DL, MVT::v8i16, Res, Rnd);
21902 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
21903 DAG.getIntPtrConstant(0, DL));
21904 Res = DAG.getBitcast(MVT::f16, Res);
21906 if (IsStrict)
21907 return DAG.getMergeValues({Res, Chain}, DL);
21909 return Res;
21912 return Op;
21915 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
21916 bool IsStrict = Op->isStrictFPOpcode();
21917 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21918 assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
21919 "Unexpected VT!");
21921 SDLoc dl(Op);
21922 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
21923 DAG.getConstant(0, dl, MVT::v8i16), Src,
21924 DAG.getIntPtrConstant(0, dl));
21926 SDValue Chain;
21927 if (IsStrict) {
21928 Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
21929 {Op.getOperand(0), Res});
21930 Chain = Res.getValue(1);
21931 } else {
21932 Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
21935 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
21936 DAG.getIntPtrConstant(0, dl));
21938 if (IsStrict)
21939 return DAG.getMergeValues({Res, Chain}, dl);
21941 return Res;
21944 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
21945 bool IsStrict = Op->isStrictFPOpcode();
21946 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21947 assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
21948 "Unexpected VT!");
21950 SDLoc dl(Op);
21951 SDValue Res, Chain;
21952 if (IsStrict) {
21953 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
21954 DAG.getConstantFP(0, dl, MVT::v4f32), Src,
21955 DAG.getIntPtrConstant(0, dl));
21956 Res = DAG.getNode(
21957 X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
21958 {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
21959 Chain = Res.getValue(1);
21960 } else {
21961 // FIXME: Should we use zeros for upper elements for non-strict?
21962 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
21963 Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
21964 DAG.getTargetConstant(4, dl, MVT::i32));
21967 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
21968 DAG.getIntPtrConstant(0, dl));
21970 if (IsStrict)
21971 return DAG.getMergeValues({Res, Chain}, dl);
21973 return Res;
21976 SDValue X86TargetLowering::LowerFP_TO_BF16(SDValue Op,
21977 SelectionDAG &DAG) const {
21978 SDLoc DL(Op);
21980 MVT SVT = Op.getOperand(0).getSimpleValueType();
21981 if (SVT == MVT::f32 && ((Subtarget.hasBF16() && Subtarget.hasVLX()) ||
21982 Subtarget.hasAVXNECONVERT())) {
21983 SDValue Res;
21984 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, Op.getOperand(0));
21985 Res = DAG.getNode(X86ISD::CVTNEPS2BF16, DL, MVT::v8bf16, Res);
21986 Res = DAG.getBitcast(MVT::v8i16, Res);
21987 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
21988 DAG.getIntPtrConstant(0, DL));
21991 MakeLibCallOptions CallOptions;
21992 RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
21993 SDValue Res =
21994 makeLibCall(DAG, LC, MVT::f16, Op.getOperand(0), CallOptions, DL).first;
21995 return DAG.getBitcast(MVT::i16, Res);
21998 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21999 /// vector operation in place of the typical scalar operation.
22000 static SDValue lowerAddSubToHorizontalOp(SDValue Op, const SDLoc &DL,
22001 SelectionDAG &DAG,
22002 const X86Subtarget &Subtarget) {
22003 // If both operands have other uses, this is probably not profitable.
22004 SDValue LHS = Op.getOperand(0);
22005 SDValue RHS = Op.getOperand(1);
22006 if (!LHS.hasOneUse() && !RHS.hasOneUse())
22007 return Op;
22009 // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
22010 bool IsFP = Op.getSimpleValueType().isFloatingPoint();
22011 if (IsFP && !Subtarget.hasSSE3())
22012 return Op;
22013 if (!IsFP && !Subtarget.hasSSSE3())
22014 return Op;
22016 // Extract from a common vector.
22017 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
22018 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
22019 LHS.getOperand(0) != RHS.getOperand(0) ||
22020 !isa<ConstantSDNode>(LHS.getOperand(1)) ||
22021 !isa<ConstantSDNode>(RHS.getOperand(1)) ||
22022 !shouldUseHorizontalOp(true, DAG, Subtarget))
22023 return Op;
22025 // Allow commuted 'hadd' ops.
22026 // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
22027 unsigned HOpcode;
22028 switch (Op.getOpcode()) {
22029 // clang-format off
22030 case ISD::ADD: HOpcode = X86ISD::HADD; break;
22031 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
22032 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
22033 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
22034 default:
22035 llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
22036 // clang-format on
22038 unsigned LExtIndex = LHS.getConstantOperandVal(1);
22039 unsigned RExtIndex = RHS.getConstantOperandVal(1);
22040 if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
22041 (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
22042 std::swap(LExtIndex, RExtIndex);
22044 if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
22045 return Op;
22047 SDValue X = LHS.getOperand(0);
22048 EVT VecVT = X.getValueType();
22049 unsigned BitWidth = VecVT.getSizeInBits();
22050 unsigned NumLanes = BitWidth / 128;
22051 unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
22052 assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
22053 "Not expecting illegal vector widths here");
22055 // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
22056 // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
22057 if (BitWidth == 256 || BitWidth == 512) {
22058 unsigned LaneIdx = LExtIndex / NumEltsPerLane;
22059 X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
22060 LExtIndex %= NumEltsPerLane;
22063 // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
22064 // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
22065 // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
22066 // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
22067 SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
22068 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
22069 DAG.getIntPtrConstant(LExtIndex / 2, DL));
22072 /// Depending on uarch and/or optimizing for size, we might prefer to use a
22073 /// vector operation in place of the typical scalar operation.
22074 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
22075 assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
22076 "Only expecting float/double");
22077 return lowerAddSubToHorizontalOp(Op, SDLoc(Op), DAG, Subtarget);
22080 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
22081 /// This mode isn't supported in hardware on X86. But as long as we aren't
22082 /// compiling with trapping math, we can emulate this with
22083 /// trunc(X + copysign(nextafter(0.5, 0.0), X)).
22084 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
22085 SDValue N0 = Op.getOperand(0);
22086 SDLoc dl(Op);
22087 MVT VT = Op.getSimpleValueType();
22089 // N0 += copysign(nextafter(0.5, 0.0), N0)
22090 const fltSemantics &Sem = VT.getFltSemantics();
22091 bool Ignored;
22092 APFloat Point5Pred = APFloat(0.5f);
22093 Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
22094 Point5Pred.next(/*nextDown*/true);
22096 SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
22097 DAG.getConstantFP(Point5Pred, dl, VT), N0);
22098 N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
22100 // Truncate the result to remove fraction.
22101 return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
22104 /// The only differences between FABS and FNEG are the mask and the logic op.
22105 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
22106 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
22107 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
22108 "Wrong opcode for lowering FABS or FNEG.");
22110 bool IsFABS = (Op.getOpcode() == ISD::FABS);
22112 // If this is a FABS and it has an FNEG user, bail out to fold the combination
22113 // into an FNABS. We'll lower the FABS after that if it is still in use.
22114 if (IsFABS)
22115 for (SDNode *User : Op->uses())
22116 if (User->getOpcode() == ISD::FNEG)
22117 return Op;
22119 SDLoc dl(Op);
22120 MVT VT = Op.getSimpleValueType();
22122 bool IsF128 = (VT == MVT::f128);
22123 assert(VT.isFloatingPoint() && VT != MVT::f80 &&
22124 DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
22125 "Unexpected type in LowerFABSorFNEG");
22127 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOptLevel to
22128 // decide if we should generate a 16-byte constant mask when we only need 4 or
22129 // 8 bytes for the scalar case.
22131 // There are no scalar bitwise logical SSE/AVX instructions, so we
22132 // generate a 16-byte vector constant and logic op even for the scalar case.
22133 // Using a 16-byte mask allows folding the load of the mask with
22134 // the logic op, so it can save (~4 bytes) on code size.
22135 bool IsFakeVector = !VT.isVector() && !IsF128;
22136 MVT LogicVT = VT;
22137 if (IsFakeVector)
22138 LogicVT = (VT == MVT::f64) ? MVT::v2f64
22139 : (VT == MVT::f32) ? MVT::v4f32
22140 : MVT::v8f16;
22142 unsigned EltBits = VT.getScalarSizeInBits();
22143 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
22144 APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
22145 APInt::getSignMask(EltBits);
22146 const fltSemantics &Sem = VT.getFltSemantics();
22147 SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
22149 SDValue Op0 = Op.getOperand(0);
22150 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
22151 unsigned LogicOp = IsFABS ? X86ISD::FAND :
22152 IsFNABS ? X86ISD::FOR :
22153 X86ISD::FXOR;
22154 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
22156 if (VT.isVector() || IsF128)
22157 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22159 // For the scalar case extend to a 128-bit vector, perform the logic op,
22160 // and extract the scalar result back out.
22161 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
22162 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22163 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
22164 DAG.getIntPtrConstant(0, dl));
22167 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
22168 SDValue Mag = Op.getOperand(0);
22169 SDValue Sign = Op.getOperand(1);
22170 SDLoc dl(Op);
22172 // If the sign operand is smaller, extend it first.
22173 MVT VT = Op.getSimpleValueType();
22174 if (Sign.getSimpleValueType().bitsLT(VT))
22175 Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
22177 // And if it is bigger, shrink it first.
22178 if (Sign.getSimpleValueType().bitsGT(VT))
22179 Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign,
22180 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
22182 // At this point the operands and the result should have the same
22183 // type, and that won't be f80 since that is not custom lowered.
22184 bool IsF128 = (VT == MVT::f128);
22185 assert(VT.isFloatingPoint() && VT != MVT::f80 &&
22186 DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
22187 "Unexpected type in LowerFCOPYSIGN");
22189 const fltSemantics &Sem = VT.getFltSemantics();
22191 // Perform all scalar logic operations as 16-byte vectors because there are no
22192 // scalar FP logic instructions in SSE.
22193 // TODO: This isn't necessary. If we used scalar types, we might avoid some
22194 // unnecessary splats, but we might miss load folding opportunities. Should
22195 // this decision be based on OptimizeForSize?
22196 bool IsFakeVector = !VT.isVector() && !IsF128;
22197 MVT LogicVT = VT;
22198 if (IsFakeVector)
22199 LogicVT = (VT == MVT::f64) ? MVT::v2f64
22200 : (VT == MVT::f32) ? MVT::v4f32
22201 : MVT::v8f16;
22203 // The mask constants are automatically splatted for vector types.
22204 unsigned EltSizeInBits = VT.getScalarSizeInBits();
22205 SDValue SignMask = DAG.getConstantFP(
22206 APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
22207 SDValue MagMask = DAG.getConstantFP(
22208 APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
22210 // First, clear all bits but the sign bit from the second operand (sign).
22211 if (IsFakeVector)
22212 Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
22213 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
22215 // Next, clear the sign bit from the first operand (magnitude).
22216 // TODO: If we had general constant folding for FP logic ops, this check
22217 // wouldn't be necessary.
22218 SDValue MagBits;
22219 if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
22220 APFloat APF = Op0CN->getValueAPF();
22221 APF.clearSign();
22222 MagBits = DAG.getConstantFP(APF, dl, LogicVT);
22223 } else {
22224 // If the magnitude operand wasn't a constant, we need to AND out the sign.
22225 if (IsFakeVector)
22226 Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
22227 MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
22230 // OR the magnitude value with the sign bit.
22231 SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
22232 return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
22233 DAG.getIntPtrConstant(0, dl));
22236 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
22237 SDValue N0 = Op.getOperand(0);
22238 SDLoc dl(Op);
22239 MVT VT = Op.getSimpleValueType();
22241 MVT OpVT = N0.getSimpleValueType();
22242 assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
22243 "Unexpected type for FGETSIGN");
22245 // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
22246 MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
22247 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
22248 Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
22249 Res = DAG.getZExtOrTrunc(Res, dl, VT);
22250 Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
22251 return Res;
22254 /// Helper for attempting to create a X86ISD::BT node.
22255 static SDValue getBT(SDValue Src, SDValue BitNo, const SDLoc &DL, SelectionDAG &DAG) {
22256 // If Src is i8, promote it to i32 with any_extend. There is no i8 BT
22257 // instruction. Since the shift amount is in-range-or-undefined, we know
22258 // that doing a bittest on the i32 value is ok. We extend to i32 because
22259 // the encoding for the i16 version is larger than the i32 version.
22260 // Also promote i16 to i32 for performance / code size reason.
22261 if (Src.getValueType().getScalarSizeInBits() < 32)
22262 Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
22264 // No legal type found, give up.
22265 if (!DAG.getTargetLoweringInfo().isTypeLegal(Src.getValueType()))
22266 return SDValue();
22268 // See if we can use the 32-bit instruction instead of the 64-bit one for a
22269 // shorter encoding. Since the former takes the modulo 32 of BitNo and the
22270 // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
22271 // known to be zero.
22272 if (Src.getValueType() == MVT::i64 &&
22273 DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
22274 Src = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
22276 // If the operand types disagree, extend the shift amount to match. Since
22277 // BT ignores high bits (like shifts) we can use anyextend.
22278 if (Src.getValueType() != BitNo.getValueType()) {
22279 // Peek through a mask/modulo operation.
22280 // TODO: DAGCombine fails to do this as it just checks isTruncateFree, but
22281 // we probably need a better IsDesirableToPromoteOp to handle this as well.
22282 if (BitNo.getOpcode() == ISD::AND && BitNo->hasOneUse())
22283 BitNo = DAG.getNode(ISD::AND, DL, Src.getValueType(),
22284 DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
22285 BitNo.getOperand(0)),
22286 DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
22287 BitNo.getOperand(1)));
22288 else
22289 BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
22292 return DAG.getNode(X86ISD::BT, DL, MVT::i32, Src, BitNo);
22295 /// Helper for creating a X86ISD::SETCC node.
22296 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
22297 SelectionDAG &DAG) {
22298 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
22299 DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
22302 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
22303 /// recognizable memcmp expansion.
22304 static bool isOrXorXorTree(SDValue X, bool Root = true) {
22305 if (X.getOpcode() == ISD::OR)
22306 return isOrXorXorTree(X.getOperand(0), false) &&
22307 isOrXorXorTree(X.getOperand(1), false);
22308 if (Root)
22309 return false;
22310 return X.getOpcode() == ISD::XOR;
22313 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
22314 /// expansion.
22315 template <typename F>
22316 static SDValue emitOrXorXorTree(SDValue X, const SDLoc &DL, SelectionDAG &DAG,
22317 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
22318 SDValue Op0 = X.getOperand(0);
22319 SDValue Op1 = X.getOperand(1);
22320 if (X.getOpcode() == ISD::OR) {
22321 SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
22322 SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
22323 if (VecVT != CmpVT)
22324 return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
22325 if (HasPT)
22326 return DAG.getNode(ISD::OR, DL, VecVT, A, B);
22327 return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
22329 if (X.getOpcode() == ISD::XOR) {
22330 SDValue A = SToV(Op0);
22331 SDValue B = SToV(Op1);
22332 if (VecVT != CmpVT)
22333 return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
22334 if (HasPT)
22335 return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
22336 return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
22338 llvm_unreachable("Impossible");
22341 /// Try to map a 128-bit or larger integer comparison to vector instructions
22342 /// before type legalization splits it up into chunks.
22343 static SDValue combineVectorSizedSetCCEquality(EVT VT, SDValue X, SDValue Y,
22344 ISD::CondCode CC,
22345 const SDLoc &DL,
22346 SelectionDAG &DAG,
22347 const X86Subtarget &Subtarget) {
22348 assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
22350 // We're looking for an oversized integer equality comparison.
22351 EVT OpVT = X.getValueType();
22352 unsigned OpSize = OpVT.getSizeInBits();
22353 if (!OpVT.isScalarInteger() || OpSize < 128)
22354 return SDValue();
22356 // Ignore a comparison with zero because that gets special treatment in
22357 // EmitTest(). But make an exception for the special case of a pair of
22358 // logically-combined vector-sized operands compared to zero. This pattern may
22359 // be generated by the memcmp expansion pass with oversized integer compares
22360 // (see PR33325).
22361 bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
22362 if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
22363 return SDValue();
22365 // Don't perform this combine if constructing the vector will be expensive.
22366 auto IsVectorBitCastCheap = [](SDValue X) {
22367 X = peekThroughBitcasts(X);
22368 return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
22369 X.getOpcode() == ISD::LOAD;
22371 if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
22372 !IsOrXorXorTreeCCZero)
22373 return SDValue();
22375 // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
22376 // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
22377 // Otherwise use PCMPEQ (plus AND) and mask testing.
22378 bool NoImplicitFloatOps =
22379 DAG.getMachineFunction().getFunction().hasFnAttribute(
22380 Attribute::NoImplicitFloat);
22381 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
22382 ((OpSize == 128 && Subtarget.hasSSE2()) ||
22383 (OpSize == 256 && Subtarget.hasAVX()) ||
22384 (OpSize == 512 && Subtarget.useAVX512Regs()))) {
22385 bool HasPT = Subtarget.hasSSE41();
22387 // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
22388 // vector registers are essentially free. (Technically, widening registers
22389 // prevents load folding, but the tradeoff is worth it.)
22390 bool PreferKOT = Subtarget.preferMaskRegisters();
22391 bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
22393 EVT VecVT = MVT::v16i8;
22394 EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
22395 if (OpSize == 256) {
22396 VecVT = MVT::v32i8;
22397 CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
22399 EVT CastVT = VecVT;
22400 bool NeedsAVX512FCast = false;
22401 if (OpSize == 512 || NeedZExt) {
22402 if (Subtarget.hasBWI()) {
22403 VecVT = MVT::v64i8;
22404 CmpVT = MVT::v64i1;
22405 if (OpSize == 512)
22406 CastVT = VecVT;
22407 } else {
22408 VecVT = MVT::v16i32;
22409 CmpVT = MVT::v16i1;
22410 CastVT = OpSize == 512 ? VecVT
22411 : OpSize == 256 ? MVT::v8i32
22412 : MVT::v4i32;
22413 NeedsAVX512FCast = true;
22417 auto ScalarToVector = [&](SDValue X) -> SDValue {
22418 bool TmpZext = false;
22419 EVT TmpCastVT = CastVT;
22420 if (X.getOpcode() == ISD::ZERO_EXTEND) {
22421 SDValue OrigX = X.getOperand(0);
22422 unsigned OrigSize = OrigX.getScalarValueSizeInBits();
22423 if (OrigSize < OpSize) {
22424 if (OrigSize == 128) {
22425 TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
22426 X = OrigX;
22427 TmpZext = true;
22428 } else if (OrigSize == 256) {
22429 TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
22430 X = OrigX;
22431 TmpZext = true;
22435 X = DAG.getBitcast(TmpCastVT, X);
22436 if (!NeedZExt && !TmpZext)
22437 return X;
22438 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
22439 DAG.getConstant(0, DL, VecVT), X,
22440 DAG.getVectorIdxConstant(0, DL));
22443 SDValue Cmp;
22444 if (IsOrXorXorTreeCCZero) {
22445 // This is a bitwise-combined equality comparison of 2 pairs of vectors:
22446 // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
22447 // Use 2 vector equality compares and 'and' the results before doing a
22448 // MOVMSK.
22449 Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
22450 } else {
22451 SDValue VecX = ScalarToVector(X);
22452 SDValue VecY = ScalarToVector(Y);
22453 if (VecVT != CmpVT) {
22454 Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
22455 } else if (HasPT) {
22456 Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
22457 } else {
22458 Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
22461 // AVX512 should emit a setcc that will lower to kortest.
22462 if (VecVT != CmpVT) {
22463 EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64
22464 : CmpVT == MVT::v32i1 ? MVT::i32
22465 : MVT::i16;
22466 return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
22467 DAG.getConstant(0, DL, KRegVT), CC);
22469 if (HasPT) {
22470 SDValue BCCmp =
22471 DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64, Cmp);
22472 SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
22473 X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
22474 SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
22475 return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
22477 // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
22478 // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
22479 // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
22480 assert(Cmp.getValueType() == MVT::v16i8 &&
22481 "Non 128-bit vector on pre-SSE41 target");
22482 SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
22483 SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
22484 return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
22487 return SDValue();
22490 /// Helper for matching BINOP(EXTRACTELT(X,0),BINOP(EXTRACTELT(X,1),...))
22491 /// style scalarized (associative) reduction patterns. Partial reductions
22492 /// are supported when the pointer SrcMask is non-null.
22493 /// TODO - move this to SelectionDAG?
22494 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
22495 SmallVectorImpl<SDValue> &SrcOps,
22496 SmallVectorImpl<APInt> *SrcMask = nullptr) {
22497 SmallVector<SDValue, 8> Opnds;
22498 DenseMap<SDValue, APInt> SrcOpMap;
22499 EVT VT = MVT::Other;
22501 // Recognize a special case where a vector is casted into wide integer to
22502 // test all 0s.
22503 assert(Op.getOpcode() == unsigned(BinOp) &&
22504 "Unexpected bit reduction opcode");
22505 Opnds.push_back(Op.getOperand(0));
22506 Opnds.push_back(Op.getOperand(1));
22508 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
22509 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
22510 // BFS traverse all BinOp operands.
22511 if (I->getOpcode() == unsigned(BinOp)) {
22512 Opnds.push_back(I->getOperand(0));
22513 Opnds.push_back(I->getOperand(1));
22514 // Re-evaluate the number of nodes to be traversed.
22515 e += 2; // 2 more nodes (LHS and RHS) are pushed.
22516 continue;
22519 // Quit if a non-EXTRACT_VECTOR_ELT
22520 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22521 return false;
22523 // Quit if without a constant index.
22524 auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
22525 if (!Idx)
22526 return false;
22528 SDValue Src = I->getOperand(0);
22529 DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
22530 if (M == SrcOpMap.end()) {
22531 VT = Src.getValueType();
22532 // Quit if not the same type.
22533 if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
22534 return false;
22535 unsigned NumElts = VT.getVectorNumElements();
22536 APInt EltCount = APInt::getZero(NumElts);
22537 M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
22538 SrcOps.push_back(Src);
22541 // Quit if element already used.
22542 unsigned CIdx = Idx->getZExtValue();
22543 if (M->second[CIdx])
22544 return false;
22545 M->second.setBit(CIdx);
22548 if (SrcMask) {
22549 // Collect the source partial masks.
22550 for (SDValue &SrcOp : SrcOps)
22551 SrcMask->push_back(SrcOpMap[SrcOp]);
22552 } else {
22553 // Quit if not all elements are used.
22554 for (const auto &I : SrcOpMap)
22555 if (!I.second.isAllOnes())
22556 return false;
22559 return true;
22562 // Helper function for comparing all bits of two vectors.
22563 static SDValue LowerVectorAllEqual(const SDLoc &DL, SDValue LHS, SDValue RHS,
22564 ISD::CondCode CC, const APInt &OriginalMask,
22565 const X86Subtarget &Subtarget,
22566 SelectionDAG &DAG, X86::CondCode &X86CC) {
22567 EVT VT = LHS.getValueType();
22568 unsigned ScalarSize = VT.getScalarSizeInBits();
22569 if (OriginalMask.getBitWidth() != ScalarSize) {
22570 assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
22571 return SDValue();
22574 // Quit if not convertable to legal scalar or 128/256-bit vector.
22575 if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
22576 return SDValue();
22578 // FCMP may use ISD::SETNE when nnan - early out if we manage to get here.
22579 if (VT.isFloatingPoint())
22580 return SDValue();
22582 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22583 X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
22585 APInt Mask = OriginalMask;
22587 auto MaskBits = [&](SDValue Src) {
22588 if (Mask.isAllOnes())
22589 return Src;
22590 EVT SrcVT = Src.getValueType();
22591 SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
22592 return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
22595 // For sub-128-bit vector, cast to (legal) integer and compare with zero.
22596 if (VT.getSizeInBits() < 128) {
22597 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
22598 if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT)) {
22599 if (IntVT != MVT::i64)
22600 return SDValue();
22601 auto SplitLHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(LHS)), DL,
22602 MVT::i32, MVT::i32);
22603 auto SplitRHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(RHS)), DL,
22604 MVT::i32, MVT::i32);
22605 SDValue Lo =
22606 DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.first, SplitRHS.first);
22607 SDValue Hi =
22608 DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.second, SplitRHS.second);
22609 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22610 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi),
22611 DAG.getConstant(0, DL, MVT::i32));
22613 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22614 DAG.getBitcast(IntVT, MaskBits(LHS)),
22615 DAG.getBitcast(IntVT, MaskBits(RHS)));
22618 // Without PTEST, a masked v2i64 or-reduction is not faster than
22619 // scalarization.
22620 bool UseKORTEST = Subtarget.useAVX512Regs();
22621 bool UsePTEST = Subtarget.hasSSE41();
22622 if (!UsePTEST && !Mask.isAllOnes() && ScalarSize > 32)
22623 return SDValue();
22625 // Split down to 128/256/512-bit vector.
22626 unsigned TestSize = UseKORTEST ? 512 : (Subtarget.hasAVX() ? 256 : 128);
22628 // If the input vector has vector elements wider than the target test size,
22629 // then cast to <X x i64> so it will safely split.
22630 if (ScalarSize > TestSize) {
22631 if (!Mask.isAllOnes())
22632 return SDValue();
22633 VT = EVT::getVectorVT(*DAG.getContext(), MVT::i64, VT.getSizeInBits() / 64);
22634 LHS = DAG.getBitcast(VT, LHS);
22635 RHS = DAG.getBitcast(VT, RHS);
22636 Mask = APInt::getAllOnes(64);
22639 if (VT.getSizeInBits() > TestSize) {
22640 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
22641 if (KnownRHS.isConstant() && KnownRHS.getConstant() == Mask) {
22642 // If ICMP(AND(LHS,MASK),MASK) - reduce using AND splits.
22643 while (VT.getSizeInBits() > TestSize) {
22644 auto Split = DAG.SplitVector(LHS, DL);
22645 VT = Split.first.getValueType();
22646 LHS = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
22648 RHS = DAG.getAllOnesConstant(DL, VT);
22649 } else if (!UsePTEST && !KnownRHS.isZero()) {
22650 // MOVMSK Special Case:
22651 // ALLOF(CMPEQ(X,Y)) -> AND(CMPEQ(X[0],Y[0]),CMPEQ(X[1],Y[1]),....)
22652 MVT SVT = ScalarSize >= 32 ? MVT::i32 : MVT::i8;
22653 VT = MVT::getVectorVT(SVT, VT.getSizeInBits() / SVT.getSizeInBits());
22654 LHS = DAG.getBitcast(VT, MaskBits(LHS));
22655 RHS = DAG.getBitcast(VT, MaskBits(RHS));
22656 EVT BoolVT = VT.changeVectorElementType(MVT::i1);
22657 SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETEQ);
22658 V = DAG.getSExtOrTrunc(V, DL, VT);
22659 while (VT.getSizeInBits() > TestSize) {
22660 auto Split = DAG.SplitVector(V, DL);
22661 VT = Split.first.getValueType();
22662 V = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
22664 V = DAG.getNOT(DL, V, VT);
22665 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22666 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22667 DAG.getConstant(0, DL, MVT::i32));
22668 } else {
22669 // Convert to a ICMP_EQ(XOR(LHS,RHS),0) pattern.
22670 SDValue V = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
22671 while (VT.getSizeInBits() > TestSize) {
22672 auto Split = DAG.SplitVector(V, DL);
22673 VT = Split.first.getValueType();
22674 V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
22676 LHS = V;
22677 RHS = DAG.getConstant(0, DL, VT);
22681 if (UseKORTEST && VT.is512BitVector()) {
22682 MVT TestVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
22683 MVT BoolVT = TestVT.changeVectorElementType(MVT::i1);
22684 LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
22685 RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
22686 SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETNE);
22687 return DAG.getNode(X86ISD::KORTEST, DL, MVT::i32, V, V);
22690 if (UsePTEST) {
22691 MVT TestVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
22692 LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
22693 RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
22694 SDValue V = DAG.getNode(ISD::XOR, DL, TestVT, LHS, RHS);
22695 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
22698 assert(VT.getSizeInBits() == 128 && "Failure to split to 128-bits");
22699 MVT MaskVT = ScalarSize >= 32 ? MVT::v4i32 : MVT::v16i8;
22700 LHS = DAG.getBitcast(MaskVT, MaskBits(LHS));
22701 RHS = DAG.getBitcast(MaskVT, MaskBits(RHS));
22702 SDValue V = DAG.getNode(X86ISD::PCMPEQ, DL, MaskVT, LHS, RHS);
22703 V = DAG.getNOT(DL, V, MaskVT);
22704 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22705 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22706 DAG.getConstant(0, DL, MVT::i32));
22709 // Check whether an AND/OR'd reduction tree is PTEST-able, or if we can fallback
22710 // to CMP(MOVMSK(PCMPEQB(X,Y))).
22711 static SDValue MatchVectorAllEqualTest(SDValue LHS, SDValue RHS,
22712 ISD::CondCode CC, const SDLoc &DL,
22713 const X86Subtarget &Subtarget,
22714 SelectionDAG &DAG,
22715 X86::CondCode &X86CC) {
22716 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22718 bool CmpNull = isNullConstant(RHS);
22719 bool CmpAllOnes = isAllOnesConstant(RHS);
22720 if (!CmpNull && !CmpAllOnes)
22721 return SDValue();
22723 SDValue Op = LHS;
22724 if (!Subtarget.hasSSE2() || !Op->hasOneUse())
22725 return SDValue();
22727 // Check whether we're masking/truncating an OR-reduction result, in which
22728 // case track the masked bits.
22729 // TODO: Add CmpAllOnes support.
22730 APInt Mask = APInt::getAllOnes(Op.getScalarValueSizeInBits());
22731 if (CmpNull) {
22732 switch (Op.getOpcode()) {
22733 case ISD::TRUNCATE: {
22734 SDValue Src = Op.getOperand(0);
22735 Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
22736 Op.getScalarValueSizeInBits());
22737 Op = Src;
22738 break;
22740 case ISD::AND: {
22741 if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22742 Mask = Cst->getAPIntValue();
22743 Op = Op.getOperand(0);
22745 break;
22750 ISD::NodeType LogicOp = CmpNull ? ISD::OR : ISD::AND;
22752 // Match icmp(or(extract(X,0),extract(X,1)),0) anyof reduction patterns.
22753 // Match icmp(and(extract(X,0),extract(X,1)),-1) allof reduction patterns.
22754 SmallVector<SDValue, 8> VecIns;
22755 if (Op.getOpcode() == LogicOp && matchScalarReduction(Op, LogicOp, VecIns)) {
22756 EVT VT = VecIns[0].getValueType();
22757 assert(llvm::all_of(VecIns,
22758 [VT](SDValue V) { return VT == V.getValueType(); }) &&
22759 "Reduction source vector mismatch");
22761 // Quit if not splittable to scalar/128/256/512-bit vector.
22762 if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
22763 return SDValue();
22765 // If more than one full vector is evaluated, AND/OR them first before
22766 // PTEST.
22767 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
22768 Slot += 2, e += 1) {
22769 // Each iteration will AND/OR 2 nodes and append the result until there is
22770 // only 1 node left, i.e. the final value of all vectors.
22771 SDValue LHS = VecIns[Slot];
22772 SDValue RHS = VecIns[Slot + 1];
22773 VecIns.push_back(DAG.getNode(LogicOp, DL, VT, LHS, RHS));
22776 return LowerVectorAllEqual(DL, VecIns.back(),
22777 CmpNull ? DAG.getConstant(0, DL, VT)
22778 : DAG.getAllOnesConstant(DL, VT),
22779 CC, Mask, Subtarget, DAG, X86CC);
22782 // Match icmp(reduce_or(X),0) anyof reduction patterns.
22783 // Match icmp(reduce_and(X),-1) allof reduction patterns.
22784 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
22785 ISD::NodeType BinOp;
22786 if (SDValue Match =
22787 DAG.matchBinOpReduction(Op.getNode(), BinOp, {LogicOp})) {
22788 EVT MatchVT = Match.getValueType();
22789 return LowerVectorAllEqual(DL, Match,
22790 CmpNull ? DAG.getConstant(0, DL, MatchVT)
22791 : DAG.getAllOnesConstant(DL, MatchVT),
22792 CC, Mask, Subtarget, DAG, X86CC);
22796 if (Mask.isAllOnes()) {
22797 assert(!Op.getValueType().isVector() &&
22798 "Illegal vector type for reduction pattern");
22799 SDValue Src = peekThroughBitcasts(Op);
22800 if (Src.getValueType().isFixedLengthVector() &&
22801 Src.getValueType().getScalarType() == MVT::i1) {
22802 // Match icmp(bitcast(icmp_ne(X,Y)),0) reduction patterns.
22803 // Match icmp(bitcast(icmp_eq(X,Y)),-1) reduction patterns.
22804 if (Src.getOpcode() == ISD::SETCC) {
22805 SDValue LHS = Src.getOperand(0);
22806 SDValue RHS = Src.getOperand(1);
22807 EVT LHSVT = LHS.getValueType();
22808 ISD::CondCode SrcCC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
22809 if (SrcCC == (CmpNull ? ISD::SETNE : ISD::SETEQ) &&
22810 llvm::has_single_bit<uint32_t>(LHSVT.getSizeInBits())) {
22811 APInt SrcMask = APInt::getAllOnes(LHSVT.getScalarSizeInBits());
22812 return LowerVectorAllEqual(DL, LHS, RHS, CC, SrcMask, Subtarget, DAG,
22813 X86CC);
22816 // Match icmp(bitcast(vXi1 trunc(Y)),0) reduction patterns.
22817 // Match icmp(bitcast(vXi1 trunc(Y)),-1) reduction patterns.
22818 // Peek through truncation, mask the LSB and compare against zero/LSB.
22819 if (Src.getOpcode() == ISD::TRUNCATE) {
22820 SDValue Inner = Src.getOperand(0);
22821 EVT InnerVT = Inner.getValueType();
22822 if (llvm::has_single_bit<uint32_t>(InnerVT.getSizeInBits())) {
22823 unsigned BW = InnerVT.getScalarSizeInBits();
22824 APInt SrcMask = APInt(BW, 1);
22825 APInt Cmp = CmpNull ? APInt::getZero(BW) : SrcMask;
22826 return LowerVectorAllEqual(DL, Inner,
22827 DAG.getConstant(Cmp, DL, InnerVT), CC,
22828 SrcMask, Subtarget, DAG, X86CC);
22834 return SDValue();
22837 /// return true if \c Op has a use that doesn't just read flags.
22838 static bool hasNonFlagsUse(SDValue Op) {
22839 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
22840 ++UI) {
22841 SDNode *User = *UI;
22842 unsigned UOpNo = UI.getOperandNo();
22843 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
22844 // Look pass truncate.
22845 UOpNo = User->use_begin().getOperandNo();
22846 User = *User->use_begin();
22849 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
22850 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
22851 return true;
22853 return false;
22856 // Transform to an x86-specific ALU node with flags if there is a chance of
22857 // using an RMW op or only the flags are used. Otherwise, leave
22858 // the node alone and emit a 'cmp' or 'test' instruction.
22859 static bool isProfitableToUseFlagOp(SDValue Op) {
22860 for (SDNode *U : Op->uses())
22861 if (U->getOpcode() != ISD::CopyToReg &&
22862 U->getOpcode() != ISD::SETCC &&
22863 U->getOpcode() != ISD::STORE)
22864 return false;
22866 return true;
22869 /// Emit nodes that will be selected as "test Op0,Op0", or something
22870 /// equivalent.
22871 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
22872 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
22873 // CF and OF aren't always set the way we want. Determine which
22874 // of these we need.
22875 bool NeedCF = false;
22876 bool NeedOF = false;
22877 switch (X86CC) {
22878 default: break;
22879 case X86::COND_A: case X86::COND_AE:
22880 case X86::COND_B: case X86::COND_BE:
22881 NeedCF = true;
22882 break;
22883 case X86::COND_G: case X86::COND_GE:
22884 case X86::COND_L: case X86::COND_LE:
22885 case X86::COND_O: case X86::COND_NO: {
22886 // Check if we really need to set the
22887 // Overflow flag. If NoSignedWrap is present
22888 // that is not actually needed.
22889 switch (Op->getOpcode()) {
22890 case ISD::ADD:
22891 case ISD::SUB:
22892 case ISD::MUL:
22893 case ISD::SHL:
22894 if (Op.getNode()->getFlags().hasNoSignedWrap())
22895 break;
22896 [[fallthrough]];
22897 default:
22898 NeedOF = true;
22899 break;
22901 break;
22904 // See if we can use the EFLAGS value from the operand instead of
22905 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
22906 // we prove that the arithmetic won't overflow, we can't use OF or CF.
22907 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
22908 // Emit a CMP with 0, which is the TEST pattern.
22909 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22910 DAG.getConstant(0, dl, Op.getValueType()));
22912 unsigned Opcode = 0;
22913 unsigned NumOperands = 0;
22915 SDValue ArithOp = Op;
22917 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
22918 // which may be the result of a CAST. We use the variable 'Op', which is the
22919 // non-casted variable when we check for possible users.
22920 switch (ArithOp.getOpcode()) {
22921 case ISD::AND:
22922 // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
22923 // because a TEST instruction will be better.
22924 if (!hasNonFlagsUse(Op))
22925 break;
22927 [[fallthrough]];
22928 case ISD::ADD:
22929 case ISD::SUB:
22930 case ISD::OR:
22931 case ISD::XOR:
22932 if (!isProfitableToUseFlagOp(Op))
22933 break;
22935 // Otherwise use a regular EFLAGS-setting instruction.
22936 switch (ArithOp.getOpcode()) {
22937 // clang-format off
22938 default: llvm_unreachable("unexpected operator!");
22939 case ISD::ADD: Opcode = X86ISD::ADD; break;
22940 case ISD::SUB: Opcode = X86ISD::SUB; break;
22941 case ISD::XOR: Opcode = X86ISD::XOR; break;
22942 case ISD::AND: Opcode = X86ISD::AND; break;
22943 case ISD::OR: Opcode = X86ISD::OR; break;
22944 // clang-format on
22947 NumOperands = 2;
22948 break;
22949 case X86ISD::ADD:
22950 case X86ISD::SUB:
22951 case X86ISD::OR:
22952 case X86ISD::XOR:
22953 case X86ISD::AND:
22954 return SDValue(Op.getNode(), 1);
22955 case ISD::SSUBO:
22956 case ISD::USUBO: {
22957 // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
22958 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22959 return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
22960 Op->getOperand(1)).getValue(1);
22962 default:
22963 break;
22966 if (Opcode == 0) {
22967 // Emit a CMP with 0, which is the TEST pattern.
22968 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22969 DAG.getConstant(0, dl, Op.getValueType()));
22971 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22972 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
22974 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
22975 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
22976 return SDValue(New.getNode(), 1);
22979 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
22980 /// equivalent.
22981 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
22982 const SDLoc &dl, SelectionDAG &DAG,
22983 const X86Subtarget &Subtarget) {
22984 if (isNullConstant(Op1))
22985 return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
22987 EVT CmpVT = Op0.getValueType();
22989 assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
22990 CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
22992 // Only promote the compare up to I32 if it is a 16 bit operation
22993 // with an immediate. 16 bit immediates are to be avoided unless the target
22994 // isn't slowed down by length changing prefixes, we're optimizing for
22995 // codesize or the comparison is with a folded load.
22996 if (CmpVT == MVT::i16 && !Subtarget.hasFastImm16() &&
22997 !X86::mayFoldLoad(Op0, Subtarget) && !X86::mayFoldLoad(Op1, Subtarget) &&
22998 !DAG.getMachineFunction().getFunction().hasMinSize()) {
22999 auto *COp0 = dyn_cast<ConstantSDNode>(Op0);
23000 auto *COp1 = dyn_cast<ConstantSDNode>(Op1);
23001 // Don't do this if the immediate can fit in 8-bits.
23002 if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
23003 (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
23004 unsigned ExtendOp =
23005 isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
23006 if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
23007 // For equality comparisons try to use SIGN_EXTEND if the input was
23008 // truncate from something with enough sign bits.
23009 if (Op0.getOpcode() == ISD::TRUNCATE) {
23010 if (DAG.ComputeMaxSignificantBits(Op0.getOperand(0)) <= 16)
23011 ExtendOp = ISD::SIGN_EXTEND;
23012 } else if (Op1.getOpcode() == ISD::TRUNCATE) {
23013 if (DAG.ComputeMaxSignificantBits(Op1.getOperand(0)) <= 16)
23014 ExtendOp = ISD::SIGN_EXTEND;
23018 CmpVT = MVT::i32;
23019 Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
23020 Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
23024 // Try to shrink i64 compares if the input has enough zero bits.
23025 // TODO: Add sign-bits equivalent for isX86CCSigned(X86CC)?
23026 if (CmpVT == MVT::i64 && !isX86CCSigned(X86CC) &&
23027 Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
23028 DAG.MaskedValueIsZero(Op1, APInt::getHighBitsSet(64, 32)) &&
23029 DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
23030 CmpVT = MVT::i32;
23031 Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
23032 Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
23035 // 0-x == y --> x+y == 0
23036 // 0-x != y --> x+y != 0
23037 if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
23038 Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23039 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23040 SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
23041 return Add.getValue(1);
23044 // x == 0-y --> x+y == 0
23045 // x != 0-y --> x+y != 0
23046 if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
23047 Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
23048 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23049 SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
23050 return Add.getValue(1);
23053 // Use SUB instead of CMP to enable CSE between SUB and CMP.
23054 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
23055 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
23056 return Sub.getValue(1);
23059 bool X86TargetLowering::isXAndYEqZeroPreferableToXAndYEqY(ISD::CondCode Cond,
23060 EVT VT) const {
23061 return !VT.isVector() || Cond != ISD::CondCode::SETEQ;
23064 bool X86TargetLowering::optimizeFMulOrFDivAsShiftAddBitcast(
23065 SDNode *N, SDValue, SDValue IntPow2) const {
23066 if (N->getOpcode() == ISD::FDIV)
23067 return true;
23069 EVT FPVT = N->getValueType(0);
23070 EVT IntVT = IntPow2.getValueType();
23072 // This indicates a non-free bitcast.
23073 // TODO: This is probably overly conservative as we will need to scale the
23074 // integer vector anyways for the int->fp cast.
23075 if (FPVT.isVector() &&
23076 FPVT.getScalarSizeInBits() != IntVT.getScalarSizeInBits())
23077 return false;
23079 return true;
23082 /// Check if replacement of SQRT with RSQRT should be disabled.
23083 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
23084 EVT VT = Op.getValueType();
23086 // We don't need to replace SQRT with RSQRT for half type.
23087 if (VT.getScalarType() == MVT::f16)
23088 return true;
23090 // We never want to use both SQRT and RSQRT instructions for the same input.
23091 if (DAG.doesNodeExist(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
23092 return false;
23094 if (VT.isVector())
23095 return Subtarget.hasFastVectorFSQRT();
23096 return Subtarget.hasFastScalarFSQRT();
23099 /// The minimum architected relative accuracy is 2^-12. We need one
23100 /// Newton-Raphson step to have a good float result (24 bits of precision).
23101 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
23102 SelectionDAG &DAG, int Enabled,
23103 int &RefinementSteps,
23104 bool &UseOneConstNR,
23105 bool Reciprocal) const {
23106 SDLoc DL(Op);
23107 EVT VT = Op.getValueType();
23109 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
23110 // It is likely not profitable to do this for f64 because a double-precision
23111 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
23112 // instructions: convert to single, rsqrtss, convert back to double, refine
23113 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
23114 // along with FMA, this could be a throughput win.
23115 // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
23116 // after legalize types.
23117 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23118 (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
23119 (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
23120 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23121 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23122 if (RefinementSteps == ReciprocalEstimate::Unspecified)
23123 RefinementSteps = 1;
23125 UseOneConstNR = false;
23126 // There is no FSQRT for 512-bits, but there is RSQRT14.
23127 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
23128 SDValue Estimate = DAG.getNode(Opcode, DL, VT, Op);
23129 if (RefinementSteps == 0 && !Reciprocal)
23130 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Op, Estimate);
23131 return Estimate;
23134 if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23135 Subtarget.hasFP16()) {
23136 assert(Reciprocal && "Don't replace SQRT with RSQRT for half type");
23137 if (RefinementSteps == ReciprocalEstimate::Unspecified)
23138 RefinementSteps = 0;
23140 if (VT == MVT::f16) {
23141 SDValue Zero = DAG.getIntPtrConstant(0, DL);
23142 SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23143 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23144 Op = DAG.getNode(X86ISD::RSQRT14S, DL, MVT::v8f16, Undef, Op);
23145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23148 return DAG.getNode(X86ISD::RSQRT14, DL, VT, Op);
23150 return SDValue();
23153 /// The minimum architected relative accuracy is 2^-12. We need one
23154 /// Newton-Raphson step to have a good float result (24 bits of precision).
23155 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
23156 int Enabled,
23157 int &RefinementSteps) const {
23158 SDLoc DL(Op);
23159 EVT VT = Op.getValueType();
23161 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
23162 // It is likely not profitable to do this for f64 because a double-precision
23163 // reciprocal estimate with refinement on x86 prior to FMA requires
23164 // 15 instructions: convert to single, rcpss, convert back to double, refine
23165 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
23166 // along with FMA, this could be a throughput win.
23168 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
23169 (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
23170 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
23171 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
23172 // Enable estimate codegen with 1 refinement step for vector division.
23173 // Scalar division estimates are disabled because they break too much
23174 // real-world code. These defaults are intended to match GCC behavior.
23175 if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
23176 return SDValue();
23178 if (RefinementSteps == ReciprocalEstimate::Unspecified)
23179 RefinementSteps = 1;
23181 // There is no FSQRT for 512-bits, but there is RCP14.
23182 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
23183 return DAG.getNode(Opcode, DL, VT, Op);
23186 if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
23187 Subtarget.hasFP16()) {
23188 if (RefinementSteps == ReciprocalEstimate::Unspecified)
23189 RefinementSteps = 0;
23191 if (VT == MVT::f16) {
23192 SDValue Zero = DAG.getIntPtrConstant(0, DL);
23193 SDValue Undef = DAG.getUNDEF(MVT::v8f16);
23194 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
23195 Op = DAG.getNode(X86ISD::RCP14S, DL, MVT::v8f16, Undef, Op);
23196 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
23199 return DAG.getNode(X86ISD::RCP14, DL, VT, Op);
23201 return SDValue();
23204 /// If we have at least two divisions that use the same divisor, convert to
23205 /// multiplication by a reciprocal. This may need to be adjusted for a given
23206 /// CPU if a division's cost is not at least twice the cost of a multiplication.
23207 /// This is because we still need one division to calculate the reciprocal and
23208 /// then we need two multiplies by that reciprocal as replacements for the
23209 /// original divisions.
23210 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
23211 return 2;
23214 SDValue
23215 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
23216 SelectionDAG &DAG,
23217 SmallVectorImpl<SDNode *> &Created) const {
23218 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
23219 if (isIntDivCheap(N->getValueType(0), Attr))
23220 return SDValue(N,0); // Lower SDIV as SDIV
23222 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
23223 "Unexpected divisor!");
23225 // Only perform this transform if CMOV is supported otherwise the select
23226 // below will become a branch.
23227 if (!Subtarget.canUseCMOV())
23228 return SDValue();
23230 // fold (sdiv X, pow2)
23231 EVT VT = N->getValueType(0);
23232 // FIXME: Support i8.
23233 if (VT != MVT::i16 && VT != MVT::i32 &&
23234 !(Subtarget.is64Bit() && VT == MVT::i64))
23235 return SDValue();
23237 // If the divisor is 2 or -2, the default expansion is better.
23238 if (Divisor == 2 ||
23239 Divisor == APInt(Divisor.getBitWidth(), -2, /*isSigned*/ true))
23240 return SDValue();
23242 return TargetLowering::buildSDIVPow2WithCMov(N, Divisor, DAG, Created);
23245 /// Result of 'and' is compared against zero. Change to a BT node if possible.
23246 /// Returns the BT node and the condition code needed to use it.
23247 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC, const SDLoc &dl,
23248 SelectionDAG &DAG, X86::CondCode &X86CC) {
23249 assert(And.getOpcode() == ISD::AND && "Expected AND node!");
23250 SDValue Op0 = And.getOperand(0);
23251 SDValue Op1 = And.getOperand(1);
23252 if (Op0.getOpcode() == ISD::TRUNCATE)
23253 Op0 = Op0.getOperand(0);
23254 if (Op1.getOpcode() == ISD::TRUNCATE)
23255 Op1 = Op1.getOperand(0);
23257 SDValue Src, BitNo;
23258 if (Op1.getOpcode() == ISD::SHL)
23259 std::swap(Op0, Op1);
23260 if (Op0.getOpcode() == ISD::SHL) {
23261 if (isOneConstant(Op0.getOperand(0))) {
23262 // If we looked past a truncate, check that it's only truncating away
23263 // known zeros.
23264 unsigned BitWidth = Op0.getValueSizeInBits();
23265 unsigned AndBitWidth = And.getValueSizeInBits();
23266 if (BitWidth > AndBitWidth) {
23267 KnownBits Known = DAG.computeKnownBits(Op0);
23268 if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
23269 return SDValue();
23271 Src = Op1;
23272 BitNo = Op0.getOperand(1);
23274 } else if (Op1.getOpcode() == ISD::Constant) {
23275 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
23276 uint64_t AndRHSVal = AndRHS->getZExtValue();
23277 SDValue AndLHS = Op0;
23279 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
23280 Src = AndLHS.getOperand(0);
23281 BitNo = AndLHS.getOperand(1);
23282 } else {
23283 // Use BT if the immediate can't be encoded in a TEST instruction or we
23284 // are optimizing for size and the immedaite won't fit in a byte.
23285 bool OptForSize = DAG.shouldOptForSize();
23286 if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
23287 isPowerOf2_64(AndRHSVal)) {
23288 Src = AndLHS;
23289 BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
23290 Src.getValueType());
23295 // No patterns found, give up.
23296 if (!Src.getNode())
23297 return SDValue();
23299 // Remove any bit flip.
23300 if (isBitwiseNot(Src)) {
23301 Src = Src.getOperand(0);
23302 CC = CC == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
23305 // Attempt to create the X86ISD::BT node.
23306 if (SDValue BT = getBT(Src, BitNo, dl, DAG)) {
23307 X86CC = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
23308 return BT;
23311 return SDValue();
23314 // Check if pre-AVX condcode can be performed by a single FCMP op.
23315 static bool cheapX86FSETCC_SSE(ISD::CondCode SetCCOpcode) {
23316 return (SetCCOpcode != ISD::SETONE) && (SetCCOpcode != ISD::SETUEQ);
23319 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
23320 /// CMPs.
23321 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
23322 SDValue &Op1, bool &IsAlwaysSignaling) {
23323 unsigned SSECC;
23324 bool Swap = false;
23326 // SSE Condition code mapping:
23327 // 0 - EQ
23328 // 1 - LT
23329 // 2 - LE
23330 // 3 - UNORD
23331 // 4 - NEQ
23332 // 5 - NLT
23333 // 6 - NLE
23334 // 7 - ORD
23335 switch (SetCCOpcode) {
23336 // clang-format off
23337 default: llvm_unreachable("Unexpected SETCC condition");
23338 case ISD::SETOEQ:
23339 case ISD::SETEQ: SSECC = 0; break;
23340 case ISD::SETOGT:
23341 case ISD::SETGT: Swap = true; [[fallthrough]];
23342 case ISD::SETLT:
23343 case ISD::SETOLT: SSECC = 1; break;
23344 case ISD::SETOGE:
23345 case ISD::SETGE: Swap = true; [[fallthrough]];
23346 case ISD::SETLE:
23347 case ISD::SETOLE: SSECC = 2; break;
23348 case ISD::SETUO: SSECC = 3; break;
23349 case ISD::SETUNE:
23350 case ISD::SETNE: SSECC = 4; break;
23351 case ISD::SETULE: Swap = true; [[fallthrough]];
23352 case ISD::SETUGE: SSECC = 5; break;
23353 case ISD::SETULT: Swap = true; [[fallthrough]];
23354 case ISD::SETUGT: SSECC = 6; break;
23355 case ISD::SETO: SSECC = 7; break;
23356 case ISD::SETUEQ: SSECC = 8; break;
23357 case ISD::SETONE: SSECC = 12; break;
23358 // clang-format on
23360 if (Swap)
23361 std::swap(Op0, Op1);
23363 switch (SetCCOpcode) {
23364 default:
23365 IsAlwaysSignaling = true;
23366 break;
23367 case ISD::SETEQ:
23368 case ISD::SETOEQ:
23369 case ISD::SETUEQ:
23370 case ISD::SETNE:
23371 case ISD::SETONE:
23372 case ISD::SETUNE:
23373 case ISD::SETO:
23374 case ISD::SETUO:
23375 IsAlwaysSignaling = false;
23376 break;
23379 return SSECC;
23382 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
23383 /// concatenate the result back.
23384 static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
23385 ISD::CondCode Cond, SelectionDAG &DAG,
23386 const SDLoc &dl) {
23387 assert(VT.isInteger() && VT == LHS.getValueType() &&
23388 VT == RHS.getValueType() && "Unsupported VTs!");
23390 SDValue CC = DAG.getCondCode(Cond);
23392 // Extract the LHS Lo/Hi vectors
23393 SDValue LHS1, LHS2;
23394 std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
23396 // Extract the RHS Lo/Hi vectors
23397 SDValue RHS1, RHS2;
23398 std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
23400 // Issue the operation on the smaller types and concatenate the result back
23401 EVT LoVT, HiVT;
23402 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
23403 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23404 DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
23405 DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
23408 static SDValue LowerIntVSETCC_AVX512(SDValue Op, const SDLoc &dl,
23409 SelectionDAG &DAG) {
23410 SDValue Op0 = Op.getOperand(0);
23411 SDValue Op1 = Op.getOperand(1);
23412 SDValue CC = Op.getOperand(2);
23413 MVT VT = Op.getSimpleValueType();
23414 assert(VT.getVectorElementType() == MVT::i1 &&
23415 "Cannot set masked compare for this operation");
23417 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
23419 // Prefer SETGT over SETLT.
23420 if (SetCCOpcode == ISD::SETLT) {
23421 SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
23422 std::swap(Op0, Op1);
23425 return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
23428 /// Given a buildvector constant, return a new vector constant with each element
23429 /// incremented or decremented. If incrementing or decrementing would result in
23430 /// unsigned overflow or underflow or this is not a simple vector constant,
23431 /// return an empty value.
23432 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc,
23433 bool NSW) {
23434 auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
23435 if (!BV || !V.getValueType().isSimple())
23436 return SDValue();
23438 MVT VT = V.getSimpleValueType();
23439 MVT EltVT = VT.getVectorElementType();
23440 unsigned NumElts = VT.getVectorNumElements();
23441 SmallVector<SDValue, 8> NewVecC;
23442 SDLoc DL(V);
23443 for (unsigned i = 0; i < NumElts; ++i) {
23444 auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
23445 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
23446 return SDValue();
23448 // Avoid overflow/underflow.
23449 const APInt &EltC = Elt->getAPIntValue();
23450 if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isZero()))
23451 return SDValue();
23452 if (NSW && ((IsInc && EltC.isMaxSignedValue()) ||
23453 (!IsInc && EltC.isMinSignedValue())))
23454 return SDValue();
23456 NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
23459 return DAG.getBuildVector(VT, DL, NewVecC);
23462 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
23463 /// Op0 u<= Op1:
23464 /// t = psubus Op0, Op1
23465 /// pcmpeq t, <0..0>
23466 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
23467 ISD::CondCode Cond, const SDLoc &dl,
23468 const X86Subtarget &Subtarget,
23469 SelectionDAG &DAG) {
23470 if (!Subtarget.hasSSE2())
23471 return SDValue();
23473 MVT VET = VT.getVectorElementType();
23474 if (VET != MVT::i8 && VET != MVT::i16)
23475 return SDValue();
23477 switch (Cond) {
23478 default:
23479 return SDValue();
23480 case ISD::SETULT: {
23481 // If the comparison is against a constant we can turn this into a
23482 // setule. With psubus, setule does not require a swap. This is
23483 // beneficial because the constant in the register is no longer
23484 // destructed as the destination so it can be hoisted out of a loop.
23485 // Only do this pre-AVX since vpcmp* is no longer destructive.
23486 if (Subtarget.hasAVX())
23487 return SDValue();
23488 SDValue ULEOp1 =
23489 incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false);
23490 if (!ULEOp1)
23491 return SDValue();
23492 Op1 = ULEOp1;
23493 break;
23495 case ISD::SETUGT: {
23496 // If the comparison is against a constant, we can turn this into a setuge.
23497 // This is beneficial because materializing a constant 0 for the PCMPEQ is
23498 // probably cheaper than XOR+PCMPGT using 2 different vector constants:
23499 // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
23500 SDValue UGEOp1 =
23501 incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false);
23502 if (!UGEOp1)
23503 return SDValue();
23504 Op1 = Op0;
23505 Op0 = UGEOp1;
23506 break;
23508 // Psubus is better than flip-sign because it requires no inversion.
23509 case ISD::SETUGE:
23510 std::swap(Op0, Op1);
23511 break;
23512 case ISD::SETULE:
23513 break;
23516 SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
23517 return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
23518 DAG.getConstant(0, dl, VT));
23521 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
23522 SelectionDAG &DAG) {
23523 bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23524 Op.getOpcode() == ISD::STRICT_FSETCCS;
23525 SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23526 SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23527 SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
23528 MVT VT = Op->getSimpleValueType(0);
23529 ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
23530 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
23531 SDLoc dl(Op);
23533 if (isFP) {
23534 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
23535 assert(EltVT == MVT::bf16 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
23536 EltVT == MVT::f64);
23537 if (isSoftF16(EltVT, Subtarget))
23538 return SDValue();
23540 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23541 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23543 // If we have a strict compare with a vXi1 result and the input is 128/256
23544 // bits we can't use a masked compare unless we have VLX. If we use a wider
23545 // compare like we do for non-strict, we might trigger spurious exceptions
23546 // from the upper elements. Instead emit a AVX compare and convert to mask.
23547 unsigned Opc;
23548 if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
23549 (!IsStrict || Subtarget.hasVLX() ||
23550 Op0.getSimpleValueType().is512BitVector())) {
23551 #ifndef NDEBUG
23552 unsigned Num = VT.getVectorNumElements();
23553 assert(Num <= 16 ||
23554 (Num == 32 && (EltVT == MVT::f16 || EltVT == MVT::bf16)));
23555 #endif
23556 Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
23557 } else {
23558 Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
23559 // The SSE/AVX packed FP comparison nodes are defined with a
23560 // floating-point vector result that matches the operand type. This allows
23561 // them to work with an SSE1 target (integer vector types are not legal).
23562 VT = Op0.getSimpleValueType();
23565 SDValue Cmp;
23566 bool IsAlwaysSignaling;
23567 unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
23568 if (!Subtarget.hasAVX()) {
23569 // TODO: We could use following steps to handle a quiet compare with
23570 // signaling encodings.
23571 // 1. Get ordered masks from a quiet ISD::SETO
23572 // 2. Use the masks to mask potential unordered elements in operand A, B
23573 // 3. Get the compare results of masked A, B
23574 // 4. Calculating final result using the mask and result from 3
23575 // But currently, we just fall back to scalar operations.
23576 if (IsStrict && IsAlwaysSignaling && !IsSignaling)
23577 return SDValue();
23579 // Insert an extra signaling instruction to raise exception.
23580 if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
23581 SDValue SignalCmp = DAG.getNode(
23582 Opc, dl, {VT, MVT::Other},
23583 {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
23584 // FIXME: It seems we need to update the flags of all new strict nodes.
23585 // Otherwise, mayRaiseFPException in MI will return false due to
23586 // NoFPExcept = false by default. However, I didn't find it in other
23587 // patches.
23588 SignalCmp->setFlags(Op->getFlags());
23589 Chain = SignalCmp.getValue(1);
23592 // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
23593 // emit two comparisons and a logic op to tie them together.
23594 if (!cheapX86FSETCC_SSE(Cond)) {
23595 // LLVM predicate is SETUEQ or SETONE.
23596 unsigned CC0, CC1;
23597 unsigned CombineOpc;
23598 if (Cond == ISD::SETUEQ) {
23599 CC0 = 3; // UNORD
23600 CC1 = 0; // EQ
23601 CombineOpc = X86ISD::FOR;
23602 } else {
23603 assert(Cond == ISD::SETONE);
23604 CC0 = 7; // ORD
23605 CC1 = 4; // NEQ
23606 CombineOpc = X86ISD::FAND;
23609 SDValue Cmp0, Cmp1;
23610 if (IsStrict) {
23611 Cmp0 = DAG.getNode(
23612 Opc, dl, {VT, MVT::Other},
23613 {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
23614 Cmp1 = DAG.getNode(
23615 Opc, dl, {VT, MVT::Other},
23616 {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
23617 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
23618 Cmp1.getValue(1));
23619 } else {
23620 Cmp0 = DAG.getNode(
23621 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
23622 Cmp1 = DAG.getNode(
23623 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
23625 Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
23626 } else {
23627 if (IsStrict) {
23628 Cmp = DAG.getNode(
23629 Opc, dl, {VT, MVT::Other},
23630 {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23631 Chain = Cmp.getValue(1);
23632 } else
23633 Cmp = DAG.getNode(
23634 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23636 } else {
23637 // Handle all other FP comparisons here.
23638 if (IsStrict) {
23639 // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
23640 SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
23641 Cmp = DAG.getNode(
23642 Opc, dl, {VT, MVT::Other},
23643 {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23644 Chain = Cmp.getValue(1);
23645 } else
23646 Cmp = DAG.getNode(
23647 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23650 if (VT.getFixedSizeInBits() >
23651 Op.getSimpleValueType().getFixedSizeInBits()) {
23652 // We emitted a compare with an XMM/YMM result. Finish converting to a
23653 // mask register using a vptestm.
23654 EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
23655 Cmp = DAG.getBitcast(CastVT, Cmp);
23656 Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
23657 DAG.getConstant(0, dl, CastVT), ISD::SETNE);
23658 } else {
23659 // If this is SSE/AVX CMPP, bitcast the result back to integer to match
23660 // the result type of SETCC. The bitcast is expected to be optimized
23661 // away during combining/isel.
23662 Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
23665 if (IsStrict)
23666 return DAG.getMergeValues({Cmp, Chain}, dl);
23668 return Cmp;
23671 assert(!IsStrict && "Strict SETCC only handles FP operands.");
23673 [[maybe_unused]] MVT VTOp0 = Op0.getSimpleValueType();
23674 assert(VTOp0 == Op1.getSimpleValueType() &&
23675 "Expected operands with same type!");
23676 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
23677 "Invalid number of packed elements for source and destination!");
23679 // The non-AVX512 code below works under the assumption that source and
23680 // destination types are the same.
23681 assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
23682 "Value types for source and destination must be the same!");
23684 // The result is boolean, but operands are int/float
23685 if (VT.getVectorElementType() == MVT::i1) {
23686 // In AVX-512 architecture setcc returns mask with i1 elements,
23687 // But there is no compare instruction for i8 and i16 elements in KNL.
23688 assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
23689 "Unexpected operand type");
23690 return LowerIntVSETCC_AVX512(Op, dl, DAG);
23693 // Lower using XOP integer comparisons.
23694 if (VT.is128BitVector() && Subtarget.hasXOP()) {
23695 // Translate compare code to XOP PCOM compare mode.
23696 unsigned CmpMode = 0;
23697 switch (Cond) {
23698 // clang-format off
23699 default: llvm_unreachable("Unexpected SETCC condition");
23700 case ISD::SETULT:
23701 case ISD::SETLT: CmpMode = 0x00; break;
23702 case ISD::SETULE:
23703 case ISD::SETLE: CmpMode = 0x01; break;
23704 case ISD::SETUGT:
23705 case ISD::SETGT: CmpMode = 0x02; break;
23706 case ISD::SETUGE:
23707 case ISD::SETGE: CmpMode = 0x03; break;
23708 case ISD::SETEQ: CmpMode = 0x04; break;
23709 case ISD::SETNE: CmpMode = 0x05; break;
23710 // clang-format on
23713 // Are we comparing unsigned or signed integers?
23714 unsigned Opc =
23715 ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
23717 return DAG.getNode(Opc, dl, VT, Op0, Op1,
23718 DAG.getTargetConstant(CmpMode, dl, MVT::i8));
23721 // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
23722 // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
23723 if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
23724 SDValue BC0 = peekThroughBitcasts(Op0);
23725 if (BC0.getOpcode() == ISD::AND &&
23726 isConstantPowerOf2(BC0.getOperand(1), VT.getScalarSizeInBits(),
23727 /*AllowUndefs=*/false)) {
23728 Cond = ISD::SETEQ;
23729 Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
23733 // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
23734 if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
23735 Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
23736 ConstantSDNode *C1 = isConstOrConstSplat(Op1);
23737 if (C1 && C1->getAPIntValue().isPowerOf2()) {
23738 unsigned BitWidth = VT.getScalarSizeInBits();
23739 unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
23741 SDValue Result = Op0.getOperand(0);
23742 Result = DAG.getNode(ISD::SHL, dl, VT, Result,
23743 DAG.getConstant(ShiftAmt, dl, VT));
23744 Result = DAG.getNode(ISD::SRA, dl, VT, Result,
23745 DAG.getConstant(BitWidth - 1, dl, VT));
23746 return Result;
23750 // Break 256-bit integer vector compare into smaller ones.
23751 if (VT.is256BitVector() && !Subtarget.hasInt256())
23752 return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23754 // Break 512-bit integer vector compare into smaller ones.
23755 // TODO: Try harder to use VPCMPx + VPMOV2x?
23756 if (VT.is512BitVector())
23757 return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23759 // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
23760 // not-of-PCMPEQ:
23761 // X != INT_MIN --> X >s INT_MIN
23762 // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
23763 // +X != 0 --> +X >s 0
23764 APInt ConstValue;
23765 if (Cond == ISD::SETNE &&
23766 ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
23767 if (ConstValue.isMinSignedValue())
23768 Cond = ISD::SETGT;
23769 else if (ConstValue.isMaxSignedValue())
23770 Cond = ISD::SETLT;
23771 else if (ConstValue.isZero() && DAG.SignBitIsZero(Op0))
23772 Cond = ISD::SETGT;
23775 // If both operands are known non-negative, then an unsigned compare is the
23776 // same as a signed compare and there's no need to flip signbits.
23777 // TODO: We could check for more general simplifications here since we're
23778 // computing known bits.
23779 bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
23780 !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
23782 // Special case: Use min/max operations for unsigned compares.
23783 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23784 if (ISD::isUnsignedIntSetCC(Cond) &&
23785 (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
23786 TLI.isOperationLegal(ISD::UMIN, VT)) {
23787 // If we have a constant operand, increment/decrement it and change the
23788 // condition to avoid an invert.
23789 if (Cond == ISD::SETUGT) {
23790 // X > C --> X >= (C+1) --> X == umax(X, C+1)
23791 if (SDValue UGTOp1 =
23792 incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false)) {
23793 Op1 = UGTOp1;
23794 Cond = ISD::SETUGE;
23797 if (Cond == ISD::SETULT) {
23798 // X < C --> X <= (C-1) --> X == umin(X, C-1)
23799 if (SDValue ULTOp1 =
23800 incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false)) {
23801 Op1 = ULTOp1;
23802 Cond = ISD::SETULE;
23805 bool Invert = false;
23806 unsigned Opc;
23807 switch (Cond) {
23808 // clang-format off
23809 default: llvm_unreachable("Unexpected condition code");
23810 case ISD::SETUGT: Invert = true; [[fallthrough]];
23811 case ISD::SETULE: Opc = ISD::UMIN; break;
23812 case ISD::SETULT: Invert = true; [[fallthrough]];
23813 case ISD::SETUGE: Opc = ISD::UMAX; break;
23814 // clang-format on
23817 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23818 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
23820 // If the logical-not of the result is required, perform that now.
23821 if (Invert)
23822 Result = DAG.getNOT(dl, Result, VT);
23824 return Result;
23827 // Try to use SUBUS and PCMPEQ.
23828 if (FlipSigns)
23829 if (SDValue V =
23830 LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
23831 return V;
23833 // We are handling one of the integer comparisons here. Since SSE only has
23834 // GT and EQ comparisons for integer, swapping operands and multiple
23835 // operations may be required for some comparisons.
23836 unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
23837 : X86ISD::PCMPGT;
23838 bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
23839 Cond == ISD::SETGE || Cond == ISD::SETUGE;
23840 bool Invert = Cond == ISD::SETNE ||
23841 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
23843 if (Swap)
23844 std::swap(Op0, Op1);
23846 // Check that the operation in question is available (most are plain SSE2,
23847 // but PCMPGTQ and PCMPEQQ have different requirements).
23848 if (VT == MVT::v2i64) {
23849 if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
23850 assert(Subtarget.hasSSE2() && "Don't know how to lower!");
23852 // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
23853 // the odd elements over the even elements.
23854 if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
23855 Op0 = DAG.getConstant(0, dl, MVT::v4i32);
23856 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23858 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23859 static const int MaskHi[] = { 1, 1, 3, 3 };
23860 SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23862 return DAG.getBitcast(VT, Result);
23865 if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
23866 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23867 Op1 = DAG.getAllOnesConstant(dl, MVT::v4i32);
23869 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23870 static const int MaskHi[] = { 1, 1, 3, 3 };
23871 SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23873 return DAG.getBitcast(VT, Result);
23876 // If the i64 elements are sign-extended enough to be representable as i32
23877 // then we can compare the lower i32 bits and splat.
23878 if (!FlipSigns && !Invert && DAG.ComputeNumSignBits(Op0) > 32 &&
23879 DAG.ComputeNumSignBits(Op1) > 32) {
23880 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23881 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23883 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23884 static const int MaskLo[] = {0, 0, 2, 2};
23885 SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
23887 return DAG.getBitcast(VT, Result);
23890 // Since SSE has no unsigned integer comparisons, we need to flip the sign
23891 // bits of the inputs before performing those operations. The lower
23892 // compare is always unsigned.
23893 SDValue SB = DAG.getConstant(FlipSigns ? 0x8000000080000000ULL
23894 : 0x0000000080000000ULL,
23895 dl, MVT::v2i64);
23897 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
23898 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
23900 // Cast everything to the right type.
23901 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23902 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23904 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
23905 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23906 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
23908 // Create masks for only the low parts/high parts of the 64 bit integers.
23909 static const int MaskHi[] = { 1, 1, 3, 3 };
23910 static const int MaskLo[] = { 0, 0, 2, 2 };
23911 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
23912 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
23913 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23915 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
23916 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
23918 if (Invert)
23919 Result = DAG.getNOT(dl, Result, MVT::v4i32);
23921 return DAG.getBitcast(VT, Result);
23924 if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
23925 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
23926 // pcmpeqd + pshufd + pand.
23927 assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
23929 // First cast everything to the right type.
23930 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23931 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23933 // Do the compare.
23934 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
23936 // Make sure the lower and upper halves are both all-ones.
23937 static const int Mask[] = { 1, 0, 3, 2 };
23938 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
23939 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
23941 if (Invert)
23942 Result = DAG.getNOT(dl, Result, MVT::v4i32);
23944 return DAG.getBitcast(VT, Result);
23948 // Since SSE has no unsigned integer comparisons, we need to flip the sign
23949 // bits of the inputs before performing those operations.
23950 if (FlipSigns) {
23951 MVT EltVT = VT.getVectorElementType();
23952 SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
23953 VT);
23954 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
23955 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
23958 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23960 // If the logical-not of the result is required, perform that now.
23961 if (Invert)
23962 Result = DAG.getNOT(dl, Result, VT);
23964 return Result;
23967 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
23968 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
23969 const SDLoc &dl, SelectionDAG &DAG,
23970 const X86Subtarget &Subtarget,
23971 SDValue &X86CC) {
23972 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
23974 // Must be a bitcast from vXi1.
23975 if (Op0.getOpcode() != ISD::BITCAST)
23976 return SDValue();
23978 Op0 = Op0.getOperand(0);
23979 MVT VT = Op0.getSimpleValueType();
23980 if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
23981 !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
23982 !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
23983 return SDValue();
23985 X86::CondCode X86Cond;
23986 if (isNullConstant(Op1)) {
23987 X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
23988 } else if (isAllOnesConstant(Op1)) {
23989 // C flag is set for all ones.
23990 X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
23991 } else
23992 return SDValue();
23994 // If the input is an AND, we can combine it's operands into the KTEST.
23995 bool KTestable = false;
23996 if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
23997 KTestable = true;
23998 if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
23999 KTestable = true;
24000 if (!isNullConstant(Op1))
24001 KTestable = false;
24002 if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
24003 SDValue LHS = Op0.getOperand(0);
24004 SDValue RHS = Op0.getOperand(1);
24005 X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24006 return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
24009 // If the input is an OR, we can combine it's operands into the KORTEST.
24010 SDValue LHS = Op0;
24011 SDValue RHS = Op0;
24012 if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
24013 LHS = Op0.getOperand(0);
24014 RHS = Op0.getOperand(1);
24017 X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24018 return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
24021 /// Emit flags for the given setcc condition and operands. Also returns the
24022 /// corresponding X86 condition code constant in X86CC.
24023 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
24024 ISD::CondCode CC, const SDLoc &dl,
24025 SelectionDAG &DAG,
24026 SDValue &X86CC) const {
24027 // Equality Combines.
24028 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
24029 X86::CondCode X86CondCode;
24031 // Optimize to BT if possible.
24032 // Lower (X & (1 << N)) == 0 to BT(X, N).
24033 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
24034 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
24035 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1)) {
24036 if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CondCode)) {
24037 X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
24038 return BT;
24042 // Try to use PTEST/PMOVMSKB for a tree AND/ORs equality compared with -1/0.
24043 if (SDValue CmpZ = MatchVectorAllEqualTest(Op0, Op1, CC, dl, Subtarget, DAG,
24044 X86CondCode)) {
24045 X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
24046 return CmpZ;
24049 // Try to lower using KORTEST or KTEST.
24050 if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
24051 return Test;
24053 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms
24054 // of these.
24055 if (isOneConstant(Op1) || isNullConstant(Op1)) {
24056 // If the input is a setcc, then reuse the input setcc or use a new one
24057 // with the inverted condition.
24058 if (Op0.getOpcode() == X86ISD::SETCC) {
24059 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
24061 X86CC = Op0.getOperand(0);
24062 if (Invert) {
24063 X86CondCode = (X86::CondCode)Op0.getConstantOperandVal(0);
24064 X86CondCode = X86::GetOppositeBranchCondition(X86CondCode);
24065 X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
24068 return Op0.getOperand(1);
24072 // Look for X == INT_MIN or X != INT_MIN. We can use NEG and test for
24073 // overflow.
24074 if (isMinSignedConstant(Op1)) {
24075 EVT VT = Op0.getValueType();
24076 if (VT == MVT::i32 || VT == MVT::i64 || Op0->hasOneUse()) {
24077 SDVTList CmpVTs = DAG.getVTList(VT, MVT::i32);
24078 X86::CondCode CondCode = CC == ISD::SETEQ ? X86::COND_O : X86::COND_NO;
24079 X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24080 SDValue Neg = DAG.getNode(X86ISD::SUB, dl, CmpVTs,
24081 DAG.getConstant(0, dl, VT), Op0);
24082 return SDValue(Neg.getNode(), 1);
24086 // Try to use the carry flag from the add in place of an separate CMP for:
24087 // (seteq (add X, -1), -1). Similar for setne.
24088 if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
24089 Op0.getOperand(1) == Op1) {
24090 if (isProfitableToUseFlagOp(Op0)) {
24091 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
24093 SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
24094 Op0.getOperand(1));
24095 DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
24096 X86CondCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
24097 X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
24098 return SDValue(New.getNode(), 1);
24103 X86::CondCode CondCode =
24104 TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
24105 assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
24107 SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
24108 X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24109 return EFLAGS;
24112 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
24114 bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
24115 Op.getOpcode() == ISD::STRICT_FSETCCS;
24116 MVT VT = Op->getSimpleValueType(0);
24118 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
24120 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
24121 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
24122 SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
24123 SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
24124 SDLoc dl(Op);
24125 ISD::CondCode CC =
24126 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
24128 if (isSoftF16(Op0.getValueType(), Subtarget))
24129 return SDValue();
24131 // Handle f128 first, since one possible outcome is a normal integer
24132 // comparison which gets handled by emitFlagsForSetcc.
24133 if (Op0.getValueType() == MVT::f128) {
24134 softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
24135 Op.getOpcode() == ISD::STRICT_FSETCCS);
24137 // If softenSetCCOperands returned a scalar, use it.
24138 if (!Op1.getNode()) {
24139 assert(Op0.getValueType() == Op.getValueType() &&
24140 "Unexpected setcc expansion!");
24141 if (IsStrict)
24142 return DAG.getMergeValues({Op0, Chain}, dl);
24143 return Op0;
24147 if (Op0.getSimpleValueType().isInteger()) {
24148 // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
24149 // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
24150 // this may translate to less uops depending on uarch implementation. The
24151 // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
24152 // canonicalize to that CondCode.
24153 // NOTE: Only do this if incrementing the constant doesn't increase the bit
24154 // encoding size - so it must either already be a i8 or i32 immediate, or it
24155 // shrinks down to that. We don't do this for any i64's to avoid additional
24156 // constant materializations.
24157 // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
24158 if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
24159 const APInt &Op1Val = Op1C->getAPIntValue();
24160 if (!Op1Val.isZero()) {
24161 // Ensure the constant+1 doesn't overflow.
24162 if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
24163 (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
24164 APInt Op1ValPlusOne = Op1Val + 1;
24165 if (Op1ValPlusOne.isSignedIntN(32) &&
24166 (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
24167 Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
24168 CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
24169 : ISD::CondCode::SETUGE;
24175 SDValue X86CC;
24176 SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
24177 SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24178 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24181 if (Subtarget.hasAVX10_2()) {
24182 if (CC == ISD::SETOEQ || CC == ISD::SETUNE) {
24183 auto NewCC = (CC == ISD::SETOEQ) ? X86::COND_E : (X86::COND_NE);
24184 return getSETCC(NewCC, DAG.getNode(X86ISD::UCOMX, dl, MVT::i32, Op0, Op1),
24185 dl, DAG);
24188 // Handle floating point.
24189 X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
24190 if (CondCode == X86::COND_INVALID)
24191 return SDValue();
24193 SDValue EFLAGS;
24194 if (IsStrict) {
24195 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
24196 EFLAGS =
24197 DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
24198 dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
24199 Chain = EFLAGS.getValue(1);
24200 } else {
24201 EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
24204 SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
24205 SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
24206 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
24209 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
24210 SDValue LHS = Op.getOperand(0);
24211 SDValue RHS = Op.getOperand(1);
24212 SDValue Carry = Op.getOperand(2);
24213 SDValue Cond = Op.getOperand(3);
24214 SDLoc DL(Op);
24216 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
24217 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
24219 // Recreate the carry if needed.
24220 EVT CarryVT = Carry.getValueType();
24221 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
24222 Carry, DAG.getAllOnesConstant(DL, CarryVT));
24224 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
24225 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
24226 return getSETCC(CC, Cmp.getValue(1), DL, DAG);
24229 // This function returns three things: the arithmetic computation itself
24230 // (Value), an EFLAGS result (Overflow), and a condition code (Cond). The
24231 // flag and the condition code define the case in which the arithmetic
24232 // computation overflows.
24233 static std::pair<SDValue, SDValue>
24234 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
24235 assert(Op.getResNo() == 0 && "Unexpected result number!");
24236 SDValue Value, Overflow;
24237 SDValue LHS = Op.getOperand(0);
24238 SDValue RHS = Op.getOperand(1);
24239 unsigned BaseOp = 0;
24240 SDLoc DL(Op);
24241 switch (Op.getOpcode()) {
24242 default: llvm_unreachable("Unknown ovf instruction!");
24243 case ISD::SADDO:
24244 BaseOp = X86ISD::ADD;
24245 Cond = X86::COND_O;
24246 break;
24247 case ISD::UADDO:
24248 BaseOp = X86ISD::ADD;
24249 Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
24250 break;
24251 case ISD::SSUBO:
24252 BaseOp = X86ISD::SUB;
24253 Cond = X86::COND_O;
24254 break;
24255 case ISD::USUBO:
24256 BaseOp = X86ISD::SUB;
24257 Cond = X86::COND_B;
24258 break;
24259 case ISD::SMULO:
24260 BaseOp = X86ISD::SMUL;
24261 Cond = X86::COND_O;
24262 break;
24263 case ISD::UMULO:
24264 BaseOp = X86ISD::UMUL;
24265 Cond = X86::COND_O;
24266 break;
24269 if (BaseOp) {
24270 // Also sets EFLAGS.
24271 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
24272 Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
24273 Overflow = Value.getValue(1);
24276 return std::make_pair(Value, Overflow);
24279 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
24280 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
24281 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
24282 // looks for this combo and may remove the "setcc" instruction if the "setcc"
24283 // has only one use.
24284 SDLoc DL(Op);
24285 X86::CondCode Cond;
24286 SDValue Value, Overflow;
24287 std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
24289 SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
24290 assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
24291 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
24294 /// Return true if opcode is a X86 logical comparison.
24295 static bool isX86LogicalCmp(SDValue Op) {
24296 unsigned Opc = Op.getOpcode();
24297 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
24298 Opc == X86ISD::FCMP)
24299 return true;
24300 if (Op.getResNo() == 1 &&
24301 (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
24302 Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
24303 Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
24304 return true;
24306 return false;
24309 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
24310 if (V.getOpcode() != ISD::TRUNCATE)
24311 return false;
24313 SDValue VOp0 = V.getOperand(0);
24314 unsigned InBits = VOp0.getValueSizeInBits();
24315 unsigned Bits = V.getValueSizeInBits();
24316 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
24319 // Lower various (select (icmp CmpVal, 0), LHS, RHS) custom patterns.
24320 static SDValue LowerSELECTWithCmpZero(SDValue CmpVal, SDValue LHS, SDValue RHS,
24321 unsigned X86CC, const SDLoc &DL,
24322 SelectionDAG &DAG,
24323 const X86Subtarget &Subtarget) {
24324 EVT CmpVT = CmpVal.getValueType();
24325 EVT VT = LHS.getValueType();
24326 if (!CmpVT.isScalarInteger() || !VT.isScalarInteger())
24327 return SDValue();
24329 if (X86CC == X86::COND_E && CmpVal.getOpcode() == ISD::AND &&
24330 isOneConstant(CmpVal.getOperand(1))) {
24331 auto SplatLSB = [&](EVT SplatVT) {
24332 // we need mask of all zeros or ones with same size of the other
24333 // operands.
24334 SDValue Neg = CmpVal;
24335 if (CmpVT.bitsGT(SplatVT))
24336 Neg = DAG.getNode(ISD::TRUNCATE, DL, SplatVT, CmpVal);
24337 else if (CmpVT.bitsLT(SplatVT))
24338 Neg = DAG.getNode(
24339 ISD::AND, DL, SplatVT,
24340 DAG.getNode(ISD::ANY_EXTEND, DL, SplatVT, CmpVal.getOperand(0)),
24341 DAG.getConstant(1, DL, SplatVT));
24342 return DAG.getNegative(Neg, DL, SplatVT); // -(and (x, 0x1))
24345 // SELECT (AND(X,1) == 0), 0, -1 -> NEG(AND(X,1))
24346 if (isNullConstant(LHS) && isAllOnesConstant(RHS))
24347 return SplatLSB(VT);
24349 // SELECT (AND(X,1) == 0), C1, C2 -> XOR(C1,AND(NEG(AND(X,1)),XOR(C1,C2))
24350 if (!Subtarget.canUseCMOV() && isa<ConstantSDNode>(LHS) &&
24351 isa<ConstantSDNode>(RHS)) {
24352 SDValue Mask = SplatLSB(VT);
24353 SDValue Diff = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
24354 SDValue Flip = DAG.getNode(ISD::AND, DL, VT, Mask, Diff);
24355 return DAG.getNode(ISD::XOR, DL, VT, LHS, Flip);
24358 SDValue Src1, Src2;
24359 auto isIdentityPatternZero = [&]() {
24360 switch (RHS.getOpcode()) {
24361 default:
24362 break;
24363 case ISD::OR:
24364 case ISD::XOR:
24365 case ISD::ADD:
24366 if (RHS.getOperand(0) == LHS || RHS.getOperand(1) == LHS) {
24367 Src1 = RHS.getOperand(RHS.getOperand(0) == LHS ? 1 : 0);
24368 Src2 = LHS;
24369 return true;
24371 break;
24372 case ISD::SHL:
24373 case ISD::SRA:
24374 case ISD::SRL:
24375 case ISD::SUB:
24376 if (RHS.getOperand(0) == LHS) {
24377 Src1 = RHS.getOperand(1);
24378 Src2 = LHS;
24379 return true;
24381 break;
24383 return false;
24386 auto isIdentityPatternOnes = [&]() {
24387 switch (LHS.getOpcode()) {
24388 default:
24389 break;
24390 case ISD::AND:
24391 if (LHS.getOperand(0) == RHS || LHS.getOperand(1) == RHS) {
24392 Src1 = LHS.getOperand(LHS.getOperand(0) == RHS ? 1 : 0);
24393 Src2 = RHS;
24394 return true;
24396 break;
24398 return false;
24401 // Convert 'identity' patterns (iff X is 0 or 1):
24402 // SELECT (AND(X,1) == 0), Y, (OR Y, Z) -> (OR Y, (AND NEG(AND(X,1)), Z))
24403 // SELECT (AND(X,1) == 0), Y, (XOR Y, Z) -> (XOR Y, (AND NEG(AND(X,1)), Z))
24404 // SELECT (AND(X,1) == 0), Y, (ADD Y, Z) -> (ADD Y, (AND NEG(AND(X,1)), Z))
24405 // SELECT (AND(X,1) == 0), Y, (SUB Y, Z) -> (SUB Y, (AND NEG(AND(X,1)), Z))
24406 // SELECT (AND(X,1) == 0), Y, (SHL Y, Z) -> (SHL Y, (AND NEG(AND(X,1)), Z))
24407 // SELECT (AND(X,1) == 0), Y, (SRA Y, Z) -> (SRA Y, (AND NEG(AND(X,1)), Z))
24408 // SELECT (AND(X,1) == 0), Y, (SRL Y, Z) -> (SRL Y, (AND NEG(AND(X,1)), Z))
24409 if (!Subtarget.canUseCMOV() && isIdentityPatternZero()) {
24410 SDValue Mask = SplatLSB(Src1.getValueType());
24411 SDValue And = DAG.getNode(ISD::AND, DL, Src1.getValueType(), Mask,
24412 Src1); // Mask & z
24413 return DAG.getNode(RHS.getOpcode(), DL, VT, Src2, And); // y Op And
24415 // SELECT (AND(X,1) == 0), (AND Y, Z), Y -> (AND Y, (OR NEG(AND(X, 1)), Z))
24416 if (!Subtarget.canUseCMOV() && isIdentityPatternOnes()) {
24417 SDValue Mask = SplatLSB(VT);
24418 SDValue Or = DAG.getNode(ISD::OR, DL, VT, Mask, Src1); // Mask | z
24419 return DAG.getNode(LHS.getOpcode(), DL, VT, Src2, Or); // y Op Or
24423 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
24424 (isAllOnesConstant(LHS) || isAllOnesConstant(RHS))) {
24425 SDValue Y = isAllOnesConstant(RHS) ? LHS : RHS;
24426 SDVTList CmpVTs = DAG.getVTList(CmpVT, MVT::i32);
24428 // 'X - 1' sets the carry flag if X == 0.
24429 // '0 - X' sets the carry flag if X != 0.
24430 // Convert the carry flag to a -1/0 mask with sbb:
24431 // select (X != 0), -1, Y --> 0 - X; or (sbb), Y
24432 // select (X == 0), Y, -1 --> 0 - X; or (sbb), Y
24433 // select (X != 0), Y, -1 --> X - 1; or (sbb), Y
24434 // select (X == 0), -1, Y --> X - 1; or (sbb), Y
24435 SDValue Sub;
24436 if (isAllOnesConstant(LHS) == (X86CC == X86::COND_NE)) {
24437 SDValue Zero = DAG.getConstant(0, DL, CmpVT);
24438 Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpVal);
24439 } else {
24440 SDValue One = DAG.getConstant(1, DL, CmpVT);
24441 Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, CmpVal, One);
24443 SDValue SBB = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24444 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
24445 Sub.getValue(1));
24446 return DAG.getNode(ISD::OR, DL, VT, SBB, Y);
24449 return SDValue();
24452 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
24453 bool AddTest = true;
24454 SDValue Cond = Op.getOperand(0);
24455 SDValue Op1 = Op.getOperand(1);
24456 SDValue Op2 = Op.getOperand(2);
24457 SDLoc DL(Op);
24458 MVT VT = Op1.getSimpleValueType();
24459 SDValue CC;
24461 if (isSoftF16(VT, Subtarget)) {
24462 MVT NVT = VT.changeTypeToInteger();
24463 return DAG.getBitcast(VT, DAG.getNode(ISD::SELECT, DL, NVT, Cond,
24464 DAG.getBitcast(NVT, Op1),
24465 DAG.getBitcast(NVT, Op2)));
24468 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
24469 // are available or VBLENDV if AVX is available.
24470 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
24471 if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
24472 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
24473 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
24474 bool IsAlwaysSignaling;
24475 unsigned SSECC =
24476 translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
24477 CondOp0, CondOp1, IsAlwaysSignaling);
24479 if (Subtarget.hasAVX512()) {
24480 SDValue Cmp =
24481 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
24482 DAG.getTargetConstant(SSECC, DL, MVT::i8));
24483 assert(!VT.isVector() && "Not a scalar type?");
24484 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
24487 if (SSECC < 8 || Subtarget.hasAVX()) {
24488 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
24489 DAG.getTargetConstant(SSECC, DL, MVT::i8));
24491 // If we have AVX, we can use a variable vector select (VBLENDV) instead
24492 // of 3 logic instructions for size savings and potentially speed.
24493 // Unfortunately, there is no scalar form of VBLENDV.
24495 // If either operand is a +0.0 constant, don't try this. We can expect to
24496 // optimize away at least one of the logic instructions later in that
24497 // case, so that sequence would be faster than a variable blend.
24499 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
24500 // uses XMM0 as the selection register. That may need just as many
24501 // instructions as the AND/ANDN/OR sequence due to register moves, so
24502 // don't bother.
24503 if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
24504 !isNullFPConstant(Op2)) {
24505 // Convert to vectors, do a VSELECT, and convert back to scalar.
24506 // All of the conversions should be optimized away.
24507 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
24508 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
24509 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
24510 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
24512 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
24513 VCmp = DAG.getBitcast(VCmpVT, VCmp);
24515 SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
24517 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
24518 VSel, DAG.getIntPtrConstant(0, DL));
24520 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
24521 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
24522 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
24526 // AVX512 fallback is to lower selects of scalar floats to masked moves.
24527 if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
24528 SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
24529 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
24532 if (Cond.getOpcode() == ISD::SETCC &&
24533 !isSoftF16(Cond.getOperand(0).getSimpleValueType(), Subtarget)) {
24534 if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
24535 Cond = NewCond;
24536 // If the condition was updated, it's possible that the operands of the
24537 // select were also updated (for example, EmitTest has a RAUW). Refresh
24538 // the local references to the select operands in case they got stale.
24539 Op1 = Op.getOperand(1);
24540 Op2 = Op.getOperand(2);
24544 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
24545 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
24546 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
24547 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
24548 // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
24549 // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
24550 // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
24551 // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
24552 if (Cond.getOpcode() == X86ISD::SETCC &&
24553 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
24554 isNullConstant(Cond.getOperand(1).getOperand(1))) {
24555 SDValue Cmp = Cond.getOperand(1);
24556 SDValue CmpOp0 = Cmp.getOperand(0);
24557 unsigned CondCode = Cond.getConstantOperandVal(0);
24559 // Special handling for __builtin_ffs(X) - 1 pattern which looks like
24560 // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
24561 // handle to keep the CMP with 0. This should be removed by
24562 // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
24563 // cttz_zero_undef.
24564 auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
24565 return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
24566 Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
24568 if (Subtarget.canUseCMOV() && (VT == MVT::i32 || VT == MVT::i64) &&
24569 ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
24570 (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
24571 // Keep Cmp.
24572 } else if (SDValue R = LowerSELECTWithCmpZero(CmpOp0, Op1, Op2, CondCode,
24573 DL, DAG, Subtarget)) {
24574 return R;
24575 } else if ((VT == MVT::i32 || VT == MVT::i64) && isNullConstant(Op2) &&
24576 Cmp.getNode()->hasOneUse() && (CmpOp0 == Op1) &&
24577 ((CondCode == X86::COND_S) || // smin(x, 0)
24578 (CondCode == X86::COND_G && hasAndNot(Op1)))) { // smax(x, 0)
24579 // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
24581 // If the comparison is testing for a positive value, we have to invert
24582 // the sign bit mask, so only do that transform if the target has a
24583 // bitwise 'and not' instruction (the invert is free).
24584 // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
24585 unsigned ShCt = VT.getSizeInBits() - 1;
24586 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, VT);
24587 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, Op1, ShiftAmt);
24588 if (CondCode == X86::COND_G)
24589 Shift = DAG.getNOT(DL, Shift, VT);
24590 return DAG.getNode(ISD::AND, DL, VT, Shift, Op1);
24594 // Look past (and (setcc_carry (cmp ...)), 1).
24595 if (Cond.getOpcode() == ISD::AND &&
24596 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
24597 isOneConstant(Cond.getOperand(1)))
24598 Cond = Cond.getOperand(0);
24600 // Attempt to fold "raw cond" cases by treating them as:
24601 // (select (and X, 1), Op1, Op2 --> (select (icmpeq (and X, 1), 0), Op2, Op1)
24602 if (Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1)))
24603 if (SDValue R = LowerSELECTWithCmpZero(Cond, Op2, Op1, X86::COND_E, DL, DAG,
24604 Subtarget))
24605 return R;
24607 // If condition flag is set by a X86ISD::CMP, then use it as the condition
24608 // setting operand in place of the X86ISD::SETCC.
24609 unsigned CondOpcode = Cond.getOpcode();
24610 if (CondOpcode == X86ISD::SETCC ||
24611 CondOpcode == X86ISD::SETCC_CARRY) {
24612 CC = Cond.getOperand(0);
24614 SDValue Cmp = Cond.getOperand(1);
24615 bool IllegalFPCMov = false;
24616 if (VT.isFloatingPoint() && !VT.isVector() &&
24617 !isScalarFPTypeInSSEReg(VT) && Subtarget.canUseCMOV()) // FPStack?
24618 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
24620 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
24621 Cmp.getOpcode() == X86ISD::BT) { // FIXME
24622 Cond = Cmp;
24623 AddTest = false;
24625 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
24626 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
24627 CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
24628 SDValue Value;
24629 X86::CondCode X86Cond;
24630 std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24632 CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
24633 AddTest = false;
24636 if (AddTest) {
24637 // Look past the truncate if the high bits are known zero.
24638 if (isTruncWithZeroHighBitsInput(Cond, DAG))
24639 Cond = Cond.getOperand(0);
24641 // We know the result of AND is compared against zero. Try to match
24642 // it to BT.
24643 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
24644 X86::CondCode X86CondCode;
24645 if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, X86CondCode)) {
24646 CC = DAG.getTargetConstant(X86CondCode, DL, MVT::i8);
24647 Cond = BT;
24648 AddTest = false;
24653 if (AddTest) {
24654 CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
24655 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
24658 // a < b ? -1 : 0 -> RES = ~setcc_carry
24659 // a < b ? 0 : -1 -> RES = setcc_carry
24660 // a >= b ? -1 : 0 -> RES = setcc_carry
24661 // a >= b ? 0 : -1 -> RES = ~setcc_carry
24662 if (Cond.getOpcode() == X86ISD::SUB) {
24663 unsigned CondCode = CC->getAsZExtVal();
24665 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
24666 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
24667 (isNullConstant(Op1) || isNullConstant(Op2))) {
24668 SDValue Res =
24669 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
24670 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
24671 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
24672 return DAG.getNOT(DL, Res, Res.getValueType());
24673 return Res;
24677 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
24678 // widen the cmov and push the truncate through. This avoids introducing a new
24679 // branch during isel and doesn't add any extensions.
24680 if (Op.getValueType() == MVT::i8 &&
24681 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
24682 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
24683 if (T1.getValueType() == T2.getValueType() &&
24684 // Exclude CopyFromReg to avoid partial register stalls.
24685 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
24686 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
24687 CC, Cond);
24688 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24692 // Or finally, promote i8 cmovs if we have CMOV,
24693 // or i16 cmovs if it won't prevent folding a load.
24694 // FIXME: we should not limit promotion of i8 case to only when the CMOV is
24695 // legal, but EmitLoweredSelect() can not deal with these extensions
24696 // being inserted between two CMOV's. (in i16 case too TBN)
24697 // https://bugs.llvm.org/show_bug.cgi?id=40974
24698 if ((Op.getValueType() == MVT::i8 && Subtarget.canUseCMOV()) ||
24699 (Op.getValueType() == MVT::i16 && !X86::mayFoldLoad(Op1, Subtarget) &&
24700 !X86::mayFoldLoad(Op2, Subtarget))) {
24701 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
24702 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
24703 SDValue Ops[] = { Op2, Op1, CC, Cond };
24704 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
24705 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24708 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
24709 // condition is true.
24710 SDValue Ops[] = { Op2, Op1, CC, Cond };
24711 return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops, Op->getFlags());
24714 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op, const SDLoc &dl,
24715 const X86Subtarget &Subtarget,
24716 SelectionDAG &DAG) {
24717 MVT VT = Op->getSimpleValueType(0);
24718 SDValue In = Op->getOperand(0);
24719 MVT InVT = In.getSimpleValueType();
24720 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
24721 MVT VTElt = VT.getVectorElementType();
24722 unsigned NumElts = VT.getVectorNumElements();
24724 // Extend VT if the scalar type is i8/i16 and BWI is not supported.
24725 MVT ExtVT = VT;
24726 if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
24727 // If v16i32 is to be avoided, we'll need to split and concatenate.
24728 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
24729 return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
24731 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
24734 // Widen to 512-bits if VLX is not supported.
24735 MVT WideVT = ExtVT;
24736 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
24737 NumElts *= 512 / ExtVT.getSizeInBits();
24738 InVT = MVT::getVectorVT(MVT::i1, NumElts);
24739 In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
24740 In, DAG.getIntPtrConstant(0, dl));
24741 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
24744 SDValue V;
24745 MVT WideEltVT = WideVT.getVectorElementType();
24746 if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
24747 (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
24748 V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
24749 } else {
24750 SDValue NegOne = DAG.getAllOnesConstant(dl, WideVT);
24751 SDValue Zero = DAG.getConstant(0, dl, WideVT);
24752 V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
24755 // Truncate if we had to extend i16/i8 above.
24756 if (VT != ExtVT) {
24757 WideVT = MVT::getVectorVT(VTElt, NumElts);
24758 V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
24761 // Extract back to 128/256-bit if we widened.
24762 if (WideVT != VT)
24763 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
24764 DAG.getIntPtrConstant(0, dl));
24766 return V;
24769 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24770 SelectionDAG &DAG) {
24771 SDValue In = Op->getOperand(0);
24772 MVT InVT = In.getSimpleValueType();
24773 SDLoc DL(Op);
24775 if (InVT.getVectorElementType() == MVT::i1)
24776 return LowerSIGN_EXTEND_Mask(Op, DL, Subtarget, DAG);
24778 assert(Subtarget.hasAVX() && "Expected AVX support");
24779 return LowerAVXExtend(Op, DL, DAG, Subtarget);
24782 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
24783 // For sign extend this needs to handle all vector sizes and SSE4.1 and
24784 // non-SSE4.1 targets. For zero extend this should only handle inputs of
24785 // MVT::v64i8 when BWI is not supported, but AVX512 is.
24786 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
24787 const X86Subtarget &Subtarget,
24788 SelectionDAG &DAG) {
24789 SDValue In = Op->getOperand(0);
24790 MVT VT = Op->getSimpleValueType(0);
24791 MVT InVT = In.getSimpleValueType();
24793 MVT SVT = VT.getVectorElementType();
24794 MVT InSVT = InVT.getVectorElementType();
24795 assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
24797 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
24798 return SDValue();
24799 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
24800 return SDValue();
24801 if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
24802 !(VT.is256BitVector() && Subtarget.hasAVX()) &&
24803 !(VT.is512BitVector() && Subtarget.hasAVX512()))
24804 return SDValue();
24806 SDLoc dl(Op);
24807 unsigned Opc = Op.getOpcode();
24808 unsigned NumElts = VT.getVectorNumElements();
24810 // For 256-bit vectors, we only need the lower (128-bit) half of the input.
24811 // For 512-bit vectors, we need 128-bits or 256-bits.
24812 if (InVT.getSizeInBits() > 128) {
24813 // Input needs to be at least the same number of elements as output, and
24814 // at least 128-bits.
24815 int InSize = InSVT.getSizeInBits() * NumElts;
24816 In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
24817 InVT = In.getSimpleValueType();
24820 // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
24821 // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
24822 // need to be handled here for 256/512-bit results.
24823 if (Subtarget.hasInt256()) {
24824 assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
24826 if (InVT.getVectorNumElements() != NumElts)
24827 return DAG.getNode(Op.getOpcode(), dl, VT, In);
24829 // FIXME: Apparently we create inreg operations that could be regular
24830 // extends.
24831 unsigned ExtOpc =
24832 Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
24833 : ISD::ZERO_EXTEND;
24834 return DAG.getNode(ExtOpc, dl, VT, In);
24837 // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
24838 if (Subtarget.hasAVX()) {
24839 assert(VT.is256BitVector() && "256-bit vector expected");
24840 MVT HalfVT = VT.getHalfNumVectorElementsVT();
24841 int HalfNumElts = HalfVT.getVectorNumElements();
24843 unsigned NumSrcElts = InVT.getVectorNumElements();
24844 SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
24845 for (int i = 0; i != HalfNumElts; ++i)
24846 HiMask[i] = HalfNumElts + i;
24848 SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
24849 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
24850 Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
24851 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
24854 // We should only get here for sign extend.
24855 assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
24856 assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
24857 unsigned InNumElts = InVT.getVectorNumElements();
24859 // If the source elements are already all-signbits, we don't need to extend,
24860 // just splat the elements.
24861 APInt DemandedElts = APInt::getLowBitsSet(InNumElts, NumElts);
24862 if (DAG.ComputeNumSignBits(In, DemandedElts) == InVT.getScalarSizeInBits()) {
24863 unsigned Scale = InNumElts / NumElts;
24864 SmallVector<int, 16> ShuffleMask;
24865 for (unsigned I = 0; I != NumElts; ++I)
24866 ShuffleMask.append(Scale, I);
24867 return DAG.getBitcast(VT,
24868 DAG.getVectorShuffle(InVT, dl, In, In, ShuffleMask));
24871 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
24872 SDValue Curr = In;
24873 SDValue SignExt = Curr;
24875 // As SRAI is only available on i16/i32 types, we expand only up to i32
24876 // and handle i64 separately.
24877 if (InVT != MVT::v4i32) {
24878 MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
24880 unsigned DestWidth = DestVT.getScalarSizeInBits();
24881 unsigned Scale = DestWidth / InSVT.getSizeInBits();
24882 unsigned DestElts = DestVT.getVectorNumElements();
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;
24890 Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
24891 Curr = DAG.getBitcast(DestVT, Curr);
24893 unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
24894 SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
24895 DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
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);
24906 return SignExt;
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);
24916 if (InVT.getVectorElementType() == MVT::i1)
24917 return LowerSIGN_EXTEND_Mask(Op, dl, Subtarget, DAG);
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");
24931 if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
24932 assert(InVT == MVT::v32i8 && "Unexpected VT!");
24933 return splitVectorIntUnary(Op, DAG, dl);
24936 if (Subtarget.hasInt256())
24937 return Op;
24939 // Optimize vectors in AVX mode
24940 // Sign extend v8i16 to v8i32 and
24941 // v4i32 to v4i64
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);
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;
24955 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
24956 OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
24958 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
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");
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();
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::getFixed(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);
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);
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();
25009 MVT StoreSVT = StoreVT.getScalarType();
25010 unsigned NumElems = StoreVT.getVectorNumElements();
25011 unsigned ScalarSize = StoreSVT.getStoreSize();
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::getFixed(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);
25027 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
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();
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");
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));
25056 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25057 St->getPointerInfo(), St->getOriginalAlign(),
25058 St->getMemOperand()->getFlags());
25061 if (St->isTruncatingStore())
25062 return SDValue();
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 if (StoredVal.hasOneUse() && isFreeToSplitVector(StoredVal.getNode(), DAG))
25073 return splitVectorStore(St, DAG);
25074 return SDValue();
25077 if (StoreVT.is32BitVector())
25078 return SDValue();
25080 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25081 assert(StoreVT.is64BitVector() && "Unexpected VT");
25082 assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
25083 TargetLowering::TypeWidenVector &&
25084 "Unexpected type action!");
25086 EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
25087 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
25088 DAG.getUNDEF(StoreVT));
25090 if (Subtarget.hasSSE2()) {
25091 // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
25092 // and store it.
25093 MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
25094 MVT CastVT = MVT::getVectorVT(StVT, 2);
25095 StoredVal = DAG.getBitcast(CastVT, StoredVal);
25096 StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
25097 DAG.getIntPtrConstant(0, dl));
25099 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
25100 St->getPointerInfo(), St->getOriginalAlign(),
25101 St->getMemOperand()->getFlags());
25103 assert(Subtarget.hasSSE1() && "Expected SSE");
25104 SDVTList Tys = DAG.getVTList(MVT::Other);
25105 SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
25106 return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
25107 St->getMemOperand());
25110 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
25111 // may emit an illegal shuffle but the expansion is still better than scalar
25112 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
25113 // we'll emit a shuffle and a arithmetic shift.
25114 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
25115 // TODO: It is possible to support ZExt by zeroing the undef values during
25116 // the shuffle phase or after the shuffle.
25117 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
25118 SelectionDAG &DAG) {
25119 MVT RegVT = Op.getSimpleValueType();
25120 assert(RegVT.isVector() && "We only custom lower vector loads.");
25121 assert(RegVT.isInteger() &&
25122 "We only custom lower integer vector loads.");
25124 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
25125 SDLoc dl(Ld);
25127 // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
25128 if (RegVT.getVectorElementType() == MVT::i1) {
25129 assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
25130 assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
25131 assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
25132 "Expected AVX512F without AVX512DQI");
25134 SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
25135 Ld->getPointerInfo(), Ld->getOriginalAlign(),
25136 Ld->getMemOperand()->getFlags());
25138 // Replace chain users with the new chain.
25139 assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
25141 SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
25142 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
25143 DAG.getBitcast(MVT::v16i1, Val),
25144 DAG.getIntPtrConstant(0, dl));
25145 return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
25148 return SDValue();
25151 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
25152 /// each of which has no other use apart from the AND / OR.
25153 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
25154 Opc = Op.getOpcode();
25155 if (Opc != ISD::OR && Opc != ISD::AND)
25156 return false;
25157 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
25158 Op.getOperand(0).hasOneUse() &&
25159 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
25160 Op.getOperand(1).hasOneUse());
25163 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
25164 SDValue Chain = Op.getOperand(0);
25165 SDValue Cond = Op.getOperand(1);
25166 SDValue Dest = Op.getOperand(2);
25167 SDLoc dl(Op);
25169 // Bail out when we don't have native compare instructions.
25170 if (Cond.getOpcode() == ISD::SETCC &&
25171 Cond.getOperand(0).getValueType() != MVT::f128 &&
25172 !isSoftF16(Cond.getOperand(0).getValueType(), Subtarget)) {
25173 SDValue LHS = Cond.getOperand(0);
25174 SDValue RHS = Cond.getOperand(1);
25175 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
25177 // Special case for
25178 // setcc([su]{add,sub,mul}o == 0)
25179 // setcc([su]{add,sub,mul}o != 1)
25180 if (ISD::isOverflowIntrOpRes(LHS) &&
25181 (CC == ISD::SETEQ || CC == ISD::SETNE) &&
25182 (isNullConstant(RHS) || isOneConstant(RHS))) {
25183 SDValue Value, Overflow;
25184 X86::CondCode X86Cond;
25185 std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
25187 if ((CC == ISD::SETEQ) == isNullConstant(RHS))
25188 X86Cond = X86::GetOppositeBranchCondition(X86Cond);
25190 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25191 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25192 Overflow, Op->getFlags());
25195 if (LHS.getSimpleValueType().isInteger()) {
25196 SDValue CCVal;
25197 SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
25198 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25199 EFLAGS, Op->getFlags());
25202 if (CC == ISD::SETOEQ) {
25203 // For FCMP_OEQ, we can emit
25204 // two branches instead of an explicit AND instruction with a
25205 // separate test. However, we only do this if this block doesn't
25206 // have a fall-through edge, because this requires an explicit
25207 // jmp when the condition is false.
25208 if (Op.getNode()->hasOneUse()) {
25209 SDNode *User = *Op.getNode()->use_begin();
25210 // Look for an unconditional branch following this conditional branch.
25211 // We need this because we need to reverse the successors in order
25212 // to implement FCMP_OEQ.
25213 if (User->getOpcode() == ISD::BR) {
25214 SDValue FalseBB = User->getOperand(1);
25215 SDNode *NewBR =
25216 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
25217 assert(NewBR == User);
25218 (void)NewBR;
25219 Dest = FalseBB;
25221 SDValue Cmp =
25222 DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25223 SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25224 Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
25225 CCVal, Cmp, Op->getFlags());
25226 CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25227 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25228 Cmp, Op->getFlags());
25231 } else if (CC == ISD::SETUNE) {
25232 // For FCMP_UNE, we can emit
25233 // two branches instead of an explicit OR instruction with a
25234 // separate test.
25235 SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25236 SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
25237 Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25238 Cmp, Op->getFlags());
25239 CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
25240 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25241 Cmp, Op->getFlags());
25242 } else {
25243 X86::CondCode X86Cond =
25244 TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
25245 SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
25246 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25247 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25248 Cmp, Op->getFlags());
25252 if (ISD::isOverflowIntrOpRes(Cond)) {
25253 SDValue Value, Overflow;
25254 X86::CondCode X86Cond;
25255 std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
25257 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
25258 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
25259 Overflow, Op->getFlags());
25262 // Look past the truncate if the high bits are known zero.
25263 if (isTruncWithZeroHighBitsInput(Cond, DAG))
25264 Cond = Cond.getOperand(0);
25266 EVT CondVT = Cond.getValueType();
25268 // Add an AND with 1 if we don't already have one.
25269 if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
25270 Cond =
25271 DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
25273 SDValue LHS = Cond;
25274 SDValue RHS = DAG.getConstant(0, dl, CondVT);
25276 SDValue CCVal;
25277 SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
25278 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, EFLAGS,
25279 Op->getFlags());
25282 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
25283 // Calls to _alloca are needed to probe the stack when allocating more than 4k
25284 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
25285 // that the guard pages used by the OS virtual memory manager are allocated in
25286 // correct sequence.
25287 SDValue
25288 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
25289 SelectionDAG &DAG) const {
25290 MachineFunction &MF = DAG.getMachineFunction();
25291 bool SplitStack = MF.shouldSplitStack();
25292 bool EmitStackProbeCall = hasStackProbeSymbol(MF);
25293 bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
25294 SplitStack || EmitStackProbeCall;
25295 SDLoc dl(Op);
25297 // Get the inputs.
25298 SDNode *Node = Op.getNode();
25299 SDValue Chain = Op.getOperand(0);
25300 SDValue Size = Op.getOperand(1);
25301 MaybeAlign Alignment(Op.getConstantOperandVal(2));
25302 EVT VT = Node->getValueType(0);
25304 // Chain the dynamic stack allocation so that it doesn't modify the stack
25305 // pointer when other instructions are using the stack.
25306 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
25308 bool Is64Bit = Subtarget.is64Bit();
25309 MVT SPTy = getPointerTy(DAG.getDataLayout());
25311 SDValue Result;
25312 if (!Lower) {
25313 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25314 Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
25315 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
25316 " not tell us which reg is the stack pointer!");
25318 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25319 const Align StackAlign = TFI.getStackAlign();
25320 if (hasInlineStackProbe(MF)) {
25321 Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, {SPTy, MVT::Other},
25322 {Chain, Size});
25323 Chain = Result.getValue(1);
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
25329 if (Alignment && *Alignment > StackAlign)
25330 Result = DAG.getNode(
25331 ISD::AND, dl, VT, Result,
25332 DAG.getSignedConstant(~(Alignment->value() - 1ULL), dl, VT));
25333 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
25334 } else if (SplitStack) {
25335 if (Is64Bit) {
25336 // The 64 bit implementation of segmented stacks needs to clobber both r10
25337 // r11. This makes it impossible to use it along with nested parameters.
25338 const Function &F = MF.getFunction();
25339 for (const auto &A : F.args()) {
25340 if (A.hasNestAttr())
25341 report_fatal_error("Cannot use segmented stacks with functions that "
25342 "have nested arguments.");
25346 Result =
25347 DAG.getNode(X86ISD::SEG_ALLOCA, dl, {SPTy, MVT::Other}, {Chain, Size});
25348 Chain = Result.getValue(1);
25349 } else {
25350 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
25351 Chain = DAG.getNode(X86ISD::DYN_ALLOCA, dl, NodeTys, Chain, Size);
25352 MF.getInfo<X86MachineFunctionInfo>()->setHasDynAlloca(true);
25354 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25355 Register SPReg = RegInfo->getStackRegister();
25356 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
25357 Chain = SP.getValue(1);
25359 if (Alignment) {
25360 SP = DAG.getNode(
25361 ISD::AND, dl, VT, SP.getValue(0),
25362 DAG.getSignedConstant(~(Alignment->value() - 1ULL), dl, VT));
25363 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
25366 Result = SP;
25369 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
25371 SDValue Ops[2] = {Result, Chain};
25372 return DAG.getMergeValues(Ops, dl);
25375 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
25376 MachineFunction &MF = DAG.getMachineFunction();
25377 auto PtrVT = getPointerTy(MF.getDataLayout());
25378 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
25380 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
25381 SDLoc DL(Op);
25383 if (!Subtarget.is64Bit() ||
25384 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
25385 // vastart just stores the address of the VarArgsFrameIndex slot into the
25386 // memory location argument.
25387 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
25388 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
25389 MachinePointerInfo(SV));
25392 // __va_list_tag:
25393 // gp_offset (0 - 6 * 8)
25394 // fp_offset (48 - 48 + 8 * 16)
25395 // overflow_arg_area (point to parameters coming in memory).
25396 // reg_save_area
25397 SmallVector<SDValue, 8> MemOps;
25398 SDValue FIN = Op.getOperand(1);
25399 // Store gp_offset
25400 SDValue Store = DAG.getStore(
25401 Op.getOperand(0), DL,
25402 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
25403 MachinePointerInfo(SV));
25404 MemOps.push_back(Store);
25406 // Store fp_offset
25407 FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::getFixed(4), DL);
25408 Store = DAG.getStore(
25409 Op.getOperand(0), DL,
25410 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
25411 MachinePointerInfo(SV, 4));
25412 MemOps.push_back(Store);
25414 // Store ptr to overflow_arg_area
25415 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
25416 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
25417 Store =
25418 DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
25419 MemOps.push_back(Store);
25421 // Store ptr to reg_save_area.
25422 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
25423 Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
25424 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
25425 Store = DAG.getStore(
25426 Op.getOperand(0), DL, RSFIN, FIN,
25427 MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
25428 MemOps.push_back(Store);
25429 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
25432 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
25433 assert(Subtarget.is64Bit() &&
25434 "LowerVAARG only handles 64-bit va_arg!");
25435 assert(Op.getNumOperands() == 4);
25437 MachineFunction &MF = DAG.getMachineFunction();
25438 if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
25439 // The Win64 ABI uses char* instead of a structure.
25440 return DAG.expandVAArg(Op.getNode());
25442 SDValue Chain = Op.getOperand(0);
25443 SDValue SrcPtr = Op.getOperand(1);
25444 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
25445 unsigned Align = Op.getConstantOperandVal(3);
25446 SDLoc dl(Op);
25448 EVT ArgVT = Op.getNode()->getValueType(0);
25449 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
25450 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
25451 uint8_t ArgMode;
25453 // Decide which area this value should be read from.
25454 // TODO: Implement the AMD64 ABI in its entirety. This simple
25455 // selection mechanism works only for the basic types.
25456 assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
25457 if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
25458 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
25459 } else {
25460 assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
25461 "Unhandled argument type in LowerVAARG");
25462 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
25465 if (ArgMode == 2) {
25466 // Make sure using fp_offset makes sense.
25467 assert(!Subtarget.useSoftFloat() &&
25468 !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
25469 Subtarget.hasSSE1());
25472 // Insert VAARG node into the DAG
25473 // VAARG returns two values: Variable Argument Address, Chain
25474 SDValue InstOps[] = {Chain, SrcPtr,
25475 DAG.getTargetConstant(ArgSize, dl, MVT::i32),
25476 DAG.getTargetConstant(ArgMode, dl, MVT::i8),
25477 DAG.getTargetConstant(Align, dl, MVT::i32)};
25478 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
25479 SDValue VAARG = DAG.getMemIntrinsicNode(
25480 Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
25481 VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
25482 /*Alignment=*/std::nullopt,
25483 MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
25484 Chain = VAARG.getValue(1);
25486 // Load the next argument and return it
25487 return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
25490 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
25491 SelectionDAG &DAG) {
25492 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
25493 // where a va_list is still an i8*.
25494 assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
25495 if (Subtarget.isCallingConvWin64(
25496 DAG.getMachineFunction().getFunction().getCallingConv()))
25497 // Probably a Win64 va_copy.
25498 return DAG.expandVACopy(Op.getNode());
25500 SDValue Chain = Op.getOperand(0);
25501 SDValue DstPtr = Op.getOperand(1);
25502 SDValue SrcPtr = Op.getOperand(2);
25503 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
25504 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
25505 SDLoc DL(Op);
25507 return DAG.getMemcpy(
25508 Chain, DL, DstPtr, SrcPtr,
25509 DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
25510 Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
25511 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
25512 MachinePointerInfo(SrcSV));
25515 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
25516 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
25517 switch (Opc) {
25518 case ISD::SHL:
25519 case X86ISD::VSHL:
25520 case X86ISD::VSHLI:
25521 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
25522 case ISD::SRL:
25523 case X86ISD::VSRL:
25524 case X86ISD::VSRLI:
25525 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
25526 case ISD::SRA:
25527 case X86ISD::VSRA:
25528 case X86ISD::VSRAI:
25529 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
25531 llvm_unreachable("Unknown target vector shift node");
25534 /// Handle vector element shifts where the shift amount is a constant.
25535 /// Takes immediate version of shift as input.
25536 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
25537 SDValue SrcOp, uint64_t ShiftAmt,
25538 SelectionDAG &DAG) {
25539 MVT ElementType = VT.getVectorElementType();
25541 // Bitcast the source vector to the output type, this is mainly necessary for
25542 // vXi8/vXi64 shifts.
25543 if (VT != SrcOp.getSimpleValueType())
25544 SrcOp = DAG.getBitcast(VT, SrcOp);
25546 // Fold this packed shift into its first operand if ShiftAmt is 0.
25547 if (ShiftAmt == 0)
25548 return SrcOp;
25550 // Check for ShiftAmt >= element width
25551 if (ShiftAmt >= ElementType.getSizeInBits()) {
25552 if (Opc == X86ISD::VSRAI)
25553 ShiftAmt = ElementType.getSizeInBits() - 1;
25554 else
25555 return DAG.getConstant(0, dl, VT);
25558 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
25559 && "Unknown target vector shift-by-constant node");
25561 // Fold this packed vector shift into a build vector if SrcOp is a
25562 // vector of Constants or UNDEFs.
25563 if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
25564 unsigned ShiftOpc;
25565 switch (Opc) {
25566 default: llvm_unreachable("Unknown opcode!");
25567 case X86ISD::VSHLI:
25568 ShiftOpc = ISD::SHL;
25569 break;
25570 case X86ISD::VSRLI:
25571 ShiftOpc = ISD::SRL;
25572 break;
25573 case X86ISD::VSRAI:
25574 ShiftOpc = ISD::SRA;
25575 break;
25578 SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
25579 if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
25580 return C;
25583 return DAG.getNode(Opc, dl, VT, SrcOp,
25584 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
25587 /// Handle vector element shifts by a splat shift amount
25588 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
25589 SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
25590 const X86Subtarget &Subtarget,
25591 SelectionDAG &DAG) {
25592 MVT AmtVT = ShAmt.getSimpleValueType();
25593 assert(AmtVT.isVector() && "Vector shift type mismatch");
25594 assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
25595 "Illegal vector splat index");
25597 // Move the splat element to the bottom element.
25598 if (ShAmtIdx != 0) {
25599 SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
25600 Mask[0] = ShAmtIdx;
25601 ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
25604 // Peek through any zext node if we can get back to a 128-bit source.
25605 if (AmtVT.getScalarSizeInBits() == 64 &&
25606 (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
25607 ShAmt.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
25608 ShAmt.getOperand(0).getValueType().isSimple() &&
25609 ShAmt.getOperand(0).getValueType().is128BitVector()) {
25610 ShAmt = ShAmt.getOperand(0);
25611 AmtVT = ShAmt.getSimpleValueType();
25614 // See if we can mask off the upper elements using the existing source node.
25615 // The shift uses the entire lower 64-bits of the amount vector, so no need to
25616 // do this for vXi64 types.
25617 bool IsMasked = false;
25618 if (AmtVT.getScalarSizeInBits() < 64) {
25619 if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
25620 ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
25621 // If the shift amount has come from a scalar, then zero-extend the scalar
25622 // before moving to the vector.
25623 ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
25624 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
25625 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
25626 AmtVT = MVT::v4i32;
25627 IsMasked = true;
25628 } else if (ShAmt.getOpcode() == ISD::AND) {
25629 // See if the shift amount is already masked (e.g. for rotation modulo),
25630 // then we can zero-extend it by setting all the other mask elements to
25631 // zero.
25632 SmallVector<SDValue> MaskElts(
25633 AmtVT.getVectorNumElements(),
25634 DAG.getConstant(0, dl, AmtVT.getScalarType()));
25635 MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
25636 SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
25637 if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
25638 {ShAmt.getOperand(1), Mask}))) {
25639 ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
25640 IsMasked = true;
25645 // Extract if the shift amount vector is larger than 128-bits.
25646 if (AmtVT.getSizeInBits() > 128) {
25647 ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
25648 AmtVT = ShAmt.getSimpleValueType();
25651 // Zero-extend bottom element to v2i64 vector type, either by extension or
25652 // shuffle masking.
25653 if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
25654 if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
25655 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
25656 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
25657 } else if (Subtarget.hasSSE41()) {
25658 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
25659 MVT::v2i64, ShAmt);
25660 } else {
25661 SDValue ByteShift = DAG.getTargetConstant(
25662 (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
25663 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
25664 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25665 ByteShift);
25666 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25667 ByteShift);
25671 // Change opcode to non-immediate version.
25672 Opc = getTargetVShiftUniformOpcode(Opc, true);
25674 // The return type has to be a 128-bit type with the same element
25675 // type as the input type.
25676 MVT EltVT = VT.getVectorElementType();
25677 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
25679 ShAmt = DAG.getBitcast(ShVT, ShAmt);
25680 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
25683 /// Return Mask with the necessary casting or extending
25684 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
25685 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
25686 const X86Subtarget &Subtarget, SelectionDAG &DAG,
25687 const SDLoc &dl) {
25689 if (isAllOnesConstant(Mask))
25690 return DAG.getConstant(1, dl, MaskVT);
25691 if (X86::isZeroNode(Mask))
25692 return DAG.getConstant(0, dl, MaskVT);
25694 assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
25696 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
25697 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
25698 assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
25699 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
25700 SDValue Lo, Hi;
25701 std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
25702 Lo = DAG.getBitcast(MVT::v32i1, Lo);
25703 Hi = DAG.getBitcast(MVT::v32i1, Hi);
25704 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
25705 } else {
25706 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
25707 Mask.getSimpleValueType().getSizeInBits());
25708 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
25709 // are extracted by EXTRACT_SUBVECTOR.
25710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
25711 DAG.getBitcast(BitcastVT, Mask),
25712 DAG.getIntPtrConstant(0, dl));
25716 /// Return (and \p Op, \p Mask) for compare instructions or
25717 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
25718 /// necessary casting or extending for \p Mask when lowering masking intrinsics
25719 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
25720 SDValue PreservedSrc,
25721 const X86Subtarget &Subtarget,
25722 SelectionDAG &DAG) {
25723 MVT VT = Op.getSimpleValueType();
25724 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
25725 unsigned OpcodeSelect = ISD::VSELECT;
25726 SDLoc dl(Op);
25728 if (isAllOnesConstant(Mask))
25729 return Op;
25731 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25733 if (PreservedSrc.isUndef())
25734 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25735 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
25738 /// Creates an SDNode for a predicated scalar operation.
25739 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
25740 /// The mask is coming as MVT::i8 and it should be transformed
25741 /// to MVT::v1i1 while lowering masking intrinsics.
25742 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
25743 /// "X86select" instead of "vselect". We just can't create the "vselect" node
25744 /// for a scalar instruction.
25745 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
25746 SDValue PreservedSrc,
25747 const X86Subtarget &Subtarget,
25748 SelectionDAG &DAG) {
25750 if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
25751 if (MaskConst->getZExtValue() & 0x1)
25752 return Op;
25754 MVT VT = Op.getSimpleValueType();
25755 SDLoc dl(Op);
25757 assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
25758 SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
25759 DAG.getBitcast(MVT::v8i1, Mask),
25760 DAG.getIntPtrConstant(0, dl));
25761 if (Op.getOpcode() == X86ISD::FSETCCM ||
25762 Op.getOpcode() == X86ISD::FSETCCM_SAE ||
25763 Op.getOpcode() == X86ISD::VFPCLASSS)
25764 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
25766 if (PreservedSrc.isUndef())
25767 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25768 return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
25771 static int getSEHRegistrationNodeSize(const Function *Fn) {
25772 if (!Fn->hasPersonalityFn())
25773 report_fatal_error(
25774 "querying registration node size for function without personality");
25775 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
25776 // WinEHStatePass for the full struct definition.
25777 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
25778 case EHPersonality::MSVC_X86SEH: return 24;
25779 case EHPersonality::MSVC_CXX: return 16;
25780 default: break;
25782 report_fatal_error(
25783 "can only recover FP for 32-bit MSVC EH personality functions");
25786 /// When the MSVC runtime transfers control to us, either to an outlined
25787 /// function or when returning to a parent frame after catching an exception, we
25788 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
25789 /// Here's the math:
25790 /// RegNodeBase = EntryEBP - RegNodeSize
25791 /// ParentFP = RegNodeBase - ParentFrameOffset
25792 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
25793 /// subtracting the offset (negative on x86) takes us back to the parent FP.
25794 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
25795 SDValue EntryEBP) {
25796 MachineFunction &MF = DAG.getMachineFunction();
25797 SDLoc dl;
25799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25800 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25802 // It's possible that the parent function no longer has a personality function
25803 // if the exceptional code was optimized away, in which case we just return
25804 // the incoming EBP.
25805 if (!Fn->hasPersonalityFn())
25806 return EntryEBP;
25808 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
25809 // registration, or the .set_setframe offset.
25810 MCSymbol *OffsetSym = MF.getContext().getOrCreateParentFrameOffsetSymbol(
25811 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25812 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
25813 SDValue ParentFrameOffset =
25814 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
25816 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
25817 // prologue to RBP in the parent function.
25818 const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
25819 if (Subtarget.is64Bit())
25820 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
25822 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
25823 // RegNodeBase = EntryEBP - RegNodeSize
25824 // ParentFP = RegNodeBase - ParentFrameOffset
25825 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
25826 DAG.getConstant(RegNodeSize, dl, PtrVT));
25827 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
25830 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
25831 SelectionDAG &DAG) const {
25832 // Helper to detect if the operand is CUR_DIRECTION rounding mode.
25833 auto isRoundModeCurDirection = [](SDValue Rnd) {
25834 if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
25835 return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
25837 return false;
25839 auto isRoundModeSAE = [](SDValue Rnd) {
25840 if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25841 unsigned RC = C->getZExtValue();
25842 if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25843 // Clear the NO_EXC bit and check remaining bits.
25844 RC ^= X86::STATIC_ROUNDING::NO_EXC;
25845 // As a convenience we allow no other bits or explicitly
25846 // current direction.
25847 return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
25851 return false;
25853 auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
25854 if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25855 RC = C->getZExtValue();
25856 if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25857 // Clear the NO_EXC bit and check remaining bits.
25858 RC ^= X86::STATIC_ROUNDING::NO_EXC;
25859 return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
25860 RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
25861 RC == X86::STATIC_ROUNDING::TO_POS_INF ||
25862 RC == X86::STATIC_ROUNDING::TO_ZERO;
25866 return false;
25869 SDLoc dl(Op);
25870 unsigned IntNo = Op.getConstantOperandVal(0);
25871 MVT VT = Op.getSimpleValueType();
25872 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
25874 // Propagate flags from original node to transformed node(s).
25875 SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
25877 if (IntrData) {
25878 switch(IntrData->Type) {
25879 case INTR_TYPE_1OP: {
25880 // We specify 2 possible opcodes for intrinsics with rounding modes.
25881 // First, we check if the intrinsic may have non-default rounding mode,
25882 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25883 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25884 if (IntrWithRoundingModeOpcode != 0) {
25885 SDValue Rnd = Op.getOperand(2);
25886 unsigned RC = 0;
25887 if (isRoundModeSAEToX(Rnd, RC))
25888 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25889 Op.getOperand(1),
25890 DAG.getTargetConstant(RC, dl, MVT::i32));
25891 if (!isRoundModeCurDirection(Rnd))
25892 return SDValue();
25894 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25895 Op.getOperand(1));
25897 case INTR_TYPE_1OP_SAE: {
25898 SDValue Sae = Op.getOperand(2);
25900 unsigned Opc;
25901 if (isRoundModeCurDirection(Sae))
25902 Opc = IntrData->Opc0;
25903 else if (isRoundModeSAE(Sae))
25904 Opc = IntrData->Opc1;
25905 else
25906 return SDValue();
25908 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
25910 case INTR_TYPE_2OP: {
25911 SDValue Src2 = Op.getOperand(2);
25913 // We specify 2 possible opcodes for intrinsics with rounding modes.
25914 // First, we check if the intrinsic may have non-default rounding mode,
25915 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25916 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25917 if (IntrWithRoundingModeOpcode != 0) {
25918 SDValue Rnd = Op.getOperand(3);
25919 unsigned RC = 0;
25920 if (isRoundModeSAEToX(Rnd, RC))
25921 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25922 Op.getOperand(1), Src2,
25923 DAG.getTargetConstant(RC, dl, MVT::i32));
25924 if (!isRoundModeCurDirection(Rnd))
25925 return SDValue();
25928 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25929 Op.getOperand(1), Src2);
25931 case INTR_TYPE_2OP_SAE: {
25932 SDValue Sae = Op.getOperand(3);
25934 unsigned Opc;
25935 if (isRoundModeCurDirection(Sae))
25936 Opc = IntrData->Opc0;
25937 else if (isRoundModeSAE(Sae))
25938 Opc = IntrData->Opc1;
25939 else
25940 return SDValue();
25942 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
25943 Op.getOperand(2));
25945 case INTR_TYPE_3OP:
25946 case INTR_TYPE_3OP_IMM8: {
25947 SDValue Src1 = Op.getOperand(1);
25948 SDValue Src2 = Op.getOperand(2);
25949 SDValue Src3 = Op.getOperand(3);
25951 if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
25952 Src3.getValueType() != MVT::i8) {
25953 Src3 = DAG.getTargetConstant(Src3->getAsZExtVal() & 0xff, dl, MVT::i8);
25956 // We specify 2 possible opcodes for intrinsics with rounding modes.
25957 // First, we check if the intrinsic may have non-default rounding mode,
25958 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25959 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25960 if (IntrWithRoundingModeOpcode != 0) {
25961 SDValue Rnd = Op.getOperand(4);
25962 unsigned RC = 0;
25963 if (isRoundModeSAEToX(Rnd, RC))
25964 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25965 Src1, Src2, Src3,
25966 DAG.getTargetConstant(RC, dl, MVT::i32));
25967 if (!isRoundModeCurDirection(Rnd))
25968 return SDValue();
25971 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25972 {Src1, Src2, Src3});
25974 case INTR_TYPE_4OP_IMM8: {
25975 assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
25976 SDValue Src4 = Op.getOperand(4);
25977 if (Src4.getValueType() != MVT::i8) {
25978 Src4 = DAG.getTargetConstant(Src4->getAsZExtVal() & 0xff, dl, MVT::i8);
25981 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25982 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
25983 Src4);
25985 case INTR_TYPE_1OP_MASK: {
25986 SDValue Src = Op.getOperand(1);
25987 SDValue PassThru = Op.getOperand(2);
25988 SDValue Mask = Op.getOperand(3);
25989 // We add rounding mode to the Node when
25990 // - RC Opcode is specified and
25991 // - RC is not "current direction".
25992 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25993 if (IntrWithRoundingModeOpcode != 0) {
25994 SDValue Rnd = Op.getOperand(4);
25995 unsigned RC = 0;
25996 if (isRoundModeSAEToX(Rnd, RC))
25997 return getVectorMaskingNode(
25998 DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25999 Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
26000 Mask, PassThru, Subtarget, DAG);
26001 if (!isRoundModeCurDirection(Rnd))
26002 return SDValue();
26004 return getVectorMaskingNode(
26005 DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
26006 Subtarget, DAG);
26008 case INTR_TYPE_1OP_MASK_SAE: {
26009 SDValue Src = Op.getOperand(1);
26010 SDValue PassThru = Op.getOperand(2);
26011 SDValue Mask = Op.getOperand(3);
26012 SDValue Rnd = Op.getOperand(4);
26014 unsigned Opc;
26015 if (isRoundModeCurDirection(Rnd))
26016 Opc = IntrData->Opc0;
26017 else if (isRoundModeSAE(Rnd))
26018 Opc = IntrData->Opc1;
26019 else
26020 return SDValue();
26022 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
26023 Subtarget, DAG);
26025 case INTR_TYPE_SCALAR_MASK: {
26026 SDValue Src1 = Op.getOperand(1);
26027 SDValue Src2 = Op.getOperand(2);
26028 SDValue passThru = Op.getOperand(3);
26029 SDValue Mask = Op.getOperand(4);
26030 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
26031 // There are 2 kinds of intrinsics in this group:
26032 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
26033 // (2) With rounding mode and sae - 7 operands.
26034 bool HasRounding = IntrWithRoundingModeOpcode != 0;
26035 if (Op.getNumOperands() == (5U + HasRounding)) {
26036 if (HasRounding) {
26037 SDValue Rnd = Op.getOperand(5);
26038 unsigned RC = 0;
26039 if (isRoundModeSAEToX(Rnd, RC))
26040 return getScalarMaskingNode(
26041 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
26042 DAG.getTargetConstant(RC, dl, MVT::i32)),
26043 Mask, passThru, Subtarget, DAG);
26044 if (!isRoundModeCurDirection(Rnd))
26045 return SDValue();
26047 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
26048 Src2),
26049 Mask, passThru, Subtarget, DAG);
26052 assert(Op.getNumOperands() == (6U + HasRounding) &&
26053 "Unexpected intrinsic form");
26054 SDValue RoundingMode = Op.getOperand(5);
26055 unsigned Opc = IntrData->Opc0;
26056 if (HasRounding) {
26057 SDValue Sae = Op.getOperand(6);
26058 if (isRoundModeSAE(Sae))
26059 Opc = IntrWithRoundingModeOpcode;
26060 else if (!isRoundModeCurDirection(Sae))
26061 return SDValue();
26063 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
26064 Src2, RoundingMode),
26065 Mask, passThru, Subtarget, DAG);
26067 case INTR_TYPE_SCALAR_MASK_RND: {
26068 SDValue Src1 = Op.getOperand(1);
26069 SDValue Src2 = Op.getOperand(2);
26070 SDValue passThru = Op.getOperand(3);
26071 SDValue Mask = Op.getOperand(4);
26072 SDValue Rnd = Op.getOperand(5);
26074 SDValue NewOp;
26075 unsigned RC = 0;
26076 if (isRoundModeCurDirection(Rnd))
26077 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26078 else if (isRoundModeSAEToX(Rnd, RC))
26079 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26080 DAG.getTargetConstant(RC, dl, MVT::i32));
26081 else
26082 return SDValue();
26084 return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
26086 case INTR_TYPE_SCALAR_MASK_SAE: {
26087 SDValue Src1 = Op.getOperand(1);
26088 SDValue Src2 = Op.getOperand(2);
26089 SDValue passThru = Op.getOperand(3);
26090 SDValue Mask = Op.getOperand(4);
26091 SDValue Sae = Op.getOperand(5);
26092 unsigned Opc;
26093 if (isRoundModeCurDirection(Sae))
26094 Opc = IntrData->Opc0;
26095 else if (isRoundModeSAE(Sae))
26096 Opc = IntrData->Opc1;
26097 else
26098 return SDValue();
26100 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26101 Mask, passThru, Subtarget, DAG);
26103 case INTR_TYPE_2OP_MASK: {
26104 SDValue Src1 = Op.getOperand(1);
26105 SDValue Src2 = Op.getOperand(2);
26106 SDValue PassThru = Op.getOperand(3);
26107 SDValue Mask = Op.getOperand(4);
26108 SDValue NewOp;
26109 if (IntrData->Opc1 != 0) {
26110 SDValue Rnd = Op.getOperand(5);
26111 unsigned RC = 0;
26112 if (isRoundModeSAEToX(Rnd, RC))
26113 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
26114 DAG.getTargetConstant(RC, dl, MVT::i32));
26115 else if (!isRoundModeCurDirection(Rnd))
26116 return SDValue();
26118 if (!NewOp)
26119 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
26120 return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26122 case INTR_TYPE_2OP_MASK_SAE: {
26123 SDValue Src1 = Op.getOperand(1);
26124 SDValue Src2 = Op.getOperand(2);
26125 SDValue PassThru = Op.getOperand(3);
26126 SDValue Mask = Op.getOperand(4);
26128 unsigned Opc = IntrData->Opc0;
26129 if (IntrData->Opc1 != 0) {
26130 SDValue Sae = Op.getOperand(5);
26131 if (isRoundModeSAE(Sae))
26132 Opc = IntrData->Opc1;
26133 else if (!isRoundModeCurDirection(Sae))
26134 return SDValue();
26137 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
26138 Mask, PassThru, Subtarget, DAG);
26140 case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
26141 SDValue Src1 = Op.getOperand(1);
26142 SDValue Src2 = Op.getOperand(2);
26143 SDValue Src3 = Op.getOperand(3);
26144 SDValue PassThru = Op.getOperand(4);
26145 SDValue Mask = Op.getOperand(5);
26146 SDValue Sae = Op.getOperand(6);
26147 unsigned Opc;
26148 if (isRoundModeCurDirection(Sae))
26149 Opc = IntrData->Opc0;
26150 else if (isRoundModeSAE(Sae))
26151 Opc = IntrData->Opc1;
26152 else
26153 return SDValue();
26155 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26156 Mask, PassThru, Subtarget, DAG);
26158 case INTR_TYPE_3OP_MASK_SAE: {
26159 SDValue Src1 = Op.getOperand(1);
26160 SDValue Src2 = Op.getOperand(2);
26161 SDValue Src3 = Op.getOperand(3);
26162 SDValue PassThru = Op.getOperand(4);
26163 SDValue Mask = Op.getOperand(5);
26165 unsigned Opc = IntrData->Opc0;
26166 if (IntrData->Opc1 != 0) {
26167 SDValue Sae = Op.getOperand(6);
26168 if (isRoundModeSAE(Sae))
26169 Opc = IntrData->Opc1;
26170 else if (!isRoundModeCurDirection(Sae))
26171 return SDValue();
26173 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
26174 Mask, PassThru, Subtarget, DAG);
26176 case BLENDV: {
26177 SDValue Src1 = Op.getOperand(1);
26178 SDValue Src2 = Op.getOperand(2);
26179 SDValue Src3 = Op.getOperand(3);
26181 EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
26182 Src3 = DAG.getBitcast(MaskVT, Src3);
26184 // Reverse the operands to match VSELECT order.
26185 return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
26187 case VPERM_2OP : {
26188 SDValue Src1 = Op.getOperand(1);
26189 SDValue Src2 = Op.getOperand(2);
26191 // Swap Src1 and Src2 in the node creation
26192 return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
26194 case CFMA_OP_MASKZ:
26195 case CFMA_OP_MASK: {
26196 SDValue Src1 = Op.getOperand(1);
26197 SDValue Src2 = Op.getOperand(2);
26198 SDValue Src3 = Op.getOperand(3);
26199 SDValue Mask = Op.getOperand(4);
26200 MVT VT = Op.getSimpleValueType();
26202 SDValue PassThru = Src3;
26203 if (IntrData->Type == CFMA_OP_MASKZ)
26204 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
26206 // We add rounding mode to the Node when
26207 // - RC Opcode is specified and
26208 // - RC is not "current direction".
26209 SDValue NewOp;
26210 if (IntrData->Opc1 != 0) {
26211 SDValue Rnd = Op.getOperand(5);
26212 unsigned RC = 0;
26213 if (isRoundModeSAEToX(Rnd, RC))
26214 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2, Src3,
26215 DAG.getTargetConstant(RC, dl, MVT::i32));
26216 else if (!isRoundModeCurDirection(Rnd))
26217 return SDValue();
26219 if (!NewOp)
26220 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2, Src3);
26221 return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
26223 case IFMA_OP:
26224 // NOTE: We need to swizzle the operands to pass the multiply operands
26225 // first.
26226 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26227 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
26228 case FPCLASSS: {
26229 SDValue Src1 = Op.getOperand(1);
26230 SDValue Imm = Op.getOperand(2);
26231 SDValue Mask = Op.getOperand(3);
26232 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
26233 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
26234 Subtarget, DAG);
26235 // Need to fill with zeros to ensure the bitcast will produce zeroes
26236 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26237 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26238 DAG.getConstant(0, dl, MVT::v8i1),
26239 FPclassMask, DAG.getIntPtrConstant(0, dl));
26240 return DAG.getBitcast(MVT::i8, Ins);
26243 case CMP_MASK_CC: {
26244 MVT MaskVT = Op.getSimpleValueType();
26245 SDValue CC = Op.getOperand(3);
26246 SDValue Mask = Op.getOperand(4);
26247 // We specify 2 possible opcodes for intrinsics with rounding modes.
26248 // First, we check if the intrinsic may have non-default rounding mode,
26249 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
26250 if (IntrData->Opc1 != 0) {
26251 SDValue Sae = Op.getOperand(5);
26252 if (isRoundModeSAE(Sae))
26253 return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
26254 Op.getOperand(2), CC, Mask, Sae);
26255 if (!isRoundModeCurDirection(Sae))
26256 return SDValue();
26258 //default rounding mode
26259 return DAG.getNode(IntrData->Opc0, dl, MaskVT,
26260 {Op.getOperand(1), Op.getOperand(2), CC, Mask});
26262 case CMP_MASK_SCALAR_CC: {
26263 SDValue Src1 = Op.getOperand(1);
26264 SDValue Src2 = Op.getOperand(2);
26265 SDValue CC = Op.getOperand(3);
26266 SDValue Mask = Op.getOperand(4);
26268 SDValue Cmp;
26269 if (IntrData->Opc1 != 0) {
26270 SDValue Sae = Op.getOperand(5);
26271 if (isRoundModeSAE(Sae))
26272 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
26273 else if (!isRoundModeCurDirection(Sae))
26274 return SDValue();
26276 //default rounding mode
26277 if (!Cmp.getNode())
26278 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
26280 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
26281 Subtarget, DAG);
26282 // Need to fill with zeros to ensure the bitcast will produce zeroes
26283 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26284 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
26285 DAG.getConstant(0, dl, MVT::v8i1),
26286 CmpMask, DAG.getIntPtrConstant(0, dl));
26287 return DAG.getBitcast(MVT::i8, Ins);
26289 case COMI: { // Comparison intrinsics
26290 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
26291 SDValue LHS = Op.getOperand(1);
26292 SDValue RHS = Op.getOperand(2);
26293 // Some conditions require the operands to be swapped.
26294 if (CC == ISD::SETLT || CC == ISD::SETLE)
26295 std::swap(LHS, RHS);
26297 // For AVX10.2, Support EQ and NE.
26298 bool HasAVX10_2_COMX =
26299 Subtarget.hasAVX10_2() && (CC == ISD::SETEQ || CC == ISD::SETNE);
26301 // AVX10.2 COMPARE supports only v2f64, v4f32 or v8f16.
26302 // For BF type we need to fall back.
26303 bool HasAVX10_2_COMX_Ty = (LHS.getSimpleValueType() != MVT::v8bf16);
26305 auto ComiOpCode = IntrData->Opc0;
26306 auto isUnordered = (ComiOpCode == X86ISD::UCOMI);
26308 if (HasAVX10_2_COMX && HasAVX10_2_COMX_Ty)
26309 ComiOpCode = isUnordered ? X86ISD::UCOMX : X86ISD::COMX;
26311 SDValue Comi = DAG.getNode(ComiOpCode, dl, MVT::i32, LHS, RHS);
26313 SDValue SetCC;
26314 switch (CC) {
26315 case ISD::SETEQ: {
26316 SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
26317 if (HasAVX10_2_COMX & HasAVX10_2_COMX_Ty) // ZF == 1
26318 break;
26319 // (ZF = 1 and PF = 0)
26320 SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
26321 SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
26322 break;
26324 case ISD::SETNE: {
26325 SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
26326 if (HasAVX10_2_COMX & HasAVX10_2_COMX_Ty) // ZF == 0
26327 break;
26328 // (ZF = 0 or PF = 1)
26329 SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
26330 SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
26331 break;
26333 case ISD::SETGT: // (CF = 0 and ZF = 0)
26334 case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
26335 SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
26336 break;
26338 case ISD::SETGE: // CF = 0
26339 case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
26340 SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
26341 break;
26342 default:
26343 llvm_unreachable("Unexpected illegal condition!");
26345 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26347 case COMI_RM: { // Comparison intrinsics with Sae
26348 SDValue LHS = Op.getOperand(1);
26349 SDValue RHS = Op.getOperand(2);
26350 unsigned CondVal = Op.getConstantOperandVal(3);
26351 SDValue Sae = Op.getOperand(4);
26353 SDValue FCmp;
26354 if (isRoundModeCurDirection(Sae))
26355 FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
26356 DAG.getTargetConstant(CondVal, dl, MVT::i8));
26357 else if (isRoundModeSAE(Sae))
26358 FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
26359 DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
26360 else
26361 return SDValue();
26362 // Need to fill with zeros to ensure the bitcast will produce zeroes
26363 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
26364 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
26365 DAG.getConstant(0, dl, MVT::v16i1),
26366 FCmp, DAG.getIntPtrConstant(0, dl));
26367 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
26368 DAG.getBitcast(MVT::i16, Ins));
26370 case VSHIFT: {
26371 SDValue SrcOp = Op.getOperand(1);
26372 SDValue ShAmt = Op.getOperand(2);
26373 assert(ShAmt.getValueType() == MVT::i32 &&
26374 "Unexpected VSHIFT amount type");
26376 // Catch shift-by-constant.
26377 if (auto *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
26378 return getTargetVShiftByConstNode(IntrData->Opc0, dl,
26379 Op.getSimpleValueType(), SrcOp,
26380 CShAmt->getZExtValue(), DAG);
26382 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
26383 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
26384 SrcOp, ShAmt, 0, Subtarget, DAG);
26386 case COMPRESS_EXPAND_IN_REG: {
26387 SDValue Mask = Op.getOperand(3);
26388 SDValue DataToCompress = Op.getOperand(1);
26389 SDValue PassThru = Op.getOperand(2);
26390 if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
26391 return Op.getOperand(1);
26393 // Avoid false dependency.
26394 if (PassThru.isUndef())
26395 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
26397 return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
26398 Mask);
26400 case FIXUPIMM:
26401 case FIXUPIMM_MASKZ: {
26402 SDValue Src1 = Op.getOperand(1);
26403 SDValue Src2 = Op.getOperand(2);
26404 SDValue Src3 = Op.getOperand(3);
26405 SDValue Imm = Op.getOperand(4);
26406 SDValue Mask = Op.getOperand(5);
26407 SDValue Passthru = (IntrData->Type == FIXUPIMM)
26408 ? Src1
26409 : getZeroVector(VT, Subtarget, DAG, dl);
26411 unsigned Opc = IntrData->Opc0;
26412 if (IntrData->Opc1 != 0) {
26413 SDValue Sae = Op.getOperand(6);
26414 if (isRoundModeSAE(Sae))
26415 Opc = IntrData->Opc1;
26416 else if (!isRoundModeCurDirection(Sae))
26417 return SDValue();
26420 SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
26422 if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
26423 return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
26425 return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
26427 case ROUNDP: {
26428 assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
26429 // Clear the upper bits of the rounding immediate so that the legacy
26430 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
26431 uint64_t Round = Op.getConstantOperandVal(2);
26432 SDValue RoundingMode = DAG.getTargetConstant(Round & 0xf, dl, MVT::i32);
26433 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26434 Op.getOperand(1), RoundingMode);
26436 case ROUNDS: {
26437 assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
26438 // Clear the upper bits of the rounding immediate so that the legacy
26439 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
26440 uint64_t Round = Op.getConstantOperandVal(3);
26441 SDValue RoundingMode = DAG.getTargetConstant(Round & 0xf, dl, MVT::i32);
26442 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26443 Op.getOperand(1), Op.getOperand(2), RoundingMode);
26445 case BEXTRI: {
26446 assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
26448 uint64_t Imm = Op.getConstantOperandVal(2);
26449 SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
26450 Op.getValueType());
26451 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
26452 Op.getOperand(1), Control);
26454 // ADC/SBB
26455 case ADX: {
26456 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
26457 SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
26459 SDValue Res;
26460 // If the carry in is zero, then we should just use ADD/SUB instead of
26461 // ADC/SBB.
26462 if (isNullConstant(Op.getOperand(1))) {
26463 Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
26464 Op.getOperand(3));
26465 } else {
26466 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
26467 DAG.getAllOnesConstant(dl, MVT::i8));
26468 Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
26469 Op.getOperand(3), GenCF.getValue(1));
26471 SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
26472 SDValue Results[] = { SetCC, Res };
26473 return DAG.getMergeValues(Results, dl);
26475 case CVTPD2PS_MASK:
26476 case CVTPD2DQ_MASK:
26477 case CVTQQ2PS_MASK:
26478 case TRUNCATE_TO_REG: {
26479 SDValue Src = Op.getOperand(1);
26480 SDValue PassThru = Op.getOperand(2);
26481 SDValue Mask = Op.getOperand(3);
26483 if (isAllOnesConstant(Mask))
26484 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
26486 MVT SrcVT = Src.getSimpleValueType();
26487 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
26488 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26489 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
26490 {Src, PassThru, Mask});
26492 case TRUNCATE2_TO_REG: {
26493 SDValue Src = Op.getOperand(1);
26494 SDValue Src2 = Op.getOperand(2);
26495 SDValue PassThru = Op.getOperand(3);
26496 SDValue Mask = Op.getOperand(4);
26498 if (isAllOnesConstant(Mask))
26499 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), {Src, Src2});
26501 MVT Src2VT = Src2.getSimpleValueType();
26502 MVT MaskVT = MVT::getVectorVT(MVT::i1, Src2VT.getVectorNumElements());
26503 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26504 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
26505 {Src, Src2, PassThru, Mask});
26507 case CVTPS2PH_MASK: {
26508 SDValue Src = Op.getOperand(1);
26509 SDValue Rnd = Op.getOperand(2);
26510 SDValue PassThru = Op.getOperand(3);
26511 SDValue Mask = Op.getOperand(4);
26513 unsigned RC = 0;
26514 unsigned Opc = IntrData->Opc0;
26515 bool SAE = Src.getValueType().is512BitVector() &&
26516 (isRoundModeSAEToX(Rnd, RC) || isRoundModeSAE(Rnd));
26517 if (SAE) {
26518 Opc = X86ISD::CVTPS2PH_SAE;
26519 Rnd = DAG.getTargetConstant(RC, dl, MVT::i32);
26522 if (isAllOnesConstant(Mask))
26523 return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd);
26525 if (SAE)
26526 Opc = X86ISD::MCVTPS2PH_SAE;
26527 else
26528 Opc = IntrData->Opc1;
26529 MVT SrcVT = Src.getSimpleValueType();
26530 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
26531 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26532 return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd, PassThru, Mask);
26534 case CVTNEPS2BF16_MASK: {
26535 SDValue Src = Op.getOperand(1);
26536 SDValue PassThru = Op.getOperand(2);
26537 SDValue Mask = Op.getOperand(3);
26539 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
26540 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
26542 // Break false dependency.
26543 if (PassThru.isUndef())
26544 PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
26546 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
26547 Mask);
26549 default:
26550 break;
26554 switch (IntNo) {
26555 default: return SDValue(); // Don't custom lower most intrinsics.
26557 // ptest and testp intrinsics. The intrinsic these come from are designed to
26558 // return an integer value, not just an instruction so lower it to the ptest
26559 // or testp pattern and a setcc for the result.
26560 case Intrinsic::x86_avx512_ktestc_b:
26561 case Intrinsic::x86_avx512_ktestc_w:
26562 case Intrinsic::x86_avx512_ktestc_d:
26563 case Intrinsic::x86_avx512_ktestc_q:
26564 case Intrinsic::x86_avx512_ktestz_b:
26565 case Intrinsic::x86_avx512_ktestz_w:
26566 case Intrinsic::x86_avx512_ktestz_d:
26567 case Intrinsic::x86_avx512_ktestz_q:
26568 case Intrinsic::x86_sse41_ptestz:
26569 case Intrinsic::x86_sse41_ptestc:
26570 case Intrinsic::x86_sse41_ptestnzc:
26571 case Intrinsic::x86_avx_ptestz_256:
26572 case Intrinsic::x86_avx_ptestc_256:
26573 case Intrinsic::x86_avx_ptestnzc_256:
26574 case Intrinsic::x86_avx_vtestz_ps:
26575 case Intrinsic::x86_avx_vtestc_ps:
26576 case Intrinsic::x86_avx_vtestnzc_ps:
26577 case Intrinsic::x86_avx_vtestz_pd:
26578 case Intrinsic::x86_avx_vtestc_pd:
26579 case Intrinsic::x86_avx_vtestnzc_pd:
26580 case Intrinsic::x86_avx_vtestz_ps_256:
26581 case Intrinsic::x86_avx_vtestc_ps_256:
26582 case Intrinsic::x86_avx_vtestnzc_ps_256:
26583 case Intrinsic::x86_avx_vtestz_pd_256:
26584 case Intrinsic::x86_avx_vtestc_pd_256:
26585 case Intrinsic::x86_avx_vtestnzc_pd_256: {
26586 unsigned TestOpc = X86ISD::PTEST;
26587 X86::CondCode X86CC;
26588 switch (IntNo) {
26589 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
26590 case Intrinsic::x86_avx512_ktestc_b:
26591 case Intrinsic::x86_avx512_ktestc_w:
26592 case Intrinsic::x86_avx512_ktestc_d:
26593 case Intrinsic::x86_avx512_ktestc_q:
26594 // CF = 1
26595 TestOpc = X86ISD::KTEST;
26596 X86CC = X86::COND_B;
26597 break;
26598 case Intrinsic::x86_avx512_ktestz_b:
26599 case Intrinsic::x86_avx512_ktestz_w:
26600 case Intrinsic::x86_avx512_ktestz_d:
26601 case Intrinsic::x86_avx512_ktestz_q:
26602 TestOpc = X86ISD::KTEST;
26603 X86CC = X86::COND_E;
26604 break;
26605 case Intrinsic::x86_avx_vtestz_ps:
26606 case Intrinsic::x86_avx_vtestz_pd:
26607 case Intrinsic::x86_avx_vtestz_ps_256:
26608 case Intrinsic::x86_avx_vtestz_pd_256:
26609 TestOpc = X86ISD::TESTP;
26610 [[fallthrough]];
26611 case Intrinsic::x86_sse41_ptestz:
26612 case Intrinsic::x86_avx_ptestz_256:
26613 // ZF = 1
26614 X86CC = X86::COND_E;
26615 break;
26616 case Intrinsic::x86_avx_vtestc_ps:
26617 case Intrinsic::x86_avx_vtestc_pd:
26618 case Intrinsic::x86_avx_vtestc_ps_256:
26619 case Intrinsic::x86_avx_vtestc_pd_256:
26620 TestOpc = X86ISD::TESTP;
26621 [[fallthrough]];
26622 case Intrinsic::x86_sse41_ptestc:
26623 case Intrinsic::x86_avx_ptestc_256:
26624 // CF = 1
26625 X86CC = X86::COND_B;
26626 break;
26627 case Intrinsic::x86_avx_vtestnzc_ps:
26628 case Intrinsic::x86_avx_vtestnzc_pd:
26629 case Intrinsic::x86_avx_vtestnzc_ps_256:
26630 case Intrinsic::x86_avx_vtestnzc_pd_256:
26631 TestOpc = X86ISD::TESTP;
26632 [[fallthrough]];
26633 case Intrinsic::x86_sse41_ptestnzc:
26634 case Intrinsic::x86_avx_ptestnzc_256:
26635 // ZF and CF = 0
26636 X86CC = X86::COND_A;
26637 break;
26640 SDValue LHS = Op.getOperand(1);
26641 SDValue RHS = Op.getOperand(2);
26642 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
26643 SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
26644 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26647 case Intrinsic::x86_sse42_pcmpistria128:
26648 case Intrinsic::x86_sse42_pcmpestria128:
26649 case Intrinsic::x86_sse42_pcmpistric128:
26650 case Intrinsic::x86_sse42_pcmpestric128:
26651 case Intrinsic::x86_sse42_pcmpistrio128:
26652 case Intrinsic::x86_sse42_pcmpestrio128:
26653 case Intrinsic::x86_sse42_pcmpistris128:
26654 case Intrinsic::x86_sse42_pcmpestris128:
26655 case Intrinsic::x86_sse42_pcmpistriz128:
26656 case Intrinsic::x86_sse42_pcmpestriz128: {
26657 unsigned Opcode;
26658 X86::CondCode X86CC;
26659 switch (IntNo) {
26660 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
26661 case Intrinsic::x86_sse42_pcmpistria128:
26662 Opcode = X86ISD::PCMPISTR;
26663 X86CC = X86::COND_A;
26664 break;
26665 case Intrinsic::x86_sse42_pcmpestria128:
26666 Opcode = X86ISD::PCMPESTR;
26667 X86CC = X86::COND_A;
26668 break;
26669 case Intrinsic::x86_sse42_pcmpistric128:
26670 Opcode = X86ISD::PCMPISTR;
26671 X86CC = X86::COND_B;
26672 break;
26673 case Intrinsic::x86_sse42_pcmpestric128:
26674 Opcode = X86ISD::PCMPESTR;
26675 X86CC = X86::COND_B;
26676 break;
26677 case Intrinsic::x86_sse42_pcmpistrio128:
26678 Opcode = X86ISD::PCMPISTR;
26679 X86CC = X86::COND_O;
26680 break;
26681 case Intrinsic::x86_sse42_pcmpestrio128:
26682 Opcode = X86ISD::PCMPESTR;
26683 X86CC = X86::COND_O;
26684 break;
26685 case Intrinsic::x86_sse42_pcmpistris128:
26686 Opcode = X86ISD::PCMPISTR;
26687 X86CC = X86::COND_S;
26688 break;
26689 case Intrinsic::x86_sse42_pcmpestris128:
26690 Opcode = X86ISD::PCMPESTR;
26691 X86CC = X86::COND_S;
26692 break;
26693 case Intrinsic::x86_sse42_pcmpistriz128:
26694 Opcode = X86ISD::PCMPISTR;
26695 X86CC = X86::COND_E;
26696 break;
26697 case Intrinsic::x86_sse42_pcmpestriz128:
26698 Opcode = X86ISD::PCMPESTR;
26699 X86CC = X86::COND_E;
26700 break;
26702 SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26703 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26704 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
26705 SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
26706 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26709 case Intrinsic::x86_sse42_pcmpistri128:
26710 case Intrinsic::x86_sse42_pcmpestri128: {
26711 unsigned Opcode;
26712 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
26713 Opcode = X86ISD::PCMPISTR;
26714 else
26715 Opcode = X86ISD::PCMPESTR;
26717 SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26718 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26719 return DAG.getNode(Opcode, dl, VTs, NewOps);
26722 case Intrinsic::x86_sse42_pcmpistrm128:
26723 case Intrinsic::x86_sse42_pcmpestrm128: {
26724 unsigned Opcode;
26725 if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
26726 Opcode = X86ISD::PCMPISTR;
26727 else
26728 Opcode = X86ISD::PCMPESTR;
26730 SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26731 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26732 return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
26735 case Intrinsic::eh_sjlj_lsda: {
26736 MachineFunction &MF = DAG.getMachineFunction();
26737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26738 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26739 auto &Context = MF.getContext();
26740 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
26741 Twine(MF.getFunctionNumber()));
26742 return DAG.getNode(getGlobalWrapperKind(nullptr, /*OpFlags=*/0), dl, VT,
26743 DAG.getMCSymbol(S, PtrVT));
26746 case Intrinsic::x86_seh_lsda: {
26747 // Compute the symbol for the LSDA. We know it'll get emitted later.
26748 MachineFunction &MF = DAG.getMachineFunction();
26749 SDValue Op1 = Op.getOperand(1);
26750 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
26751 MCSymbol *LSDASym = MF.getContext().getOrCreateLSDASymbol(
26752 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
26754 // Generate a simple absolute symbol reference. This intrinsic is only
26755 // supported on 32-bit Windows, which isn't PIC.
26756 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
26757 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
26760 case Intrinsic::eh_recoverfp: {
26761 SDValue FnOp = Op.getOperand(1);
26762 SDValue IncomingFPOp = Op.getOperand(2);
26763 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
26764 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
26765 if (!Fn)
26766 report_fatal_error(
26767 "llvm.eh.recoverfp must take a function as the first argument");
26768 return recoverFramePointer(DAG, Fn, IncomingFPOp);
26771 case Intrinsic::localaddress: {
26772 // Returns one of the stack, base, or frame pointer registers, depending on
26773 // which is used to reference local variables.
26774 MachineFunction &MF = DAG.getMachineFunction();
26775 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26776 unsigned Reg;
26777 if (RegInfo->hasBasePointer(MF))
26778 Reg = RegInfo->getBaseRegister();
26779 else { // Handles the SP or FP case.
26780 bool CantUseFP = RegInfo->hasStackRealignment(MF);
26781 if (CantUseFP)
26782 Reg = RegInfo->getPtrSizedStackRegister(MF);
26783 else
26784 Reg = RegInfo->getPtrSizedFrameRegister(MF);
26786 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
26788 case Intrinsic::x86_avx512_vp2intersect_q_512:
26789 case Intrinsic::x86_avx512_vp2intersect_q_256:
26790 case Intrinsic::x86_avx512_vp2intersect_q_128:
26791 case Intrinsic::x86_avx512_vp2intersect_d_512:
26792 case Intrinsic::x86_avx512_vp2intersect_d_256:
26793 case Intrinsic::x86_avx512_vp2intersect_d_128: {
26794 MVT MaskVT = Op.getSimpleValueType();
26796 SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
26797 SDLoc DL(Op);
26799 SDValue Operation =
26800 DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
26801 Op->getOperand(1), Op->getOperand(2));
26803 SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
26804 MaskVT, Operation);
26805 SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
26806 MaskVT, Operation);
26807 return DAG.getMergeValues({Result0, Result1}, DL);
26809 case Intrinsic::x86_mmx_pslli_w:
26810 case Intrinsic::x86_mmx_pslli_d:
26811 case Intrinsic::x86_mmx_pslli_q:
26812 case Intrinsic::x86_mmx_psrli_w:
26813 case Intrinsic::x86_mmx_psrli_d:
26814 case Intrinsic::x86_mmx_psrli_q:
26815 case Intrinsic::x86_mmx_psrai_w:
26816 case Intrinsic::x86_mmx_psrai_d: {
26817 SDLoc DL(Op);
26818 SDValue ShAmt = Op.getOperand(2);
26819 // If the argument is a constant, convert it to a target constant.
26820 if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
26821 // Clamp out of bounds shift amounts since they will otherwise be masked
26822 // to 8-bits which may make it no longer out of bounds.
26823 unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
26824 if (ShiftAmount == 0)
26825 return Op.getOperand(1);
26827 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26828 Op.getOperand(0), Op.getOperand(1),
26829 DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
26832 unsigned NewIntrinsic;
26833 switch (IntNo) {
26834 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
26835 case Intrinsic::x86_mmx_pslli_w:
26836 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
26837 break;
26838 case Intrinsic::x86_mmx_pslli_d:
26839 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
26840 break;
26841 case Intrinsic::x86_mmx_pslli_q:
26842 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
26843 break;
26844 case Intrinsic::x86_mmx_psrli_w:
26845 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
26846 break;
26847 case Intrinsic::x86_mmx_psrli_d:
26848 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
26849 break;
26850 case Intrinsic::x86_mmx_psrli_q:
26851 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
26852 break;
26853 case Intrinsic::x86_mmx_psrai_w:
26854 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
26855 break;
26856 case Intrinsic::x86_mmx_psrai_d:
26857 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
26858 break;
26861 // The vector shift intrinsics with scalars uses 32b shift amounts but
26862 // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
26863 // MMX register.
26864 ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
26865 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26866 DAG.getTargetConstant(NewIntrinsic, DL,
26867 getPointerTy(DAG.getDataLayout())),
26868 Op.getOperand(1), ShAmt);
26870 case Intrinsic::thread_pointer: {
26871 if (Subtarget.isTargetELF()) {
26872 SDLoc dl(Op);
26873 EVT PtrVT = getPointerTy(DAG.getDataLayout());
26874 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
26875 Value *Ptr = Constant::getNullValue(PointerType::get(
26876 *DAG.getContext(), Subtarget.is64Bit() ? X86AS::FS : X86AS::GS));
26877 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
26878 DAG.getIntPtrConstant(0, dl), MachinePointerInfo(Ptr));
26880 report_fatal_error(
26881 "Target OS doesn't support __builtin_thread_pointer() yet.");
26886 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26887 SDValue Src, SDValue Mask, SDValue Base,
26888 SDValue Index, SDValue ScaleOp, SDValue Chain,
26889 const X86Subtarget &Subtarget) {
26890 SDLoc dl(Op);
26891 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26892 // Scale must be constant.
26893 if (!C)
26894 return SDValue();
26895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26896 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26897 TLI.getPointerTy(DAG.getDataLayout()));
26898 EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
26899 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26900 // If source is undef or we know it won't be used, use a zero vector
26901 // to break register dependency.
26902 // TODO: use undef instead and let BreakFalseDeps deal with it?
26903 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26904 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26906 // Cast mask to an integer type.
26907 Mask = DAG.getBitcast(MaskVT, Mask);
26909 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26911 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26912 SDValue Res =
26913 DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26914 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26915 return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26918 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
26919 SDValue Src, SDValue Mask, SDValue Base,
26920 SDValue Index, SDValue ScaleOp, SDValue Chain,
26921 const X86Subtarget &Subtarget) {
26922 MVT VT = Op.getSimpleValueType();
26923 SDLoc dl(Op);
26924 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26925 // Scale must be constant.
26926 if (!C)
26927 return SDValue();
26928 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26929 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26930 TLI.getPointerTy(DAG.getDataLayout()));
26931 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26932 VT.getVectorNumElements());
26933 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26935 // We support two versions of the gather intrinsics. One with scalar mask and
26936 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26937 if (Mask.getValueType() != MaskVT)
26938 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26941 // If source is undef or we know it won't be used, use a zero vector
26942 // to break register dependency.
26943 // TODO: use undef instead and let BreakFalseDeps deal with it?
26944 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26945 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26947 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26949 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26950 SDValue Res =
26951 DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26952 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26953 return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26956 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26957 SDValue Src, SDValue Mask, SDValue Base,
26958 SDValue Index, SDValue ScaleOp, SDValue Chain,
26959 const X86Subtarget &Subtarget) {
26960 SDLoc dl(Op);
26961 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26962 // Scale must be constant.
26963 if (!C)
26964 return SDValue();
26965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26966 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26967 TLI.getPointerTy(DAG.getDataLayout()));
26968 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26969 Src.getSimpleValueType().getVectorNumElements());
26970 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26972 // We support two versions of the scatter intrinsics. One with scalar mask and
26973 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26974 if (Mask.getValueType() != MaskVT)
26975 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26977 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26979 SDVTList VTs = DAG.getVTList(MVT::Other);
26980 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
26981 SDValue Res =
26982 DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
26983 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26984 return Res;
26987 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26988 SDValue Mask, SDValue Base, SDValue Index,
26989 SDValue ScaleOp, SDValue Chain,
26990 const X86Subtarget &Subtarget) {
26991 SDLoc dl(Op);
26992 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26993 // Scale must be constant.
26994 if (!C)
26995 return SDValue();
26996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26997 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26998 TLI.getPointerTy(DAG.getDataLayout()));
26999 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
27000 SDValue Segment = DAG.getRegister(0, MVT::i32);
27001 MVT MaskVT =
27002 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
27003 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27004 SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
27005 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
27006 return SDValue(Res, 0);
27009 /// Handles the lowering of builtin intrinsics with chain that return their
27010 /// value into registers EDX:EAX.
27011 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
27012 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
27013 /// TargetOpcode.
27014 /// Returns a Glue value which can be used to add extra copy-from-reg if the
27015 /// expanded intrinsics implicitly defines extra registers (i.e. not just
27016 /// EDX:EAX).
27017 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
27018 SelectionDAG &DAG,
27019 unsigned TargetOpcode,
27020 unsigned SrcReg,
27021 const X86Subtarget &Subtarget,
27022 SmallVectorImpl<SDValue> &Results) {
27023 SDValue Chain = N->getOperand(0);
27024 SDValue Glue;
27026 if (SrcReg) {
27027 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
27028 Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
27029 Glue = Chain.getValue(1);
27032 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
27033 SDValue N1Ops[] = {Chain, Glue};
27034 SDNode *N1 = DAG.getMachineNode(
27035 TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
27036 Chain = SDValue(N1, 0);
27038 // Reads the content of XCR and returns it in registers EDX:EAX.
27039 SDValue LO, HI;
27040 if (Subtarget.is64Bit()) {
27041 LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
27042 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
27043 LO.getValue(2));
27044 } else {
27045 LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
27046 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
27047 LO.getValue(2));
27049 Chain = HI.getValue(1);
27050 Glue = HI.getValue(2);
27052 if (Subtarget.is64Bit()) {
27053 // Merge the two 32-bit values into a 64-bit one.
27054 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
27055 DAG.getConstant(32, DL, MVT::i8));
27056 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
27057 Results.push_back(Chain);
27058 return Glue;
27061 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
27062 SDValue Ops[] = { LO, HI };
27063 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
27064 Results.push_back(Pair);
27065 Results.push_back(Chain);
27066 return Glue;
27069 /// Handles the lowering of builtin intrinsics that read the time stamp counter
27070 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
27071 /// READCYCLECOUNTER nodes.
27072 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
27073 SelectionDAG &DAG,
27074 const X86Subtarget &Subtarget,
27075 SmallVectorImpl<SDValue> &Results) {
27076 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
27077 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
27078 // and the EAX register is loaded with the low-order 32 bits.
27079 SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
27080 /* NoRegister */0, Subtarget,
27081 Results);
27082 if (Opcode != X86::RDTSCP)
27083 return;
27085 SDValue Chain = Results[1];
27086 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
27087 // the ECX register. Add 'ecx' explicitly to the chain.
27088 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
27089 Results[1] = ecx;
27090 Results.push_back(ecx.getValue(1));
27093 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
27094 SelectionDAG &DAG) {
27095 SmallVector<SDValue, 3> Results;
27096 SDLoc DL(Op);
27097 getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
27098 Results);
27099 return DAG.getMergeValues(Results, DL);
27102 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
27103 MachineFunction &MF = DAG.getMachineFunction();
27104 SDValue Chain = Op.getOperand(0);
27105 SDValue RegNode = Op.getOperand(2);
27106 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27107 if (!EHInfo)
27108 report_fatal_error("EH registrations only live in functions using WinEH");
27110 // Cast the operand to an alloca, and remember the frame index.
27111 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
27112 if (!FINode)
27113 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
27114 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
27116 // Return the chain operand without making any DAG nodes.
27117 return Chain;
27120 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
27121 MachineFunction &MF = DAG.getMachineFunction();
27122 SDValue Chain = Op.getOperand(0);
27123 SDValue EHGuard = Op.getOperand(2);
27124 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
27125 if (!EHInfo)
27126 report_fatal_error("EHGuard only live in functions using WinEH");
27128 // Cast the operand to an alloca, and remember the frame index.
27129 auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
27130 if (!FINode)
27131 report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
27132 EHInfo->EHGuardFrameIndex = FINode->getIndex();
27134 // Return the chain operand without making any DAG nodes.
27135 return Chain;
27138 /// Emit Truncating Store with signed or unsigned saturation.
27139 static SDValue
27140 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &DL, SDValue Val,
27141 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
27142 SelectionDAG &DAG) {
27143 SDVTList VTs = DAG.getVTList(MVT::Other);
27144 SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
27145 SDValue Ops[] = { Chain, Val, Ptr, Undef };
27146 unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
27147 return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
27150 /// Emit Masked Truncating Store with signed or unsigned saturation.
27151 static SDValue EmitMaskedTruncSStore(bool SignedSat, SDValue Chain,
27152 const SDLoc &DL,
27153 SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
27154 MachineMemOperand *MMO, SelectionDAG &DAG) {
27155 SDVTList VTs = DAG.getVTList(MVT::Other);
27156 SDValue Ops[] = { Chain, Val, Ptr, Mask };
27157 unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
27158 return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
27161 bool X86::isExtendedSwiftAsyncFrameSupported(const X86Subtarget &Subtarget,
27162 const MachineFunction &MF) {
27163 if (!Subtarget.is64Bit())
27164 return false;
27165 // 64-bit targets support extended Swift async frame setup,
27166 // except for targets that use the windows 64 prologue.
27167 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
27170 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
27171 SelectionDAG &DAG) {
27172 unsigned IntNo = Op.getConstantOperandVal(1);
27173 const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
27174 if (!IntrData) {
27175 switch (IntNo) {
27177 case Intrinsic::swift_async_context_addr: {
27178 SDLoc dl(Op);
27179 auto &MF = DAG.getMachineFunction();
27180 auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
27181 if (X86::isExtendedSwiftAsyncFrameSupported(Subtarget, MF)) {
27182 MF.getFrameInfo().setFrameAddressIsTaken(true);
27183 X86FI->setHasSwiftAsyncContext(true);
27184 SDValue Chain = Op->getOperand(0);
27185 SDValue CopyRBP = DAG.getCopyFromReg(Chain, dl, X86::RBP, MVT::i64);
27186 SDValue Result =
27187 SDValue(DAG.getMachineNode(X86::SUB64ri32, dl, MVT::i64, CopyRBP,
27188 DAG.getTargetConstant(8, dl, MVT::i32)),
27190 // Return { result, chain }.
27191 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
27192 CopyRBP.getValue(1));
27193 } else {
27194 // No special extended frame, create or reuse an existing stack slot.
27195 int PtrSize = Subtarget.is64Bit() ? 8 : 4;
27196 if (!X86FI->getSwiftAsyncContextFrameIdx())
27197 X86FI->setSwiftAsyncContextFrameIdx(
27198 MF.getFrameInfo().CreateStackObject(PtrSize, Align(PtrSize),
27199 false));
27200 SDValue Result =
27201 DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(),
27202 PtrSize == 8 ? MVT::i64 : MVT::i32);
27203 // Return { result, chain }.
27204 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
27205 Op->getOperand(0));
27209 case llvm::Intrinsic::x86_seh_ehregnode:
27210 return MarkEHRegistrationNode(Op, DAG);
27211 case llvm::Intrinsic::x86_seh_ehguard:
27212 return MarkEHGuard(Op, DAG);
27213 case llvm::Intrinsic::x86_rdpkru: {
27214 SDLoc dl(Op);
27215 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27216 // Create a RDPKRU node and pass 0 to the ECX parameter.
27217 return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
27218 DAG.getConstant(0, dl, MVT::i32));
27220 case llvm::Intrinsic::x86_wrpkru: {
27221 SDLoc dl(Op);
27222 // Create a WRPKRU node, pass the input to the EAX parameter, and pass 0
27223 // to the EDX and ECX parameters.
27224 return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
27225 Op.getOperand(0), Op.getOperand(2),
27226 DAG.getConstant(0, dl, MVT::i32),
27227 DAG.getConstant(0, dl, MVT::i32));
27229 case llvm::Intrinsic::asan_check_memaccess: {
27230 // Mark this as adjustsStack because it will be lowered to a call.
27231 DAG.getMachineFunction().getFrameInfo().setAdjustsStack(true);
27232 // Don't do anything here, we will expand these intrinsics out later.
27233 return Op;
27235 case llvm::Intrinsic::x86_flags_read_u32:
27236 case llvm::Intrinsic::x86_flags_read_u64:
27237 case llvm::Intrinsic::x86_flags_write_u32:
27238 case llvm::Intrinsic::x86_flags_write_u64: {
27239 // We need a frame pointer because this will get lowered to a PUSH/POP
27240 // sequence.
27241 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27242 MFI.setHasCopyImplyingStackAdjustment(true);
27243 // Don't do anything here, we will expand these intrinsics out later
27244 // during FinalizeISel in EmitInstrWithCustomInserter.
27245 return Op;
27247 case Intrinsic::x86_lwpins32:
27248 case Intrinsic::x86_lwpins64:
27249 case Intrinsic::x86_umwait:
27250 case Intrinsic::x86_tpause: {
27251 SDLoc dl(Op);
27252 SDValue Chain = Op->getOperand(0);
27253 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27254 unsigned Opcode;
27256 switch (IntNo) {
27257 default: llvm_unreachable("Impossible intrinsic");
27258 case Intrinsic::x86_umwait:
27259 Opcode = X86ISD::UMWAIT;
27260 break;
27261 case Intrinsic::x86_tpause:
27262 Opcode = X86ISD::TPAUSE;
27263 break;
27264 case Intrinsic::x86_lwpins32:
27265 case Intrinsic::x86_lwpins64:
27266 Opcode = X86ISD::LWPINS;
27267 break;
27270 SDValue Operation =
27271 DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
27272 Op->getOperand(3), Op->getOperand(4));
27273 SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27274 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27275 Operation.getValue(1));
27277 case Intrinsic::x86_enqcmd:
27278 case Intrinsic::x86_enqcmds: {
27279 SDLoc dl(Op);
27280 SDValue Chain = Op.getOperand(0);
27281 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27282 unsigned Opcode;
27283 switch (IntNo) {
27284 default: llvm_unreachable("Impossible intrinsic!");
27285 case Intrinsic::x86_enqcmd:
27286 Opcode = X86ISD::ENQCMD;
27287 break;
27288 case Intrinsic::x86_enqcmds:
27289 Opcode = X86ISD::ENQCMDS;
27290 break;
27292 SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
27293 Op.getOperand(3));
27294 SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
27295 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27296 Operation.getValue(1));
27298 case Intrinsic::x86_aesenc128kl:
27299 case Intrinsic::x86_aesdec128kl:
27300 case Intrinsic::x86_aesenc256kl:
27301 case Intrinsic::x86_aesdec256kl: {
27302 SDLoc DL(Op);
27303 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
27304 SDValue Chain = Op.getOperand(0);
27305 unsigned Opcode;
27307 switch (IntNo) {
27308 default: llvm_unreachable("Impossible intrinsic");
27309 case Intrinsic::x86_aesenc128kl:
27310 Opcode = X86ISD::AESENC128KL;
27311 break;
27312 case Intrinsic::x86_aesdec128kl:
27313 Opcode = X86ISD::AESDEC128KL;
27314 break;
27315 case Intrinsic::x86_aesenc256kl:
27316 Opcode = X86ISD::AESENC256KL;
27317 break;
27318 case Intrinsic::x86_aesdec256kl:
27319 Opcode = X86ISD::AESDEC256KL;
27320 break;
27323 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27324 MachineMemOperand *MMO = MemIntr->getMemOperand();
27325 EVT MemVT = MemIntr->getMemoryVT();
27326 SDValue Operation = DAG.getMemIntrinsicNode(
27327 Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
27328 MMO);
27329 SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
27331 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27332 {ZF, Operation.getValue(0), Operation.getValue(2)});
27334 case Intrinsic::x86_aesencwide128kl:
27335 case Intrinsic::x86_aesdecwide128kl:
27336 case Intrinsic::x86_aesencwide256kl:
27337 case Intrinsic::x86_aesdecwide256kl: {
27338 SDLoc DL(Op);
27339 SDVTList VTs = DAG.getVTList(
27340 {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
27341 MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
27342 SDValue Chain = Op.getOperand(0);
27343 unsigned Opcode;
27345 switch (IntNo) {
27346 default: llvm_unreachable("Impossible intrinsic");
27347 case Intrinsic::x86_aesencwide128kl:
27348 Opcode = X86ISD::AESENCWIDE128KL;
27349 break;
27350 case Intrinsic::x86_aesdecwide128kl:
27351 Opcode = X86ISD::AESDECWIDE128KL;
27352 break;
27353 case Intrinsic::x86_aesencwide256kl:
27354 Opcode = X86ISD::AESENCWIDE256KL;
27355 break;
27356 case Intrinsic::x86_aesdecwide256kl:
27357 Opcode = X86ISD::AESDECWIDE256KL;
27358 break;
27361 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
27362 MachineMemOperand *MMO = MemIntr->getMemOperand();
27363 EVT MemVT = MemIntr->getMemoryVT();
27364 SDValue Operation = DAG.getMemIntrinsicNode(
27365 Opcode, DL, VTs,
27366 {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
27367 Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
27368 Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
27369 MemVT, MMO);
27370 SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
27372 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
27373 {ZF, Operation.getValue(1), Operation.getValue(2),
27374 Operation.getValue(3), Operation.getValue(4),
27375 Operation.getValue(5), Operation.getValue(6),
27376 Operation.getValue(7), Operation.getValue(8),
27377 Operation.getValue(9)});
27379 case Intrinsic::x86_testui: {
27380 SDLoc dl(Op);
27381 SDValue Chain = Op.getOperand(0);
27382 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
27383 SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
27384 SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
27385 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
27386 Operation.getValue(1));
27388 case Intrinsic::x86_t2rpntlvwz0rs_internal:
27389 case Intrinsic::x86_t2rpntlvwz0rst1_internal:
27390 case Intrinsic::x86_t2rpntlvwz1rs_internal:
27391 case Intrinsic::x86_t2rpntlvwz1rst1_internal:
27392 case Intrinsic::x86_t2rpntlvwz0_internal:
27393 case Intrinsic::x86_t2rpntlvwz0t1_internal:
27394 case Intrinsic::x86_t2rpntlvwz1_internal:
27395 case Intrinsic::x86_t2rpntlvwz1t1_internal: {
27396 auto *X86MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
27397 X86MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
27398 unsigned IntNo = Op.getConstantOperandVal(1);
27399 unsigned Opc = 0;
27400 switch (IntNo) {
27401 default:
27402 llvm_unreachable("Unexpected intrinsic!");
27403 case Intrinsic::x86_t2rpntlvwz0_internal:
27404 Opc = X86::PT2RPNTLVWZ0V;
27405 break;
27406 case Intrinsic::x86_t2rpntlvwz0t1_internal:
27407 Opc = X86::PT2RPNTLVWZ0T1V;
27408 break;
27409 case Intrinsic::x86_t2rpntlvwz1_internal:
27410 Opc = X86::PT2RPNTLVWZ1V;
27411 break;
27412 case Intrinsic::x86_t2rpntlvwz1t1_internal:
27413 Opc = X86::PT2RPNTLVWZ1T1V;
27414 break;
27415 case Intrinsic::x86_t2rpntlvwz0rs_internal:
27416 Opc = X86::PT2RPNTLVWZ0RSV;
27417 break;
27418 case Intrinsic::x86_t2rpntlvwz0rst1_internal:
27419 Opc = X86::PT2RPNTLVWZ0RST1V;
27420 break;
27421 case Intrinsic::x86_t2rpntlvwz1rs_internal:
27422 Opc = X86::PT2RPNTLVWZ1RSV;
27423 break;
27424 case Intrinsic::x86_t2rpntlvwz1rst1_internal:
27425 Opc = X86::PT2RPNTLVWZ1RST1V;
27426 break;
27429 SDLoc DL(Op);
27430 SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
27432 SDValue Ops[] = {Op.getOperand(2), // Row
27433 Op.getOperand(3), // Col0
27434 Op.getOperand(4), // Col1
27435 Op.getOperand(5), // Base
27436 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
27437 Op.getOperand(6), // Index
27438 DAG.getTargetConstant(0, DL, MVT::i32), // Disp
27439 DAG.getRegister(0, MVT::i16), // Segment
27440 Op.getOperand(0)}; // Chain
27442 MachineSDNode *Res = DAG.getMachineNode(Opc, DL, VTs, Ops);
27443 SDValue Res0 = DAG.getTargetExtractSubreg(X86::sub_t0, DL, MVT::x86amx,
27444 SDValue(Res, 0));
27445 SDValue Res1 = DAG.getTargetExtractSubreg(X86::sub_t1, DL, MVT::x86amx,
27446 SDValue(Res, 0));
27447 return DAG.getMergeValues({Res0, Res1, SDValue(Res, 1)}, DL);
27449 case Intrinsic::x86_atomic_bts_rm:
27450 case Intrinsic::x86_atomic_btc_rm:
27451 case Intrinsic::x86_atomic_btr_rm: {
27452 SDLoc DL(Op);
27453 MVT VT = Op.getSimpleValueType();
27454 SDValue Chain = Op.getOperand(0);
27455 SDValue Op1 = Op.getOperand(2);
27456 SDValue Op2 = Op.getOperand(3);
27457 unsigned Opc = IntNo == Intrinsic::x86_atomic_bts_rm ? X86ISD::LBTS_RM
27458 : IntNo == Intrinsic::x86_atomic_btc_rm ? X86ISD::LBTC_RM
27459 : X86ISD::LBTR_RM;
27460 MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
27461 SDValue Res =
27462 DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
27463 {Chain, Op1, Op2}, VT, MMO);
27464 Chain = Res.getValue(1);
27465 Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
27466 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
27468 case Intrinsic::x86_atomic_bts:
27469 case Intrinsic::x86_atomic_btc:
27470 case Intrinsic::x86_atomic_btr: {
27471 SDLoc DL(Op);
27472 MVT VT = Op.getSimpleValueType();
27473 SDValue Chain = Op.getOperand(0);
27474 SDValue Op1 = Op.getOperand(2);
27475 SDValue Op2 = Op.getOperand(3);
27476 unsigned Opc = IntNo == Intrinsic::x86_atomic_bts ? X86ISD::LBTS
27477 : IntNo == Intrinsic::x86_atomic_btc ? X86ISD::LBTC
27478 : X86ISD::LBTR;
27479 SDValue Size = DAG.getConstant(VT.getScalarSizeInBits(), DL, MVT::i32);
27480 MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
27481 SDValue Res =
27482 DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
27483 {Chain, Op1, Op2, Size}, VT, MMO);
27484 Chain = Res.getValue(1);
27485 Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
27486 unsigned Imm = Op2->getAsZExtVal();
27487 if (Imm)
27488 Res = DAG.getNode(ISD::SHL, DL, VT, Res,
27489 DAG.getShiftAmountConstant(Imm, VT, DL));
27490 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
27492 case Intrinsic::x86_cmpccxadd32:
27493 case Intrinsic::x86_cmpccxadd64: {
27494 SDLoc DL(Op);
27495 SDValue Chain = Op.getOperand(0);
27496 SDValue Addr = Op.getOperand(2);
27497 SDValue Src1 = Op.getOperand(3);
27498 SDValue Src2 = Op.getOperand(4);
27499 SDValue CC = Op.getOperand(5);
27500 MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
27501 SDValue Operation = DAG.getMemIntrinsicNode(
27502 X86ISD::CMPCCXADD, DL, Op->getVTList(), {Chain, Addr, Src1, Src2, CC},
27503 MVT::i32, MMO);
27504 return Operation;
27506 case Intrinsic::x86_aadd32:
27507 case Intrinsic::x86_aadd64:
27508 case Intrinsic::x86_aand32:
27509 case Intrinsic::x86_aand64:
27510 case Intrinsic::x86_aor32:
27511 case Intrinsic::x86_aor64:
27512 case Intrinsic::x86_axor32:
27513 case Intrinsic::x86_axor64: {
27514 SDLoc DL(Op);
27515 SDValue Chain = Op.getOperand(0);
27516 SDValue Op1 = Op.getOperand(2);
27517 SDValue Op2 = Op.getOperand(3);
27518 MVT VT = Op2.getSimpleValueType();
27519 unsigned Opc = 0;
27520 switch (IntNo) {
27521 default:
27522 llvm_unreachable("Unknown Intrinsic");
27523 case Intrinsic::x86_aadd32:
27524 case Intrinsic::x86_aadd64:
27525 Opc = X86ISD::AADD;
27526 break;
27527 case Intrinsic::x86_aand32:
27528 case Intrinsic::x86_aand64:
27529 Opc = X86ISD::AAND;
27530 break;
27531 case Intrinsic::x86_aor32:
27532 case Intrinsic::x86_aor64:
27533 Opc = X86ISD::AOR;
27534 break;
27535 case Intrinsic::x86_axor32:
27536 case Intrinsic::x86_axor64:
27537 Opc = X86ISD::AXOR;
27538 break;
27540 MachineMemOperand *MMO = cast<MemSDNode>(Op)->getMemOperand();
27541 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(),
27542 {Chain, Op1, Op2}, VT, MMO);
27544 case Intrinsic::x86_atomic_add_cc:
27545 case Intrinsic::x86_atomic_sub_cc:
27546 case Intrinsic::x86_atomic_or_cc:
27547 case Intrinsic::x86_atomic_and_cc:
27548 case Intrinsic::x86_atomic_xor_cc: {
27549 SDLoc DL(Op);
27550 SDValue Chain = Op.getOperand(0);
27551 SDValue Op1 = Op.getOperand(2);
27552 SDValue Op2 = Op.getOperand(3);
27553 X86::CondCode CC = (X86::CondCode)Op.getConstantOperandVal(4);
27554 MVT VT = Op2.getSimpleValueType();
27555 unsigned Opc = 0;
27556 switch (IntNo) {
27557 default:
27558 llvm_unreachable("Unknown Intrinsic");
27559 case Intrinsic::x86_atomic_add_cc:
27560 Opc = X86ISD::LADD;
27561 break;
27562 case Intrinsic::x86_atomic_sub_cc:
27563 Opc = X86ISD::LSUB;
27564 break;
27565 case Intrinsic::x86_atomic_or_cc:
27566 Opc = X86ISD::LOR;
27567 break;
27568 case Intrinsic::x86_atomic_and_cc:
27569 Opc = X86ISD::LAND;
27570 break;
27571 case Intrinsic::x86_atomic_xor_cc:
27572 Opc = X86ISD::LXOR;
27573 break;
27575 MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
27576 SDValue LockArith =
27577 DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
27578 {Chain, Op1, Op2}, VT, MMO);
27579 Chain = LockArith.getValue(1);
27580 return DAG.getMergeValues({getSETCC(CC, LockArith, DL, DAG), Chain}, DL);
27583 return SDValue();
27586 SDLoc dl(Op);
27587 switch(IntrData->Type) {
27588 default: llvm_unreachable("Unknown Intrinsic Type");
27589 case RDSEED:
27590 case RDRAND: {
27591 // Emit the node with the right value type.
27592 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
27593 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
27595 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
27596 // Otherwise return the value from Rand, which is always 0, casted to i32.
27597 SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
27598 DAG.getConstant(1, dl, Op->getValueType(1)),
27599 DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
27600 SDValue(Result.getNode(), 1)};
27601 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
27603 // Return { result, isValid, chain }.
27604 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
27605 SDValue(Result.getNode(), 2));
27607 case GATHER_AVX2: {
27608 SDValue Chain = Op.getOperand(0);
27609 SDValue Src = Op.getOperand(2);
27610 SDValue Base = Op.getOperand(3);
27611 SDValue Index = Op.getOperand(4);
27612 SDValue Mask = Op.getOperand(5);
27613 SDValue Scale = Op.getOperand(6);
27614 return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
27615 Scale, Chain, Subtarget);
27617 case GATHER: {
27618 //gather(v1, mask, index, base, scale);
27619 SDValue Chain = Op.getOperand(0);
27620 SDValue Src = Op.getOperand(2);
27621 SDValue Base = Op.getOperand(3);
27622 SDValue Index = Op.getOperand(4);
27623 SDValue Mask = Op.getOperand(5);
27624 SDValue Scale = Op.getOperand(6);
27625 return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
27626 Chain, Subtarget);
27628 case SCATTER: {
27629 //scatter(base, mask, index, v1, scale);
27630 SDValue Chain = Op.getOperand(0);
27631 SDValue Base = Op.getOperand(2);
27632 SDValue Mask = Op.getOperand(3);
27633 SDValue Index = Op.getOperand(4);
27634 SDValue Src = Op.getOperand(5);
27635 SDValue Scale = Op.getOperand(6);
27636 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
27637 Scale, Chain, Subtarget);
27639 case PREFETCH: {
27640 const APInt &HintVal = Op.getConstantOperandAPInt(6);
27641 assert((HintVal == 2 || HintVal == 3) &&
27642 "Wrong prefetch hint in intrinsic: should be 2 or 3");
27643 unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
27644 SDValue Chain = Op.getOperand(0);
27645 SDValue Mask = Op.getOperand(2);
27646 SDValue Index = Op.getOperand(3);
27647 SDValue Base = Op.getOperand(4);
27648 SDValue Scale = Op.getOperand(5);
27649 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
27650 Subtarget);
27652 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
27653 case RDTSC: {
27654 SmallVector<SDValue, 2> Results;
27655 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
27656 Results);
27657 return DAG.getMergeValues(Results, dl);
27659 // Read Performance Monitoring Counters.
27660 case RDPMC:
27661 // Read Processor Register.
27662 case RDPRU:
27663 // GetExtended Control Register.
27664 case XGETBV: {
27665 SmallVector<SDValue, 2> Results;
27667 // RDPMC uses ECX to select the index of the performance counter to read.
27668 // RDPRU uses ECX to select the processor register to read.
27669 // XGETBV uses ECX to select the index of the XCR register to return.
27670 // The result is stored into registers EDX:EAX.
27671 expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
27672 Subtarget, Results);
27673 return DAG.getMergeValues(Results, dl);
27675 // XTEST intrinsics.
27676 case XTEST: {
27677 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
27678 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
27680 SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
27681 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
27682 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
27683 Ret, SDValue(InTrans.getNode(), 1));
27685 case TRUNCATE_TO_MEM_VI8:
27686 case TRUNCATE_TO_MEM_VI16:
27687 case TRUNCATE_TO_MEM_VI32: {
27688 SDValue Mask = Op.getOperand(4);
27689 SDValue DataToTruncate = Op.getOperand(3);
27690 SDValue Addr = Op.getOperand(2);
27691 SDValue Chain = Op.getOperand(0);
27693 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
27694 assert(MemIntr && "Expected MemIntrinsicSDNode!");
27696 EVT MemVT = MemIntr->getMemoryVT();
27698 uint16_t TruncationOp = IntrData->Opc0;
27699 switch (TruncationOp) {
27700 case X86ISD::VTRUNC: {
27701 if (isAllOnesConstant(Mask)) // return just a truncate store
27702 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
27703 MemIntr->getMemOperand());
27705 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27706 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27707 SDValue Offset = DAG.getUNDEF(VMask.getValueType());
27709 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
27710 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
27711 true /* truncating */);
27713 case X86ISD::VTRUNCUS:
27714 case X86ISD::VTRUNCS: {
27715 bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
27716 if (isAllOnesConstant(Mask))
27717 return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
27718 MemIntr->getMemOperand(), DAG);
27720 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27721 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27723 return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
27724 VMask, MemVT, MemIntr->getMemOperand(), DAG);
27726 default:
27727 llvm_unreachable("Unsupported truncstore intrinsic");
27730 case INTR_TYPE_CAST_MMX:
27731 return SDValue(); // handled in combineINTRINSIC_*
27735 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
27736 SelectionDAG &DAG) const {
27737 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27738 MFI.setReturnAddressIsTaken(true);
27740 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
27741 return SDValue();
27743 unsigned Depth = Op.getConstantOperandVal(0);
27744 SDLoc dl(Op);
27745 EVT PtrVT = getPointerTy(DAG.getDataLayout());
27747 if (Depth > 0) {
27748 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
27749 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27750 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
27751 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
27752 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
27753 MachinePointerInfo());
27756 // Just load the return address.
27757 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
27758 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
27759 MachinePointerInfo());
27762 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
27763 SelectionDAG &DAG) const {
27764 DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
27765 return getReturnAddressFrameIndex(DAG);
27768 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
27769 MachineFunction &MF = DAG.getMachineFunction();
27770 MachineFrameInfo &MFI = MF.getFrameInfo();
27771 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
27772 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27773 EVT VT = Op.getValueType();
27775 MFI.setFrameAddressIsTaken(true);
27777 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
27778 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
27779 // is not possible to crawl up the stack without looking at the unwind codes
27780 // simultaneously.
27781 int FrameAddrIndex = FuncInfo->getFAIndex();
27782 if (!FrameAddrIndex) {
27783 // Set up a frame object for the return address.
27784 unsigned SlotSize = RegInfo->getSlotSize();
27785 FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
27786 SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
27787 FuncInfo->setFAIndex(FrameAddrIndex);
27789 return DAG.getFrameIndex(FrameAddrIndex, VT);
27792 unsigned FrameReg =
27793 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
27794 SDLoc dl(Op); // FIXME probably not meaningful
27795 unsigned Depth = Op.getConstantOperandVal(0);
27796 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
27797 (FrameReg == X86::EBP && VT == MVT::i32)) &&
27798 "Invalid Frame Register!");
27799 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
27800 while (Depth--)
27801 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
27802 MachinePointerInfo());
27803 return FrameAddr;
27806 // FIXME? Maybe this could be a TableGen attribute on some registers and
27807 // this table could be generated automatically from RegInfo.
27808 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
27809 const MachineFunction &MF) const {
27810 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
27812 Register Reg = StringSwitch<unsigned>(RegName)
27813 .Case("esp", X86::ESP)
27814 .Case("rsp", X86::RSP)
27815 .Case("ebp", X86::EBP)
27816 .Case("rbp", X86::RBP)
27817 .Case("r14", X86::R14)
27818 .Case("r15", X86::R15)
27819 .Default(0);
27821 if (Reg == X86::EBP || Reg == X86::RBP) {
27822 if (!TFI.hasFP(MF))
27823 report_fatal_error("register " + StringRef(RegName) +
27824 " is allocatable: function has no frame pointer");
27825 #ifndef NDEBUG
27826 else {
27827 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27828 Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
27829 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
27830 "Invalid Frame Register!");
27832 #endif
27835 if (Reg)
27836 return Reg;
27838 report_fatal_error("Invalid register name global variable");
27841 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
27842 SelectionDAG &DAG) const {
27843 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27844 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
27847 Register X86TargetLowering::getExceptionPointerRegister(
27848 const Constant *PersonalityFn) const {
27849 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
27850 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27852 return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
27855 Register X86TargetLowering::getExceptionSelectorRegister(
27856 const Constant *PersonalityFn) const {
27857 // Funclet personalities don't use selectors (the runtime does the selection).
27858 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
27859 return X86::NoRegister;
27860 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27863 bool X86TargetLowering::needsFixedCatchObjects() const {
27864 return Subtarget.isTargetWin64();
27867 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
27868 SDValue Chain = Op.getOperand(0);
27869 SDValue Offset = Op.getOperand(1);
27870 SDValue Handler = Op.getOperand(2);
27871 SDLoc dl (Op);
27873 EVT PtrVT = getPointerTy(DAG.getDataLayout());
27874 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27875 Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
27876 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
27877 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
27878 "Invalid Frame Register!");
27879 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
27880 Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
27882 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
27883 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
27884 dl));
27885 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
27886 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
27887 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
27889 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
27890 DAG.getRegister(StoreAddrReg, PtrVT));
27893 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
27894 SelectionDAG &DAG) const {
27895 SDLoc DL(Op);
27896 // If the subtarget is not 64bit, we may need the global base reg
27897 // after isel expand pseudo, i.e., after CGBR pass ran.
27898 // Therefore, ask for the GlobalBaseReg now, so that the pass
27899 // inserts the code for us in case we need it.
27900 // Otherwise, we will end up in a situation where we will
27901 // reference a virtual register that is not defined!
27902 if (!Subtarget.is64Bit()) {
27903 const X86InstrInfo *TII = Subtarget.getInstrInfo();
27904 (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
27906 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
27907 DAG.getVTList(MVT::i32, MVT::Other),
27908 Op.getOperand(0), Op.getOperand(1));
27911 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
27912 SelectionDAG &DAG) const {
27913 SDLoc DL(Op);
27914 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
27915 Op.getOperand(0), Op.getOperand(1));
27918 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
27919 SelectionDAG &DAG) const {
27920 SDLoc DL(Op);
27921 return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
27922 Op.getOperand(0));
27925 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
27926 return Op.getOperand(0);
27929 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
27930 SelectionDAG &DAG) const {
27931 SDValue Root = Op.getOperand(0);
27932 SDValue Trmp = Op.getOperand(1); // trampoline
27933 SDValue FPtr = Op.getOperand(2); // nested function
27934 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
27935 SDLoc dl (Op);
27937 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
27938 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
27940 if (Subtarget.is64Bit()) {
27941 SDValue OutChains[6];
27943 // Large code-model.
27944 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
27945 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
27947 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
27948 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
27950 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
27952 // Load the pointer to the nested function into R11.
27953 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
27954 SDValue Addr = Trmp;
27955 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27956 Addr, MachinePointerInfo(TrmpAddr));
27958 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27959 DAG.getConstant(2, dl, MVT::i64));
27960 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
27961 MachinePointerInfo(TrmpAddr, 2), Align(2));
27963 // Load the 'nest' parameter value into R10.
27964 // R10 is specified in X86CallingConv.td
27965 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
27966 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27967 DAG.getConstant(10, dl, MVT::i64));
27968 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27969 Addr, MachinePointerInfo(TrmpAddr, 10));
27971 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27972 DAG.getConstant(12, dl, MVT::i64));
27973 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
27974 MachinePointerInfo(TrmpAddr, 12), Align(2));
27976 // Jump to the nested function.
27977 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
27978 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27979 DAG.getConstant(20, dl, MVT::i64));
27980 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27981 Addr, MachinePointerInfo(TrmpAddr, 20));
27983 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
27984 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27985 DAG.getConstant(22, dl, MVT::i64));
27986 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
27987 Addr, MachinePointerInfo(TrmpAddr, 22));
27989 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27990 } else {
27991 const Function *Func =
27992 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
27993 CallingConv::ID CC = Func->getCallingConv();
27994 unsigned NestReg;
27996 switch (CC) {
27997 default:
27998 llvm_unreachable("Unsupported calling convention");
27999 case CallingConv::C:
28000 case CallingConv::X86_StdCall: {
28001 // Pass 'nest' parameter in ECX.
28002 // Must be kept in sync with X86CallingConv.td
28003 NestReg = X86::ECX;
28005 // Check that ECX wasn't needed by an 'inreg' parameter.
28006 FunctionType *FTy = Func->getFunctionType();
28007 const AttributeList &Attrs = Func->getAttributes();
28009 if (!Attrs.isEmpty() && !Func->isVarArg()) {
28010 unsigned InRegCount = 0;
28011 unsigned Idx = 0;
28013 for (FunctionType::param_iterator I = FTy->param_begin(),
28014 E = FTy->param_end(); I != E; ++I, ++Idx)
28015 if (Attrs.hasParamAttr(Idx, Attribute::InReg)) {
28016 const DataLayout &DL = DAG.getDataLayout();
28017 // FIXME: should only count parameters that are lowered to integers.
28018 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
28021 if (InRegCount > 2) {
28022 report_fatal_error("Nest register in use - reduce number of inreg"
28023 " parameters!");
28026 break;
28028 case CallingConv::X86_FastCall:
28029 case CallingConv::X86_ThisCall:
28030 case CallingConv::Fast:
28031 case CallingConv::Tail:
28032 case CallingConv::SwiftTail:
28033 // Pass 'nest' parameter in EAX.
28034 // Must be kept in sync with X86CallingConv.td
28035 NestReg = X86::EAX;
28036 break;
28039 SDValue OutChains[4];
28040 SDValue Addr, Disp;
28042 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28043 DAG.getConstant(10, dl, MVT::i32));
28044 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
28046 // This is storing the opcode for MOV32ri.
28047 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
28048 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
28049 OutChains[0] =
28050 DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
28051 Trmp, MachinePointerInfo(TrmpAddr));
28053 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28054 DAG.getConstant(1, dl, MVT::i32));
28055 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
28056 MachinePointerInfo(TrmpAddr, 1), Align(1));
28058 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
28059 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28060 DAG.getConstant(5, dl, MVT::i32));
28061 OutChains[2] =
28062 DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
28063 MachinePointerInfo(TrmpAddr, 5), Align(1));
28065 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
28066 DAG.getConstant(6, dl, MVT::i32));
28067 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
28068 MachinePointerInfo(TrmpAddr, 6), Align(1));
28070 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
28074 SDValue X86TargetLowering::LowerGET_ROUNDING(SDValue Op,
28075 SelectionDAG &DAG) const {
28077 The rounding mode is in bits 11:10 of FPSR, and has the following
28078 settings:
28079 00 Round to nearest
28080 01 Round to -inf
28081 10 Round to +inf
28082 11 Round to 0
28084 GET_ROUNDING, on the other hand, expects the following:
28085 -1 Undefined
28086 0 Round to 0
28087 1 Round to nearest
28088 2 Round to +inf
28089 3 Round to -inf
28091 To perform the conversion, we use a packed lookup table of the four 2-bit
28092 values that we can index by FPSP[11:10]
28093 0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
28095 (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
28098 MachineFunction &MF = DAG.getMachineFunction();
28099 MVT VT = Op.getSimpleValueType();
28100 SDLoc DL(Op);
28102 // Save FP Control Word to stack slot
28103 int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
28104 SDValue StackSlot =
28105 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
28107 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
28109 SDValue Chain = Op.getOperand(0);
28110 SDValue Ops[] = {Chain, StackSlot};
28111 Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
28112 DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
28113 Align(2), MachineMemOperand::MOStore);
28115 // Load FP Control Word from stack slot
28116 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
28117 Chain = CWD.getValue(1);
28119 // Mask and turn the control bits into a shift for the lookup table.
28120 SDValue Shift =
28121 DAG.getNode(ISD::SRL, DL, MVT::i16,
28122 DAG.getNode(ISD::AND, DL, MVT::i16,
28123 CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
28124 DAG.getConstant(9, DL, MVT::i8));
28125 Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
28127 SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
28128 SDValue RetVal =
28129 DAG.getNode(ISD::AND, DL, MVT::i32,
28130 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
28131 DAG.getConstant(3, DL, MVT::i32));
28133 RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
28135 return DAG.getMergeValues({RetVal, Chain}, DL);
28138 SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
28139 SelectionDAG &DAG) const {
28140 MachineFunction &MF = DAG.getMachineFunction();
28141 SDLoc DL(Op);
28142 SDValue Chain = Op.getNode()->getOperand(0);
28144 // FP control word may be set only from data in memory. So we need to allocate
28145 // stack space to save/load FP control word.
28146 int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
28147 SDValue StackSlot =
28148 DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
28149 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
28150 MachineMemOperand *MMO =
28151 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
28153 // Store FP control word into memory.
28154 SDValue Ops[] = {Chain, StackSlot};
28155 Chain = DAG.getMemIntrinsicNode(
28156 X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
28158 // Load FP Control Word from stack slot and clear RM field (bits 11:10).
28159 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
28160 Chain = CWD.getValue(1);
28161 CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
28162 DAG.getConstant(0xf3ff, DL, MVT::i16));
28164 // Calculate new rounding mode.
28165 SDValue NewRM = Op.getNode()->getOperand(1);
28166 SDValue RMBits;
28167 if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
28168 uint64_t RM = CVal->getZExtValue();
28169 int FieldVal;
28170 switch (static_cast<RoundingMode>(RM)) {
28171 // clang-format off
28172 case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
28173 case RoundingMode::TowardNegative: FieldVal = X86::rmDownward; break;
28174 case RoundingMode::TowardPositive: FieldVal = X86::rmUpward; break;
28175 case RoundingMode::TowardZero: FieldVal = X86::rmTowardZero; break;
28176 default:
28177 llvm_unreachable("rounding mode is not supported by X86 hardware");
28178 // clang-format on
28180 RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
28181 } else {
28182 // Need to convert argument into bits of control word:
28183 // 0 Round to 0 -> 11
28184 // 1 Round to nearest -> 00
28185 // 2 Round to +inf -> 10
28186 // 3 Round to -inf -> 01
28187 // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
28188 // To make the conversion, put all these values into a value 0xc9 and shift
28189 // it left depending on the rounding mode:
28190 // (0xc9 << 4) & 0xc00 = X86::rmTowardZero
28191 // (0xc9 << 6) & 0xc00 = X86::rmToNearest
28192 // ...
28193 // (0xc9 << (2 * NewRM + 4)) & 0xc00
28194 SDValue ShiftValue =
28195 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
28196 DAG.getNode(ISD::ADD, DL, MVT::i32,
28197 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
28198 DAG.getConstant(1, DL, MVT::i8)),
28199 DAG.getConstant(4, DL, MVT::i32)));
28200 SDValue Shifted =
28201 DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
28202 ShiftValue);
28203 RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
28204 DAG.getConstant(0xc00, DL, MVT::i16));
28207 // Update rounding mode bits and store the new FP Control Word into stack.
28208 CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
28209 Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(2));
28211 // Load FP control word from the slot.
28212 SDValue OpsLD[] = {Chain, StackSlot};
28213 MachineMemOperand *MMOL =
28214 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
28215 Chain = DAG.getMemIntrinsicNode(
28216 X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
28218 // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
28219 // same way but in bits 14:13.
28220 if (Subtarget.hasSSE1()) {
28221 // Store MXCSR into memory.
28222 Chain = DAG.getNode(
28223 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28224 DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
28225 StackSlot);
28227 // Load MXCSR from stack slot and clear RM field (bits 14:13).
28228 SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
28229 Chain = CWD.getValue(1);
28230 CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
28231 DAG.getConstant(0xffff9fff, DL, MVT::i32));
28233 // Shift X87 RM bits from 11:10 to 14:13.
28234 RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
28235 RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
28236 DAG.getConstant(3, DL, MVT::i8));
28238 // Update rounding mode bits and store the new FP Control Word into stack.
28239 CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
28240 Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(4));
28242 // Load MXCSR from the slot.
28243 Chain = DAG.getNode(
28244 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28245 DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
28246 StackSlot);
28249 return Chain;
28252 const unsigned X87StateSize = 28;
28253 const unsigned FPStateSize = 32;
28254 [[maybe_unused]] const unsigned FPStateSizeInBits = FPStateSize * 8;
28256 SDValue X86TargetLowering::LowerGET_FPENV_MEM(SDValue Op,
28257 SelectionDAG &DAG) const {
28258 MachineFunction &MF = DAG.getMachineFunction();
28259 SDLoc DL(Op);
28260 SDValue Chain = Op->getOperand(0);
28261 SDValue Ptr = Op->getOperand(1);
28262 auto *Node = cast<FPStateAccessSDNode>(Op);
28263 EVT MemVT = Node->getMemoryVT();
28264 assert(MemVT.getSizeInBits() == FPStateSizeInBits);
28265 MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
28267 // Get x87 state, if it presents.
28268 if (Subtarget.hasX87()) {
28269 Chain =
28270 DAG.getMemIntrinsicNode(X86ISD::FNSTENVm, DL, DAG.getVTList(MVT::Other),
28271 {Chain, Ptr}, MemVT, MMO);
28273 // FNSTENV changes the exception mask, so load back the stored environment.
28274 MachineMemOperand::Flags NewFlags =
28275 MachineMemOperand::MOLoad |
28276 (MMO->getFlags() & ~MachineMemOperand::MOStore);
28277 MMO = MF.getMachineMemOperand(MMO, NewFlags);
28278 Chain =
28279 DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
28280 {Chain, Ptr}, MemVT, MMO);
28283 // If target supports SSE, get MXCSR as well.
28284 if (Subtarget.hasSSE1()) {
28285 // Get pointer to the MXCSR location in memory.
28286 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
28287 SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
28288 DAG.getConstant(X87StateSize, DL, PtrVT));
28289 // Store MXCSR into memory.
28290 Chain = DAG.getNode(
28291 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28292 DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
28293 MXCSRAddr);
28296 return Chain;
28299 static SDValue createSetFPEnvNodes(SDValue Ptr, SDValue Chain, const SDLoc &DL,
28300 EVT MemVT, MachineMemOperand *MMO,
28301 SelectionDAG &DAG,
28302 const X86Subtarget &Subtarget) {
28303 // Set x87 state, if it presents.
28304 if (Subtarget.hasX87())
28305 Chain =
28306 DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
28307 {Chain, Ptr}, MemVT, MMO);
28308 // If target supports SSE, set MXCSR as well.
28309 if (Subtarget.hasSSE1()) {
28310 // Get pointer to the MXCSR location in memory.
28311 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
28312 SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
28313 DAG.getConstant(X87StateSize, DL, PtrVT));
28314 // Load MXCSR from memory.
28315 Chain = DAG.getNode(
28316 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
28317 DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
28318 MXCSRAddr);
28320 return Chain;
28323 SDValue X86TargetLowering::LowerSET_FPENV_MEM(SDValue Op,
28324 SelectionDAG &DAG) const {
28325 SDLoc DL(Op);
28326 SDValue Chain = Op->getOperand(0);
28327 SDValue Ptr = Op->getOperand(1);
28328 auto *Node = cast<FPStateAccessSDNode>(Op);
28329 EVT MemVT = Node->getMemoryVT();
28330 assert(MemVT.getSizeInBits() == FPStateSizeInBits);
28331 MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
28332 return createSetFPEnvNodes(Ptr, Chain, DL, MemVT, MMO, DAG, Subtarget);
28335 SDValue X86TargetLowering::LowerRESET_FPENV(SDValue Op,
28336 SelectionDAG &DAG) const {
28337 MachineFunction &MF = DAG.getMachineFunction();
28338 SDLoc DL(Op);
28339 SDValue Chain = Op.getNode()->getOperand(0);
28341 IntegerType *ItemTy = Type::getInt32Ty(*DAG.getContext());
28342 ArrayType *FPEnvTy = ArrayType::get(ItemTy, 8);
28343 SmallVector<Constant *, 8> FPEnvVals;
28345 // x87 FPU Control Word: mask all floating-point exceptions, sets rounding to
28346 // nearest. FPU precision is set to 53 bits on Windows and 64 bits otherwise
28347 // for compatibility with glibc.
28348 unsigned X87CW = Subtarget.isTargetWindowsMSVC() ? 0x27F : 0x37F;
28349 FPEnvVals.push_back(ConstantInt::get(ItemTy, X87CW));
28350 Constant *Zero = ConstantInt::get(ItemTy, 0);
28351 for (unsigned I = 0; I < 6; ++I)
28352 FPEnvVals.push_back(Zero);
28354 // MXCSR: mask all floating-point exceptions, sets rounding to nearest, clear
28355 // all exceptions, sets DAZ and FTZ to 0.
28356 FPEnvVals.push_back(ConstantInt::get(ItemTy, 0x1F80));
28357 Constant *FPEnvBits = ConstantArray::get(FPEnvTy, FPEnvVals);
28358 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
28359 SDValue Env = DAG.getConstantPool(FPEnvBits, PtrVT);
28360 MachinePointerInfo MPI =
28361 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
28362 MachineMemOperand *MMO = MF.getMachineMemOperand(
28363 MPI, MachineMemOperand::MOStore, X87StateSize, Align(4));
28365 return createSetFPEnvNodes(Env, Chain, DL, MVT::i32, MMO, DAG, Subtarget);
28368 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
28370 // i8/i16 vector implemented using dword LZCNT vector instruction
28371 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
28372 // split the vector, perform operation on it's Lo a Hi part and
28373 // concatenate the results.
28374 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
28375 const X86Subtarget &Subtarget) {
28376 assert(Op.getOpcode() == ISD::CTLZ);
28377 SDLoc dl(Op);
28378 MVT VT = Op.getSimpleValueType();
28379 MVT EltVT = VT.getVectorElementType();
28380 unsigned NumElems = VT.getVectorNumElements();
28382 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
28383 "Unsupported element type");
28385 // Split vector, it's Lo and Hi parts will be handled in next iteration.
28386 if (NumElems > 16 ||
28387 (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
28388 return splitVectorIntUnary(Op, DAG, dl);
28390 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
28391 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
28392 "Unsupported value type for operation");
28394 // Use native supported vector instruction vplzcntd.
28395 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
28396 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
28397 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
28398 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
28400 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
28403 // Lower CTLZ using a PSHUFB lookup table implementation.
28404 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
28405 const X86Subtarget &Subtarget,
28406 SelectionDAG &DAG) {
28407 MVT VT = Op.getSimpleValueType();
28408 int NumElts = VT.getVectorNumElements();
28409 int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
28410 MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
28412 // Per-nibble leading zero PSHUFB lookup table.
28413 const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
28414 /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
28415 /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
28416 /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
28418 SmallVector<SDValue, 64> LUTVec;
28419 for (int i = 0; i < NumBytes; ++i)
28420 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
28421 SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
28423 // Begin by bitcasting the input to byte vector, then split those bytes
28424 // into lo/hi nibbles and use the PSHUFB LUT to perform CTLZ on each of them.
28425 // If the hi input nibble is zero then we add both results together, otherwise
28426 // we just take the hi result (by masking the lo result to zero before the
28427 // add).
28428 SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
28429 SDValue Zero = DAG.getConstant(0, DL, CurrVT);
28431 SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
28432 SDValue Lo = Op0;
28433 SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
28434 SDValue HiZ;
28435 if (CurrVT.is512BitVector()) {
28436 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28437 HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
28438 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28439 } else {
28440 HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
28443 Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
28444 Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
28445 Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
28446 SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
28448 // Merge result back from vXi8 back to VT, working on the lo/hi halves
28449 // of the current vector width in the same way we did for the nibbles.
28450 // If the upper half of the input element is zero then add the halves'
28451 // leading zero counts together, otherwise just use the upper half's.
28452 // Double the width of the result until we are at target width.
28453 while (CurrVT != VT) {
28454 int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
28455 int CurrNumElts = CurrVT.getVectorNumElements();
28456 MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
28457 MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
28458 SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
28460 // Check if the upper half of the input element is zero.
28461 if (CurrVT.is512BitVector()) {
28462 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
28463 HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
28464 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28465 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
28466 } else {
28467 HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
28468 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
28470 HiZ = DAG.getBitcast(NextVT, HiZ);
28472 // Move the upper/lower halves to the lower bits as we'll be extending to
28473 // NextVT. Mask the lower result to zero if HiZ is true and add the results
28474 // together.
28475 SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
28476 SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
28477 SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
28478 R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
28479 Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
28480 CurrVT = NextVT;
28483 return Res;
28486 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
28487 const X86Subtarget &Subtarget,
28488 SelectionDAG &DAG) {
28489 MVT VT = Op.getSimpleValueType();
28491 if (Subtarget.hasCDI() &&
28492 // vXi8 vectors need to be promoted to 512-bits for vXi32.
28493 (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
28494 return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
28496 // Decompose 256-bit ops into smaller 128-bit ops.
28497 if (VT.is256BitVector() && !Subtarget.hasInt256())
28498 return splitVectorIntUnary(Op, DAG, DL);
28500 // Decompose 512-bit ops into smaller 256-bit ops.
28501 if (VT.is512BitVector() && !Subtarget.hasBWI())
28502 return splitVectorIntUnary(Op, DAG, DL);
28504 assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
28505 return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
28508 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
28509 SelectionDAG &DAG) {
28510 MVT VT = Op.getSimpleValueType();
28511 MVT OpVT = VT;
28512 unsigned NumBits = VT.getSizeInBits();
28513 SDLoc dl(Op);
28514 unsigned Opc = Op.getOpcode();
28516 if (VT.isVector())
28517 return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
28519 Op = Op.getOperand(0);
28520 if (VT == MVT::i8) {
28521 // Zero extend to i32 since there is not an i8 bsr.
28522 OpVT = MVT::i32;
28523 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
28526 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
28527 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
28528 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
28530 if (Opc == ISD::CTLZ) {
28531 // If src is zero (i.e. bsr sets ZF), returns NumBits.
28532 SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
28533 DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28534 Op.getValue(1)};
28535 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
28538 // Finally xor with NumBits-1.
28539 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
28540 DAG.getConstant(NumBits - 1, dl, OpVT));
28542 if (VT == MVT::i8)
28543 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
28544 return Op;
28547 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
28548 SelectionDAG &DAG) {
28549 MVT VT = Op.getSimpleValueType();
28550 unsigned NumBits = VT.getScalarSizeInBits();
28551 SDValue N0 = Op.getOperand(0);
28552 SDLoc dl(Op);
28554 assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
28555 "Only scalar CTTZ requires custom lowering");
28557 // Issue a bsf (scan bits forward) which also sets EFLAGS.
28558 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28559 Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
28561 // If src is known never zero we can skip the CMOV.
28562 if (DAG.isKnownNeverZero(N0))
28563 return Op;
28565 // If src is zero (i.e. bsf sets ZF), returns NumBits.
28566 SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
28567 DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
28568 Op.getValue(1)};
28569 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
28572 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
28573 const X86Subtarget &Subtarget) {
28574 MVT VT = Op.getSimpleValueType();
28575 SDLoc DL(Op);
28577 if (VT == MVT::i16 || VT == MVT::i32)
28578 return lowerAddSubToHorizontalOp(Op, DL, DAG, Subtarget);
28580 if (VT == MVT::v32i16 || VT == MVT::v64i8)
28581 return splitVectorIntBinary(Op, DAG, DL);
28583 assert(Op.getSimpleValueType().is256BitVector() &&
28584 Op.getSimpleValueType().isInteger() &&
28585 "Only handle AVX 256-bit vector integer operation");
28586 return splitVectorIntBinary(Op, DAG, DL);
28589 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
28590 const X86Subtarget &Subtarget) {
28591 MVT VT = Op.getSimpleValueType();
28592 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
28593 unsigned Opcode = Op.getOpcode();
28594 SDLoc DL(Op);
28596 if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
28597 (VT.is256BitVector() && !Subtarget.hasInt256())) {
28598 assert(Op.getSimpleValueType().isInteger() &&
28599 "Only handle AVX vector integer operation");
28600 return splitVectorIntBinary(Op, DAG, DL);
28603 // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
28604 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28605 EVT SetCCResultType =
28606 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28608 unsigned BitWidth = VT.getScalarSizeInBits();
28609 if (Opcode == ISD::USUBSAT) {
28610 if (!TLI.isOperationLegal(ISD::UMAX, VT) || useVPTERNLOG(Subtarget, VT)) {
28611 // Handle a special-case with a bit-hack instead of cmp+select:
28612 // usubsat X, SMIN --> (X ^ SMIN) & (X s>> BW-1)
28613 // If the target can use VPTERNLOG, DAGToDAG will match this as
28614 // "vpsra + vpternlog" which is better than "vpmax + vpsub" with a
28615 // "broadcast" constant load.
28616 ConstantSDNode *C = isConstOrConstSplat(Y, true);
28617 if (C && C->getAPIntValue().isSignMask()) {
28618 SDValue SignMask = DAG.getConstant(C->getAPIntValue(), DL, VT);
28619 SDValue ShiftAmt = DAG.getConstant(BitWidth - 1, DL, VT);
28620 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, SignMask);
28621 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShiftAmt);
28622 return DAG.getNode(ISD::AND, DL, VT, Xor, Sra);
28625 if (!TLI.isOperationLegal(ISD::UMAX, VT)) {
28626 // usubsat X, Y --> (X >u Y) ? X - Y : 0
28627 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
28628 SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
28629 // TODO: Move this to DAGCombiner?
28630 if (SetCCResultType == VT &&
28631 DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
28632 return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
28633 return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
28637 if ((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
28638 (!VT.isVector() || VT == MVT::v2i64)) {
28639 APInt MinVal = APInt::getSignedMinValue(BitWidth);
28640 APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
28641 SDValue Zero = DAG.getConstant(0, DL, VT);
28642 SDValue Result =
28643 DAG.getNode(Opcode == ISD::SADDSAT ? ISD::SADDO : ISD::SSUBO, DL,
28644 DAG.getVTList(VT, SetCCResultType), X, Y);
28645 SDValue SumDiff = Result.getValue(0);
28646 SDValue Overflow = Result.getValue(1);
28647 SDValue SatMin = DAG.getConstant(MinVal, DL, VT);
28648 SDValue SatMax = DAG.getConstant(MaxVal, DL, VT);
28649 SDValue SumNeg =
28650 DAG.getSetCC(DL, SetCCResultType, SumDiff, Zero, ISD::SETLT);
28651 Result = DAG.getSelect(DL, VT, SumNeg, SatMax, SatMin);
28652 return DAG.getSelect(DL, VT, Overflow, Result, SumDiff);
28655 // Use default expansion.
28656 return SDValue();
28659 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
28660 SelectionDAG &DAG) {
28661 MVT VT = Op.getSimpleValueType();
28662 SDLoc DL(Op);
28664 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
28665 // Since X86 does not have CMOV for 8-bit integer, we don't convert
28666 // 8-bit integer abs to NEG and CMOV.
28667 SDValue N0 = Op.getOperand(0);
28668 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
28669 DAG.getConstant(0, DL, VT), N0);
28670 SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_NS, DL, MVT::i8),
28671 SDValue(Neg.getNode(), 1)};
28672 return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
28675 // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
28676 if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
28677 SDValue Src = Op.getOperand(0);
28678 SDValue Neg = DAG.getNegative(Src, DL, VT);
28679 return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Neg, Src);
28682 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
28683 assert(VT.isInteger() &&
28684 "Only handle AVX 256-bit vector integer operation");
28685 return splitVectorIntUnary(Op, DAG, DL);
28688 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28689 return splitVectorIntUnary(Op, DAG, DL);
28691 // Default to expand.
28692 return SDValue();
28695 static SDValue LowerAVG(SDValue Op, const X86Subtarget &Subtarget,
28696 SelectionDAG &DAG) {
28697 MVT VT = Op.getSimpleValueType();
28698 SDLoc DL(Op);
28700 // For AVX1 cases, split to use legal ops.
28701 if (VT.is256BitVector() && !Subtarget.hasInt256())
28702 return splitVectorIntBinary(Op, DAG, DL);
28704 if (VT == MVT::v32i16 || VT == MVT::v64i8)
28705 return splitVectorIntBinary(Op, DAG, DL);
28707 // Default to expand.
28708 return SDValue();
28711 static SDValue LowerMINMAX(SDValue Op, const X86Subtarget &Subtarget,
28712 SelectionDAG &DAG) {
28713 MVT VT = Op.getSimpleValueType();
28714 SDLoc DL(Op);
28716 // For AVX1 cases, split to use legal ops.
28717 if (VT.is256BitVector() && !Subtarget.hasInt256())
28718 return splitVectorIntBinary(Op, DAG, DL);
28720 if (VT == MVT::v32i16 || VT == MVT::v64i8)
28721 return splitVectorIntBinary(Op, DAG, DL);
28723 // Default to expand.
28724 return SDValue();
28727 static SDValue LowerFMINIMUM_FMAXIMUM(SDValue Op, const X86Subtarget &Subtarget,
28728 SelectionDAG &DAG) {
28729 assert((Op.getOpcode() == ISD::FMAXIMUM || Op.getOpcode() == ISD::FMINIMUM) &&
28730 "Expected FMAXIMUM or FMINIMUM opcode");
28731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28732 EVT VT = Op.getValueType();
28733 SDValue X = Op.getOperand(0);
28734 SDValue Y = Op.getOperand(1);
28735 SDLoc DL(Op);
28736 uint64_t SizeInBits = VT.getScalarSizeInBits();
28737 APInt PreferredZero = APInt::getZero(SizeInBits);
28738 APInt OppositeZero = PreferredZero;
28739 EVT IVT = VT.changeTypeToInteger();
28740 X86ISD::NodeType MinMaxOp;
28741 if (Op.getOpcode() == ISD::FMAXIMUM) {
28742 MinMaxOp = X86ISD::FMAX;
28743 OppositeZero.setSignBit();
28744 } else {
28745 PreferredZero.setSignBit();
28746 MinMaxOp = X86ISD::FMIN;
28748 EVT SetCCType =
28749 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28751 // The tables below show the expected result of Max in cases of NaN and
28752 // signed zeros.
28754 // Y Y
28755 // Num xNaN +0 -0
28756 // --------------- ---------------
28757 // Num | Max | Y | +0 | +0 | +0 |
28758 // X --------------- X ---------------
28759 // xNaN | X | X/Y | -0 | +0 | -0 |
28760 // --------------- ---------------
28762 // It is achieved by means of FMAX/FMIN with preliminary checks and operand
28763 // reordering.
28765 // We check if any of operands is NaN and return NaN. Then we check if any of
28766 // operands is zero or negative zero (for fmaximum and fminimum respectively)
28767 // to ensure the correct zero is returned.
28768 auto MatchesZero = [](SDValue Op, APInt Zero) {
28769 Op = peekThroughBitcasts(Op);
28770 if (auto *CstOp = dyn_cast<ConstantFPSDNode>(Op))
28771 return CstOp->getValueAPF().bitcastToAPInt() == Zero;
28772 if (auto *CstOp = dyn_cast<ConstantSDNode>(Op))
28773 return CstOp->getAPIntValue() == Zero;
28774 if (Op->getOpcode() == ISD::BUILD_VECTOR ||
28775 Op->getOpcode() == ISD::SPLAT_VECTOR) {
28776 for (const SDValue &OpVal : Op->op_values()) {
28777 if (OpVal.isUndef())
28778 continue;
28779 auto *CstOp = dyn_cast<ConstantFPSDNode>(OpVal);
28780 if (!CstOp)
28781 return false;
28782 if (!CstOp->getValueAPF().isZero())
28783 continue;
28784 if (CstOp->getValueAPF().bitcastToAPInt() != Zero)
28785 return false;
28787 return true;
28789 return false;
28792 bool IsXNeverNaN = DAG.isKnownNeverNaN(X);
28793 bool IsYNeverNaN = DAG.isKnownNeverNaN(Y);
28794 bool IgnoreSignedZero = DAG.getTarget().Options.NoSignedZerosFPMath ||
28795 Op->getFlags().hasNoSignedZeros() ||
28796 DAG.isKnownNeverZeroFloat(X) ||
28797 DAG.isKnownNeverZeroFloat(Y);
28798 SDValue NewX, NewY;
28799 if (IgnoreSignedZero || MatchesZero(Y, PreferredZero) ||
28800 MatchesZero(X, OppositeZero)) {
28801 // Operands are already in right order or order does not matter.
28802 NewX = X;
28803 NewY = Y;
28804 } else if (MatchesZero(X, PreferredZero) || MatchesZero(Y, OppositeZero)) {
28805 NewX = Y;
28806 NewY = X;
28807 } else if (!VT.isVector() && (VT == MVT::f16 || Subtarget.hasDQI()) &&
28808 (Op->getFlags().hasNoNaNs() || IsXNeverNaN || IsYNeverNaN)) {
28809 if (IsXNeverNaN)
28810 std::swap(X, Y);
28811 // VFPCLASSS consumes a vector type. So provide a minimal one corresponded
28812 // xmm register.
28813 MVT VectorType = MVT::getVectorVT(VT.getSimpleVT(), 128 / SizeInBits);
28814 SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorType, X);
28815 // Bits of classes:
28816 // Bits Imm8[0] Imm8[1] Imm8[2] Imm8[3] Imm8[4] Imm8[5] Imm8[6] Imm8[7]
28817 // Class QNAN PosZero NegZero PosINF NegINF Denormal Negative SNAN
28818 SDValue Imm = DAG.getTargetConstant(MinMaxOp == X86ISD::FMAX ? 0b11 : 0b101,
28819 DL, MVT::i32);
28820 SDValue IsNanZero = DAG.getNode(X86ISD::VFPCLASSS, DL, MVT::v1i1, VX, Imm);
28821 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
28822 DAG.getConstant(0, DL, MVT::v8i1), IsNanZero,
28823 DAG.getIntPtrConstant(0, DL));
28824 SDValue NeedSwap = DAG.getBitcast(MVT::i8, Ins);
28825 NewX = DAG.getSelect(DL, VT, NeedSwap, Y, X);
28826 NewY = DAG.getSelect(DL, VT, NeedSwap, X, Y);
28827 return DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
28828 } else {
28829 SDValue IsXSigned;
28830 if (Subtarget.is64Bit() || VT != MVT::f64) {
28831 SDValue XInt = DAG.getNode(ISD::BITCAST, DL, IVT, X);
28832 SDValue ZeroCst = DAG.getConstant(0, DL, IVT);
28833 IsXSigned = DAG.getSetCC(DL, SetCCType, XInt, ZeroCst, ISD::SETLT);
28834 } else {
28835 assert(VT == MVT::f64);
28836 SDValue Ins = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v2f64,
28837 DAG.getConstantFP(0, DL, MVT::v2f64), X,
28838 DAG.getIntPtrConstant(0, DL));
28839 SDValue VX = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, Ins);
28840 SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VX,
28841 DAG.getIntPtrConstant(1, DL));
28842 Hi = DAG.getBitcast(MVT::i32, Hi);
28843 SDValue ZeroCst = DAG.getConstant(0, DL, MVT::i32);
28844 EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(),
28845 *DAG.getContext(), MVT::i32);
28846 IsXSigned = DAG.getSetCC(DL, SetCCType, Hi, ZeroCst, ISD::SETLT);
28848 if (MinMaxOp == X86ISD::FMAX) {
28849 NewX = DAG.getSelect(DL, VT, IsXSigned, X, Y);
28850 NewY = DAG.getSelect(DL, VT, IsXSigned, Y, X);
28851 } else {
28852 NewX = DAG.getSelect(DL, VT, IsXSigned, Y, X);
28853 NewY = DAG.getSelect(DL, VT, IsXSigned, X, Y);
28857 bool IgnoreNaN = DAG.getTarget().Options.NoNaNsFPMath ||
28858 Op->getFlags().hasNoNaNs() || (IsXNeverNaN && IsYNeverNaN);
28860 // If we did no ordering operands for signed zero handling and we need
28861 // to process NaN and we know that the second operand is not NaN then put
28862 // it in first operand and we will not need to post handle NaN after max/min.
28863 if (IgnoreSignedZero && !IgnoreNaN && DAG.isKnownNeverNaN(NewY))
28864 std::swap(NewX, NewY);
28866 SDValue MinMax = DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
28868 if (IgnoreNaN || DAG.isKnownNeverNaN(NewX))
28869 return MinMax;
28871 SDValue IsNaN = DAG.getSetCC(DL, SetCCType, NewX, NewX, ISD::SETUO);
28872 return DAG.getSelect(DL, VT, IsNaN, NewX, MinMax);
28875 static SDValue LowerABD(SDValue Op, const X86Subtarget &Subtarget,
28876 SelectionDAG &DAG) {
28877 MVT VT = Op.getSimpleValueType();
28878 SDLoc dl(Op);
28880 // For AVX1 cases, split to use legal ops.
28881 if (VT.is256BitVector() && !Subtarget.hasInt256())
28882 return splitVectorIntBinary(Op, DAG, dl);
28884 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.useBWIRegs())
28885 return splitVectorIntBinary(Op, DAG, dl);
28887 bool IsSigned = Op.getOpcode() == ISD::ABDS;
28888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28890 if (Subtarget.canUseCMOV() && VT.isScalarInteger()) {
28891 X86::CondCode CC = IsSigned ? X86::COND_L : X86::COND_B;
28892 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28894 // abds(lhs, rhs) -> select(slt(lhs,rhs),sub(rhs,lhs),sub(lhs,rhs))
28895 // abdu(lhs, rhs) -> select(ult(lhs,rhs),sub(rhs,lhs),sub(lhs,rhs))
28896 if (VT.bitsGE(MVT::i32)) {
28897 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28898 SDValue LHS = DAG.getFreeze(Op.getOperand(0));
28899 SDValue RHS = DAG.getFreeze(Op.getOperand(1));
28900 SDValue Diff0 = DAG.getNode(X86ISD::SUB, dl, VTs, LHS, RHS);
28901 SDValue Diff1 = DAG.getNode(X86ISD::SUB, dl, VTs, RHS, LHS);
28902 return DAG.getNode(X86ISD::CMOV, dl, VT, Diff1, Diff0,
28903 DAG.getTargetConstant(CC, dl, MVT::i8),
28904 Diff1.getValue(1));
28907 // abds(lhs, rhs) -> trunc(abs(sub(sext(lhs), sext(rhs))))
28908 // abdu(lhs, rhs) -> trunc(abs(sub(zext(lhs), zext(rhs))))
28909 unsigned WideBits = std::max<unsigned>(2 * VT.getScalarSizeInBits(), 32u);
28910 MVT WideVT = MVT::getIntegerVT(WideBits);
28911 if (TLI.isTypeLegal(WideVT)) {
28912 SDVTList WideVTs = DAG.getVTList(WideVT, MVT::i32);
28913 SDValue LHS = DAG.getNode(ExtOpc, dl, WideVT, Op.getOperand(0));
28914 SDValue RHS = DAG.getNode(ExtOpc, dl, WideVT, Op.getOperand(1));
28915 SDValue Diff0 = DAG.getNode(X86ISD::SUB, dl, WideVTs, LHS, RHS);
28916 SDValue Diff1 = DAG.getNode(X86ISD::SUB, dl, WideVTs, RHS, LHS);
28917 SDValue AbsDiff = DAG.getNode(X86ISD::CMOV, dl, WideVT, Diff1, Diff0,
28918 DAG.getTargetConstant(CC, dl, MVT::i8),
28919 Diff1.getValue(1));
28920 return DAG.getNode(ISD::TRUNCATE, dl, VT, AbsDiff);
28924 // Default to expand.
28925 return SDValue();
28928 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
28929 SelectionDAG &DAG) {
28930 SDLoc dl(Op);
28931 MVT VT = Op.getSimpleValueType();
28933 // Decompose 256-bit ops into 128-bit ops.
28934 if (VT.is256BitVector() && !Subtarget.hasInt256())
28935 return splitVectorIntBinary(Op, DAG, dl);
28937 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28938 return splitVectorIntBinary(Op, DAG, dl);
28940 SDValue A = Op.getOperand(0);
28941 SDValue B = Op.getOperand(1);
28943 // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
28944 // vector pairs, multiply and truncate.
28945 if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
28946 unsigned NumElts = VT.getVectorNumElements();
28947 unsigned NumLanes = VT.getSizeInBits() / 128;
28948 unsigned NumEltsPerLane = NumElts / NumLanes;
28950 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28951 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28952 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
28953 return DAG.getNode(
28954 ISD::TRUNCATE, dl, VT,
28955 DAG.getNode(ISD::MUL, dl, ExVT,
28956 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
28957 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
28960 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28962 // For vXi8 mul, try PMADDUBSW to avoid the need for extension.
28963 // Don't do this if we only need to unpack one half.
28964 if (Subtarget.hasSSSE3()) {
28965 bool BIsBuildVector = isa<BuildVectorSDNode>(B);
28966 bool IsLoLaneAllZeroOrUndef = BIsBuildVector;
28967 bool IsHiLaneAllZeroOrUndef = BIsBuildVector;
28968 if (BIsBuildVector) {
28969 for (auto [Idx, Val] : enumerate(B->ops())) {
28970 if ((Idx % NumEltsPerLane) >= (NumEltsPerLane / 2))
28971 IsHiLaneAllZeroOrUndef &= isNullConstantOrUndef(Val);
28972 else
28973 IsLoLaneAllZeroOrUndef &= isNullConstantOrUndef(Val);
28976 if (!(IsLoLaneAllZeroOrUndef || IsHiLaneAllZeroOrUndef)) {
28977 SDValue Mask = DAG.getBitcast(VT, DAG.getConstant(0x00FF, dl, ExVT));
28978 SDValue BLo = DAG.getNode(ISD::AND, dl, VT, Mask, B);
28979 SDValue BHi = DAG.getNode(X86ISD::ANDNP, dl, VT, Mask, B);
28980 SDValue RLo = DAG.getNode(X86ISD::VPMADDUBSW, dl, ExVT, A, BLo);
28981 SDValue RHi = DAG.getNode(X86ISD::VPMADDUBSW, dl, ExVT, A, BHi);
28982 RLo = DAG.getNode(ISD::AND, dl, VT, DAG.getBitcast(VT, RLo), Mask);
28983 RHi = DAG.getNode(X86ISD::VSHLI, dl, ExVT, RHi,
28984 DAG.getTargetConstant(8, dl, MVT::i8));
28985 return DAG.getNode(ISD::OR, dl, VT, RLo, DAG.getBitcast(VT, RHi));
28989 // Extract the lo/hi parts to any extend to i16.
28990 // We're going to mask off the low byte of each result element of the
28991 // pmullw, so it doesn't matter what's in the high byte of each 16-bit
28992 // element.
28993 SDValue Undef = DAG.getUNDEF(VT);
28994 SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
28995 SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
28997 SDValue BLo, BHi;
28998 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
28999 // If the RHS is a constant, manually unpackl/unpackh.
29000 SmallVector<SDValue, 16> LoOps, HiOps;
29001 for (unsigned i = 0; i != NumElts; i += 16) {
29002 for (unsigned j = 0; j != 8; ++j) {
29003 LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
29004 MVT::i16));
29005 HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
29006 MVT::i16));
29010 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
29011 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
29012 } else {
29013 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
29014 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
29017 // Multiply, mask the lower 8bits of the lo/hi results and pack.
29018 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
29019 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
29020 return getPack(DAG, Subtarget, dl, VT, RLo, RHi);
29023 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
29024 if (VT == MVT::v4i32) {
29025 assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
29026 "Should not custom lower when pmulld is available!");
29028 // Extract the odd parts.
29029 static const int UnpackMask[] = { 1, -1, 3, -1 };
29030 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
29031 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
29033 // Multiply the even parts.
29034 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
29035 DAG.getBitcast(MVT::v2i64, A),
29036 DAG.getBitcast(MVT::v2i64, B));
29037 // Now multiply odd parts.
29038 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
29039 DAG.getBitcast(MVT::v2i64, Aodds),
29040 DAG.getBitcast(MVT::v2i64, Bodds));
29042 Evens = DAG.getBitcast(VT, Evens);
29043 Odds = DAG.getBitcast(VT, Odds);
29045 // Merge the two vectors back together with a shuffle. This expands into 2
29046 // shuffles.
29047 static const int ShufMask[] = { 0, 4, 2, 6 };
29048 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
29051 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
29052 "Only know how to lower V2I64/V4I64/V8I64 multiply");
29053 assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
29055 // Ahi = psrlqi(a, 32);
29056 // Bhi = psrlqi(b, 32);
29058 // AloBlo = pmuludq(a, b);
29059 // AloBhi = pmuludq(a, Bhi);
29060 // AhiBlo = pmuludq(Ahi, b);
29062 // Hi = psllqi(AloBhi + AhiBlo, 32);
29063 // return AloBlo + Hi;
29064 KnownBits AKnown = DAG.computeKnownBits(A);
29065 KnownBits BKnown = DAG.computeKnownBits(B);
29067 APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
29068 bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
29069 bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
29071 APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
29072 bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
29073 bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
29075 SDValue Zero = DAG.getConstant(0, dl, VT);
29077 // Only multiply lo/hi halves that aren't known to be zero.
29078 SDValue AloBlo = Zero;
29079 if (!ALoIsZero && !BLoIsZero)
29080 AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
29082 SDValue AloBhi = Zero;
29083 if (!ALoIsZero && !BHiIsZero) {
29084 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
29085 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
29088 SDValue AhiBlo = Zero;
29089 if (!AHiIsZero && !BLoIsZero) {
29090 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
29091 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
29094 SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
29095 Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
29097 return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
29100 static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
29101 MVT VT, bool IsSigned,
29102 const X86Subtarget &Subtarget,
29103 SelectionDAG &DAG,
29104 SDValue *Low = nullptr) {
29105 unsigned NumElts = VT.getVectorNumElements();
29107 // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
29108 // to a vXi16 type. Do the multiplies, shift the results and pack the half
29109 // lane results back together.
29111 // We'll take different approaches for signed and unsigned.
29112 // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
29113 // and use pmullw to calculate the full 16-bit product.
29114 // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
29115 // shift them left into the upper byte of each word. This allows us to use
29116 // pmulhw to calculate the full 16-bit product. This trick means we don't
29117 // need to sign extend the bytes to use pmullw.
29119 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29120 SDValue Zero = DAG.getConstant(0, dl, VT);
29122 SDValue ALo, AHi;
29123 if (IsSigned) {
29124 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
29125 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
29126 } else {
29127 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
29128 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
29131 SDValue BLo, BHi;
29132 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
29133 // If the RHS is a constant, manually unpackl/unpackh and extend.
29134 SmallVector<SDValue, 16> LoOps, HiOps;
29135 for (unsigned i = 0; i != NumElts; i += 16) {
29136 for (unsigned j = 0; j != 8; ++j) {
29137 SDValue LoOp = B.getOperand(i + j);
29138 SDValue HiOp = B.getOperand(i + j + 8);
29140 if (IsSigned) {
29141 LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
29142 HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
29143 LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
29144 DAG.getConstant(8, dl, MVT::i16));
29145 HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
29146 DAG.getConstant(8, dl, MVT::i16));
29147 } else {
29148 LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
29149 HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
29152 LoOps.push_back(LoOp);
29153 HiOps.push_back(HiOp);
29157 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
29158 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
29159 } else if (IsSigned) {
29160 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
29161 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
29162 } else {
29163 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
29164 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
29167 // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
29168 // pack back to vXi8.
29169 unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
29170 SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
29171 SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
29173 if (Low)
29174 *Low = getPack(DAG, Subtarget, dl, VT, RLo, RHi);
29176 return getPack(DAG, Subtarget, dl, VT, RLo, RHi, /*PackHiHalf*/ true);
29179 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
29180 SelectionDAG &DAG) {
29181 SDLoc dl(Op);
29182 MVT VT = Op.getSimpleValueType();
29183 bool IsSigned = Op->getOpcode() == ISD::MULHS;
29184 unsigned NumElts = VT.getVectorNumElements();
29185 SDValue A = Op.getOperand(0);
29186 SDValue B = Op.getOperand(1);
29188 // Decompose 256-bit ops into 128-bit ops.
29189 if (VT.is256BitVector() && !Subtarget.hasInt256())
29190 return splitVectorIntBinary(Op, DAG, dl);
29192 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
29193 return splitVectorIntBinary(Op, DAG, dl);
29195 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
29196 assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
29197 (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
29198 (VT == MVT::v16i32 && Subtarget.hasAVX512()));
29200 // PMULxD operations multiply each even value (starting at 0) of LHS with
29201 // the related value of RHS and produce a widen result.
29202 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
29203 // => <2 x i64> <ae|cg>
29205 // In other word, to have all the results, we need to perform two PMULxD:
29206 // 1. one with the even values.
29207 // 2. one with the odd values.
29208 // To achieve #2, with need to place the odd values at an even position.
29210 // Place the odd value at an even position (basically, shift all values 1
29211 // step to the left):
29212 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1,
29213 9, -1, 11, -1, 13, -1, 15, -1};
29214 // <a|b|c|d> => <b|undef|d|undef>
29215 SDValue Odd0 =
29216 DAG.getVectorShuffle(VT, dl, A, A, ArrayRef(&Mask[0], NumElts));
29217 // <e|f|g|h> => <f|undef|h|undef>
29218 SDValue Odd1 =
29219 DAG.getVectorShuffle(VT, dl, B, B, ArrayRef(&Mask[0], NumElts));
29221 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
29222 // ints.
29223 MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
29224 unsigned Opcode =
29225 (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
29226 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
29227 // => <2 x i64> <ae|cg>
29228 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
29229 DAG.getBitcast(MulVT, A),
29230 DAG.getBitcast(MulVT, B)));
29231 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
29232 // => <2 x i64> <bf|dh>
29233 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
29234 DAG.getBitcast(MulVT, Odd0),
29235 DAG.getBitcast(MulVT, Odd1)));
29237 // Shuffle it back into the right order.
29238 SmallVector<int, 16> ShufMask(NumElts);
29239 for (int i = 0; i != (int)NumElts; ++i)
29240 ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
29242 SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
29244 // If we have a signed multiply but no PMULDQ fix up the result of an
29245 // unsigned multiply.
29246 if (IsSigned && !Subtarget.hasSSE41()) {
29247 SDValue Zero = DAG.getConstant(0, dl, VT);
29248 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
29249 DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
29250 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
29251 DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
29253 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
29254 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
29257 return Res;
29260 // Only i8 vectors should need custom lowering after this.
29261 assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
29262 (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
29263 "Unsupported vector type");
29265 // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
29266 // logical shift down the upper half and pack back to i8.
29268 // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
29269 // and then ashr/lshr the upper bits down to the lower bits before multiply.
29271 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
29272 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
29273 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29274 unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29275 SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
29276 SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
29277 SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
29278 Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29279 return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
29282 return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
29285 // Custom lowering for SMULO/UMULO.
29286 static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
29287 SelectionDAG &DAG) {
29288 MVT VT = Op.getSimpleValueType();
29290 // Scalars defer to LowerXALUO.
29291 if (!VT.isVector())
29292 return LowerXALUO(Op, DAG);
29294 SDLoc dl(Op);
29295 bool IsSigned = Op->getOpcode() == ISD::SMULO;
29296 SDValue A = Op.getOperand(0);
29297 SDValue B = Op.getOperand(1);
29298 EVT OvfVT = Op->getValueType(1);
29300 if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
29301 (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
29302 // Extract the LHS Lo/Hi vectors
29303 SDValue LHSLo, LHSHi;
29304 std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
29306 // Extract the RHS Lo/Hi vectors
29307 SDValue RHSLo, RHSHi;
29308 std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
29310 EVT LoOvfVT, HiOvfVT;
29311 std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
29312 SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
29313 SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
29315 // Issue the split operations.
29316 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
29317 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
29319 // Join the separate data results and the overflow results.
29320 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29321 SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
29322 Hi.getValue(1));
29324 return DAG.getMergeValues({Res, Ovf}, dl);
29327 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29328 EVT SetccVT =
29329 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
29331 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
29332 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
29333 unsigned NumElts = VT.getVectorNumElements();
29334 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29335 unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29336 SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
29337 SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
29338 SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
29340 SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
29342 SDValue Ovf;
29343 if (IsSigned) {
29344 SDValue High, LowSign;
29345 if (OvfVT.getVectorElementType() == MVT::i1 &&
29346 (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
29347 // Rather the truncating try to do the compare on vXi16 or vXi32.
29348 // Shift the high down filling with sign bits.
29349 High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
29350 // Fill all 16 bits with the sign bit from the low.
29351 LowSign =
29352 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
29353 LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
29354 15, DAG);
29355 SetccVT = OvfVT;
29356 if (!Subtarget.hasBWI()) {
29357 // We can't do a vXi16 compare so sign extend to v16i32.
29358 High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
29359 LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
29361 } else {
29362 // Otherwise do the compare at vXi8.
29363 High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29364 High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
29365 LowSign =
29366 DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
29369 Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
29370 } else {
29371 SDValue High =
29372 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
29373 if (OvfVT.getVectorElementType() == MVT::i1 &&
29374 (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
29375 // Rather the truncating try to do the compare on vXi16 or vXi32.
29376 SetccVT = OvfVT;
29377 if (!Subtarget.hasBWI()) {
29378 // We can't do a vXi16 compare so sign extend to v16i32.
29379 High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
29381 } else {
29382 // Otherwise do the compare at vXi8.
29383 High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
29386 Ovf =
29387 DAG.getSetCC(dl, SetccVT, High,
29388 DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
29391 Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
29393 return DAG.getMergeValues({Low, Ovf}, dl);
29396 SDValue Low;
29397 SDValue High =
29398 LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
29400 SDValue Ovf;
29401 if (IsSigned) {
29402 // SMULO overflows if the high bits don't match the sign of the low.
29403 SDValue LowSign =
29404 DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
29405 Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
29406 } else {
29407 // UMULO overflows if the high bits are non-zero.
29408 Ovf =
29409 DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
29412 Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
29414 return DAG.getMergeValues({Low, Ovf}, dl);
29417 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
29418 assert(Subtarget.isTargetWin64() && "Unexpected target");
29419 EVT VT = Op.getValueType();
29420 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
29421 "Unexpected return type for lowering");
29423 if (isa<ConstantSDNode>(Op->getOperand(1))) {
29424 SmallVector<SDValue> Result;
29425 if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i64, DAG))
29426 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), VT, Result[0], Result[1]);
29429 RTLIB::Libcall LC;
29430 bool isSigned;
29431 switch (Op->getOpcode()) {
29432 // clang-format off
29433 default: llvm_unreachable("Unexpected request for libcall!");
29434 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
29435 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
29436 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
29437 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
29438 // clang-format on
29441 SDLoc dl(Op);
29442 SDValue InChain = DAG.getEntryNode();
29444 TargetLowering::ArgListTy Args;
29445 TargetLowering::ArgListEntry Entry;
29446 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
29447 EVT ArgVT = Op->getOperand(i).getValueType();
29448 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
29449 "Unexpected argument type for lowering");
29450 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
29451 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29452 MachinePointerInfo MPI =
29453 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29454 Entry.Node = StackPtr;
29455 InChain =
29456 DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
29457 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
29458 Entry.Ty = PointerType::get(ArgTy,0);
29459 Entry.IsSExt = false;
29460 Entry.IsZExt = false;
29461 Args.push_back(Entry);
29464 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
29465 getPointerTy(DAG.getDataLayout()));
29467 TargetLowering::CallLoweringInfo CLI(DAG);
29468 CLI.setDebugLoc(dl)
29469 .setChain(InChain)
29470 .setLibCallee(
29471 getLibcallCallingConv(LC),
29472 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
29473 std::move(Args))
29474 .setInRegister()
29475 .setSExtResult(isSigned)
29476 .setZExtResult(!isSigned);
29478 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
29479 return DAG.getBitcast(VT, CallInfo.first);
29482 SDValue X86TargetLowering::LowerWin64_FP_TO_INT128(SDValue Op,
29483 SelectionDAG &DAG,
29484 SDValue &Chain) const {
29485 assert(Subtarget.isTargetWin64() && "Unexpected target");
29486 EVT VT = Op.getValueType();
29487 bool IsStrict = Op->isStrictFPOpcode();
29489 SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
29490 EVT ArgVT = Arg.getValueType();
29492 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
29493 "Unexpected return type for lowering");
29495 RTLIB::Libcall LC;
29496 if (Op->getOpcode() == ISD::FP_TO_SINT ||
29497 Op->getOpcode() == ISD::STRICT_FP_TO_SINT)
29498 LC = RTLIB::getFPTOSINT(ArgVT, VT);
29499 else
29500 LC = RTLIB::getFPTOUINT(ArgVT, VT);
29501 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
29503 SDLoc dl(Op);
29504 MakeLibCallOptions CallOptions;
29505 Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
29507 SDValue Result;
29508 // Expect the i128 argument returned as a v2i64 in xmm0, cast back to the
29509 // expected VT (i128).
29510 std::tie(Result, Chain) =
29511 makeLibCall(DAG, LC, MVT::v2i64, Arg, CallOptions, dl, Chain);
29512 Result = DAG.getBitcast(VT, Result);
29513 return Result;
29516 SDValue X86TargetLowering::LowerWin64_INT128_TO_FP(SDValue Op,
29517 SelectionDAG &DAG) const {
29518 assert(Subtarget.isTargetWin64() && "Unexpected target");
29519 EVT VT = Op.getValueType();
29520 bool IsStrict = Op->isStrictFPOpcode();
29522 SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
29523 EVT ArgVT = Arg.getValueType();
29525 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
29526 "Unexpected argument type for lowering");
29528 RTLIB::Libcall LC;
29529 if (Op->getOpcode() == ISD::SINT_TO_FP ||
29530 Op->getOpcode() == ISD::STRICT_SINT_TO_FP)
29531 LC = RTLIB::getSINTTOFP(ArgVT, VT);
29532 else
29533 LC = RTLIB::getUINTTOFP(ArgVT, VT);
29534 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
29536 SDLoc dl(Op);
29537 MakeLibCallOptions CallOptions;
29538 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
29540 // Pass the i128 argument as an indirect argument on the stack.
29541 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
29542 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29543 MachinePointerInfo MPI =
29544 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29545 Chain = DAG.getStore(Chain, dl, Arg, StackPtr, MPI, Align(16));
29547 SDValue Result;
29548 std::tie(Result, Chain) =
29549 makeLibCall(DAG, LC, VT, StackPtr, CallOptions, dl, Chain);
29550 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
29553 // Generate a GFNI gf2p8affine bitmask for vXi8 bitreverse/shift/rotate.
29554 uint64_t getGFNICtrlImm(unsigned Opcode, unsigned Amt = 0) {
29555 assert((Amt < 8) && "Shift/Rotation amount out of range");
29556 switch (Opcode) {
29557 case ISD::BITREVERSE:
29558 return 0x8040201008040201ULL;
29559 case ISD::SHL:
29560 return ((0x0102040810204080ULL >> (Amt)) &
29561 (0x0101010101010101ULL * (0xFF >> (Amt))));
29562 case ISD::SRL:
29563 return ((0x0102040810204080ULL << (Amt)) &
29564 (0x0101010101010101ULL * ((0xFF << (Amt)) & 0xFF)));
29565 case ISD::SRA:
29566 return (getGFNICtrlImm(ISD::SRL, Amt) |
29567 (0x8080808080808080ULL >> (64 - (8 * Amt))));
29568 case ISD::ROTL:
29569 return getGFNICtrlImm(ISD::SRL, 8 - Amt) | getGFNICtrlImm(ISD::SHL, Amt);
29570 case ISD::ROTR:
29571 return getGFNICtrlImm(ISD::SHL, 8 - Amt) | getGFNICtrlImm(ISD::SRL, Amt);
29573 llvm_unreachable("Unsupported GFNI opcode");
29576 // Generate a GFNI gf2p8affine bitmask for vXi8 bitreverse/shift/rotate.
29577 SDValue getGFNICtrlMask(unsigned Opcode, SelectionDAG &DAG, const SDLoc &DL, MVT VT,
29578 unsigned Amt = 0) {
29579 assert(VT.getVectorElementType() == MVT::i8 &&
29580 (VT.getSizeInBits() % 64) == 0 && "Illegal GFNI control type");
29581 uint64_t Imm = getGFNICtrlImm(Opcode, Amt);
29582 SmallVector<SDValue> MaskBits;
29583 for (unsigned I = 0, E = VT.getSizeInBits(); I != E; I += 8) {
29584 uint64_t Bits = (Imm >> (I % 64)) & 255;
29585 MaskBits.push_back(DAG.getConstant(Bits, DL, MVT::i8));
29587 return DAG.getBuildVector(VT, DL, MaskBits);
29590 // Return true if the required (according to Opcode) shift-imm form is natively
29591 // supported by the Subtarget
29592 static bool supportedVectorShiftWithImm(EVT VT, const X86Subtarget &Subtarget,
29593 unsigned Opcode) {
29594 assert((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
29595 "Unexpected shift opcode");
29597 if (!VT.isSimple())
29598 return false;
29600 if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
29601 return false;
29603 if (VT.getScalarSizeInBits() < 16)
29604 return false;
29606 if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
29607 (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
29608 return true;
29610 bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
29611 (VT.is256BitVector() && Subtarget.hasInt256());
29613 bool AShift = LShift && (Subtarget.hasAVX512() ||
29614 (VT != MVT::v2i64 && VT != MVT::v4i64));
29615 return (Opcode == ISD::SRA) ? AShift : LShift;
29618 // The shift amount is a variable, but it is the same for all vector lanes.
29619 // These instructions are defined together with shift-immediate.
29620 static
29621 bool supportedVectorShiftWithBaseAmnt(EVT VT, const X86Subtarget &Subtarget,
29622 unsigned Opcode) {
29623 return supportedVectorShiftWithImm(VT, Subtarget, Opcode);
29626 // Return true if the required (according to Opcode) variable-shift form is
29627 // natively supported by the Subtarget
29628 static bool supportedVectorVarShift(EVT VT, const X86Subtarget &Subtarget,
29629 unsigned Opcode) {
29630 assert((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
29631 "Unexpected shift opcode");
29633 if (!VT.isSimple())
29634 return false;
29636 if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
29637 return false;
29639 if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
29640 return false;
29642 // vXi16 supported only on AVX-512, BWI
29643 if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
29644 return false;
29646 if (Subtarget.hasAVX512() &&
29647 (Subtarget.useAVX512Regs() || !VT.is512BitVector()))
29648 return true;
29650 bool LShift = VT.is128BitVector() || VT.is256BitVector();
29651 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
29652 return (Opcode == ISD::SRA) ? AShift : LShift;
29655 static SDValue LowerShiftByScalarImmediate(SDValue Op, SelectionDAG &DAG,
29656 const X86Subtarget &Subtarget) {
29657 MVT VT = Op.getSimpleValueType();
29658 SDLoc dl(Op);
29659 SDValue R = Op.getOperand(0);
29660 SDValue Amt = Op.getOperand(1);
29661 unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
29662 unsigned EltSizeInBits = VT.getScalarSizeInBits();
29664 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
29665 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
29666 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
29667 SDValue Ex = DAG.getBitcast(ExVT, R);
29669 // ashr(R, 63) === cmp_slt(R, 0)
29670 if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
29671 assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
29672 "Unsupported PCMPGT op");
29673 return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
29676 if (ShiftAmt >= 32) {
29677 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
29678 SDValue Upper =
29679 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
29680 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
29681 ShiftAmt - 32, DAG);
29682 if (VT == MVT::v2i64)
29683 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
29684 if (VT == MVT::v4i64)
29685 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
29686 {9, 1, 11, 3, 13, 5, 15, 7});
29687 } else {
29688 // SRA upper i32, SRL whole i64 and select lower i32.
29689 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
29690 ShiftAmt, DAG);
29691 SDValue Lower =
29692 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
29693 Lower = DAG.getBitcast(ExVT, Lower);
29694 if (VT == MVT::v2i64)
29695 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
29696 if (VT == MVT::v4i64)
29697 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
29698 {8, 1, 10, 3, 12, 5, 14, 7});
29700 return DAG.getBitcast(VT, Ex);
29703 // Optimize shl/srl/sra with constant shift amount.
29704 APInt APIntShiftAmt;
29705 if (!X86::isConstantSplat(Amt, APIntShiftAmt))
29706 return SDValue();
29708 // If the shift amount is out of range, return undef.
29709 if (APIntShiftAmt.uge(EltSizeInBits))
29710 return DAG.getUNDEF(VT);
29712 uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
29714 if (supportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode())) {
29715 // Hardware support for vector shifts is sparse which makes us scalarize the
29716 // vector operations in many cases. Also, on sandybridge ADD is faster than
29717 // shl: (shl V, 1) -> (add (freeze V), (freeze V))
29718 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
29719 // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
29720 // must be 0). (add undef, undef) however can be any value. To make this
29721 // safe, we must freeze R to ensure that register allocation uses the same
29722 // register for an undefined value. This ensures that the result will
29723 // still be even and preserves the original semantics.
29724 R = DAG.getFreeze(R);
29725 return DAG.getNode(ISD::ADD, dl, VT, R, R);
29728 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
29731 // i64 SRA needs to be performed as partial shifts.
29732 if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
29733 (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
29734 Op.getOpcode() == ISD::SRA)
29735 return ArithmeticShiftRight64(ShiftAmt);
29737 // If we're logical shifting an all-signbits value then we can just perform as
29738 // a mask.
29739 if ((Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL) &&
29740 DAG.ComputeNumSignBits(R) == EltSizeInBits) {
29741 SDValue Mask = DAG.getAllOnesConstant(dl, VT);
29742 Mask = DAG.getNode(Op.getOpcode(), dl, VT, Mask, Amt);
29743 return DAG.getNode(ISD::AND, dl, VT, R, Mask);
29746 if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29747 (Subtarget.hasBWI() && VT == MVT::v64i8)) {
29748 unsigned NumElts = VT.getVectorNumElements();
29749 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29751 // Simple i8 add case
29752 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
29753 // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
29754 // must be 0). (add undef, undef) however can be any value. To make this
29755 // safe, we must freeze R to ensure that register allocation uses the same
29756 // register for an undefined value. This ensures that the result will
29757 // still be even and preserves the original semantics.
29758 R = DAG.getFreeze(R);
29759 return DAG.getNode(ISD::ADD, dl, VT, R, R);
29762 // ashr(R, 7) === cmp_slt(R, 0)
29763 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
29764 SDValue Zeros = DAG.getConstant(0, dl, VT);
29765 if (VT.is512BitVector()) {
29766 assert(VT == MVT::v64i8 && "Unexpected element type!");
29767 SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
29768 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
29770 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
29773 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
29774 if (VT == MVT::v16i8 && Subtarget.hasXOP())
29775 return SDValue();
29777 if (Subtarget.hasGFNI()) {
29778 SDValue Mask = getGFNICtrlMask(Op.getOpcode(), DAG, dl, VT, ShiftAmt);
29779 return DAG.getNode(X86ISD::GF2P8AFFINEQB, dl, VT, R, Mask,
29780 DAG.getTargetConstant(0, dl, MVT::i8));
29783 if (Op.getOpcode() == ISD::SHL) {
29784 // Make a large shift.
29785 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
29786 ShiftAmt, DAG);
29787 SHL = DAG.getBitcast(VT, SHL);
29788 // Zero out the rightmost bits.
29789 APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
29790 return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
29792 if (Op.getOpcode() == ISD::SRL) {
29793 // Make a large shift.
29794 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
29795 ShiftAmt, DAG);
29796 SRL = DAG.getBitcast(VT, SRL);
29797 // Zero out the leftmost bits.
29798 APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
29799 return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
29801 if (Op.getOpcode() == ISD::SRA) {
29802 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
29803 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29805 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
29806 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
29807 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
29808 return Res;
29810 llvm_unreachable("Unknown shift opcode.");
29813 return SDValue();
29816 static SDValue LowerShiftByScalarVariable(SDValue Op, SelectionDAG &DAG,
29817 const X86Subtarget &Subtarget) {
29818 MVT VT = Op.getSimpleValueType();
29819 SDLoc dl(Op);
29820 SDValue R = Op.getOperand(0);
29821 SDValue Amt = Op.getOperand(1);
29822 unsigned Opcode = Op.getOpcode();
29823 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
29825 int BaseShAmtIdx = -1;
29826 if (SDValue BaseShAmt = DAG.getSplatSourceVector(Amt, BaseShAmtIdx)) {
29827 if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode))
29828 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, BaseShAmtIdx,
29829 Subtarget, DAG);
29831 // vXi8 shifts - shift as v8i16 + mask result.
29832 if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
29833 (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
29834 VT == MVT::v64i8) &&
29835 !Subtarget.hasXOP()) {
29836 unsigned NumElts = VT.getVectorNumElements();
29837 MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29838 if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
29839 unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
29840 unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
29842 // Create the mask using vXi16 shifts. For shift-rights we need to move
29843 // the upper byte down before splatting the vXi8 mask.
29844 SDValue BitMask = DAG.getAllOnesConstant(dl, ExtVT);
29845 BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
29846 BaseShAmt, BaseShAmtIdx, Subtarget, DAG);
29847 if (Opcode != ISD::SHL)
29848 BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
29849 8, DAG);
29850 BitMask = DAG.getBitcast(VT, BitMask);
29851 BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
29852 SmallVector<int, 64>(NumElts, 0));
29854 SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
29855 DAG.getBitcast(ExtVT, R), BaseShAmt,
29856 BaseShAmtIdx, Subtarget, DAG);
29857 Res = DAG.getBitcast(VT, Res);
29858 Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
29860 if (Opcode == ISD::SRA) {
29861 // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
29862 // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
29863 SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
29864 SignMask =
29865 getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask, BaseShAmt,
29866 BaseShAmtIdx, Subtarget, DAG);
29867 SignMask = DAG.getBitcast(VT, SignMask);
29868 Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
29869 Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
29871 return Res;
29876 return SDValue();
29879 // Convert a shift/rotate left amount to a multiplication scale factor.
29880 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
29881 const X86Subtarget &Subtarget,
29882 SelectionDAG &DAG) {
29883 MVT VT = Amt.getSimpleValueType();
29884 if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
29885 (Subtarget.hasInt256() && VT == MVT::v16i16) ||
29886 (Subtarget.hasAVX512() && VT == MVT::v32i16) ||
29887 (!Subtarget.hasAVX512() && VT == MVT::v16i8) ||
29888 (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29889 (Subtarget.hasBWI() && VT == MVT::v64i8)))
29890 return SDValue();
29892 MVT SVT = VT.getVectorElementType();
29893 unsigned SVTBits = SVT.getSizeInBits();
29894 unsigned NumElems = VT.getVectorNumElements();
29896 APInt UndefElts;
29897 SmallVector<APInt> EltBits;
29898 if (getTargetConstantBitsFromNode(Amt, SVTBits, UndefElts, EltBits)) {
29899 APInt One(SVTBits, 1);
29900 SmallVector<SDValue> Elts(NumElems, DAG.getUNDEF(SVT));
29901 for (unsigned I = 0; I != NumElems; ++I) {
29902 if (UndefElts[I] || EltBits[I].uge(SVTBits))
29903 continue;
29904 uint64_t ShAmt = EltBits[I].getZExtValue();
29905 Elts[I] = DAG.getConstant(One.shl(ShAmt), dl, SVT);
29907 return DAG.getBuildVector(VT, dl, Elts);
29910 // If the target doesn't support variable shifts, use either FP conversion
29911 // or integer multiplication to avoid shifting each element individually.
29912 if (VT == MVT::v4i32) {
29913 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
29914 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
29915 DAG.getConstant(0x3f800000U, dl, VT));
29916 Amt = DAG.getBitcast(MVT::v4f32, Amt);
29917 return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
29920 // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
29921 if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
29922 SDValue Z = DAG.getConstant(0, dl, VT);
29923 SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
29924 SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
29925 Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
29926 Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
29927 if (Subtarget.hasSSE41())
29928 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29929 return getPack(DAG, Subtarget, dl, VT, Lo, Hi);
29932 return SDValue();
29935 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
29936 SelectionDAG &DAG) {
29937 MVT VT = Op.getSimpleValueType();
29938 SDLoc dl(Op);
29939 SDValue R = Op.getOperand(0);
29940 SDValue Amt = Op.getOperand(1);
29941 unsigned EltSizeInBits = VT.getScalarSizeInBits();
29942 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29944 unsigned Opc = Op.getOpcode();
29945 unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
29946 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
29948 assert(VT.isVector() && "Custom lowering only for vector shifts!");
29949 assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
29951 if (SDValue V = LowerShiftByScalarImmediate(Op, DAG, Subtarget))
29952 return V;
29954 if (SDValue V = LowerShiftByScalarVariable(Op, DAG, Subtarget))
29955 return V;
29957 if (supportedVectorVarShift(VT, Subtarget, Opc))
29958 return Op;
29960 // i64 vector arithmetic shift can be emulated with the transform:
29961 // M = lshr(SIGN_MASK, Amt)
29962 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
29963 if (((VT == MVT::v2i64 && !Subtarget.hasXOP()) ||
29964 (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
29965 Opc == ISD::SRA) {
29966 SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
29967 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
29968 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29969 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
29970 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
29971 return R;
29974 // XOP has 128-bit variable logical/arithmetic shifts.
29975 // +ve/-ve Amt = shift left/right.
29976 if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
29977 VT == MVT::v8i16 || VT == MVT::v16i8)) {
29978 if (Opc == ISD::SRL || Opc == ISD::SRA)
29979 Amt = DAG.getNegative(Amt, dl, VT);
29980 if (Opc == ISD::SHL || Opc == ISD::SRL)
29981 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
29982 if (Opc == ISD::SRA)
29983 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
29986 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
29987 // shifts per-lane and then shuffle the partial results back together.
29988 if (VT == MVT::v2i64 && Opc != ISD::SRA) {
29989 // Splat the shift amounts so the scalar shifts above will catch it.
29990 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
29991 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
29992 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
29993 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
29994 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
29997 // If possible, lower this shift as a sequence of two shifts by
29998 // constant plus a BLENDing shuffle instead of scalarizing it.
29999 // Example:
30000 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
30002 // Could be rewritten as:
30003 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
30005 // The advantage is that the two shifts from the example would be
30006 // lowered as X86ISD::VSRLI nodes in parallel before blending.
30007 if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
30008 (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
30009 SDValue Amt1, Amt2;
30010 unsigned NumElts = VT.getVectorNumElements();
30011 SmallVector<int, 8> ShuffleMask;
30012 for (unsigned i = 0; i != NumElts; ++i) {
30013 SDValue A = Amt->getOperand(i);
30014 if (A.isUndef()) {
30015 ShuffleMask.push_back(SM_SentinelUndef);
30016 continue;
30018 if (!Amt1 || Amt1 == A) {
30019 ShuffleMask.push_back(i);
30020 Amt1 = A;
30021 continue;
30023 if (!Amt2 || Amt2 == A) {
30024 ShuffleMask.push_back(i + NumElts);
30025 Amt2 = A;
30026 continue;
30028 break;
30031 // Only perform this blend if we can perform it without loading a mask.
30032 if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
30033 (VT != MVT::v16i16 ||
30034 is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
30035 (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
30036 canWidenShuffleElements(ShuffleMask))) {
30037 auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
30038 auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
30039 if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
30040 Cst2->getAPIntValue().ult(EltSizeInBits)) {
30041 SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
30042 Cst1->getZExtValue(), DAG);
30043 SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
30044 Cst2->getZExtValue(), DAG);
30045 return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
30050 // Constant ISD::SRA/SRL/SHL can be performed efficiently on vXiN vectors by
30051 // using vYiM vector operations where X*N == Y*M and M > N.
30052 if (ConstantAmt &&
30053 (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8 ||
30054 VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16) &&
30055 !Subtarget.hasXOP()) {
30056 MVT NarrowScalarVT = VT.getScalarType();
30057 int NumElts = VT.getVectorNumElements();
30058 // We can do this extra fast if each pair of narrow elements is shifted by
30059 // the same amount by doing this SWAR style: use a shift to move the valid
30060 // bits to the right position, mask out any bits which crossed from one
30061 // element to the other.
30062 // This optimized lowering is only valid if the elements in a pair can
30063 // be treated identically.
30064 SmallVector<SDValue, 32> AmtWideElts;
30065 AmtWideElts.reserve(NumElts);
30066 for (int I = 0; I != NumElts; ++I) {
30067 AmtWideElts.push_back(Amt.getOperand(I));
30069 SmallVector<SDValue, 32> TmpAmtWideElts;
30070 int WideEltSizeInBits = EltSizeInBits;
30071 while (WideEltSizeInBits < 32) {
30072 // AVX1 does not have psrlvd, etc. which makes interesting 32-bit shifts
30073 // unprofitable.
30074 if (WideEltSizeInBits >= 16 && !Subtarget.hasAVX2()) {
30075 break;
30077 TmpAmtWideElts.resize(AmtWideElts.size() / 2);
30078 bool SameShifts = true;
30079 for (unsigned SrcI = 0, E = AmtWideElts.size(); SrcI != E; SrcI += 2) {
30080 unsigned DstI = SrcI / 2;
30081 // Both elements are undef? Make a note and keep going.
30082 if (AmtWideElts[SrcI].isUndef() && AmtWideElts[SrcI + 1].isUndef()) {
30083 TmpAmtWideElts[DstI] = AmtWideElts[SrcI];
30084 continue;
30086 // Even element is undef? We will shift it by the same shift amount as
30087 // the odd element.
30088 if (AmtWideElts[SrcI].isUndef()) {
30089 TmpAmtWideElts[DstI] = AmtWideElts[SrcI + 1];
30090 continue;
30092 // Odd element is undef? We will shift it by the same shift amount as
30093 // the even element.
30094 if (AmtWideElts[SrcI + 1].isUndef()) {
30095 TmpAmtWideElts[DstI] = AmtWideElts[SrcI];
30096 continue;
30098 // Both elements are equal.
30099 if (AmtWideElts[SrcI].getNode()->getAsAPIntVal() ==
30100 AmtWideElts[SrcI + 1].getNode()->getAsAPIntVal()) {
30101 TmpAmtWideElts[DstI] = AmtWideElts[SrcI];
30102 continue;
30104 // One of the provisional wide elements will not have the same shift
30105 // amount. Let's bail.
30106 SameShifts = false;
30107 break;
30109 if (!SameShifts) {
30110 break;
30112 WideEltSizeInBits *= 2;
30113 std::swap(TmpAmtWideElts, AmtWideElts);
30115 APInt APIntShiftAmt;
30116 bool IsConstantSplat = X86::isConstantSplat(Amt, APIntShiftAmt);
30117 bool Profitable = WidenShift;
30118 // AVX512BW brings support for vpsllvw.
30119 if (WideEltSizeInBits * AmtWideElts.size() >= 512 &&
30120 WideEltSizeInBits < 32 && !Subtarget.hasBWI()) {
30121 Profitable = false;
30123 // Leave AVX512 uniform arithmetic shifts alone, they can be implemented
30124 // fairly cheaply in other ways.
30125 if (WideEltSizeInBits * AmtWideElts.size() >= 512 && IsConstantSplat) {
30126 Profitable = false;
30128 // Leave it up to GFNI if we have it around.
30129 // TODO: gf2p8affine is usually higher latency and more port restricted. It
30130 // is probably a win to use other strategies in some cases.
30131 if (EltSizeInBits == 8 && Subtarget.hasGFNI()) {
30132 Profitable = false;
30135 // AVX1 does not have vpand which makes our masking impractical. It does
30136 // have vandps but that is an FP instruction and crossing FP<->int typically
30137 // has some cost.
30138 if (WideEltSizeInBits * AmtWideElts.size() >= 256 &&
30139 (WideEltSizeInBits < 32 || IsConstantSplat) && !Subtarget.hasAVX2()) {
30140 Profitable = false;
30142 int WideNumElts = AmtWideElts.size();
30143 // We are only dealing with identical pairs.
30144 if (Profitable && WideNumElts != NumElts) {
30145 MVT WideScalarVT = MVT::getIntegerVT(WideEltSizeInBits);
30146 MVT WideVT = MVT::getVectorVT(WideScalarVT, WideNumElts);
30147 // Cast the operand to vXiM.
30148 SDValue RWide = DAG.getBitcast(WideVT, R);
30149 // Create our new vector of shift amounts.
30150 SDValue AmtWide = DAG.getBuildVector(
30151 MVT::getVectorVT(NarrowScalarVT, WideNumElts), dl, AmtWideElts);
30152 AmtWide = DAG.getZExtOrTrunc(AmtWide, dl, WideVT);
30153 // Perform the actual shift.
30154 unsigned LogicalOpc = Opc == ISD::SRA ? (unsigned)ISD::SRL : Opc;
30155 SDValue ShiftedR = DAG.getNode(LogicalOpc, dl, WideVT, RWide, AmtWide);
30156 // Now we need to construct a mask which will "drop" bits that get
30157 // shifted past the LSB/MSB. For a logical shift left, it will look
30158 // like:
30159 // FullMask = (1 << EltSizeInBits) - 1
30160 // Mask = FullMask << Amt
30162 // This masking ensures that bits cannot migrate from one narrow lane to
30163 // another. The construction of this mask will be constant folded.
30164 // The mask for a logical right shift is nearly identical, the only
30165 // difference is that the all ones mask is shifted right instead of left.
30166 SDValue CstFullMask = DAG.getAllOnesConstant(dl, NarrowScalarVT);
30167 SDValue SplatFullMask = DAG.getSplat(VT, dl, CstFullMask);
30168 SDValue Mask = DAG.getNode(LogicalOpc, dl, VT, SplatFullMask, Amt);
30169 Mask = DAG.getBitcast(WideVT, Mask);
30170 // Finally, we mask the shifted vector with the SWAR mask.
30171 SDValue Masked = DAG.getNode(ISD::AND, dl, WideVT, ShiftedR, Mask);
30172 Masked = DAG.getBitcast(VT, Masked);
30173 if (Opc != ISD::SRA) {
30174 // Logical shifts are complete at this point.
30175 return Masked;
30177 // At this point, we have done a *logical* shift right. We now need to
30178 // sign extend the result so that we get behavior equivalent to an
30179 // arithmetic shift right. Post-shifting by AmtWide, our narrow elements
30180 // are `EltSizeInBits-AmtWide` bits wide.
30182 // To convert our `EltSizeInBits-AmtWide` bit unsigned numbers to signed
30183 // numbers as wide as `EltSizeInBits`, we need to replicate the bit at
30184 // position `EltSizeInBits-AmtWide` into the MSBs of each narrow lane. We
30185 // can use the following trick to accomplish this:
30186 // SignBitMask = 1 << (EltSizeInBits-AmtWide-1)
30187 // (Masked ^ SignBitMask) - SignBitMask
30189 // When the sign bit is already clear, this will compute:
30190 // Masked + SignBitMask - SignBitMask
30192 // This is equal to Masked which is what we want: the sign bit was clear
30193 // so sign extending should be a no-op.
30195 // When the sign bit is set, this will compute:
30196 // Masked - SignBitmask - SignBitMask
30198 // This is equal to Masked - 2*SignBitMask which will correctly sign
30199 // extend our result.
30200 SDValue CstHighBit =
30201 DAG.getConstant(1ULL << (EltSizeInBits - 1), dl, NarrowScalarVT);
30202 SDValue SplatHighBit = DAG.getSplat(VT, dl, CstHighBit);
30203 // This does not induce recursion, all operands are constants.
30204 SDValue SignBitMask = DAG.getNode(LogicalOpc, dl, VT, SplatHighBit, Amt);
30205 SDValue FlippedSignBit =
30206 DAG.getNode(ISD::XOR, dl, VT, Masked, SignBitMask);
30207 SDValue Subtraction =
30208 DAG.getNode(ISD::SUB, dl, VT, FlippedSignBit, SignBitMask);
30209 return Subtraction;
30213 // If possible, lower this packed shift into a vector multiply instead of
30214 // expanding it into a sequence of scalar shifts.
30215 // For v32i8 cases, it might be quicker to split/extend to vXi16 shifts.
30216 if (Opc == ISD::SHL && !(VT == MVT::v32i8 && (Subtarget.hasXOP() ||
30217 Subtarget.canExtendTo512BW())))
30218 if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
30219 return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
30221 // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
30222 // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
30223 if (Opc == ISD::SRL && ConstantAmt &&
30224 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
30225 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
30226 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
30227 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
30228 SDValue Zero = DAG.getConstant(0, dl, VT);
30229 SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
30230 SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
30231 return DAG.getSelect(dl, VT, ZAmt, R, Res);
30235 // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
30236 // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
30237 // TODO: Special case handling for shift by 0/1, really we can afford either
30238 // of these cases in pre-SSE41/XOP/AVX512 but not both.
30239 if (Opc == ISD::SRA && ConstantAmt &&
30240 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
30241 ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
30242 !Subtarget.hasAVX512()) ||
30243 DAG.isKnownNeverZero(Amt))) {
30244 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
30245 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
30246 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
30247 SDValue Amt0 =
30248 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
30249 SDValue Amt1 =
30250 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
30251 SDValue Sra1 =
30252 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
30253 SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
30254 Res = DAG.getSelect(dl, VT, Amt0, R, Res);
30255 return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
30259 // v4i32 Non Uniform Shifts.
30260 // If the shift amount is constant we can shift each lane using the SSE2
30261 // immediate shifts, else we need to zero-extend each lane to the lower i64
30262 // and shift using the SSE2 variable shifts.
30263 // The separate results can then be blended together.
30264 if (VT == MVT::v4i32) {
30265 SDValue Amt0, Amt1, Amt2, Amt3;
30266 if (ConstantAmt) {
30267 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
30268 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
30269 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
30270 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
30271 } else {
30272 // The SSE2 shifts use the lower i64 as the same shift amount for
30273 // all lanes and the upper i64 is ignored. On AVX we're better off
30274 // just zero-extending, but for SSE just duplicating the top 16-bits is
30275 // cheaper and has the same effect for out of range values.
30276 if (Subtarget.hasAVX()) {
30277 SDValue Z = DAG.getConstant(0, dl, VT);
30278 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
30279 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
30280 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
30281 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
30282 } else {
30283 SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
30284 SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
30285 {4, 5, 6, 7, -1, -1, -1, -1});
30286 SDValue Msk02 = getV4X86ShuffleImm8ForMask({0, 1, 1, 1}, dl, DAG);
30287 SDValue Msk13 = getV4X86ShuffleImm8ForMask({2, 3, 3, 3}, dl, DAG);
30288 Amt0 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk02);
30289 Amt1 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk13);
30290 Amt2 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk02);
30291 Amt3 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk13);
30295 unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
30296 SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
30297 SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
30298 SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
30299 SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
30301 // Merge the shifted lane results optimally with/without PBLENDW.
30302 // TODO - ideally shuffle combining would handle this.
30303 if (Subtarget.hasSSE41()) {
30304 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
30305 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
30306 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
30308 SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
30309 SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
30310 return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
30313 // If we're shifting (per-lane) uniform vXi8 constants, we can use PSHUFB to
30314 // look up the pre-computed shift values.
30315 if ((VT == MVT::v16i8 && Subtarget.hasSSSE3()) ||
30316 (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
30317 (VT == MVT::v64i8 && Subtarget.hasBWI())) {
30318 unsigned NumElts = VT.getVectorNumElements();
30319 unsigned NumLanes = VT.getSizeInBits() / 128u;
30320 unsigned NumEltsPerLane = NumElts / NumLanes;
30321 SmallVector<APInt, 16> LUT;
30322 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
30323 unsigned LoElt = Lane * NumEltsPerLane;
30324 APInt EltMask = APInt::getBitsSet(NumElts, LoElt, LoElt + NumEltsPerLane);
30325 KnownBits KnownLane = DAG.computeKnownBits(R, EltMask);
30326 if (!KnownLane.isConstant())
30327 break;
30328 const APInt &LaneSplat = KnownLane.getConstant();
30329 for (unsigned I = 0; I != 8; ++I) {
30330 if (Opc == ISD::SHL)
30331 LUT.push_back(LaneSplat.shl(I));
30332 else if (Opc == ISD::SRL)
30333 LUT.push_back(LaneSplat.lshr(I));
30334 else if (Opc == ISD::SRA)
30335 LUT.push_back(LaneSplat.ashr(I));
30337 LUT.append(8, APInt::getZero(8));
30339 if (LUT.size() == NumElts) {
30340 APInt Undefs = APInt::getSplat(NumElts, APInt(16, 0xFF00));
30341 SDValue Mask = getConstVector(LUT, Undefs, VT, DAG, dl);
30342 return DAG.getNode(X86ISD::PSHUFB, dl, VT, Mask, Amt);
30346 // It's worth extending once and using the vXi16/vXi32 shifts for smaller
30347 // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
30348 // make the existing SSE solution better.
30349 // NOTE: We honor prefered vector width before promoting to 512-bits.
30350 if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
30351 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
30352 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
30353 (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
30354 (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
30355 assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
30356 "Unexpected vector type");
30357 MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
30358 MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
30359 unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
30360 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
30361 Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
30362 return DAG.getNode(ISD::TRUNCATE, dl, VT,
30363 DAG.getNode(Opc, dl, ExtVT, R, Amt));
30366 // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
30367 // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
30368 if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
30369 (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
30370 (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
30371 !Subtarget.hasXOP()) {
30372 int NumElts = VT.getVectorNumElements();
30373 MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
30374 SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
30376 // Extend constant shift amount to vXi16 (it doesn't matter if the type
30377 // isn't legal).
30378 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
30379 Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
30380 Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
30381 Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
30382 assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
30383 "Constant build vector expected");
30385 if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
30386 bool IsSigned = Opc == ISD::SRA;
30387 R = DAG.getExtOrTrunc(IsSigned, R, dl, ExVT);
30388 R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
30389 R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
30390 return DAG.getZExtOrTrunc(R, dl, VT);
30393 SmallVector<SDValue, 16> LoAmt, HiAmt;
30394 for (int i = 0; i != NumElts; i += 16) {
30395 for (int j = 0; j != 8; ++j) {
30396 LoAmt.push_back(Amt.getOperand(i + j));
30397 HiAmt.push_back(Amt.getOperand(i + j + 8));
30401 SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
30402 SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
30404 SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
30405 SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
30406 LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
30407 HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
30408 LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
30409 HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
30410 LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
30411 HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
30412 return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
30415 if (VT == MVT::v16i8 ||
30416 (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
30417 (VT == MVT::v64i8 && Subtarget.hasBWI())) {
30418 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
30420 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
30421 if (VT.is512BitVector()) {
30422 // On AVX512BW targets we make use of the fact that VSELECT lowers
30423 // to a masked blend which selects bytes based just on the sign bit
30424 // extracted to a mask.
30425 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
30426 V0 = DAG.getBitcast(VT, V0);
30427 V1 = DAG.getBitcast(VT, V1);
30428 Sel = DAG.getBitcast(VT, Sel);
30429 Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
30430 ISD::SETGT);
30431 return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
30432 } else if (Subtarget.hasSSE41()) {
30433 // On SSE41 targets we can use PBLENDVB which selects bytes based just
30434 // on the sign bit.
30435 V0 = DAG.getBitcast(VT, V0);
30436 V1 = DAG.getBitcast(VT, V1);
30437 Sel = DAG.getBitcast(VT, Sel);
30438 return DAG.getBitcast(SelVT,
30439 DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
30441 // On pre-SSE41 targets we test for the sign bit by comparing to
30442 // zero - a negative value will set all bits of the lanes to true
30443 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
30444 SDValue Z = DAG.getConstant(0, dl, SelVT);
30445 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
30446 return DAG.getSelect(dl, SelVT, C, V0, V1);
30449 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
30450 // We can safely do this using i16 shifts as we're only interested in
30451 // the 3 lower bits of each byte.
30452 Amt = DAG.getBitcast(ExtVT, Amt);
30453 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
30454 Amt = DAG.getBitcast(VT, Amt);
30456 if (Opc == ISD::SHL || Opc == ISD::SRL) {
30457 // r = VSELECT(r, shift(r, 4), a);
30458 SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
30459 R = SignBitSelect(VT, Amt, M, R);
30461 // a += a
30462 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30464 // r = VSELECT(r, shift(r, 2), a);
30465 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
30466 R = SignBitSelect(VT, Amt, M, R);
30468 // a += a
30469 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30471 // return VSELECT(r, shift(r, 1), a);
30472 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
30473 R = SignBitSelect(VT, Amt, M, R);
30474 return R;
30477 if (Opc == ISD::SRA) {
30478 // For SRA we need to unpack each byte to the higher byte of a i16 vector
30479 // so we can correctly sign extend. We don't care what happens to the
30480 // lower byte.
30481 SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
30482 SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
30483 SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
30484 SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
30485 ALo = DAG.getBitcast(ExtVT, ALo);
30486 AHi = DAG.getBitcast(ExtVT, AHi);
30487 RLo = DAG.getBitcast(ExtVT, RLo);
30488 RHi = DAG.getBitcast(ExtVT, RHi);
30490 // r = VSELECT(r, shift(r, 4), a);
30491 SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
30492 SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
30493 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30494 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30496 // a += a
30497 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
30498 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
30500 // r = VSELECT(r, shift(r, 2), a);
30501 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
30502 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
30503 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30504 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30506 // a += a
30507 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
30508 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
30510 // r = VSELECT(r, shift(r, 1), a);
30511 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
30512 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
30513 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
30514 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
30516 // Logical shift the result back to the lower byte, leaving a zero upper
30517 // byte meaning that we can safely pack with PACKUSWB.
30518 RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
30519 RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
30520 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
30524 if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
30525 MVT ExtVT = MVT::v8i32;
30526 SDValue Z = DAG.getConstant(0, dl, VT);
30527 SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
30528 SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
30529 SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
30530 SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
30531 ALo = DAG.getBitcast(ExtVT, ALo);
30532 AHi = DAG.getBitcast(ExtVT, AHi);
30533 RLo = DAG.getBitcast(ExtVT, RLo);
30534 RHi = DAG.getBitcast(ExtVT, RHi);
30535 SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
30536 SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
30537 Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
30538 Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
30539 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
30542 if (VT == MVT::v8i16) {
30543 // If we have a constant shift amount, the non-SSE41 path is best as
30544 // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
30545 bool UseSSE41 = Subtarget.hasSSE41() &&
30546 !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30548 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
30549 // On SSE41 targets we can use PBLENDVB which selects bytes based just on
30550 // the sign bit.
30551 if (UseSSE41) {
30552 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
30553 V0 = DAG.getBitcast(ExtVT, V0);
30554 V1 = DAG.getBitcast(ExtVT, V1);
30555 Sel = DAG.getBitcast(ExtVT, Sel);
30556 return DAG.getBitcast(
30557 VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
30559 // On pre-SSE41 targets we splat the sign bit - a negative value will
30560 // set all bits of the lanes to true and VSELECT uses that in
30561 // its OR(AND(V0,C),AND(V1,~C)) lowering.
30562 SDValue C =
30563 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
30564 return DAG.getSelect(dl, VT, C, V0, V1);
30567 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
30568 if (UseSSE41) {
30569 // On SSE41 targets we need to replicate the shift mask in both
30570 // bytes for PBLENDVB.
30571 Amt = DAG.getNode(
30572 ISD::OR, dl, VT,
30573 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
30574 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
30575 } else {
30576 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
30579 // r = VSELECT(r, shift(r, 8), a);
30580 SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
30581 R = SignBitSelect(Amt, M, R);
30583 // a += a
30584 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30586 // r = VSELECT(r, shift(r, 4), a);
30587 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
30588 R = SignBitSelect(Amt, M, R);
30590 // a += a
30591 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30593 // r = VSELECT(r, shift(r, 2), a);
30594 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
30595 R = SignBitSelect(Amt, M, R);
30597 // a += a
30598 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
30600 // return VSELECT(r, shift(r, 1), a);
30601 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
30602 R = SignBitSelect(Amt, M, R);
30603 return R;
30606 // Decompose 256-bit shifts into 128-bit shifts.
30607 if (VT.is256BitVector())
30608 return splitVectorIntBinary(Op, DAG, dl);
30610 if (VT == MVT::v32i16 || VT == MVT::v64i8)
30611 return splitVectorIntBinary(Op, DAG, dl);
30613 return SDValue();
30616 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
30617 SelectionDAG &DAG) {
30618 MVT VT = Op.getSimpleValueType();
30619 assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
30620 "Unexpected funnel shift opcode!");
30622 SDLoc DL(Op);
30623 SDValue Op0 = Op.getOperand(0);
30624 SDValue Op1 = Op.getOperand(1);
30625 SDValue Amt = Op.getOperand(2);
30626 unsigned EltSizeInBits = VT.getScalarSizeInBits();
30627 bool IsFSHR = Op.getOpcode() == ISD::FSHR;
30629 if (VT.isVector()) {
30630 APInt APIntShiftAmt;
30631 bool IsCstSplat = X86::isConstantSplat(Amt, APIntShiftAmt);
30632 unsigned NumElts = VT.getVectorNumElements();
30634 if (Subtarget.hasVBMI2() && EltSizeInBits > 8) {
30635 if (IsFSHR)
30636 std::swap(Op0, Op1);
30638 if (IsCstSplat) {
30639 uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
30640 SDValue Imm = DAG.getTargetConstant(ShiftAmt, DL, MVT::i8);
30641 return getAVX512Node(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
30642 {Op0, Op1, Imm}, DAG, Subtarget);
30644 return getAVX512Node(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
30645 {Op0, Op1, Amt}, DAG, Subtarget);
30647 assert((VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8 ||
30648 VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16 ||
30649 VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) &&
30650 "Unexpected funnel shift type!");
30652 // fshl(x,y,z) -> unpack(y,x) << (z & (bw-1))) >> bw.
30653 // fshr(x,y,z) -> unpack(y,x) >> (z & (bw-1))).
30654 if (IsCstSplat) {
30655 // TODO: Can't use generic expansion as UNDEF amt elements can be
30656 // converted to other values when folded to shift amounts, losing the
30657 // splat.
30658 uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
30659 uint64_t ShXAmt = IsFSHR ? (EltSizeInBits - ShiftAmt) : ShiftAmt;
30660 uint64_t ShYAmt = IsFSHR ? ShiftAmt : (EltSizeInBits - ShiftAmt);
30661 assert((ShXAmt + ShYAmt) == EltSizeInBits && "Illegal funnel shift");
30662 MVT WideVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
30664 if (EltSizeInBits == 8 &&
30665 (Subtarget.hasXOP() ||
30666 (useVPTERNLOG(Subtarget, VT) &&
30667 supportedVectorShiftWithImm(WideVT, Subtarget, ISD::SHL)))) {
30668 // For vXi8 cases on Subtargets that can perform VPCMOV/VPTERNLOG
30669 // bit-select - lower using vXi16 shifts and then perform the bitmask at
30670 // the original vector width to handle cases where we split.
30671 APInt MaskX = APInt::getHighBitsSet(8, 8 - ShXAmt);
30672 APInt MaskY = APInt::getLowBitsSet(8, 8 - ShYAmt);
30673 SDValue ShX =
30674 DAG.getNode(ISD::SHL, DL, WideVT, DAG.getBitcast(WideVT, Op0),
30675 DAG.getShiftAmountConstant(ShXAmt, WideVT, DL));
30676 SDValue ShY =
30677 DAG.getNode(ISD::SRL, DL, WideVT, DAG.getBitcast(WideVT, Op1),
30678 DAG.getShiftAmountConstant(ShYAmt, WideVT, DL));
30679 ShX = DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, ShX),
30680 DAG.getConstant(MaskX, DL, VT));
30681 ShY = DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, ShY),
30682 DAG.getConstant(MaskY, DL, VT));
30683 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
30686 SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, Op0,
30687 DAG.getShiftAmountConstant(ShXAmt, VT, DL));
30688 SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Op1,
30689 DAG.getShiftAmountConstant(ShYAmt, VT, DL));
30690 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
30693 SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
30694 SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30695 bool IsCst = ISD::isBuildVectorOfConstantSDNodes(AmtMod.getNode());
30697 // Constant vXi16 funnel shifts can be efficiently handled by default.
30698 if (IsCst && EltSizeInBits == 16)
30699 return SDValue();
30701 unsigned ShiftOpc = IsFSHR ? ISD::SRL : ISD::SHL;
30702 MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
30703 MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
30705 // Split 256-bit integers on XOP/pre-AVX2 targets.
30706 // Split 512-bit integers on non 512-bit BWI targets.
30707 if ((VT.is256BitVector() && ((Subtarget.hasXOP() && EltSizeInBits < 16) ||
30708 !Subtarget.hasAVX2())) ||
30709 (VT.is512BitVector() && !Subtarget.useBWIRegs() &&
30710 EltSizeInBits < 32)) {
30711 // Pre-mask the amount modulo using the wider vector.
30712 Op = DAG.getNode(Op.getOpcode(), DL, VT, Op0, Op1, AmtMod);
30713 return splitVectorOp(Op, DAG, DL);
30716 // Attempt to fold scalar shift as unpack(y,x) << zext(splat(z))
30717 if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, ShiftOpc)) {
30718 int ScalarAmtIdx = -1;
30719 if (SDValue ScalarAmt = DAG.getSplatSourceVector(AmtMod, ScalarAmtIdx)) {
30720 // Uniform vXi16 funnel shifts can be efficiently handled by default.
30721 if (EltSizeInBits == 16)
30722 return SDValue();
30724 SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
30725 SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
30726 Lo = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Lo, ScalarAmt,
30727 ScalarAmtIdx, Subtarget, DAG);
30728 Hi = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Hi, ScalarAmt,
30729 ScalarAmtIdx, Subtarget, DAG);
30730 return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
30734 MVT WideSVT = MVT::getIntegerVT(
30735 std::min<unsigned>(EltSizeInBits * 2, Subtarget.hasBWI() ? 16 : 32));
30736 MVT WideVT = MVT::getVectorVT(WideSVT, NumElts);
30738 // If per-element shifts are legal, fallback to generic expansion.
30739 if (supportedVectorVarShift(VT, Subtarget, ShiftOpc) || Subtarget.hasXOP())
30740 return SDValue();
30742 // Attempt to fold as:
30743 // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
30744 // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
30745 if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
30746 supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
30747 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Op0);
30748 Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Op1);
30749 AmtMod = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
30750 Op0 = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, Op0,
30751 EltSizeInBits, DAG);
30752 SDValue Res = DAG.getNode(ISD::OR, DL, WideVT, Op0, Op1);
30753 Res = DAG.getNode(ShiftOpc, DL, WideVT, Res, AmtMod);
30754 if (!IsFSHR)
30755 Res = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, Res,
30756 EltSizeInBits, DAG);
30757 return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
30760 // Attempt to fold per-element (ExtVT) shift as unpack(y,x) << zext(z)
30761 if (((IsCst || !Subtarget.hasAVX512()) && !IsFSHR && EltSizeInBits <= 16) ||
30762 supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
30763 SDValue Z = DAG.getConstant(0, DL, VT);
30764 SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
30765 SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
30766 SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
30767 SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
30768 SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
30769 SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
30770 return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
30773 // Fallback to generic expansion.
30774 return SDValue();
30776 assert(
30777 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
30778 "Unexpected funnel shift type!");
30780 // Expand slow SHLD/SHRD cases if we are not optimizing for size.
30781 bool OptForSize = DAG.shouldOptForSize();
30782 bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
30784 // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
30785 // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
30786 if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
30787 !isa<ConstantSDNode>(Amt)) {
30788 SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
30789 SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
30790 Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
30791 Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
30792 Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
30793 SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
30794 Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
30795 if (IsFSHR) {
30796 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
30797 } else {
30798 Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
30799 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
30801 return DAG.getZExtOrTrunc(Res, DL, VT);
30804 if (VT == MVT::i8 || ExpandFunnel)
30805 return SDValue();
30807 // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
30808 if (VT == MVT::i16) {
30809 Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
30810 DAG.getConstant(15, DL, Amt.getValueType()));
30811 unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
30812 return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
30815 return Op;
30818 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
30819 SelectionDAG &DAG) {
30820 MVT VT = Op.getSimpleValueType();
30821 assert(VT.isVector() && "Custom lowering only for vector rotates!");
30823 SDLoc DL(Op);
30824 SDValue R = Op.getOperand(0);
30825 SDValue Amt = Op.getOperand(1);
30826 unsigned Opcode = Op.getOpcode();
30827 unsigned EltSizeInBits = VT.getScalarSizeInBits();
30828 int NumElts = VT.getVectorNumElements();
30829 bool IsROTL = Opcode == ISD::ROTL;
30831 // Check for constant splat rotation amount.
30832 APInt CstSplatValue;
30833 bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
30835 // Check for splat rotate by zero.
30836 if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
30837 return R;
30839 // AVX512 implicitly uses modulo rotation amounts.
30840 if ((Subtarget.hasVLX() ||
30841 (Subtarget.hasAVX512() && Subtarget.hasEVEX512())) &&
30842 32 <= EltSizeInBits) {
30843 // Attempt to rotate by immediate.
30844 if (IsCstSplat) {
30845 unsigned RotOpc = IsROTL ? X86ISD::VROTLI : X86ISD::VROTRI;
30846 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30847 return DAG.getNode(RotOpc, DL, VT, R,
30848 DAG.getTargetConstant(RotAmt, DL, MVT::i8));
30851 // Else, fall-back on VPROLV/VPRORV.
30852 return Op;
30855 // AVX512 VBMI2 vXi16 - lower to funnel shifts.
30856 if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
30857 unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
30858 return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
30861 SDValue Z = DAG.getConstant(0, DL, VT);
30863 if (!IsROTL) {
30864 // If the ISD::ROTR amount is constant, we're always better converting to
30865 // ISD::ROTL.
30866 if (SDValue NegAmt = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {Z, Amt}))
30867 return DAG.getNode(ISD::ROTL, DL, VT, R, NegAmt);
30869 // XOP targets always prefers ISD::ROTL.
30870 if (Subtarget.hasXOP())
30871 return DAG.getNode(ISD::ROTL, DL, VT, R,
30872 DAG.getNode(ISD::SUB, DL, VT, Z, Amt));
30875 // Attempt to use GFNI gf2p8affine to rotate vXi8 by an uniform constant.
30876 if (IsCstSplat && Subtarget.hasGFNI() && VT.getScalarType() == MVT::i8 &&
30877 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
30878 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30879 SDValue Mask = getGFNICtrlMask(Opcode, DAG, DL, VT, RotAmt);
30880 return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, R, Mask,
30881 DAG.getTargetConstant(0, DL, MVT::i8));
30884 // Split 256-bit integers on XOP/pre-AVX2 targets.
30885 if (VT.is256BitVector() && (Subtarget.hasXOP() || !Subtarget.hasAVX2()))
30886 return splitVectorIntBinary(Op, DAG, DL);
30888 // XOP has 128-bit vector variable + immediate rotates.
30889 // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
30890 // XOP implicitly uses modulo rotation amounts.
30891 if (Subtarget.hasXOP()) {
30892 assert(IsROTL && "Only ROTL expected");
30893 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
30895 // Attempt to rotate by immediate.
30896 if (IsCstSplat) {
30897 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30898 return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
30899 DAG.getTargetConstant(RotAmt, DL, MVT::i8));
30902 // Use general rotate by variable (per-element).
30903 return Op;
30906 // Rotate by an uniform constant - expand back to shifts.
30907 // TODO: Can't use generic expansion as UNDEF amt elements can be converted
30908 // to other values when folded to shift amounts, losing the splat.
30909 if (IsCstSplat) {
30910 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
30911 uint64_t ShlAmt = IsROTL ? RotAmt : (EltSizeInBits - RotAmt);
30912 uint64_t SrlAmt = IsROTL ? (EltSizeInBits - RotAmt) : RotAmt;
30913 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, R,
30914 DAG.getShiftAmountConstant(ShlAmt, VT, DL));
30915 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, R,
30916 DAG.getShiftAmountConstant(SrlAmt, VT, DL));
30917 return DAG.getNode(ISD::OR, DL, VT, Shl, Srl);
30920 // Split 512-bit integers on non 512-bit BWI targets.
30921 if (VT.is512BitVector() && !Subtarget.useBWIRegs())
30922 return splitVectorIntBinary(Op, DAG, DL);
30924 assert(
30925 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
30926 ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
30927 Subtarget.hasAVX2()) ||
30928 ((VT == MVT::v32i16 || VT == MVT::v64i8) && Subtarget.useBWIRegs())) &&
30929 "Only vXi32/vXi16/vXi8 vector rotates supported");
30931 MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
30932 MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
30934 SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
30935 SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30937 // Attempt to fold as unpack(x,x) << zext(splat(y)):
30938 // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
30939 // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
30940 if (EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) {
30941 int BaseRotAmtIdx = -1;
30942 if (SDValue BaseRotAmt = DAG.getSplatSourceVector(AmtMod, BaseRotAmtIdx)) {
30943 if (EltSizeInBits == 16 && Subtarget.hasSSE41()) {
30944 unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
30945 return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
30947 unsigned ShiftX86Opc = IsROTL ? X86ISD::VSHLI : X86ISD::VSRLI;
30948 SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
30949 SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
30950 Lo = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Lo, BaseRotAmt,
30951 BaseRotAmtIdx, Subtarget, DAG);
30952 Hi = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Hi, BaseRotAmt,
30953 BaseRotAmtIdx, Subtarget, DAG);
30954 return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
30958 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
30959 unsigned ShiftOpc = IsROTL ? ISD::SHL : ISD::SRL;
30961 // Attempt to fold as unpack(x,x) << zext(y):
30962 // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
30963 // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
30964 // Const vXi16/vXi32 are excluded in favor of MUL-based lowering.
30965 if (!(ConstantAmt && EltSizeInBits != 8) &&
30966 !supportedVectorVarShift(VT, Subtarget, ShiftOpc) &&
30967 (ConstantAmt || supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc))) {
30968 SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
30969 SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
30970 SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
30971 SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
30972 SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
30973 SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
30974 return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
30977 // v16i8/v32i8/v64i8: Split rotation into rot4/rot2/rot1 stages and select by
30978 // the amount bit.
30979 // TODO: We're doing nothing here that we couldn't do for funnel shifts.
30980 if (EltSizeInBits == 8) {
30981 MVT WideVT =
30982 MVT::getVectorVT(Subtarget.hasBWI() ? MVT::i16 : MVT::i32, NumElts);
30984 // Attempt to fold as:
30985 // rotl(x,y) -> (((aext(x) << bw) | zext(x)) << (y & (bw-1))) >> bw.
30986 // rotr(x,y) -> (((aext(x) << bw) | zext(x)) >> (y & (bw-1))).
30987 if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
30988 supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
30989 // If we're rotating by constant, just use default promotion.
30990 if (ConstantAmt)
30991 return SDValue();
30992 // See if we can perform this by widening to vXi16 or vXi32.
30993 R = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, R);
30994 R = DAG.getNode(
30995 ISD::OR, DL, WideVT, R,
30996 getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, R, 8, DAG));
30997 Amt = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
30998 R = DAG.getNode(ShiftOpc, DL, WideVT, R, Amt);
30999 if (IsROTL)
31000 R = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, R, 8, DAG);
31001 return DAG.getNode(ISD::TRUNCATE, DL, VT, R);
31004 // We don't need ModuloAmt here as we just peek at individual bits.
31005 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
31006 if (Subtarget.hasSSE41()) {
31007 // On SSE41 targets we can use PBLENDVB which selects bytes based just
31008 // on the sign bit.
31009 V0 = DAG.getBitcast(VT, V0);
31010 V1 = DAG.getBitcast(VT, V1);
31011 Sel = DAG.getBitcast(VT, Sel);
31012 return DAG.getBitcast(SelVT,
31013 DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
31015 // On pre-SSE41 targets we test for the sign bit by comparing to
31016 // zero - a negative value will set all bits of the lanes to true
31017 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
31018 SDValue Z = DAG.getConstant(0, DL, SelVT);
31019 SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
31020 return DAG.getSelect(DL, SelVT, C, V0, V1);
31023 // ISD::ROTR is currently only profitable on AVX512 targets with VPTERNLOG.
31024 if (!IsROTL && !useVPTERNLOG(Subtarget, VT)) {
31025 Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
31026 IsROTL = true;
31029 unsigned ShiftLHS = IsROTL ? ISD::SHL : ISD::SRL;
31030 unsigned ShiftRHS = IsROTL ? ISD::SRL : ISD::SHL;
31032 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
31033 // We can safely do this using i16 shifts as we're only interested in
31034 // the 3 lower bits of each byte.
31035 Amt = DAG.getBitcast(ExtVT, Amt);
31036 Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
31037 Amt = DAG.getBitcast(VT, Amt);
31039 // r = VSELECT(r, rot(r, 4), a);
31040 SDValue M;
31041 M = DAG.getNode(
31042 ISD::OR, DL, VT,
31043 DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(4, DL, VT)),
31044 DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(4, DL, VT)));
31045 R = SignBitSelect(VT, Amt, M, R);
31047 // a += a
31048 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
31050 // r = VSELECT(r, rot(r, 2), a);
31051 M = DAG.getNode(
31052 ISD::OR, DL, VT,
31053 DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(2, DL, VT)),
31054 DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(6, DL, VT)));
31055 R = SignBitSelect(VT, Amt, M, R);
31057 // a += a
31058 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
31060 // return VSELECT(r, rot(r, 1), a);
31061 M = DAG.getNode(
31062 ISD::OR, DL, VT,
31063 DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(1, DL, VT)),
31064 DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(7, DL, VT)));
31065 return SignBitSelect(VT, Amt, M, R);
31068 bool IsSplatAmt = DAG.isSplatValue(Amt);
31069 bool LegalVarShifts = supportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
31070 supportedVectorVarShift(VT, Subtarget, ISD::SRL);
31072 // Fallback for splats + all supported variable shifts.
31073 // Fallback for non-constants AVX2 vXi16 as well.
31074 if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
31075 Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
31076 SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
31077 AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
31078 SDValue SHL = DAG.getNode(IsROTL ? ISD::SHL : ISD::SRL, DL, VT, R, Amt);
31079 SDValue SRL = DAG.getNode(IsROTL ? ISD::SRL : ISD::SHL, DL, VT, R, AmtR);
31080 return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
31083 // Everything below assumes ISD::ROTL.
31084 if (!IsROTL) {
31085 Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
31086 IsROTL = true;
31089 // ISD::ROT* uses modulo rotate amounts.
31090 Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
31092 assert(IsROTL && "Only ROTL supported");
31094 // As with shifts, attempt to convert the rotation amount to a multiplication
31095 // factor, fallback to general expansion.
31096 SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
31097 if (!Scale)
31098 return SDValue();
31100 // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
31101 if (EltSizeInBits == 16) {
31102 SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
31103 SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
31104 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
31107 // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
31108 // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
31109 // that can then be OR'd with the lower 32-bits.
31110 assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
31111 static const int OddMask[] = {1, -1, 3, -1};
31112 SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
31113 SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
31115 SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
31116 DAG.getBitcast(MVT::v2i64, R),
31117 DAG.getBitcast(MVT::v2i64, Scale));
31118 SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
31119 DAG.getBitcast(MVT::v2i64, R13),
31120 DAG.getBitcast(MVT::v2i64, Scale13));
31121 Res02 = DAG.getBitcast(VT, Res02);
31122 Res13 = DAG.getBitcast(VT, Res13);
31124 return DAG.getNode(ISD::OR, DL, VT,
31125 DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
31126 DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
31129 /// Returns true if the operand type is exactly twice the native width, and
31130 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
31131 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
31132 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
31133 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
31134 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
31136 if (OpWidth == 64)
31137 return Subtarget.canUseCMPXCHG8B() && !Subtarget.is64Bit();
31138 if (OpWidth == 128)
31139 return Subtarget.canUseCMPXCHG16B();
31141 return false;
31144 TargetLoweringBase::AtomicExpansionKind
31145 X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
31146 Type *MemType = SI->getValueOperand()->getType();
31148 if (!SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
31149 !Subtarget.useSoftFloat()) {
31150 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
31151 (Subtarget.hasSSE1() || Subtarget.hasX87()))
31152 return AtomicExpansionKind::None;
31154 if (MemType->getPrimitiveSizeInBits() == 128 && Subtarget.is64Bit() &&
31155 Subtarget.hasAVX())
31156 return AtomicExpansionKind::None;
31159 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::Expand
31160 : AtomicExpansionKind::None;
31163 // Note: this turns large loads into lock cmpxchg8b/16b.
31164 TargetLowering::AtomicExpansionKind
31165 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
31166 Type *MemType = LI->getType();
31168 if (!LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
31169 !Subtarget.useSoftFloat()) {
31170 // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
31171 // can use movq to do the load. If we have X87 we can load into an 80-bit
31172 // X87 register and store it to a stack temporary.
31173 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
31174 (Subtarget.hasSSE1() || Subtarget.hasX87()))
31175 return AtomicExpansionKind::None;
31177 // If this is a 128-bit load with AVX, 128-bit SSE loads/stores are atomic.
31178 if (MemType->getPrimitiveSizeInBits() == 128 && Subtarget.is64Bit() &&
31179 Subtarget.hasAVX())
31180 return AtomicExpansionKind::None;
31183 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
31184 : AtomicExpansionKind::None;
31187 enum BitTestKind : unsigned {
31188 UndefBit,
31189 ConstantBit,
31190 NotConstantBit,
31191 ShiftBit,
31192 NotShiftBit
31195 static std::pair<Value *, BitTestKind> FindSingleBitChange(Value *V) {
31196 using namespace llvm::PatternMatch;
31197 BitTestKind BTK = UndefBit;
31198 if (auto *C = dyn_cast<ConstantInt>(V)) {
31199 // Check if V is a power of 2 or NOT power of 2.
31200 if (isPowerOf2_64(C->getZExtValue()))
31201 BTK = ConstantBit;
31202 else if (isPowerOf2_64((~C->getValue()).getZExtValue()))
31203 BTK = NotConstantBit;
31204 return {V, BTK};
31207 // Check if V is some power of 2 pattern known to be non-zero
31208 if (auto *I = dyn_cast<Instruction>(V)) {
31209 bool Not = false;
31210 // Check if we have a NOT
31211 Value *PeekI;
31212 if (match(I, m_Not(m_Value(PeekI))) ||
31213 match(I, m_Sub(m_AllOnes(), m_Value(PeekI)))) {
31214 Not = true;
31215 I = dyn_cast<Instruction>(PeekI);
31217 // If I is constant, it will fold and we can evaluate later. If its an
31218 // argument or something of that nature, we can't analyze.
31219 if (I == nullptr)
31220 return {nullptr, UndefBit};
31222 // We can only use 1 << X without more sophisticated analysis. C << X where
31223 // C is a power of 2 but not 1 can result in zero which cannot be translated
31224 // to bittest. Likewise any C >> X (either arith or logical) can be zero.
31225 if (I->getOpcode() == Instruction::Shl) {
31226 // Todo(1): The cmpxchg case is pretty costly so matching `BLSI(X)`, `X &
31227 // -X` and some other provable power of 2 patterns that we can use CTZ on
31228 // may be profitable.
31229 // Todo(2): It may be possible in some cases to prove that Shl(C, X) is
31230 // non-zero even where C != 1. Likewise LShr(C, X) and AShr(C, X) may also
31231 // be provably a non-zero power of 2.
31232 // Todo(3): ROTL and ROTR patterns on a power of 2 C should also be
31233 // transformable to bittest.
31234 auto *ShiftVal = dyn_cast<ConstantInt>(I->getOperand(0));
31235 if (!ShiftVal)
31236 return {nullptr, UndefBit};
31237 if (ShiftVal->equalsInt(1))
31238 BTK = Not ? NotShiftBit : ShiftBit;
31240 if (BTK == UndefBit)
31241 return {nullptr, UndefBit};
31243 Value *BitV = I->getOperand(1);
31245 // Read past a shiftmask instruction to find count
31246 Value *AndOp;
31247 uint64_t ShiftMask = I->getType()->getPrimitiveSizeInBits() - 1;
31248 if (match(BitV, m_c_And(m_Value(AndOp), m_SpecificInt(ShiftMask))))
31249 BitV = AndOp;
31251 return {BitV, BTK};
31254 return {nullptr, UndefBit};
31257 TargetLowering::AtomicExpansionKind
31258 X86TargetLowering::shouldExpandLogicAtomicRMWInIR(AtomicRMWInst *AI) const {
31259 using namespace llvm::PatternMatch;
31260 // If the atomicrmw's result isn't actually used, we can just add a "lock"
31261 // prefix to a normal instruction for these operations.
31262 if (AI->use_empty())
31263 return AtomicExpansionKind::None;
31265 if (AI->getOperation() == AtomicRMWInst::Xor) {
31266 // A ^ SignBit -> A + SignBit. This allows us to use `xadd` which is
31267 // preferable to both `cmpxchg` and `btc`.
31268 if (match(AI->getOperand(1), m_SignMask()))
31269 return AtomicExpansionKind::None;
31272 // If the atomicrmw's result is used by a single bit AND, we may use
31273 // bts/btr/btc instruction for these operations.
31274 // Note: InstCombinePass can cause a de-optimization here. It replaces the
31275 // SETCC(And(AtomicRMW(P, power_of_2), power_of_2)) with LShr and Xor
31276 // (depending on CC). This pattern can only use bts/btr/btc but we don't
31277 // detect it.
31278 Instruction *I = AI->user_back();
31279 auto BitChange = FindSingleBitChange(AI->getValOperand());
31280 if (BitChange.second == UndefBit || !AI->hasOneUse() ||
31281 I->getOpcode() != Instruction::And ||
31282 AI->getType()->getPrimitiveSizeInBits() == 8 ||
31283 AI->getParent() != I->getParent())
31284 return AtomicExpansionKind::CmpXChg;
31286 unsigned OtherIdx = I->getOperand(0) == AI ? 1 : 0;
31288 // This is a redundant AND, it should get cleaned up elsewhere.
31289 if (AI == I->getOperand(OtherIdx))
31290 return AtomicExpansionKind::CmpXChg;
31292 // The following instruction must be a AND single bit.
31293 if (BitChange.second == ConstantBit || BitChange.second == NotConstantBit) {
31294 auto *C1 = cast<ConstantInt>(AI->getValOperand());
31295 auto *C2 = dyn_cast<ConstantInt>(I->getOperand(OtherIdx));
31296 if (!C2 || !isPowerOf2_64(C2->getZExtValue())) {
31297 return AtomicExpansionKind::CmpXChg;
31299 if (AI->getOperation() == AtomicRMWInst::And) {
31300 return ~C1->getValue() == C2->getValue()
31301 ? AtomicExpansionKind::BitTestIntrinsic
31302 : AtomicExpansionKind::CmpXChg;
31304 return C1 == C2 ? AtomicExpansionKind::BitTestIntrinsic
31305 : AtomicExpansionKind::CmpXChg;
31308 assert(BitChange.second == ShiftBit || BitChange.second == NotShiftBit);
31310 auto BitTested = FindSingleBitChange(I->getOperand(OtherIdx));
31311 if (BitTested.second != ShiftBit && BitTested.second != NotShiftBit)
31312 return AtomicExpansionKind::CmpXChg;
31314 assert(BitChange.first != nullptr && BitTested.first != nullptr);
31316 // If shift amounts are not the same we can't use BitTestIntrinsic.
31317 if (BitChange.first != BitTested.first)
31318 return AtomicExpansionKind::CmpXChg;
31320 // If atomic AND need to be masking all be one bit and testing the one bit
31321 // unset in the mask.
31322 if (AI->getOperation() == AtomicRMWInst::And)
31323 return (BitChange.second == NotShiftBit && BitTested.second == ShiftBit)
31324 ? AtomicExpansionKind::BitTestIntrinsic
31325 : AtomicExpansionKind::CmpXChg;
31327 // If atomic XOR/OR need to be setting and testing the same bit.
31328 return (BitChange.second == ShiftBit && BitTested.second == ShiftBit)
31329 ? AtomicExpansionKind::BitTestIntrinsic
31330 : AtomicExpansionKind::CmpXChg;
31333 void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
31334 IRBuilder<> Builder(AI);
31335 Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
31336 Intrinsic::ID IID_C = Intrinsic::not_intrinsic;
31337 Intrinsic::ID IID_I = Intrinsic::not_intrinsic;
31338 switch (AI->getOperation()) {
31339 default:
31340 llvm_unreachable("Unknown atomic operation");
31341 case AtomicRMWInst::Or:
31342 IID_C = Intrinsic::x86_atomic_bts;
31343 IID_I = Intrinsic::x86_atomic_bts_rm;
31344 break;
31345 case AtomicRMWInst::Xor:
31346 IID_C = Intrinsic::x86_atomic_btc;
31347 IID_I = Intrinsic::x86_atomic_btc_rm;
31348 break;
31349 case AtomicRMWInst::And:
31350 IID_C = Intrinsic::x86_atomic_btr;
31351 IID_I = Intrinsic::x86_atomic_btr_rm;
31352 break;
31354 Instruction *I = AI->user_back();
31355 LLVMContext &Ctx = AI->getContext();
31356 Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
31357 PointerType::getUnqual(Ctx));
31358 Value *Result = nullptr;
31359 auto BitTested = FindSingleBitChange(AI->getValOperand());
31360 assert(BitTested.first != nullptr);
31362 if (BitTested.second == ConstantBit || BitTested.second == NotConstantBit) {
31363 auto *C = cast<ConstantInt>(I->getOperand(I->getOperand(0) == AI ? 1 : 0));
31365 unsigned Imm = llvm::countr_zero(C->getZExtValue());
31366 Result = Builder.CreateIntrinsic(IID_C, AI->getType(),
31367 {Addr, Builder.getInt8(Imm)});
31368 } else {
31369 assert(BitTested.second == ShiftBit || BitTested.second == NotShiftBit);
31371 Value *SI = BitTested.first;
31372 assert(SI != nullptr);
31374 // BT{S|R|C} on memory operand don't modulo bit position so we need to
31375 // mask it.
31376 unsigned ShiftBits = SI->getType()->getPrimitiveSizeInBits();
31377 Value *BitPos =
31378 Builder.CreateAnd(SI, Builder.getIntN(ShiftBits, ShiftBits - 1));
31379 // Todo(1): In many cases it may be provable that SI is less than
31380 // ShiftBits in which case this mask is unnecessary
31381 // Todo(2): In the fairly idiomatic case of P[X / sizeof_bits(X)] OP 1
31382 // << (X % sizeof_bits(X)) we can drop the shift mask and AGEN in
31383 // favor of just a raw BT{S|R|C}.
31385 Result = Builder.CreateIntrinsic(IID_I, AI->getType(), {Addr, BitPos});
31386 Result = Builder.CreateZExtOrTrunc(Result, AI->getType());
31388 // If the result is only used for zero/non-zero status then we don't need to
31389 // shift value back. Otherwise do so.
31390 for (auto It = I->user_begin(); It != I->user_end(); ++It) {
31391 if (auto *ICmp = dyn_cast<ICmpInst>(*It)) {
31392 if (ICmp->isEquality()) {
31393 auto *C0 = dyn_cast<ConstantInt>(ICmp->getOperand(0));
31394 auto *C1 = dyn_cast<ConstantInt>(ICmp->getOperand(1));
31395 if (C0 || C1) {
31396 assert(C0 == nullptr || C1 == nullptr);
31397 if ((C0 ? C0 : C1)->isZero())
31398 continue;
31402 Result = Builder.CreateShl(Result, BitPos);
31403 break;
31407 I->replaceAllUsesWith(Result);
31408 I->eraseFromParent();
31409 AI->eraseFromParent();
31412 static bool shouldExpandCmpArithRMWInIR(AtomicRMWInst *AI) {
31413 using namespace llvm::PatternMatch;
31414 if (!AI->hasOneUse())
31415 return false;
31417 Value *Op = AI->getOperand(1);
31418 ICmpInst::Predicate Pred;
31419 Instruction *I = AI->user_back();
31420 AtomicRMWInst::BinOp Opc = AI->getOperation();
31421 if (Opc == AtomicRMWInst::Add) {
31422 if (match(I, m_c_ICmp(Pred, m_Sub(m_ZeroInt(), m_Specific(Op)), m_Value())))
31423 return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
31424 if (match(I, m_OneUse(m_c_Add(m_Specific(Op), m_Value())))) {
31425 if (match(I->user_back(),
31426 m_SpecificICmp(CmpInst::ICMP_SLT, m_Value(), m_ZeroInt())))
31427 return true;
31428 if (match(I->user_back(),
31429 m_SpecificICmp(CmpInst::ICMP_SGT, m_Value(), m_AllOnes())))
31430 return true;
31432 return false;
31434 if (Opc == AtomicRMWInst::Sub) {
31435 if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
31436 return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
31437 if (match(I, m_OneUse(m_Sub(m_Value(), m_Specific(Op))))) {
31438 if (match(I->user_back(),
31439 m_SpecificICmp(CmpInst::ICMP_SLT, m_Value(), m_ZeroInt())))
31440 return true;
31441 if (match(I->user_back(),
31442 m_SpecificICmp(CmpInst::ICMP_SGT, m_Value(), m_AllOnes())))
31443 return true;
31445 return false;
31447 if ((Opc == AtomicRMWInst::Or &&
31448 match(I, m_OneUse(m_c_Or(m_Specific(Op), m_Value())))) ||
31449 (Opc == AtomicRMWInst::And &&
31450 match(I, m_OneUse(m_c_And(m_Specific(Op), m_Value()))))) {
31451 if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
31452 return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE ||
31453 Pred == CmpInst::ICMP_SLT;
31454 if (match(I->user_back(),
31455 m_SpecificICmp(CmpInst::ICMP_SGT, m_Value(), m_AllOnes())))
31456 return true;
31457 return false;
31459 if (Opc == AtomicRMWInst::Xor) {
31460 if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
31461 return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
31462 if (match(I, m_OneUse(m_c_Xor(m_Specific(Op), m_Value())))) {
31463 if (match(I->user_back(),
31464 m_SpecificICmp(CmpInst::ICMP_SLT, m_Value(), m_ZeroInt())))
31465 return true;
31466 if (match(I->user_back(),
31467 m_SpecificICmp(CmpInst::ICMP_SGT, m_Value(), m_AllOnes())))
31468 return true;
31470 return false;
31473 return false;
31476 void X86TargetLowering::emitCmpArithAtomicRMWIntrinsic(
31477 AtomicRMWInst *AI) const {
31478 IRBuilder<> Builder(AI);
31479 Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
31480 Instruction *TempI = nullptr;
31481 LLVMContext &Ctx = AI->getContext();
31482 ICmpInst *ICI = dyn_cast<ICmpInst>(AI->user_back());
31483 if (!ICI) {
31484 TempI = AI->user_back();
31485 assert(TempI->hasOneUse() && "Must have one use");
31486 ICI = cast<ICmpInst>(TempI->user_back());
31488 X86::CondCode CC = X86::COND_INVALID;
31489 ICmpInst::Predicate Pred = ICI->getPredicate();
31490 switch (Pred) {
31491 default:
31492 llvm_unreachable("Not supported Pred");
31493 case CmpInst::ICMP_EQ:
31494 CC = X86::COND_E;
31495 break;
31496 case CmpInst::ICMP_NE:
31497 CC = X86::COND_NE;
31498 break;
31499 case CmpInst::ICMP_SLT:
31500 CC = X86::COND_S;
31501 break;
31502 case CmpInst::ICMP_SGT:
31503 CC = X86::COND_NS;
31504 break;
31506 Intrinsic::ID IID = Intrinsic::not_intrinsic;
31507 switch (AI->getOperation()) {
31508 default:
31509 llvm_unreachable("Unknown atomic operation");
31510 case AtomicRMWInst::Add:
31511 IID = Intrinsic::x86_atomic_add_cc;
31512 break;
31513 case AtomicRMWInst::Sub:
31514 IID = Intrinsic::x86_atomic_sub_cc;
31515 break;
31516 case AtomicRMWInst::Or:
31517 IID = Intrinsic::x86_atomic_or_cc;
31518 break;
31519 case AtomicRMWInst::And:
31520 IID = Intrinsic::x86_atomic_and_cc;
31521 break;
31522 case AtomicRMWInst::Xor:
31523 IID = Intrinsic::x86_atomic_xor_cc;
31524 break;
31526 Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
31527 PointerType::getUnqual(Ctx));
31528 Value *Call = Builder.CreateIntrinsic(
31529 IID, AI->getType(),
31530 {Addr, AI->getValOperand(), Builder.getInt32((unsigned)CC)});
31531 Value *Result = Builder.CreateTrunc(Call, Type::getInt1Ty(Ctx));
31532 ICI->replaceAllUsesWith(Result);
31533 ICI->eraseFromParent();
31534 if (TempI)
31535 TempI->eraseFromParent();
31536 AI->eraseFromParent();
31539 TargetLowering::AtomicExpansionKind
31540 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
31541 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
31542 Type *MemType = AI->getType();
31544 // If the operand is too big, we must see if cmpxchg8/16b is available
31545 // and default to library calls otherwise.
31546 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
31547 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
31548 : AtomicExpansionKind::None;
31551 AtomicRMWInst::BinOp Op = AI->getOperation();
31552 switch (Op) {
31553 case AtomicRMWInst::Xchg:
31554 return AtomicExpansionKind::None;
31555 case AtomicRMWInst::Add:
31556 case AtomicRMWInst::Sub:
31557 if (shouldExpandCmpArithRMWInIR(AI))
31558 return AtomicExpansionKind::CmpArithIntrinsic;
31559 // It's better to use xadd, xsub or xchg for these in other cases.
31560 return AtomicExpansionKind::None;
31561 case AtomicRMWInst::Or:
31562 case AtomicRMWInst::And:
31563 case AtomicRMWInst::Xor:
31564 if (shouldExpandCmpArithRMWInIR(AI))
31565 return AtomicExpansionKind::CmpArithIntrinsic;
31566 return shouldExpandLogicAtomicRMWInIR(AI);
31567 case AtomicRMWInst::Nand:
31568 case AtomicRMWInst::Max:
31569 case AtomicRMWInst::Min:
31570 case AtomicRMWInst::UMax:
31571 case AtomicRMWInst::UMin:
31572 case AtomicRMWInst::FAdd:
31573 case AtomicRMWInst::FSub:
31574 case AtomicRMWInst::FMax:
31575 case AtomicRMWInst::FMin:
31576 case AtomicRMWInst::UIncWrap:
31577 case AtomicRMWInst::UDecWrap:
31578 case AtomicRMWInst::USubCond:
31579 case AtomicRMWInst::USubSat:
31580 default:
31581 // These always require a non-trivial set of data operations on x86. We must
31582 // use a cmpxchg loop.
31583 return AtomicExpansionKind::CmpXChg;
31587 LoadInst *
31588 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
31589 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
31590 Type *MemType = AI->getType();
31591 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
31592 // there is no benefit in turning such RMWs into loads, and it is actually
31593 // harmful as it introduces a mfence.
31594 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
31595 return nullptr;
31597 // If this is a canonical idempotent atomicrmw w/no uses, we have a better
31598 // lowering available in lowerAtomicArith.
31599 // TODO: push more cases through this path.
31600 if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
31601 if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
31602 AI->use_empty())
31603 return nullptr;
31605 IRBuilder<> Builder(AI);
31606 Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
31607 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
31608 auto SSID = AI->getSyncScopeID();
31609 // We must restrict the ordering to avoid generating loads with Release or
31610 // ReleaseAcquire orderings.
31611 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
31613 // Before the load we need a fence. Here is an example lifted from
31614 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
31615 // is required:
31616 // Thread 0:
31617 // x.store(1, relaxed);
31618 // r1 = y.fetch_add(0, release);
31619 // Thread 1:
31620 // y.fetch_add(42, acquire);
31621 // r2 = x.load(relaxed);
31622 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
31623 // lowered to just a load without a fence. A mfence flushes the store buffer,
31624 // making the optimization clearly correct.
31625 // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
31626 // otherwise, we might be able to be more aggressive on relaxed idempotent
31627 // rmw. In practice, they do not look useful, so we don't try to be
31628 // especially clever.
31629 if (SSID == SyncScope::SingleThread)
31630 // FIXME: we could just insert an ISD::MEMBARRIER here, except we are at
31631 // the IR level, so we must wrap it in an intrinsic.
31632 return nullptr;
31634 if (!Subtarget.hasMFence())
31635 // FIXME: it might make sense to use a locked operation here but on a
31636 // different cache-line to prevent cache-line bouncing. In practice it
31637 // is probably a small win, and x86 processors without mfence are rare
31638 // enough that we do not bother.
31639 return nullptr;
31641 Function *MFence =
31642 llvm::Intrinsic::getOrInsertDeclaration(M, Intrinsic::x86_sse2_mfence);
31643 Builder.CreateCall(MFence, {});
31645 // Finally we can emit the atomic load.
31646 LoadInst *Loaded = Builder.CreateAlignedLoad(
31647 AI->getType(), AI->getPointerOperand(), AI->getAlign());
31648 Loaded->setAtomic(Order, SSID);
31649 AI->replaceAllUsesWith(Loaded);
31650 AI->eraseFromParent();
31651 return Loaded;
31654 /// Emit a locked operation on a stack location which does not change any
31655 /// memory location, but does involve a lock prefix. Location is chosen to be
31656 /// a) very likely accessed only by a single thread to minimize cache traffic,
31657 /// and b) definitely dereferenceable. Returns the new Chain result.
31658 static SDValue emitLockedStackOp(SelectionDAG &DAG,
31659 const X86Subtarget &Subtarget, SDValue Chain,
31660 const SDLoc &DL) {
31661 // Implementation notes:
31662 // 1) LOCK prefix creates a full read/write reordering barrier for memory
31663 // operations issued by the current processor. As such, the location
31664 // referenced is not relevant for the ordering properties of the instruction.
31665 // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
31666 // 8.2.3.9 Loads and Stores Are Not Reordered with Locked Instructions
31667 // 2) Using an immediate operand appears to be the best encoding choice
31668 // here since it doesn't require an extra register.
31669 // 3) OR appears to be very slightly faster than ADD. (Though, the difference
31670 // is small enough it might just be measurement noise.)
31671 // 4) When choosing offsets, there are several contributing factors:
31672 // a) If there's no redzone, we default to TOS. (We could allocate a cache
31673 // line aligned stack object to improve this case.)
31674 // b) To minimize our chances of introducing a false dependence, we prefer
31675 // to offset the stack usage from TOS slightly.
31676 // c) To minimize concerns about cross thread stack usage - in particular,
31677 // the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
31678 // captures state in the TOS frame and accesses it from many threads -
31679 // we want to use an offset such that the offset is in a distinct cache
31680 // line from the TOS frame.
31682 // For a general discussion of the tradeoffs and benchmark results, see:
31683 // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
31685 auto &MF = DAG.getMachineFunction();
31686 auto &TFL = *Subtarget.getFrameLowering();
31687 const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
31689 if (Subtarget.is64Bit()) {
31690 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
31691 SDValue Ops[] = {
31692 DAG.getRegister(X86::RSP, MVT::i64), // Base
31693 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
31694 DAG.getRegister(0, MVT::i64), // Index
31695 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
31696 DAG.getRegister(0, MVT::i16), // Segment.
31697 Zero,
31698 Chain};
31699 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
31700 MVT::Other, Ops);
31701 return SDValue(Res, 1);
31704 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
31705 SDValue Ops[] = {
31706 DAG.getRegister(X86::ESP, MVT::i32), // Base
31707 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
31708 DAG.getRegister(0, MVT::i32), // Index
31709 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
31710 DAG.getRegister(0, MVT::i16), // Segment.
31711 Zero,
31712 Chain
31714 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
31715 MVT::Other, Ops);
31716 return SDValue(Res, 1);
31719 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
31720 SelectionDAG &DAG) {
31721 SDLoc dl(Op);
31722 AtomicOrdering FenceOrdering =
31723 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
31724 SyncScope::ID FenceSSID =
31725 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
31727 // The only fence that needs an instruction is a sequentially-consistent
31728 // cross-thread fence.
31729 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
31730 FenceSSID == SyncScope::System) {
31731 if (Subtarget.hasMFence())
31732 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
31734 SDValue Chain = Op.getOperand(0);
31735 return emitLockedStackOp(DAG, Subtarget, Chain, dl);
31738 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
31739 return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
31742 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
31743 SelectionDAG &DAG) {
31744 MVT T = Op.getSimpleValueType();
31745 SDLoc DL(Op);
31746 unsigned Reg = 0;
31747 unsigned size = 0;
31748 switch(T.SimpleTy) {
31749 default: llvm_unreachable("Invalid value type!");
31750 case MVT::i8: Reg = X86::AL; size = 1; break;
31751 case MVT::i16: Reg = X86::AX; size = 2; break;
31752 case MVT::i32: Reg = X86::EAX; size = 4; break;
31753 case MVT::i64:
31754 assert(Subtarget.is64Bit() && "Node not type legal!");
31755 Reg = X86::RAX; size = 8;
31756 break;
31758 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
31759 Op.getOperand(2), SDValue());
31760 SDValue Ops[] = { cpIn.getValue(0),
31761 Op.getOperand(1),
31762 Op.getOperand(3),
31763 DAG.getTargetConstant(size, DL, MVT::i8),
31764 cpIn.getValue(1) };
31765 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
31766 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
31767 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
31768 Ops, T, MMO);
31770 SDValue cpOut =
31771 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
31772 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
31773 MVT::i32, cpOut.getValue(2));
31774 SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
31776 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
31777 cpOut, Success, EFLAGS.getValue(1));
31780 // Create MOVMSKB, taking into account whether we need to split for AVX1.
31781 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
31782 const X86Subtarget &Subtarget) {
31783 MVT InVT = V.getSimpleValueType();
31785 if (InVT == MVT::v64i8) {
31786 SDValue Lo, Hi;
31787 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
31788 Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
31789 Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
31790 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
31791 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
31792 Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
31793 DAG.getConstant(32, DL, MVT::i8));
31794 return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
31796 if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
31797 SDValue Lo, Hi;
31798 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
31799 Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
31800 Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
31801 Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
31802 DAG.getConstant(16, DL, MVT::i8));
31803 return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
31806 return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
31809 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
31810 SelectionDAG &DAG) {
31811 SDValue Src = Op.getOperand(0);
31812 MVT SrcVT = Src.getSimpleValueType();
31813 MVT DstVT = Op.getSimpleValueType();
31815 // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
31816 // half to v32i1 and concatenating the result.
31817 if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
31818 assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
31819 assert(Subtarget.hasBWI() && "Expected BWI target");
31820 SDLoc dl(Op);
31821 SDValue Lo, Hi;
31822 std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::i32, MVT::i32);
31823 Lo = DAG.getBitcast(MVT::v32i1, Lo);
31824 Hi = DAG.getBitcast(MVT::v32i1, Hi);
31825 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
31828 // Use MOVMSK for vector to scalar conversion to prevent scalarization.
31829 if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
31830 assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
31831 MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
31832 SDLoc DL(Op);
31833 SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
31834 V = getPMOVMSKB(DL, V, DAG, Subtarget);
31835 return DAG.getZExtOrTrunc(V, DL, DstVT);
31838 assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
31839 SrcVT == MVT::i64) && "Unexpected VT!");
31841 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
31842 if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
31843 !(DstVT == MVT::x86mmx && SrcVT.isVector()))
31844 // This conversion needs to be expanded.
31845 return SDValue();
31847 SDLoc dl(Op);
31848 if (SrcVT.isVector()) {
31849 // Widen the vector in input in the case of MVT::v2i32.
31850 // Example: from MVT::v2i32 to MVT::v4i32.
31851 MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
31852 SrcVT.getVectorNumElements() * 2);
31853 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
31854 DAG.getUNDEF(SrcVT));
31855 } else {
31856 assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
31857 "Unexpected source type in LowerBITCAST");
31858 Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
31861 MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
31862 Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
31864 if (DstVT == MVT::x86mmx)
31865 return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
31867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
31868 DAG.getIntPtrConstant(0, dl));
31871 /// Compute the horizontal sum of bytes in V for the elements of VT.
31873 /// Requires V to be a byte vector and VT to be an integer vector type with
31874 /// wider elements than V's type. The width of the elements of VT determines
31875 /// how many bytes of V are summed horizontally to produce each element of the
31876 /// result.
31877 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
31878 const X86Subtarget &Subtarget,
31879 SelectionDAG &DAG) {
31880 SDLoc DL(V);
31881 MVT ByteVecVT = V.getSimpleValueType();
31882 MVT EltVT = VT.getVectorElementType();
31883 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
31884 "Expected value to have byte element type.");
31885 assert(EltVT != MVT::i8 &&
31886 "Horizontal byte sum only makes sense for wider elements!");
31887 unsigned VecSize = VT.getSizeInBits();
31888 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
31890 // PSADBW instruction horizontally add all bytes and leave the result in i64
31891 // chunks, thus directly computes the pop count for v2i64 and v4i64.
31892 if (EltVT == MVT::i64) {
31893 SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
31894 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
31895 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
31896 return DAG.getBitcast(VT, V);
31899 if (EltVT == MVT::i32) {
31900 // We unpack the low half and high half into i32s interleaved with zeros so
31901 // that we can use PSADBW to horizontally sum them. The most useful part of
31902 // this is that it lines up the results of two PSADBW instructions to be
31903 // two v2i64 vectors which concatenated are the 4 population counts. We can
31904 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
31905 SDValue Zeros = DAG.getConstant(0, DL, VT);
31906 SDValue V32 = DAG.getBitcast(VT, V);
31907 SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
31908 SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
31910 // Do the horizontal sums into two v2i64s.
31911 Zeros = DAG.getConstant(0, DL, ByteVecVT);
31912 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
31913 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
31914 DAG.getBitcast(ByteVecVT, Low), Zeros);
31915 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
31916 DAG.getBitcast(ByteVecVT, High), Zeros);
31918 // Merge them together.
31919 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
31920 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
31921 DAG.getBitcast(ShortVecVT, Low),
31922 DAG.getBitcast(ShortVecVT, High));
31924 return DAG.getBitcast(VT, V);
31927 // The only element type left is i16.
31928 assert(EltVT == MVT::i16 && "Unknown how to handle type");
31930 // To obtain pop count for each i16 element starting from the pop count for
31931 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
31932 // right by 8. It is important to shift as i16s as i8 vector shift isn't
31933 // directly supported.
31934 SDValue ShifterV = DAG.getConstant(8, DL, VT);
31935 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
31936 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
31937 DAG.getBitcast(ByteVecVT, V));
31938 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
31941 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
31942 const X86Subtarget &Subtarget,
31943 SelectionDAG &DAG) {
31944 MVT VT = Op.getSimpleValueType();
31945 MVT EltVT = VT.getVectorElementType();
31946 int NumElts = VT.getVectorNumElements();
31947 (void)EltVT;
31948 assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
31950 // Implement a lookup table in register by using an algorithm based on:
31951 // http://wm.ite.pl/articles/sse-popcount.html
31953 // The general idea is that every lower byte nibble in the input vector is an
31954 // index into a in-register pre-computed pop count table. We then split up the
31955 // input vector in two new ones: (1) a vector with only the shifted-right
31956 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
31957 // masked out higher ones) for each byte. PSHUFB is used separately with both
31958 // to index the in-register table. Next, both are added and the result is a
31959 // i8 vector where each element contains the pop count for input byte.
31960 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
31961 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
31962 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
31963 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
31965 SmallVector<SDValue, 64> LUTVec;
31966 for (int i = 0; i < NumElts; ++i)
31967 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
31968 SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
31969 SDValue M0F = DAG.getConstant(0x0F, DL, VT);
31971 // High nibbles
31972 SDValue FourV = DAG.getConstant(4, DL, VT);
31973 SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
31975 // Low nibbles
31976 SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
31978 // The input vector is used as the shuffle mask that index elements into the
31979 // LUT. After counting low and high nibbles, add the vector to obtain the
31980 // final pop count per i8 element.
31981 SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
31982 SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
31983 return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
31986 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
31987 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
31988 static SDValue LowerVectorCTPOP(SDValue Op, const SDLoc &DL,
31989 const X86Subtarget &Subtarget,
31990 SelectionDAG &DAG) {
31991 MVT VT = Op.getSimpleValueType();
31992 assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
31993 "Unknown CTPOP type to handle");
31994 SDValue Op0 = Op.getOperand(0);
31996 // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
31997 if (Subtarget.hasVPOPCNTDQ()) {
31998 unsigned NumElems = VT.getVectorNumElements();
31999 assert((VT.getVectorElementType() == MVT::i8 ||
32000 VT.getVectorElementType() == MVT::i16) && "Unexpected type");
32001 if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
32002 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
32003 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
32004 Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
32005 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
32009 // Decompose 256-bit ops into smaller 128-bit ops.
32010 if (VT.is256BitVector() && !Subtarget.hasInt256())
32011 return splitVectorIntUnary(Op, DAG, DL);
32013 // Decompose 512-bit ops into smaller 256-bit ops.
32014 if (VT.is512BitVector() && !Subtarget.hasBWI())
32015 return splitVectorIntUnary(Op, DAG, DL);
32017 // For element types greater than i8, do vXi8 pop counts and a bytesum.
32018 if (VT.getScalarType() != MVT::i8) {
32019 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
32020 SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
32021 SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
32022 return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
32025 // We can't use the fast LUT approach, so fall back on LegalizeDAG.
32026 if (!Subtarget.hasSSSE3())
32027 return SDValue();
32029 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
32032 static SDValue LowerCTPOP(SDValue N, const X86Subtarget &Subtarget,
32033 SelectionDAG &DAG) {
32034 MVT VT = N.getSimpleValueType();
32035 SDValue Op = N.getOperand(0);
32036 SDLoc DL(N);
32038 if (VT.isScalarInteger()) {
32039 // Compute the lower/upper bounds of the active bits of the value,
32040 // allowing us to shift the active bits down if necessary to fit into the
32041 // special cases below.
32042 KnownBits Known = DAG.computeKnownBits(Op);
32043 unsigned LZ = Known.countMinLeadingZeros();
32044 unsigned TZ = Known.countMinTrailingZeros();
32045 assert((LZ + TZ) < Known.getBitWidth() && "Illegal shifted mask");
32046 unsigned ActiveBits = Known.getBitWidth() - LZ;
32047 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
32049 // i2 CTPOP - "ctpop(x) --> sub(x, (x >> 1))".
32050 if (ShiftedActiveBits <= 2) {
32051 if (ActiveBits > 2)
32052 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
32053 DAG.getShiftAmountConstant(TZ, VT, DL));
32054 Op = DAG.getZExtOrTrunc(Op, DL, MVT::i32);
32055 Op = DAG.getNode(ISD::SUB, DL, MVT::i32, Op,
32056 DAG.getNode(ISD::SRL, DL, MVT::i32, Op,
32057 DAG.getShiftAmountConstant(1, VT, DL)));
32058 return DAG.getZExtOrTrunc(Op, DL, VT);
32061 // i3 CTPOP - perform LUT into i32 integer.
32062 if (ShiftedActiveBits <= 3) {
32063 if (ActiveBits > 3)
32064 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
32065 DAG.getShiftAmountConstant(TZ, VT, DL));
32066 Op = DAG.getZExtOrTrunc(Op, DL, MVT::i32);
32067 Op = DAG.getNode(ISD::SHL, DL, MVT::i32, Op,
32068 DAG.getShiftAmountConstant(1, VT, DL));
32069 Op = DAG.getNode(ISD::SRL, DL, MVT::i32,
32070 DAG.getConstant(0b1110100110010100U, DL, MVT::i32), Op);
32071 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
32072 DAG.getConstant(0x3, DL, MVT::i32));
32073 return DAG.getZExtOrTrunc(Op, DL, VT);
32076 // i4 CTPOP - perform LUT into i64 integer.
32077 if (ShiftedActiveBits <= 4 &&
32078 DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64)) {
32079 SDValue LUT = DAG.getConstant(0x4332322132212110ULL, DL, MVT::i64);
32080 if (ActiveBits > 4)
32081 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
32082 DAG.getShiftAmountConstant(TZ, VT, DL));
32083 Op = DAG.getZExtOrTrunc(Op, DL, MVT::i32);
32084 Op = DAG.getNode(ISD::MUL, DL, MVT::i32, Op,
32085 DAG.getConstant(4, DL, MVT::i32));
32086 Op = DAG.getNode(ISD::SRL, DL, MVT::i64, LUT,
32087 DAG.getShiftAmountOperand(MVT::i64, Op));
32088 Op = DAG.getNode(ISD::AND, DL, MVT::i64, Op,
32089 DAG.getConstant(0x7, DL, MVT::i64));
32090 return DAG.getZExtOrTrunc(Op, DL, VT);
32093 // i8 CTPOP - with efficient i32 MUL, then attempt multiply-mask-multiply.
32094 if (ShiftedActiveBits <= 8) {
32095 SDValue Mask11 = DAG.getConstant(0x11111111U, DL, MVT::i32);
32096 if (ActiveBits > 8)
32097 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
32098 DAG.getShiftAmountConstant(TZ, VT, DL));
32099 Op = DAG.getZExtOrTrunc(Op, DL, MVT::i32);
32100 Op = DAG.getNode(ISD::MUL, DL, MVT::i32, Op,
32101 DAG.getConstant(0x08040201U, DL, MVT::i32));
32102 Op = DAG.getNode(ISD::SRL, DL, MVT::i32, Op,
32103 DAG.getShiftAmountConstant(3, MVT::i32, DL));
32104 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op, Mask11);
32105 Op = DAG.getNode(ISD::MUL, DL, MVT::i32, Op, Mask11);
32106 Op = DAG.getNode(ISD::SRL, DL, MVT::i32, Op,
32107 DAG.getShiftAmountConstant(28, MVT::i32, DL));
32108 return DAG.getZExtOrTrunc(Op, DL, VT);
32111 return SDValue(); // fallback to generic expansion.
32114 assert(VT.isVector() &&
32115 "We only do custom lowering for vector population count.");
32116 return LowerVectorCTPOP(N, DL, Subtarget, DAG);
32119 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
32120 MVT VT = Op.getSimpleValueType();
32121 SDValue In = Op.getOperand(0);
32122 SDLoc DL(Op);
32124 // For scalars, its still beneficial to transfer to/from the SIMD unit to
32125 // perform the BITREVERSE.
32126 if (!VT.isVector()) {
32127 MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
32128 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
32129 Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
32130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
32131 DAG.getIntPtrConstant(0, DL));
32134 int NumElts = VT.getVectorNumElements();
32135 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
32137 // Decompose 256-bit ops into smaller 128-bit ops.
32138 if (VT.is256BitVector())
32139 return splitVectorIntUnary(Op, DAG, DL);
32141 assert(VT.is128BitVector() &&
32142 "Only 128-bit vector bitreverse lowering supported.");
32144 // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
32145 // perform the BSWAP in the shuffle.
32146 // Its best to shuffle using the second operand as this will implicitly allow
32147 // memory folding for multiple vectors.
32148 SmallVector<SDValue, 16> MaskElts;
32149 for (int i = 0; i != NumElts; ++i) {
32150 for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
32151 int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
32152 int PermuteByte = SourceByte | (2 << 5);
32153 MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
32157 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
32158 SDValue Res = DAG.getBitcast(MVT::v16i8, In);
32159 Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
32160 Res, Mask);
32161 return DAG.getBitcast(VT, Res);
32164 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
32165 SelectionDAG &DAG) {
32166 MVT VT = Op.getSimpleValueType();
32168 if (Subtarget.hasXOP() && !VT.is512BitVector())
32169 return LowerBITREVERSE_XOP(Op, DAG);
32171 assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
32173 SDValue In = Op.getOperand(0);
32174 SDLoc DL(Op);
32176 // Split 512-bit ops without BWI so that we can still use the PSHUFB lowering.
32177 if (VT.is512BitVector() && !Subtarget.hasBWI())
32178 return splitVectorIntUnary(Op, DAG, DL);
32180 // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
32181 if (VT.is256BitVector() && !Subtarget.hasInt256())
32182 return splitVectorIntUnary(Op, DAG, DL);
32184 // Lower i8/i16/i32/i64 as vXi8 BITREVERSE + BSWAP
32185 if (!VT.isVector()) {
32186 assert(
32187 (VT == MVT::i32 || VT == MVT::i64 || VT == MVT::i16 || VT == MVT::i8) &&
32188 "Only tested for i8/i16/i32/i64");
32189 MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
32190 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
32191 Res = DAG.getNode(ISD::BITREVERSE, DL, MVT::v16i8,
32192 DAG.getBitcast(MVT::v16i8, Res));
32193 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
32194 DAG.getBitcast(VecVT, Res), DAG.getIntPtrConstant(0, DL));
32195 return (VT == MVT::i8) ? Res : DAG.getNode(ISD::BSWAP, DL, VT, Res);
32198 assert(VT.isVector() && VT.getSizeInBits() >= 128);
32200 // Lower vXi16/vXi32/vXi64 as BSWAP + vXi8 BITREVERSE.
32201 if (VT.getScalarType() != MVT::i8) {
32202 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
32203 SDValue Res = DAG.getNode(ISD::BSWAP, DL, VT, In);
32204 Res = DAG.getBitcast(ByteVT, Res);
32205 Res = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Res);
32206 return DAG.getBitcast(VT, Res);
32208 assert(VT.isVector() && VT.getScalarType() == MVT::i8 &&
32209 "Only byte vector BITREVERSE supported");
32211 unsigned NumElts = VT.getVectorNumElements();
32213 // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
32214 if (Subtarget.hasGFNI()) {
32215 SDValue Matrix = getGFNICtrlMask(ISD::BITREVERSE, DAG, DL, VT);
32216 return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
32217 DAG.getTargetConstant(0, DL, MVT::i8));
32220 // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
32221 // two nibbles and a PSHUFB lookup to find the bitreverse of each
32222 // 0-15 value (moved to the other nibble).
32223 SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
32224 SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
32225 SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
32227 const int LoLUT[16] = {
32228 /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
32229 /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
32230 /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
32231 /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
32232 const int HiLUT[16] = {
32233 /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
32234 /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
32235 /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
32236 /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
32238 SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
32239 for (unsigned i = 0; i < NumElts; ++i) {
32240 LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
32241 HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
32244 SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
32245 SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
32246 Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
32247 Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
32248 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
32251 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
32252 SelectionDAG &DAG) {
32253 SDLoc DL(Op);
32254 SDValue X = Op.getOperand(0);
32255 MVT VT = Op.getSimpleValueType();
32257 // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
32258 if (VT == MVT::i8 ||
32259 DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
32260 X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
32261 SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
32262 DAG.getConstant(0, DL, MVT::i8));
32263 // Copy the inverse of the parity flag into a register with setcc.
32264 SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
32265 // Extend to the original type.
32266 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
32269 // If we have POPCNT, use the default expansion.
32270 if (Subtarget.hasPOPCNT())
32271 return SDValue();
32273 if (VT == MVT::i64) {
32274 // Xor the high and low 16-bits together using a 32-bit operation.
32275 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
32276 DAG.getNode(ISD::SRL, DL, MVT::i64, X,
32277 DAG.getConstant(32, DL, MVT::i8)));
32278 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
32279 X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
32282 if (VT != MVT::i16) {
32283 // Xor the high and low 16-bits together using a 32-bit operation.
32284 SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
32285 DAG.getConstant(16, DL, MVT::i8));
32286 X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
32287 } else {
32288 // If the input is 16-bits, we need to extend to use an i32 shift below.
32289 X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
32292 // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
32293 // This should allow an h-reg to be used to save a shift.
32294 SDValue Hi = DAG.getNode(
32295 ISD::TRUNCATE, DL, MVT::i8,
32296 DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
32297 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
32298 SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
32299 SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
32301 // Copy the inverse of the parity flag into a register with setcc.
32302 SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
32303 // Extend to the original type.
32304 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
32307 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
32308 const X86Subtarget &Subtarget) {
32309 unsigned NewOpc = 0;
32310 switch (N->getOpcode()) {
32311 case ISD::ATOMIC_LOAD_ADD:
32312 NewOpc = X86ISD::LADD;
32313 break;
32314 case ISD::ATOMIC_LOAD_SUB:
32315 NewOpc = X86ISD::LSUB;
32316 break;
32317 case ISD::ATOMIC_LOAD_OR:
32318 NewOpc = X86ISD::LOR;
32319 break;
32320 case ISD::ATOMIC_LOAD_XOR:
32321 NewOpc = X86ISD::LXOR;
32322 break;
32323 case ISD::ATOMIC_LOAD_AND:
32324 NewOpc = X86ISD::LAND;
32325 break;
32326 default:
32327 llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
32330 MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
32332 return DAG.getMemIntrinsicNode(
32333 NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
32334 {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
32335 /*MemVT=*/N->getSimpleValueType(0), MMO);
32338 /// Lower atomic_load_ops into LOCK-prefixed operations.
32339 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
32340 const X86Subtarget &Subtarget) {
32341 AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
32342 SDValue Chain = N->getOperand(0);
32343 SDValue LHS = N->getOperand(1);
32344 SDValue RHS = N->getOperand(2);
32345 unsigned Opc = N->getOpcode();
32346 MVT VT = N->getSimpleValueType(0);
32347 SDLoc DL(N);
32349 // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
32350 // can only be lowered when the result is unused. They should have already
32351 // been transformed into a cmpxchg loop in AtomicExpand.
32352 if (N->hasAnyUseOfValue(0)) {
32353 // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
32354 // select LXADD if LOCK_SUB can't be selected.
32355 // Handle (atomic_load_xor p, SignBit) as (atomic_load_add p, SignBit) so we
32356 // can use LXADD as opposed to cmpxchg.
32357 if (Opc == ISD::ATOMIC_LOAD_SUB ||
32358 (Opc == ISD::ATOMIC_LOAD_XOR && isMinSignedConstant(RHS)))
32359 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
32360 DAG.getNegative(RHS, DL, VT), AN->getMemOperand());
32362 assert(Opc == ISD::ATOMIC_LOAD_ADD &&
32363 "Used AtomicRMW ops other than Add should have been expanded!");
32364 return N;
32367 // Specialized lowering for the canonical form of an idemptotent atomicrmw.
32368 // The core idea here is that since the memory location isn't actually
32369 // changing, all we need is a lowering for the *ordering* impacts of the
32370 // atomicrmw. As such, we can chose a different operation and memory
32371 // location to minimize impact on other code.
32372 // The above holds unless the node is marked volatile in which
32373 // case it needs to be preserved according to the langref.
32374 if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS) && !AN->isVolatile()) {
32375 // On X86, the only ordering which actually requires an instruction is
32376 // seq_cst which isn't SingleThread, everything just needs to be preserved
32377 // during codegen and then dropped. Note that we expect (but don't assume),
32378 // that orderings other than seq_cst and acq_rel have been canonicalized to
32379 // a store or load.
32380 if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
32381 AN->getSyncScopeID() == SyncScope::System) {
32382 // Prefer a locked operation against a stack location to minimize cache
32383 // traffic. This assumes that stack locations are very likely to be
32384 // accessed only by the owning thread.
32385 SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
32386 assert(!N->hasAnyUseOfValue(0));
32387 // NOTE: The getUNDEF is needed to give something for the unused result 0.
32388 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
32389 DAG.getUNDEF(VT), NewChain);
32391 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
32392 SDValue NewChain = DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Chain);
32393 assert(!N->hasAnyUseOfValue(0));
32394 // NOTE: The getUNDEF is needed to give something for the unused result 0.
32395 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
32396 DAG.getUNDEF(VT), NewChain);
32399 SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
32400 // RAUW the chain, but don't worry about the result, as it's unused.
32401 assert(!N->hasAnyUseOfValue(0));
32402 // NOTE: The getUNDEF is needed to give something for the unused result 0.
32403 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
32404 DAG.getUNDEF(VT), LockOp.getValue(1));
32407 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
32408 const X86Subtarget &Subtarget) {
32409 auto *Node = cast<AtomicSDNode>(Op.getNode());
32410 SDLoc dl(Node);
32411 EVT VT = Node->getMemoryVT();
32413 bool IsSeqCst =
32414 Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
32415 bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
32417 // If this store is not sequentially consistent and the type is legal
32418 // we can just keep it.
32419 if (!IsSeqCst && IsTypeLegal)
32420 return Op;
32422 if (!IsTypeLegal && !Subtarget.useSoftFloat() &&
32423 !DAG.getMachineFunction().getFunction().hasFnAttribute(
32424 Attribute::NoImplicitFloat)) {
32425 SDValue Chain;
32426 // For illegal i128 atomic_store, when AVX is enabled, we can simply emit a
32427 // vector store.
32428 if (VT == MVT::i128 && Subtarget.is64Bit() && Subtarget.hasAVX()) {
32429 SDValue VecVal = DAG.getBitcast(MVT::v2i64, Node->getVal());
32430 Chain = DAG.getStore(Node->getChain(), dl, VecVal, Node->getBasePtr(),
32431 Node->getMemOperand());
32434 // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
32435 // is enabled.
32436 if (VT == MVT::i64) {
32437 if (Subtarget.hasSSE1()) {
32438 SDValue SclToVec =
32439 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Node->getVal());
32440 MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
32441 SclToVec = DAG.getBitcast(StVT, SclToVec);
32442 SDVTList Tys = DAG.getVTList(MVT::Other);
32443 SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
32444 Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
32445 MVT::i64, Node->getMemOperand());
32446 } else if (Subtarget.hasX87()) {
32447 // First load this into an 80-bit X87 register using a stack temporary.
32448 // This will put the whole integer into the significand.
32449 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
32450 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
32451 MachinePointerInfo MPI =
32452 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
32453 Chain = DAG.getStore(Node->getChain(), dl, Node->getVal(), StackPtr,
32454 MPI, MaybeAlign(), MachineMemOperand::MOStore);
32455 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
32456 SDValue LdOps[] = {Chain, StackPtr};
32457 SDValue Value = DAG.getMemIntrinsicNode(
32458 X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
32459 /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
32460 Chain = Value.getValue(1);
32462 // Now use an FIST to do the atomic store.
32463 SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
32464 Chain =
32465 DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
32466 StoreOps, MVT::i64, Node->getMemOperand());
32470 if (Chain) {
32471 // If this is a sequentially consistent store, also emit an appropriate
32472 // barrier.
32473 if (IsSeqCst)
32474 Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
32476 return Chain;
32480 // Convert seq_cst store -> xchg
32481 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
32482 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
32483 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, Node->getMemoryVT(),
32484 Node->getOperand(0), Node->getOperand(2),
32485 Node->getOperand(1), Node->getMemOperand());
32486 return Swap.getValue(1);
32489 static SDValue LowerADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
32490 SDNode *N = Op.getNode();
32491 MVT VT = N->getSimpleValueType(0);
32492 unsigned Opc = Op.getOpcode();
32494 // Let legalize expand this if it isn't a legal type yet.
32495 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
32496 return SDValue();
32498 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
32499 SDLoc DL(N);
32501 // Set the carry flag.
32502 SDValue Carry = Op.getOperand(2);
32503 EVT CarryVT = Carry.getValueType();
32504 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
32505 Carry, DAG.getAllOnesConstant(DL, CarryVT));
32507 bool IsAdd = Opc == ISD::UADDO_CARRY || Opc == ISD::SADDO_CARRY;
32508 SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
32509 Op.getOperand(0), Op.getOperand(1),
32510 Carry.getValue(1));
32512 bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
32513 SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
32514 Sum.getValue(1), DL, DAG);
32515 if (N->getValueType(1) == MVT::i1)
32516 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
32518 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
32521 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
32522 SelectionDAG &DAG) {
32523 assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
32525 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
32526 // which returns the values as { float, float } (in XMM0) or
32527 // { double, double } (which is returned in XMM0, XMM1).
32528 SDLoc dl(Op);
32529 SDValue Arg = Op.getOperand(0);
32530 EVT ArgVT = Arg.getValueType();
32531 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
32533 TargetLowering::ArgListTy Args;
32534 TargetLowering::ArgListEntry Entry;
32536 Entry.Node = Arg;
32537 Entry.Ty = ArgTy;
32538 Entry.IsSExt = false;
32539 Entry.IsZExt = false;
32540 Args.push_back(Entry);
32542 bool isF64 = ArgVT == MVT::f64;
32543 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
32544 // the small struct {f32, f32} is returned in (eax, edx). For f64,
32545 // the results are returned via SRet in memory.
32546 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32547 RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
32548 const char *LibcallName = TLI.getLibcallName(LC);
32549 SDValue Callee =
32550 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
32552 Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
32553 : (Type *)FixedVectorType::get(ArgTy, 4);
32555 TargetLowering::CallLoweringInfo CLI(DAG);
32556 CLI.setDebugLoc(dl)
32557 .setChain(DAG.getEntryNode())
32558 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
32560 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
32562 if (isF64)
32563 // Returned in xmm0 and xmm1.
32564 return CallResult.first;
32566 // Returned in bits 0:31 and 32:64 xmm0.
32567 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
32568 CallResult.first, DAG.getIntPtrConstant(0, dl));
32569 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
32570 CallResult.first, DAG.getIntPtrConstant(1, dl));
32571 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
32572 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
32575 /// Widen a vector input to a vector of NVT. The
32576 /// input vector must have the same element type as NVT.
32577 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
32578 bool FillWithZeroes = false) {
32579 // Check if InOp already has the right width.
32580 MVT InVT = InOp.getSimpleValueType();
32581 if (InVT == NVT)
32582 return InOp;
32584 if (InOp.isUndef())
32585 return DAG.getUNDEF(NVT);
32587 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
32588 "input and widen element type must match");
32590 unsigned InNumElts = InVT.getVectorNumElements();
32591 unsigned WidenNumElts = NVT.getVectorNumElements();
32592 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
32593 "Unexpected request for vector widening");
32595 SDLoc dl(InOp);
32596 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
32597 InOp.getNumOperands() == 2) {
32598 SDValue N1 = InOp.getOperand(1);
32599 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
32600 N1.isUndef()) {
32601 InOp = InOp.getOperand(0);
32602 InVT = InOp.getSimpleValueType();
32603 InNumElts = InVT.getVectorNumElements();
32606 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
32607 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
32608 SmallVector<SDValue, 16> Ops;
32609 for (unsigned i = 0; i < InNumElts; ++i)
32610 Ops.push_back(InOp.getOperand(i));
32612 EVT EltVT = InOp.getOperand(0).getValueType();
32614 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
32615 DAG.getUNDEF(EltVT);
32616 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
32617 Ops.push_back(FillVal);
32618 return DAG.getBuildVector(NVT, dl, Ops);
32620 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
32621 DAG.getUNDEF(NVT);
32622 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
32623 InOp, DAG.getIntPtrConstant(0, dl));
32626 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
32627 SelectionDAG &DAG) {
32628 assert(Subtarget.hasAVX512() &&
32629 "MGATHER/MSCATTER are supported on AVX-512 arch only");
32631 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
32632 SDValue Src = N->getValue();
32633 MVT VT = Src.getSimpleValueType();
32634 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
32635 SDLoc dl(Op);
32637 SDValue Scale = N->getScale();
32638 SDValue Index = N->getIndex();
32639 SDValue Mask = N->getMask();
32640 SDValue Chain = N->getChain();
32641 SDValue BasePtr = N->getBasePtr();
32643 if (VT == MVT::v2f32 || VT == MVT::v2i32) {
32644 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
32645 // If the index is v2i64 and we have VLX we can use xmm for data and index.
32646 if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
32647 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
32648 EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
32649 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
32650 SDVTList VTs = DAG.getVTList(MVT::Other);
32651 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
32652 return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
32653 N->getMemoryVT(), N->getMemOperand());
32655 return SDValue();
32658 MVT IndexVT = Index.getSimpleValueType();
32660 // If the index is v2i32, we're being called by type legalization and we
32661 // should just let the default handling take care of it.
32662 if (IndexVT == MVT::v2i32)
32663 return SDValue();
32665 // If we don't have VLX and neither the passthru or index is 512-bits, we
32666 // need to widen until one is.
32667 if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
32668 !Index.getSimpleValueType().is512BitVector()) {
32669 // Determine how much we need to widen by to get a 512-bit type.
32670 unsigned Factor = std::min(512/VT.getSizeInBits(),
32671 512/IndexVT.getSizeInBits());
32672 unsigned NumElts = VT.getVectorNumElements() * Factor;
32674 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
32675 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
32676 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
32678 Src = ExtendToType(Src, VT, DAG);
32679 Index = ExtendToType(Index, IndexVT, DAG);
32680 Mask = ExtendToType(Mask, MaskVT, DAG, true);
32683 SDVTList VTs = DAG.getVTList(MVT::Other);
32684 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
32685 return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
32686 N->getMemoryVT(), N->getMemOperand());
32689 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
32690 SelectionDAG &DAG) {
32692 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
32693 MVT VT = Op.getSimpleValueType();
32694 MVT ScalarVT = VT.getScalarType();
32695 SDValue Mask = N->getMask();
32696 MVT MaskVT = Mask.getSimpleValueType();
32697 SDValue PassThru = N->getPassThru();
32698 SDLoc dl(Op);
32700 // Handle AVX masked loads which don't support passthru other than 0.
32701 if (MaskVT.getVectorElementType() != MVT::i1) {
32702 // We also allow undef in the isel pattern.
32703 if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
32704 return Op;
32706 SDValue NewLoad = DAG.getMaskedLoad(
32707 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
32708 getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
32709 N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
32710 N->isExpandingLoad());
32711 // Emit a blend.
32712 SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
32713 return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
32716 assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
32717 "Expanding masked load is supported on AVX-512 target only!");
32719 assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
32720 "Expanding masked load is supported for 32 and 64-bit types only!");
32722 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32723 "Cannot lower masked load op.");
32725 assert((ScalarVT.getSizeInBits() >= 32 ||
32726 (Subtarget.hasBWI() &&
32727 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
32728 "Unsupported masked load op.");
32730 // This operation is legal for targets with VLX, but without
32731 // VLX the vector should be widened to 512 bit
32732 unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
32733 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
32734 PassThru = ExtendToType(PassThru, WideDataVT, DAG);
32736 // Mask element has to be i1.
32737 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
32738 "Unexpected mask type");
32740 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
32742 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
32743 SDValue NewLoad = DAG.getMaskedLoad(
32744 WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
32745 PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
32746 N->getExtensionType(), N->isExpandingLoad());
32748 SDValue Extract =
32749 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
32750 DAG.getIntPtrConstant(0, dl));
32751 SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
32752 return DAG.getMergeValues(RetOps, dl);
32755 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
32756 SelectionDAG &DAG) {
32757 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
32758 SDValue DataToStore = N->getValue();
32759 MVT VT = DataToStore.getSimpleValueType();
32760 MVT ScalarVT = VT.getScalarType();
32761 SDValue Mask = N->getMask();
32762 SDLoc dl(Op);
32764 assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
32765 "Expanding masked load is supported on AVX-512 target only!");
32767 assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
32768 "Expanding masked load is supported for 32 and 64-bit types only!");
32770 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32771 "Cannot lower masked store op.");
32773 assert((ScalarVT.getSizeInBits() >= 32 ||
32774 (Subtarget.hasBWI() &&
32775 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
32776 "Unsupported masked store op.");
32778 // This operation is legal for targets with VLX, but without
32779 // VLX the vector should be widened to 512 bit
32780 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
32781 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
32783 // Mask element has to be i1.
32784 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
32785 "Unexpected mask type");
32787 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
32789 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
32790 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
32791 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
32792 N->getOffset(), Mask, N->getMemoryVT(),
32793 N->getMemOperand(), N->getAddressingMode(),
32794 N->isTruncatingStore(), N->isCompressingStore());
32797 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
32798 SelectionDAG &DAG) {
32799 assert(Subtarget.hasAVX2() &&
32800 "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
32802 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
32803 SDLoc dl(Op);
32804 MVT VT = Op.getSimpleValueType();
32805 SDValue Index = N->getIndex();
32806 SDValue Mask = N->getMask();
32807 SDValue PassThru = N->getPassThru();
32808 MVT IndexVT = Index.getSimpleValueType();
32810 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
32812 // If the index is v2i32, we're being called by type legalization.
32813 if (IndexVT == MVT::v2i32)
32814 return SDValue();
32816 // If we don't have VLX and neither the passthru or index is 512-bits, we
32817 // need to widen until one is.
32818 MVT OrigVT = VT;
32819 if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
32820 !IndexVT.is512BitVector()) {
32821 // Determine how much we need to widen by to get a 512-bit type.
32822 unsigned Factor = std::min(512/VT.getSizeInBits(),
32823 512/IndexVT.getSizeInBits());
32825 unsigned NumElts = VT.getVectorNumElements() * Factor;
32827 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
32828 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
32829 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
32831 PassThru = ExtendToType(PassThru, VT, DAG);
32832 Index = ExtendToType(Index, IndexVT, DAG);
32833 Mask = ExtendToType(Mask, MaskVT, DAG, true);
32836 // Break dependency on the data register.
32837 if (PassThru.isUndef())
32838 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
32840 SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
32841 N->getScale() };
32842 SDValue NewGather = DAG.getMemIntrinsicNode(
32843 X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
32844 N->getMemOperand());
32845 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
32846 NewGather, DAG.getIntPtrConstant(0, dl));
32847 return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
32850 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
32851 SDLoc dl(Op);
32852 SDValue Src = Op.getOperand(0);
32853 MVT DstVT = Op.getSimpleValueType();
32855 AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
32856 unsigned SrcAS = N->getSrcAddressSpace();
32858 assert(SrcAS != N->getDestAddressSpace() &&
32859 "addrspacecast must be between different address spaces");
32861 if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
32862 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
32863 } else if (DstVT == MVT::i64) {
32864 Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
32865 } else if (DstVT == MVT::i32) {
32866 Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
32867 } else {
32868 report_fatal_error("Bad address space in addrspacecast");
32870 return Op;
32873 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
32874 SelectionDAG &DAG) const {
32875 // TODO: Eventually, the lowering of these nodes should be informed by or
32876 // deferred to the GC strategy for the function in which they appear. For
32877 // now, however, they must be lowered to something. Since they are logically
32878 // no-ops in the case of a null GC strategy (or a GC strategy which does not
32879 // require special handling for these nodes), lower them as literal NOOPs for
32880 // the time being.
32881 SmallVector<SDValue, 2> Ops;
32882 Ops.push_back(Op.getOperand(0));
32883 if (Op->getGluedNode())
32884 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
32886 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
32887 return SDValue(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
32890 // Custom split CVTPS2PH with wide types.
32891 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
32892 SDLoc dl(Op);
32893 EVT VT = Op.getValueType();
32894 SDValue Lo, Hi;
32895 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
32896 EVT LoVT, HiVT;
32897 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32898 SDValue RC = Op.getOperand(1);
32899 Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
32900 Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
32901 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32904 static SDValue LowerPREFETCH(SDValue Op, const X86Subtarget &Subtarget,
32905 SelectionDAG &DAG) {
32906 unsigned IsData = Op.getConstantOperandVal(4);
32908 // We don't support non-data prefetch without PREFETCHI.
32909 // Just preserve the chain.
32910 if (!IsData && !Subtarget.hasPREFETCHI())
32911 return Op.getOperand(0);
32913 return Op;
32916 static SDValue LowerFCanonicalize(SDValue Op, SelectionDAG &DAG) {
32917 SDNode *N = Op.getNode();
32918 SDValue Operand = N->getOperand(0);
32919 EVT VT = Operand.getValueType();
32920 SDLoc dl(N);
32922 SDValue One = DAG.getConstantFP(1.0, dl, VT);
32924 // TODO: Fix Crash for bf16 when generating strict_fmul as it
32925 // leads to a error : SoftPromoteHalfResult #0: t11: bf16,ch = strict_fmul t0,
32926 // ConstantFP:bf16<APFloat(16256)>, t5 LLVM ERROR: Do not know how to soft
32927 // promote this operator's result!
32928 SDValue Chain = DAG.getEntryNode();
32929 SDValue StrictFmul = DAG.getNode(ISD::STRICT_FMUL, dl, {VT, MVT::Other},
32930 {Chain, Operand, One});
32931 return StrictFmul;
32934 static StringRef getInstrStrFromOpNo(const SmallVectorImpl<StringRef> &AsmStrs,
32935 unsigned OpNo) {
32936 const APInt Operand(32, OpNo);
32937 std::string OpNoStr = llvm::toString(Operand, 10, false);
32938 std::string Str(" $");
32940 std::string OpNoStr1(Str + OpNoStr); // e.g. " $1" (OpNo=1)
32941 std::string OpNoStr2(Str + "{" + OpNoStr + ":"); // With modifier, e.g. ${1:P}
32943 auto I = StringRef::npos;
32944 for (auto &AsmStr : AsmStrs) {
32945 // Match the OpNo string. We should match exactly to exclude match
32946 // sub-string, e.g. "$12" contain "$1"
32947 if (AsmStr.ends_with(OpNoStr1))
32948 I = AsmStr.size() - OpNoStr1.size();
32950 // Get the index of operand in AsmStr.
32951 if (I == StringRef::npos)
32952 I = AsmStr.find(OpNoStr1 + ",");
32953 if (I == StringRef::npos)
32954 I = AsmStr.find(OpNoStr2);
32956 if (I == StringRef::npos)
32957 continue;
32959 assert(I > 0 && "Unexpected inline asm string!");
32960 // Remove the operand string and label (if exsit).
32961 // For example:
32962 // ".L__MSASMLABEL_.${:uid}__l:call dword ptr ${0:P}"
32963 // ==>
32964 // ".L__MSASMLABEL_.${:uid}__l:call dword ptr "
32965 // ==>
32966 // "call dword ptr "
32967 auto TmpStr = AsmStr.substr(0, I);
32968 I = TmpStr.rfind(':');
32969 if (I != StringRef::npos)
32970 TmpStr = TmpStr.substr(I + 1);
32971 return TmpStr.take_while(llvm::isAlpha);
32974 return StringRef();
32977 bool X86TargetLowering::isInlineAsmTargetBranch(
32978 const SmallVectorImpl<StringRef> &AsmStrs, unsigned OpNo) const {
32979 // In a __asm block, __asm inst foo where inst is CALL or JMP should be
32980 // changed from indirect TargetLowering::C_Memory to direct
32981 // TargetLowering::C_Address.
32982 // We don't need to special case LOOP* and Jcc, which cannot target a memory
32983 // location.
32984 StringRef Inst = getInstrStrFromOpNo(AsmStrs, OpNo);
32985 return Inst.equals_insensitive("call") || Inst.equals_insensitive("jmp");
32988 static SDValue getFlagsOfCmpZeroFori1(SelectionDAG &DAG, const SDLoc &DL,
32989 SDValue Mask) {
32990 EVT Ty = MVT::i8;
32991 auto V = DAG.getBitcast(MVT::i1, Mask);
32992 auto VE = DAG.getZExtOrTrunc(V, DL, Ty);
32993 auto Zero = DAG.getConstant(0, DL, Ty);
32994 SDVTList X86SubVTs = DAG.getVTList(Ty, MVT::i32);
32995 auto CmpZero = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, VE);
32996 return SDValue(CmpZero.getNode(), 1);
32999 SDValue X86TargetLowering::visitMaskedLoad(
33000 SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO,
33001 SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const {
33002 // @llvm.masked.load.v1*(ptr, alignment, mask, passthru)
33003 // ->
33004 // _, flags = SUB 0, mask
33005 // res, chain = CLOAD inchain, ptr, (bit_cast_to_scalar passthru), cond, flags
33006 // bit_cast_to_vector<res>
33007 EVT VTy = PassThru.getValueType();
33008 EVT Ty = VTy.getVectorElementType();
33009 SDVTList Tys = DAG.getVTList(Ty, MVT::Other);
33010 auto ScalarPassThru = PassThru.isUndef() ? DAG.getConstant(0, DL, Ty)
33011 : DAG.getBitcast(Ty, PassThru);
33012 auto Flags = getFlagsOfCmpZeroFori1(DAG, DL, Mask);
33013 auto COND_NE = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
33014 SDValue Ops[] = {Chain, Ptr, ScalarPassThru, COND_NE, Flags};
33015 NewLoad = DAG.getMemIntrinsicNode(X86ISD::CLOAD, DL, Tys, Ops, Ty, MMO);
33016 return DAG.getBitcast(VTy, NewLoad);
33019 SDValue X86TargetLowering::visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL,
33020 SDValue Chain,
33021 MachineMemOperand *MMO, SDValue Ptr,
33022 SDValue Val, SDValue Mask) const {
33023 // llvm.masked.store.v1*(Src0, Ptr, alignment, Mask)
33024 // ->
33025 // _, flags = SUB 0, mask
33026 // chain = CSTORE inchain, (bit_cast_to_scalar val), ptr, cond, flags
33027 EVT Ty = Val.getValueType().getVectorElementType();
33028 SDVTList Tys = DAG.getVTList(MVT::Other);
33029 auto ScalarVal = DAG.getBitcast(Ty, Val);
33030 auto Flags = getFlagsOfCmpZeroFori1(DAG, DL, Mask);
33031 auto COND_NE = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
33032 SDValue Ops[] = {Chain, ScalarVal, Ptr, COND_NE, Flags};
33033 return DAG.getMemIntrinsicNode(X86ISD::CSTORE, DL, Tys, Ops, Ty, MMO);
33036 /// Provide custom lowering hooks for some operations.
33037 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
33038 switch (Op.getOpcode()) {
33039 // clang-format off
33040 default: llvm_unreachable("Should not custom lower this!");
33041 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
33042 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
33043 return LowerCMP_SWAP(Op, Subtarget, DAG);
33044 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
33045 case ISD::ATOMIC_LOAD_ADD:
33046 case ISD::ATOMIC_LOAD_SUB:
33047 case ISD::ATOMIC_LOAD_OR:
33048 case ISD::ATOMIC_LOAD_XOR:
33049 case ISD::ATOMIC_LOAD_AND: return lowerAtomicArith(Op, DAG, Subtarget);
33050 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG, Subtarget);
33051 case ISD::BITREVERSE: return LowerBITREVERSE(Op, Subtarget, DAG);
33052 case ISD::PARITY: return LowerPARITY(Op, Subtarget, DAG);
33053 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
33054 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
33055 case ISD::VECTOR_SHUFFLE: return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
33056 case ISD::VECTOR_COMPRESS: return lowerVECTOR_COMPRESS(Op, Subtarget, DAG);
33057 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
33058 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
33059 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
33060 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
33061 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
33062 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
33063 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
33064 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
33065 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
33066 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
33067 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
33068 case ISD::SHL_PARTS:
33069 case ISD::SRA_PARTS:
33070 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
33071 case ISD::FSHL:
33072 case ISD::FSHR: return LowerFunnelShift(Op, Subtarget, DAG);
33073 case ISD::FCANONICALIZE: return LowerFCanonicalize(Op, DAG);
33074 case ISD::STRICT_SINT_TO_FP:
33075 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
33076 case ISD::STRICT_UINT_TO_FP:
33077 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
33078 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
33079 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
33080 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
33081 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
33082 case ISD::ZERO_EXTEND_VECTOR_INREG:
33083 case ISD::SIGN_EXTEND_VECTOR_INREG:
33084 return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
33085 case ISD::FP_TO_SINT:
33086 case ISD::STRICT_FP_TO_SINT:
33087 case ISD::FP_TO_UINT:
33088 case ISD::STRICT_FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
33089 case ISD::FP_TO_SINT_SAT:
33090 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG);
33091 case ISD::FP_EXTEND:
33092 case ISD::STRICT_FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
33093 case ISD::FP_ROUND:
33094 case ISD::STRICT_FP_ROUND: return LowerFP_ROUND(Op, DAG);
33095 case ISD::FP16_TO_FP:
33096 case ISD::STRICT_FP16_TO_FP: return LowerFP16_TO_FP(Op, DAG);
33097 case ISD::FP_TO_FP16:
33098 case ISD::STRICT_FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
33099 case ISD::FP_TO_BF16: return LowerFP_TO_BF16(Op, DAG);
33100 case ISD::LOAD: return LowerLoad(Op, Subtarget, DAG);
33101 case ISD::STORE: return LowerStore(Op, Subtarget, DAG);
33102 case ISD::FADD:
33103 case ISD::FSUB: return lowerFaddFsub(Op, DAG);
33104 case ISD::FROUND: return LowerFROUND(Op, DAG);
33105 case ISD::FABS:
33106 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
33107 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
33108 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
33109 case ISD::LRINT:
33110 case ISD::LLRINT: return LowerLRINT_LLRINT(Op, DAG);
33111 case ISD::SETCC:
33112 case ISD::STRICT_FSETCC:
33113 case ISD::STRICT_FSETCCS: return LowerSETCC(Op, DAG);
33114 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
33115 case ISD::SELECT: return LowerSELECT(Op, DAG);
33116 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
33117 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
33118 case ISD::VASTART: return LowerVASTART(Op, DAG);
33119 case ISD::VAARG: return LowerVAARG(Op, DAG);
33120 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
33121 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
33122 case ISD::INTRINSIC_VOID:
33123 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
33124 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
33125 case ISD::ADDROFRETURNADDR: return LowerADDROFRETURNADDR(Op, DAG);
33126 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
33127 case ISD::FRAME_TO_ARGS_OFFSET:
33128 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
33129 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
33130 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
33131 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
33132 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
33133 case ISD::EH_SJLJ_SETUP_DISPATCH:
33134 return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
33135 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
33136 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
33137 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
33138 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
33139 case ISD::GET_FPENV_MEM: return LowerGET_FPENV_MEM(Op, DAG);
33140 case ISD::SET_FPENV_MEM: return LowerSET_FPENV_MEM(Op, DAG);
33141 case ISD::RESET_FPENV: return LowerRESET_FPENV(Op, DAG);
33142 case ISD::CTLZ:
33143 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ(Op, Subtarget, DAG);
33144 case ISD::CTTZ:
33145 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, Subtarget, DAG);
33146 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
33147 case ISD::MULHS:
33148 case ISD::MULHU: return LowerMULH(Op, Subtarget, DAG);
33149 case ISD::ROTL:
33150 case ISD::ROTR: return LowerRotate(Op, Subtarget, DAG);
33151 case ISD::SRA:
33152 case ISD::SRL:
33153 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
33154 case ISD::SADDO:
33155 case ISD::UADDO:
33156 case ISD::SSUBO:
33157 case ISD::USUBO: return LowerXALUO(Op, DAG);
33158 case ISD::SMULO:
33159 case ISD::UMULO: return LowerMULO(Op, Subtarget, DAG);
33160 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
33161 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
33162 case ISD::SADDO_CARRY:
33163 case ISD::SSUBO_CARRY:
33164 case ISD::UADDO_CARRY:
33165 case ISD::USUBO_CARRY: return LowerADDSUBO_CARRY(Op, DAG);
33166 case ISD::ADD:
33167 case ISD::SUB: return lowerAddSub(Op, DAG, Subtarget);
33168 case ISD::UADDSAT:
33169 case ISD::SADDSAT:
33170 case ISD::USUBSAT:
33171 case ISD::SSUBSAT: return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
33172 case ISD::SMAX:
33173 case ISD::SMIN:
33174 case ISD::UMAX:
33175 case ISD::UMIN: return LowerMINMAX(Op, Subtarget, DAG);
33176 case ISD::FMINIMUM:
33177 case ISD::FMAXIMUM:
33178 return LowerFMINIMUM_FMAXIMUM(Op, Subtarget, DAG);
33179 case ISD::ABS: return LowerABS(Op, Subtarget, DAG);
33180 case ISD::ABDS:
33181 case ISD::ABDU: return LowerABD(Op, Subtarget, DAG);
33182 case ISD::AVGCEILU: return LowerAVG(Op, Subtarget, DAG);
33183 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
33184 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
33185 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
33186 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
33187 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
33188 case ISD::GC_TRANSITION_START:
33189 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION(Op, DAG);
33190 case ISD::ADDRSPACECAST: return LowerADDRSPACECAST(Op, DAG);
33191 case X86ISD::CVTPS2PH: return LowerCVTPS2PH(Op, DAG);
33192 case ISD::PREFETCH: return LowerPREFETCH(Op, Subtarget, DAG);
33193 // clang-format on
33197 /// Replace a node with an illegal result type with a new node built out of
33198 /// custom code.
33199 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
33200 SmallVectorImpl<SDValue>&Results,
33201 SelectionDAG &DAG) const {
33202 SDLoc dl(N);
33203 switch (N->getOpcode()) {
33204 default:
33205 #ifndef NDEBUG
33206 dbgs() << "ReplaceNodeResults: ";
33207 N->dump(&DAG);
33208 #endif
33209 llvm_unreachable("Do not know how to custom type legalize this operation!");
33210 case X86ISD::CVTPH2PS: {
33211 EVT VT = N->getValueType(0);
33212 SDValue Lo, Hi;
33213 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
33214 EVT LoVT, HiVT;
33215 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
33216 Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
33217 Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
33218 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
33219 Results.push_back(Res);
33220 return;
33222 case X86ISD::STRICT_CVTPH2PS: {
33223 EVT VT = N->getValueType(0);
33224 SDValue Lo, Hi;
33225 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
33226 EVT LoVT, HiVT;
33227 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
33228 Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
33229 {N->getOperand(0), Lo});
33230 Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
33231 {N->getOperand(0), Hi});
33232 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
33233 Lo.getValue(1), Hi.getValue(1));
33234 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
33235 Results.push_back(Res);
33236 Results.push_back(Chain);
33237 return;
33239 case X86ISD::CVTPS2PH:
33240 Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
33241 return;
33242 case ISD::CTPOP: {
33243 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
33244 // If we have at most 32 active bits, then perform as i32 CTPOP.
33245 // TODO: Perform this in generic legalizer?
33246 KnownBits Known = DAG.computeKnownBits(N->getOperand(0));
33247 unsigned LZ = Known.countMinLeadingZeros();
33248 unsigned TZ = Known.countMinTrailingZeros();
33249 if ((LZ + TZ) >= 32) {
33250 SDValue Op = DAG.getNode(ISD::SRL, dl, MVT::i64, N->getOperand(0),
33251 DAG.getShiftAmountConstant(TZ, MVT::i64, dl));
33252 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Op);
33253 Op = DAG.getNode(ISD::CTPOP, dl, MVT::i32, Op);
33254 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Op);
33255 Results.push_back(Op);
33256 return;
33258 // Use a v2i64 if possible.
33259 bool NoImplicitFloatOps =
33260 DAG.getMachineFunction().getFunction().hasFnAttribute(
33261 Attribute::NoImplicitFloat);
33262 if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
33263 SDValue Wide =
33264 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
33265 Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
33266 // Bit count should fit in 32-bits, extract it as that and then zero
33267 // extend to i64. Otherwise we end up extracting bits 63:32 separately.
33268 Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
33269 Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
33270 DAG.getIntPtrConstant(0, dl));
33271 Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
33272 Results.push_back(Wide);
33274 return;
33276 case ISD::MUL: {
33277 EVT VT = N->getValueType(0);
33278 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33279 VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
33280 // Pre-promote these to vXi16 to avoid op legalization thinking all 16
33281 // elements are needed.
33282 MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
33283 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
33284 SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
33285 SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
33286 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
33287 unsigned NumConcats = 16 / VT.getVectorNumElements();
33288 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
33289 ConcatOps[0] = Res;
33290 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
33291 Results.push_back(Res);
33292 return;
33294 case ISD::SMULO:
33295 case ISD::UMULO: {
33296 EVT VT = N->getValueType(0);
33297 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33298 VT == MVT::v2i32 && "Unexpected VT!");
33299 bool IsSigned = N->getOpcode() == ISD::SMULO;
33300 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
33301 SDValue Op0 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(0));
33302 SDValue Op1 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(1));
33303 SDValue Res = DAG.getNode(ISD::MUL, dl, MVT::v2i64, Op0, Op1);
33304 // Extract the high 32 bits from each result using PSHUFD.
33305 // TODO: Could use SRL+TRUNCATE but that doesn't become a PSHUFD.
33306 SDValue Hi = DAG.getBitcast(MVT::v4i32, Res);
33307 Hi = DAG.getVectorShuffle(MVT::v4i32, dl, Hi, Hi, {1, 3, -1, -1});
33308 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Hi,
33309 DAG.getIntPtrConstant(0, dl));
33311 // Truncate the low bits of the result. This will become PSHUFD.
33312 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
33314 SDValue HiCmp;
33315 if (IsSigned) {
33316 // SMULO overflows if the high bits don't match the sign of the low.
33317 HiCmp = DAG.getNode(ISD::SRA, dl, VT, Res, DAG.getConstant(31, dl, VT));
33318 } else {
33319 // UMULO overflows if the high bits are non-zero.
33320 HiCmp = DAG.getConstant(0, dl, VT);
33322 SDValue Ovf = DAG.getSetCC(dl, N->getValueType(1), Hi, HiCmp, ISD::SETNE);
33324 // Widen the result with by padding with undef.
33325 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
33326 DAG.getUNDEF(VT));
33327 Results.push_back(Res);
33328 Results.push_back(Ovf);
33329 return;
33331 case X86ISD::VPMADDWD: {
33332 // Legalize types for X86ISD::VPMADDWD by widening.
33333 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33335 EVT VT = N->getValueType(0);
33336 EVT InVT = N->getOperand(0).getValueType();
33337 assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
33338 "Expected a VT that divides into 128 bits.");
33339 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33340 "Unexpected type action!");
33341 unsigned NumConcat = 128 / InVT.getSizeInBits();
33343 EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
33344 InVT.getVectorElementType(),
33345 NumConcat * InVT.getVectorNumElements());
33346 EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
33347 VT.getVectorElementType(),
33348 NumConcat * VT.getVectorNumElements());
33350 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
33351 Ops[0] = N->getOperand(0);
33352 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
33353 Ops[0] = N->getOperand(1);
33354 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
33356 SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
33357 Results.push_back(Res);
33358 return;
33360 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
33361 case X86ISD::FMINC:
33362 case X86ISD::FMIN:
33363 case X86ISD::FMAXC:
33364 case X86ISD::FMAX: {
33365 EVT VT = N->getValueType(0);
33366 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
33367 SDValue UNDEF = DAG.getUNDEF(VT);
33368 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
33369 N->getOperand(0), UNDEF);
33370 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
33371 N->getOperand(1), UNDEF);
33372 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
33373 return;
33375 case ISD::SDIV:
33376 case ISD::UDIV:
33377 case ISD::SREM:
33378 case ISD::UREM: {
33379 EVT VT = N->getValueType(0);
33380 if (VT.isVector()) {
33381 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33382 "Unexpected type action!");
33383 // If this RHS is a constant splat vector we can widen this and let
33384 // division/remainder by constant optimize it.
33385 // TODO: Can we do something for non-splat?
33386 APInt SplatVal;
33387 if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
33388 unsigned NumConcats = 128 / VT.getSizeInBits();
33389 SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
33390 Ops0[0] = N->getOperand(0);
33391 EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
33392 SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
33393 SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
33394 SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
33395 Results.push_back(Res);
33397 return;
33400 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
33401 Results.push_back(V);
33402 return;
33404 case ISD::TRUNCATE: {
33405 MVT VT = N->getSimpleValueType(0);
33406 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
33407 return;
33409 // The generic legalizer will try to widen the input type to the same
33410 // number of elements as the widened result type. But this isn't always
33411 // the best thing so do some custom legalization to avoid some cases.
33412 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
33413 SDValue In = N->getOperand(0);
33414 EVT InVT = In.getValueType();
33415 EVT InEltVT = InVT.getVectorElementType();
33416 EVT EltVT = VT.getVectorElementType();
33417 unsigned MinElts = VT.getVectorNumElements();
33418 unsigned WidenNumElts = WidenVT.getVectorNumElements();
33419 unsigned InBits = InVT.getSizeInBits();
33421 // See if there are sufficient leading bits to perform a PACKUS/PACKSS.
33422 unsigned PackOpcode;
33423 if (SDValue Src =
33424 matchTruncateWithPACK(PackOpcode, VT, In, dl, DAG, Subtarget)) {
33425 if (SDValue Res = truncateVectorWithPACK(PackOpcode, VT, Src,
33426 dl, DAG, Subtarget)) {
33427 Res = widenSubVector(WidenVT, Res, false, Subtarget, DAG, dl);
33428 Results.push_back(Res);
33429 return;
33433 if ((128 % InBits) == 0 && WidenVT.is128BitVector()) {
33434 // 128 bit and smaller inputs should avoid truncate all together and
33435 // use a shuffle.
33436 if ((InEltVT.getSizeInBits() % EltVT.getSizeInBits()) == 0) {
33437 int Scale = InEltVT.getSizeInBits() / EltVT.getSizeInBits();
33438 SmallVector<int, 16> TruncMask(WidenNumElts, -1);
33439 for (unsigned I = 0; I < MinElts; ++I)
33440 TruncMask[I] = Scale * I;
33441 SDValue WidenIn = widenSubVector(In, false, Subtarget, DAG, dl, 128);
33442 assert(isTypeLegal(WidenVT) && isTypeLegal(WidenIn.getValueType()) &&
33443 "Illegal vector type in truncation");
33444 WidenIn = DAG.getBitcast(WidenVT, WidenIn);
33445 Results.push_back(
33446 DAG.getVectorShuffle(WidenVT, dl, WidenIn, WidenIn, TruncMask));
33447 return;
33451 // With AVX512 there are some cases that can use a target specific
33452 // truncate node to go from 256/512 to less than 128 with zeros in the
33453 // upper elements of the 128 bit result.
33454 if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
33455 // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
33456 if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
33457 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
33458 return;
33460 // There's one case we can widen to 512 bits and use VTRUNC.
33461 if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
33462 In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
33463 DAG.getUNDEF(MVT::v4i64));
33464 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
33465 return;
33468 if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
33469 getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
33470 isTypeLegal(MVT::v4i64)) {
33471 // Input needs to be split and output needs to widened. Let's use two
33472 // VTRUNCs, and shuffle their results together into the wider type.
33473 SDValue Lo, Hi;
33474 std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
33476 Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
33477 Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
33478 SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
33479 { 0, 1, 2, 3, 16, 17, 18, 19,
33480 -1, -1, -1, -1, -1, -1, -1, -1 });
33481 Results.push_back(Res);
33482 return;
33485 // Attempt to widen the truncation input vector to let LowerTRUNCATE handle
33486 // this via type legalization.
33487 if ((InEltVT == MVT::i16 || InEltVT == MVT::i32 || InEltVT == MVT::i64) &&
33488 (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32) &&
33489 (!Subtarget.hasSSSE3() ||
33490 (!isTypeLegal(InVT) &&
33491 !(MinElts <= 4 && InEltVT == MVT::i64 && EltVT == MVT::i8)))) {
33492 SDValue WidenIn = widenSubVector(In, false, Subtarget, DAG, dl,
33493 InEltVT.getSizeInBits() * WidenNumElts);
33494 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, WidenVT, WidenIn));
33495 return;
33498 return;
33500 case ISD::ANY_EXTEND:
33501 // Right now, only MVT::v8i8 has Custom action for an illegal type.
33502 // It's intended to custom handle the input type.
33503 assert(N->getValueType(0) == MVT::v8i8 &&
33504 "Do not know how to legalize this Node");
33505 return;
33506 case ISD::SIGN_EXTEND:
33507 case ISD::ZERO_EXTEND: {
33508 EVT VT = N->getValueType(0);
33509 SDValue In = N->getOperand(0);
33510 EVT InVT = In.getValueType();
33511 if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
33512 (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
33513 assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
33514 "Unexpected type action!");
33515 assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
33516 // Custom split this so we can extend i8/i16->i32 invec. This is better
33517 // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
33518 // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
33519 // we allow the sra from the extend to i32 to be shared by the split.
33520 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
33522 // Fill a vector with sign bits for each element.
33523 SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
33524 SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
33526 // Create an unpackl and unpackh to interleave the sign bits then bitcast
33527 // to v2i64.
33528 SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
33529 {0, 4, 1, 5});
33530 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
33531 SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
33532 {2, 6, 3, 7});
33533 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
33535 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
33536 Results.push_back(Res);
33537 return;
33540 if (VT == MVT::v16i32 || VT == MVT::v8i64) {
33541 if (!InVT.is128BitVector()) {
33542 // Not a 128 bit vector, but maybe type legalization will promote
33543 // it to 128 bits.
33544 if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
33545 return;
33546 InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
33547 if (!InVT.is128BitVector())
33548 return;
33550 // Promote the input to 128 bits. Type legalization will turn this into
33551 // zext_inreg/sext_inreg.
33552 In = DAG.getNode(N->getOpcode(), dl, InVT, In);
33555 // Perform custom splitting instead of the two stage extend we would get
33556 // by default.
33557 EVT LoVT, HiVT;
33558 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
33559 assert(isTypeLegal(LoVT) && "Split VT not legal?");
33561 SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
33563 // We need to shift the input over by half the number of elements.
33564 unsigned NumElts = InVT.getVectorNumElements();
33565 unsigned HalfNumElts = NumElts / 2;
33566 SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
33567 for (unsigned i = 0; i != HalfNumElts; ++i)
33568 ShufMask[i] = i + HalfNumElts;
33570 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
33571 Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
33573 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
33574 Results.push_back(Res);
33576 return;
33578 case ISD::FP_TO_SINT:
33579 case ISD::STRICT_FP_TO_SINT:
33580 case ISD::FP_TO_UINT:
33581 case ISD::STRICT_FP_TO_UINT: {
33582 bool IsStrict = N->isStrictFPOpcode();
33583 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
33584 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
33585 EVT VT = N->getValueType(0);
33586 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
33587 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
33588 EVT SrcVT = Src.getValueType();
33590 SDValue Res;
33591 if (isSoftF16(SrcVT, Subtarget)) {
33592 EVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
33593 if (IsStrict) {
33594 Res =
33595 DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
33596 {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
33597 {NVT, MVT::Other}, {Chain, Src})});
33598 Chain = Res.getValue(1);
33599 } else {
33600 Res = DAG.getNode(N->getOpcode(), dl, VT,
33601 DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
33603 Results.push_back(Res);
33604 if (IsStrict)
33605 Results.push_back(Chain);
33607 return;
33610 if (VT.isVector() && Subtarget.hasFP16() &&
33611 SrcVT.getVectorElementType() == MVT::f16) {
33612 EVT EleVT = VT.getVectorElementType();
33613 EVT ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
33615 if (SrcVT != MVT::v8f16) {
33616 SDValue Tmp =
33617 IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
33618 SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
33619 Ops[0] = Src;
33620 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
33623 if (IsStrict) {
33624 unsigned Opc =
33625 IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
33626 Res =
33627 DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {N->getOperand(0), Src});
33628 Chain = Res.getValue(1);
33629 } else {
33630 unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
33631 Res = DAG.getNode(Opc, dl, ResVT, Src);
33634 // TODO: Need to add exception check code for strict FP.
33635 if (EleVT.getSizeInBits() < 16) {
33636 MVT TmpVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8);
33637 Res = DAG.getNode(ISD::TRUNCATE, dl, TmpVT, Res);
33639 // Now widen to 128 bits.
33640 unsigned NumConcats = 128 / TmpVT.getSizeInBits();
33641 MVT ConcatVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8 * NumConcats);
33642 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(TmpVT));
33643 ConcatOps[0] = Res;
33644 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
33647 Results.push_back(Res);
33648 if (IsStrict)
33649 Results.push_back(Chain);
33651 return;
33654 if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
33655 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33656 "Unexpected type action!");
33658 // Try to create a 128 bit vector, but don't exceed a 32 bit element.
33659 unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
33660 MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
33661 VT.getVectorNumElements());
33662 SDValue Res;
33663 SDValue Chain;
33664 if (IsStrict) {
33665 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
33666 {N->getOperand(0), Src});
33667 Chain = Res.getValue(1);
33668 } else
33669 Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
33671 // Preserve what we know about the size of the original result. If the
33672 // result is v2i32, we have to manually widen the assert.
33673 if (PromoteVT == MVT::v2i32)
33674 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
33675 DAG.getUNDEF(MVT::v2i32));
33677 Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
33678 Res.getValueType(), Res,
33679 DAG.getValueType(VT.getVectorElementType()));
33681 if (PromoteVT == MVT::v2i32)
33682 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
33683 DAG.getIntPtrConstant(0, dl));
33685 // Truncate back to the original width.
33686 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
33688 // Now widen to 128 bits.
33689 unsigned NumConcats = 128 / VT.getSizeInBits();
33690 MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
33691 VT.getVectorNumElements() * NumConcats);
33692 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
33693 ConcatOps[0] = Res;
33694 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
33695 Results.push_back(Res);
33696 if (IsStrict)
33697 Results.push_back(Chain);
33698 return;
33702 if (VT == MVT::v2i32) {
33703 assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&
33704 "Strict unsigned conversion requires AVX512");
33705 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33706 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33707 "Unexpected type action!");
33708 if (Src.getValueType() == MVT::v2f64) {
33709 if (!IsSigned && !Subtarget.hasAVX512()) {
33710 SDValue Res =
33711 expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
33712 Results.push_back(Res);
33713 return;
33716 unsigned Opc;
33717 if (IsStrict)
33718 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
33719 else
33720 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
33722 // If we have VLX we can emit a target specific FP_TO_UINT node,.
33723 if (!IsSigned && !Subtarget.hasVLX()) {
33724 // Otherwise we can defer to the generic legalizer which will widen
33725 // the input as well. This will be further widened during op
33726 // legalization to v8i32<-v8f64.
33727 // For strict nodes we'll need to widen ourselves.
33728 // FIXME: Fix the type legalizer to safely widen strict nodes?
33729 if (!IsStrict)
33730 return;
33731 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
33732 DAG.getConstantFP(0.0, dl, MVT::v2f64));
33733 Opc = N->getOpcode();
33735 SDValue Res;
33736 SDValue Chain;
33737 if (IsStrict) {
33738 Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
33739 {N->getOperand(0), Src});
33740 Chain = Res.getValue(1);
33741 } else {
33742 Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
33744 Results.push_back(Res);
33745 if (IsStrict)
33746 Results.push_back(Chain);
33747 return;
33750 // Custom widen strict v2f32->v2i32 by padding with zeros.
33751 // FIXME: Should generic type legalizer do this?
33752 if (Src.getValueType() == MVT::v2f32 && IsStrict) {
33753 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
33754 DAG.getConstantFP(0.0, dl, MVT::v2f32));
33755 SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
33756 {N->getOperand(0), Src});
33757 Results.push_back(Res);
33758 Results.push_back(Res.getValue(1));
33759 return;
33762 // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
33763 // so early out here.
33764 return;
33767 assert(!VT.isVector() && "Vectors should have been handled above!");
33769 if ((Subtarget.hasDQI() && VT == MVT::i64 &&
33770 (SrcVT == MVT::f32 || SrcVT == MVT::f64)) ||
33771 (Subtarget.hasFP16() && SrcVT == MVT::f16)) {
33772 assert(!Subtarget.is64Bit() && "i64 should be legal");
33773 unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
33774 // If we use a 128-bit result we might need to use a target specific node.
33775 unsigned SrcElts =
33776 std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
33777 MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
33778 MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
33779 unsigned Opc = N->getOpcode();
33780 if (NumElts != SrcElts) {
33781 if (IsStrict)
33782 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
33783 else
33784 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
33787 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
33788 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
33789 DAG.getConstantFP(0.0, dl, VecInVT), Src,
33790 ZeroIdx);
33791 SDValue Chain;
33792 if (IsStrict) {
33793 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
33794 Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
33795 Chain = Res.getValue(1);
33796 } else
33797 Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
33798 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
33799 Results.push_back(Res);
33800 if (IsStrict)
33801 Results.push_back(Chain);
33802 return;
33805 if (VT == MVT::i128 && Subtarget.isTargetWin64()) {
33806 SDValue Chain;
33807 SDValue V = LowerWin64_FP_TO_INT128(SDValue(N, 0), DAG, Chain);
33808 Results.push_back(V);
33809 if (IsStrict)
33810 Results.push_back(Chain);
33811 return;
33814 if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
33815 Results.push_back(V);
33816 if (IsStrict)
33817 Results.push_back(Chain);
33819 return;
33821 case ISD::LRINT:
33822 case ISD::LLRINT: {
33823 if (SDValue V = LRINT_LLRINTHelper(N, DAG))
33824 Results.push_back(V);
33825 return;
33828 case ISD::SINT_TO_FP:
33829 case ISD::STRICT_SINT_TO_FP:
33830 case ISD::UINT_TO_FP:
33831 case ISD::STRICT_UINT_TO_FP: {
33832 bool IsStrict = N->isStrictFPOpcode();
33833 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
33834 N->getOpcode() == ISD::STRICT_SINT_TO_FP;
33835 EVT VT = N->getValueType(0);
33836 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
33837 if (VT.getVectorElementType() == MVT::f16 && Subtarget.hasFP16() &&
33838 Subtarget.hasVLX()) {
33839 if (Src.getValueType().getVectorElementType() == MVT::i16)
33840 return;
33842 if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2i32)
33843 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
33844 IsStrict ? DAG.getConstant(0, dl, MVT::v2i32)
33845 : DAG.getUNDEF(MVT::v2i32));
33846 if (IsStrict) {
33847 unsigned Opc =
33848 IsSigned ? X86ISD::STRICT_CVTSI2P : X86ISD::STRICT_CVTUI2P;
33849 SDValue Res = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
33850 {N->getOperand(0), Src});
33851 Results.push_back(Res);
33852 Results.push_back(Res.getValue(1));
33853 } else {
33854 unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
33855 Results.push_back(DAG.getNode(Opc, dl, MVT::v8f16, Src));
33857 return;
33859 if (VT != MVT::v2f32)
33860 return;
33861 EVT SrcVT = Src.getValueType();
33862 if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
33863 if (IsStrict) {
33864 unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
33865 : X86ISD::STRICT_CVTUI2P;
33866 SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
33867 {N->getOperand(0), Src});
33868 Results.push_back(Res);
33869 Results.push_back(Res.getValue(1));
33870 } else {
33871 unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
33872 Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
33874 return;
33876 if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
33877 Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
33878 SDValue Zero = DAG.getConstant(0, dl, SrcVT);
33879 SDValue One = DAG.getConstant(1, dl, SrcVT);
33880 SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
33881 DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
33882 DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
33883 SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
33884 SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
33885 SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
33886 for (int i = 0; i != 2; ++i) {
33887 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
33888 SignSrc, DAG.getIntPtrConstant(i, dl));
33889 if (IsStrict)
33890 SignCvts[i] =
33891 DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
33892 {N->getOperand(0), Elt});
33893 else
33894 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
33896 SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
33897 SDValue Slow, Chain;
33898 if (IsStrict) {
33899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
33900 SignCvts[0].getValue(1), SignCvts[1].getValue(1));
33901 Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
33902 {Chain, SignCvt, SignCvt});
33903 Chain = Slow.getValue(1);
33904 } else {
33905 Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
33907 IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
33908 IsNeg =
33909 DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
33910 SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
33911 Results.push_back(Cvt);
33912 if (IsStrict)
33913 Results.push_back(Chain);
33914 return;
33917 if (SrcVT != MVT::v2i32)
33918 return;
33920 if (IsSigned || Subtarget.hasAVX512()) {
33921 if (!IsStrict)
33922 return;
33924 // Custom widen strict v2i32->v2f32 to avoid scalarization.
33925 // FIXME: Should generic type legalizer do this?
33926 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
33927 DAG.getConstant(0, dl, MVT::v2i32));
33928 SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
33929 {N->getOperand(0), Src});
33930 Results.push_back(Res);
33931 Results.push_back(Res.getValue(1));
33932 return;
33935 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
33936 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
33937 SDValue VBias = DAG.getConstantFP(
33938 llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::v2f64);
33939 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
33940 DAG.getBitcast(MVT::v2i64, VBias));
33941 Or = DAG.getBitcast(MVT::v2f64, Or);
33942 if (IsStrict) {
33943 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
33944 {N->getOperand(0), Or, VBias});
33945 SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
33946 {MVT::v4f32, MVT::Other},
33947 {Sub.getValue(1), Sub});
33948 Results.push_back(Res);
33949 Results.push_back(Res.getValue(1));
33950 } else {
33951 // TODO: Are there any fast-math-flags to propagate here?
33952 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
33953 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
33955 return;
33957 case ISD::STRICT_FP_ROUND:
33958 case ISD::FP_ROUND: {
33959 bool IsStrict = N->isStrictFPOpcode();
33960 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
33961 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
33962 SDValue Rnd = N->getOperand(IsStrict ? 2 : 1);
33963 EVT SrcVT = Src.getValueType();
33964 EVT VT = N->getValueType(0);
33965 SDValue V;
33966 if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2f32) {
33967 SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f32)
33968 : DAG.getUNDEF(MVT::v2f32);
33969 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src, Ext);
33971 if (!Subtarget.hasFP16() && VT.getVectorElementType() == MVT::f16) {
33972 assert(Subtarget.hasF16C() && "Cannot widen f16 without F16C");
33973 if (SrcVT.getVectorElementType() != MVT::f32)
33974 return;
33976 if (IsStrict)
33977 V = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
33978 {Chain, Src, Rnd});
33979 else
33980 V = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Src, Rnd);
33982 Results.push_back(DAG.getBitcast(MVT::v8f16, V));
33983 if (IsStrict)
33984 Results.push_back(V.getValue(1));
33985 return;
33987 if (!isTypeLegal(Src.getValueType()))
33988 return;
33989 EVT NewVT = VT.getVectorElementType() == MVT::f16 ? MVT::v8f16 : MVT::v4f32;
33990 if (IsStrict)
33991 V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {NewVT, MVT::Other},
33992 {Chain, Src});
33993 else
33994 V = DAG.getNode(X86ISD::VFPROUND, dl, NewVT, Src);
33995 Results.push_back(V);
33996 if (IsStrict)
33997 Results.push_back(V.getValue(1));
33998 return;
34000 case ISD::FP_EXTEND:
34001 case ISD::STRICT_FP_EXTEND: {
34002 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
34003 // No other ValueType for FP_EXTEND should reach this point.
34004 assert(N->getValueType(0) == MVT::v2f32 &&
34005 "Do not know how to legalize this Node");
34006 if (!Subtarget.hasFP16() || !Subtarget.hasVLX())
34007 return;
34008 bool IsStrict = N->isStrictFPOpcode();
34009 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
34010 if (Src.getValueType().getVectorElementType() != MVT::f16)
34011 return;
34012 SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f16)
34013 : DAG.getUNDEF(MVT::v2f16);
34014 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f16, Src, Ext);
34015 if (IsStrict)
34016 V = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::v4f32, MVT::Other},
34017 {N->getOperand(0), V});
34018 else
34019 V = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, V);
34020 Results.push_back(V);
34021 if (IsStrict)
34022 Results.push_back(V.getValue(1));
34023 return;
34025 case ISD::INTRINSIC_W_CHAIN: {
34026 unsigned IntNo = N->getConstantOperandVal(1);
34027 switch (IntNo) {
34028 default : llvm_unreachable("Do not know how to custom type "
34029 "legalize this intrinsic operation!");
34030 case Intrinsic::x86_rdtsc:
34031 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
34032 Results);
34033 case Intrinsic::x86_rdtscp:
34034 return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
34035 Results);
34036 case Intrinsic::x86_rdpmc:
34037 expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
34038 Results);
34039 return;
34040 case Intrinsic::x86_rdpru:
34041 expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPRU, X86::ECX, Subtarget,
34042 Results);
34043 return;
34044 case Intrinsic::x86_xgetbv:
34045 expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
34046 Results);
34047 return;
34050 case ISD::READCYCLECOUNTER: {
34051 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
34053 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
34054 EVT T = N->getValueType(0);
34055 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
34056 bool Regs64bit = T == MVT::i128;
34057 assert((!Regs64bit || Subtarget.canUseCMPXCHG16B()) &&
34058 "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
34059 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
34060 SDValue cpInL, cpInH;
34061 std::tie(cpInL, cpInH) =
34062 DAG.SplitScalar(N->getOperand(2), dl, HalfT, HalfT);
34063 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
34064 Regs64bit ? X86::RAX : X86::EAX, cpInL, SDValue());
34065 cpInH =
34066 DAG.getCopyToReg(cpInL.getValue(0), dl, Regs64bit ? X86::RDX : X86::EDX,
34067 cpInH, cpInL.getValue(1));
34068 SDValue swapInL, swapInH;
34069 std::tie(swapInL, swapInH) =
34070 DAG.SplitScalar(N->getOperand(3), dl, HalfT, HalfT);
34071 swapInH =
34072 DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
34073 swapInH, cpInH.getValue(1));
34075 // In 64-bit mode we might need the base pointer in RBX, but we can't know
34076 // until later. So we keep the RBX input in a vreg and use a custom
34077 // inserter.
34078 // Since RBX will be a reserved register the register allocator will not
34079 // make sure its value will be properly saved and restored around this
34080 // live-range.
34081 SDValue Result;
34082 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
34083 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
34084 if (Regs64bit) {
34085 SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
34086 swapInH.getValue(1)};
34087 Result =
34088 DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
34089 } else {
34090 swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
34091 swapInH.getValue(1));
34092 SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
34093 swapInL.getValue(1)};
34094 Result =
34095 DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
34098 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
34099 Regs64bit ? X86::RAX : X86::EAX,
34100 HalfT, Result.getValue(1));
34101 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
34102 Regs64bit ? X86::RDX : X86::EDX,
34103 HalfT, cpOutL.getValue(2));
34104 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
34106 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
34107 MVT::i32, cpOutH.getValue(2));
34108 SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
34109 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
34111 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
34112 Results.push_back(Success);
34113 Results.push_back(EFLAGS.getValue(1));
34114 return;
34116 case ISD::ATOMIC_LOAD: {
34117 assert(
34118 (N->getValueType(0) == MVT::i64 || N->getValueType(0) == MVT::i128) &&
34119 "Unexpected VT!");
34120 bool NoImplicitFloatOps =
34121 DAG.getMachineFunction().getFunction().hasFnAttribute(
34122 Attribute::NoImplicitFloat);
34123 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
34124 auto *Node = cast<AtomicSDNode>(N);
34126 if (N->getValueType(0) == MVT::i128) {
34127 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
34128 SDValue Ld = DAG.getLoad(MVT::v2i64, dl, Node->getChain(),
34129 Node->getBasePtr(), Node->getMemOperand());
34130 SDValue ResL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
34131 DAG.getIntPtrConstant(0, dl));
34132 SDValue ResH = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
34133 DAG.getIntPtrConstant(1, dl));
34134 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0),
34135 {ResL, ResH}));
34136 Results.push_back(Ld.getValue(1));
34137 return;
34139 break;
34141 if (Subtarget.hasSSE1()) {
34142 // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
34143 // Then extract the lower 64-bits.
34144 MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
34145 SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
34146 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
34147 SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
34148 MVT::i64, Node->getMemOperand());
34149 if (Subtarget.hasSSE2()) {
34150 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
34151 DAG.getIntPtrConstant(0, dl));
34152 Results.push_back(Res);
34153 Results.push_back(Ld.getValue(1));
34154 return;
34156 // We use an alternative sequence for SSE1 that extracts as v2f32 and
34157 // then casts to i64. This avoids a 128-bit stack temporary being
34158 // created by type legalization if we were to cast v4f32->v2i64.
34159 SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
34160 DAG.getIntPtrConstant(0, dl));
34161 Res = DAG.getBitcast(MVT::i64, Res);
34162 Results.push_back(Res);
34163 Results.push_back(Ld.getValue(1));
34164 return;
34166 if (Subtarget.hasX87()) {
34167 // First load this into an 80-bit X87 register. This will put the whole
34168 // integer into the significand.
34169 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
34170 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
34171 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
34172 dl, Tys, Ops, MVT::i64,
34173 Node->getMemOperand());
34174 SDValue Chain = Result.getValue(1);
34176 // Now store the X87 register to a stack temporary and convert to i64.
34177 // This store is not atomic and doesn't need to be.
34178 // FIXME: We don't need a stack temporary if the result of the load
34179 // is already being stored. We could just directly store there.
34180 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
34181 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
34182 MachinePointerInfo MPI =
34183 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
34184 SDValue StoreOps[] = { Chain, Result, StackPtr };
34185 Chain = DAG.getMemIntrinsicNode(
34186 X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
34187 MPI, std::nullopt /*Align*/, MachineMemOperand::MOStore);
34189 // Finally load the value back from the stack temporary and return it.
34190 // This load is not atomic and doesn't need to be.
34191 // This load will be further type legalized.
34192 Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
34193 Results.push_back(Result);
34194 Results.push_back(Result.getValue(1));
34195 return;
34198 // TODO: Use MOVLPS when SSE1 is available?
34199 // Delegate to generic TypeLegalization. Situations we can really handle
34200 // should have already been dealt with by AtomicExpandPass.cpp.
34201 break;
34203 case ISD::ATOMIC_SWAP:
34204 case ISD::ATOMIC_LOAD_ADD:
34205 case ISD::ATOMIC_LOAD_SUB:
34206 case ISD::ATOMIC_LOAD_AND:
34207 case ISD::ATOMIC_LOAD_OR:
34208 case ISD::ATOMIC_LOAD_XOR:
34209 case ISD::ATOMIC_LOAD_NAND:
34210 case ISD::ATOMIC_LOAD_MIN:
34211 case ISD::ATOMIC_LOAD_MAX:
34212 case ISD::ATOMIC_LOAD_UMIN:
34213 case ISD::ATOMIC_LOAD_UMAX:
34214 // Delegate to generic TypeLegalization. Situations we can really handle
34215 // should have already been dealt with by AtomicExpandPass.cpp.
34216 break;
34218 case ISD::BITCAST: {
34219 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
34220 EVT DstVT = N->getValueType(0);
34221 EVT SrcVT = N->getOperand(0).getValueType();
34223 // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
34224 // we can split using the k-register rather than memory.
34225 if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
34226 assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
34227 SDValue Lo, Hi;
34228 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
34229 Lo = DAG.getBitcast(MVT::i32, Lo);
34230 Hi = DAG.getBitcast(MVT::i32, Hi);
34231 SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
34232 Results.push_back(Res);
34233 return;
34236 if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
34237 // FIXME: Use v4f32 for SSE1?
34238 assert(Subtarget.hasSSE2() && "Requires SSE2");
34239 assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
34240 "Unexpected type action!");
34241 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
34242 SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
34243 N->getOperand(0));
34244 Res = DAG.getBitcast(WideVT, Res);
34245 Results.push_back(Res);
34246 return;
34249 return;
34251 case ISD::MGATHER: {
34252 EVT VT = N->getValueType(0);
34253 if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
34254 (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
34255 auto *Gather = cast<MaskedGatherSDNode>(N);
34256 SDValue Index = Gather->getIndex();
34257 if (Index.getValueType() != MVT::v2i64)
34258 return;
34259 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34260 "Unexpected type action!");
34261 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
34262 SDValue Mask = Gather->getMask();
34263 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
34264 SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
34265 Gather->getPassThru(),
34266 DAG.getUNDEF(VT));
34267 if (!Subtarget.hasVLX()) {
34268 // We need to widen the mask, but the instruction will only use 2
34269 // of its elements. So we can use undef.
34270 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
34271 DAG.getUNDEF(MVT::v2i1));
34272 Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
34274 SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
34275 Gather->getBasePtr(), Index, Gather->getScale() };
34276 SDValue Res = DAG.getMemIntrinsicNode(
34277 X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
34278 Gather->getMemoryVT(), Gather->getMemOperand());
34279 Results.push_back(Res);
34280 Results.push_back(Res.getValue(1));
34281 return;
34283 return;
34285 case ISD::LOAD: {
34286 // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
34287 // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
34288 // cast since type legalization will try to use an i64 load.
34289 MVT VT = N->getSimpleValueType(0);
34290 assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
34291 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
34292 "Unexpected type action!");
34293 if (!ISD::isNON_EXTLoad(N))
34294 return;
34295 auto *Ld = cast<LoadSDNode>(N);
34296 if (Subtarget.hasSSE2()) {
34297 MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
34298 SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
34299 Ld->getPointerInfo(), Ld->getOriginalAlign(),
34300 Ld->getMemOperand()->getFlags());
34301 SDValue Chain = Res.getValue(1);
34302 MVT VecVT = MVT::getVectorVT(LdVT, 2);
34303 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
34304 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
34305 Res = DAG.getBitcast(WideVT, Res);
34306 Results.push_back(Res);
34307 Results.push_back(Chain);
34308 return;
34310 assert(Subtarget.hasSSE1() && "Expected SSE");
34311 SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
34312 SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
34313 SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
34314 MVT::i64, Ld->getMemOperand());
34315 Results.push_back(Res);
34316 Results.push_back(Res.getValue(1));
34317 return;
34319 case ISD::ADDRSPACECAST: {
34320 SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
34321 Results.push_back(V);
34322 return;
34324 case ISD::BITREVERSE: {
34325 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
34326 assert((Subtarget.hasXOP() || Subtarget.hasGFNI()) && "Expected XOP/GFNI");
34327 // We can use VPPERM/GF2P8AFFINEQB by copying to a vector register and back.
34328 // We'll need to move the scalar in two i32 pieces.
34329 Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
34330 return;
34332 case ISD::EXTRACT_VECTOR_ELT: {
34333 // f16 = extract vXf16 %vec, i64 %idx
34334 assert(N->getSimpleValueType(0) == MVT::f16 &&
34335 "Unexpected Value type of EXTRACT_VECTOR_ELT!");
34336 assert(Subtarget.hasFP16() && "Expected FP16");
34337 SDValue VecOp = N->getOperand(0);
34338 EVT ExtVT = VecOp.getValueType().changeVectorElementTypeToInteger();
34339 SDValue Split = DAG.getBitcast(ExtVT, N->getOperand(0));
34340 Split = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Split,
34341 N->getOperand(1));
34342 Split = DAG.getBitcast(MVT::f16, Split);
34343 Results.push_back(Split);
34344 return;
34349 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
34350 switch ((X86ISD::NodeType)Opcode) {
34351 case X86ISD::FIRST_NUMBER: break;
34352 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
34353 NODE_NAME_CASE(BSF)
34354 NODE_NAME_CASE(BSR)
34355 NODE_NAME_CASE(FSHL)
34356 NODE_NAME_CASE(FSHR)
34357 NODE_NAME_CASE(FAND)
34358 NODE_NAME_CASE(FANDN)
34359 NODE_NAME_CASE(FOR)
34360 NODE_NAME_CASE(FXOR)
34361 NODE_NAME_CASE(FILD)
34362 NODE_NAME_CASE(FIST)
34363 NODE_NAME_CASE(FP_TO_INT_IN_MEM)
34364 NODE_NAME_CASE(FLD)
34365 NODE_NAME_CASE(FST)
34366 NODE_NAME_CASE(CALL)
34367 NODE_NAME_CASE(CALL_RVMARKER)
34368 NODE_NAME_CASE(BT)
34369 NODE_NAME_CASE(CMP)
34370 NODE_NAME_CASE(FCMP)
34371 NODE_NAME_CASE(STRICT_FCMP)
34372 NODE_NAME_CASE(STRICT_FCMPS)
34373 NODE_NAME_CASE(COMI)
34374 NODE_NAME_CASE(UCOMI)
34375 NODE_NAME_CASE(COMX)
34376 NODE_NAME_CASE(UCOMX)
34377 NODE_NAME_CASE(CMPM)
34378 NODE_NAME_CASE(CMPMM)
34379 NODE_NAME_CASE(STRICT_CMPM)
34380 NODE_NAME_CASE(CMPMM_SAE)
34381 NODE_NAME_CASE(SETCC)
34382 NODE_NAME_CASE(SETCC_CARRY)
34383 NODE_NAME_CASE(FSETCC)
34384 NODE_NAME_CASE(FSETCCM)
34385 NODE_NAME_CASE(FSETCCM_SAE)
34386 NODE_NAME_CASE(CMOV)
34387 NODE_NAME_CASE(BRCOND)
34388 NODE_NAME_CASE(RET_GLUE)
34389 NODE_NAME_CASE(IRET)
34390 NODE_NAME_CASE(REP_STOS)
34391 NODE_NAME_CASE(REP_MOVS)
34392 NODE_NAME_CASE(GlobalBaseReg)
34393 NODE_NAME_CASE(Wrapper)
34394 NODE_NAME_CASE(WrapperRIP)
34395 NODE_NAME_CASE(MOVQ2DQ)
34396 NODE_NAME_CASE(MOVDQ2Q)
34397 NODE_NAME_CASE(MMX_MOVD2W)
34398 NODE_NAME_CASE(MMX_MOVW2D)
34399 NODE_NAME_CASE(PEXTRB)
34400 NODE_NAME_CASE(PEXTRW)
34401 NODE_NAME_CASE(INSERTPS)
34402 NODE_NAME_CASE(PINSRB)
34403 NODE_NAME_CASE(PINSRW)
34404 NODE_NAME_CASE(PSHUFB)
34405 NODE_NAME_CASE(ANDNP)
34406 NODE_NAME_CASE(BLENDI)
34407 NODE_NAME_CASE(BLENDV)
34408 NODE_NAME_CASE(HADD)
34409 NODE_NAME_CASE(HSUB)
34410 NODE_NAME_CASE(FHADD)
34411 NODE_NAME_CASE(FHSUB)
34412 NODE_NAME_CASE(CONFLICT)
34413 NODE_NAME_CASE(FMAX)
34414 NODE_NAME_CASE(FMAXS)
34415 NODE_NAME_CASE(FMAX_SAE)
34416 NODE_NAME_CASE(FMAXS_SAE)
34417 NODE_NAME_CASE(STRICT_FMAX)
34418 NODE_NAME_CASE(FMIN)
34419 NODE_NAME_CASE(FMINS)
34420 NODE_NAME_CASE(FMIN_SAE)
34421 NODE_NAME_CASE(FMINS_SAE)
34422 NODE_NAME_CASE(STRICT_FMIN)
34423 NODE_NAME_CASE(FMAXC)
34424 NODE_NAME_CASE(FMINC)
34425 NODE_NAME_CASE(FRSQRT)
34426 NODE_NAME_CASE(FRCP)
34427 NODE_NAME_CASE(EXTRQI)
34428 NODE_NAME_CASE(INSERTQI)
34429 NODE_NAME_CASE(TLSADDR)
34430 NODE_NAME_CASE(TLSBASEADDR)
34431 NODE_NAME_CASE(TLSCALL)
34432 NODE_NAME_CASE(TLSDESC)
34433 NODE_NAME_CASE(EH_SJLJ_SETJMP)
34434 NODE_NAME_CASE(EH_SJLJ_LONGJMP)
34435 NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
34436 NODE_NAME_CASE(EH_RETURN)
34437 NODE_NAME_CASE(TC_RETURN)
34438 NODE_NAME_CASE(FNSTCW16m)
34439 NODE_NAME_CASE(FLDCW16m)
34440 NODE_NAME_CASE(FNSTENVm)
34441 NODE_NAME_CASE(FLDENVm)
34442 NODE_NAME_CASE(LCMPXCHG_DAG)
34443 NODE_NAME_CASE(LCMPXCHG8_DAG)
34444 NODE_NAME_CASE(LCMPXCHG16_DAG)
34445 NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
34446 NODE_NAME_CASE(LADD)
34447 NODE_NAME_CASE(LSUB)
34448 NODE_NAME_CASE(LOR)
34449 NODE_NAME_CASE(LXOR)
34450 NODE_NAME_CASE(LAND)
34451 NODE_NAME_CASE(LBTS)
34452 NODE_NAME_CASE(LBTC)
34453 NODE_NAME_CASE(LBTR)
34454 NODE_NAME_CASE(LBTS_RM)
34455 NODE_NAME_CASE(LBTC_RM)
34456 NODE_NAME_CASE(LBTR_RM)
34457 NODE_NAME_CASE(AADD)
34458 NODE_NAME_CASE(AOR)
34459 NODE_NAME_CASE(AXOR)
34460 NODE_NAME_CASE(AAND)
34461 NODE_NAME_CASE(VZEXT_MOVL)
34462 NODE_NAME_CASE(VZEXT_LOAD)
34463 NODE_NAME_CASE(VEXTRACT_STORE)
34464 NODE_NAME_CASE(VTRUNC)
34465 NODE_NAME_CASE(VTRUNCS)
34466 NODE_NAME_CASE(VTRUNCUS)
34467 NODE_NAME_CASE(VMTRUNC)
34468 NODE_NAME_CASE(VMTRUNCS)
34469 NODE_NAME_CASE(VMTRUNCUS)
34470 NODE_NAME_CASE(VTRUNCSTORES)
34471 NODE_NAME_CASE(VTRUNCSTOREUS)
34472 NODE_NAME_CASE(VMTRUNCSTORES)
34473 NODE_NAME_CASE(VMTRUNCSTOREUS)
34474 NODE_NAME_CASE(VFPEXT)
34475 NODE_NAME_CASE(STRICT_VFPEXT)
34476 NODE_NAME_CASE(VFPEXT_SAE)
34477 NODE_NAME_CASE(VFPEXTS)
34478 NODE_NAME_CASE(VFPEXTS_SAE)
34479 NODE_NAME_CASE(VFPROUND)
34480 NODE_NAME_CASE(VFPROUND2)
34481 NODE_NAME_CASE(VFPROUND2_RND)
34482 NODE_NAME_CASE(STRICT_VFPROUND)
34483 NODE_NAME_CASE(VMFPROUND)
34484 NODE_NAME_CASE(VFPROUND_RND)
34485 NODE_NAME_CASE(VFPROUNDS)
34486 NODE_NAME_CASE(VFPROUNDS_RND)
34487 NODE_NAME_CASE(VSHLDQ)
34488 NODE_NAME_CASE(VSRLDQ)
34489 NODE_NAME_CASE(VSHL)
34490 NODE_NAME_CASE(VSRL)
34491 NODE_NAME_CASE(VSRA)
34492 NODE_NAME_CASE(VSHLI)
34493 NODE_NAME_CASE(VSRLI)
34494 NODE_NAME_CASE(VSRAI)
34495 NODE_NAME_CASE(VSHLV)
34496 NODE_NAME_CASE(VSRLV)
34497 NODE_NAME_CASE(VSRAV)
34498 NODE_NAME_CASE(VROTLI)
34499 NODE_NAME_CASE(VROTRI)
34500 NODE_NAME_CASE(VPPERM)
34501 NODE_NAME_CASE(CMPP)
34502 NODE_NAME_CASE(STRICT_CMPP)
34503 NODE_NAME_CASE(PCMPEQ)
34504 NODE_NAME_CASE(PCMPGT)
34505 NODE_NAME_CASE(PHMINPOS)
34506 NODE_NAME_CASE(ADD)
34507 NODE_NAME_CASE(SUB)
34508 NODE_NAME_CASE(ADC)
34509 NODE_NAME_CASE(SBB)
34510 NODE_NAME_CASE(SMUL)
34511 NODE_NAME_CASE(UMUL)
34512 NODE_NAME_CASE(OR)
34513 NODE_NAME_CASE(XOR)
34514 NODE_NAME_CASE(AND)
34515 NODE_NAME_CASE(BEXTR)
34516 NODE_NAME_CASE(BEXTRI)
34517 NODE_NAME_CASE(BZHI)
34518 NODE_NAME_CASE(PDEP)
34519 NODE_NAME_CASE(PEXT)
34520 NODE_NAME_CASE(MUL_IMM)
34521 NODE_NAME_CASE(MOVMSK)
34522 NODE_NAME_CASE(PTEST)
34523 NODE_NAME_CASE(TESTP)
34524 NODE_NAME_CASE(KORTEST)
34525 NODE_NAME_CASE(KTEST)
34526 NODE_NAME_CASE(KADD)
34527 NODE_NAME_CASE(KSHIFTL)
34528 NODE_NAME_CASE(KSHIFTR)
34529 NODE_NAME_CASE(PACKSS)
34530 NODE_NAME_CASE(PACKUS)
34531 NODE_NAME_CASE(PALIGNR)
34532 NODE_NAME_CASE(VALIGN)
34533 NODE_NAME_CASE(VSHLD)
34534 NODE_NAME_CASE(VSHRD)
34535 NODE_NAME_CASE(VSHLDV)
34536 NODE_NAME_CASE(VSHRDV)
34537 NODE_NAME_CASE(PSHUFD)
34538 NODE_NAME_CASE(PSHUFHW)
34539 NODE_NAME_CASE(PSHUFLW)
34540 NODE_NAME_CASE(SHUFP)
34541 NODE_NAME_CASE(SHUF128)
34542 NODE_NAME_CASE(MOVLHPS)
34543 NODE_NAME_CASE(MOVHLPS)
34544 NODE_NAME_CASE(MOVDDUP)
34545 NODE_NAME_CASE(MOVSHDUP)
34546 NODE_NAME_CASE(MOVSLDUP)
34547 NODE_NAME_CASE(MOVSD)
34548 NODE_NAME_CASE(MOVSS)
34549 NODE_NAME_CASE(MOVSH)
34550 NODE_NAME_CASE(UNPCKL)
34551 NODE_NAME_CASE(UNPCKH)
34552 NODE_NAME_CASE(VBROADCAST)
34553 NODE_NAME_CASE(VBROADCAST_LOAD)
34554 NODE_NAME_CASE(VBROADCASTM)
34555 NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
34556 NODE_NAME_CASE(VPERMILPV)
34557 NODE_NAME_CASE(VPERMILPI)
34558 NODE_NAME_CASE(VPERM2X128)
34559 NODE_NAME_CASE(VPERMV)
34560 NODE_NAME_CASE(VPERMV3)
34561 NODE_NAME_CASE(VPERMI)
34562 NODE_NAME_CASE(VPTERNLOG)
34563 NODE_NAME_CASE(VFIXUPIMM)
34564 NODE_NAME_CASE(VFIXUPIMM_SAE)
34565 NODE_NAME_CASE(VFIXUPIMMS)
34566 NODE_NAME_CASE(VFIXUPIMMS_SAE)
34567 NODE_NAME_CASE(VRANGE)
34568 NODE_NAME_CASE(VRANGE_SAE)
34569 NODE_NAME_CASE(VRANGES)
34570 NODE_NAME_CASE(VRANGES_SAE)
34571 NODE_NAME_CASE(PMULUDQ)
34572 NODE_NAME_CASE(PMULDQ)
34573 NODE_NAME_CASE(PSADBW)
34574 NODE_NAME_CASE(DBPSADBW)
34575 NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
34576 NODE_NAME_CASE(VAARG_64)
34577 NODE_NAME_CASE(VAARG_X32)
34578 NODE_NAME_CASE(DYN_ALLOCA)
34579 NODE_NAME_CASE(MFENCE)
34580 NODE_NAME_CASE(SEG_ALLOCA)
34581 NODE_NAME_CASE(PROBED_ALLOCA)
34582 NODE_NAME_CASE(RDRAND)
34583 NODE_NAME_CASE(RDSEED)
34584 NODE_NAME_CASE(RDPKRU)
34585 NODE_NAME_CASE(WRPKRU)
34586 NODE_NAME_CASE(VPMADDUBSW)
34587 NODE_NAME_CASE(VPMADDWD)
34588 NODE_NAME_CASE(VPSHA)
34589 NODE_NAME_CASE(VPSHL)
34590 NODE_NAME_CASE(VPCOM)
34591 NODE_NAME_CASE(VPCOMU)
34592 NODE_NAME_CASE(VPERMIL2)
34593 NODE_NAME_CASE(FMSUB)
34594 NODE_NAME_CASE(STRICT_FMSUB)
34595 NODE_NAME_CASE(FNMADD)
34596 NODE_NAME_CASE(STRICT_FNMADD)
34597 NODE_NAME_CASE(FNMSUB)
34598 NODE_NAME_CASE(STRICT_FNMSUB)
34599 NODE_NAME_CASE(FMADDSUB)
34600 NODE_NAME_CASE(FMSUBADD)
34601 NODE_NAME_CASE(FMADD_RND)
34602 NODE_NAME_CASE(FNMADD_RND)
34603 NODE_NAME_CASE(FMSUB_RND)
34604 NODE_NAME_CASE(FNMSUB_RND)
34605 NODE_NAME_CASE(FMADDSUB_RND)
34606 NODE_NAME_CASE(FMSUBADD_RND)
34607 NODE_NAME_CASE(VFMADDC)
34608 NODE_NAME_CASE(VFMADDC_RND)
34609 NODE_NAME_CASE(VFCMADDC)
34610 NODE_NAME_CASE(VFCMADDC_RND)
34611 NODE_NAME_CASE(VFMULC)
34612 NODE_NAME_CASE(VFMULC_RND)
34613 NODE_NAME_CASE(VFCMULC)
34614 NODE_NAME_CASE(VFCMULC_RND)
34615 NODE_NAME_CASE(VFMULCSH)
34616 NODE_NAME_CASE(VFMULCSH_RND)
34617 NODE_NAME_CASE(VFCMULCSH)
34618 NODE_NAME_CASE(VFCMULCSH_RND)
34619 NODE_NAME_CASE(VFMADDCSH)
34620 NODE_NAME_CASE(VFMADDCSH_RND)
34621 NODE_NAME_CASE(VFCMADDCSH)
34622 NODE_NAME_CASE(VFCMADDCSH_RND)
34623 NODE_NAME_CASE(VPMADD52H)
34624 NODE_NAME_CASE(VPMADD52L)
34625 NODE_NAME_CASE(VRNDSCALE)
34626 NODE_NAME_CASE(STRICT_VRNDSCALE)
34627 NODE_NAME_CASE(VRNDSCALE_SAE)
34628 NODE_NAME_CASE(VRNDSCALES)
34629 NODE_NAME_CASE(VRNDSCALES_SAE)
34630 NODE_NAME_CASE(VREDUCE)
34631 NODE_NAME_CASE(VREDUCE_SAE)
34632 NODE_NAME_CASE(VREDUCES)
34633 NODE_NAME_CASE(VREDUCES_SAE)
34634 NODE_NAME_CASE(VGETMANT)
34635 NODE_NAME_CASE(VGETMANT_SAE)
34636 NODE_NAME_CASE(VGETMANTS)
34637 NODE_NAME_CASE(VGETMANTS_SAE)
34638 NODE_NAME_CASE(PCMPESTR)
34639 NODE_NAME_CASE(PCMPISTR)
34640 NODE_NAME_CASE(XTEST)
34641 NODE_NAME_CASE(COMPRESS)
34642 NODE_NAME_CASE(EXPAND)
34643 NODE_NAME_CASE(SELECTS)
34644 NODE_NAME_CASE(ADDSUB)
34645 NODE_NAME_CASE(RCP14)
34646 NODE_NAME_CASE(RCP14S)
34647 NODE_NAME_CASE(RSQRT14)
34648 NODE_NAME_CASE(RSQRT14S)
34649 NODE_NAME_CASE(FADD_RND)
34650 NODE_NAME_CASE(FADDS)
34651 NODE_NAME_CASE(FADDS_RND)
34652 NODE_NAME_CASE(FSUB_RND)
34653 NODE_NAME_CASE(FSUBS)
34654 NODE_NAME_CASE(FSUBS_RND)
34655 NODE_NAME_CASE(FMUL_RND)
34656 NODE_NAME_CASE(FMULS)
34657 NODE_NAME_CASE(FMULS_RND)
34658 NODE_NAME_CASE(FDIV_RND)
34659 NODE_NAME_CASE(FDIVS)
34660 NODE_NAME_CASE(FDIVS_RND)
34661 NODE_NAME_CASE(FSQRT_RND)
34662 NODE_NAME_CASE(FSQRTS)
34663 NODE_NAME_CASE(FSQRTS_RND)
34664 NODE_NAME_CASE(FGETEXP)
34665 NODE_NAME_CASE(FGETEXP_SAE)
34666 NODE_NAME_CASE(FGETEXPS)
34667 NODE_NAME_CASE(FGETEXPS_SAE)
34668 NODE_NAME_CASE(SCALEF)
34669 NODE_NAME_CASE(SCALEF_RND)
34670 NODE_NAME_CASE(SCALEFS)
34671 NODE_NAME_CASE(SCALEFS_RND)
34672 NODE_NAME_CASE(MULHRS)
34673 NODE_NAME_CASE(SINT_TO_FP_RND)
34674 NODE_NAME_CASE(UINT_TO_FP_RND)
34675 NODE_NAME_CASE(CVTTP2SI)
34676 NODE_NAME_CASE(CVTTP2UI)
34677 NODE_NAME_CASE(STRICT_CVTTP2SI)
34678 NODE_NAME_CASE(STRICT_CVTTP2UI)
34679 NODE_NAME_CASE(MCVTTP2SI)
34680 NODE_NAME_CASE(MCVTTP2UI)
34681 NODE_NAME_CASE(CVTTP2SI_SAE)
34682 NODE_NAME_CASE(CVTTP2UI_SAE)
34683 NODE_NAME_CASE(CVTTS2SI)
34684 NODE_NAME_CASE(CVTTS2UI)
34685 NODE_NAME_CASE(CVTTS2SI_SAE)
34686 NODE_NAME_CASE(CVTTS2UI_SAE)
34687 NODE_NAME_CASE(CVTSI2P)
34688 NODE_NAME_CASE(CVTUI2P)
34689 NODE_NAME_CASE(STRICT_CVTSI2P)
34690 NODE_NAME_CASE(STRICT_CVTUI2P)
34691 NODE_NAME_CASE(MCVTSI2P)
34692 NODE_NAME_CASE(MCVTUI2P)
34693 NODE_NAME_CASE(VFPCLASS)
34694 NODE_NAME_CASE(VFPCLASSS)
34695 NODE_NAME_CASE(MULTISHIFT)
34696 NODE_NAME_CASE(SCALAR_SINT_TO_FP)
34697 NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
34698 NODE_NAME_CASE(SCALAR_UINT_TO_FP)
34699 NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
34700 NODE_NAME_CASE(CVTPS2PH)
34701 NODE_NAME_CASE(STRICT_CVTPS2PH)
34702 NODE_NAME_CASE(CVTPS2PH_SAE)
34703 NODE_NAME_CASE(MCVTPS2PH)
34704 NODE_NAME_CASE(MCVTPS2PH_SAE)
34705 NODE_NAME_CASE(CVTPH2PS)
34706 NODE_NAME_CASE(STRICT_CVTPH2PS)
34707 NODE_NAME_CASE(CVTPH2PS_SAE)
34708 NODE_NAME_CASE(CVTP2SI)
34709 NODE_NAME_CASE(CVTP2UI)
34710 NODE_NAME_CASE(MCVTP2SI)
34711 NODE_NAME_CASE(MCVTP2UI)
34712 NODE_NAME_CASE(CVTP2SI_RND)
34713 NODE_NAME_CASE(CVTP2UI_RND)
34714 NODE_NAME_CASE(CVTS2SI)
34715 NODE_NAME_CASE(CVTS2UI)
34716 NODE_NAME_CASE(CVTS2SI_RND)
34717 NODE_NAME_CASE(CVTS2UI_RND)
34718 NODE_NAME_CASE(CVTNEPS2BF16)
34719 NODE_NAME_CASE(MCVTNEPS2BF16)
34720 NODE_NAME_CASE(DPBF16PS)
34721 NODE_NAME_CASE(DPFP16PS)
34722 NODE_NAME_CASE(MPSADBW)
34723 NODE_NAME_CASE(LWPINS)
34724 NODE_NAME_CASE(MGATHER)
34725 NODE_NAME_CASE(MSCATTER)
34726 NODE_NAME_CASE(VPDPBUSD)
34727 NODE_NAME_CASE(VPDPBUSDS)
34728 NODE_NAME_CASE(VPDPWSSD)
34729 NODE_NAME_CASE(VPDPWSSDS)
34730 NODE_NAME_CASE(VPSHUFBITQMB)
34731 NODE_NAME_CASE(GF2P8MULB)
34732 NODE_NAME_CASE(GF2P8AFFINEQB)
34733 NODE_NAME_CASE(GF2P8AFFINEINVQB)
34734 NODE_NAME_CASE(NT_CALL)
34735 NODE_NAME_CASE(NT_BRIND)
34736 NODE_NAME_CASE(UMWAIT)
34737 NODE_NAME_CASE(TPAUSE)
34738 NODE_NAME_CASE(ENQCMD)
34739 NODE_NAME_CASE(ENQCMDS)
34740 NODE_NAME_CASE(VP2INTERSECT)
34741 NODE_NAME_CASE(VPDPBSUD)
34742 NODE_NAME_CASE(VPDPBSUDS)
34743 NODE_NAME_CASE(VPDPBUUD)
34744 NODE_NAME_CASE(VPDPBUUDS)
34745 NODE_NAME_CASE(VPDPBSSD)
34746 NODE_NAME_CASE(VPDPBSSDS)
34747 NODE_NAME_CASE(VPDPWSUD)
34748 NODE_NAME_CASE(VPDPWSUDS)
34749 NODE_NAME_CASE(VPDPWUSD)
34750 NODE_NAME_CASE(VPDPWUSDS)
34751 NODE_NAME_CASE(VPDPWUUD)
34752 NODE_NAME_CASE(VPDPWUUDS)
34753 NODE_NAME_CASE(VMINMAX)
34754 NODE_NAME_CASE(VMINMAX_SAE)
34755 NODE_NAME_CASE(VMINMAXS)
34756 NODE_NAME_CASE(VMINMAXS_SAE)
34757 NODE_NAME_CASE(CVTP2IBS)
34758 NODE_NAME_CASE(CVTP2IUBS)
34759 NODE_NAME_CASE(CVTP2IBS_RND)
34760 NODE_NAME_CASE(CVTP2IUBS_RND)
34761 NODE_NAME_CASE(CVTTP2IBS)
34762 NODE_NAME_CASE(CVTTP2IUBS)
34763 NODE_NAME_CASE(CVTTP2IBS_SAE)
34764 NODE_NAME_CASE(CVTTP2IUBS_SAE)
34765 NODE_NAME_CASE(VCVTNE2PH2BF8)
34766 NODE_NAME_CASE(VCVTNE2PH2BF8S)
34767 NODE_NAME_CASE(VCVTNE2PH2HF8)
34768 NODE_NAME_CASE(VCVTNE2PH2HF8S)
34769 NODE_NAME_CASE(VCVTBIASPH2BF8)
34770 NODE_NAME_CASE(VCVTBIASPH2BF8S)
34771 NODE_NAME_CASE(VCVTBIASPH2HF8)
34772 NODE_NAME_CASE(VCVTBIASPH2HF8S)
34773 NODE_NAME_CASE(VCVTNEPH2BF8)
34774 NODE_NAME_CASE(VCVTNEPH2BF8S)
34775 NODE_NAME_CASE(VCVTNEPH2HF8)
34776 NODE_NAME_CASE(VCVTNEPH2HF8S)
34777 NODE_NAME_CASE(VMCVTBIASPH2BF8)
34778 NODE_NAME_CASE(VMCVTBIASPH2BF8S)
34779 NODE_NAME_CASE(VMCVTBIASPH2HF8)
34780 NODE_NAME_CASE(VMCVTBIASPH2HF8S)
34781 NODE_NAME_CASE(VMCVTNEPH2BF8)
34782 NODE_NAME_CASE(VMCVTNEPH2BF8S)
34783 NODE_NAME_CASE(VMCVTNEPH2HF8)
34784 NODE_NAME_CASE(VMCVTNEPH2HF8S)
34785 NODE_NAME_CASE(VCVTHF82PH)
34786 NODE_NAME_CASE(AESENC128KL)
34787 NODE_NAME_CASE(AESDEC128KL)
34788 NODE_NAME_CASE(AESENC256KL)
34789 NODE_NAME_CASE(AESDEC256KL)
34790 NODE_NAME_CASE(AESENCWIDE128KL)
34791 NODE_NAME_CASE(AESDECWIDE128KL)
34792 NODE_NAME_CASE(AESENCWIDE256KL)
34793 NODE_NAME_CASE(AESDECWIDE256KL)
34794 NODE_NAME_CASE(CMPCCXADD)
34795 NODE_NAME_CASE(TESTUI)
34796 NODE_NAME_CASE(FP80_ADD)
34797 NODE_NAME_CASE(STRICT_FP80_ADD)
34798 NODE_NAME_CASE(CCMP)
34799 NODE_NAME_CASE(CTEST)
34800 NODE_NAME_CASE(CLOAD)
34801 NODE_NAME_CASE(CSTORE)
34802 NODE_NAME_CASE(CVTTS2SIS)
34803 NODE_NAME_CASE(CVTTS2UIS)
34804 NODE_NAME_CASE(CVTTS2SIS_SAE)
34805 NODE_NAME_CASE(CVTTS2UIS_SAE)
34806 NODE_NAME_CASE(CVTTP2SIS)
34807 NODE_NAME_CASE(MCVTTP2SIS)
34808 NODE_NAME_CASE(CVTTP2UIS_SAE)
34809 NODE_NAME_CASE(CVTTP2SIS_SAE)
34810 NODE_NAME_CASE(CVTTP2UIS)
34811 NODE_NAME_CASE(MCVTTP2UIS)
34813 return nullptr;
34814 #undef NODE_NAME_CASE
34817 /// Return true if the addressing mode represented by AM is legal for this
34818 /// target, for a load/store of the specified type.
34819 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
34820 const AddrMode &AM, Type *Ty,
34821 unsigned AS,
34822 Instruction *I) const {
34823 // X86 supports extremely general addressing modes.
34824 CodeModel::Model M = getTargetMachine().getCodeModel();
34826 // X86 allows a sign-extended 32-bit immediate field as a displacement.
34827 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
34828 return false;
34830 if (AM.BaseGV) {
34831 unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
34833 // If a reference to this global requires an extra load, we can't fold it.
34834 if (isGlobalStubReference(GVFlags))
34835 return false;
34837 // If BaseGV requires a register for the PIC base, we cannot also have a
34838 // BaseReg specified.
34839 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
34840 return false;
34842 // If lower 4G is not available, then we must use rip-relative addressing.
34843 if ((M != CodeModel::Small || isPositionIndependent()) &&
34844 Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
34845 return false;
34848 switch (AM.Scale) {
34849 case 0:
34850 case 1:
34851 case 2:
34852 case 4:
34853 case 8:
34854 // These scales always work.
34855 break;
34856 case 3:
34857 case 5:
34858 case 9:
34859 // These scales are formed with basereg+scalereg. Only accept if there is
34860 // no basereg yet.
34861 if (AM.HasBaseReg)
34862 return false;
34863 break;
34864 default: // Other stuff never works.
34865 return false;
34868 return true;
34871 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
34872 switch (Opcode) {
34873 // These are non-commutative binops.
34874 // TODO: Add more X86ISD opcodes once we have test coverage.
34875 case X86ISD::ANDNP:
34876 case X86ISD::PCMPGT:
34877 case X86ISD::FMAX:
34878 case X86ISD::FMIN:
34879 case X86ISD::FANDN:
34880 case X86ISD::VPSHA:
34881 case X86ISD::VPSHL:
34882 case X86ISD::VSHLV:
34883 case X86ISD::VSRLV:
34884 case X86ISD::VSRAV:
34885 return true;
34888 return TargetLoweringBase::isBinOp(Opcode);
34891 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
34892 switch (Opcode) {
34893 // TODO: Add more X86ISD opcodes once we have test coverage.
34894 case X86ISD::PCMPEQ:
34895 case X86ISD::PMULDQ:
34896 case X86ISD::PMULUDQ:
34897 case X86ISD::FMAXC:
34898 case X86ISD::FMINC:
34899 case X86ISD::FAND:
34900 case X86ISD::FOR:
34901 case X86ISD::FXOR:
34902 return true;
34905 return TargetLoweringBase::isCommutativeBinOp(Opcode);
34908 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
34909 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
34910 return false;
34911 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
34912 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
34913 return NumBits1 > NumBits2;
34916 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
34917 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
34918 return false;
34920 if (!isTypeLegal(EVT::getEVT(Ty1)))
34921 return false;
34923 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
34925 // Assuming the caller doesn't have a zeroext or signext return parameter,
34926 // truncation all the way down to i1 is valid.
34927 return true;
34930 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
34931 return isInt<32>(Imm);
34934 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
34935 // Can also use sub to handle negated immediates.
34936 return isInt<32>(Imm);
34939 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
34940 return isInt<32>(Imm);
34943 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
34944 if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
34945 return false;
34946 unsigned NumBits1 = VT1.getSizeInBits();
34947 unsigned NumBits2 = VT2.getSizeInBits();
34948 return NumBits1 > NumBits2;
34951 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
34952 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
34953 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
34956 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
34957 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
34958 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
34961 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
34962 EVT VT1 = Val.getValueType();
34963 if (isZExtFree(VT1, VT2))
34964 return true;
34966 if (Val.getOpcode() != ISD::LOAD)
34967 return false;
34969 if (!VT1.isSimple() || !VT1.isInteger() ||
34970 !VT2.isSimple() || !VT2.isInteger())
34971 return false;
34973 switch (VT1.getSimpleVT().SimpleTy) {
34974 default: break;
34975 case MVT::i8:
34976 case MVT::i16:
34977 case MVT::i32:
34978 // X86 has 8, 16, and 32-bit zero-extending loads.
34979 return true;
34982 return false;
34985 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
34986 if (!Subtarget.is64Bit())
34987 return false;
34988 return TargetLowering::shouldConvertPhiType(From, To);
34991 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
34992 if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
34993 return false;
34995 EVT SrcVT = ExtVal.getOperand(0).getValueType();
34997 // There is no extending load for vXi1.
34998 if (SrcVT.getScalarType() == MVT::i1)
34999 return false;
35001 return true;
35004 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
35005 EVT VT) const {
35006 if (Subtarget.useSoftFloat())
35007 return false;
35009 if (!Subtarget.hasAnyFMA())
35010 return false;
35012 VT = VT.getScalarType();
35014 if (!VT.isSimple())
35015 return false;
35017 switch (VT.getSimpleVT().SimpleTy) {
35018 case MVT::f16:
35019 return Subtarget.hasFP16();
35020 case MVT::f32:
35021 case MVT::f64:
35022 return true;
35023 default:
35024 break;
35027 return false;
35030 bool X86TargetLowering::isNarrowingProfitable(SDNode *N, EVT SrcVT,
35031 EVT DestVT) const {
35032 // i16 instructions are longer (0x66 prefix) and potentially slower.
35033 return !(SrcVT == MVT::i32 && DestVT == MVT::i16);
35036 bool X86TargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode,
35037 EVT VT) const {
35038 // TODO: This is too general. There are cases where pre-AVX512 codegen would
35039 // benefit. The transform may also be profitable for scalar code.
35040 if (!Subtarget.hasAVX512())
35041 return false;
35042 if (!Subtarget.hasVLX() && !VT.is512BitVector())
35043 return false;
35044 if (!VT.isVector() || VT.getScalarType() == MVT::i1)
35045 return false;
35047 return true;
35050 /// Targets can use this to indicate that they only support *some*
35051 /// VECTOR_SHUFFLE operations, those with specific masks.
35052 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
35053 /// are assumed to be legal.
35054 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
35055 if (!VT.isSimple())
35056 return false;
35058 // Not for i1 vectors
35059 if (VT.getSimpleVT().getScalarType() == MVT::i1)
35060 return false;
35062 // Very little shuffling can be done for 64-bit vectors right now.
35063 if (VT.getSimpleVT().getSizeInBits() == 64)
35064 return false;
35066 // We only care that the types being shuffled are legal. The lowering can
35067 // handle any possible shuffle mask that results.
35068 return isTypeLegal(VT.getSimpleVT());
35071 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
35072 EVT VT) const {
35073 // Don't convert an 'and' into a shuffle that we don't directly support.
35074 // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
35075 if (!Subtarget.hasAVX2())
35076 if (VT == MVT::v32i8 || VT == MVT::v16i16)
35077 return false;
35079 // Just delegate to the generic legality, clear masks aren't special.
35080 return isShuffleMaskLegal(Mask, VT);
35083 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
35084 // If the subtarget is using thunks, we need to not generate jump tables.
35085 if (Subtarget.useIndirectThunkBranches())
35086 return false;
35088 // Otherwise, fallback on the generic logic.
35089 return TargetLowering::areJTsAllowed(Fn);
35092 MVT X86TargetLowering::getPreferredSwitchConditionType(LLVMContext &Context,
35093 EVT ConditionVT) const {
35094 // Avoid 8 and 16 bit types because they increase the chance for unnecessary
35095 // zero-extensions.
35096 if (ConditionVT.getSizeInBits() < 32)
35097 return MVT::i32;
35098 return TargetLoweringBase::getPreferredSwitchConditionType(Context,
35099 ConditionVT);
35102 //===----------------------------------------------------------------------===//
35103 // X86 Scheduler Hooks
35104 //===----------------------------------------------------------------------===//
35106 // Returns true if EFLAG is consumed after this iterator in the rest of the
35107 // basic block or any successors of the basic block.
35108 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
35109 MachineBasicBlock *BB) {
35110 // Scan forward through BB for a use/def of EFLAGS.
35111 for (const MachineInstr &mi : llvm::make_range(std::next(Itr), BB->end())) {
35112 if (mi.readsRegister(X86::EFLAGS, /*TRI=*/nullptr))
35113 return true;
35114 // If we found a def, we can stop searching.
35115 if (mi.definesRegister(X86::EFLAGS, /*TRI=*/nullptr))
35116 return false;
35119 // If we hit the end of the block, check whether EFLAGS is live into a
35120 // successor.
35121 for (MachineBasicBlock *Succ : BB->successors())
35122 if (Succ->isLiveIn(X86::EFLAGS))
35123 return true;
35125 return false;
35128 /// Utility function to emit xbegin specifying the start of an RTM region.
35129 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
35130 const TargetInstrInfo *TII) {
35131 const MIMetadata MIMD(MI);
35133 const BasicBlock *BB = MBB->getBasicBlock();
35134 MachineFunction::iterator I = ++MBB->getIterator();
35136 // For the v = xbegin(), we generate
35138 // thisMBB:
35139 // xbegin sinkMBB
35141 // mainMBB:
35142 // s0 = -1
35144 // fallBB:
35145 // eax = # XABORT_DEF
35146 // s1 = eax
35148 // sinkMBB:
35149 // v = phi(s0/mainBB, s1/fallBB)
35151 MachineBasicBlock *thisMBB = MBB;
35152 MachineFunction *MF = MBB->getParent();
35153 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
35154 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
35155 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
35156 MF->insert(I, mainMBB);
35157 MF->insert(I, fallMBB);
35158 MF->insert(I, sinkMBB);
35160 if (isEFLAGSLiveAfter(MI, MBB)) {
35161 mainMBB->addLiveIn(X86::EFLAGS);
35162 fallMBB->addLiveIn(X86::EFLAGS);
35163 sinkMBB->addLiveIn(X86::EFLAGS);
35166 // Transfer the remainder of BB and its successor edges to sinkMBB.
35167 sinkMBB->splice(sinkMBB->begin(), MBB,
35168 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
35169 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
35171 MachineRegisterInfo &MRI = MF->getRegInfo();
35172 Register DstReg = MI.getOperand(0).getReg();
35173 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
35174 Register mainDstReg = MRI.createVirtualRegister(RC);
35175 Register fallDstReg = MRI.createVirtualRegister(RC);
35177 // thisMBB:
35178 // xbegin fallMBB
35179 // # fallthrough to mainMBB
35180 // # abortion to fallMBB
35181 BuildMI(thisMBB, MIMD, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
35182 thisMBB->addSuccessor(mainMBB);
35183 thisMBB->addSuccessor(fallMBB);
35185 // mainMBB:
35186 // mainDstReg := -1
35187 BuildMI(mainMBB, MIMD, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
35188 BuildMI(mainMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
35189 mainMBB->addSuccessor(sinkMBB);
35191 // fallMBB:
35192 // ; pseudo instruction to model hardware's definition from XABORT
35193 // EAX := XABORT_DEF
35194 // fallDstReg := EAX
35195 BuildMI(fallMBB, MIMD, TII->get(X86::XABORT_DEF));
35196 BuildMI(fallMBB, MIMD, TII->get(TargetOpcode::COPY), fallDstReg)
35197 .addReg(X86::EAX);
35198 fallMBB->addSuccessor(sinkMBB);
35200 // sinkMBB:
35201 // DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
35202 BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
35203 .addReg(mainDstReg).addMBB(mainMBB)
35204 .addReg(fallDstReg).addMBB(fallMBB);
35206 MI.eraseFromParent();
35207 return sinkMBB;
35210 MachineBasicBlock *
35211 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
35212 MachineBasicBlock *MBB) const {
35213 // Emit va_arg instruction on X86-64.
35215 // Operands to this pseudo-instruction:
35216 // 0 ) Output : destination address (reg)
35217 // 1-5) Input : va_list address (addr, i64mem)
35218 // 6 ) ArgSize : Size (in bytes) of vararg type
35219 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
35220 // 8 ) Align : Alignment of type
35221 // 9 ) EFLAGS (implicit-def)
35223 assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
35224 static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
35226 Register DestReg = MI.getOperand(0).getReg();
35227 MachineOperand &Base = MI.getOperand(1);
35228 MachineOperand &Scale = MI.getOperand(2);
35229 MachineOperand &Index = MI.getOperand(3);
35230 MachineOperand &Disp = MI.getOperand(4);
35231 MachineOperand &Segment = MI.getOperand(5);
35232 unsigned ArgSize = MI.getOperand(6).getImm();
35233 unsigned ArgMode = MI.getOperand(7).getImm();
35234 Align Alignment = Align(MI.getOperand(8).getImm());
35236 MachineFunction *MF = MBB->getParent();
35238 // Memory Reference
35239 assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
35241 MachineMemOperand *OldMMO = MI.memoperands().front();
35243 // Clone the MMO into two separate MMOs for loading and storing
35244 MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
35245 OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
35246 MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
35247 OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
35249 // Machine Information
35250 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35251 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
35252 const TargetRegisterClass *AddrRegClass =
35253 getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
35254 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
35255 const MIMetadata MIMD(MI);
35257 // struct va_list {
35258 // i32 gp_offset
35259 // i32 fp_offset
35260 // i64 overflow_area (address)
35261 // i64 reg_save_area (address)
35262 // }
35263 // sizeof(va_list) = 24
35264 // alignment(va_list) = 8
35266 unsigned TotalNumIntRegs = 6;
35267 unsigned TotalNumXMMRegs = 8;
35268 bool UseGPOffset = (ArgMode == 1);
35269 bool UseFPOffset = (ArgMode == 2);
35270 unsigned MaxOffset = TotalNumIntRegs * 8 +
35271 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
35273 /* Align ArgSize to a multiple of 8 */
35274 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
35275 bool NeedsAlign = (Alignment > 8);
35277 MachineBasicBlock *thisMBB = MBB;
35278 MachineBasicBlock *overflowMBB;
35279 MachineBasicBlock *offsetMBB;
35280 MachineBasicBlock *endMBB;
35282 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
35283 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
35284 unsigned OffsetReg = 0;
35286 if (!UseGPOffset && !UseFPOffset) {
35287 // If we only pull from the overflow region, we don't create a branch.
35288 // We don't need to alter control flow.
35289 OffsetDestReg = 0; // unused
35290 OverflowDestReg = DestReg;
35292 offsetMBB = nullptr;
35293 overflowMBB = thisMBB;
35294 endMBB = thisMBB;
35295 } else {
35296 // First emit code to check if gp_offset (or fp_offset) is below the bound.
35297 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
35298 // If not, pull from overflow_area. (branch to overflowMBB)
35300 // thisMBB
35301 // | .
35302 // | .
35303 // offsetMBB overflowMBB
35304 // | .
35305 // | .
35306 // endMBB
35308 // Registers for the PHI in endMBB
35309 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
35310 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
35312 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
35313 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35314 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35315 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35317 MachineFunction::iterator MBBIter = ++MBB->getIterator();
35319 // Insert the new basic blocks
35320 MF->insert(MBBIter, offsetMBB);
35321 MF->insert(MBBIter, overflowMBB);
35322 MF->insert(MBBIter, endMBB);
35324 // Transfer the remainder of MBB and its successor edges to endMBB.
35325 endMBB->splice(endMBB->begin(), thisMBB,
35326 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
35327 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
35329 // Make offsetMBB and overflowMBB successors of thisMBB
35330 thisMBB->addSuccessor(offsetMBB);
35331 thisMBB->addSuccessor(overflowMBB);
35333 // endMBB is a successor of both offsetMBB and overflowMBB
35334 offsetMBB->addSuccessor(endMBB);
35335 overflowMBB->addSuccessor(endMBB);
35337 // Load the offset value into a register
35338 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
35339 BuildMI(thisMBB, MIMD, TII->get(X86::MOV32rm), OffsetReg)
35340 .add(Base)
35341 .add(Scale)
35342 .add(Index)
35343 .addDisp(Disp, UseFPOffset ? 4 : 0)
35344 .add(Segment)
35345 .setMemRefs(LoadOnlyMMO);
35347 // Check if there is enough room left to pull this argument.
35348 BuildMI(thisMBB, MIMD, TII->get(X86::CMP32ri))
35349 .addReg(OffsetReg)
35350 .addImm(MaxOffset + 8 - ArgSizeA8);
35352 // Branch to "overflowMBB" if offset >= max
35353 // Fall through to "offsetMBB" otherwise
35354 BuildMI(thisMBB, MIMD, TII->get(X86::JCC_1))
35355 .addMBB(overflowMBB).addImm(X86::COND_AE);
35358 // In offsetMBB, emit code to use the reg_save_area.
35359 if (offsetMBB) {
35360 assert(OffsetReg != 0);
35362 // Read the reg_save_area address.
35363 Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
35364 BuildMI(
35365 offsetMBB, MIMD,
35366 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
35367 RegSaveReg)
35368 .add(Base)
35369 .add(Scale)
35370 .add(Index)
35371 .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
35372 .add(Segment)
35373 .setMemRefs(LoadOnlyMMO);
35375 if (Subtarget.isTarget64BitLP64()) {
35376 // Zero-extend the offset
35377 Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
35378 BuildMI(offsetMBB, MIMD, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
35379 .addImm(0)
35380 .addReg(OffsetReg)
35381 .addImm(X86::sub_32bit);
35383 // Add the offset to the reg_save_area to get the final address.
35384 BuildMI(offsetMBB, MIMD, TII->get(X86::ADD64rr), OffsetDestReg)
35385 .addReg(OffsetReg64)
35386 .addReg(RegSaveReg);
35387 } else {
35388 // Add the offset to the reg_save_area to get the final address.
35389 BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32rr), OffsetDestReg)
35390 .addReg(OffsetReg)
35391 .addReg(RegSaveReg);
35394 // Compute the offset for the next argument
35395 Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
35396 BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32ri), NextOffsetReg)
35397 .addReg(OffsetReg)
35398 .addImm(UseFPOffset ? 16 : 8);
35400 // Store it back into the va_list.
35401 BuildMI(offsetMBB, MIMD, TII->get(X86::MOV32mr))
35402 .add(Base)
35403 .add(Scale)
35404 .add(Index)
35405 .addDisp(Disp, UseFPOffset ? 4 : 0)
35406 .add(Segment)
35407 .addReg(NextOffsetReg)
35408 .setMemRefs(StoreOnlyMMO);
35410 // Jump to endMBB
35411 BuildMI(offsetMBB, MIMD, TII->get(X86::JMP_1))
35412 .addMBB(endMBB);
35416 // Emit code to use overflow area
35419 // Load the overflow_area address into a register.
35420 Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
35421 BuildMI(overflowMBB, MIMD,
35422 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
35423 OverflowAddrReg)
35424 .add(Base)
35425 .add(Scale)
35426 .add(Index)
35427 .addDisp(Disp, 8)
35428 .add(Segment)
35429 .setMemRefs(LoadOnlyMMO);
35431 // If we need to align it, do so. Otherwise, just copy the address
35432 // to OverflowDestReg.
35433 if (NeedsAlign) {
35434 // Align the overflow address
35435 Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
35437 // aligned_addr = (addr + (align-1)) & ~(align-1)
35438 BuildMI(
35439 overflowMBB, MIMD,
35440 TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
35441 TmpReg)
35442 .addReg(OverflowAddrReg)
35443 .addImm(Alignment.value() - 1);
35445 BuildMI(
35446 overflowMBB, MIMD,
35447 TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
35448 OverflowDestReg)
35449 .addReg(TmpReg)
35450 .addImm(~(uint64_t)(Alignment.value() - 1));
35451 } else {
35452 BuildMI(overflowMBB, MIMD, TII->get(TargetOpcode::COPY), OverflowDestReg)
35453 .addReg(OverflowAddrReg);
35456 // Compute the next overflow address after this argument.
35457 // (the overflow address should be kept 8-byte aligned)
35458 Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
35459 BuildMI(
35460 overflowMBB, MIMD,
35461 TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
35462 NextAddrReg)
35463 .addReg(OverflowDestReg)
35464 .addImm(ArgSizeA8);
35466 // Store the new overflow address.
35467 BuildMI(overflowMBB, MIMD,
35468 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
35469 .add(Base)
35470 .add(Scale)
35471 .add(Index)
35472 .addDisp(Disp, 8)
35473 .add(Segment)
35474 .addReg(NextAddrReg)
35475 .setMemRefs(StoreOnlyMMO);
35477 // If we branched, emit the PHI to the front of endMBB.
35478 if (offsetMBB) {
35479 BuildMI(*endMBB, endMBB->begin(), MIMD,
35480 TII->get(X86::PHI), DestReg)
35481 .addReg(OffsetDestReg).addMBB(offsetMBB)
35482 .addReg(OverflowDestReg).addMBB(overflowMBB);
35485 // Erase the pseudo instruction
35486 MI.eraseFromParent();
35488 return endMBB;
35491 // The EFLAGS operand of SelectItr might be missing a kill marker
35492 // because there were multiple uses of EFLAGS, and ISel didn't know
35493 // which to mark. Figure out whether SelectItr should have had a
35494 // kill marker, and set it if it should. Returns the correct kill
35495 // marker value.
35496 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
35497 MachineBasicBlock* BB,
35498 const TargetRegisterInfo* TRI) {
35499 if (isEFLAGSLiveAfter(SelectItr, BB))
35500 return false;
35502 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
35503 // out. SelectMI should have a kill flag on EFLAGS.
35504 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
35505 return true;
35508 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
35509 // together with other CMOV pseudo-opcodes into a single basic-block with
35510 // conditional jump around it.
35511 static bool isCMOVPseudo(MachineInstr &MI) {
35512 switch (MI.getOpcode()) {
35513 case X86::CMOV_FR16:
35514 case X86::CMOV_FR16X:
35515 case X86::CMOV_FR32:
35516 case X86::CMOV_FR32X:
35517 case X86::CMOV_FR64:
35518 case X86::CMOV_FR64X:
35519 case X86::CMOV_GR8:
35520 case X86::CMOV_GR16:
35521 case X86::CMOV_GR32:
35522 case X86::CMOV_RFP32:
35523 case X86::CMOV_RFP64:
35524 case X86::CMOV_RFP80:
35525 case X86::CMOV_VR64:
35526 case X86::CMOV_VR128:
35527 case X86::CMOV_VR128X:
35528 case X86::CMOV_VR256:
35529 case X86::CMOV_VR256X:
35530 case X86::CMOV_VR512:
35531 case X86::CMOV_VK1:
35532 case X86::CMOV_VK2:
35533 case X86::CMOV_VK4:
35534 case X86::CMOV_VK8:
35535 case X86::CMOV_VK16:
35536 case X86::CMOV_VK32:
35537 case X86::CMOV_VK64:
35538 return true;
35540 default:
35541 return false;
35545 // Helper function, which inserts PHI functions into SinkMBB:
35546 // %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
35547 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
35548 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
35549 // the last PHI function inserted.
35550 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
35551 MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
35552 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
35553 MachineBasicBlock *SinkMBB) {
35554 MachineFunction *MF = TrueMBB->getParent();
35555 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
35556 const MIMetadata MIMD(*MIItBegin);
35558 X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
35559 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
35561 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
35563 // As we are creating the PHIs, we have to be careful if there is more than
35564 // one. Later CMOVs may reference the results of earlier CMOVs, but later
35565 // PHIs have to reference the individual true/false inputs from earlier PHIs.
35566 // That also means that PHI construction must work forward from earlier to
35567 // later, and that the code must maintain a mapping from earlier PHI's
35568 // destination registers, and the registers that went into the PHI.
35569 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
35570 MachineInstrBuilder MIB;
35572 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
35573 Register DestReg = MIIt->getOperand(0).getReg();
35574 Register Op1Reg = MIIt->getOperand(1).getReg();
35575 Register Op2Reg = MIIt->getOperand(2).getReg();
35577 // If this CMOV we are generating is the opposite condition from
35578 // the jump we generated, then we have to swap the operands for the
35579 // PHI that is going to be generated.
35580 if (MIIt->getOperand(3).getImm() == OppCC)
35581 std::swap(Op1Reg, Op2Reg);
35583 if (auto It = RegRewriteTable.find(Op1Reg); It != RegRewriteTable.end())
35584 Op1Reg = It->second.first;
35586 if (auto It = RegRewriteTable.find(Op2Reg); It != RegRewriteTable.end())
35587 Op2Reg = It->second.second;
35589 MIB =
35590 BuildMI(*SinkMBB, SinkInsertionPoint, MIMD, TII->get(X86::PHI), DestReg)
35591 .addReg(Op1Reg)
35592 .addMBB(FalseMBB)
35593 .addReg(Op2Reg)
35594 .addMBB(TrueMBB);
35596 // Add this PHI to the rewrite table.
35597 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
35600 return MIB;
35603 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
35604 MachineBasicBlock *
35605 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
35606 MachineInstr &SecondCascadedCMOV,
35607 MachineBasicBlock *ThisMBB) const {
35608 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35609 const MIMetadata MIMD(FirstCMOV);
35611 // We lower cascaded CMOVs such as
35613 // (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
35615 // to two successive branches.
35617 // Without this, we would add a PHI between the two jumps, which ends up
35618 // creating a few copies all around. For instance, for
35620 // (sitofp (zext (fcmp une)))
35622 // we would generate:
35624 // ucomiss %xmm1, %xmm0
35625 // movss <1.0f>, %xmm0
35626 // movaps %xmm0, %xmm1
35627 // jne .LBB5_2
35628 // xorps %xmm1, %xmm1
35629 // .LBB5_2:
35630 // jp .LBB5_4
35631 // movaps %xmm1, %xmm0
35632 // .LBB5_4:
35633 // retq
35635 // because this custom-inserter would have generated:
35637 // A
35638 // | \
35639 // | B
35640 // | /
35641 // C
35642 // | \
35643 // | D
35644 // | /
35645 // E
35647 // A: X = ...; Y = ...
35648 // B: empty
35649 // C: Z = PHI [X, A], [Y, B]
35650 // D: empty
35651 // E: PHI [X, C], [Z, D]
35653 // If we lower both CMOVs in a single step, we can instead generate:
35655 // A
35656 // | \
35657 // | C
35658 // | /|
35659 // |/ |
35660 // | |
35661 // | D
35662 // | /
35663 // E
35665 // A: X = ...; Y = ...
35666 // D: empty
35667 // E: PHI [X, A], [X, C], [Y, D]
35669 // Which, in our sitofp/fcmp example, gives us something like:
35671 // ucomiss %xmm1, %xmm0
35672 // movss <1.0f>, %xmm0
35673 // jne .LBB5_4
35674 // jp .LBB5_4
35675 // xorps %xmm0, %xmm0
35676 // .LBB5_4:
35677 // retq
35680 // We lower cascaded CMOV into two successive branches to the same block.
35681 // EFLAGS is used by both, so mark it as live in the second.
35682 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
35683 MachineFunction *F = ThisMBB->getParent();
35684 MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
35685 MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
35686 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
35688 MachineFunction::iterator It = ++ThisMBB->getIterator();
35689 F->insert(It, FirstInsertedMBB);
35690 F->insert(It, SecondInsertedMBB);
35691 F->insert(It, SinkMBB);
35693 // For a cascaded CMOV, we lower it to two successive branches to
35694 // the same block (SinkMBB). EFLAGS is used by both, so mark it as live in
35695 // the FirstInsertedMBB.
35696 FirstInsertedMBB->addLiveIn(X86::EFLAGS);
35698 // If the EFLAGS register isn't dead in the terminator, then claim that it's
35699 // live into the sink and copy blocks.
35700 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
35701 if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS, /*TRI=*/nullptr) &&
35702 !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
35703 SecondInsertedMBB->addLiveIn(X86::EFLAGS);
35704 SinkMBB->addLiveIn(X86::EFLAGS);
35707 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
35708 SinkMBB->splice(SinkMBB->begin(), ThisMBB,
35709 std::next(MachineBasicBlock::iterator(FirstCMOV)),
35710 ThisMBB->end());
35711 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
35713 // Fallthrough block for ThisMBB.
35714 ThisMBB->addSuccessor(FirstInsertedMBB);
35715 // The true block target of the first branch is always SinkMBB.
35716 ThisMBB->addSuccessor(SinkMBB);
35717 // Fallthrough block for FirstInsertedMBB.
35718 FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
35719 // The true block for the branch of FirstInsertedMBB.
35720 FirstInsertedMBB->addSuccessor(SinkMBB);
35721 // This is fallthrough.
35722 SecondInsertedMBB->addSuccessor(SinkMBB);
35724 // Create the conditional branch instructions.
35725 X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
35726 BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
35728 X86::CondCode SecondCC =
35729 X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
35730 BuildMI(FirstInsertedMBB, MIMD, TII->get(X86::JCC_1))
35731 .addMBB(SinkMBB)
35732 .addImm(SecondCC);
35734 // SinkMBB:
35735 // %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
35736 Register DestReg = SecondCascadedCMOV.getOperand(0).getReg();
35737 Register Op1Reg = FirstCMOV.getOperand(1).getReg();
35738 Register Op2Reg = FirstCMOV.getOperand(2).getReg();
35739 MachineInstrBuilder MIB =
35740 BuildMI(*SinkMBB, SinkMBB->begin(), MIMD, TII->get(X86::PHI), DestReg)
35741 .addReg(Op1Reg)
35742 .addMBB(SecondInsertedMBB)
35743 .addReg(Op2Reg)
35744 .addMBB(ThisMBB);
35746 // The second SecondInsertedMBB provides the same incoming value as the
35747 // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
35748 MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
35750 // Now remove the CMOVs.
35751 FirstCMOV.eraseFromParent();
35752 SecondCascadedCMOV.eraseFromParent();
35754 return SinkMBB;
35757 MachineBasicBlock *
35758 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
35759 MachineBasicBlock *ThisMBB) const {
35760 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35761 const MIMetadata MIMD(MI);
35763 // To "insert" a SELECT_CC instruction, we actually have to insert the
35764 // diamond control-flow pattern. The incoming instruction knows the
35765 // destination vreg to set, the condition code register to branch on, the
35766 // true/false values to select between and a branch opcode to use.
35768 // ThisMBB:
35769 // ...
35770 // TrueVal = ...
35771 // cmpTY ccX, r1, r2
35772 // bCC copy1MBB
35773 // fallthrough --> FalseMBB
35775 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
35776 // as described above, by inserting a BB, and then making a PHI at the join
35777 // point to select the true and false operands of the CMOV in the PHI.
35779 // The code also handles two different cases of multiple CMOV opcodes
35780 // in a row.
35782 // Case 1:
35783 // In this case, there are multiple CMOVs in a row, all which are based on
35784 // the same condition setting (or the exact opposite condition setting).
35785 // In this case we can lower all the CMOVs using a single inserted BB, and
35786 // then make a number of PHIs at the join point to model the CMOVs. The only
35787 // trickiness here, is that in a case like:
35789 // t2 = CMOV cond1 t1, f1
35790 // t3 = CMOV cond1 t2, f2
35792 // when rewriting this into PHIs, we have to perform some renaming on the
35793 // temps since you cannot have a PHI operand refer to a PHI result earlier
35794 // in the same block. The "simple" but wrong lowering would be:
35796 // t2 = PHI t1(BB1), f1(BB2)
35797 // t3 = PHI t2(BB1), f2(BB2)
35799 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
35800 // renaming is to note that on the path through BB1, t2 is really just a
35801 // copy of t1, and do that renaming, properly generating:
35803 // t2 = PHI t1(BB1), f1(BB2)
35804 // t3 = PHI t1(BB1), f2(BB2)
35806 // Case 2:
35807 // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
35808 // function - EmitLoweredCascadedSelect.
35810 X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
35811 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
35812 MachineInstr *LastCMOV = &MI;
35813 MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
35815 // Check for case 1, where there are multiple CMOVs with the same condition
35816 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
35817 // number of jumps the most.
35819 if (isCMOVPseudo(MI)) {
35820 // See if we have a string of CMOVS with the same condition. Skip over
35821 // intervening debug insts.
35822 while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
35823 (NextMIIt->getOperand(3).getImm() == CC ||
35824 NextMIIt->getOperand(3).getImm() == OppCC)) {
35825 LastCMOV = &*NextMIIt;
35826 NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
35830 // This checks for case 2, but only do this if we didn't already find
35831 // case 1, as indicated by LastCMOV == MI.
35832 if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
35833 NextMIIt->getOpcode() == MI.getOpcode() &&
35834 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
35835 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
35836 NextMIIt->getOperand(1).isKill()) {
35837 return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
35840 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
35841 MachineFunction *F = ThisMBB->getParent();
35842 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
35843 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
35845 MachineFunction::iterator It = ++ThisMBB->getIterator();
35846 F->insert(It, FalseMBB);
35847 F->insert(It, SinkMBB);
35849 // Set the call frame size on entry to the new basic blocks.
35850 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
35851 FalseMBB->setCallFrameSize(CallFrameSize);
35852 SinkMBB->setCallFrameSize(CallFrameSize);
35854 // If the EFLAGS register isn't dead in the terminator, then claim that it's
35855 // live into the sink and copy blocks.
35856 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
35857 if (!LastCMOV->killsRegister(X86::EFLAGS, /*TRI=*/nullptr) &&
35858 !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
35859 FalseMBB->addLiveIn(X86::EFLAGS);
35860 SinkMBB->addLiveIn(X86::EFLAGS);
35863 // Transfer any debug instructions inside the CMOV sequence to the sunk block.
35864 auto DbgRange = llvm::make_range(MachineBasicBlock::iterator(MI),
35865 MachineBasicBlock::iterator(LastCMOV));
35866 for (MachineInstr &MI : llvm::make_early_inc_range(DbgRange))
35867 if (MI.isDebugInstr())
35868 SinkMBB->push_back(MI.removeFromParent());
35870 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
35871 SinkMBB->splice(SinkMBB->end(), ThisMBB,
35872 std::next(MachineBasicBlock::iterator(LastCMOV)),
35873 ThisMBB->end());
35874 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
35876 // Fallthrough block for ThisMBB.
35877 ThisMBB->addSuccessor(FalseMBB);
35878 // The true block target of the first (or only) branch is always a SinkMBB.
35879 ThisMBB->addSuccessor(SinkMBB);
35880 // Fallthrough block for FalseMBB.
35881 FalseMBB->addSuccessor(SinkMBB);
35883 // Create the conditional branch instruction.
35884 BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
35886 // SinkMBB:
35887 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
35888 // ...
35889 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
35890 MachineBasicBlock::iterator MIItEnd =
35891 std::next(MachineBasicBlock::iterator(LastCMOV));
35892 createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
35894 // Now remove the CMOV(s).
35895 ThisMBB->erase(MIItBegin, MIItEnd);
35897 return SinkMBB;
35900 static unsigned getSUBriOpcode(bool IsLP64) {
35901 if (IsLP64)
35902 return X86::SUB64ri32;
35903 else
35904 return X86::SUB32ri;
35907 MachineBasicBlock *
35908 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
35909 MachineBasicBlock *MBB) const {
35910 MachineFunction *MF = MBB->getParent();
35911 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35912 const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
35913 const MIMetadata MIMD(MI);
35914 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
35916 const unsigned ProbeSize = getStackProbeSize(*MF);
35918 MachineRegisterInfo &MRI = MF->getRegInfo();
35919 MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35920 MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35921 MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
35923 MachineFunction::iterator MBBIter = ++MBB->getIterator();
35924 MF->insert(MBBIter, testMBB);
35925 MF->insert(MBBIter, blockMBB);
35926 MF->insert(MBBIter, tailMBB);
35928 Register sizeVReg = MI.getOperand(1).getReg();
35930 Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
35932 Register TmpStackPtr = MRI.createVirtualRegister(
35933 TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
35934 Register FinalStackPtr = MRI.createVirtualRegister(
35935 TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
35937 BuildMI(*MBB, {MI}, MIMD, TII->get(TargetOpcode::COPY), TmpStackPtr)
35938 .addReg(physSPReg);
35940 const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
35941 BuildMI(*MBB, {MI}, MIMD, TII->get(Opc), FinalStackPtr)
35942 .addReg(TmpStackPtr)
35943 .addReg(sizeVReg);
35946 // test rsp size
35948 BuildMI(testMBB, MIMD,
35949 TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
35950 .addReg(FinalStackPtr)
35951 .addReg(physSPReg);
35953 BuildMI(testMBB, MIMD, TII->get(X86::JCC_1))
35954 .addMBB(tailMBB)
35955 .addImm(X86::COND_GE);
35956 testMBB->addSuccessor(blockMBB);
35957 testMBB->addSuccessor(tailMBB);
35959 // Touch the block then extend it. This is done on the opposite side of
35960 // static probe where we allocate then touch, to avoid the need of probing the
35961 // tail of the static alloca. Possible scenarios are:
35963 // + ---- <- ------------ <- ------------- <- ------------ +
35964 // | |
35965 // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
35966 // | |
35967 // + <- ----------- <- ------------ <- ----------- <- ------------ +
35969 // The property we want to enforce is to never have more than [page alloc] between two probes.
35971 const unsigned XORMIOpc =
35972 TFI.Uses64BitFramePtr ? X86::XOR64mi32 : X86::XOR32mi;
35973 addRegOffset(BuildMI(blockMBB, MIMD, TII->get(XORMIOpc)), physSPReg, false, 0)
35974 .addImm(0);
35976 BuildMI(blockMBB, MIMD, TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr)),
35977 physSPReg)
35978 .addReg(physSPReg)
35979 .addImm(ProbeSize);
35981 BuildMI(blockMBB, MIMD, TII->get(X86::JMP_1)).addMBB(testMBB);
35982 blockMBB->addSuccessor(testMBB);
35984 // Replace original instruction by the expected stack ptr
35985 BuildMI(tailMBB, MIMD, TII->get(TargetOpcode::COPY),
35986 MI.getOperand(0).getReg())
35987 .addReg(FinalStackPtr);
35989 tailMBB->splice(tailMBB->end(), MBB,
35990 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
35991 tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
35992 MBB->addSuccessor(testMBB);
35994 // Delete the original pseudo instruction.
35995 MI.eraseFromParent();
35997 // And we're done.
35998 return tailMBB;
36001 MachineBasicBlock *
36002 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
36003 MachineBasicBlock *BB) const {
36004 MachineFunction *MF = BB->getParent();
36005 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36006 const MIMetadata MIMD(MI);
36007 const BasicBlock *LLVM_BB = BB->getBasicBlock();
36009 assert(MF->shouldSplitStack());
36011 const bool Is64Bit = Subtarget.is64Bit();
36012 const bool IsLP64 = Subtarget.isTarget64BitLP64();
36014 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
36015 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
36017 // BB:
36018 // ... [Till the alloca]
36019 // If stacklet is not large enough, jump to mallocMBB
36021 // bumpMBB:
36022 // Allocate by subtracting from RSP
36023 // Jump to continueMBB
36025 // mallocMBB:
36026 // Allocate by call to runtime
36028 // continueMBB:
36029 // ...
36030 // [rest of original BB]
36033 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36034 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36035 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
36037 MachineRegisterInfo &MRI = MF->getRegInfo();
36038 const TargetRegisterClass *AddrRegClass =
36039 getRegClassFor(getPointerTy(MF->getDataLayout()));
36041 Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
36042 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
36043 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
36044 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
36045 sizeVReg = MI.getOperand(1).getReg(),
36046 physSPReg =
36047 IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
36049 MachineFunction::iterator MBBIter = ++BB->getIterator();
36051 MF->insert(MBBIter, bumpMBB);
36052 MF->insert(MBBIter, mallocMBB);
36053 MF->insert(MBBIter, continueMBB);
36055 continueMBB->splice(continueMBB->begin(), BB,
36056 std::next(MachineBasicBlock::iterator(MI)), BB->end());
36057 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
36059 // Add code to the main basic block to check if the stack limit has been hit,
36060 // and if so, jump to mallocMBB otherwise to bumpMBB.
36061 BuildMI(BB, MIMD, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
36062 BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
36063 .addReg(tmpSPVReg).addReg(sizeVReg);
36064 BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
36065 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
36066 .addReg(SPLimitVReg);
36067 BuildMI(BB, MIMD, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
36069 // bumpMBB simply decreases the stack pointer, since we know the current
36070 // stacklet has enough space.
36071 BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), physSPReg)
36072 .addReg(SPLimitVReg);
36073 BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
36074 .addReg(SPLimitVReg);
36075 BuildMI(bumpMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
36077 // Calls into a routine in libgcc to allocate more space from the heap.
36078 const uint32_t *RegMask =
36079 Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
36080 if (IsLP64) {
36081 BuildMI(mallocMBB, MIMD, TII->get(X86::MOV64rr), X86::RDI)
36082 .addReg(sizeVReg);
36083 BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
36084 .addExternalSymbol("__morestack_allocate_stack_space")
36085 .addRegMask(RegMask)
36086 .addReg(X86::RDI, RegState::Implicit)
36087 .addReg(X86::RAX, RegState::ImplicitDefine);
36088 } else if (Is64Bit) {
36089 BuildMI(mallocMBB, MIMD, TII->get(X86::MOV32rr), X86::EDI)
36090 .addReg(sizeVReg);
36091 BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
36092 .addExternalSymbol("__morestack_allocate_stack_space")
36093 .addRegMask(RegMask)
36094 .addReg(X86::EDI, RegState::Implicit)
36095 .addReg(X86::EAX, RegState::ImplicitDefine);
36096 } else {
36097 BuildMI(mallocMBB, MIMD, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
36098 .addImm(12);
36099 BuildMI(mallocMBB, MIMD, TII->get(X86::PUSH32r)).addReg(sizeVReg);
36100 BuildMI(mallocMBB, MIMD, TII->get(X86::CALLpcrel32))
36101 .addExternalSymbol("__morestack_allocate_stack_space")
36102 .addRegMask(RegMask)
36103 .addReg(X86::EAX, RegState::ImplicitDefine);
36106 if (!Is64Bit)
36107 BuildMI(mallocMBB, MIMD, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
36108 .addImm(16);
36110 BuildMI(mallocMBB, MIMD, TII->get(TargetOpcode::COPY), mallocPtrVReg)
36111 .addReg(IsLP64 ? X86::RAX : X86::EAX);
36112 BuildMI(mallocMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
36114 // Set up the CFG correctly.
36115 BB->addSuccessor(bumpMBB);
36116 BB->addSuccessor(mallocMBB);
36117 mallocMBB->addSuccessor(continueMBB);
36118 bumpMBB->addSuccessor(continueMBB);
36120 // Take care of the PHI nodes.
36121 BuildMI(*continueMBB, continueMBB->begin(), MIMD, TII->get(X86::PHI),
36122 MI.getOperand(0).getReg())
36123 .addReg(mallocPtrVReg)
36124 .addMBB(mallocMBB)
36125 .addReg(bumpSPPtrVReg)
36126 .addMBB(bumpMBB);
36128 // Delete the original pseudo instruction.
36129 MI.eraseFromParent();
36131 // And we're done.
36132 return continueMBB;
36135 MachineBasicBlock *
36136 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
36137 MachineBasicBlock *BB) const {
36138 MachineFunction *MF = BB->getParent();
36139 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
36140 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
36141 const MIMetadata MIMD(MI);
36143 assert(!isAsynchronousEHPersonality(
36144 classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
36145 "SEH does not use catchret!");
36147 // Only 32-bit EH needs to worry about manually restoring stack pointers.
36148 if (!Subtarget.is32Bit())
36149 return BB;
36151 // C++ EH creates a new target block to hold the restore code, and wires up
36152 // the new block to the return destination with a normal JMP_4.
36153 MachineBasicBlock *RestoreMBB =
36154 MF->CreateMachineBasicBlock(BB->getBasicBlock());
36155 assert(BB->succ_size() == 1);
36156 MF->insert(std::next(BB->getIterator()), RestoreMBB);
36157 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
36158 BB->addSuccessor(RestoreMBB);
36159 MI.getOperand(0).setMBB(RestoreMBB);
36161 // Marking this as an EH pad but not a funclet entry block causes PEI to
36162 // restore stack pointers in the block.
36163 RestoreMBB->setIsEHPad(true);
36165 auto RestoreMBBI = RestoreMBB->begin();
36166 BuildMI(*RestoreMBB, RestoreMBBI, MIMD, TII.get(X86::JMP_4)).addMBB(TargetMBB);
36167 return BB;
36170 MachineBasicBlock *
36171 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
36172 MachineBasicBlock *BB) const {
36173 // This is pretty easy. We're taking the value that we received from
36174 // our load from the relocation, sticking it in either RDI (x86-64)
36175 // or EAX and doing an indirect call. The return value will then
36176 // be in the normal return register.
36177 MachineFunction *F = BB->getParent();
36178 const X86InstrInfo *TII = Subtarget.getInstrInfo();
36179 const MIMetadata MIMD(MI);
36181 assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
36182 assert(MI.getOperand(3).isGlobal() && "This should be a global");
36184 // Get a register mask for the lowered call.
36185 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
36186 // proper register mask.
36187 const uint32_t *RegMask =
36188 Subtarget.is64Bit() ?
36189 Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
36190 Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
36191 if (Subtarget.is64Bit()) {
36192 MachineInstrBuilder MIB =
36193 BuildMI(*BB, MI, MIMD, TII->get(X86::MOV64rm), X86::RDI)
36194 .addReg(X86::RIP)
36195 .addImm(0)
36196 .addReg(0)
36197 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
36198 MI.getOperand(3).getTargetFlags())
36199 .addReg(0);
36200 MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL64m));
36201 addDirectMem(MIB, X86::RDI);
36202 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
36203 } else if (!isPositionIndependent()) {
36204 MachineInstrBuilder MIB =
36205 BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
36206 .addReg(0)
36207 .addImm(0)
36208 .addReg(0)
36209 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
36210 MI.getOperand(3).getTargetFlags())
36211 .addReg(0);
36212 MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
36213 addDirectMem(MIB, X86::EAX);
36214 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
36215 } else {
36216 MachineInstrBuilder MIB =
36217 BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
36218 .addReg(TII->getGlobalBaseReg(F))
36219 .addImm(0)
36220 .addReg(0)
36221 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
36222 MI.getOperand(3).getTargetFlags())
36223 .addReg(0);
36224 MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
36225 addDirectMem(MIB, X86::EAX);
36226 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
36229 MI.eraseFromParent(); // The pseudo instruction is gone now.
36230 return BB;
36233 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
36234 switch (RPOpc) {
36235 case X86::INDIRECT_THUNK_CALL32:
36236 return X86::CALLpcrel32;
36237 case X86::INDIRECT_THUNK_CALL64:
36238 return X86::CALL64pcrel32;
36239 case X86::INDIRECT_THUNK_TCRETURN32:
36240 return X86::TCRETURNdi;
36241 case X86::INDIRECT_THUNK_TCRETURN64:
36242 return X86::TCRETURNdi64;
36244 llvm_unreachable("not indirect thunk opcode");
36247 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
36248 unsigned Reg) {
36249 if (Subtarget.useRetpolineExternalThunk()) {
36250 // When using an external thunk for retpolines, we pick names that match the
36251 // names GCC happens to use as well. This helps simplify the implementation
36252 // of the thunks for kernels where they have no easy ability to create
36253 // aliases and are doing non-trivial configuration of the thunk's body. For
36254 // example, the Linux kernel will do boot-time hot patching of the thunk
36255 // bodies and cannot easily export aliases of these to loaded modules.
36257 // Note that at any point in the future, we may need to change the semantics
36258 // of how we implement retpolines and at that time will likely change the
36259 // name of the called thunk. Essentially, there is no hard guarantee that
36260 // LLVM will generate calls to specific thunks, we merely make a best-effort
36261 // attempt to help out kernels and other systems where duplicating the
36262 // thunks is costly.
36263 switch (Reg) {
36264 case X86::EAX:
36265 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36266 return "__x86_indirect_thunk_eax";
36267 case X86::ECX:
36268 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36269 return "__x86_indirect_thunk_ecx";
36270 case X86::EDX:
36271 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36272 return "__x86_indirect_thunk_edx";
36273 case X86::EDI:
36274 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36275 return "__x86_indirect_thunk_edi";
36276 case X86::R11:
36277 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
36278 return "__x86_indirect_thunk_r11";
36280 llvm_unreachable("unexpected reg for external indirect thunk");
36283 if (Subtarget.useRetpolineIndirectCalls() ||
36284 Subtarget.useRetpolineIndirectBranches()) {
36285 // When targeting an internal COMDAT thunk use an LLVM-specific name.
36286 switch (Reg) {
36287 case X86::EAX:
36288 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36289 return "__llvm_retpoline_eax";
36290 case X86::ECX:
36291 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36292 return "__llvm_retpoline_ecx";
36293 case X86::EDX:
36294 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36295 return "__llvm_retpoline_edx";
36296 case X86::EDI:
36297 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
36298 return "__llvm_retpoline_edi";
36299 case X86::R11:
36300 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
36301 return "__llvm_retpoline_r11";
36303 llvm_unreachable("unexpected reg for retpoline");
36306 if (Subtarget.useLVIControlFlowIntegrity()) {
36307 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
36308 return "__llvm_lvi_thunk_r11";
36310 llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
36313 MachineBasicBlock *
36314 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
36315 MachineBasicBlock *BB) const {
36316 // Copy the virtual register into the R11 physical register and
36317 // call the retpoline thunk.
36318 const MIMetadata MIMD(MI);
36319 const X86InstrInfo *TII = Subtarget.getInstrInfo();
36320 Register CalleeVReg = MI.getOperand(0).getReg();
36321 unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
36323 // Find an available scratch register to hold the callee. On 64-bit, we can
36324 // just use R11, but we scan for uses anyway to ensure we don't generate
36325 // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
36326 // already a register use operand to the call to hold the callee. If none
36327 // are available, use EDI instead. EDI is chosen because EBX is the PIC base
36328 // register and ESI is the base pointer to realigned stack frames with VLAs.
36329 SmallVector<unsigned, 3> AvailableRegs;
36330 if (Subtarget.is64Bit())
36331 AvailableRegs.push_back(X86::R11);
36332 else
36333 AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
36335 // Zero out any registers that are already used.
36336 for (const auto &MO : MI.operands()) {
36337 if (MO.isReg() && MO.isUse())
36338 llvm::replace(AvailableRegs, static_cast<unsigned>(MO.getReg()), 0U);
36341 // Choose the first remaining non-zero available register.
36342 unsigned AvailableReg = 0;
36343 for (unsigned MaybeReg : AvailableRegs) {
36344 if (MaybeReg) {
36345 AvailableReg = MaybeReg;
36346 break;
36349 if (!AvailableReg)
36350 report_fatal_error("calling convention incompatible with retpoline, no "
36351 "available registers");
36353 const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
36355 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), AvailableReg)
36356 .addReg(CalleeVReg);
36357 MI.getOperand(0).ChangeToES(Symbol);
36358 MI.setDesc(TII->get(Opc));
36359 MachineInstrBuilder(*BB->getParent(), &MI)
36360 .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
36361 return BB;
36364 /// SetJmp implies future control flow change upon calling the corresponding
36365 /// LongJmp.
36366 /// Instead of using the 'return' instruction, the long jump fixes the stack and
36367 /// performs an indirect branch. To do so it uses the registers that were stored
36368 /// in the jump buffer (when calling SetJmp).
36369 /// In case the shadow stack is enabled we need to fix it as well, because some
36370 /// return addresses will be skipped.
36371 /// The function will save the SSP for future fixing in the function
36372 /// emitLongJmpShadowStackFix.
36373 /// \sa emitLongJmpShadowStackFix
36374 /// \param [in] MI The temporary Machine Instruction for the builtin.
36375 /// \param [in] MBB The Machine Basic Block that will be modified.
36376 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
36377 MachineBasicBlock *MBB) const {
36378 const MIMetadata MIMD(MI);
36379 MachineFunction *MF = MBB->getParent();
36380 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36381 MachineRegisterInfo &MRI = MF->getRegInfo();
36382 MachineInstrBuilder MIB;
36384 // Memory Reference.
36385 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands());
36387 // Initialize a register with zero.
36388 MVT PVT = getPointerTy(MF->getDataLayout());
36389 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
36390 Register ZReg = MRI.createVirtualRegister(PtrRC);
36391 unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
36392 BuildMI(*MBB, MI, MIMD, TII->get(XorRROpc))
36393 .addDef(ZReg)
36394 .addReg(ZReg, RegState::Undef)
36395 .addReg(ZReg, RegState::Undef);
36397 // Read the current SSP Register value to the zeroed register.
36398 Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
36399 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
36400 BuildMI(*MBB, MI, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
36402 // Write the SSP register value to offset 3 in input memory buffer.
36403 unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
36404 MIB = BuildMI(*MBB, MI, MIMD, TII->get(PtrStoreOpc));
36405 const int64_t SSPOffset = 3 * PVT.getStoreSize();
36406 const unsigned MemOpndSlot = 1;
36407 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36408 if (i == X86::AddrDisp)
36409 MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
36410 else
36411 MIB.add(MI.getOperand(MemOpndSlot + i));
36413 MIB.addReg(SSPCopyReg);
36414 MIB.setMemRefs(MMOs);
36417 MachineBasicBlock *
36418 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
36419 MachineBasicBlock *MBB) const {
36420 const MIMetadata MIMD(MI);
36421 MachineFunction *MF = MBB->getParent();
36422 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36423 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
36424 MachineRegisterInfo &MRI = MF->getRegInfo();
36426 const BasicBlock *BB = MBB->getBasicBlock();
36427 MachineFunction::iterator I = ++MBB->getIterator();
36429 // Memory Reference
36430 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands());
36432 unsigned DstReg;
36433 unsigned MemOpndSlot = 0;
36435 unsigned CurOp = 0;
36437 DstReg = MI.getOperand(CurOp++).getReg();
36438 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
36439 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
36440 (void)TRI;
36441 Register mainDstReg = MRI.createVirtualRegister(RC);
36442 Register restoreDstReg = MRI.createVirtualRegister(RC);
36444 MemOpndSlot = CurOp;
36446 MVT PVT = getPointerTy(MF->getDataLayout());
36447 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
36448 "Invalid Pointer Size!");
36450 // For v = setjmp(buf), we generate
36452 // thisMBB:
36453 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
36454 // SjLjSetup restoreMBB
36456 // mainMBB:
36457 // v_main = 0
36459 // sinkMBB:
36460 // v = phi(main, restore)
36462 // restoreMBB:
36463 // if base pointer being used, load it from frame
36464 // v_restore = 1
36466 MachineBasicBlock *thisMBB = MBB;
36467 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
36468 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
36469 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
36470 MF->insert(I, mainMBB);
36471 MF->insert(I, sinkMBB);
36472 MF->push_back(restoreMBB);
36473 restoreMBB->setMachineBlockAddressTaken();
36475 MachineInstrBuilder MIB;
36477 // Transfer the remainder of BB and its successor edges to sinkMBB.
36478 sinkMBB->splice(sinkMBB->begin(), MBB,
36479 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
36480 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
36482 // thisMBB:
36483 unsigned PtrStoreOpc = 0;
36484 unsigned LabelReg = 0;
36485 const int64_t LabelOffset = 1 * PVT.getStoreSize();
36486 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
36487 !isPositionIndependent();
36489 // Prepare IP either in reg or imm.
36490 if (!UseImmLabel) {
36491 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
36492 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
36493 LabelReg = MRI.createVirtualRegister(PtrRC);
36494 if (Subtarget.is64Bit()) {
36495 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA64r), LabelReg)
36496 .addReg(X86::RIP)
36497 .addImm(0)
36498 .addReg(0)
36499 .addMBB(restoreMBB)
36500 .addReg(0);
36501 } else {
36502 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
36503 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA32r), LabelReg)
36504 .addReg(XII->getGlobalBaseReg(MF))
36505 .addImm(0)
36506 .addReg(0)
36507 .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
36508 .addReg(0);
36510 } else
36511 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
36512 // Store IP
36513 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrStoreOpc));
36514 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36515 if (i == X86::AddrDisp)
36516 MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
36517 else
36518 MIB.add(MI.getOperand(MemOpndSlot + i));
36520 if (!UseImmLabel)
36521 MIB.addReg(LabelReg);
36522 else
36523 MIB.addMBB(restoreMBB);
36524 MIB.setMemRefs(MMOs);
36526 if (MF->getFunction().getParent()->getModuleFlag("cf-protection-return")) {
36527 emitSetJmpShadowStackFix(MI, thisMBB);
36530 // Setup
36531 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::EH_SjLj_Setup))
36532 .addMBB(restoreMBB);
36534 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
36535 MIB.addRegMask(RegInfo->getNoPreservedMask());
36536 thisMBB->addSuccessor(mainMBB);
36537 thisMBB->addSuccessor(restoreMBB);
36539 // mainMBB:
36540 // EAX = 0
36541 BuildMI(mainMBB, MIMD, TII->get(X86::MOV32r0), mainDstReg);
36542 mainMBB->addSuccessor(sinkMBB);
36544 // sinkMBB:
36545 BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
36546 .addReg(mainDstReg)
36547 .addMBB(mainMBB)
36548 .addReg(restoreDstReg)
36549 .addMBB(restoreMBB);
36551 // restoreMBB:
36552 if (RegInfo->hasBasePointer(*MF)) {
36553 const bool Uses64BitFramePtr =
36554 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
36555 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
36556 X86FI->setRestoreBasePointer(MF);
36557 Register FramePtr = RegInfo->getFrameRegister(*MF);
36558 Register BasePtr = RegInfo->getBaseRegister();
36559 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
36560 addRegOffset(BuildMI(restoreMBB, MIMD, TII->get(Opm), BasePtr),
36561 FramePtr, true, X86FI->getRestoreBasePointerOffset())
36562 .setMIFlag(MachineInstr::FrameSetup);
36564 BuildMI(restoreMBB, MIMD, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
36565 BuildMI(restoreMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
36566 restoreMBB->addSuccessor(sinkMBB);
36568 MI.eraseFromParent();
36569 return sinkMBB;
36572 /// Fix the shadow stack using the previously saved SSP pointer.
36573 /// \sa emitSetJmpShadowStackFix
36574 /// \param [in] MI The temporary Machine Instruction for the builtin.
36575 /// \param [in] MBB The Machine Basic Block that will be modified.
36576 /// \return The sink MBB that will perform the future indirect branch.
36577 MachineBasicBlock *
36578 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
36579 MachineBasicBlock *MBB) const {
36580 const MIMetadata MIMD(MI);
36581 MachineFunction *MF = MBB->getParent();
36582 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36583 MachineRegisterInfo &MRI = MF->getRegInfo();
36585 // Memory Reference
36586 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands());
36588 MVT PVT = getPointerTy(MF->getDataLayout());
36589 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
36591 // checkSspMBB:
36592 // xor vreg1, vreg1
36593 // rdssp vreg1
36594 // test vreg1, vreg1
36595 // je sinkMBB # Jump if Shadow Stack is not supported
36596 // fallMBB:
36597 // mov buf+24/12(%rip), vreg2
36598 // sub vreg1, vreg2
36599 // jbe sinkMBB # No need to fix the Shadow Stack
36600 // fixShadowMBB:
36601 // shr 3/2, vreg2
36602 // incssp vreg2 # fix the SSP according to the lower 8 bits
36603 // shr 8, vreg2
36604 // je sinkMBB
36605 // fixShadowLoopPrepareMBB:
36606 // shl vreg2
36607 // mov 128, vreg3
36608 // fixShadowLoopMBB:
36609 // incssp vreg3
36610 // dec vreg2
36611 // jne fixShadowLoopMBB # Iterate until you finish fixing
36612 // # the Shadow Stack
36613 // sinkMBB:
36615 MachineFunction::iterator I = ++MBB->getIterator();
36616 const BasicBlock *BB = MBB->getBasicBlock();
36618 MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
36619 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
36620 MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
36621 MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
36622 MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
36623 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
36624 MF->insert(I, checkSspMBB);
36625 MF->insert(I, fallMBB);
36626 MF->insert(I, fixShadowMBB);
36627 MF->insert(I, fixShadowLoopPrepareMBB);
36628 MF->insert(I, fixShadowLoopMBB);
36629 MF->insert(I, sinkMBB);
36631 // Transfer the remainder of BB and its successor edges to sinkMBB.
36632 sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
36633 MBB->end());
36634 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
36636 MBB->addSuccessor(checkSspMBB);
36638 // Initialize a register with zero.
36639 Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
36640 BuildMI(checkSspMBB, MIMD, TII->get(X86::MOV32r0), ZReg);
36642 if (PVT == MVT::i64) {
36643 Register TmpZReg = MRI.createVirtualRegister(PtrRC);
36644 BuildMI(checkSspMBB, MIMD, TII->get(X86::SUBREG_TO_REG), TmpZReg)
36645 .addImm(0)
36646 .addReg(ZReg)
36647 .addImm(X86::sub_32bit);
36648 ZReg = TmpZReg;
36651 // Read the current SSP Register value to the zeroed register.
36652 Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
36653 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
36654 BuildMI(checkSspMBB, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
36656 // Check whether the result of the SSP register is zero and jump directly
36657 // to the sink.
36658 unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
36659 BuildMI(checkSspMBB, MIMD, TII->get(TestRROpc))
36660 .addReg(SSPCopyReg)
36661 .addReg(SSPCopyReg);
36662 BuildMI(checkSspMBB, MIMD, TII->get(X86::JCC_1))
36663 .addMBB(sinkMBB)
36664 .addImm(X86::COND_E);
36665 checkSspMBB->addSuccessor(sinkMBB);
36666 checkSspMBB->addSuccessor(fallMBB);
36668 // Reload the previously saved SSP register value.
36669 Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
36670 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
36671 const int64_t SPPOffset = 3 * PVT.getStoreSize();
36672 MachineInstrBuilder MIB =
36673 BuildMI(fallMBB, MIMD, TII->get(PtrLoadOpc), PrevSSPReg);
36674 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36675 const MachineOperand &MO = MI.getOperand(i);
36676 if (i == X86::AddrDisp)
36677 MIB.addDisp(MO, SPPOffset);
36678 else if (MO.isReg()) // Don't add the whole operand, we don't want to
36679 // preserve kill flags.
36680 MIB.addReg(MO.getReg());
36681 else
36682 MIB.add(MO);
36684 MIB.setMemRefs(MMOs);
36686 // Subtract the current SSP from the previous SSP.
36687 Register SspSubReg = MRI.createVirtualRegister(PtrRC);
36688 unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
36689 BuildMI(fallMBB, MIMD, TII->get(SubRROpc), SspSubReg)
36690 .addReg(PrevSSPReg)
36691 .addReg(SSPCopyReg);
36693 // Jump to sink in case PrevSSPReg <= SSPCopyReg.
36694 BuildMI(fallMBB, MIMD, TII->get(X86::JCC_1))
36695 .addMBB(sinkMBB)
36696 .addImm(X86::COND_BE);
36697 fallMBB->addSuccessor(sinkMBB);
36698 fallMBB->addSuccessor(fixShadowMBB);
36700 // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
36701 unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
36702 unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
36703 Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
36704 BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspFirstShrReg)
36705 .addReg(SspSubReg)
36706 .addImm(Offset);
36708 // Increase SSP when looking only on the lower 8 bits of the delta.
36709 unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
36710 BuildMI(fixShadowMBB, MIMD, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
36712 // Reset the lower 8 bits.
36713 Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
36714 BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspSecondShrReg)
36715 .addReg(SspFirstShrReg)
36716 .addImm(8);
36718 // Jump if the result of the shift is zero.
36719 BuildMI(fixShadowMBB, MIMD, TII->get(X86::JCC_1))
36720 .addMBB(sinkMBB)
36721 .addImm(X86::COND_E);
36722 fixShadowMBB->addSuccessor(sinkMBB);
36723 fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
36725 // Do a single shift left.
36726 unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64ri : X86::SHL32ri;
36727 Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
36728 BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(ShlR1Opc), SspAfterShlReg)
36729 .addReg(SspSecondShrReg)
36730 .addImm(1);
36732 // Save the value 128 to a register (will be used next with incssp).
36733 Register Value128InReg = MRI.createVirtualRegister(PtrRC);
36734 unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
36735 BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(MovRIOpc), Value128InReg)
36736 .addImm(128);
36737 fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
36739 // Since incssp only looks at the lower 8 bits, we might need to do several
36740 // iterations of incssp until we finish fixing the shadow stack.
36741 Register DecReg = MRI.createVirtualRegister(PtrRC);
36742 Register CounterReg = MRI.createVirtualRegister(PtrRC);
36743 BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::PHI), CounterReg)
36744 .addReg(SspAfterShlReg)
36745 .addMBB(fixShadowLoopPrepareMBB)
36746 .addReg(DecReg)
36747 .addMBB(fixShadowLoopMBB);
36749 // Every iteration we increase the SSP by 128.
36750 BuildMI(fixShadowLoopMBB, MIMD, TII->get(IncsspOpc)).addReg(Value128InReg);
36752 // Every iteration we decrement the counter by 1.
36753 unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
36754 BuildMI(fixShadowLoopMBB, MIMD, TII->get(DecROpc), DecReg).addReg(CounterReg);
36756 // Jump if the counter is not zero yet.
36757 BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::JCC_1))
36758 .addMBB(fixShadowLoopMBB)
36759 .addImm(X86::COND_NE);
36760 fixShadowLoopMBB->addSuccessor(sinkMBB);
36761 fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
36763 return sinkMBB;
36766 MachineBasicBlock *
36767 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
36768 MachineBasicBlock *MBB) const {
36769 const MIMetadata MIMD(MI);
36770 MachineFunction *MF = MBB->getParent();
36771 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
36772 MachineRegisterInfo &MRI = MF->getRegInfo();
36774 // Memory Reference
36775 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands());
36777 MVT PVT = getPointerTy(MF->getDataLayout());
36778 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
36779 "Invalid Pointer Size!");
36781 const TargetRegisterClass *RC =
36782 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
36783 Register Tmp = MRI.createVirtualRegister(RC);
36784 // Since FP is only updated here but NOT referenced, it's treated as GPR.
36785 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
36786 Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
36787 Register SP = RegInfo->getStackRegister();
36789 MachineInstrBuilder MIB;
36791 const int64_t LabelOffset = 1 * PVT.getStoreSize();
36792 const int64_t SPOffset = 2 * PVT.getStoreSize();
36794 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
36795 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
36797 MachineBasicBlock *thisMBB = MBB;
36799 // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
36800 if (MF->getFunction().getParent()->getModuleFlag("cf-protection-return")) {
36801 thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
36804 // Reload FP
36805 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), FP);
36806 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36807 const MachineOperand &MO = MI.getOperand(i);
36808 if (MO.isReg()) // Don't add the whole operand, we don't want to
36809 // preserve kill flags.
36810 MIB.addReg(MO.getReg());
36811 else
36812 MIB.add(MO);
36814 MIB.setMemRefs(MMOs);
36815 MIB.setMIFlag(MachineInstr::FrameDestroy);
36817 // Reload IP
36818 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), Tmp);
36819 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36820 const MachineOperand &MO = MI.getOperand(i);
36821 if (i == X86::AddrDisp)
36822 MIB.addDisp(MO, LabelOffset);
36823 else if (MO.isReg()) // Don't add the whole operand, we don't want to
36824 // preserve kill flags.
36825 MIB.addReg(MO.getReg());
36826 else
36827 MIB.add(MO);
36829 MIB.setMemRefs(MMOs);
36831 // Reload SP
36832 MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), SP);
36833 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
36834 if (i == X86::AddrDisp)
36835 MIB.addDisp(MI.getOperand(i), SPOffset);
36836 else
36837 MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
36838 // the last instruction of the expansion.
36840 MIB.setMemRefs(MMOs);
36841 MIB.setMIFlag(MachineInstr::FrameDestroy);
36843 // Jump
36844 BuildMI(*thisMBB, MI, MIMD, TII->get(IJmpOpc)).addReg(Tmp);
36846 MI.eraseFromParent();
36847 return thisMBB;
36850 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
36851 MachineBasicBlock *MBB,
36852 MachineBasicBlock *DispatchBB,
36853 int FI) const {
36854 const MIMetadata MIMD(MI);
36855 MachineFunction *MF = MBB->getParent();
36856 MachineRegisterInfo *MRI = &MF->getRegInfo();
36857 const X86InstrInfo *TII = Subtarget.getInstrInfo();
36859 MVT PVT = getPointerTy(MF->getDataLayout());
36860 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
36862 unsigned Op = 0;
36863 unsigned VR = 0;
36865 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
36866 !isPositionIndependent();
36868 if (UseImmLabel) {
36869 Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
36870 } else {
36871 const TargetRegisterClass *TRC =
36872 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
36873 VR = MRI->createVirtualRegister(TRC);
36874 Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
36876 if (Subtarget.is64Bit())
36877 BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA64r), VR)
36878 .addReg(X86::RIP)
36879 .addImm(1)
36880 .addReg(0)
36881 .addMBB(DispatchBB)
36882 .addReg(0);
36883 else
36884 BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA32r), VR)
36885 .addReg(0) /* TII->getGlobalBaseReg(MF) */
36886 .addImm(1)
36887 .addReg(0)
36888 .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
36889 .addReg(0);
36892 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MIMD, TII->get(Op));
36893 addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
36894 if (UseImmLabel)
36895 MIB.addMBB(DispatchBB);
36896 else
36897 MIB.addReg(VR);
36900 MachineBasicBlock *
36901 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
36902 MachineBasicBlock *BB) const {
36903 const MIMetadata MIMD(MI);
36904 MachineFunction *MF = BB->getParent();
36905 MachineRegisterInfo *MRI = &MF->getRegInfo();
36906 const X86InstrInfo *TII = Subtarget.getInstrInfo();
36907 int FI = MF->getFrameInfo().getFunctionContextIndex();
36909 // Get a mapping of the call site numbers to all of the landing pads they're
36910 // associated with.
36911 DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
36912 unsigned MaxCSNum = 0;
36913 for (auto &MBB : *MF) {
36914 if (!MBB.isEHPad())
36915 continue;
36917 MCSymbol *Sym = nullptr;
36918 for (const auto &MI : MBB) {
36919 if (MI.isDebugInstr())
36920 continue;
36922 assert(MI.isEHLabel() && "expected EH_LABEL");
36923 Sym = MI.getOperand(0).getMCSymbol();
36924 break;
36927 if (!MF->hasCallSiteLandingPad(Sym))
36928 continue;
36930 for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
36931 CallSiteNumToLPad[CSI].push_back(&MBB);
36932 MaxCSNum = std::max(MaxCSNum, CSI);
36936 // Get an ordered list of the machine basic blocks for the jump table.
36937 std::vector<MachineBasicBlock *> LPadList;
36938 SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
36939 LPadList.reserve(CallSiteNumToLPad.size());
36941 for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
36942 for (auto &LP : CallSiteNumToLPad[CSI]) {
36943 LPadList.push_back(LP);
36944 InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
36948 assert(!LPadList.empty() &&
36949 "No landing pad destinations for the dispatch jump table!");
36951 // Create the MBBs for the dispatch code.
36953 // Shove the dispatch's address into the return slot in the function context.
36954 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
36955 DispatchBB->setIsEHPad(true);
36957 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
36958 BuildMI(TrapBB, MIMD, TII->get(X86::TRAP));
36959 DispatchBB->addSuccessor(TrapBB);
36961 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
36962 DispatchBB->addSuccessor(DispContBB);
36964 // Insert MBBs.
36965 MF->push_back(DispatchBB);
36966 MF->push_back(DispContBB);
36967 MF->push_back(TrapBB);
36969 // Insert code into the entry block that creates and registers the function
36970 // context.
36971 SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
36973 // Create the jump table and associated information
36974 unsigned JTE = getJumpTableEncoding();
36975 MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
36976 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
36978 const X86RegisterInfo &RI = TII->getRegisterInfo();
36979 // Add a register mask with no preserved registers. This results in all
36980 // registers being marked as clobbered.
36981 if (RI.hasBasePointer(*MF)) {
36982 const bool FPIs64Bit =
36983 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
36984 X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
36985 MFI->setRestoreBasePointer(MF);
36987 Register FP = RI.getFrameRegister(*MF);
36988 Register BP = RI.getBaseRegister();
36989 unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
36990 addRegOffset(BuildMI(DispatchBB, MIMD, TII->get(Op), BP), FP, true,
36991 MFI->getRestoreBasePointerOffset())
36992 .addRegMask(RI.getNoPreservedMask());
36993 } else {
36994 BuildMI(DispatchBB, MIMD, TII->get(X86::NOOP))
36995 .addRegMask(RI.getNoPreservedMask());
36998 // IReg is used as an index in a memory operand and therefore can't be SP
36999 Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
37000 addFrameReference(BuildMI(DispatchBB, MIMD, TII->get(X86::MOV32rm), IReg), FI,
37001 Subtarget.is64Bit() ? 8 : 4);
37002 BuildMI(DispatchBB, MIMD, TII->get(X86::CMP32ri))
37003 .addReg(IReg)
37004 .addImm(LPadList.size());
37005 BuildMI(DispatchBB, MIMD, TII->get(X86::JCC_1))
37006 .addMBB(TrapBB)
37007 .addImm(X86::COND_AE);
37009 if (Subtarget.is64Bit()) {
37010 Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
37011 Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
37013 // leaq .LJTI0_0(%rip), BReg
37014 BuildMI(DispContBB, MIMD, TII->get(X86::LEA64r), BReg)
37015 .addReg(X86::RIP)
37016 .addImm(1)
37017 .addReg(0)
37018 .addJumpTableIndex(MJTI)
37019 .addReg(0);
37020 // movzx IReg64, IReg
37021 BuildMI(DispContBB, MIMD, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
37022 .addImm(0)
37023 .addReg(IReg)
37024 .addImm(X86::sub_32bit);
37026 switch (JTE) {
37027 case MachineJumpTableInfo::EK_BlockAddress:
37028 // jmpq *(BReg,IReg64,8)
37029 BuildMI(DispContBB, MIMD, TII->get(X86::JMP64m))
37030 .addReg(BReg)
37031 .addImm(8)
37032 .addReg(IReg64)
37033 .addImm(0)
37034 .addReg(0);
37035 break;
37036 case MachineJumpTableInfo::EK_LabelDifference32: {
37037 Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
37038 Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
37039 Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
37041 // movl (BReg,IReg64,4), OReg
37042 BuildMI(DispContBB, MIMD, TII->get(X86::MOV32rm), OReg)
37043 .addReg(BReg)
37044 .addImm(4)
37045 .addReg(IReg64)
37046 .addImm(0)
37047 .addReg(0);
37048 // movsx OReg64, OReg
37049 BuildMI(DispContBB, MIMD, TII->get(X86::MOVSX64rr32), OReg64)
37050 .addReg(OReg);
37051 // addq BReg, OReg64, TReg
37052 BuildMI(DispContBB, MIMD, TII->get(X86::ADD64rr), TReg)
37053 .addReg(OReg64)
37054 .addReg(BReg);
37055 // jmpq *TReg
37056 BuildMI(DispContBB, MIMD, TII->get(X86::JMP64r)).addReg(TReg);
37057 break;
37059 default:
37060 llvm_unreachable("Unexpected jump table encoding");
37062 } else {
37063 // jmpl *.LJTI0_0(,IReg,4)
37064 BuildMI(DispContBB, MIMD, TII->get(X86::JMP32m))
37065 .addReg(0)
37066 .addImm(4)
37067 .addReg(IReg)
37068 .addJumpTableIndex(MJTI)
37069 .addReg(0);
37072 // Add the jump table entries as successors to the MBB.
37073 SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
37074 for (auto &LP : LPadList)
37075 if (SeenMBBs.insert(LP).second)
37076 DispContBB->addSuccessor(LP);
37078 // N.B. the order the invoke BBs are processed in doesn't matter here.
37079 SmallVector<MachineBasicBlock *, 64> MBBLPads;
37080 const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
37081 for (MachineBasicBlock *MBB : InvokeBBs) {
37082 // Remove the landing pad successor from the invoke block and replace it
37083 // with the new dispatch block.
37084 // Keep a copy of Successors since it's modified inside the loop.
37085 SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
37086 MBB->succ_rend());
37087 // FIXME: Avoid quadratic complexity.
37088 for (auto *MBBS : Successors) {
37089 if (MBBS->isEHPad()) {
37090 MBB->removeSuccessor(MBBS);
37091 MBBLPads.push_back(MBBS);
37095 MBB->addSuccessor(DispatchBB);
37097 // Find the invoke call and mark all of the callee-saved registers as
37098 // 'implicit defined' so that they're spilled. This prevents code from
37099 // moving instructions to before the EH block, where they will never be
37100 // executed.
37101 for (auto &II : reverse(*MBB)) {
37102 if (!II.isCall())
37103 continue;
37105 DenseMap<unsigned, bool> DefRegs;
37106 for (auto &MOp : II.operands())
37107 if (MOp.isReg())
37108 DefRegs[MOp.getReg()] = true;
37110 MachineInstrBuilder MIB(*MF, &II);
37111 for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
37112 unsigned Reg = SavedRegs[RegIdx];
37113 if (!DefRegs[Reg])
37114 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
37117 break;
37121 // Mark all former landing pads as non-landing pads. The dispatch is the only
37122 // landing pad now.
37123 for (auto &LP : MBBLPads)
37124 LP->setIsEHPad(false);
37126 // The instruction is gone now.
37127 MI.eraseFromParent();
37128 return BB;
37131 MachineBasicBlock *
37132 X86TargetLowering::emitPatchableEventCall(MachineInstr &MI,
37133 MachineBasicBlock *BB) const {
37134 // Wrap patchable event calls in CALLSEQ_START/CALLSEQ_END, as tracing
37135 // calls may require proper stack alignment.
37136 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
37137 const MIMetadata MIMD(MI);
37138 MachineFunction &MF = *BB->getParent();
37140 // Emit CALLSEQ_START right before the instruction.
37141 MF.getFrameInfo().setAdjustsStack(true);
37142 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
37143 MachineInstrBuilder CallseqStart =
37144 BuildMI(MF, MIMD, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
37145 BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
37147 // Emit CALLSEQ_END right after the instruction.
37148 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
37149 MachineInstrBuilder CallseqEnd =
37150 BuildMI(MF, MIMD, TII.get(AdjStackUp)).addImm(0).addImm(0);
37151 BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
37153 return BB;
37156 MachineBasicBlock *
37157 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
37158 MachineBasicBlock *BB) const {
37159 MachineFunction *MF = BB->getParent();
37160 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
37161 const MIMetadata MIMD(MI);
37163 auto TMMImmToTMMReg = [](unsigned Imm) {
37164 assert (Imm < 8 && "Illegal tmm index");
37165 return X86::TMM0 + Imm;
37167 auto TMMImmToTMMPair = [](unsigned Imm) {
37168 assert(Imm < 8 && "Illegal tmm pair index.");
37169 return X86::TMM0_TMM1 + Imm / 2;
37171 switch (MI.getOpcode()) {
37172 default:
37173 llvm_unreachable("Unexpected instr type to insert");
37174 case X86::INDIRECT_THUNK_CALL32:
37175 case X86::INDIRECT_THUNK_CALL64:
37176 case X86::INDIRECT_THUNK_TCRETURN32:
37177 case X86::INDIRECT_THUNK_TCRETURN64:
37178 return EmitLoweredIndirectThunk(MI, BB);
37179 case X86::CATCHRET:
37180 return EmitLoweredCatchRet(MI, BB);
37181 case X86::SEG_ALLOCA_32:
37182 case X86::SEG_ALLOCA_64:
37183 return EmitLoweredSegAlloca(MI, BB);
37184 case X86::PROBED_ALLOCA_32:
37185 case X86::PROBED_ALLOCA_64:
37186 return EmitLoweredProbedAlloca(MI, BB);
37187 case X86::TLSCall_32:
37188 case X86::TLSCall_64:
37189 return EmitLoweredTLSCall(MI, BB);
37190 case X86::CMOV_FR16:
37191 case X86::CMOV_FR16X:
37192 case X86::CMOV_FR32:
37193 case X86::CMOV_FR32X:
37194 case X86::CMOV_FR64:
37195 case X86::CMOV_FR64X:
37196 case X86::CMOV_GR8:
37197 case X86::CMOV_GR16:
37198 case X86::CMOV_GR32:
37199 case X86::CMOV_RFP32:
37200 case X86::CMOV_RFP64:
37201 case X86::CMOV_RFP80:
37202 case X86::CMOV_VR64:
37203 case X86::CMOV_VR128:
37204 case X86::CMOV_VR128X:
37205 case X86::CMOV_VR256:
37206 case X86::CMOV_VR256X:
37207 case X86::CMOV_VR512:
37208 case X86::CMOV_VK1:
37209 case X86::CMOV_VK2:
37210 case X86::CMOV_VK4:
37211 case X86::CMOV_VK8:
37212 case X86::CMOV_VK16:
37213 case X86::CMOV_VK32:
37214 case X86::CMOV_VK64:
37215 return EmitLoweredSelect(MI, BB);
37217 case X86::FP80_ADDr:
37218 case X86::FP80_ADDm32: {
37219 // Change the floating point control register to use double extended
37220 // precision when performing the addition.
37221 int OrigCWFrameIdx =
37222 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
37223 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
37224 OrigCWFrameIdx);
37226 // Load the old value of the control word...
37227 Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
37228 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
37229 OrigCWFrameIdx);
37231 // OR 0b11 into bit 8 and 9. 0b11 is the encoding for double extended
37232 // precision.
37233 Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
37234 BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
37235 .addReg(OldCW, RegState::Kill)
37236 .addImm(0x300);
37238 // Extract to 16 bits.
37239 Register NewCW16 =
37240 MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
37241 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
37242 .addReg(NewCW, RegState::Kill, X86::sub_16bit);
37244 // Prepare memory for FLDCW.
37245 int NewCWFrameIdx =
37246 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
37247 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
37248 NewCWFrameIdx)
37249 .addReg(NewCW16, RegState::Kill);
37251 // Reload the modified control word now...
37252 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
37253 NewCWFrameIdx);
37255 // Do the addition.
37256 if (MI.getOpcode() == X86::FP80_ADDr) {
37257 BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80))
37258 .add(MI.getOperand(0))
37259 .add(MI.getOperand(1))
37260 .add(MI.getOperand(2));
37261 } else {
37262 BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80m32))
37263 .add(MI.getOperand(0))
37264 .add(MI.getOperand(1))
37265 .add(MI.getOperand(2))
37266 .add(MI.getOperand(3))
37267 .add(MI.getOperand(4))
37268 .add(MI.getOperand(5))
37269 .add(MI.getOperand(6));
37272 // Reload the original control word now.
37273 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
37274 OrigCWFrameIdx);
37276 MI.eraseFromParent(); // The pseudo instruction is gone now.
37277 return BB;
37280 case X86::FP32_TO_INT16_IN_MEM:
37281 case X86::FP32_TO_INT32_IN_MEM:
37282 case X86::FP32_TO_INT64_IN_MEM:
37283 case X86::FP64_TO_INT16_IN_MEM:
37284 case X86::FP64_TO_INT32_IN_MEM:
37285 case X86::FP64_TO_INT64_IN_MEM:
37286 case X86::FP80_TO_INT16_IN_MEM:
37287 case X86::FP80_TO_INT32_IN_MEM:
37288 case X86::FP80_TO_INT64_IN_MEM: {
37289 // Change the floating point control register to use "round towards zero"
37290 // mode when truncating to an integer value.
37291 int OrigCWFrameIdx =
37292 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
37293 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
37294 OrigCWFrameIdx);
37296 // Load the old value of the control word...
37297 Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
37298 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
37299 OrigCWFrameIdx);
37301 // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
37302 Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
37303 BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
37304 .addReg(OldCW, RegState::Kill).addImm(0xC00);
37306 // Extract to 16 bits.
37307 Register NewCW16 =
37308 MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
37309 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
37310 .addReg(NewCW, RegState::Kill, X86::sub_16bit);
37312 // Prepare memory for FLDCW.
37313 int NewCWFrameIdx =
37314 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
37315 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
37316 NewCWFrameIdx)
37317 .addReg(NewCW16, RegState::Kill);
37319 // Reload the modified control word now...
37320 addFrameReference(BuildMI(*BB, MI, MIMD,
37321 TII->get(X86::FLDCW16m)), NewCWFrameIdx);
37323 // Get the X86 opcode to use.
37324 unsigned Opc;
37325 switch (MI.getOpcode()) {
37326 // clang-format off
37327 default: llvm_unreachable("illegal opcode!");
37328 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
37329 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
37330 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
37331 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
37332 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
37333 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
37334 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
37335 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
37336 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
37337 // clang-format on
37340 X86AddressMode AM = getAddressFromInstr(&MI, 0);
37341 addFullAddress(BuildMI(*BB, MI, MIMD, TII->get(Opc)), AM)
37342 .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
37344 // Reload the original control word now.
37345 addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
37346 OrigCWFrameIdx);
37348 MI.eraseFromParent(); // The pseudo instruction is gone now.
37349 return BB;
37352 // xbegin
37353 case X86::XBEGIN:
37354 return emitXBegin(MI, BB, Subtarget.getInstrInfo());
37356 case X86::VAARG_64:
37357 case X86::VAARG_X32:
37358 return EmitVAARGWithCustomInserter(MI, BB);
37360 case X86::EH_SjLj_SetJmp32:
37361 case X86::EH_SjLj_SetJmp64:
37362 return emitEHSjLjSetJmp(MI, BB);
37364 case X86::EH_SjLj_LongJmp32:
37365 case X86::EH_SjLj_LongJmp64:
37366 return emitEHSjLjLongJmp(MI, BB);
37368 case X86::Int_eh_sjlj_setup_dispatch:
37369 return EmitSjLjDispatchBlock(MI, BB);
37371 case TargetOpcode::STATEPOINT:
37372 // As an implementation detail, STATEPOINT shares the STACKMAP format at
37373 // this point in the process. We diverge later.
37374 return emitPatchPoint(MI, BB);
37376 case TargetOpcode::STACKMAP:
37377 case TargetOpcode::PATCHPOINT:
37378 return emitPatchPoint(MI, BB);
37380 case TargetOpcode::PATCHABLE_EVENT_CALL:
37381 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
37382 return emitPatchableEventCall(MI, BB);
37384 case X86::LCMPXCHG8B: {
37385 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
37386 // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
37387 // requires a memory operand. If it happens that current architecture is
37388 // i686 and for current function we need a base pointer
37389 // - which is ESI for i686 - register allocator would not be able to
37390 // allocate registers for an address in form of X(%reg, %reg, Y)
37391 // - there never would be enough unreserved registers during regalloc
37392 // (without the need for base ptr the only option would be X(%edi, %esi, Y).
37393 // We are giving a hand to register allocator by precomputing the address in
37394 // a new vreg using LEA.
37396 // If it is not i686 or there is no base pointer - nothing to do here.
37397 if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
37398 return BB;
37400 // Even though this code does not necessarily needs the base pointer to
37401 // be ESI, we check for that. The reason: if this assert fails, there are
37402 // some changes happened in the compiler base pointer handling, which most
37403 // probably have to be addressed somehow here.
37404 assert(TRI->getBaseRegister() == X86::ESI &&
37405 "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
37406 "base pointer in mind");
37408 MachineRegisterInfo &MRI = MF->getRegInfo();
37409 MVT SPTy = getPointerTy(MF->getDataLayout());
37410 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
37411 Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
37413 X86AddressMode AM = getAddressFromInstr(&MI, 0);
37414 // Regalloc does not need any help when the memory operand of CMPXCHG8B
37415 // does not use index register.
37416 if (AM.IndexReg == X86::NoRegister)
37417 return BB;
37419 // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
37420 // four operand definitions that are E[ABCD] registers. We skip them and
37421 // then insert the LEA.
37422 MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
37423 while (RMBBI != BB->rend() &&
37424 (RMBBI->definesRegister(X86::EAX, /*TRI=*/nullptr) ||
37425 RMBBI->definesRegister(X86::EBX, /*TRI=*/nullptr) ||
37426 RMBBI->definesRegister(X86::ECX, /*TRI=*/nullptr) ||
37427 RMBBI->definesRegister(X86::EDX, /*TRI=*/nullptr))) {
37428 ++RMBBI;
37430 MachineBasicBlock::iterator MBBI(RMBBI);
37431 addFullAddress(
37432 BuildMI(*BB, *MBBI, MIMD, TII->get(X86::LEA32r), computedAddrVReg), AM);
37434 setDirectAddressInInstr(&MI, 0, computedAddrVReg);
37436 return BB;
37438 case X86::LCMPXCHG16B_NO_RBX: {
37439 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
37440 Register BasePtr = TRI->getBaseRegister();
37441 if (TRI->hasBasePointer(*MF) &&
37442 (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
37443 if (!BB->isLiveIn(BasePtr))
37444 BB->addLiveIn(BasePtr);
37445 // Save RBX into a virtual register.
37446 Register SaveRBX =
37447 MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
37448 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
37449 .addReg(X86::RBX);
37450 Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
37451 MachineInstrBuilder MIB =
37452 BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
37453 for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
37454 MIB.add(MI.getOperand(Idx));
37455 MIB.add(MI.getOperand(X86::AddrNumOperands));
37456 MIB.addReg(SaveRBX);
37457 } else {
37458 // Simple case, just copy the virtual register to RBX.
37459 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::RBX)
37460 .add(MI.getOperand(X86::AddrNumOperands));
37461 MachineInstrBuilder MIB =
37462 BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B));
37463 for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
37464 MIB.add(MI.getOperand(Idx));
37466 MI.eraseFromParent();
37467 return BB;
37469 case X86::MWAITX: {
37470 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
37471 Register BasePtr = TRI->getBaseRegister();
37472 bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
37473 // If no need to save the base pointer, we generate MWAITXrrr,
37474 // else we generate pseudo MWAITX_SAVE_RBX.
37475 if (!IsRBX || !TRI->hasBasePointer(*MF)) {
37476 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
37477 .addReg(MI.getOperand(0).getReg());
37478 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
37479 .addReg(MI.getOperand(1).getReg());
37480 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EBX)
37481 .addReg(MI.getOperand(2).getReg());
37482 BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITXrrr));
37483 MI.eraseFromParent();
37484 } else {
37485 if (!BB->isLiveIn(BasePtr)) {
37486 BB->addLiveIn(BasePtr);
37488 // Parameters can be copied into ECX and EAX but not EBX yet.
37489 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
37490 .addReg(MI.getOperand(0).getReg());
37491 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
37492 .addReg(MI.getOperand(1).getReg());
37493 assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
37494 // Save RBX into a virtual register.
37495 Register SaveRBX =
37496 MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
37497 BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
37498 .addReg(X86::RBX);
37499 // Generate mwaitx pseudo.
37500 Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
37501 BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITX_SAVE_RBX))
37502 .addDef(Dst) // Destination tied in with SaveRBX.
37503 .addReg(MI.getOperand(2).getReg()) // input value of EBX.
37504 .addUse(SaveRBX); // Save of base pointer.
37505 MI.eraseFromParent();
37507 return BB;
37509 case TargetOpcode::PREALLOCATED_SETUP: {
37510 assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
37511 auto *MFI = MF->getInfo<X86MachineFunctionInfo>();
37512 MFI->setHasPreallocatedCall(true);
37513 int64_t PreallocatedId = MI.getOperand(0).getImm();
37514 size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
37515 assert(StackAdjustment != 0 && "0 stack adjustment");
37516 LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
37517 << StackAdjustment << "\n");
37518 BuildMI(*BB, MI, MIMD, TII->get(X86::SUB32ri), X86::ESP)
37519 .addReg(X86::ESP)
37520 .addImm(StackAdjustment);
37521 MI.eraseFromParent();
37522 return BB;
37524 case TargetOpcode::PREALLOCATED_ARG: {
37525 assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
37526 int64_t PreallocatedId = MI.getOperand(1).getImm();
37527 int64_t ArgIdx = MI.getOperand(2).getImm();
37528 auto *MFI = MF->getInfo<X86MachineFunctionInfo>();
37529 size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
37530 LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
37531 << ", arg offset " << ArgOffset << "\n");
37532 // stack pointer + offset
37533 addRegOffset(BuildMI(*BB, MI, MIMD, TII->get(X86::LEA32r),
37534 MI.getOperand(0).getReg()),
37535 X86::ESP, false, ArgOffset);
37536 MI.eraseFromParent();
37537 return BB;
37539 case X86::PTDPBSSD:
37540 case X86::PTDPBSUD:
37541 case X86::PTDPBUSD:
37542 case X86::PTDPBUUD:
37543 case X86::PTDPBF16PS:
37544 case X86::PTDPFP16PS:
37545 case X86::PTCMMIMFP16PS:
37546 case X86::PTCMMRLFP16PS:
37547 case X86::PTDPBF8PS:
37548 case X86::PTDPBHF8PS:
37549 case X86::PTDPHBF8PS:
37550 case X86::PTDPHF8PS:
37551 case X86::PTTDPBF16PS:
37552 case X86::PTTDPFP16PS:
37553 case X86::PTTCMMIMFP16PS:
37554 case X86::PTTCMMRLFP16PS:
37555 case X86::PTCONJTCMMIMFP16PS:
37556 case X86::PTMMULTF32PS:
37557 case X86::PTTMMULTF32PS: {
37558 unsigned Opc;
37559 switch (MI.getOpcode()) {
37560 default: llvm_unreachable("illegal opcode!");
37561 case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
37562 case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
37563 case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
37564 case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
37565 case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
37566 case X86::PTDPFP16PS: Opc = X86::TDPFP16PS; break;
37567 case X86::PTCMMIMFP16PS:
37568 Opc = X86::TCMMIMFP16PS;
37569 break;
37570 case X86::PTCMMRLFP16PS:
37571 Opc = X86::TCMMRLFP16PS;
37572 break;
37573 case X86::PTDPBF8PS: Opc = X86::TDPBF8PS; break;
37574 case X86::PTDPBHF8PS: Opc = X86::TDPBHF8PS; break;
37575 case X86::PTDPHBF8PS: Opc = X86::TDPHBF8PS; break;
37576 case X86::PTDPHF8PS: Opc = X86::TDPHF8PS; break;
37577 case X86::PTTDPBF16PS:
37578 Opc = X86::TTDPBF16PS;
37579 break;
37580 case X86::PTTDPFP16PS:
37581 Opc = X86::TTDPFP16PS;
37582 break;
37583 case X86::PTTCMMIMFP16PS:
37584 Opc = X86::TTCMMIMFP16PS;
37585 break;
37586 case X86::PTTCMMRLFP16PS:
37587 Opc = X86::TTCMMRLFP16PS;
37588 break;
37589 case X86::PTCONJTCMMIMFP16PS:
37590 Opc = X86::TCONJTCMMIMFP16PS;
37591 break;
37592 case X86::PTMMULTF32PS:
37593 Opc = X86::TMMULTF32PS;
37594 break;
37595 case X86::PTTMMULTF32PS:
37596 Opc = X86::TTMMULTF32PS;
37597 break;
37600 MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
37601 MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
37602 MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
37603 MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
37604 MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
37606 MI.eraseFromParent(); // The pseudo is gone now.
37607 return BB;
37609 case X86::PTILEZERO: {
37610 unsigned Imm = MI.getOperand(0).getImm();
37611 BuildMI(*BB, MI, MIMD, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
37612 MI.eraseFromParent(); // The pseudo is gone now.
37613 auto *MFI = MF->getInfo<X86MachineFunctionInfo>();
37614 MFI->setAMXProgModel(AMXProgModelEnum::DirectReg);
37615 return BB;
37617 case X86::PTILEZEROV: {
37618 auto *MFI = MF->getInfo<X86MachineFunctionInfo>();
37619 MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
37620 return BB;
37622 case X86::PTILELOADDRS:
37623 case X86::PTILELOADDRST1:
37624 case X86::PTILELOADD:
37625 case X86::PTILELOADDT1:
37626 case X86::PTILESTORED: {
37627 unsigned Opc;
37628 switch (MI.getOpcode()) {
37629 default: llvm_unreachable("illegal opcode!");
37630 #define GET_EGPR_IF_ENABLED(OPC) (Subtarget.hasEGPR() ? OPC##_EVEX : OPC)
37631 case X86::PTILELOADD:
37632 Opc = GET_EGPR_IF_ENABLED(X86::TILELOADD);
37633 break;
37634 case X86::PTILELOADDT1:
37635 Opc = GET_EGPR_IF_ENABLED(X86::TILELOADDT1);
37636 break;
37637 case X86::PTILESTORED:
37638 Opc = GET_EGPR_IF_ENABLED(X86::TILESTORED);
37639 break;
37640 #undef GET_EGPR_IF_ENABLED
37641 case X86::PTILELOADDRS:
37642 Opc = X86::TILELOADDRS;
37643 break;
37644 case X86::PTILELOADDRST1:
37645 Opc = X86::TILELOADDRST1;
37646 break;
37649 MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
37650 unsigned CurOp = 0;
37651 if (Opc != X86::TILESTORED && Opc != X86::TILESTORED_EVEX)
37652 MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
37653 RegState::Define);
37655 MIB.add(MI.getOperand(CurOp++)); // base
37656 MIB.add(MI.getOperand(CurOp++)); // scale
37657 MIB.add(MI.getOperand(CurOp++)); // index -- stride
37658 MIB.add(MI.getOperand(CurOp++)); // displacement
37659 MIB.add(MI.getOperand(CurOp++)); // segment
37661 if (Opc == X86::TILESTORED || Opc == X86::TILESTORED_EVEX)
37662 MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
37663 RegState::Undef);
37665 MI.eraseFromParent(); // The pseudo is gone now.
37666 return BB;
37668 case X86::PT2RPNTLVWZ0:
37669 case X86::PT2RPNTLVWZ0T1:
37670 case X86::PT2RPNTLVWZ1:
37671 case X86::PT2RPNTLVWZ1T1:
37672 case X86::PT2RPNTLVWZ0RS:
37673 case X86::PT2RPNTLVWZ0RST1:
37674 case X86::PT2RPNTLVWZ1RS:
37675 case X86::PT2RPNTLVWZ1RST1: {
37676 const DebugLoc &DL = MI.getDebugLoc();
37677 unsigned Opc;
37678 switch (MI.getOpcode()) {
37679 default:
37680 llvm_unreachable("Unexpected instruction!");
37681 case X86::PT2RPNTLVWZ0:
37682 Opc = X86::T2RPNTLVWZ0;
37683 break;
37684 case X86::PT2RPNTLVWZ0T1:
37685 Opc = X86::T2RPNTLVWZ0T1;
37686 break;
37687 case X86::PT2RPNTLVWZ1:
37688 Opc = X86::T2RPNTLVWZ1;
37689 break;
37690 case X86::PT2RPNTLVWZ1T1:
37691 Opc = X86::T2RPNTLVWZ1T1;
37692 break;
37693 case X86::PT2RPNTLVWZ0RS:
37694 Opc = X86::T2RPNTLVWZ0RS;
37695 break;
37696 case X86::PT2RPNTLVWZ0RST1:
37697 Opc = X86::T2RPNTLVWZ0RST1;
37698 break;
37699 case X86::PT2RPNTLVWZ1RS:
37700 Opc = X86::T2RPNTLVWZ1RS;
37701 break;
37702 case X86::PT2RPNTLVWZ1RST1:
37703 Opc = X86::T2RPNTLVWZ1RST1;
37704 break;
37706 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
37707 MIB.addReg(TMMImmToTMMPair(MI.getOperand(0).getImm()), RegState::Define);
37709 MIB.add(MI.getOperand(1)); // base
37710 MIB.add(MI.getOperand(2)); // scale
37711 MIB.add(MI.getOperand(3)); // index
37712 MIB.add(MI.getOperand(4)); // displacement
37713 MIB.add(MI.getOperand(5)); // segment
37714 MI.eraseFromParent(); // The pseudo is gone now.
37715 return BB;
37717 case X86::PTTRANSPOSED:
37718 case X86::PTCONJTFP16: {
37719 const DebugLoc &DL = MI.getDebugLoc();
37720 unsigned Opc = MI.getOpcode() == X86::PTTRANSPOSED ? X86::TTRANSPOSED
37721 : X86::TCONJTFP16;
37723 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
37724 MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
37725 MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
37727 MI.eraseFromParent(); // The pseudo is gone now.
37728 return BB;
37730 case X86::PTCVTROWPS2PBF16Hrri:
37731 case X86::PTCVTROWPS2PBF16Lrri:
37732 case X86::PTCVTROWPS2PHHrri:
37733 case X86::PTCVTROWPS2PHLrri:
37734 case X86::PTCVTROWD2PSrri:
37735 case X86::PTILEMOVROWrri: {
37736 const DebugLoc &DL = MI.getDebugLoc();
37737 unsigned Opc;
37738 switch (MI.getOpcode()) {
37739 default:
37740 llvm_unreachable("Unexpected instruction!");
37741 case X86::PTCVTROWD2PSrri:
37742 Opc = X86::TCVTROWD2PSrri;
37743 break;
37744 case X86::PTCVTROWPS2PBF16Hrri:
37745 Opc = X86::TCVTROWPS2PBF16Hrri;
37746 break;
37747 case X86::PTCVTROWPS2PHHrri:
37748 Opc = X86::TCVTROWPS2PHHrri;
37749 break;
37750 case X86::PTCVTROWPS2PBF16Lrri:
37751 Opc = X86::TCVTROWPS2PBF16Lrri;
37752 break;
37753 case X86::PTCVTROWPS2PHLrri:
37754 Opc = X86::TCVTROWPS2PHLrri;
37755 break;
37756 case X86::PTILEMOVROWrri:
37757 Opc = X86::TILEMOVROWrri;
37758 break;
37760 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
37761 MIB.add(MI.getOperand(0));
37762 MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
37763 MIB.addImm(MI.getOperand(2).getImm());
37765 MI.eraseFromParent(); // The pseudo is gone now.
37766 return BB;
37768 case X86::PTCVTROWPS2PBF16Hrre:
37769 case X86::PTCVTROWPS2PBF16Lrre:
37770 case X86::PTCVTROWPS2PHHrre:
37771 case X86::PTCVTROWPS2PHLrre:
37772 case X86::PTCVTROWD2PSrre:
37773 case X86::PTILEMOVROWrre: {
37774 const DebugLoc &DL = MI.getDebugLoc();
37775 unsigned Opc;
37776 switch (MI.getOpcode()) {
37777 default:
37778 llvm_unreachable("Unexpected instruction!");
37779 case X86::PTCVTROWD2PSrre:
37780 Opc = X86::TCVTROWD2PSrre;
37781 break;
37782 case X86::PTCVTROWPS2PBF16Hrre:
37783 Opc = X86::TCVTROWPS2PBF16Hrre;
37784 break;
37785 case X86::PTCVTROWPS2PBF16Lrre:
37786 Opc = X86::TCVTROWPS2PBF16Lrre;
37787 break;
37788 case X86::PTCVTROWPS2PHHrre:
37789 Opc = X86::TCVTROWPS2PHHrre;
37790 break;
37791 case X86::PTCVTROWPS2PHLrre:
37792 Opc = X86::TCVTROWPS2PHLrre;
37793 break;
37794 case X86::PTILEMOVROWrre:
37795 Opc = X86::TILEMOVROWrre;
37796 break;
37798 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
37799 MIB.add(MI.getOperand(0));
37800 MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
37801 MIB.add(MI.getOperand(2));
37803 MI.eraseFromParent(); // The pseudo is gone now.
37804 return BB;
37809 //===----------------------------------------------------------------------===//
37810 // X86 Optimization Hooks
37811 //===----------------------------------------------------------------------===//
37813 bool
37814 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
37815 const APInt &DemandedBits,
37816 const APInt &DemandedElts,
37817 TargetLoweringOpt &TLO) const {
37818 EVT VT = Op.getValueType();
37819 unsigned Opcode = Op.getOpcode();
37820 unsigned EltSize = VT.getScalarSizeInBits();
37822 if (VT.isVector()) {
37823 // If the constant is only all signbits in the active bits, then we should
37824 // extend it to the entire constant to allow it act as a boolean constant
37825 // vector.
37826 auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
37827 if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
37828 return false;
37829 for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
37830 if (!DemandedElts[i] || V.getOperand(i).isUndef())
37831 continue;
37832 const APInt &Val = V.getConstantOperandAPInt(i);
37833 if (Val.getBitWidth() > Val.getNumSignBits() &&
37834 Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
37835 return true;
37837 return false;
37839 // For vectors - if we have a constant, then try to sign extend.
37840 // TODO: Handle AND cases.
37841 unsigned ActiveBits = DemandedBits.getActiveBits();
37842 if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
37843 (Opcode == ISD::OR || Opcode == ISD::XOR || Opcode == X86ISD::ANDNP) &&
37844 NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
37845 EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
37846 EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
37847 VT.getVectorNumElements());
37848 SDValue NewC =
37849 TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
37850 Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
37851 SDValue NewOp =
37852 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
37853 return TLO.CombineTo(Op, NewOp);
37855 return false;
37858 // Only optimize Ands to prevent shrinking a constant that could be
37859 // matched by movzx.
37860 if (Opcode != ISD::AND)
37861 return false;
37863 // Make sure the RHS really is a constant.
37864 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
37865 if (!C)
37866 return false;
37868 const APInt &Mask = C->getAPIntValue();
37870 // Clear all non-demanded bits initially.
37871 APInt ShrunkMask = Mask & DemandedBits;
37873 // Find the width of the shrunk mask.
37874 unsigned Width = ShrunkMask.getActiveBits();
37876 // If the mask is all 0s there's nothing to do here.
37877 if (Width == 0)
37878 return false;
37880 // Find the next power of 2 width, rounding up to a byte.
37881 Width = llvm::bit_ceil(std::max(Width, 8U));
37882 // Truncate the width to size to handle illegal types.
37883 Width = std::min(Width, EltSize);
37885 // Calculate a possible zero extend mask for this constant.
37886 APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
37888 // If we aren't changing the mask, just return true to keep it and prevent
37889 // the caller from optimizing.
37890 if (ZeroExtendMask == Mask)
37891 return true;
37893 // Make sure the new mask can be represented by a combination of mask bits
37894 // and non-demanded bits.
37895 if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
37896 return false;
37898 // Replace the constant with the zero extend mask.
37899 SDLoc DL(Op);
37900 SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
37901 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
37902 return TLO.CombineTo(Op, NewOp);
37905 static void computeKnownBitsForPSADBW(SDValue LHS, SDValue RHS,
37906 KnownBits &Known,
37907 const APInt &DemandedElts,
37908 const SelectionDAG &DAG, unsigned Depth) {
37909 KnownBits Known2;
37910 unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
37911 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
37912 Known = DAG.computeKnownBits(RHS, DemandedSrcElts, Depth + 1);
37913 Known2 = DAG.computeKnownBits(LHS, DemandedSrcElts, Depth + 1);
37914 Known = KnownBits::abdu(Known, Known2).zext(16);
37915 // Known = (((D0 + D1) + (D2 + D3)) + ((D4 + D5) + (D6 + D7)))
37916 Known = KnownBits::add(Known, Known, /*NSW=*/true, /*NUW=*/true);
37917 Known = KnownBits::add(Known, Known, /*NSW=*/true, /*NUW=*/true);
37918 Known = KnownBits::add(Known, Known, /*NSW=*/true, /*NUW=*/true);
37919 Known = Known.zext(64);
37922 static void computeKnownBitsForPMADDWD(SDValue LHS, SDValue RHS,
37923 KnownBits &Known,
37924 const APInt &DemandedElts,
37925 const SelectionDAG &DAG,
37926 unsigned Depth) {
37927 unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
37929 // Multiply signed i16 elements to create i32 values and add Lo/Hi pairs.
37930 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
37931 APInt DemandedLoElts =
37932 DemandedSrcElts & APInt::getSplat(NumSrcElts, APInt(2, 0b01));
37933 APInt DemandedHiElts =
37934 DemandedSrcElts & APInt::getSplat(NumSrcElts, APInt(2, 0b10));
37935 KnownBits LHSLo = DAG.computeKnownBits(LHS, DemandedLoElts, Depth + 1);
37936 KnownBits LHSHi = DAG.computeKnownBits(LHS, DemandedHiElts, Depth + 1);
37937 KnownBits RHSLo = DAG.computeKnownBits(RHS, DemandedLoElts, Depth + 1);
37938 KnownBits RHSHi = DAG.computeKnownBits(RHS, DemandedHiElts, Depth + 1);
37939 KnownBits Lo = KnownBits::mul(LHSLo.sext(32), RHSLo.sext(32));
37940 KnownBits Hi = KnownBits::mul(LHSHi.sext(32), RHSHi.sext(32));
37941 Known = KnownBits::add(Lo, Hi, /*NSW=*/false, /*NUW=*/false);
37944 static void computeKnownBitsForPMADDUBSW(SDValue LHS, SDValue RHS,
37945 KnownBits &Known,
37946 const APInt &DemandedElts,
37947 const SelectionDAG &DAG,
37948 unsigned Depth) {
37949 unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
37951 // Multiply unsigned/signed i8 elements to create i16 values and add_sat Lo/Hi
37952 // pairs.
37953 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
37954 APInt DemandedLoElts =
37955 DemandedSrcElts & APInt::getSplat(NumSrcElts, APInt(2, 0b01));
37956 APInt DemandedHiElts =
37957 DemandedSrcElts & APInt::getSplat(NumSrcElts, APInt(2, 0b10));
37958 KnownBits LHSLo = DAG.computeKnownBits(LHS, DemandedLoElts, Depth + 1);
37959 KnownBits LHSHi = DAG.computeKnownBits(LHS, DemandedHiElts, Depth + 1);
37960 KnownBits RHSLo = DAG.computeKnownBits(RHS, DemandedLoElts, Depth + 1);
37961 KnownBits RHSHi = DAG.computeKnownBits(RHS, DemandedHiElts, Depth + 1);
37962 KnownBits Lo = KnownBits::mul(LHSLo.zext(16), RHSLo.sext(16));
37963 KnownBits Hi = KnownBits::mul(LHSHi.zext(16), RHSHi.sext(16));
37964 Known = KnownBits::sadd_sat(Lo, Hi);
37967 static KnownBits computeKnownBitsForHorizontalOperation(
37968 const SDValue Op, const APInt &DemandedElts, unsigned Depth,
37969 const SelectionDAG &DAG,
37970 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
37971 KnownBitsFunc) {
37972 APInt DemandedEltsLHS, DemandedEltsRHS;
37973 getHorizDemandedEltsForFirstOperand(Op.getValueType().getSizeInBits(),
37974 DemandedElts, DemandedEltsLHS,
37975 DemandedEltsRHS);
37977 const auto ComputeForSingleOpFunc =
37978 [&DAG, Depth, KnownBitsFunc](SDValue Op, APInt &DemandedEltsOp) {
37979 return KnownBitsFunc(
37980 DAG.computeKnownBits(Op, DemandedEltsOp, Depth + 1),
37981 DAG.computeKnownBits(Op, DemandedEltsOp << 1, Depth + 1));
37984 if (DemandedEltsRHS.isZero())
37985 return ComputeForSingleOpFunc(Op.getOperand(0), DemandedEltsLHS);
37986 if (DemandedEltsLHS.isZero())
37987 return ComputeForSingleOpFunc(Op.getOperand(1), DemandedEltsRHS);
37989 return ComputeForSingleOpFunc(Op.getOperand(0), DemandedEltsLHS)
37990 .intersectWith(ComputeForSingleOpFunc(Op.getOperand(1), DemandedEltsRHS));
37993 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
37994 KnownBits &Known,
37995 const APInt &DemandedElts,
37996 const SelectionDAG &DAG,
37997 unsigned Depth) const {
37998 unsigned BitWidth = Known.getBitWidth();
37999 unsigned NumElts = DemandedElts.getBitWidth();
38000 unsigned Opc = Op.getOpcode();
38001 EVT VT = Op.getValueType();
38002 assert((Opc >= ISD::BUILTIN_OP_END ||
38003 Opc == ISD::INTRINSIC_WO_CHAIN ||
38004 Opc == ISD::INTRINSIC_W_CHAIN ||
38005 Opc == ISD::INTRINSIC_VOID) &&
38006 "Should use MaskedValueIsZero if you don't know whether Op"
38007 " is a target node!");
38009 Known.resetAll();
38010 switch (Opc) {
38011 default: break;
38012 case X86ISD::MUL_IMM: {
38013 KnownBits Known2;
38014 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38015 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38016 Known = KnownBits::mul(Known, Known2);
38017 break;
38019 case X86ISD::BSR:
38020 // BSR(0) is undef, but any use of BSR already accounts for non-zero inputs.
38021 // Similar KnownBits behaviour to CTLZ_ZERO_UNDEF.
38022 // TODO: Bound with input known bits?
38023 Known.Zero.setBitsFrom(Log2_32(BitWidth));
38024 break;
38025 case X86ISD::SETCC:
38026 Known.Zero.setBitsFrom(1);
38027 break;
38028 case X86ISD::MOVMSK: {
38029 unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
38030 Known.Zero.setBitsFrom(NumLoBits);
38031 break;
38033 case X86ISD::PEXTRB:
38034 case X86ISD::PEXTRW: {
38035 SDValue Src = Op.getOperand(0);
38036 EVT SrcVT = Src.getValueType();
38037 APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
38038 Op.getConstantOperandVal(1));
38039 Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
38040 Known = Known.anyextOrTrunc(BitWidth);
38041 Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
38042 break;
38044 case X86ISD::VSRAI:
38045 case X86ISD::VSHLI:
38046 case X86ISD::VSRLI: {
38047 unsigned ShAmt = Op.getConstantOperandVal(1);
38048 if (ShAmt >= VT.getScalarSizeInBits()) {
38049 // Out of range logical bit shifts are guaranteed to be zero.
38050 // Out of range arithmetic bit shifts splat the sign bit.
38051 if (Opc != X86ISD::VSRAI) {
38052 Known.setAllZero();
38053 break;
38056 ShAmt = VT.getScalarSizeInBits() - 1;
38059 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38060 if (Opc == X86ISD::VSHLI) {
38061 Known.Zero <<= ShAmt;
38062 Known.One <<= ShAmt;
38063 // Low bits are known zero.
38064 Known.Zero.setLowBits(ShAmt);
38065 } else if (Opc == X86ISD::VSRLI) {
38066 Known.Zero.lshrInPlace(ShAmt);
38067 Known.One.lshrInPlace(ShAmt);
38068 // High bits are known zero.
38069 Known.Zero.setHighBits(ShAmt);
38070 } else {
38071 Known.Zero.ashrInPlace(ShAmt);
38072 Known.One.ashrInPlace(ShAmt);
38074 break;
38076 case X86ISD::PACKUS: {
38077 // PACKUS is just a truncation if the upper half is zero.
38078 APInt DemandedLHS, DemandedRHS;
38079 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
38081 Known.One = APInt::getAllOnes(BitWidth * 2);
38082 Known.Zero = APInt::getAllOnes(BitWidth * 2);
38084 KnownBits Known2;
38085 if (!!DemandedLHS) {
38086 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
38087 Known = Known.intersectWith(Known2);
38089 if (!!DemandedRHS) {
38090 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
38091 Known = Known.intersectWith(Known2);
38094 if (Known.countMinLeadingZeros() < BitWidth)
38095 Known.resetAll();
38096 Known = Known.trunc(BitWidth);
38097 break;
38099 case X86ISD::PSHUFB: {
38100 SDValue Src = Op.getOperand(0);
38101 SDValue Idx = Op.getOperand(1);
38103 // If the index vector is never negative (MSB is zero), then all elements
38104 // come from the source vector. This is useful for cases where
38105 // PSHUFB is being used as a LUT (ctpop etc.) - the target shuffle handling
38106 // below will handle the more common constant shuffle mask case.
38107 KnownBits KnownIdx = DAG.computeKnownBits(Idx, DemandedElts, Depth + 1);
38108 if (KnownIdx.isNonNegative())
38109 Known = DAG.computeKnownBits(Src, Depth + 1);
38110 break;
38112 case X86ISD::VBROADCAST: {
38113 SDValue Src = Op.getOperand(0);
38114 if (!Src.getSimpleValueType().isVector()) {
38115 Known = DAG.computeKnownBits(Src, Depth + 1);
38116 return;
38118 break;
38120 case X86ISD::AND: {
38121 if (Op.getResNo() == 0) {
38122 KnownBits Known2;
38123 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38124 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38125 Known &= Known2;
38127 break;
38129 case X86ISD::ANDNP: {
38130 KnownBits Known2;
38131 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38132 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38134 // ANDNP = (~X & Y);
38135 Known.One &= Known2.Zero;
38136 Known.Zero |= Known2.One;
38137 break;
38139 case X86ISD::FOR: {
38140 KnownBits Known2;
38141 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38142 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38144 Known |= Known2;
38145 break;
38147 case X86ISD::PSADBW: {
38148 SDValue LHS = Op.getOperand(0);
38149 SDValue RHS = Op.getOperand(1);
38150 assert(VT.getScalarType() == MVT::i64 &&
38151 LHS.getValueType() == RHS.getValueType() &&
38152 LHS.getValueType().getScalarType() == MVT::i8 &&
38153 "Unexpected PSADBW types");
38154 computeKnownBitsForPSADBW(LHS, RHS, Known, DemandedElts, DAG, Depth);
38155 break;
38157 case X86ISD::PCMPGT:
38158 case X86ISD::PCMPEQ: {
38159 KnownBits KnownLhs =
38160 DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38161 KnownBits KnownRhs =
38162 DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38163 std::optional<bool> Res = Opc == X86ISD::PCMPEQ
38164 ? KnownBits::eq(KnownLhs, KnownRhs)
38165 : KnownBits::sgt(KnownLhs, KnownRhs);
38166 if (Res) {
38167 if (*Res)
38168 Known.setAllOnes();
38169 else
38170 Known.setAllZero();
38172 break;
38174 case X86ISD::VPMADDWD: {
38175 SDValue LHS = Op.getOperand(0);
38176 SDValue RHS = Op.getOperand(1);
38177 assert(VT.getVectorElementType() == MVT::i32 &&
38178 LHS.getValueType() == RHS.getValueType() &&
38179 LHS.getValueType().getVectorElementType() == MVT::i16 &&
38180 "Unexpected PMADDWD types");
38181 computeKnownBitsForPMADDWD(LHS, RHS, Known, DemandedElts, DAG, Depth);
38182 break;
38184 case X86ISD::VPMADDUBSW: {
38185 SDValue LHS = Op.getOperand(0);
38186 SDValue RHS = Op.getOperand(1);
38187 assert(VT.getVectorElementType() == MVT::i16 &&
38188 LHS.getValueType() == RHS.getValueType() &&
38189 LHS.getValueType().getVectorElementType() == MVT::i8 &&
38190 "Unexpected PMADDUBSW types");
38191 computeKnownBitsForPMADDUBSW(LHS, RHS, Known, DemandedElts, DAG, Depth);
38192 break;
38194 case X86ISD::PMULUDQ: {
38195 KnownBits Known2;
38196 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38197 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38199 Known = Known.trunc(BitWidth / 2).zext(BitWidth);
38200 Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
38201 Known = KnownBits::mul(Known, Known2);
38202 break;
38204 case X86ISD::CMOV: {
38205 Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
38206 // If we don't know any bits, early out.
38207 if (Known.isUnknown())
38208 break;
38209 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
38211 // Only known if known in both the LHS and RHS.
38212 Known = Known.intersectWith(Known2);
38213 break;
38215 case X86ISD::BEXTR:
38216 case X86ISD::BEXTRI: {
38217 SDValue Op0 = Op.getOperand(0);
38218 SDValue Op1 = Op.getOperand(1);
38220 if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
38221 unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
38222 unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
38224 // If the length is 0, the result is 0.
38225 if (Length == 0) {
38226 Known.setAllZero();
38227 break;
38230 if ((Shift + Length) <= BitWidth) {
38231 Known = DAG.computeKnownBits(Op0, Depth + 1);
38232 Known = Known.extractBits(Length, Shift);
38233 Known = Known.zextOrTrunc(BitWidth);
38236 break;
38238 case X86ISD::PDEP: {
38239 KnownBits Known2;
38240 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38241 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
38242 // Zeros are retained from the mask operand. But not ones.
38243 Known.One.clearAllBits();
38244 // The result will have at least as many trailing zeros as the non-mask
38245 // operand since bits can only map to the same or higher bit position.
38246 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
38247 break;
38249 case X86ISD::PEXT: {
38250 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
38251 // The result has as many leading zeros as the number of zeroes in the mask.
38252 unsigned Count = Known.Zero.popcount();
38253 Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
38254 Known.One.clearAllBits();
38255 break;
38257 case X86ISD::VTRUNC:
38258 case X86ISD::VTRUNCS:
38259 case X86ISD::VTRUNCUS:
38260 case X86ISD::CVTSI2P:
38261 case X86ISD::CVTUI2P:
38262 case X86ISD::CVTP2SI:
38263 case X86ISD::CVTP2UI:
38264 case X86ISD::MCVTP2SI:
38265 case X86ISD::MCVTP2UI:
38266 case X86ISD::CVTTP2SI:
38267 case X86ISD::CVTTP2UI:
38268 case X86ISD::MCVTTP2SI:
38269 case X86ISD::MCVTTP2UI:
38270 case X86ISD::MCVTSI2P:
38271 case X86ISD::MCVTUI2P:
38272 case X86ISD::VFPROUND:
38273 case X86ISD::VMFPROUND:
38274 case X86ISD::CVTPS2PH:
38275 case X86ISD::MCVTPS2PH:
38276 case X86ISD::MCVTTP2SIS:
38277 case X86ISD::MCVTTP2UIS: {
38278 // Truncations/Conversions - upper elements are known zero.
38279 EVT SrcVT = Op.getOperand(0).getValueType();
38280 if (SrcVT.isVector()) {
38281 unsigned NumSrcElts = SrcVT.getVectorNumElements();
38282 if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
38283 Known.setAllZero();
38285 break;
38287 case X86ISD::STRICT_CVTTP2SI:
38288 case X86ISD::STRICT_CVTTP2UI:
38289 case X86ISD::STRICT_CVTSI2P:
38290 case X86ISD::STRICT_CVTUI2P:
38291 case X86ISD::STRICT_VFPROUND:
38292 case X86ISD::STRICT_CVTPS2PH: {
38293 // Strict Conversions - upper elements are known zero.
38294 EVT SrcVT = Op.getOperand(1).getValueType();
38295 if (SrcVT.isVector()) {
38296 unsigned NumSrcElts = SrcVT.getVectorNumElements();
38297 if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
38298 Known.setAllZero();
38300 break;
38302 case X86ISD::MOVQ2DQ: {
38303 // Move from MMX to XMM. Upper half of XMM should be 0.
38304 if (DemandedElts.countr_zero() >= (NumElts / 2))
38305 Known.setAllZero();
38306 break;
38308 case X86ISD::VBROADCAST_LOAD: {
38309 APInt UndefElts;
38310 SmallVector<APInt, 16> EltBits;
38311 if (getTargetConstantBitsFromNode(Op, BitWidth, UndefElts, EltBits,
38312 /*AllowWholeUndefs*/ false,
38313 /*AllowPartialUndefs*/ false)) {
38314 Known.Zero.setAllBits();
38315 Known.One.setAllBits();
38316 for (unsigned I = 0; I != NumElts; ++I) {
38317 if (!DemandedElts[I])
38318 continue;
38319 if (UndefElts[I]) {
38320 Known.resetAll();
38321 break;
38323 KnownBits Known2 = KnownBits::makeConstant(EltBits[I]);
38324 Known = Known.intersectWith(Known2);
38326 return;
38328 break;
38330 case X86ISD::HADD:
38331 case X86ISD::HSUB: {
38332 Known = computeKnownBitsForHorizontalOperation(
38333 Op, DemandedElts, Depth, DAG,
38334 [Opc](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
38335 return KnownBits::computeForAddSub(
38336 /*Add=*/Opc == X86ISD::HADD, /*NSW=*/false, /*NUW=*/false,
38337 KnownLHS, KnownRHS);
38339 break;
38341 case ISD::INTRINSIC_WO_CHAIN: {
38342 switch (Op->getConstantOperandVal(0)) {
38343 case Intrinsic::x86_sse2_pmadd_wd:
38344 case Intrinsic::x86_avx2_pmadd_wd:
38345 case Intrinsic::x86_avx512_pmaddw_d_512: {
38346 SDValue LHS = Op.getOperand(1);
38347 SDValue RHS = Op.getOperand(2);
38348 assert(VT.getScalarType() == MVT::i32 &&
38349 LHS.getValueType() == RHS.getValueType() &&
38350 LHS.getValueType().getScalarType() == MVT::i16 &&
38351 "Unexpected PMADDWD types");
38352 computeKnownBitsForPMADDWD(LHS, RHS, Known, DemandedElts, DAG, Depth);
38353 break;
38355 case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
38356 case Intrinsic::x86_avx2_pmadd_ub_sw:
38357 case Intrinsic::x86_avx512_pmaddubs_w_512: {
38358 SDValue LHS = Op.getOperand(1);
38359 SDValue RHS = Op.getOperand(2);
38360 assert(VT.getScalarType() == MVT::i16 &&
38361 LHS.getValueType() == RHS.getValueType() &&
38362 LHS.getValueType().getScalarType() == MVT::i8 &&
38363 "Unexpected PMADDUBSW types");
38364 computeKnownBitsForPMADDUBSW(LHS, RHS, Known, DemandedElts, DAG, Depth);
38365 break;
38367 case Intrinsic::x86_sse2_psad_bw:
38368 case Intrinsic::x86_avx2_psad_bw:
38369 case Intrinsic::x86_avx512_psad_bw_512: {
38370 SDValue LHS = Op.getOperand(1);
38371 SDValue RHS = Op.getOperand(2);
38372 assert(VT.getScalarType() == MVT::i64 &&
38373 LHS.getValueType() == RHS.getValueType() &&
38374 LHS.getValueType().getScalarType() == MVT::i8 &&
38375 "Unexpected PSADBW types");
38376 computeKnownBitsForPSADBW(LHS, RHS, Known, DemandedElts, DAG, Depth);
38377 break;
38380 break;
38384 // Handle target shuffles.
38385 // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
38386 if (isTargetShuffle(Opc)) {
38387 SmallVector<int, 64> Mask;
38388 SmallVector<SDValue, 2> Ops;
38389 if (getTargetShuffleMask(Op, true, Ops, Mask)) {
38390 unsigned NumOps = Ops.size();
38391 unsigned NumElts = VT.getVectorNumElements();
38392 if (Mask.size() == NumElts) {
38393 SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
38394 Known.Zero.setAllBits(); Known.One.setAllBits();
38395 for (unsigned i = 0; i != NumElts; ++i) {
38396 if (!DemandedElts[i])
38397 continue;
38398 int M = Mask[i];
38399 if (M == SM_SentinelUndef) {
38400 // For UNDEF elements, we don't know anything about the common state
38401 // of the shuffle result.
38402 Known.resetAll();
38403 break;
38405 if (M == SM_SentinelZero) {
38406 Known.One.clearAllBits();
38407 continue;
38409 assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
38410 "Shuffle index out of range");
38412 unsigned OpIdx = (unsigned)M / NumElts;
38413 unsigned EltIdx = (unsigned)M % NumElts;
38414 if (Ops[OpIdx].getValueType() != VT) {
38415 // TODO - handle target shuffle ops with different value types.
38416 Known.resetAll();
38417 break;
38419 DemandedOps[OpIdx].setBit(EltIdx);
38421 // Known bits are the values that are shared by every demanded element.
38422 for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
38423 if (!DemandedOps[i])
38424 continue;
38425 KnownBits Known2 =
38426 DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
38427 Known = Known.intersectWith(Known2);
38434 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
38435 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
38436 unsigned Depth) const {
38437 EVT VT = Op.getValueType();
38438 unsigned VTBits = VT.getScalarSizeInBits();
38439 unsigned Opcode = Op.getOpcode();
38440 switch (Opcode) {
38441 case X86ISD::SETCC_CARRY:
38442 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
38443 return VTBits;
38445 case X86ISD::VTRUNC: {
38446 SDValue Src = Op.getOperand(0);
38447 MVT SrcVT = Src.getSimpleValueType();
38448 unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
38449 assert(VTBits < NumSrcBits && "Illegal truncation input type");
38450 APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
38451 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
38452 if (Tmp > (NumSrcBits - VTBits))
38453 return Tmp - (NumSrcBits - VTBits);
38454 return 1;
38457 case X86ISD::PACKSS: {
38458 // PACKSS is just a truncation if the sign bits extend to the packed size.
38459 APInt DemandedLHS, DemandedRHS;
38460 getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
38461 DemandedRHS);
38463 // Helper to detect PACKSSDW(BITCAST(PACKSSDW(X)),BITCAST(PACKSSDW(Y)))
38464 // patterns often used to compact vXi64 allsignbit patterns.
38465 auto NumSignBitsPACKSS = [&](SDValue V, const APInt &Elts) -> unsigned {
38466 SDValue BC = peekThroughBitcasts(V);
38467 if (BC.getOpcode() == X86ISD::PACKSS &&
38468 BC.getScalarValueSizeInBits() == 16 &&
38469 V.getScalarValueSizeInBits() == 32) {
38470 SDValue BC0 = peekThroughBitcasts(BC.getOperand(0));
38471 SDValue BC1 = peekThroughBitcasts(BC.getOperand(1));
38472 if (BC0.getScalarValueSizeInBits() == 64 &&
38473 BC1.getScalarValueSizeInBits() == 64 &&
38474 DAG.ComputeNumSignBits(BC0, Depth + 1) == 64 &&
38475 DAG.ComputeNumSignBits(BC1, Depth + 1) == 64)
38476 return 32;
38478 return DAG.ComputeNumSignBits(V, Elts, Depth + 1);
38481 unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
38482 unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
38483 if (!!DemandedLHS)
38484 Tmp0 = NumSignBitsPACKSS(Op.getOperand(0), DemandedLHS);
38485 if (!!DemandedRHS)
38486 Tmp1 = NumSignBitsPACKSS(Op.getOperand(1), DemandedRHS);
38487 unsigned Tmp = std::min(Tmp0, Tmp1);
38488 if (Tmp > (SrcBits - VTBits))
38489 return Tmp - (SrcBits - VTBits);
38490 return 1;
38493 case X86ISD::VBROADCAST: {
38494 SDValue Src = Op.getOperand(0);
38495 if (!Src.getSimpleValueType().isVector())
38496 return DAG.ComputeNumSignBits(Src, Depth + 1);
38497 break;
38500 case X86ISD::VSHLI: {
38501 SDValue Src = Op.getOperand(0);
38502 const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
38503 if (ShiftVal.uge(VTBits))
38504 return VTBits; // Shifted all bits out --> zero.
38505 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
38506 if (ShiftVal.uge(Tmp))
38507 return 1; // Shifted all sign bits out --> unknown.
38508 return Tmp - ShiftVal.getZExtValue();
38511 case X86ISD::VSRAI: {
38512 SDValue Src = Op.getOperand(0);
38513 APInt ShiftVal = Op.getConstantOperandAPInt(1);
38514 if (ShiftVal.uge(VTBits - 1))
38515 return VTBits; // Sign splat.
38516 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
38517 ShiftVal += Tmp;
38518 return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
38521 case X86ISD::FSETCC:
38522 // cmpss/cmpsd return zero/all-bits result values in the bottom element.
38523 if (VT == MVT::f32 || VT == MVT::f64 ||
38524 ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
38525 return VTBits;
38526 break;
38528 case X86ISD::PCMPGT:
38529 case X86ISD::PCMPEQ:
38530 case X86ISD::CMPP:
38531 case X86ISD::VPCOM:
38532 case X86ISD::VPCOMU:
38533 // Vector compares return zero/all-bits result values.
38534 return VTBits;
38536 case X86ISD::ANDNP: {
38537 unsigned Tmp0 =
38538 DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
38539 if (Tmp0 == 1) return 1; // Early out.
38540 unsigned Tmp1 =
38541 DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
38542 return std::min(Tmp0, Tmp1);
38545 case X86ISD::CMOV: {
38546 unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
38547 if (Tmp0 == 1) return 1; // Early out.
38548 unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
38549 return std::min(Tmp0, Tmp1);
38553 // Handle target shuffles.
38554 // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
38555 if (isTargetShuffle(Opcode)) {
38556 SmallVector<int, 64> Mask;
38557 SmallVector<SDValue, 2> Ops;
38558 if (getTargetShuffleMask(Op, true, Ops, Mask)) {
38559 unsigned NumOps = Ops.size();
38560 unsigned NumElts = VT.getVectorNumElements();
38561 if (Mask.size() == NumElts) {
38562 SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
38563 for (unsigned i = 0; i != NumElts; ++i) {
38564 if (!DemandedElts[i])
38565 continue;
38566 int M = Mask[i];
38567 if (M == SM_SentinelUndef) {
38568 // For UNDEF elements, we don't know anything about the common state
38569 // of the shuffle result.
38570 return 1;
38571 } else if (M == SM_SentinelZero) {
38572 // Zero = all sign bits.
38573 continue;
38575 assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
38576 "Shuffle index out of range");
38578 unsigned OpIdx = (unsigned)M / NumElts;
38579 unsigned EltIdx = (unsigned)M % NumElts;
38580 if (Ops[OpIdx].getValueType() != VT) {
38581 // TODO - handle target shuffle ops with different value types.
38582 return 1;
38584 DemandedOps[OpIdx].setBit(EltIdx);
38586 unsigned Tmp0 = VTBits;
38587 for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
38588 if (!DemandedOps[i])
38589 continue;
38590 unsigned Tmp1 =
38591 DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
38592 Tmp0 = std::min(Tmp0, Tmp1);
38594 return Tmp0;
38599 // Fallback case.
38600 return 1;
38603 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
38604 if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
38605 return N->getOperand(0);
38606 return N;
38609 // Helper to look for a normal load that can be narrowed into a vzload with the
38610 // specified VT and memory VT. Returns SDValue() on failure.
38611 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
38612 SelectionDAG &DAG) {
38613 // Can't if the load is volatile or atomic.
38614 if (!LN->isSimple())
38615 return SDValue();
38617 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
38618 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
38619 return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
38620 LN->getPointerInfo(), LN->getOriginalAlign(),
38621 LN->getMemOperand()->getFlags());
38624 // Attempt to match a combined shuffle mask against supported unary shuffle
38625 // instructions.
38626 // TODO: Investigate sharing more of this with shuffle lowering.
38627 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
38628 bool AllowFloatDomain, bool AllowIntDomain,
38629 SDValue V1, const SelectionDAG &DAG,
38630 const X86Subtarget &Subtarget, unsigned &Shuffle,
38631 MVT &SrcVT, MVT &DstVT) {
38632 unsigned NumMaskElts = Mask.size();
38633 unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
38635 // Match against a VZEXT_MOVL vXi32 and vXi16 zero-extending instruction.
38636 if (Mask[0] == 0 &&
38637 (MaskEltSize == 32 || (MaskEltSize == 16 && Subtarget.hasFP16()))) {
38638 if ((isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) ||
38639 (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
38640 isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1))) {
38641 Shuffle = X86ISD::VZEXT_MOVL;
38642 if (MaskEltSize == 16)
38643 SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
38644 else
38645 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
38646 return true;
38650 // Match against a ANY/SIGN/ZERO_EXTEND_VECTOR_INREG instruction.
38651 // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
38652 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
38653 (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
38654 unsigned MaxScale = 64 / MaskEltSize;
38655 bool UseSign = V1.getScalarValueSizeInBits() == MaskEltSize &&
38656 DAG.ComputeNumSignBits(V1) == MaskEltSize;
38657 for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
38658 bool MatchAny = true;
38659 bool MatchZero = true;
38660 bool MatchSign = UseSign;
38661 unsigned NumDstElts = NumMaskElts / Scale;
38662 for (unsigned i = 0;
38663 i != NumDstElts && (MatchAny || MatchSign || MatchZero); ++i) {
38664 if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
38665 MatchAny = MatchSign = MatchZero = false;
38666 break;
38668 unsigned Pos = (i * Scale) + 1;
38669 unsigned Len = Scale - 1;
38670 MatchAny &= isUndefInRange(Mask, Pos, Len);
38671 MatchZero &= isUndefOrZeroInRange(Mask, Pos, Len);
38672 MatchSign &= isUndefOrEqualInRange(Mask, (int)i, Pos, Len);
38674 if (MatchAny || MatchSign || MatchZero) {
38675 assert((MatchSign || MatchZero) &&
38676 "Failed to match sext/zext but matched aext?");
38677 unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
38678 MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType()
38679 : MVT::getIntegerVT(MaskEltSize);
38680 SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
38682 Shuffle = unsigned(
38683 MatchAny ? ISD::ANY_EXTEND
38684 : (MatchSign ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND));
38685 if (SrcVT.getVectorNumElements() != NumDstElts)
38686 Shuffle = DAG.getOpcode_EXTEND_VECTOR_INREG(Shuffle);
38688 DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
38689 DstVT = MVT::getVectorVT(DstVT, NumDstElts);
38690 return true;
38695 // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
38696 if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2()) ||
38697 (MaskEltSize == 16 && Subtarget.hasFP16())) &&
38698 isUndefOrEqual(Mask[0], 0) &&
38699 isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
38700 Shuffle = X86ISD::VZEXT_MOVL;
38701 if (MaskEltSize == 16)
38702 SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
38703 else
38704 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
38705 return true;
38708 // Check if we have SSE3 which will let us use MOVDDUP etc. The
38709 // instructions are no slower than UNPCKLPD but has the option to
38710 // fold the input operand into even an unaligned memory load.
38711 if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
38712 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG, V1)) {
38713 Shuffle = X86ISD::MOVDDUP;
38714 SrcVT = DstVT = MVT::v2f64;
38715 return true;
38717 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
38718 Shuffle = X86ISD::MOVSLDUP;
38719 SrcVT = DstVT = MVT::v4f32;
38720 return true;
38722 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, DAG, V1)) {
38723 Shuffle = X86ISD::MOVSHDUP;
38724 SrcVT = DstVT = MVT::v4f32;
38725 return true;
38729 if (MaskVT.is256BitVector() && AllowFloatDomain) {
38730 assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
38731 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
38732 Shuffle = X86ISD::MOVDDUP;
38733 SrcVT = DstVT = MVT::v4f64;
38734 return true;
38736 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
38737 V1)) {
38738 Shuffle = X86ISD::MOVSLDUP;
38739 SrcVT = DstVT = MVT::v8f32;
38740 return true;
38742 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, DAG,
38743 V1)) {
38744 Shuffle = X86ISD::MOVSHDUP;
38745 SrcVT = DstVT = MVT::v8f32;
38746 return true;
38750 if (MaskVT.is512BitVector() && AllowFloatDomain) {
38751 assert(Subtarget.hasAVX512() &&
38752 "AVX512 required for 512-bit vector shuffles");
38753 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
38754 V1)) {
38755 Shuffle = X86ISD::MOVDDUP;
38756 SrcVT = DstVT = MVT::v8f64;
38757 return true;
38759 if (isTargetShuffleEquivalent(
38760 MaskVT, Mask,
38761 {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, DAG, V1)) {
38762 Shuffle = X86ISD::MOVSLDUP;
38763 SrcVT = DstVT = MVT::v16f32;
38764 return true;
38766 if (isTargetShuffleEquivalent(
38767 MaskVT, Mask,
38768 {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, DAG, V1)) {
38769 Shuffle = X86ISD::MOVSHDUP;
38770 SrcVT = DstVT = MVT::v16f32;
38771 return true;
38775 return false;
38778 // Attempt to match a combined shuffle mask against supported unary immediate
38779 // permute instructions.
38780 // TODO: Investigate sharing more of this with shuffle lowering.
38781 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
38782 const APInt &Zeroable,
38783 bool AllowFloatDomain, bool AllowIntDomain,
38784 const SelectionDAG &DAG,
38785 const X86Subtarget &Subtarget,
38786 unsigned &Shuffle, MVT &ShuffleVT,
38787 unsigned &PermuteImm) {
38788 unsigned NumMaskElts = Mask.size();
38789 unsigned InputSizeInBits = MaskVT.getSizeInBits();
38790 unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
38791 MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
38792 bool ContainsZeros = isAnyZero(Mask);
38794 // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
38795 if (!ContainsZeros && MaskScalarSizeInBits == 64) {
38796 // Check for lane crossing permutes.
38797 if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
38798 // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
38799 if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
38800 Shuffle = X86ISD::VPERMI;
38801 ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
38802 PermuteImm = getV4X86ShuffleImm(Mask);
38803 return true;
38805 if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
38806 SmallVector<int, 4> RepeatedMask;
38807 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
38808 Shuffle = X86ISD::VPERMI;
38809 ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
38810 PermuteImm = getV4X86ShuffleImm(RepeatedMask);
38811 return true;
38814 } else if (AllowFloatDomain && Subtarget.hasAVX()) {
38815 // VPERMILPD can permute with a non-repeating shuffle.
38816 Shuffle = X86ISD::VPERMILPI;
38817 ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
38818 PermuteImm = 0;
38819 for (int i = 0, e = Mask.size(); i != e; ++i) {
38820 int M = Mask[i];
38821 if (M == SM_SentinelUndef)
38822 continue;
38823 assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
38824 PermuteImm |= (M & 1) << i;
38826 return true;
38830 // We are checking for shuffle match or shift match. Loop twice so we can
38831 // order which we try and match first depending on target preference.
38832 for (unsigned Order = 0; Order < 2; ++Order) {
38833 if (Subtarget.preferLowerShuffleAsShift() ? (Order == 1) : (Order == 0)) {
38834 // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
38835 // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
38836 // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
38837 if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
38838 !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
38839 SmallVector<int, 4> RepeatedMask;
38840 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
38841 // Narrow the repeated mask to create 32-bit element permutes.
38842 SmallVector<int, 4> WordMask = RepeatedMask;
38843 if (MaskScalarSizeInBits == 64)
38844 narrowShuffleMaskElts(2, RepeatedMask, WordMask);
38846 Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
38847 ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
38848 ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
38849 PermuteImm = getV4X86ShuffleImm(WordMask);
38850 return true;
38854 // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
38855 if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
38856 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
38857 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
38858 (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
38859 SmallVector<int, 4> RepeatedMask;
38860 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
38861 ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
38862 ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
38864 // PSHUFLW: permute lower 4 elements only.
38865 if (isUndefOrInRange(LoMask, 0, 4) &&
38866 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
38867 Shuffle = X86ISD::PSHUFLW;
38868 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
38869 PermuteImm = getV4X86ShuffleImm(LoMask);
38870 return true;
38873 // PSHUFHW: permute upper 4 elements only.
38874 if (isUndefOrInRange(HiMask, 4, 8) &&
38875 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
38876 // Offset the HiMask so that we can create the shuffle immediate.
38877 int OffsetHiMask[4];
38878 for (int i = 0; i != 4; ++i)
38879 OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
38881 Shuffle = X86ISD::PSHUFHW;
38882 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
38883 PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
38884 return true;
38888 } else {
38889 // Attempt to match against bit rotates.
38890 if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
38891 ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
38892 Subtarget.hasAVX512())) {
38893 int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
38894 Subtarget, Mask);
38895 if (0 < RotateAmt) {
38896 Shuffle = X86ISD::VROTLI;
38897 PermuteImm = (unsigned)RotateAmt;
38898 return true;
38902 // Attempt to match against byte/bit shifts.
38903 if (AllowIntDomain &&
38904 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
38905 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
38906 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
38907 int ShiftAmt =
38908 matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits, Mask, 0,
38909 Zeroable, Subtarget);
38910 if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
38911 32 <= ShuffleVT.getScalarSizeInBits())) {
38912 // Byte shifts can be slower so only match them on second attempt.
38913 if (Order == 0 &&
38914 (Shuffle == X86ISD::VSHLDQ || Shuffle == X86ISD::VSRLDQ))
38915 continue;
38917 PermuteImm = (unsigned)ShiftAmt;
38918 return true;
38924 return false;
38927 // Attempt to match a combined unary shuffle mask against supported binary
38928 // shuffle instructions.
38929 // TODO: Investigate sharing more of this with shuffle lowering.
38930 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
38931 bool AllowFloatDomain, bool AllowIntDomain,
38932 SDValue &V1, SDValue &V2, const SDLoc &DL,
38933 SelectionDAG &DAG, const X86Subtarget &Subtarget,
38934 unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
38935 bool IsUnary) {
38936 unsigned NumMaskElts = Mask.size();
38937 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
38938 unsigned SizeInBits = MaskVT.getSizeInBits();
38940 if (MaskVT.is128BitVector()) {
38941 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG) &&
38942 AllowFloatDomain) {
38943 V2 = V1;
38944 V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
38945 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
38946 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
38947 return true;
38949 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}, DAG) &&
38950 AllowFloatDomain) {
38951 V2 = V1;
38952 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
38953 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
38954 return true;
38956 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}, DAG) &&
38957 Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
38958 std::swap(V1, V2);
38959 Shuffle = X86ISD::MOVSD;
38960 SrcVT = DstVT = MVT::v2f64;
38961 return true;
38963 if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG) &&
38964 (AllowFloatDomain || !Subtarget.hasSSE41())) {
38965 Shuffle = X86ISD::MOVSS;
38966 SrcVT = DstVT = MVT::v4f32;
38967 return true;
38969 if (isTargetShuffleEquivalent(MaskVT, Mask, {8, 1, 2, 3, 4, 5, 6, 7},
38970 DAG) &&
38971 Subtarget.hasFP16()) {
38972 Shuffle = X86ISD::MOVSH;
38973 SrcVT = DstVT = MVT::v8f16;
38974 return true;
38978 // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
38979 if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
38980 ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
38981 ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
38982 if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
38983 Subtarget)) {
38984 DstVT = MaskVT;
38985 return true;
38988 // TODO: Can we handle this inside matchShuffleWithPACK?
38989 if (MaskVT == MVT::v4i32 && Subtarget.hasSSE2() &&
38990 isTargetShuffleEquivalent(MaskVT, Mask, {0, 2, 4, 6}, DAG) &&
38991 V1.getScalarValueSizeInBits() == 64 &&
38992 V2.getScalarValueSizeInBits() == 64) {
38993 // Use (SSE41) PACKUSWD if the leading zerobits goto the lowest 16-bits.
38994 unsigned MinLZV1 = DAG.computeKnownBits(V1).countMinLeadingZeros();
38995 unsigned MinLZV2 = DAG.computeKnownBits(V2).countMinLeadingZeros();
38996 if (Subtarget.hasSSE41() && MinLZV1 >= 48 && MinLZV2 >= 48) {
38997 SrcVT = MVT::v4i32;
38998 DstVT = MVT::v8i16;
38999 Shuffle = X86ISD::PACKUS;
39000 return true;
39002 // Use PACKUSBW if the leading zerobits goto the lowest 8-bits.
39003 if (MinLZV1 >= 56 && MinLZV2 >= 56) {
39004 SrcVT = MVT::v8i16;
39005 DstVT = MVT::v16i8;
39006 Shuffle = X86ISD::PACKUS;
39007 return true;
39009 // Use PACKSSWD if the signbits extend to the lowest 16-bits.
39010 if (DAG.ComputeNumSignBits(V1) > 48 && DAG.ComputeNumSignBits(V2) > 48) {
39011 SrcVT = MVT::v4i32;
39012 DstVT = MVT::v8i16;
39013 Shuffle = X86ISD::PACKSS;
39014 return true;
39018 // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
39019 if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
39020 (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
39021 (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
39022 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
39023 (MaskVT.is512BitVector() && Subtarget.hasAVX512() &&
39024 (32 <= EltSizeInBits || Subtarget.hasBWI()))) {
39025 if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
39026 Subtarget)) {
39027 SrcVT = DstVT = MaskVT;
39028 if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
39029 SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
39030 return true;
39034 // Attempt to match against a OR if we're performing a blend shuffle and the
39035 // non-blended source element is zero in each case.
39036 // TODO: Handle cases where V1/V2 sizes doesn't match SizeInBits.
39037 if (SizeInBits == V1.getValueSizeInBits() &&
39038 SizeInBits == V2.getValueSizeInBits() &&
39039 (EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
39040 (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
39041 bool IsBlend = true;
39042 unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
39043 unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
39044 unsigned Scale1 = NumV1Elts / NumMaskElts;
39045 unsigned Scale2 = NumV2Elts / NumMaskElts;
39046 APInt DemandedZeroV1 = APInt::getZero(NumV1Elts);
39047 APInt DemandedZeroV2 = APInt::getZero(NumV2Elts);
39048 for (unsigned i = 0; i != NumMaskElts; ++i) {
39049 int M = Mask[i];
39050 if (M == SM_SentinelUndef)
39051 continue;
39052 if (M == SM_SentinelZero) {
39053 DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
39054 DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
39055 continue;
39057 if (M == (int)i) {
39058 DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
39059 continue;
39061 if (M == (int)(i + NumMaskElts)) {
39062 DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
39063 continue;
39065 IsBlend = false;
39066 break;
39068 if (IsBlend) {
39069 if (DAG.MaskedVectorIsZero(V1, DemandedZeroV1) &&
39070 DAG.MaskedVectorIsZero(V2, DemandedZeroV2)) {
39071 Shuffle = ISD::OR;
39072 SrcVT = DstVT = MaskVT.changeTypeToInteger();
39073 return true;
39075 if (NumV1Elts == NumV2Elts && NumV1Elts == NumMaskElts) {
39076 // FIXME: handle mismatched sizes?
39077 // TODO: investigate if `ISD::OR` handling in
39078 // `TargetLowering::SimplifyDemandedVectorElts` can be improved instead.
39079 auto computeKnownBitsElementWise = [&DAG](SDValue V) {
39080 unsigned NumElts = V.getValueType().getVectorNumElements();
39081 KnownBits Known(NumElts);
39082 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
39083 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
39084 KnownBits PeepholeKnown = DAG.computeKnownBits(V, Mask);
39085 if (PeepholeKnown.isZero())
39086 Known.Zero.setBit(EltIdx);
39087 if (PeepholeKnown.isAllOnes())
39088 Known.One.setBit(EltIdx);
39090 return Known;
39093 KnownBits V1Known = computeKnownBitsElementWise(V1);
39094 KnownBits V2Known = computeKnownBitsElementWise(V2);
39096 for (unsigned i = 0; i != NumMaskElts && IsBlend; ++i) {
39097 int M = Mask[i];
39098 if (M == SM_SentinelUndef)
39099 continue;
39100 if (M == SM_SentinelZero) {
39101 IsBlend &= V1Known.Zero[i] && V2Known.Zero[i];
39102 continue;
39104 if (M == (int)i) {
39105 IsBlend &= V2Known.Zero[i] || V1Known.One[i];
39106 continue;
39108 if (M == (int)(i + NumMaskElts)) {
39109 IsBlend &= V1Known.Zero[i] || V2Known.One[i];
39110 continue;
39112 llvm_unreachable("will not get here.");
39114 if (IsBlend) {
39115 Shuffle = ISD::OR;
39116 SrcVT = DstVT = MaskVT.changeTypeToInteger();
39117 return true;
39123 return false;
39126 static bool matchBinaryPermuteShuffle(
39127 MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
39128 bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
39129 const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
39130 unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
39131 unsigned NumMaskElts = Mask.size();
39132 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
39134 // Attempt to match against VALIGND/VALIGNQ rotate.
39135 if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
39136 ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
39137 (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
39138 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
39139 if (!isAnyZero(Mask)) {
39140 int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
39141 if (0 < Rotation) {
39142 Shuffle = X86ISD::VALIGN;
39143 if (EltSizeInBits == 64)
39144 ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
39145 else
39146 ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
39147 PermuteImm = Rotation;
39148 return true;
39153 // Attempt to match against PALIGNR byte rotate.
39154 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
39155 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
39156 (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
39157 int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
39158 if (0 < ByteRotation) {
39159 Shuffle = X86ISD::PALIGNR;
39160 ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
39161 PermuteImm = ByteRotation;
39162 return true;
39166 // Attempt to combine to X86ISD::BLENDI.
39167 if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
39168 (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
39169 (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
39170 uint64_t BlendMask = 0;
39171 bool ForceV1Zero = false, ForceV2Zero = false;
39172 SmallVector<int, 8> TargetMask(Mask);
39173 if (matchShuffleAsBlend(MaskVT, V1, V2, TargetMask, Zeroable, ForceV1Zero,
39174 ForceV2Zero, BlendMask)) {
39175 if (MaskVT == MVT::v16i16) {
39176 // We can only use v16i16 PBLENDW if the lanes are repeated.
39177 SmallVector<int, 8> RepeatedMask;
39178 if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
39179 RepeatedMask)) {
39180 assert(RepeatedMask.size() == 8 &&
39181 "Repeated mask size doesn't match!");
39182 PermuteImm = 0;
39183 for (int i = 0; i < 8; ++i)
39184 if (RepeatedMask[i] >= 8)
39185 PermuteImm |= 1 << i;
39186 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
39187 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
39188 Shuffle = X86ISD::BLENDI;
39189 ShuffleVT = MaskVT;
39190 return true;
39192 } else {
39193 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
39194 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
39195 PermuteImm = (unsigned)BlendMask;
39196 Shuffle = X86ISD::BLENDI;
39197 ShuffleVT = MaskVT;
39198 return true;
39203 // Attempt to combine to INSERTPS, but only if it has elements that need to
39204 // be set to zero.
39205 if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
39206 MaskVT.is128BitVector() && isAnyZero(Mask) &&
39207 matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
39208 Shuffle = X86ISD::INSERTPS;
39209 ShuffleVT = MVT::v4f32;
39210 return true;
39213 // Attempt to combine to SHUFPD.
39214 if (AllowFloatDomain && EltSizeInBits == 64 &&
39215 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
39216 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
39217 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
39218 bool ForceV1Zero = false, ForceV2Zero = false;
39219 if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
39220 PermuteImm, Mask, Zeroable)) {
39221 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
39222 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
39223 Shuffle = X86ISD::SHUFP;
39224 ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
39225 return true;
39229 // Attempt to combine to SHUFPS.
39230 if (AllowFloatDomain && EltSizeInBits == 32 &&
39231 ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
39232 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
39233 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
39234 SmallVector<int, 4> RepeatedMask;
39235 if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
39236 // Match each half of the repeated mask, to determine if its just
39237 // referencing one of the vectors, is zeroable or entirely undef.
39238 auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
39239 int M0 = RepeatedMask[Offset];
39240 int M1 = RepeatedMask[Offset + 1];
39242 if (isUndefInRange(RepeatedMask, Offset, 2)) {
39243 return DAG.getUNDEF(MaskVT);
39244 } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
39245 S0 = (SM_SentinelUndef == M0 ? -1 : 0);
39246 S1 = (SM_SentinelUndef == M1 ? -1 : 1);
39247 return getZeroVector(MaskVT, Subtarget, DAG, DL);
39248 } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
39249 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
39250 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
39251 return V1;
39252 } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
39253 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
39254 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
39255 return V2;
39258 return SDValue();
39261 int ShufMask[4] = {-1, -1, -1, -1};
39262 SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
39263 SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
39265 if (Lo && Hi) {
39266 V1 = Lo;
39267 V2 = Hi;
39268 Shuffle = X86ISD::SHUFP;
39269 ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
39270 PermuteImm = getV4X86ShuffleImm(ShufMask);
39271 return true;
39276 // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
39277 if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
39278 MaskVT.is128BitVector() &&
39279 matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
39280 Shuffle = X86ISD::INSERTPS;
39281 ShuffleVT = MVT::v4f32;
39282 return true;
39285 return false;
39288 static SDValue combineX86ShuffleChainWithExtract(
39289 ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
39290 bool HasVariableMask, bool AllowVariableCrossLaneMask,
39291 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
39292 const X86Subtarget &Subtarget);
39294 /// Combine an arbitrary chain of shuffles into a single instruction if
39295 /// possible.
39297 /// This is the leaf of the recursive combine below. When we have found some
39298 /// chain of single-use x86 shuffle instructions and accumulated the combined
39299 /// shuffle mask represented by them, this will try to pattern match that mask
39300 /// into either a single instruction if there is a special purpose instruction
39301 /// for this operation, or into a PSHUFB instruction which is a fully general
39302 /// instruction but should only be used to replace chains over a certain depth.
39303 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
39304 ArrayRef<int> BaseMask, int Depth,
39305 bool HasVariableMask,
39306 bool AllowVariableCrossLaneMask,
39307 bool AllowVariablePerLaneMask,
39308 SelectionDAG &DAG,
39309 const X86Subtarget &Subtarget) {
39310 assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
39311 assert((Inputs.size() == 1 || Inputs.size() == 2) &&
39312 "Unexpected number of shuffle inputs!");
39314 SDLoc DL(Root);
39315 MVT RootVT = Root.getSimpleValueType();
39316 unsigned RootSizeInBits = RootVT.getSizeInBits();
39317 unsigned NumRootElts = RootVT.getVectorNumElements();
39319 // Canonicalize shuffle input op to the requested type.
39320 auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
39321 if (VT.getSizeInBits() > Op.getValueSizeInBits())
39322 Op = widenSubVector(Op, false, Subtarget, DAG, DL, VT.getSizeInBits());
39323 else if (VT.getSizeInBits() < Op.getValueSizeInBits())
39324 Op = extractSubVector(Op, 0, DAG, DL, VT.getSizeInBits());
39325 return DAG.getBitcast(VT, Op);
39328 // Find the inputs that enter the chain. Note that multiple uses are OK
39329 // here, we're not going to remove the operands we find.
39330 bool UnaryShuffle = (Inputs.size() == 1);
39331 SDValue V1 = peekThroughBitcasts(Inputs[0]);
39332 SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
39333 : peekThroughBitcasts(Inputs[1]));
39335 MVT VT1 = V1.getSimpleValueType();
39336 MVT VT2 = V2.getSimpleValueType();
39337 assert((RootSizeInBits % VT1.getSizeInBits()) == 0 &&
39338 (RootSizeInBits % VT2.getSizeInBits()) == 0 && "Vector size mismatch");
39340 SDValue Res;
39342 unsigned NumBaseMaskElts = BaseMask.size();
39343 if (NumBaseMaskElts == 1) {
39344 assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
39345 return CanonicalizeShuffleInput(RootVT, V1);
39348 bool OptForSize = DAG.shouldOptForSize();
39349 unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
39350 bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
39351 (RootVT.isFloatingPoint() && Depth >= 1) ||
39352 (RootVT.is256BitVector() && !Subtarget.hasAVX2());
39354 // Don't combine if we are a AVX512/EVEX target and the mask element size
39355 // is different from the root element size - this would prevent writemasks
39356 // from being reused.
39357 bool IsMaskedShuffle = false;
39358 if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
39359 if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
39360 Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
39361 IsMaskedShuffle = true;
39365 // If we are shuffling a splat (and not introducing zeros) then we can just
39366 // use it directly. This works for smaller elements as well as they already
39367 // repeat across each mask element.
39368 if (UnaryShuffle && !isAnyZero(BaseMask) &&
39369 V1.getValueSizeInBits() >= RootSizeInBits &&
39370 (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
39371 DAG.isSplatValue(V1, /*AllowUndefs*/ false)) {
39372 return CanonicalizeShuffleInput(RootVT, V1);
39375 SmallVector<int, 64> Mask(BaseMask);
39377 // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
39378 // etc. can be simplified.
39379 if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits && VT1.isVector()) {
39380 SmallVector<int> ScaledMask, IdentityMask;
39381 unsigned NumElts = VT1.getVectorNumElements();
39382 if (Mask.size() <= NumElts &&
39383 scaleShuffleElements(Mask, NumElts, ScaledMask)) {
39384 for (unsigned i = 0; i != NumElts; ++i)
39385 IdentityMask.push_back(i);
39386 if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, DAG, V1,
39387 V2))
39388 return CanonicalizeShuffleInput(RootVT, V1);
39392 // Handle 128/256-bit lane shuffles of 512-bit vectors.
39393 if (RootVT.is512BitVector() &&
39394 (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
39395 // If the upper subvectors are zeroable, then an extract+insert is more
39396 // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
39397 // to zero the upper subvectors.
39398 if (isUndefOrZeroInRange(Mask, 1, NumBaseMaskElts - 1)) {
39399 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
39400 return SDValue(); // Nothing to do!
39401 assert(isInRange(Mask[0], 0, NumBaseMaskElts) &&
39402 "Unexpected lane shuffle");
39403 Res = CanonicalizeShuffleInput(RootVT, V1);
39404 unsigned SubIdx = Mask[0] * (NumRootElts / NumBaseMaskElts);
39405 bool UseZero = isAnyZero(Mask);
39406 Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
39407 return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
39410 // Narrow shuffle mask to v4x128.
39411 SmallVector<int, 4> ScaledMask;
39412 assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
39413 narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, Mask, ScaledMask);
39415 // Try to lower to vshuf64x2/vshuf32x4.
39416 auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL,
39417 ArrayRef<int> ScaledMask, SDValue V1, SDValue V2,
39418 SelectionDAG &DAG) {
39419 int PermMask[4] = {-1, -1, -1, -1};
39420 // Ensure elements came from the same Op.
39421 SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
39422 for (int i = 0; i < 4; ++i) {
39423 assert(ScaledMask[i] >= -1 && "Illegal shuffle sentinel value");
39424 if (ScaledMask[i] < 0)
39425 continue;
39427 SDValue Op = ScaledMask[i] >= 4 ? V2 : V1;
39428 unsigned OpIndex = i / 2;
39429 if (Ops[OpIndex].isUndef())
39430 Ops[OpIndex] = Op;
39431 else if (Ops[OpIndex] != Op)
39432 return SDValue();
39434 PermMask[i] = ScaledMask[i] % 4;
39437 return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
39438 CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
39439 CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
39440 getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
39443 // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
39444 // doesn't work because our mask is for 128 bits and we don't have an MVT
39445 // to match that.
39446 bool PreferPERMQ = UnaryShuffle && isUndefOrInRange(ScaledMask[0], 0, 2) &&
39447 isUndefOrInRange(ScaledMask[1], 0, 2) &&
39448 isUndefOrInRange(ScaledMask[2], 2, 4) &&
39449 isUndefOrInRange(ScaledMask[3], 2, 4) &&
39450 (ScaledMask[0] < 0 || ScaledMask[2] < 0 ||
39451 ScaledMask[0] == (ScaledMask[2] % 2)) &&
39452 (ScaledMask[1] < 0 || ScaledMask[3] < 0 ||
39453 ScaledMask[1] == (ScaledMask[3] % 2));
39455 if (!isAnyZero(ScaledMask) && !PreferPERMQ) {
39456 if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
39457 return SDValue(); // Nothing to do!
39458 MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
39459 if (SDValue V = MatchSHUF128(ShuffleVT, DL, ScaledMask, V1, V2, DAG))
39460 return DAG.getBitcast(RootVT, V);
39464 // Handle 128-bit lane shuffles of 256-bit vectors.
39465 if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
39466 // If the upper half is zeroable, then an extract+insert is more optimal
39467 // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
39468 // zero the upper half.
39469 if (isUndefOrZero(Mask[1])) {
39470 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
39471 return SDValue(); // Nothing to do!
39472 assert(isInRange(Mask[0], 0, 2) && "Unexpected lane shuffle");
39473 Res = CanonicalizeShuffleInput(RootVT, V1);
39474 Res = extract128BitVector(Res, Mask[0] * (NumRootElts / 2), DAG, DL);
39475 return widenSubVector(Res, Mask[1] == SM_SentinelZero, Subtarget, DAG, DL,
39476 256);
39479 // If we're inserting the low subvector, an insert-subvector 'concat'
39480 // pattern is quicker than VPERM2X128.
39481 // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
39482 if (BaseMask[0] == 0 && (BaseMask[1] == 0 || BaseMask[1] == 2) &&
39483 !Subtarget.hasAVX2()) {
39484 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
39485 return SDValue(); // Nothing to do!
39486 SDValue Lo = CanonicalizeShuffleInput(RootVT, V1);
39487 SDValue Hi = CanonicalizeShuffleInput(RootVT, BaseMask[1] == 0 ? V1 : V2);
39488 Hi = extractSubVector(Hi, 0, DAG, DL, 128);
39489 return insertSubVector(Lo, Hi, NumRootElts / 2, DAG, DL, 128);
39492 if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
39493 return SDValue(); // Nothing to do!
39495 // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
39496 // we need to use the zeroing feature.
39497 // Prefer blends for sequential shuffles unless we are optimizing for size.
39498 if (UnaryShuffle &&
39499 !(Subtarget.hasAVX2() && isUndefOrInRange(Mask, 0, 2)) &&
39500 (OptForSize || !isSequentialOrUndefOrZeroInRange(Mask, 0, 2, 0))) {
39501 unsigned PermMask = 0;
39502 PermMask |= ((Mask[0] < 0 ? 0x8 : (Mask[0] & 1)) << 0);
39503 PermMask |= ((Mask[1] < 0 ? 0x8 : (Mask[1] & 1)) << 4);
39504 return DAG.getNode(
39505 X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
39506 DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
39509 if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
39510 return SDValue(); // Nothing to do!
39512 // TODO - handle AVX512VL cases with X86ISD::SHUF128.
39513 if (!UnaryShuffle && !IsMaskedShuffle) {
39514 assert(llvm::all_of(Mask, [](int M) { return 0 <= M && M < 4; }) &&
39515 "Unexpected shuffle sentinel value");
39516 // Prefer blends to X86ISD::VPERM2X128.
39517 if (!((Mask[0] == 0 && Mask[1] == 3) || (Mask[0] == 2 && Mask[1] == 1))) {
39518 unsigned PermMask = 0;
39519 PermMask |= ((Mask[0] & 3) << 0);
39520 PermMask |= ((Mask[1] & 3) << 4);
39521 SDValue LHS = isInRange(Mask[0], 0, 2) ? V1 : V2;
39522 SDValue RHS = isInRange(Mask[1], 0, 2) ? V1 : V2;
39523 return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
39524 CanonicalizeShuffleInput(RootVT, LHS),
39525 CanonicalizeShuffleInput(RootVT, RHS),
39526 DAG.getTargetConstant(PermMask, DL, MVT::i8));
39531 // For masks that have been widened to 128-bit elements or more,
39532 // narrow back down to 64-bit elements.
39533 if (BaseMaskEltSizeInBits > 64) {
39534 assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
39535 int MaskScale = BaseMaskEltSizeInBits / 64;
39536 SmallVector<int, 64> ScaledMask;
39537 narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
39538 Mask = std::move(ScaledMask);
39541 // For masked shuffles, we're trying to match the root width for better
39542 // writemask folding, attempt to scale the mask.
39543 // TODO - variable shuffles might need this to be widened again.
39544 if (IsMaskedShuffle && NumRootElts > Mask.size()) {
39545 assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
39546 int MaskScale = NumRootElts / Mask.size();
39547 SmallVector<int, 64> ScaledMask;
39548 narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
39549 Mask = std::move(ScaledMask);
39552 unsigned NumMaskElts = Mask.size();
39553 unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
39554 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39556 // Determine the effective mask value type.
39557 FloatDomain &= (32 <= MaskEltSizeInBits);
39558 MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
39559 : MVT::getIntegerVT(MaskEltSizeInBits);
39560 MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
39562 // Only allow legal mask types.
39563 if (!TLI.isTypeLegal(MaskVT))
39564 return SDValue();
39566 // Attempt to match the mask against known shuffle patterns.
39567 MVT ShuffleSrcVT, ShuffleVT;
39568 unsigned Shuffle, PermuteImm;
39570 // Which shuffle domains are permitted?
39571 // Permit domain crossing at higher combine depths.
39572 // TODO: Should we indicate which domain is preferred if both are allowed?
39573 bool AllowFloatDomain = FloatDomain || (Depth >= 3);
39574 bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
39575 (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
39577 // Determine zeroable mask elements.
39578 APInt KnownUndef, KnownZero;
39579 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
39580 APInt Zeroable = KnownUndef | KnownZero;
39582 if (UnaryShuffle) {
39583 // Attempt to match against broadcast-from-vector.
39584 // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
39585 if ((Subtarget.hasAVX2() ||
39586 (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
39587 (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
39588 if (isUndefOrEqual(Mask, 0)) {
39589 if (V1.getValueType() == MaskVT &&
39590 V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39591 X86::mayFoldLoad(V1.getOperand(0), Subtarget)) {
39592 if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
39593 return SDValue(); // Nothing to do!
39594 Res = V1.getOperand(0);
39595 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
39596 return DAG.getBitcast(RootVT, Res);
39598 if (Subtarget.hasAVX2()) {
39599 if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
39600 return SDValue(); // Nothing to do!
39601 Res = CanonicalizeShuffleInput(MaskVT, V1);
39602 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
39603 return DAG.getBitcast(RootVT, Res);
39608 if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, V1,
39609 DAG, Subtarget, Shuffle, ShuffleSrcVT, ShuffleVT) &&
39610 (!IsMaskedShuffle ||
39611 (NumRootElts == ShuffleVT.getVectorNumElements()))) {
39612 if (Depth == 0 && Root.getOpcode() == Shuffle)
39613 return SDValue(); // Nothing to do!
39614 Res = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
39615 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
39616 return DAG.getBitcast(RootVT, Res);
39619 if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
39620 AllowIntDomain, DAG, Subtarget, Shuffle, ShuffleVT,
39621 PermuteImm) &&
39622 (!IsMaskedShuffle ||
39623 (NumRootElts == ShuffleVT.getVectorNumElements()))) {
39624 if (Depth == 0 && Root.getOpcode() == Shuffle)
39625 return SDValue(); // Nothing to do!
39626 Res = CanonicalizeShuffleInput(ShuffleVT, V1);
39627 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
39628 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
39629 return DAG.getBitcast(RootVT, Res);
39633 // Attempt to combine to INSERTPS, but only if the inserted element has come
39634 // from a scalar.
39635 // TODO: Handle other insertions here as well?
39636 if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
39637 Subtarget.hasSSE41() &&
39638 !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG)) {
39639 if (MaskEltSizeInBits == 32) {
39640 SDValue SrcV1 = V1, SrcV2 = V2;
39641 if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
39642 DAG) &&
39643 SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
39644 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
39645 return SDValue(); // Nothing to do!
39646 Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
39647 CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
39648 CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
39649 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
39650 return DAG.getBitcast(RootVT, Res);
39653 if (MaskEltSizeInBits == 64 &&
39654 isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}, DAG) &&
39655 V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39656 V2.getScalarValueSizeInBits() <= 32) {
39657 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
39658 return SDValue(); // Nothing to do!
39659 PermuteImm = (/*DstIdx*/ 2 << 4) | (/*SrcIdx*/ 0 << 0);
39660 Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
39661 CanonicalizeShuffleInput(MVT::v4f32, V1),
39662 CanonicalizeShuffleInput(MVT::v4f32, V2),
39663 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
39664 return DAG.getBitcast(RootVT, Res);
39668 SDValue NewV1 = V1; // Save operands in case early exit happens.
39669 SDValue NewV2 = V2;
39670 if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
39671 NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
39672 ShuffleVT, UnaryShuffle) &&
39673 (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
39674 if (Depth == 0 && Root.getOpcode() == Shuffle)
39675 return SDValue(); // Nothing to do!
39676 NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
39677 NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
39678 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
39679 return DAG.getBitcast(RootVT, Res);
39682 NewV1 = V1; // Save operands in case early exit happens.
39683 NewV2 = V2;
39684 if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
39685 AllowIntDomain, NewV1, NewV2, DL, DAG,
39686 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
39687 (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
39688 if (Depth == 0 && Root.getOpcode() == Shuffle)
39689 return SDValue(); // Nothing to do!
39690 NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
39691 NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
39692 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
39693 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
39694 return DAG.getBitcast(RootVT, Res);
39697 // Typically from here on, we need an integer version of MaskVT.
39698 MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
39699 IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
39701 // Annoyingly, SSE4A instructions don't map into the above match helpers.
39702 if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
39703 uint64_t BitLen, BitIdx;
39704 if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
39705 Zeroable)) {
39706 if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
39707 return SDValue(); // Nothing to do!
39708 V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
39709 Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
39710 DAG.getTargetConstant(BitLen, DL, MVT::i8),
39711 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
39712 return DAG.getBitcast(RootVT, Res);
39715 if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
39716 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
39717 return SDValue(); // Nothing to do!
39718 V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
39719 V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
39720 Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
39721 DAG.getTargetConstant(BitLen, DL, MVT::i8),
39722 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
39723 return DAG.getBitcast(RootVT, Res);
39727 // Match shuffle against TRUNCATE patterns.
39728 if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
39729 // Match against a VTRUNC instruction, accounting for src/dst sizes.
39730 if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
39731 Subtarget)) {
39732 bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
39733 ShuffleSrcVT.getVectorNumElements();
39734 unsigned Opc =
39735 IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
39736 if (Depth == 0 && Root.getOpcode() == Opc)
39737 return SDValue(); // Nothing to do!
39738 V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
39739 Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
39740 if (ShuffleVT.getSizeInBits() < RootSizeInBits)
39741 Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
39742 return DAG.getBitcast(RootVT, Res);
39745 // Do we need a more general binary truncation pattern?
39746 if (RootSizeInBits < 512 &&
39747 ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
39748 (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
39749 (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
39750 isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
39751 // Bail if this was already a truncation or PACK node.
39752 // We sometimes fail to match PACK if we demand known undef elements.
39753 if (Depth == 0 && (Root.getOpcode() == ISD::TRUNCATE ||
39754 Root.getOpcode() == X86ISD::PACKSS ||
39755 Root.getOpcode() == X86ISD::PACKUS))
39756 return SDValue(); // Nothing to do!
39757 ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
39758 ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
39759 V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
39760 V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
39761 ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
39762 ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
39763 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
39764 Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
39765 return DAG.getBitcast(RootVT, Res);
39769 // Don't try to re-form single instruction chains under any circumstances now
39770 // that we've done encoding canonicalization for them.
39771 if (Depth < 1)
39772 return SDValue();
39774 // Depth threshold above which we can efficiently use variable mask shuffles.
39775 int VariableCrossLaneShuffleDepth =
39776 Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
39777 int VariablePerLaneShuffleDepth =
39778 Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
39779 AllowVariableCrossLaneMask &=
39780 (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
39781 AllowVariablePerLaneMask &=
39782 (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
39783 // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
39784 // higher depth before combining them.
39785 bool AllowBWIVPERMV3 =
39786 (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
39788 bool MaskContainsZeros = isAnyZero(Mask);
39790 if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
39791 // If we have a single input lane-crossing shuffle then lower to VPERMV.
39792 if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
39793 if (Subtarget.hasAVX2() &&
39794 (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
39795 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
39796 Res = CanonicalizeShuffleInput(MaskVT, V1);
39797 Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
39798 return DAG.getBitcast(RootVT, Res);
39800 // AVX512 variants (non-VLX will pad to 512-bit shuffles).
39801 if ((Subtarget.hasAVX512() &&
39802 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
39803 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
39804 (Subtarget.hasBWI() &&
39805 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
39806 (Subtarget.hasVBMI() &&
39807 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
39808 V1 = CanonicalizeShuffleInput(MaskVT, V1);
39809 V2 = DAG.getUNDEF(MaskVT);
39810 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
39811 return DAG.getBitcast(RootVT, Res);
39815 // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
39816 // vector as the second source (non-VLX will pad to 512-bit shuffles).
39817 if (UnaryShuffle && AllowVariableCrossLaneMask &&
39818 ((Subtarget.hasAVX512() &&
39819 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
39820 MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
39821 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
39822 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
39823 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
39824 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
39825 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
39826 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
39827 // Adjust shuffle mask - replace SM_SentinelZero with second source index.
39828 for (unsigned i = 0; i != NumMaskElts; ++i)
39829 if (Mask[i] == SM_SentinelZero)
39830 Mask[i] = NumMaskElts + i;
39831 V1 = CanonicalizeShuffleInput(MaskVT, V1);
39832 V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
39833 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
39834 return DAG.getBitcast(RootVT, Res);
39837 // If that failed and either input is extracted then try to combine as a
39838 // shuffle with the larger type.
39839 if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
39840 Inputs, Root, BaseMask, Depth, HasVariableMask,
39841 AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
39842 Subtarget))
39843 return WideShuffle;
39845 // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
39846 // (non-VLX will pad to 512-bit shuffles).
39847 if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
39848 ((Subtarget.hasAVX512() &&
39849 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
39850 MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
39851 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
39852 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
39853 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
39854 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
39855 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
39856 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
39857 V1 = CanonicalizeShuffleInput(MaskVT, V1);
39858 V2 = CanonicalizeShuffleInput(MaskVT, V2);
39859 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
39860 return DAG.getBitcast(RootVT, Res);
39862 return SDValue();
39865 // See if we can combine a single input shuffle with zeros to a bit-mask,
39866 // which is much simpler than any shuffle.
39867 if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
39868 isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
39869 TLI.isTypeLegal(MaskVT)) {
39870 APInt Zero = APInt::getZero(MaskEltSizeInBits);
39871 APInt AllOnes = APInt::getAllOnes(MaskEltSizeInBits);
39872 APInt UndefElts(NumMaskElts, 0);
39873 SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
39874 for (unsigned i = 0; i != NumMaskElts; ++i) {
39875 int M = Mask[i];
39876 if (M == SM_SentinelUndef) {
39877 UndefElts.setBit(i);
39878 continue;
39880 if (M == SM_SentinelZero)
39881 continue;
39882 EltBits[i] = AllOnes;
39884 SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
39885 Res = CanonicalizeShuffleInput(MaskVT, V1);
39886 unsigned AndOpcode =
39887 MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
39888 Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
39889 return DAG.getBitcast(RootVT, Res);
39892 // If we have a single input shuffle with different shuffle patterns in the
39893 // the 128-bit lanes use the variable mask to VPERMILPS.
39894 // TODO Combine other mask types at higher depths.
39895 if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
39896 ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
39897 (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
39898 SmallVector<SDValue, 16> VPermIdx;
39899 for (int M : Mask) {
39900 SDValue Idx =
39901 M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
39902 VPermIdx.push_back(Idx);
39904 SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
39905 Res = CanonicalizeShuffleInput(MaskVT, V1);
39906 Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
39907 return DAG.getBitcast(RootVT, Res);
39910 // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
39911 // to VPERMIL2PD/VPERMIL2PS.
39912 if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
39913 (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
39914 MaskVT == MVT::v8f32)) {
39915 // VPERMIL2 Operation.
39916 // Bits[3] - Match Bit.
39917 // Bits[2:1] - (Per Lane) PD Shuffle Mask.
39918 // Bits[2:0] - (Per Lane) PS Shuffle Mask.
39919 unsigned NumLanes = MaskVT.getSizeInBits() / 128;
39920 unsigned NumEltsPerLane = NumMaskElts / NumLanes;
39921 SmallVector<int, 8> VPerm2Idx;
39922 unsigned M2ZImm = 0;
39923 for (int M : Mask) {
39924 if (M == SM_SentinelUndef) {
39925 VPerm2Idx.push_back(-1);
39926 continue;
39928 if (M == SM_SentinelZero) {
39929 M2ZImm = 2;
39930 VPerm2Idx.push_back(8);
39931 continue;
39933 int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
39934 Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
39935 VPerm2Idx.push_back(Index);
39937 V1 = CanonicalizeShuffleInput(MaskVT, V1);
39938 V2 = CanonicalizeShuffleInput(MaskVT, V2);
39939 SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
39940 Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
39941 DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
39942 return DAG.getBitcast(RootVT, Res);
39945 // If we have 3 or more shuffle instructions or a chain involving a variable
39946 // mask, we can replace them with a single PSHUFB instruction profitably.
39947 // Intel's manuals suggest only using PSHUFB if doing so replacing 5
39948 // instructions, but in practice PSHUFB tends to be *very* fast so we're
39949 // more aggressive.
39950 if (UnaryShuffle && AllowVariablePerLaneMask &&
39951 ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
39952 (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
39953 (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
39954 SmallVector<SDValue, 16> PSHUFBMask;
39955 int NumBytes = RootVT.getSizeInBits() / 8;
39956 int Ratio = NumBytes / NumMaskElts;
39957 for (int i = 0; i < NumBytes; ++i) {
39958 int M = Mask[i / Ratio];
39959 if (M == SM_SentinelUndef) {
39960 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
39961 continue;
39963 if (M == SM_SentinelZero) {
39964 PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
39965 continue;
39967 M = Ratio * M + i % Ratio;
39968 assert((M / 16) == (i / 16) && "Lane crossing detected");
39969 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
39971 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
39972 Res = CanonicalizeShuffleInput(ByteVT, V1);
39973 SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
39974 Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
39975 return DAG.getBitcast(RootVT, Res);
39978 // With XOP, if we have a 128-bit binary input shuffle we can always combine
39979 // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
39980 // slower than PSHUFB on targets that support both.
39981 if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
39982 Subtarget.hasXOP()) {
39983 // VPPERM Mask Operation
39984 // Bits[4:0] - Byte Index (0 - 31)
39985 // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
39986 SmallVector<SDValue, 16> VPPERMMask;
39987 int NumBytes = 16;
39988 int Ratio = NumBytes / NumMaskElts;
39989 for (int i = 0; i < NumBytes; ++i) {
39990 int M = Mask[i / Ratio];
39991 if (M == SM_SentinelUndef) {
39992 VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
39993 continue;
39995 if (M == SM_SentinelZero) {
39996 VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
39997 continue;
39999 M = Ratio * M + i % Ratio;
40000 VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
40002 MVT ByteVT = MVT::v16i8;
40003 V1 = CanonicalizeShuffleInput(ByteVT, V1);
40004 V2 = CanonicalizeShuffleInput(ByteVT, V2);
40005 SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
40006 Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
40007 return DAG.getBitcast(RootVT, Res);
40010 // If that failed and either input is extracted then try to combine as a
40011 // shuffle with the larger type.
40012 if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
40013 Inputs, Root, BaseMask, Depth, HasVariableMask,
40014 AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
40015 return WideShuffle;
40017 // If we have a dual input shuffle then lower to VPERMV3,
40018 // (non-VLX will pad to 512-bit shuffles)
40019 if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
40020 ((Subtarget.hasAVX512() &&
40021 (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
40022 MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
40023 MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
40024 MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
40025 MaskVT == MVT::v16i32)) ||
40026 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
40027 (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
40028 MaskVT == MVT::v32i16)) ||
40029 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
40030 (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
40031 MaskVT == MVT::v64i8)))) {
40032 V1 = CanonicalizeShuffleInput(MaskVT, V1);
40033 V2 = CanonicalizeShuffleInput(MaskVT, V2);
40034 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
40035 return DAG.getBitcast(RootVT, Res);
40038 // Failed to find any combines.
40039 return SDValue();
40042 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
40043 // instruction if possible.
40045 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
40046 // type size to attempt to combine:
40047 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
40048 // -->
40049 // extract_subvector(shuffle(x,y,m2),0)
40050 static SDValue combineX86ShuffleChainWithExtract(
40051 ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
40052 bool HasVariableMask, bool AllowVariableCrossLaneMask,
40053 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
40054 const X86Subtarget &Subtarget) {
40055 unsigned NumMaskElts = BaseMask.size();
40056 unsigned NumInputs = Inputs.size();
40057 if (NumInputs == 0)
40058 return SDValue();
40060 EVT RootVT = Root.getValueType();
40061 unsigned RootSizeInBits = RootVT.getSizeInBits();
40062 unsigned RootEltSizeInBits = RootSizeInBits / NumMaskElts;
40063 assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
40065 // Peek through subvectors to find widest legal vector.
40066 // TODO: Handle ISD::TRUNCATE
40067 unsigned WideSizeInBits = RootSizeInBits;
40068 for (SDValue Input : Inputs) {
40069 Input = peekThroughBitcasts(Input);
40070 while (1) {
40071 if (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
40072 Input = peekThroughBitcasts(Input.getOperand(0));
40073 continue;
40075 if (Input.getOpcode() == ISD::INSERT_SUBVECTOR &&
40076 Input.getOperand(0).isUndef()) {
40077 Input = peekThroughBitcasts(Input.getOperand(1));
40078 continue;
40080 break;
40082 if (DAG.getTargetLoweringInfo().isTypeLegal(Input.getValueType()) &&
40083 WideSizeInBits < Input.getValueSizeInBits())
40084 WideSizeInBits = Input.getValueSizeInBits();
40087 // Bail if we fail to find a source larger than the existing root.
40088 unsigned Scale = WideSizeInBits / RootSizeInBits;
40089 if (WideSizeInBits <= RootSizeInBits ||
40090 (WideSizeInBits % RootSizeInBits) != 0)
40091 return SDValue();
40093 // Create new mask for larger type.
40094 SmallVector<int, 64> WideMask(BaseMask);
40095 for (int &M : WideMask) {
40096 if (M < 0)
40097 continue;
40098 M = (M % NumMaskElts) + ((M / NumMaskElts) * Scale * NumMaskElts);
40100 WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
40102 // Attempt to peek through inputs and adjust mask when we extract from an
40103 // upper subvector.
40104 int AdjustedMasks = 0;
40105 SmallVector<SDValue, 4> WideInputs(Inputs);
40106 for (unsigned I = 0; I != NumInputs; ++I) {
40107 SDValue &Input = WideInputs[I];
40108 Input = peekThroughBitcasts(Input);
40109 while (1) {
40110 if (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40111 Input.getOperand(0).getValueSizeInBits() <= WideSizeInBits) {
40112 uint64_t Idx = Input.getConstantOperandVal(1);
40113 if (Idx != 0) {
40114 ++AdjustedMasks;
40115 unsigned InputEltSizeInBits = Input.getScalarValueSizeInBits();
40116 Idx = (Idx * InputEltSizeInBits) / RootEltSizeInBits;
40118 int lo = I * WideMask.size();
40119 int hi = (I + 1) * WideMask.size();
40120 for (int &M : WideMask)
40121 if (lo <= M && M < hi)
40122 M += Idx;
40124 Input = peekThroughBitcasts(Input.getOperand(0));
40125 continue;
40127 // TODO: Handle insertions into upper subvectors.
40128 if (Input.getOpcode() == ISD::INSERT_SUBVECTOR &&
40129 Input.getOperand(0).isUndef() &&
40130 isNullConstant(Input.getOperand(2))) {
40131 Input = peekThroughBitcasts(Input.getOperand(1));
40132 continue;
40134 break;
40138 // Remove unused/repeated shuffle source ops.
40139 resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
40140 assert(!WideInputs.empty() && "Shuffle with no inputs detected");
40142 // Bail if we're always extracting from the lowest subvectors,
40143 // combineX86ShuffleChain should match this for the current width, or the
40144 // shuffle still references too many inputs.
40145 if (AdjustedMasks == 0 || WideInputs.size() > 2)
40146 return SDValue();
40148 // Minor canonicalization of the accumulated shuffle mask to make it easier
40149 // to match below. All this does is detect masks with sequential pairs of
40150 // elements, and shrink them to the half-width mask. It does this in a loop
40151 // so it will reduce the size of the mask to the minimal width mask which
40152 // performs an equivalent shuffle.
40153 while (WideMask.size() > 1) {
40154 SmallVector<int, 64> WidenedMask;
40155 if (!canWidenShuffleElements(WideMask, WidenedMask))
40156 break;
40157 WideMask = std::move(WidenedMask);
40160 // Canonicalization of binary shuffle masks to improve pattern matching by
40161 // commuting the inputs.
40162 if (WideInputs.size() == 2 && canonicalizeShuffleMaskWithCommute(WideMask)) {
40163 ShuffleVectorSDNode::commuteMask(WideMask);
40164 std::swap(WideInputs[0], WideInputs[1]);
40167 // Increase depth for every upper subvector we've peeked through.
40168 Depth += AdjustedMasks;
40170 // Attempt to combine wider chain.
40171 // TODO: Can we use a better Root?
40172 SDValue WideRoot = WideInputs.front().getValueSizeInBits() >
40173 WideInputs.back().getValueSizeInBits()
40174 ? WideInputs.front()
40175 : WideInputs.back();
40176 assert(WideRoot.getValueSizeInBits() == WideSizeInBits &&
40177 "WideRootSize mismatch");
40179 if (SDValue WideShuffle =
40180 combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
40181 HasVariableMask, AllowVariableCrossLaneMask,
40182 AllowVariablePerLaneMask, DAG, Subtarget)) {
40183 WideShuffle =
40184 extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
40185 return DAG.getBitcast(RootVT, WideShuffle);
40188 return SDValue();
40191 // Canonicalize the combined shuffle mask chain with horizontal ops.
40192 // NOTE: This may update the Ops and Mask.
40193 static SDValue canonicalizeShuffleMaskWithHorizOp(
40194 MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
40195 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
40196 const X86Subtarget &Subtarget) {
40197 if (Mask.empty() || Ops.empty())
40198 return SDValue();
40200 SmallVector<SDValue> BC;
40201 for (SDValue Op : Ops)
40202 BC.push_back(peekThroughBitcasts(Op));
40204 // All ops must be the same horizop + type.
40205 SDValue BC0 = BC[0];
40206 EVT VT0 = BC0.getValueType();
40207 unsigned Opcode0 = BC0.getOpcode();
40208 if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
40209 return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
40211 return SDValue();
40213 bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
40214 Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
40215 bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
40216 if (!isHoriz && !isPack)
40217 return SDValue();
40219 // Do all ops have a single use?
40220 bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
40221 return Op.hasOneUse() &&
40222 peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
40225 int NumElts = VT0.getVectorNumElements();
40226 int NumLanes = VT0.getSizeInBits() / 128;
40227 int NumEltsPerLane = NumElts / NumLanes;
40228 int NumHalfEltsPerLane = NumEltsPerLane / 2;
40229 MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
40230 unsigned EltSizeInBits = RootSizeInBits / Mask.size();
40232 if (NumEltsPerLane >= 4 &&
40233 (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
40234 SmallVector<int> LaneMask, ScaledMask;
40235 if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
40236 scaleShuffleElements(LaneMask, 4, ScaledMask)) {
40237 // See if we can remove the shuffle by resorting the HOP chain so that
40238 // the HOP args are pre-shuffled.
40239 // TODO: Generalize to any sized/depth chain.
40240 // TODO: Add support for PACKSS/PACKUS.
40241 if (isHoriz) {
40242 // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
40243 auto GetHOpSrc = [&](int M) {
40244 if (M == SM_SentinelUndef)
40245 return DAG.getUNDEF(VT0);
40246 if (M == SM_SentinelZero)
40247 return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
40248 SDValue Src0 = BC[M / 4];
40249 SDValue Src1 = Src0.getOperand((M % 4) >= 2);
40250 if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
40251 return Src1.getOperand(M % 2);
40252 return SDValue();
40254 SDValue M0 = GetHOpSrc(ScaledMask[0]);
40255 SDValue M1 = GetHOpSrc(ScaledMask[1]);
40256 SDValue M2 = GetHOpSrc(ScaledMask[2]);
40257 SDValue M3 = GetHOpSrc(ScaledMask[3]);
40258 if (M0 && M1 && M2 && M3) {
40259 SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
40260 SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
40261 return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
40264 // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
40265 if (Ops.size() >= 2) {
40266 SDValue LHS, RHS;
40267 auto GetHOpSrc = [&](int M, int &OutM) {
40268 // TODO: Support SM_SentinelZero
40269 if (M < 0)
40270 return M == SM_SentinelUndef;
40271 SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
40272 if (!LHS || LHS == Src) {
40273 LHS = Src;
40274 OutM = (M % 2);
40275 return true;
40277 if (!RHS || RHS == Src) {
40278 RHS = Src;
40279 OutM = (M % 2) + 2;
40280 return true;
40282 return false;
40284 int PostMask[4] = {-1, -1, -1, -1};
40285 if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
40286 GetHOpSrc(ScaledMask[1], PostMask[1]) &&
40287 GetHOpSrc(ScaledMask[2], PostMask[2]) &&
40288 GetHOpSrc(ScaledMask[3], PostMask[3])) {
40289 LHS = DAG.getBitcast(SrcVT, LHS);
40290 RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
40291 SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
40292 // Use SHUFPS for the permute so this will work on SSE2 targets,
40293 // shuffle combining and domain handling will simplify this later on.
40294 MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
40295 Res = DAG.getBitcast(ShuffleVT, Res);
40296 return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
40297 getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
40303 if (2 < Ops.size())
40304 return SDValue();
40306 SDValue BC1 = BC[BC.size() - 1];
40307 if (Mask.size() == VT0.getVectorNumElements()) {
40308 // Canonicalize binary shuffles of horizontal ops that use the
40309 // same sources to an unary shuffle.
40310 // TODO: Try to perform this fold even if the shuffle remains.
40311 if (Ops.size() == 2) {
40312 auto ContainsOps = [](SDValue HOp, SDValue Op) {
40313 return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
40315 // Commute if all BC0's ops are contained in BC1.
40316 if (ContainsOps(BC1, BC0.getOperand(0)) &&
40317 ContainsOps(BC1, BC0.getOperand(1))) {
40318 ShuffleVectorSDNode::commuteMask(Mask);
40319 std::swap(Ops[0], Ops[1]);
40320 std::swap(BC0, BC1);
40323 // If BC1 can be represented by BC0, then convert to unary shuffle.
40324 if (ContainsOps(BC0, BC1.getOperand(0)) &&
40325 ContainsOps(BC0, BC1.getOperand(1))) {
40326 for (int &M : Mask) {
40327 if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
40328 continue;
40329 int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
40330 M -= NumElts + (SubLane * NumHalfEltsPerLane);
40331 if (BC1.getOperand(SubLane) != BC0.getOperand(0))
40332 M += NumHalfEltsPerLane;
40337 // Canonicalize unary horizontal ops to only refer to lower halves.
40338 for (int i = 0; i != NumElts; ++i) {
40339 int &M = Mask[i];
40340 if (isUndefOrZero(M))
40341 continue;
40342 if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
40343 (M % NumEltsPerLane) >= NumHalfEltsPerLane)
40344 M -= NumHalfEltsPerLane;
40345 if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
40346 (M % NumEltsPerLane) >= NumHalfEltsPerLane)
40347 M -= NumHalfEltsPerLane;
40351 // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
40352 // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
40353 // represents the LHS/RHS inputs for the lower/upper halves.
40354 SmallVector<int, 16> TargetMask128, WideMask128;
40355 if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
40356 scaleShuffleElements(TargetMask128, 2, WideMask128)) {
40357 assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
40358 bool SingleOp = (Ops.size() == 1);
40359 if (isPack || OneUseOps ||
40360 shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
40361 SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
40362 SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
40363 Lo = Lo.getOperand(WideMask128[0] & 1);
40364 Hi = Hi.getOperand(WideMask128[1] & 1);
40365 if (SingleOp) {
40366 SDValue Undef = DAG.getUNDEF(SrcVT);
40367 SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
40368 Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
40369 Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
40370 Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
40371 Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
40373 return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
40377 // If we are post-shuffling a 256-bit hop and not requiring the upper
40378 // elements, then try to narrow to a 128-bit hop directly.
40379 SmallVector<int, 16> WideMask64;
40380 if (Ops.size() == 1 && NumLanes == 2 &&
40381 scaleShuffleElements(Mask, 4, WideMask64) &&
40382 isUndefInRange(WideMask64, 2, 2)) {
40383 int M0 = WideMask64[0];
40384 int M1 = WideMask64[1];
40385 if (isInRange(M0, 0, 4) && isInRange(M1, 0, 4)) {
40386 MVT HalfVT = VT0.getSimpleVT().getHalfNumVectorElementsVT();
40387 unsigned Idx0 = (M0 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
40388 unsigned Idx1 = (M1 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
40389 SDValue V0 = extract128BitVector(BC[0].getOperand(M0 & 1), Idx0, DAG, DL);
40390 SDValue V1 = extract128BitVector(BC[0].getOperand(M1 & 1), Idx1, DAG, DL);
40391 SDValue Res = DAG.getNode(Opcode0, DL, HalfVT, V0, V1);
40392 return widenSubVector(Res, false, Subtarget, DAG, DL, 256);
40396 return SDValue();
40399 // Attempt to constant fold all of the constant source ops.
40400 // Returns true if the entire shuffle is folded to a constant.
40401 // TODO: Extend this to merge multiple constant Ops and update the mask.
40402 static SDValue combineX86ShufflesConstants(MVT VT, ArrayRef<SDValue> Ops,
40403 ArrayRef<int> Mask,
40404 bool HasVariableMask,
40405 SelectionDAG &DAG, const SDLoc &DL,
40406 const X86Subtarget &Subtarget) {
40407 unsigned SizeInBits = VT.getSizeInBits();
40408 unsigned NumMaskElts = Mask.size();
40409 unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
40410 unsigned NumOps = Ops.size();
40412 // Extract constant bits from each source op.
40413 SmallVector<APInt, 16> UndefEltsOps(NumOps);
40414 SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
40415 for (unsigned I = 0; I != NumOps; ++I)
40416 if (!getTargetConstantBitsFromNode(Ops[I], MaskSizeInBits, UndefEltsOps[I],
40417 RawBitsOps[I],
40418 /*AllowWholeUndefs*/ true,
40419 /*AllowPartialUndefs*/ true))
40420 return SDValue();
40422 // If we're optimizing for size, only fold if at least one of the constants is
40423 // only used once or the combined shuffle has included a variable mask
40424 // shuffle, this is to avoid constant pool bloat.
40425 bool IsOptimizingSize = DAG.shouldOptForSize();
40426 if (IsOptimizingSize && !HasVariableMask &&
40427 llvm::none_of(Ops, [](SDValue SrcOp) { return SrcOp->hasOneUse(); }))
40428 return SDValue();
40430 // Shuffle the constant bits according to the mask.
40431 APInt UndefElts(NumMaskElts, 0);
40432 APInt ZeroElts(NumMaskElts, 0);
40433 APInt ConstantElts(NumMaskElts, 0);
40434 SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
40435 APInt::getZero(MaskSizeInBits));
40436 for (unsigned i = 0; i != NumMaskElts; ++i) {
40437 int M = Mask[i];
40438 if (M == SM_SentinelUndef) {
40439 UndefElts.setBit(i);
40440 continue;
40441 } else if (M == SM_SentinelZero) {
40442 ZeroElts.setBit(i);
40443 continue;
40445 assert(0 <= M && M < (int)(NumMaskElts * NumOps));
40447 unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
40448 unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
40450 auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
40451 if (SrcUndefElts[SrcMaskIdx]) {
40452 UndefElts.setBit(i);
40453 continue;
40456 auto &SrcEltBits = RawBitsOps[SrcOpIdx];
40457 APInt &Bits = SrcEltBits[SrcMaskIdx];
40458 if (!Bits) {
40459 ZeroElts.setBit(i);
40460 continue;
40463 ConstantElts.setBit(i);
40464 ConstantBitData[i] = Bits;
40466 assert((UndefElts | ZeroElts | ConstantElts).isAllOnes());
40468 // Attempt to create a zero vector.
40469 if ((UndefElts | ZeroElts).isAllOnes())
40470 return getZeroVector(VT, Subtarget, DAG, DL);
40472 // Create the constant data.
40473 MVT MaskSVT;
40474 if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
40475 MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
40476 else
40477 MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
40479 MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
40480 if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
40481 return SDValue();
40483 SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
40484 return DAG.getBitcast(VT, CstOp);
40487 namespace llvm {
40488 namespace X86 {
40489 enum {
40490 MaxShuffleCombineDepth = 8
40492 } // namespace X86
40493 } // namespace llvm
40495 /// Fully generic combining of x86 shuffle instructions.
40497 /// This should be the last combine run over the x86 shuffle instructions. Once
40498 /// they have been fully optimized, this will recursively consider all chains
40499 /// of single-use shuffle instructions, build a generic model of the cumulative
40500 /// shuffle operation, and check for simpler instructions which implement this
40501 /// operation. We use this primarily for two purposes:
40503 /// 1) Collapse generic shuffles to specialized single instructions when
40504 /// equivalent. In most cases, this is just an encoding size win, but
40505 /// sometimes we will collapse multiple generic shuffles into a single
40506 /// special-purpose shuffle.
40507 /// 2) Look for sequences of shuffle instructions with 3 or more total
40508 /// instructions, and replace them with the slightly more expensive SSSE3
40509 /// PSHUFB instruction if available. We do this as the last combining step
40510 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
40511 /// a suitable short sequence of other instructions. The PSHUFB will either
40512 /// use a register or have to read from memory and so is slightly (but only
40513 /// slightly) more expensive than the other shuffle instructions.
40515 /// Because this is inherently a quadratic operation (for each shuffle in
40516 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
40517 /// This should never be an issue in practice as the shuffle lowering doesn't
40518 /// produce sequences of more than 8 instructions.
40520 /// FIXME: We will currently miss some cases where the redundant shuffling
40521 /// would simplify under the threshold for PSHUFB formation because of
40522 /// combine-ordering. To fix this, we should do the redundant instruction
40523 /// combining in this recursive walk.
40524 static SDValue combineX86ShufflesRecursively(
40525 ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
40526 ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
40527 unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
40528 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
40529 const X86Subtarget &Subtarget) {
40530 assert(!RootMask.empty() &&
40531 (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
40532 "Illegal shuffle root mask");
40533 MVT RootVT = Root.getSimpleValueType();
40534 assert(RootVT.isVector() && "Shuffles operate on vector types!");
40535 unsigned RootSizeInBits = RootVT.getSizeInBits();
40536 SDLoc DL(Root);
40538 // Bound the depth of our recursive combine because this is ultimately
40539 // quadratic in nature.
40540 if (Depth >= MaxDepth)
40541 return SDValue();
40543 // Directly rip through bitcasts to find the underlying operand.
40544 SDValue Op = SrcOps[SrcOpIndex];
40545 Op = peekThroughOneUseBitcasts(Op);
40547 EVT VT = Op.getValueType();
40548 if (!VT.isVector() || !VT.isSimple())
40549 return SDValue(); // Bail if we hit a non-simple non-vector.
40551 // FIXME: Just bail on f16 for now.
40552 if (VT.getVectorElementType() == MVT::f16)
40553 return SDValue();
40555 assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
40556 "Can only combine shuffles upto size of the root op.");
40558 // Create a demanded elts mask from the referenced elements of Op.
40559 APInt OpDemandedElts = APInt::getZero(RootMask.size());
40560 for (int M : RootMask) {
40561 int BaseIdx = RootMask.size() * SrcOpIndex;
40562 if (isInRange(M, BaseIdx, BaseIdx + RootMask.size()))
40563 OpDemandedElts.setBit(M - BaseIdx);
40565 if (RootSizeInBits != VT.getSizeInBits()) {
40566 // Op is smaller than Root - extract the demanded elts for the subvector.
40567 unsigned Scale = RootSizeInBits / VT.getSizeInBits();
40568 unsigned NumOpMaskElts = RootMask.size() / Scale;
40569 assert((RootMask.size() % Scale) == 0 && "Root mask size mismatch");
40570 assert(OpDemandedElts
40571 .extractBits(RootMask.size() - NumOpMaskElts, NumOpMaskElts)
40572 .isZero() &&
40573 "Out of range elements referenced in root mask");
40574 OpDemandedElts = OpDemandedElts.extractBits(NumOpMaskElts, 0);
40576 OpDemandedElts =
40577 APIntOps::ScaleBitMask(OpDemandedElts, VT.getVectorNumElements());
40579 // Extract target shuffle mask and resolve sentinels and inputs.
40580 SmallVector<int, 64> OpMask;
40581 SmallVector<SDValue, 2> OpInputs;
40582 APInt OpUndef, OpZero;
40583 bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
40584 if (getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
40585 OpZero, DAG, Depth, false)) {
40586 // Shuffle inputs must not be larger than the shuffle result.
40587 // TODO: Relax this for single input faux shuffles (e.g. trunc).
40588 if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
40589 return OpInput.getValueSizeInBits() > VT.getSizeInBits();
40591 return SDValue();
40592 } else if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40593 (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
40594 !isNullConstant(Op.getOperand(1))) {
40595 SDValue SrcVec = Op.getOperand(0);
40596 int ExtractIdx = Op.getConstantOperandVal(1);
40597 unsigned NumElts = VT.getVectorNumElements();
40598 OpInputs.assign({SrcVec});
40599 OpMask.assign(NumElts, SM_SentinelUndef);
40600 std::iota(OpMask.begin(), OpMask.end(), ExtractIdx);
40601 OpZero = OpUndef = APInt::getZero(NumElts);
40602 } else {
40603 return SDValue();
40606 // If the shuffle result was smaller than the root, we need to adjust the
40607 // mask indices and pad the mask with undefs.
40608 if (RootSizeInBits > VT.getSizeInBits()) {
40609 unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
40610 unsigned OpMaskSize = OpMask.size();
40611 if (OpInputs.size() > 1) {
40612 unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
40613 for (int &M : OpMask) {
40614 if (M < 0)
40615 continue;
40616 int EltIdx = M % OpMaskSize;
40617 int OpIdx = M / OpMaskSize;
40618 M = (PaddedMaskSize * OpIdx) + EltIdx;
40621 OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
40622 OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
40623 OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
40626 SmallVector<int, 64> Mask;
40627 SmallVector<SDValue, 16> Ops;
40629 // We don't need to merge masks if the root is empty.
40630 bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
40631 if (EmptyRoot) {
40632 // Only resolve zeros if it will remove an input, otherwise we might end
40633 // up in an infinite loop.
40634 bool ResolveKnownZeros = true;
40635 if (!OpZero.isZero()) {
40636 APInt UsedInputs = APInt::getZero(OpInputs.size());
40637 for (int i = 0, e = OpMask.size(); i != e; ++i) {
40638 int M = OpMask[i];
40639 if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
40640 continue;
40641 UsedInputs.setBit(M / OpMask.size());
40642 if (UsedInputs.isAllOnes()) {
40643 ResolveKnownZeros = false;
40644 break;
40648 resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
40649 ResolveKnownZeros);
40651 Mask = OpMask;
40652 Ops.append(OpInputs.begin(), OpInputs.end());
40653 } else {
40654 resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
40656 // Add the inputs to the Ops list, avoiding duplicates.
40657 Ops.append(SrcOps.begin(), SrcOps.end());
40659 auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
40660 // Attempt to find an existing match.
40661 SDValue InputBC = peekThroughBitcasts(Input);
40662 for (int i = 0, e = Ops.size(); i < e; ++i)
40663 if (InputBC == peekThroughBitcasts(Ops[i]))
40664 return i;
40665 // Match failed - should we replace an existing Op?
40666 if (InsertionPoint >= 0) {
40667 Ops[InsertionPoint] = Input;
40668 return InsertionPoint;
40670 // Add to the end of the Ops list.
40671 Ops.push_back(Input);
40672 return Ops.size() - 1;
40675 SmallVector<int, 2> OpInputIdx;
40676 for (SDValue OpInput : OpInputs)
40677 OpInputIdx.push_back(
40678 AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
40680 assert(((RootMask.size() > OpMask.size() &&
40681 RootMask.size() % OpMask.size() == 0) ||
40682 (OpMask.size() > RootMask.size() &&
40683 OpMask.size() % RootMask.size() == 0) ||
40684 OpMask.size() == RootMask.size()) &&
40685 "The smaller number of elements must divide the larger.");
40687 // This function can be performance-critical, so we rely on the power-of-2
40688 // knowledge that we have about the mask sizes to replace div/rem ops with
40689 // bit-masks and shifts.
40690 assert(llvm::has_single_bit<uint32_t>(RootMask.size()) &&
40691 "Non-power-of-2 shuffle mask sizes");
40692 assert(llvm::has_single_bit<uint32_t>(OpMask.size()) &&
40693 "Non-power-of-2 shuffle mask sizes");
40694 unsigned RootMaskSizeLog2 = llvm::countr_zero(RootMask.size());
40695 unsigned OpMaskSizeLog2 = llvm::countr_zero(OpMask.size());
40697 unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
40698 unsigned RootRatio =
40699 std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
40700 unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
40701 assert((RootRatio == 1 || OpRatio == 1) &&
40702 "Must not have a ratio for both incoming and op masks!");
40704 assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
40705 assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
40706 assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
40707 unsigned RootRatioLog2 = llvm::countr_zero(RootRatio);
40708 unsigned OpRatioLog2 = llvm::countr_zero(OpRatio);
40710 Mask.resize(MaskWidth, SM_SentinelUndef);
40712 // Merge this shuffle operation's mask into our accumulated mask. Note that
40713 // this shuffle's mask will be the first applied to the input, followed by
40714 // the root mask to get us all the way to the root value arrangement. The
40715 // reason for this order is that we are recursing up the operation chain.
40716 for (unsigned i = 0; i < MaskWidth; ++i) {
40717 unsigned RootIdx = i >> RootRatioLog2;
40718 if (RootMask[RootIdx] < 0) {
40719 // This is a zero or undef lane, we're done.
40720 Mask[i] = RootMask[RootIdx];
40721 continue;
40724 unsigned RootMaskedIdx =
40725 RootRatio == 1
40726 ? RootMask[RootIdx]
40727 : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
40729 // Just insert the scaled root mask value if it references an input other
40730 // than the SrcOp we're currently inserting.
40731 if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
40732 (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
40733 Mask[i] = RootMaskedIdx;
40734 continue;
40737 RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
40738 unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
40739 if (OpMask[OpIdx] < 0) {
40740 // The incoming lanes are zero or undef, it doesn't matter which ones we
40741 // are using.
40742 Mask[i] = OpMask[OpIdx];
40743 continue;
40746 // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
40747 unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
40748 : (OpMask[OpIdx] << OpRatioLog2) +
40749 (RootMaskedIdx & (OpRatio - 1));
40751 OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
40752 int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
40753 assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
40754 OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
40756 Mask[i] = OpMaskedIdx;
40760 // Peek through vector widenings and set out of bounds mask indices to undef.
40761 // TODO: Can resolveTargetShuffleInputsAndMask do some of this?
40762 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
40763 SDValue &Op = Ops[I];
40764 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op.getOperand(0).isUndef() &&
40765 isNullConstant(Op.getOperand(2))) {
40766 Op = Op.getOperand(1);
40767 unsigned Scale = RootSizeInBits / Op.getValueSizeInBits();
40768 int Lo = I * Mask.size();
40769 int Hi = (I + 1) * Mask.size();
40770 int NewHi = Lo + (Mask.size() / Scale);
40771 for (int &M : Mask) {
40772 if (Lo <= M && NewHi <= M && M < Hi)
40773 M = SM_SentinelUndef;
40778 // Peek through any free extract_subvector nodes back to root size.
40779 for (SDValue &Op : Ops)
40780 while (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40781 (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
40782 isNullConstant(Op.getOperand(1)))
40783 Op = Op.getOperand(0);
40785 // Remove unused/repeated shuffle source ops.
40786 resolveTargetShuffleInputsAndMask(Ops, Mask);
40788 // Handle the all undef/zero/ones cases early.
40789 if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
40790 return DAG.getUNDEF(RootVT);
40791 if (all_of(Mask, [](int Idx) { return Idx < 0; }))
40792 return getZeroVector(RootVT, Subtarget, DAG, DL);
40793 if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
40794 !llvm::is_contained(Mask, SM_SentinelZero))
40795 return getOnesVector(RootVT, DAG, DL);
40797 assert(!Ops.empty() && "Shuffle with no inputs detected");
40798 HasVariableMask |= IsOpVariableMask;
40800 // Update the list of shuffle nodes that have been combined so far.
40801 SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes);
40802 CombinedNodes.push_back(Op.getNode());
40804 // See if we can recurse into each shuffle source op (if it's a target
40805 // shuffle). The source op should only be generally combined if it either has
40806 // a single use (i.e. current Op) or all its users have already been combined,
40807 // if not then we can still combine but should prevent generation of variable
40808 // shuffles to avoid constant pool bloat.
40809 // Don't recurse if we already have more source ops than we can combine in
40810 // the remaining recursion depth.
40811 if (Ops.size() < (MaxDepth - Depth)) {
40812 for (int i = 0, e = Ops.size(); i < e; ++i) {
40813 // For empty roots, we need to resolve zeroable elements before combining
40814 // them with other shuffles.
40815 SmallVector<int, 64> ResolvedMask = Mask;
40816 if (EmptyRoot)
40817 resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
40818 bool AllowCrossLaneVar = false;
40819 bool AllowPerLaneVar = false;
40820 if (Ops[i].getNode()->hasOneUse() ||
40821 SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
40822 AllowCrossLaneVar = AllowVariableCrossLaneMask;
40823 AllowPerLaneVar = AllowVariablePerLaneMask;
40825 if (SDValue Res = combineX86ShufflesRecursively(
40826 Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
40827 HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
40828 Subtarget))
40829 return Res;
40833 // Attempt to constant fold all of the constant source ops.
40834 if (SDValue Cst = combineX86ShufflesConstants(
40835 RootVT, Ops, Mask, HasVariableMask, DAG, DL, Subtarget))
40836 return Cst;
40838 // If constant fold failed and we only have constants - then we have
40839 // multiple uses by a single non-variable shuffle - just bail.
40840 if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
40841 APInt UndefElts;
40842 SmallVector<APInt> RawBits;
40843 unsigned EltSizeInBits = RootSizeInBits / Mask.size();
40844 return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
40845 RawBits,
40846 /*AllowWholeUndefs*/ true,
40847 /*AllowPartialUndefs*/ true);
40848 })) {
40849 return SDValue();
40852 // Canonicalize the combined shuffle mask chain with horizontal ops.
40853 // NOTE: This will update the Ops and Mask.
40854 if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
40855 Ops, Mask, RootSizeInBits, DL, DAG, Subtarget))
40856 return DAG.getBitcast(RootVT, HOp);
40858 // Try to refine our inputs given our knowledge of target shuffle mask.
40859 for (auto I : enumerate(Ops)) {
40860 int OpIdx = I.index();
40861 SDValue &Op = I.value();
40863 // What range of shuffle mask element values results in picking from Op?
40864 int Lo = OpIdx * Mask.size();
40865 int Hi = Lo + Mask.size();
40867 // Which elements of Op do we demand, given the mask's granularity?
40868 APInt OpDemandedElts(Mask.size(), 0);
40869 for (int MaskElt : Mask) {
40870 if (isInRange(MaskElt, Lo, Hi)) { // Picks from Op?
40871 int OpEltIdx = MaskElt - Lo;
40872 OpDemandedElts.setBit(OpEltIdx);
40876 // Is the shuffle result smaller than the root?
40877 if (Op.getValueSizeInBits() < RootSizeInBits) {
40878 // We padded the mask with undefs. But we now need to undo that.
40879 unsigned NumExpectedVectorElts = Mask.size();
40880 unsigned EltSizeInBits = RootSizeInBits / NumExpectedVectorElts;
40881 unsigned NumOpVectorElts = Op.getValueSizeInBits() / EltSizeInBits;
40882 assert(!OpDemandedElts.extractBits(
40883 NumExpectedVectorElts - NumOpVectorElts, NumOpVectorElts) &&
40884 "Demanding the virtual undef widening padding?");
40885 OpDemandedElts = OpDemandedElts.trunc(NumOpVectorElts); // NUW
40888 // The Op itself may be of different VT, so we need to scale the mask.
40889 unsigned NumOpElts = Op.getValueType().getVectorNumElements();
40890 APInt OpScaledDemandedElts = APIntOps::ScaleBitMask(OpDemandedElts, NumOpElts);
40892 // Can this operand be simplified any further, given it's demanded elements?
40893 if (SDValue NewOp =
40894 DAG.getTargetLoweringInfo().SimplifyMultipleUseDemandedVectorElts(
40895 Op, OpScaledDemandedElts, DAG))
40896 Op = NewOp;
40898 // FIXME: should we rerun resolveTargetShuffleInputsAndMask() now?
40900 // Widen any subvector shuffle inputs we've collected.
40901 // TODO: Remove this to avoid generating temporary nodes, we should only
40902 // widen once combineX86ShuffleChain has found a match.
40903 if (any_of(Ops, [RootSizeInBits](SDValue Op) {
40904 return Op.getValueSizeInBits() < RootSizeInBits;
40905 })) {
40906 for (SDValue &Op : Ops)
40907 if (Op.getValueSizeInBits() < RootSizeInBits)
40908 Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
40909 RootSizeInBits);
40910 // Reresolve - we might have repeated subvector sources.
40911 resolveTargetShuffleInputsAndMask(Ops, Mask);
40914 // We can only combine unary and binary shuffle mask cases.
40915 if (Ops.size() <= 2) {
40916 // Minor canonicalization of the accumulated shuffle mask to make it easier
40917 // to match below. All this does is detect masks with sequential pairs of
40918 // elements, and shrink them to the half-width mask. It does this in a loop
40919 // so it will reduce the size of the mask to the minimal width mask which
40920 // performs an equivalent shuffle.
40921 while (Mask.size() > 1) {
40922 SmallVector<int, 64> WidenedMask;
40923 if (!canWidenShuffleElements(Mask, WidenedMask))
40924 break;
40925 Mask = std::move(WidenedMask);
40928 // Canonicalization of binary shuffle masks to improve pattern matching by
40929 // commuting the inputs.
40930 if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
40931 ShuffleVectorSDNode::commuteMask(Mask);
40932 std::swap(Ops[0], Ops[1]);
40935 // Try to combine into a single shuffle instruction.
40936 if (SDValue Shuffle = combineX86ShuffleChain(
40937 Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
40938 AllowVariablePerLaneMask, DAG, Subtarget))
40939 return Shuffle;
40941 // If all the operands come from the same larger vector, fallthrough and try
40942 // to use combineX86ShuffleChainWithExtract.
40943 SDValue LHS = peekThroughBitcasts(Ops.front());
40944 SDValue RHS = peekThroughBitcasts(Ops.back());
40945 if (Ops.size() != 2 || !Subtarget.hasAVX2() || RootSizeInBits != 128 ||
40946 (RootSizeInBits / Mask.size()) != 64 ||
40947 LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
40948 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
40949 LHS.getOperand(0) != RHS.getOperand(0))
40950 return SDValue();
40953 // If that failed and any input is extracted then try to combine as a
40954 // shuffle with the larger type.
40955 return combineX86ShuffleChainWithExtract(
40956 Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
40957 AllowVariablePerLaneMask, DAG, Subtarget);
40960 /// Helper entry wrapper to combineX86ShufflesRecursively.
40961 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
40962 const X86Subtarget &Subtarget) {
40963 return combineX86ShufflesRecursively(
40964 {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
40965 /*HasVarMask*/ false,
40966 /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
40967 Subtarget);
40970 /// Get the PSHUF-style mask from PSHUF node.
40972 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
40973 /// PSHUF-style masks that can be reused with such instructions.
40974 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
40975 MVT VT = N.getSimpleValueType();
40976 SmallVector<int, 4> Mask;
40977 SmallVector<SDValue, 2> Ops;
40978 bool HaveMask = getTargetShuffleMask(N, false, Ops, Mask);
40979 (void)HaveMask;
40980 assert(HaveMask);
40982 // If we have more than 128-bits, only the low 128-bits of shuffle mask
40983 // matter. Check that the upper masks are repeats and remove them.
40984 if (VT.getSizeInBits() > 128) {
40985 int LaneElts = 128 / VT.getScalarSizeInBits();
40986 #ifndef NDEBUG
40987 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
40988 for (int j = 0; j < LaneElts; ++j)
40989 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
40990 "Mask doesn't repeat in high 128-bit lanes!");
40991 #endif
40992 Mask.resize(LaneElts);
40995 switch (N.getOpcode()) {
40996 case X86ISD::PSHUFD:
40997 return Mask;
40998 case X86ISD::PSHUFLW:
40999 Mask.resize(4);
41000 return Mask;
41001 case X86ISD::PSHUFHW:
41002 Mask.erase(Mask.begin(), Mask.begin() + 4);
41003 for (int &M : Mask)
41004 M -= 4;
41005 return Mask;
41006 default:
41007 llvm_unreachable("No valid shuffle instruction found!");
41011 /// Search for a combinable shuffle across a chain ending in pshufd.
41013 /// We walk up the chain and look for a combinable shuffle, skipping over
41014 /// shuffles that we could hoist this shuffle's transformation past without
41015 /// altering anything.
41016 static SDValue combineRedundantDWordShuffle(SDValue N,
41017 MutableArrayRef<int> Mask,
41018 const SDLoc &DL,
41019 SelectionDAG &DAG) {
41020 assert(N.getOpcode() == X86ISD::PSHUFD &&
41021 "Called with something other than an x86 128-bit half shuffle!");
41023 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
41024 // of the shuffles in the chain so that we can form a fresh chain to replace
41025 // this one.
41026 SmallVector<SDValue, 8> Chain;
41027 SDValue V = N.getOperand(0);
41028 for (; V.hasOneUse(); V = V.getOperand(0)) {
41029 switch (V.getOpcode()) {
41030 default:
41031 return SDValue(); // Nothing combined!
41033 case ISD::BITCAST:
41034 // Skip bitcasts as we always know the type for the target specific
41035 // instructions.
41036 continue;
41038 case X86ISD::PSHUFD:
41039 // Found another dword shuffle.
41040 break;
41042 case X86ISD::PSHUFLW:
41043 // Check that the low words (being shuffled) are the identity in the
41044 // dword shuffle, and the high words are self-contained.
41045 if (Mask[0] != 0 || Mask[1] != 1 ||
41046 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
41047 return SDValue();
41049 Chain.push_back(V);
41050 continue;
41052 case X86ISD::PSHUFHW:
41053 // Check that the high words (being shuffled) are the identity in the
41054 // dword shuffle, and the low words are self-contained.
41055 if (Mask[2] != 2 || Mask[3] != 3 ||
41056 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
41057 return SDValue();
41059 Chain.push_back(V);
41060 continue;
41062 case X86ISD::UNPCKL:
41063 case X86ISD::UNPCKH:
41064 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
41065 // shuffle into a preceding word shuffle.
41066 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
41067 V.getSimpleValueType().getVectorElementType() != MVT::i16)
41068 return SDValue();
41070 // Search for a half-shuffle which we can combine with.
41071 unsigned CombineOp =
41072 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
41073 if (V.getOperand(0) != V.getOperand(1) ||
41074 !V->isOnlyUserOf(V.getOperand(0).getNode()))
41075 return SDValue();
41076 Chain.push_back(V);
41077 V = V.getOperand(0);
41078 do {
41079 switch (V.getOpcode()) {
41080 default:
41081 return SDValue(); // Nothing to combine.
41083 case X86ISD::PSHUFLW:
41084 case X86ISD::PSHUFHW:
41085 if (V.getOpcode() == CombineOp)
41086 break;
41088 Chain.push_back(V);
41090 [[fallthrough]];
41091 case ISD::BITCAST:
41092 V = V.getOperand(0);
41093 continue;
41095 break;
41096 } while (V.hasOneUse());
41097 break;
41099 // Break out of the loop if we break out of the switch.
41100 break;
41103 if (!V.hasOneUse())
41104 // We fell out of the loop without finding a viable combining instruction.
41105 return SDValue();
41107 // Merge this node's mask and our incoming mask.
41108 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
41109 for (int &M : Mask)
41110 M = VMask[M];
41111 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
41112 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
41114 // Rebuild the chain around this new shuffle.
41115 while (!Chain.empty()) {
41116 SDValue W = Chain.pop_back_val();
41118 if (V.getValueType() != W.getOperand(0).getValueType())
41119 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
41121 switch (W.getOpcode()) {
41122 default:
41123 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
41125 case X86ISD::UNPCKL:
41126 case X86ISD::UNPCKH:
41127 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
41128 break;
41130 case X86ISD::PSHUFD:
41131 case X86ISD::PSHUFLW:
41132 case X86ISD::PSHUFHW:
41133 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
41134 break;
41137 if (V.getValueType() != N.getValueType())
41138 V = DAG.getBitcast(N.getValueType(), V);
41140 // Return the new chain to replace N.
41141 return V;
41144 // Attempt to commute shufps LHS loads:
41145 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
41146 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
41147 SelectionDAG &DAG) {
41148 // TODO: Add vXf64 support.
41149 if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
41150 return SDValue();
41152 // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
41153 auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
41154 if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
41155 return SDValue();
41156 SDValue N0 = V.getOperand(0);
41157 SDValue N1 = V.getOperand(1);
41158 unsigned Imm = V.getConstantOperandVal(2);
41159 const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
41160 if (!X86::mayFoldLoad(peekThroughOneUseBitcasts(N0), Subtarget) ||
41161 X86::mayFoldLoad(peekThroughOneUseBitcasts(N1), Subtarget))
41162 return SDValue();
41163 Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
41164 return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
41165 DAG.getTargetConstant(Imm, DL, MVT::i8));
41168 switch (N.getOpcode()) {
41169 case X86ISD::VPERMILPI:
41170 if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
41171 unsigned Imm = N.getConstantOperandVal(1);
41172 return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
41173 DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
41175 break;
41176 case X86ISD::SHUFP: {
41177 SDValue N0 = N.getOperand(0);
41178 SDValue N1 = N.getOperand(1);
41179 unsigned Imm = N.getConstantOperandVal(2);
41180 if (N0 == N1) {
41181 if (SDValue NewSHUFP = commuteSHUFP(N, N0))
41182 return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
41183 DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
41184 } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
41185 return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
41186 DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
41187 } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
41188 return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
41189 DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
41191 break;
41195 return SDValue();
41198 // Attempt to fold BLEND(PERMUTE(X),PERMUTE(Y)) -> PERMUTE(BLEND(X,Y))
41199 // iff we don't demand the same element index for both X and Y.
41200 static SDValue
41201 combineBlendOfPermutes(MVT VT, SDValue N0, SDValue N1, ArrayRef<int> BlendMask,
41202 const APInt &DemandedElts, SelectionDAG &DAG,
41203 const X86Subtarget &Subtarget, const SDLoc &DL) {
41204 assert(isBlendOrUndef(BlendMask) && "Blend shuffle expected");
41205 if (!N0.hasOneUse() || !N1.hasOneUse())
41206 return SDValue();
41208 unsigned NumElts = VT.getVectorNumElements();
41209 SDValue BC0 = peekThroughOneUseBitcasts(N0);
41210 SDValue BC1 = peekThroughOneUseBitcasts(N1);
41212 // See if both operands are shuffles, and that we can scale the shuffle masks
41213 // to the same width as the blend mask.
41214 // TODO: Support SM_SentinelZero?
41215 SmallVector<SDValue, 2> Ops0, Ops1;
41216 SmallVector<int, 32> Mask0, Mask1, ScaledMask0, ScaledMask1;
41217 if (!getTargetShuffleMask(BC0, /*AllowSentinelZero=*/false, Ops0, Mask0) ||
41218 !getTargetShuffleMask(BC1, /*AllowSentinelZero=*/false, Ops1, Mask1) ||
41219 !scaleShuffleElements(Mask0, NumElts, ScaledMask0) ||
41220 !scaleShuffleElements(Mask1, NumElts, ScaledMask1))
41221 return SDValue();
41223 // Determine the demanded elts from both permutes.
41224 APInt Demanded0, DemandedLHS0, DemandedRHS0;
41225 APInt Demanded1, DemandedLHS1, DemandedRHS1;
41226 if (!getShuffleDemandedElts(NumElts, BlendMask, DemandedElts, Demanded0,
41227 Demanded1,
41228 /*AllowUndefElts=*/true) ||
41229 !getShuffleDemandedElts(NumElts, ScaledMask0, Demanded0, DemandedLHS0,
41230 DemandedRHS0, /*AllowUndefElts=*/true) ||
41231 !getShuffleDemandedElts(NumElts, ScaledMask1, Demanded1, DemandedLHS1,
41232 DemandedRHS1, /*AllowUndefElts=*/true))
41233 return SDValue();
41235 // Confirm that we only use a single operand from both permutes and that we
41236 // don't demand the same index from both.
41237 if (!DemandedRHS0.isZero() || !DemandedRHS1.isZero() ||
41238 DemandedLHS0.intersects(DemandedLHS1))
41239 return SDValue();
41241 // Use the permute demanded elts masks as the new blend mask.
41242 // Create the new permute mask as a blend of the 2 original permute masks.
41243 SmallVector<int, 32> NewBlendMask(NumElts, SM_SentinelUndef);
41244 SmallVector<int, 32> NewPermuteMask(NumElts, SM_SentinelUndef);
41245 for (unsigned I = 0; I != NumElts; ++I) {
41246 if (Demanded0[I]) {
41247 int M = ScaledMask0[I];
41248 if (0 <= M) {
41249 assert(isUndefOrEqual(NewBlendMask[M], M) &&
41250 "BlendMask demands LHS AND RHS");
41251 NewBlendMask[M] = M;
41252 NewPermuteMask[I] = M;
41254 } else if (Demanded1[I]) {
41255 int M = ScaledMask1[I];
41256 if (0 <= M) {
41257 assert(isUndefOrEqual(NewBlendMask[M], M + NumElts) &&
41258 "BlendMask demands LHS AND RHS");
41259 NewBlendMask[M] = M + NumElts;
41260 NewPermuteMask[I] = M;
41264 assert(isBlendOrUndef(NewBlendMask) && "Bad blend");
41265 assert(isUndefOrInRange(NewPermuteMask, 0, NumElts) && "Bad permute");
41267 // v16i16 shuffles can explode in complexity very easily, only accept them if
41268 // the blend mask is the same in the 128-bit subvectors (or can widen to
41269 // v8i32) and the permute can be widened as well.
41270 if (VT == MVT::v16i16) {
41271 if (!is128BitLaneRepeatedShuffleMask(VT, NewBlendMask) &&
41272 !canWidenShuffleElements(NewBlendMask))
41273 return SDValue();
41274 if (!canWidenShuffleElements(NewPermuteMask))
41275 return SDValue();
41278 // Don't introduce lane-crossing permutes without AVX2, unless it can be
41279 // widened to a lane permute (vperm2f128).
41280 if (VT.is256BitVector() && !Subtarget.hasAVX2() &&
41281 isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(),
41282 NewPermuteMask) &&
41283 !canScaleShuffleElements(NewPermuteMask, 2))
41284 return SDValue();
41286 SDValue NewBlend =
41287 DAG.getVectorShuffle(VT, DL, DAG.getBitcast(VT, Ops0[0]),
41288 DAG.getBitcast(VT, Ops1[0]), NewBlendMask);
41289 return DAG.getVectorShuffle(VT, DL, NewBlend, DAG.getUNDEF(VT),
41290 NewPermuteMask);
41293 // TODO - move this to TLI like isBinOp?
41294 static bool isUnaryOp(unsigned Opcode) {
41295 switch (Opcode) {
41296 case ISD::CTLZ:
41297 case ISD::CTTZ:
41298 case ISD::CTPOP:
41299 return true;
41301 return false;
41304 // Canonicalize SHUFFLE(UNARYOP(X)) -> UNARYOP(SHUFFLE(X)).
41305 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
41306 static SDValue canonicalizeShuffleWithOp(SDValue N, SelectionDAG &DAG,
41307 const SDLoc &DL) {
41308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41309 EVT ShuffleVT = N.getValueType();
41310 unsigned Opc = N.getOpcode();
41312 auto IsMergeableWithShuffle = [Opc, &DAG](SDValue Op, bool FoldShuf = true,
41313 bool FoldLoad = false) {
41314 // AllZeros/AllOnes constants are freely shuffled and will peek through
41315 // bitcasts. Other constant build vectors do not peek through bitcasts. Only
41316 // merge with target shuffles if it has one use so shuffle combining is
41317 // likely to kick in. Shuffles of splats are expected to be removed.
41318 return ISD::isBuildVectorAllOnes(Op.getNode()) ||
41319 ISD::isBuildVectorAllZeros(Op.getNode()) ||
41320 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
41321 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
41322 getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op)) ||
41323 (Op.getOpcode() == Opc && Op->hasOneUse()) ||
41324 (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op->hasOneUse()) ||
41325 (FoldShuf && isTargetShuffle(Op.getOpcode()) && Op->hasOneUse()) ||
41326 (FoldLoad && isShuffleFoldableLoad(Op)) ||
41327 DAG.isSplatValue(Op, /*AllowUndefs*/ false);
41329 auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
41330 // Ensure we only shuffle whole vector src elements, unless its a logical
41331 // binops where we can more aggressively move shuffles from dst to src.
41332 return isLogicOp(BinOp) ||
41333 (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
41336 switch (Opc) {
41337 // Unary and Unary+Permute Shuffles.
41338 case X86ISD::PSHUFB: {
41339 // Don't merge PSHUFB if it contains zero'd elements.
41340 SmallVector<int> Mask;
41341 SmallVector<SDValue> Ops;
41342 if (!getTargetShuffleMask(N, false, Ops, Mask))
41343 break;
41344 [[fallthrough]];
41346 case X86ISD::VBROADCAST:
41347 case X86ISD::MOVDDUP:
41348 case X86ISD::PSHUFD:
41349 case X86ISD::PSHUFHW:
41350 case X86ISD::PSHUFLW:
41351 case X86ISD::VPERMI:
41352 case X86ISD::VPERMILPI: {
41353 if (N.getOperand(0).getValueType() == ShuffleVT &&
41354 N->isOnlyUserOf(N.getOperand(0).getNode())) {
41355 SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
41356 unsigned SrcOpcode = N0.getOpcode();
41357 if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
41358 SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
41359 SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
41360 if (IsMergeableWithShuffle(Op00, Opc != X86ISD::VPERMI,
41361 Opc != X86ISD::PSHUFB) ||
41362 IsMergeableWithShuffle(Op01, Opc != X86ISD::VPERMI,
41363 Opc != X86ISD::PSHUFB)) {
41364 SDValue LHS, RHS;
41365 Op00 = DAG.getBitcast(ShuffleVT, Op00);
41366 Op01 = DAG.getBitcast(ShuffleVT, Op01);
41367 if (N.getNumOperands() == 2) {
41368 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
41369 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
41370 } else {
41371 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
41372 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
41374 EVT OpVT = N0.getValueType();
41375 return DAG.getBitcast(ShuffleVT,
41376 DAG.getNode(SrcOpcode, DL, OpVT,
41377 DAG.getBitcast(OpVT, LHS),
41378 DAG.getBitcast(OpVT, RHS)));
41382 break;
41384 // Binary and Binary+Permute Shuffles.
41385 case X86ISD::INSERTPS: {
41386 // Don't merge INSERTPS if it contains zero'd elements.
41387 unsigned InsertPSMask = N.getConstantOperandVal(2);
41388 unsigned ZeroMask = InsertPSMask & 0xF;
41389 if (ZeroMask != 0)
41390 break;
41391 [[fallthrough]];
41393 case X86ISD::MOVSD:
41394 case X86ISD::MOVSS:
41395 case X86ISD::BLENDI:
41396 case X86ISD::SHUFP:
41397 case X86ISD::UNPCKH:
41398 case X86ISD::UNPCKL: {
41399 if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
41400 N->isOnlyUserOf(N.getOperand(1).getNode())) {
41401 SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
41402 SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
41403 unsigned SrcOpcode = N0.getOpcode();
41404 if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
41405 N0.getValueType() == N1.getValueType() &&
41406 IsSafeToMoveShuffle(N0, SrcOpcode) &&
41407 IsSafeToMoveShuffle(N1, SrcOpcode)) {
41408 SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
41409 SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
41410 SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
41411 SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
41412 // Ensure the total number of shuffles doesn't increase by folding this
41413 // shuffle through to the source ops.
41414 if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
41415 (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
41416 ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
41417 (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
41418 SDValue LHS, RHS;
41419 Op00 = DAG.getBitcast(ShuffleVT, Op00);
41420 Op10 = DAG.getBitcast(ShuffleVT, Op10);
41421 Op01 = DAG.getBitcast(ShuffleVT, Op01);
41422 Op11 = DAG.getBitcast(ShuffleVT, Op11);
41423 if (N.getNumOperands() == 3) {
41424 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
41425 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
41426 } else {
41427 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
41428 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
41430 EVT OpVT = N0.getValueType();
41431 return DAG.getBitcast(ShuffleVT,
41432 DAG.getNode(SrcOpcode, DL, OpVT,
41433 DAG.getBitcast(OpVT, LHS),
41434 DAG.getBitcast(OpVT, RHS)));
41437 if (isUnaryOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
41438 N0.getValueType() == N1.getValueType() &&
41439 IsSafeToMoveShuffle(N0, SrcOpcode) &&
41440 IsSafeToMoveShuffle(N1, SrcOpcode)) {
41441 SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
41442 SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
41443 SDValue Res;
41444 Op00 = DAG.getBitcast(ShuffleVT, Op00);
41445 Op10 = DAG.getBitcast(ShuffleVT, Op10);
41446 if (N.getNumOperands() == 3) {
41447 Res = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
41448 } else {
41449 Res = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
41451 EVT OpVT = N0.getValueType();
41452 return DAG.getBitcast(
41453 ShuffleVT,
41454 DAG.getNode(SrcOpcode, DL, OpVT, DAG.getBitcast(OpVT, Res)));
41457 break;
41460 return SDValue();
41463 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
41464 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
41465 SelectionDAG &DAG,
41466 const SDLoc &DL) {
41467 assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
41469 MVT VT = V.getSimpleValueType();
41470 SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
41471 SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
41472 unsigned SrcOpc0 = Src0.getOpcode();
41473 unsigned SrcOpc1 = Src1.getOpcode();
41474 EVT SrcVT0 = Src0.getValueType();
41475 EVT SrcVT1 = Src1.getValueType();
41477 if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
41478 return SDValue();
41480 switch (SrcOpc0) {
41481 case X86ISD::MOVDDUP: {
41482 SDValue LHS = Src0.getOperand(0);
41483 SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
41484 SDValue Res =
41485 DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
41486 Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
41487 return DAG.getBitcast(VT, Res);
41489 case X86ISD::VPERMILPI:
41490 // TODO: Handle v4f64 permutes with different low/high lane masks.
41491 if (SrcVT0 == MVT::v4f64) {
41492 uint64_t Mask = Src0.getConstantOperandVal(1);
41493 if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
41494 break;
41496 [[fallthrough]];
41497 case X86ISD::VSHLI:
41498 case X86ISD::VSRLI:
41499 case X86ISD::VSRAI:
41500 case X86ISD::PSHUFD:
41501 if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
41502 SDValue LHS = Src0.getOperand(0);
41503 SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
41504 SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
41505 V.getOperand(2));
41506 Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
41507 return DAG.getBitcast(VT, Res);
41509 break;
41512 return SDValue();
41515 /// Try to combine x86 target specific shuffles.
41516 static SDValue combineTargetShuffle(SDValue N, const SDLoc &DL,
41517 SelectionDAG &DAG,
41518 TargetLowering::DAGCombinerInfo &DCI,
41519 const X86Subtarget &Subtarget) {
41520 MVT VT = N.getSimpleValueType();
41521 SmallVector<int, 4> Mask;
41522 unsigned Opcode = N.getOpcode();
41523 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41525 if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
41526 return R;
41528 // Handle specific target shuffles.
41529 switch (Opcode) {
41530 case X86ISD::MOVDDUP: {
41531 SDValue Src = N.getOperand(0);
41532 // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
41533 if (VT == MVT::v2f64 && Src.hasOneUse() &&
41534 ISD::isNormalLoad(Src.getNode())) {
41535 LoadSDNode *LN = cast<LoadSDNode>(Src);
41536 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
41537 SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
41538 DCI.CombineTo(N.getNode(), Movddup);
41539 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
41540 DCI.recursivelyDeleteUnusedNodes(LN);
41541 return N; // Return N so it doesn't get rechecked!
41545 return SDValue();
41547 case X86ISD::VBROADCAST: {
41548 SDValue Src = N.getOperand(0);
41549 SDValue BC = peekThroughBitcasts(Src);
41550 EVT SrcVT = Src.getValueType();
41551 EVT BCVT = BC.getValueType();
41553 // If broadcasting from another shuffle, attempt to simplify it.
41554 // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
41555 if (isTargetShuffle(BC.getOpcode()) &&
41556 VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
41557 unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
41558 SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
41559 SM_SentinelUndef);
41560 for (unsigned i = 0; i != Scale; ++i)
41561 DemandedMask[i] = i;
41562 if (SDValue Res = combineX86ShufflesRecursively(
41563 {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
41564 X86::MaxShuffleCombineDepth,
41565 /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
41566 /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
41567 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
41568 DAG.getBitcast(SrcVT, Res));
41571 // broadcast(bitcast(src)) -> bitcast(broadcast(src))
41572 // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
41573 if (Src.getOpcode() == ISD::BITCAST &&
41574 SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
41575 TLI.isTypeLegal(BCVT) &&
41576 FixedVectorType::isValidElementType(
41577 BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
41578 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
41579 VT.getVectorNumElements());
41580 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
41583 // vbroadcast(bitcast(vbroadcast(src))) -> bitcast(vbroadcast(src))
41584 // If we're re-broadcasting a smaller type then broadcast with that type and
41585 // bitcast.
41586 // TODO: Do this for any splat?
41587 if (Src.getOpcode() == ISD::BITCAST &&
41588 (BC.getOpcode() == X86ISD::VBROADCAST ||
41589 BC.getOpcode() == X86ISD::VBROADCAST_LOAD) &&
41590 (VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits()) == 0 &&
41591 (VT.getSizeInBits() % BCVT.getSizeInBits()) == 0) {
41592 MVT NewVT =
41593 MVT::getVectorVT(BCVT.getSimpleVT().getScalarType(),
41594 VT.getSizeInBits() / BCVT.getScalarSizeInBits());
41595 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
41598 // Reduce broadcast source vector to lowest 128-bits.
41599 if (SrcVT.getSizeInBits() > 128)
41600 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
41601 extract128BitVector(Src, 0, DAG, DL));
41603 // broadcast(scalar_to_vector(x)) -> broadcast(x).
41604 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
41605 Src.getValueType().getScalarType() == Src.getOperand(0).getValueType())
41606 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
41608 // broadcast(extract_vector_elt(x, 0)) -> broadcast(x).
41609 if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
41610 isNullConstant(Src.getOperand(1)) &&
41611 Src.getValueType() ==
41612 Src.getOperand(0).getValueType().getScalarType() &&
41613 TLI.isTypeLegal(Src.getOperand(0).getValueType()))
41614 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
41616 // Share broadcast with the longest vector and extract low subvector (free).
41617 // Ensure the same SDValue from the SDNode use is being used.
41618 for (SDNode *User : Src->uses())
41619 if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
41620 Src == User->getOperand(0) &&
41621 User->getValueSizeInBits(0).getFixedValue() >
41622 VT.getFixedSizeInBits()) {
41623 return extractSubVector(SDValue(User, 0), 0, DAG, DL,
41624 VT.getSizeInBits());
41627 // vbroadcast(scalarload X) -> vbroadcast_load X
41628 // For float loads, extract other uses of the scalar from the broadcast.
41629 if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
41630 ISD::isNormalLoad(Src.getNode())) {
41631 LoadSDNode *LN = cast<LoadSDNode>(Src);
41632 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41633 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
41634 SDValue BcastLd =
41635 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
41636 LN->getMemoryVT(), LN->getMemOperand());
41637 // If the load value is used only by N, replace it via CombineTo N.
41638 bool NoReplaceExtract = Src.hasOneUse();
41639 DCI.CombineTo(N.getNode(), BcastLd);
41640 if (NoReplaceExtract) {
41641 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41642 DCI.recursivelyDeleteUnusedNodes(LN);
41643 } else {
41644 SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
41645 DAG.getIntPtrConstant(0, DL));
41646 DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
41648 return N; // Return N so it doesn't get rechecked!
41651 // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
41652 // i16. So shrink it ourselves if we can make a broadcast_load.
41653 if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
41654 Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
41655 assert(Subtarget.hasAVX2() && "Expected AVX2");
41656 SDValue TruncIn = Src.getOperand(0);
41658 // If this is a truncate of a non extending load we can just narrow it to
41659 // use a broadcast_load.
41660 if (ISD::isNormalLoad(TruncIn.getNode())) {
41661 LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
41662 // Unless its volatile or atomic.
41663 if (LN->isSimple()) {
41664 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41665 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
41666 SDValue BcastLd = DAG.getMemIntrinsicNode(
41667 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
41668 LN->getPointerInfo(), LN->getOriginalAlign(),
41669 LN->getMemOperand()->getFlags());
41670 DCI.CombineTo(N.getNode(), BcastLd);
41671 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41672 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
41673 return N; // Return N so it doesn't get rechecked!
41677 // If this is a truncate of an i16 extload, we can directly replace it.
41678 if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
41679 ISD::isEXTLoad(Src.getOperand(0).getNode())) {
41680 LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
41681 if (LN->getMemoryVT().getSizeInBits() == 16) {
41682 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41683 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
41684 SDValue BcastLd =
41685 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
41686 LN->getMemoryVT(), LN->getMemOperand());
41687 DCI.CombineTo(N.getNode(), BcastLd);
41688 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41689 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
41690 return N; // Return N so it doesn't get rechecked!
41694 // If this is a truncate of load that has been shifted right, we can
41695 // offset the pointer and use a narrower load.
41696 if (TruncIn.getOpcode() == ISD::SRL &&
41697 TruncIn.getOperand(0).hasOneUse() &&
41698 isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
41699 ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
41700 LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
41701 unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
41702 // Make sure the shift amount and the load size are divisible by 16.
41703 // Don't do this if the load is volatile or atomic.
41704 if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
41705 LN->isSimple()) {
41706 unsigned Offset = ShiftAmt / 8;
41707 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41708 SDValue Ptr = DAG.getMemBasePlusOffset(
41709 LN->getBasePtr(), TypeSize::getFixed(Offset), DL);
41710 SDValue Ops[] = { LN->getChain(), Ptr };
41711 SDValue BcastLd = DAG.getMemIntrinsicNode(
41712 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
41713 LN->getPointerInfo().getWithOffset(Offset),
41714 LN->getOriginalAlign(),
41715 LN->getMemOperand()->getFlags());
41716 DCI.CombineTo(N.getNode(), BcastLd);
41717 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41718 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
41719 return N; // Return N so it doesn't get rechecked!
41724 // vbroadcast(vzload X) -> vbroadcast_load X
41725 if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
41726 MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
41727 if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
41728 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41729 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
41730 SDValue BcastLd =
41731 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
41732 LN->getMemoryVT(), LN->getMemOperand());
41733 DCI.CombineTo(N.getNode(), BcastLd);
41734 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41735 DCI.recursivelyDeleteUnusedNodes(LN);
41736 return N; // Return N so it doesn't get rechecked!
41740 // vbroadcast(vector load X) -> vbroadcast_load
41741 if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
41742 SrcVT == MVT::v4i32) &&
41743 Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
41744 LoadSDNode *LN = cast<LoadSDNode>(Src);
41745 // Unless the load is volatile or atomic.
41746 if (LN->isSimple()) {
41747 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41748 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
41749 SDValue BcastLd = DAG.getMemIntrinsicNode(
41750 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
41751 LN->getPointerInfo(), LN->getOriginalAlign(),
41752 LN->getMemOperand()->getFlags());
41753 DCI.CombineTo(N.getNode(), BcastLd);
41754 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
41755 DCI.recursivelyDeleteUnusedNodes(LN);
41756 return N; // Return N so it doesn't get rechecked!
41760 return SDValue();
41762 case X86ISD::VZEXT_MOVL: {
41763 SDValue N0 = N.getOperand(0);
41765 // If this a vzmovl of a full vector load, replace it with a vzload, unless
41766 // the load is volatile.
41767 if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
41768 auto *LN = cast<LoadSDNode>(N0);
41769 if (SDValue VZLoad =
41770 narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
41771 DCI.CombineTo(N.getNode(), VZLoad);
41772 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
41773 DCI.recursivelyDeleteUnusedNodes(LN);
41774 return N;
41778 // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
41779 // and can just use a VZEXT_LOAD.
41780 // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
41781 if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
41782 auto *LN = cast<MemSDNode>(N0);
41783 if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
41784 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
41785 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
41786 SDValue VZLoad =
41787 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
41788 LN->getMemoryVT(), LN->getMemOperand());
41789 DCI.CombineTo(N.getNode(), VZLoad);
41790 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
41791 DCI.recursivelyDeleteUnusedNodes(LN);
41792 return N;
41796 // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
41797 // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
41798 // if the upper bits of the i64 are zero.
41799 if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
41800 N0.getOperand(0).hasOneUse() &&
41801 N0.getOperand(0).getValueType() == MVT::i64) {
41802 SDValue In = N0.getOperand(0);
41803 APInt Mask = APInt::getHighBitsSet(64, 32);
41804 if (DAG.MaskedValueIsZero(In, Mask)) {
41805 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
41806 MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
41807 SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
41808 SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
41809 return DAG.getBitcast(VT, Movl);
41813 // Load a scalar integer constant directly to XMM instead of transferring an
41814 // immediate value from GPR.
41815 // vzext_movl (scalar_to_vector C) --> load [C,0...]
41816 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
41817 if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
41818 // Create a vector constant - scalar constant followed by zeros.
41819 EVT ScalarVT = N0.getOperand(0).getValueType();
41820 Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
41821 unsigned NumElts = VT.getVectorNumElements();
41822 Constant *Zero = ConstantInt::getNullValue(ScalarTy);
41823 SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
41824 ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
41826 // Load the vector constant from constant pool.
41827 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
41828 SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
41829 MachinePointerInfo MPI =
41830 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
41831 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
41832 return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
41833 MachineMemOperand::MOLoad);
41837 // Pull subvector inserts into undef through VZEXT_MOVL by making it an
41838 // insert into a zero vector. This helps get VZEXT_MOVL closer to
41839 // scalar_to_vectors where 256/512 are canonicalized to an insert and a
41840 // 128-bit scalar_to_vector. This reduces the number of isel patterns.
41841 if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
41842 SDValue V = peekThroughOneUseBitcasts(N0);
41844 if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
41845 isNullConstant(V.getOperand(2))) {
41846 SDValue In = V.getOperand(1);
41847 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
41848 In.getValueSizeInBits() /
41849 VT.getScalarSizeInBits());
41850 In = DAG.getBitcast(SubVT, In);
41851 SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
41852 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
41853 getZeroVector(VT, Subtarget, DAG, DL), Movl,
41854 V.getOperand(2));
41858 return SDValue();
41860 case X86ISD::BLENDI: {
41861 SDValue N0 = N.getOperand(0);
41862 SDValue N1 = N.getOperand(1);
41863 unsigned EltBits = VT.getScalarSizeInBits();
41865 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
41866 // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
41867 // TODO: Handle MVT::v16i16 repeated blend mask.
41868 if (N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
41869 MVT SrcVT = N0.getOperand(0).getSimpleValueType();
41870 unsigned SrcBits = SrcVT.getScalarSizeInBits();
41871 if ((EltBits % SrcBits) == 0 && SrcBits >= 32) {
41872 unsigned Size = VT.getVectorNumElements();
41873 unsigned NewSize = SrcVT.getVectorNumElements();
41874 APInt BlendMask = N.getConstantOperandAPInt(2).zextOrTrunc(Size);
41875 APInt NewBlendMask = APIntOps::ScaleBitMask(BlendMask, NewSize);
41876 return DAG.getBitcast(
41877 VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
41878 N1.getOperand(0),
41879 DAG.getTargetConstant(NewBlendMask.getZExtValue(),
41880 DL, MVT::i8)));
41883 // Share PSHUFB masks:
41884 // blend(pshufb(x,m1),pshufb(y,m2))
41885 // --> m3 = blend(m1,m2)
41886 // blend(pshufb(x,m3),pshufb(y,m3))
41887 if (N0.hasOneUse() && N1.hasOneUse()) {
41888 SmallVector<int> Mask, ByteMask;
41889 SmallVector<SDValue> Ops;
41890 SDValue LHS = peekThroughOneUseBitcasts(N0);
41891 SDValue RHS = peekThroughOneUseBitcasts(N1);
41892 if (LHS.getOpcode() == X86ISD::PSHUFB &&
41893 RHS.getOpcode() == X86ISD::PSHUFB &&
41894 LHS.getOperand(1) != RHS.getOperand(1) &&
41895 LHS.getOperand(1).hasOneUse() && RHS.getOperand(1).hasOneUse() &&
41896 getTargetShuffleMask(N, /*AllowSentinelZero=*/false, Ops, Mask)) {
41897 assert(Ops.size() == 2 && LHS == peekThroughOneUseBitcasts(Ops[0]) &&
41898 RHS == peekThroughOneUseBitcasts(Ops[1]) &&
41899 "BLENDI decode mismatch");
41900 MVT ShufVT = LHS.getSimpleValueType();
41901 SDValue MaskLHS = LHS.getOperand(1);
41902 SDValue MaskRHS = RHS.getOperand(1);
41903 llvm::narrowShuffleMaskElts(EltBits / 8, Mask, ByteMask);
41904 if (SDValue NewMask = combineX86ShufflesConstants(
41905 ShufVT, {MaskLHS, MaskRHS}, ByteMask,
41906 /*HasVariableMask=*/true, DAG, DL, Subtarget)) {
41907 SDValue NewLHS = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT,
41908 LHS.getOperand(0), NewMask);
41909 SDValue NewRHS = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT,
41910 RHS.getOperand(0), NewMask);
41911 return DAG.getNode(X86ISD::BLENDI, DL, VT,
41912 DAG.getBitcast(VT, NewLHS),
41913 DAG.getBitcast(VT, NewRHS), N.getOperand(2));
41918 return SDValue();
41920 case X86ISD::SHUFP: {
41921 // Fold shufps(shuffle(x),shuffle(y)) -> shufps(x,y).
41922 // This is a more relaxed shuffle combiner that can ignore oneuse limits.
41923 // TODO: Support types other than v4f32.
41924 if (VT == MVT::v4f32) {
41925 bool Updated = false;
41926 SmallVector<int> Mask;
41927 SmallVector<SDValue> Ops;
41928 if (getTargetShuffleMask(N, false, Ops, Mask) && Ops.size() == 2) {
41929 for (int i = 0; i != 2; ++i) {
41930 SmallVector<SDValue> SubOps;
41931 SmallVector<int> SubMask, SubScaledMask;
41932 SDValue Sub = peekThroughBitcasts(Ops[i]);
41933 // TODO: Scaling might be easier if we specify the demanded elts.
41934 if (getTargetShuffleInputs(Sub, SubOps, SubMask, DAG, 0, false) &&
41935 scaleShuffleElements(SubMask, 4, SubScaledMask) &&
41936 SubOps.size() == 1 && isUndefOrInRange(SubScaledMask, 0, 4)) {
41937 int Ofs = i * 2;
41938 Mask[Ofs + 0] = SubScaledMask[Mask[Ofs + 0] % 4] + (i * 4);
41939 Mask[Ofs + 1] = SubScaledMask[Mask[Ofs + 1] % 4] + (i * 4);
41940 Ops[i] = DAG.getBitcast(VT, SubOps[0]);
41941 Updated = true;
41945 if (Updated) {
41946 for (int &M : Mask)
41947 M %= 4;
41948 Ops.push_back(getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
41949 return DAG.getNode(X86ISD::SHUFP, DL, VT, Ops);
41952 return SDValue();
41954 case X86ISD::VPERMI: {
41955 // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
41956 // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
41957 SDValue N0 = N.getOperand(0);
41958 SDValue N1 = N.getOperand(1);
41959 unsigned EltSizeInBits = VT.getScalarSizeInBits();
41960 if (N0.getOpcode() == ISD::BITCAST &&
41961 N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
41962 SDValue Src = N0.getOperand(0);
41963 EVT SrcVT = Src.getValueType();
41964 SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
41965 return DAG.getBitcast(VT, Res);
41967 return SDValue();
41969 case X86ISD::SHUF128: {
41970 // If we're permuting the upper 256-bits subvectors of a concatenation, then
41971 // see if we can peek through and access the subvector directly.
41972 if (VT.is512BitVector()) {
41973 // 512-bit mask uses 4 x i2 indices - if the msb is always set then only the
41974 // upper subvector is used.
41975 SDValue LHS = N->getOperand(0);
41976 SDValue RHS = N->getOperand(1);
41977 uint64_t Mask = N->getConstantOperandVal(2);
41978 SmallVector<SDValue> LHSOps, RHSOps;
41979 SDValue NewLHS, NewRHS;
41980 if ((Mask & 0x0A) == 0x0A &&
41981 collectConcatOps(LHS.getNode(), LHSOps, DAG) && LHSOps.size() == 2) {
41982 NewLHS = widenSubVector(LHSOps[1], false, Subtarget, DAG, DL, 512);
41983 Mask &= ~0x0A;
41985 if ((Mask & 0xA0) == 0xA0 &&
41986 collectConcatOps(RHS.getNode(), RHSOps, DAG) && RHSOps.size() == 2) {
41987 NewRHS = widenSubVector(RHSOps[1], false, Subtarget, DAG, DL, 512);
41988 Mask &= ~0xA0;
41990 if (NewLHS || NewRHS)
41991 return DAG.getNode(X86ISD::SHUF128, DL, VT, NewLHS ? NewLHS : LHS,
41992 NewRHS ? NewRHS : RHS,
41993 DAG.getTargetConstant(Mask, DL, MVT::i8));
41995 return SDValue();
41997 case X86ISD::VPERM2X128: {
41998 // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
41999 SDValue LHS = N->getOperand(0);
42000 SDValue RHS = N->getOperand(1);
42001 if (LHS.getOpcode() == ISD::BITCAST &&
42002 (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
42003 EVT SrcVT = LHS.getOperand(0).getValueType();
42004 if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
42005 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
42006 DAG.getBitcast(SrcVT, LHS),
42007 DAG.getBitcast(SrcVT, RHS),
42008 N->getOperand(2)));
42012 // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
42013 if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
42014 return Res;
42016 // Fold vperm2x128 subvector shuffle with an inner concat pattern.
42017 // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
42018 auto FindSubVector128 = [&](unsigned Idx) {
42019 if (Idx > 3)
42020 return SDValue();
42021 SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
42022 SmallVector<SDValue> SubOps;
42023 if (collectConcatOps(Src.getNode(), SubOps, DAG) && SubOps.size() == 2)
42024 return SubOps[Idx & 1];
42025 unsigned NumElts = Src.getValueType().getVectorNumElements();
42026 if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
42027 Src.getOperand(1).getValueSizeInBits() == 128 &&
42028 Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
42029 return Src.getOperand(1);
42031 return SDValue();
42033 unsigned Imm = N.getConstantOperandVal(2);
42034 if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
42035 if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
42036 MVT SubVT = VT.getHalfNumVectorElementsVT();
42037 SubLo = DAG.getBitcast(SubVT, SubLo);
42038 SubHi = DAG.getBitcast(SubVT, SubHi);
42039 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
42042 return SDValue();
42044 case X86ISD::PSHUFD:
42045 case X86ISD::PSHUFLW:
42046 case X86ISD::PSHUFHW: {
42047 SDValue N0 = N.getOperand(0);
42048 SDValue N1 = N.getOperand(1);
42049 if (N0->hasOneUse()) {
42050 SDValue V = peekThroughOneUseBitcasts(N0);
42051 switch (V.getOpcode()) {
42052 case X86ISD::VSHL:
42053 case X86ISD::VSRL:
42054 case X86ISD::VSRA:
42055 case X86ISD::VSHLI:
42056 case X86ISD::VSRLI:
42057 case X86ISD::VSRAI:
42058 case X86ISD::VROTLI:
42059 case X86ISD::VROTRI: {
42060 MVT InnerVT = V.getSimpleValueType();
42061 if (InnerVT.getScalarSizeInBits() <= VT.getScalarSizeInBits()) {
42062 SDValue Res = DAG.getNode(Opcode, DL, VT,
42063 DAG.getBitcast(VT, V.getOperand(0)), N1);
42064 Res = DAG.getBitcast(InnerVT, Res);
42065 Res = DAG.getNode(V.getOpcode(), DL, InnerVT, Res, V.getOperand(1));
42066 return DAG.getBitcast(VT, Res);
42068 break;
42073 Mask = getPSHUFShuffleMask(N);
42074 assert(Mask.size() == 4);
42075 break;
42077 case X86ISD::MOVSD:
42078 case X86ISD::MOVSH:
42079 case X86ISD::MOVSS: {
42080 SDValue N0 = N.getOperand(0);
42081 SDValue N1 = N.getOperand(1);
42083 // Canonicalize scalar FPOps:
42084 // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
42085 // If commutable, allow OP(N1[0], N0[0]).
42086 unsigned Opcode1 = N1.getOpcode();
42087 if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
42088 Opcode1 == ISD::FDIV) {
42089 SDValue N10 = N1.getOperand(0);
42090 SDValue N11 = N1.getOperand(1);
42091 if (N10 == N0 ||
42092 (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
42093 if (N10 != N0)
42094 std::swap(N10, N11);
42095 MVT SVT = VT.getVectorElementType();
42096 SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
42097 N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
42098 N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
42099 SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
42100 SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
42101 return DAG.getNode(Opcode, DL, VT, N0, SclVec);
42105 return SDValue();
42107 case X86ISD::INSERTPS: {
42108 assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
42109 SDValue Op0 = N.getOperand(0);
42110 SDValue Op1 = N.getOperand(1);
42111 unsigned InsertPSMask = N.getConstantOperandVal(2);
42112 unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
42113 unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
42114 unsigned ZeroMask = InsertPSMask & 0xF;
42116 // If we zero out all elements from Op0 then we don't need to reference it.
42117 if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
42118 return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
42119 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42121 // If we zero out the element from Op1 then we don't need to reference it.
42122 if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
42123 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
42124 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42126 // Attempt to merge insertps Op1 with an inner target shuffle node.
42127 SmallVector<int, 8> TargetMask1;
42128 SmallVector<SDValue, 2> Ops1;
42129 APInt KnownUndef1, KnownZero1;
42130 if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
42131 KnownZero1)) {
42132 if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
42133 // Zero/UNDEF insertion - zero out element and remove dependency.
42134 InsertPSMask |= (1u << DstIdx);
42135 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
42136 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42138 // Update insertps mask srcidx and reference the source input directly.
42139 int M = TargetMask1[SrcIdx];
42140 assert(0 <= M && M < 8 && "Shuffle index out of range");
42141 InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
42142 Op1 = Ops1[M < 4 ? 0 : 1];
42143 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
42144 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42147 // Attempt to merge insertps Op0 with an inner target shuffle node.
42148 SmallVector<int, 8> TargetMask0;
42149 SmallVector<SDValue, 2> Ops0;
42150 APInt KnownUndef0, KnownZero0;
42151 if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
42152 KnownZero0)) {
42153 bool Updated = false;
42154 bool UseInput00 = false;
42155 bool UseInput01 = false;
42156 for (int i = 0; i != 4; ++i) {
42157 if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
42158 // No change if element is already zero or the inserted element.
42159 continue;
42162 if (KnownUndef0[i] || KnownZero0[i]) {
42163 // If the target mask is undef/zero then we must zero the element.
42164 InsertPSMask |= (1u << i);
42165 Updated = true;
42166 continue;
42169 // The input vector element must be inline.
42170 int M = TargetMask0[i];
42171 if (M != i && M != (i + 4))
42172 return SDValue();
42174 // Determine which inputs of the target shuffle we're using.
42175 UseInput00 |= (0 <= M && M < 4);
42176 UseInput01 |= (4 <= M);
42179 // If we're not using both inputs of the target shuffle then use the
42180 // referenced input directly.
42181 if (UseInput00 && !UseInput01) {
42182 Updated = true;
42183 Op0 = Ops0[0];
42184 } else if (!UseInput00 && UseInput01) {
42185 Updated = true;
42186 Op0 = Ops0[1];
42189 if (Updated)
42190 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
42191 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
42194 // If we're inserting an element from a vbroadcast load, fold the
42195 // load into the X86insertps instruction. We need to convert the scalar
42196 // load to a vector and clear the source lane of the INSERTPS control.
42197 if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
42198 auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
42199 if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
42200 SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
42201 MemIntr->getBasePtr(),
42202 MemIntr->getMemOperand());
42203 SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
42204 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
42205 Load),
42206 DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
42207 DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
42208 return Insert;
42212 return SDValue();
42214 case X86ISD::VPERMV3: {
42215 // Combine VPERMV3 to widened VPERMV if the two source operands are split
42216 // from the same vector.
42217 SDValue V1 = peekThroughBitcasts(N.getOperand(0));
42218 SDValue V2 = peekThroughBitcasts(N.getOperand(2));
42219 MVT SVT = V1.getSimpleValueType();
42220 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42221 V1.getConstantOperandVal(1) == 0 &&
42222 V2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42223 V2.getConstantOperandVal(1) == SVT.getVectorNumElements() &&
42224 V1.getOperand(0) == V2.getOperand(0)) {
42225 EVT NVT = V1.getOperand(0).getValueType();
42226 if (NVT.is256BitVector() ||
42227 (NVT.is512BitVector() && Subtarget.hasEVEX512())) {
42228 MVT WideVT = MVT::getVectorVT(
42229 VT.getScalarType(), NVT.getSizeInBits() / VT.getScalarSizeInBits());
42230 SDValue Mask = widenSubVector(N.getOperand(1), false, Subtarget, DAG,
42231 DL, WideVT.getSizeInBits());
42232 SDValue Perm = DAG.getNode(X86ISD::VPERMV, DL, WideVT, Mask,
42233 DAG.getBitcast(WideVT, V1.getOperand(0)));
42234 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Perm,
42235 DAG.getIntPtrConstant(0, DL));
42238 return SDValue();
42240 default:
42241 return SDValue();
42244 // Nuke no-op shuffles that show up after combining.
42245 if (isNoopShuffleMask(Mask))
42246 return N.getOperand(0);
42248 // Look for simplifications involving one or two shuffle instructions.
42249 SDValue V = N.getOperand(0);
42250 switch (N.getOpcode()) {
42251 default:
42252 break;
42253 case X86ISD::PSHUFLW:
42254 case X86ISD::PSHUFHW:
42255 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
42257 // See if this reduces to a PSHUFD which is no more expensive and can
42258 // combine with more operations. Note that it has to at least flip the
42259 // dwords as otherwise it would have been removed as a no-op.
42260 if (ArrayRef<int>(Mask).equals({2, 3, 0, 1})) {
42261 int DMask[] = {0, 1, 2, 3};
42262 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
42263 DMask[DOffset + 0] = DOffset + 1;
42264 DMask[DOffset + 1] = DOffset + 0;
42265 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
42266 V = DAG.getBitcast(DVT, V);
42267 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
42268 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
42269 return DAG.getBitcast(VT, V);
42272 // Look for shuffle patterns which can be implemented as a single unpack.
42273 // FIXME: This doesn't handle the location of the PSHUFD generically, and
42274 // only works when we have a PSHUFD followed by two half-shuffles.
42275 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
42276 (V.getOpcode() == X86ISD::PSHUFLW ||
42277 V.getOpcode() == X86ISD::PSHUFHW) &&
42278 V.getOpcode() != N.getOpcode() &&
42279 V.hasOneUse() && V.getOperand(0).hasOneUse()) {
42280 SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
42281 if (D.getOpcode() == X86ISD::PSHUFD) {
42282 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
42283 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
42284 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
42285 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
42286 int WordMask[8];
42287 for (int i = 0; i < 4; ++i) {
42288 WordMask[i + NOffset] = Mask[i] + NOffset;
42289 WordMask[i + VOffset] = VMask[i] + VOffset;
42291 // Map the word mask through the DWord mask.
42292 int MappedMask[8];
42293 for (int i = 0; i < 8; ++i)
42294 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
42295 if (ArrayRef<int>(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
42296 ArrayRef<int>(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
42297 // We can replace all three shuffles with an unpack.
42298 V = DAG.getBitcast(VT, D.getOperand(0));
42299 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
42300 : X86ISD::UNPCKH,
42301 DL, VT, V, V);
42306 break;
42308 case X86ISD::PSHUFD:
42309 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DL, DAG))
42310 return NewN;
42312 break;
42315 return SDValue();
42318 /// Checks if the shuffle mask takes subsequent elements
42319 /// alternately from two vectors.
42320 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
42321 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
42323 int ParitySrc[2] = {-1, -1};
42324 unsigned Size = Mask.size();
42325 for (unsigned i = 0; i != Size; ++i) {
42326 int M = Mask[i];
42327 if (M < 0)
42328 continue;
42330 // Make sure we are using the matching element from the input.
42331 if ((M % Size) != i)
42332 return false;
42334 // Make sure we use the same input for all elements of the same parity.
42335 int Src = M / Size;
42336 if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
42337 return false;
42338 ParitySrc[i % 2] = Src;
42341 // Make sure each input is used.
42342 if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
42343 return false;
42345 Op0Even = ParitySrc[0] == 0;
42346 return true;
42349 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
42350 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
42351 /// are written to the parameters \p Opnd0 and \p Opnd1.
42353 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
42354 /// so it is easier to generically match. We also insert dummy vector shuffle
42355 /// nodes for the operands which explicitly discard the lanes which are unused
42356 /// by this operation to try to flow through the rest of the combiner
42357 /// the fact that they're unused.
42358 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
42359 SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
42360 bool &IsSubAdd) {
42362 EVT VT = N->getValueType(0);
42363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42364 if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
42365 !VT.getSimpleVT().isFloatingPoint())
42366 return false;
42368 // We only handle target-independent shuffles.
42369 // FIXME: It would be easy and harmless to use the target shuffle mask
42370 // extraction tool to support more.
42371 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
42372 return false;
42374 SDValue V1 = N->getOperand(0);
42375 SDValue V2 = N->getOperand(1);
42377 // Make sure we have an FADD and an FSUB.
42378 if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
42379 (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
42380 V1.getOpcode() == V2.getOpcode())
42381 return false;
42383 // If there are other uses of these operations we can't fold them.
42384 if (!V1->hasOneUse() || !V2->hasOneUse())
42385 return false;
42387 // Ensure that both operations have the same operands. Note that we can
42388 // commute the FADD operands.
42389 SDValue LHS, RHS;
42390 if (V1.getOpcode() == ISD::FSUB) {
42391 LHS = V1->getOperand(0); RHS = V1->getOperand(1);
42392 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
42393 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
42394 return false;
42395 } else {
42396 assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
42397 LHS = V2->getOperand(0); RHS = V2->getOperand(1);
42398 if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
42399 (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
42400 return false;
42403 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
42404 bool Op0Even;
42405 if (!isAddSubOrSubAddMask(Mask, Op0Even))
42406 return false;
42408 // It's a subadd if the vector in the even parity is an FADD.
42409 IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
42410 : V2->getOpcode() == ISD::FADD;
42412 Opnd0 = LHS;
42413 Opnd1 = RHS;
42414 return true;
42417 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
42418 static SDValue combineShuffleToFMAddSub(SDNode *N, const SDLoc &DL,
42419 const X86Subtarget &Subtarget,
42420 SelectionDAG &DAG) {
42421 // We only handle target-independent shuffles.
42422 // FIXME: It would be easy and harmless to use the target shuffle mask
42423 // extraction tool to support more.
42424 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
42425 return SDValue();
42427 MVT VT = N->getSimpleValueType(0);
42428 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42429 if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
42430 return SDValue();
42432 // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
42433 SDValue Op0 = N->getOperand(0);
42434 SDValue Op1 = N->getOperand(1);
42435 SDValue FMAdd = Op0, FMSub = Op1;
42436 if (FMSub.getOpcode() != X86ISD::FMSUB)
42437 std::swap(FMAdd, FMSub);
42439 if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
42440 FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
42441 FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
42442 FMAdd.getOperand(2) != FMSub.getOperand(2))
42443 return SDValue();
42445 // Check for correct shuffle mask.
42446 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
42447 bool Op0Even;
42448 if (!isAddSubOrSubAddMask(Mask, Op0Even))
42449 return SDValue();
42451 // FMAddSub takes zeroth operand from FMSub node.
42452 bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
42453 unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
42454 return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
42455 FMAdd.getOperand(2));
42458 /// Try to combine a shuffle into a target-specific add-sub or
42459 /// mul-add-sub node.
42460 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N, const SDLoc &DL,
42461 const X86Subtarget &Subtarget,
42462 SelectionDAG &DAG) {
42463 if (SDValue V = combineShuffleToFMAddSub(N, DL, Subtarget, DAG))
42464 return V;
42466 SDValue Opnd0, Opnd1;
42467 bool IsSubAdd;
42468 if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
42469 return SDValue();
42471 MVT VT = N->getSimpleValueType(0);
42473 // Try to generate X86ISD::FMADDSUB node here.
42474 SDValue Opnd2;
42475 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
42476 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
42477 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
42480 if (IsSubAdd)
42481 return SDValue();
42483 // Do not generate X86ISD::ADDSUB node for 512-bit types even though
42484 // the ADDSUB idiom has been successfully recognized. There are no known
42485 // X86 targets with 512-bit ADDSUB instructions!
42486 if (VT.is512BitVector())
42487 return SDValue();
42489 // Do not generate X86ISD::ADDSUB node for FP16's vector types even though
42490 // the ADDSUB idiom has been successfully recognized. There are no known
42491 // X86 targets with FP16 ADDSUB instructions!
42492 if (VT.getVectorElementType() == MVT::f16)
42493 return SDValue();
42495 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
42498 // We are looking for a shuffle where both sources are concatenated with undef
42499 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
42500 // if we can express this as a single-source shuffle, that's preferable.
42501 static SDValue combineShuffleOfConcatUndef(SDNode *N, const SDLoc &DL,
42502 SelectionDAG &DAG,
42503 const X86Subtarget &Subtarget) {
42504 if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
42505 return SDValue();
42507 EVT VT = N->getValueType(0);
42509 // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
42510 if (!VT.is128BitVector() && !VT.is256BitVector())
42511 return SDValue();
42513 if (VT.getVectorElementType() != MVT::i32 &&
42514 VT.getVectorElementType() != MVT::i64 &&
42515 VT.getVectorElementType() != MVT::f32 &&
42516 VT.getVectorElementType() != MVT::f64)
42517 return SDValue();
42519 SDValue N0 = N->getOperand(0);
42520 SDValue N1 = N->getOperand(1);
42522 // Check that both sources are concats with undef.
42523 if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
42524 N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
42525 N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
42526 !N1.getOperand(1).isUndef())
42527 return SDValue();
42529 // Construct the new shuffle mask. Elements from the first source retain their
42530 // index, but elements from the second source no longer need to skip an undef.
42531 SmallVector<int, 8> Mask;
42532 int NumElts = VT.getVectorNumElements();
42534 auto *SVOp = cast<ShuffleVectorSDNode>(N);
42535 for (int Elt : SVOp->getMask())
42536 Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
42538 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
42539 N1.getOperand(0));
42540 return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
42543 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
42544 /// low half of each source vector and does not set any high half elements in
42545 /// the destination vector, narrow the shuffle to half its original size.
42546 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
42547 EVT VT = Shuf->getValueType(0);
42548 if (!DAG.getTargetLoweringInfo().isTypeLegal(Shuf->getValueType(0)))
42549 return SDValue();
42550 if (!VT.is256BitVector() && !VT.is512BitVector())
42551 return SDValue();
42553 // See if we can ignore all of the high elements of the shuffle.
42554 ArrayRef<int> Mask = Shuf->getMask();
42555 if (!isUndefUpperHalf(Mask))
42556 return SDValue();
42558 // Check if the shuffle mask accesses only the low half of each input vector
42559 // (half-index output is 0 or 2).
42560 int HalfIdx1, HalfIdx2;
42561 SmallVector<int, 8> HalfMask(Mask.size() / 2);
42562 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
42563 (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
42564 return SDValue();
42566 // Create a half-width shuffle to replace the unnecessarily wide shuffle.
42567 // The trick is knowing that all of the insert/extract are actually free
42568 // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
42569 // of narrow inputs into a narrow output, and that is always cheaper than
42570 // the wide shuffle that we started with.
42571 return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
42572 Shuf->getOperand(1), HalfMask, HalfIdx1,
42573 HalfIdx2, false, DAG, /*UseConcat*/ true);
42576 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
42577 TargetLowering::DAGCombinerInfo &DCI,
42578 const X86Subtarget &Subtarget) {
42579 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
42580 if (SDValue V = narrowShuffle(Shuf, DAG))
42581 return V;
42583 // If we have legalized the vector types, look for blends of FADD and FSUB
42584 // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
42585 SDLoc dl(N);
42586 EVT VT = N->getValueType(0);
42587 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42588 if (TLI.isTypeLegal(VT) && !isSoftF16(VT, Subtarget))
42589 if (SDValue AddSub =
42590 combineShuffleToAddSubOrFMAddSub(N, dl, Subtarget, DAG))
42591 return AddSub;
42593 // Attempt to combine into a vector load/broadcast.
42594 if (SDValue LD = combineToConsecutiveLoads(
42595 VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
42596 return LD;
42598 // For AVX2, we sometimes want to combine
42599 // (vector_shuffle <mask> (concat_vectors t1, undef)
42600 // (concat_vectors t2, undef))
42601 // Into:
42602 // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
42603 // Since the latter can be efficiently lowered with VPERMD/VPERMQ
42604 if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, dl, DAG, Subtarget))
42605 return ShufConcat;
42607 if (isTargetShuffle(N->getOpcode())) {
42608 SDValue Op(N, 0);
42609 if (SDValue Shuffle = combineTargetShuffle(Op, dl, DAG, DCI, Subtarget))
42610 return Shuffle;
42612 // Try recursively combining arbitrary sequences of x86 shuffle
42613 // instructions into higher-order shuffles. We do this after combining
42614 // specific PSHUF instruction sequences into their minimal form so that we
42615 // can evaluate how many specialized shuffle instructions are involved in
42616 // a particular chain.
42617 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
42618 return Res;
42620 // Simplify source operands based on shuffle mask.
42621 // TODO - merge this into combineX86ShufflesRecursively.
42622 APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
42623 if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, DCI))
42624 return SDValue(N, 0);
42626 // Canonicalize SHUFFLE(UNARYOP(X)) -> UNARYOP(SHUFFLE(X)).
42627 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
42628 // Perform this after other shuffle combines to allow inner shuffles to be
42629 // combined away first.
42630 if (SDValue BinOp = canonicalizeShuffleWithOp(Op, DAG, dl))
42631 return BinOp;
42634 return SDValue();
42637 // Simplify variable target shuffle masks based on the demanded elements.
42638 // TODO: Handle DemandedBits in mask indices as well?
42639 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
42640 SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
42641 TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
42642 // If we're demanding all elements don't bother trying to simplify the mask.
42643 unsigned NumElts = DemandedElts.getBitWidth();
42644 if (DemandedElts.isAllOnes())
42645 return false;
42647 SDValue Mask = Op.getOperand(MaskIndex);
42648 if (!Mask.hasOneUse())
42649 return false;
42651 // Attempt to generically simplify the variable shuffle mask.
42652 APInt MaskUndef, MaskZero;
42653 if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
42654 Depth + 1))
42655 return true;
42657 // Attempt to extract+simplify a (constant pool load) shuffle mask.
42658 // TODO: Support other types from getTargetShuffleMaskIndices?
42659 SDValue BC = peekThroughOneUseBitcasts(Mask);
42660 EVT BCVT = BC.getValueType();
42661 auto *Load = dyn_cast<LoadSDNode>(BC);
42662 if (!Load || !Load->getBasePtr().hasOneUse())
42663 return false;
42665 const Constant *C = getTargetConstantFromNode(Load);
42666 if (!C)
42667 return false;
42669 Type *CTy = C->getType();
42670 if (!CTy->isVectorTy() ||
42671 CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
42672 return false;
42674 // Handle scaling for i64 elements on 32-bit targets.
42675 unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
42676 if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
42677 return false;
42678 unsigned Scale = NumCstElts / NumElts;
42680 // Simplify mask if we have an undemanded element that is not undef.
42681 bool Simplified = false;
42682 SmallVector<Constant *, 32> ConstVecOps;
42683 for (unsigned i = 0; i != NumCstElts; ++i) {
42684 Constant *Elt = C->getAggregateElement(i);
42685 if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
42686 ConstVecOps.push_back(UndefValue::get(Elt->getType()));
42687 Simplified = true;
42688 continue;
42690 ConstVecOps.push_back(Elt);
42692 if (!Simplified)
42693 return false;
42695 // Generate new constant pool entry + legalize immediately for the load.
42696 SDLoc DL(Op);
42697 SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
42698 SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
42699 SDValue NewMask = TLO.DAG.getLoad(
42700 BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
42701 MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
42702 Load->getAlign());
42703 return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
42706 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
42707 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
42708 TargetLoweringOpt &TLO, unsigned Depth) const {
42709 int NumElts = DemandedElts.getBitWidth();
42710 unsigned Opc = Op.getOpcode();
42711 EVT VT = Op.getValueType();
42713 // Handle special case opcodes.
42714 switch (Opc) {
42715 case X86ISD::PMULDQ:
42716 case X86ISD::PMULUDQ: {
42717 APInt LHSUndef, LHSZero;
42718 APInt RHSUndef, RHSZero;
42719 SDValue LHS = Op.getOperand(0);
42720 SDValue RHS = Op.getOperand(1);
42721 if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
42722 Depth + 1))
42723 return true;
42724 if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
42725 Depth + 1))
42726 return true;
42727 // Multiply by zero.
42728 KnownZero = LHSZero | RHSZero;
42729 break;
42731 case X86ISD::VPMADDUBSW:
42732 case X86ISD::VPMADDWD: {
42733 APInt LHSUndef, LHSZero;
42734 APInt RHSUndef, RHSZero;
42735 SDValue LHS = Op.getOperand(0);
42736 SDValue RHS = Op.getOperand(1);
42737 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, 2 * NumElts);
42739 if (SimplifyDemandedVectorElts(LHS, DemandedSrcElts, LHSUndef, LHSZero, TLO,
42740 Depth + 1))
42741 return true;
42742 if (SimplifyDemandedVectorElts(RHS, DemandedSrcElts, RHSUndef, RHSZero, TLO,
42743 Depth + 1))
42744 return true;
42746 // TODO: Multiply by zero.
42748 // If RHS/LHS elements are known zero then we don't need the LHS/RHS equivalent.
42749 APInt DemandedLHSElts = DemandedSrcElts & ~RHSZero;
42750 if (SimplifyDemandedVectorElts(LHS, DemandedLHSElts, LHSUndef, LHSZero, TLO,
42751 Depth + 1))
42752 return true;
42753 APInt DemandedRHSElts = DemandedSrcElts & ~LHSZero;
42754 if (SimplifyDemandedVectorElts(RHS, DemandedRHSElts, RHSUndef, RHSZero, TLO,
42755 Depth + 1))
42756 return true;
42757 break;
42759 case X86ISD::PSADBW: {
42760 SDValue LHS = Op.getOperand(0);
42761 SDValue RHS = Op.getOperand(1);
42762 assert(VT.getScalarType() == MVT::i64 &&
42763 LHS.getValueType() == RHS.getValueType() &&
42764 LHS.getValueType().getScalarType() == MVT::i8 &&
42765 "Unexpected PSADBW types");
42767 // Aggressively peek through ops to get at the demanded elts.
42768 if (!DemandedElts.isAllOnes()) {
42769 unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
42770 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
42771 SDValue NewLHS = SimplifyMultipleUseDemandedVectorElts(
42772 LHS, DemandedSrcElts, TLO.DAG, Depth + 1);
42773 SDValue NewRHS = SimplifyMultipleUseDemandedVectorElts(
42774 RHS, DemandedSrcElts, TLO.DAG, Depth + 1);
42775 if (NewLHS || NewRHS) {
42776 NewLHS = NewLHS ? NewLHS : LHS;
42777 NewRHS = NewRHS ? NewRHS : RHS;
42778 return TLO.CombineTo(
42779 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
42782 break;
42784 case X86ISD::VSHL:
42785 case X86ISD::VSRL:
42786 case X86ISD::VSRA: {
42787 // We only need the bottom 64-bits of the (128-bit) shift amount.
42788 SDValue Amt = Op.getOperand(1);
42789 MVT AmtVT = Amt.getSimpleValueType();
42790 assert(AmtVT.is128BitVector() && "Unexpected value type");
42792 // If we reuse the shift amount just for sse shift amounts then we know that
42793 // only the bottom 64-bits are only ever used.
42794 bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
42795 unsigned UseOpc = Use->getOpcode();
42796 return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
42797 UseOpc == X86ISD::VSRA) &&
42798 Use->getOperand(0) != Amt;
42801 APInt AmtUndef, AmtZero;
42802 unsigned NumAmtElts = AmtVT.getVectorNumElements();
42803 APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
42804 if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
42805 Depth + 1, AssumeSingleUse))
42806 return true;
42807 [[fallthrough]];
42809 case X86ISD::VSHLI:
42810 case X86ISD::VSRLI:
42811 case X86ISD::VSRAI: {
42812 SDValue Src = Op.getOperand(0);
42813 APInt SrcUndef;
42814 if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
42815 Depth + 1))
42816 return true;
42818 // Fold shift(0,x) -> 0
42819 if (DemandedElts.isSubsetOf(KnownZero))
42820 return TLO.CombineTo(
42821 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
42823 // Aggressively peek through ops to get at the demanded elts.
42824 if (!DemandedElts.isAllOnes())
42825 if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
42826 Src, DemandedElts, TLO.DAG, Depth + 1))
42827 return TLO.CombineTo(
42828 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
42829 break;
42831 case X86ISD::VPSHA:
42832 case X86ISD::VPSHL:
42833 case X86ISD::VSHLV:
42834 case X86ISD::VSRLV:
42835 case X86ISD::VSRAV: {
42836 APInt LHSUndef, LHSZero;
42837 APInt RHSUndef, RHSZero;
42838 SDValue LHS = Op.getOperand(0);
42839 SDValue RHS = Op.getOperand(1);
42840 if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
42841 Depth + 1))
42842 return true;
42844 // Fold shift(0,x) -> 0
42845 if (DemandedElts.isSubsetOf(LHSZero))
42846 return TLO.CombineTo(
42847 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
42849 if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
42850 Depth + 1))
42851 return true;
42853 KnownZero = LHSZero;
42854 break;
42856 case X86ISD::PCMPEQ:
42857 case X86ISD::PCMPGT: {
42858 APInt LHSUndef, LHSZero;
42859 APInt RHSUndef, RHSZero;
42860 SDValue LHS = Op.getOperand(0);
42861 SDValue RHS = Op.getOperand(1);
42862 if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
42863 Depth + 1))
42864 return true;
42865 if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
42866 Depth + 1))
42867 return true;
42868 break;
42870 case X86ISD::KSHIFTL: {
42871 SDValue Src = Op.getOperand(0);
42872 auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
42873 assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
42874 unsigned ShiftAmt = Amt->getZExtValue();
42876 if (ShiftAmt == 0)
42877 return TLO.CombineTo(Op, Src);
42879 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
42880 // single shift. We can do this if the bottom bits (which are shifted
42881 // out) are never demanded.
42882 if (Src.getOpcode() == X86ISD::KSHIFTR) {
42883 if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
42884 unsigned C1 = Src.getConstantOperandVal(1);
42885 unsigned NewOpc = X86ISD::KSHIFTL;
42886 int Diff = ShiftAmt - C1;
42887 if (Diff < 0) {
42888 Diff = -Diff;
42889 NewOpc = X86ISD::KSHIFTR;
42892 SDLoc dl(Op);
42893 SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
42894 return TLO.CombineTo(
42895 Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
42899 APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
42900 if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
42901 Depth + 1))
42902 return true;
42904 KnownUndef <<= ShiftAmt;
42905 KnownZero <<= ShiftAmt;
42906 KnownZero.setLowBits(ShiftAmt);
42907 break;
42909 case X86ISD::KSHIFTR: {
42910 SDValue Src = Op.getOperand(0);
42911 auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
42912 assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
42913 unsigned ShiftAmt = Amt->getZExtValue();
42915 if (ShiftAmt == 0)
42916 return TLO.CombineTo(Op, Src);
42918 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
42919 // single shift. We can do this if the top bits (which are shifted
42920 // out) are never demanded.
42921 if (Src.getOpcode() == X86ISD::KSHIFTL) {
42922 if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
42923 unsigned C1 = Src.getConstantOperandVal(1);
42924 unsigned NewOpc = X86ISD::KSHIFTR;
42925 int Diff = ShiftAmt - C1;
42926 if (Diff < 0) {
42927 Diff = -Diff;
42928 NewOpc = X86ISD::KSHIFTL;
42931 SDLoc dl(Op);
42932 SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
42933 return TLO.CombineTo(
42934 Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
42938 APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
42939 if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
42940 Depth + 1))
42941 return true;
42943 KnownUndef.lshrInPlace(ShiftAmt);
42944 KnownZero.lshrInPlace(ShiftAmt);
42945 KnownZero.setHighBits(ShiftAmt);
42946 break;
42948 case X86ISD::ANDNP: {
42949 // ANDNP = (~LHS & RHS);
42950 SDValue LHS = Op.getOperand(0);
42951 SDValue RHS = Op.getOperand(1);
42953 auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
42954 APInt UndefElts;
42955 SmallVector<APInt> EltBits;
42956 int NumElts = VT.getVectorNumElements();
42957 int EltSizeInBits = VT.getScalarSizeInBits();
42958 APInt OpBits = APInt::getAllOnes(EltSizeInBits);
42959 APInt OpElts = DemandedElts;
42960 if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
42961 EltBits)) {
42962 OpBits.clearAllBits();
42963 OpElts.clearAllBits();
42964 for (int I = 0; I != NumElts; ++I) {
42965 if (!DemandedElts[I])
42966 continue;
42967 if (UndefElts[I]) {
42968 // We can't assume an undef src element gives an undef dst - the
42969 // other src might be zero.
42970 OpBits.setAllBits();
42971 OpElts.setBit(I);
42972 } else if ((Invert && !EltBits[I].isAllOnes()) ||
42973 (!Invert && !EltBits[I].isZero())) {
42974 OpBits |= Invert ? ~EltBits[I] : EltBits[I];
42975 OpElts.setBit(I);
42979 return std::make_pair(OpBits, OpElts);
42981 APInt BitsLHS, EltsLHS;
42982 APInt BitsRHS, EltsRHS;
42983 std::tie(BitsLHS, EltsLHS) = GetDemandedMasks(RHS);
42984 std::tie(BitsRHS, EltsRHS) = GetDemandedMasks(LHS, true);
42986 APInt LHSUndef, LHSZero;
42987 APInt RHSUndef, RHSZero;
42988 if (SimplifyDemandedVectorElts(LHS, EltsLHS, LHSUndef, LHSZero, TLO,
42989 Depth + 1))
42990 return true;
42991 if (SimplifyDemandedVectorElts(RHS, EltsRHS, RHSUndef, RHSZero, TLO,
42992 Depth + 1))
42993 return true;
42995 if (!DemandedElts.isAllOnes()) {
42996 SDValue NewLHS = SimplifyMultipleUseDemandedBits(LHS, BitsLHS, EltsLHS,
42997 TLO.DAG, Depth + 1);
42998 SDValue NewRHS = SimplifyMultipleUseDemandedBits(RHS, BitsRHS, EltsRHS,
42999 TLO.DAG, Depth + 1);
43000 if (NewLHS || NewRHS) {
43001 NewLHS = NewLHS ? NewLHS : LHS;
43002 NewRHS = NewRHS ? NewRHS : RHS;
43003 return TLO.CombineTo(
43004 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
43007 break;
43009 case X86ISD::CVTSI2P:
43010 case X86ISD::CVTUI2P:
43011 case X86ISD::CVTPH2PS:
43012 case X86ISD::CVTPS2PH: {
43013 SDValue Src = Op.getOperand(0);
43014 EVT SrcVT = Src.getValueType();
43015 APInt SrcUndef, SrcZero;
43016 APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
43017 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
43018 Depth + 1))
43019 return true;
43020 break;
43022 case X86ISD::PACKSS:
43023 case X86ISD::PACKUS: {
43024 SDValue N0 = Op.getOperand(0);
43025 SDValue N1 = Op.getOperand(1);
43027 APInt DemandedLHS, DemandedRHS;
43028 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
43030 APInt LHSUndef, LHSZero;
43031 if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
43032 Depth + 1))
43033 return true;
43034 APInt RHSUndef, RHSZero;
43035 if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
43036 Depth + 1))
43037 return true;
43039 // TODO - pass on known zero/undef.
43041 // Aggressively peek through ops to get at the demanded elts.
43042 // TODO - we should do this for all target/faux shuffles ops.
43043 if (!DemandedElts.isAllOnes()) {
43044 SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
43045 TLO.DAG, Depth + 1);
43046 SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
43047 TLO.DAG, Depth + 1);
43048 if (NewN0 || NewN1) {
43049 NewN0 = NewN0 ? NewN0 : N0;
43050 NewN1 = NewN1 ? NewN1 : N1;
43051 return TLO.CombineTo(Op,
43052 TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
43055 break;
43057 case X86ISD::HADD:
43058 case X86ISD::HSUB:
43059 case X86ISD::FHADD:
43060 case X86ISD::FHSUB: {
43061 SDValue N0 = Op.getOperand(0);
43062 SDValue N1 = Op.getOperand(1);
43064 APInt DemandedLHS, DemandedRHS;
43065 getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
43067 APInt LHSUndef, LHSZero;
43068 if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
43069 Depth + 1))
43070 return true;
43071 APInt RHSUndef, RHSZero;
43072 if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
43073 Depth + 1))
43074 return true;
43076 // TODO - pass on known zero/undef.
43078 // Aggressively peek through ops to get at the demanded elts.
43079 // TODO: Handle repeated operands.
43080 if (N0 != N1 && !DemandedElts.isAllOnes()) {
43081 SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
43082 TLO.DAG, Depth + 1);
43083 SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
43084 TLO.DAG, Depth + 1);
43085 if (NewN0 || NewN1) {
43086 NewN0 = NewN0 ? NewN0 : N0;
43087 NewN1 = NewN1 ? NewN1 : N1;
43088 return TLO.CombineTo(Op,
43089 TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
43092 break;
43094 case X86ISD::VTRUNC:
43095 case X86ISD::VTRUNCS:
43096 case X86ISD::VTRUNCUS: {
43097 SDValue Src = Op.getOperand(0);
43098 MVT SrcVT = Src.getSimpleValueType();
43099 APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
43100 APInt SrcUndef, SrcZero;
43101 if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
43102 Depth + 1))
43103 return true;
43104 KnownZero = SrcZero.zextOrTrunc(NumElts);
43105 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
43106 break;
43108 case X86ISD::BLENDI: {
43109 SmallVector<int, 16> BlendMask;
43110 DecodeBLENDMask(NumElts, Op.getConstantOperandVal(2), BlendMask);
43111 if (SDValue R = combineBlendOfPermutes(
43112 VT.getSimpleVT(), Op.getOperand(0), Op.getOperand(1), BlendMask,
43113 DemandedElts, TLO.DAG, Subtarget, SDLoc(Op)))
43114 return TLO.CombineTo(Op, R);
43115 break;
43117 case X86ISD::BLENDV: {
43118 APInt SelUndef, SelZero;
43119 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
43120 SelZero, TLO, Depth + 1))
43121 return true;
43123 // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
43124 APInt LHSUndef, LHSZero;
43125 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
43126 LHSZero, TLO, Depth + 1))
43127 return true;
43129 APInt RHSUndef, RHSZero;
43130 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
43131 RHSZero, TLO, Depth + 1))
43132 return true;
43134 KnownZero = LHSZero & RHSZero;
43135 KnownUndef = LHSUndef & RHSUndef;
43136 break;
43138 case X86ISD::VZEXT_MOVL: {
43139 // If upper demanded elements are already zero then we have nothing to do.
43140 SDValue Src = Op.getOperand(0);
43141 APInt DemandedUpperElts = DemandedElts;
43142 DemandedUpperElts.clearLowBits(1);
43143 if (TLO.DAG.MaskedVectorIsZero(Src, DemandedUpperElts, Depth + 1))
43144 return TLO.CombineTo(Op, Src);
43145 break;
43147 case X86ISD::VZEXT_LOAD: {
43148 // If upper demanded elements are not demanded then simplify to a
43149 // scalar_to_vector(load()).
43150 MVT SVT = VT.getSimpleVT().getVectorElementType();
43151 if (DemandedElts == 1 && Op.getValue(1).use_empty() && isTypeLegal(SVT)) {
43152 SDLoc DL(Op);
43153 auto *Mem = cast<MemSDNode>(Op);
43154 SDValue Elt = TLO.DAG.getLoad(SVT, DL, Mem->getChain(), Mem->getBasePtr(),
43155 Mem->getMemOperand());
43156 SDValue Vec = TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Elt);
43157 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Vec));
43159 break;
43161 case X86ISD::VBROADCAST: {
43162 SDValue Src = Op.getOperand(0);
43163 MVT SrcVT = Src.getSimpleValueType();
43164 // Don't bother broadcasting if we just need the 0'th element.
43165 if (DemandedElts == 1) {
43166 if (!SrcVT.isVector())
43167 Src = TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op), VT, Src);
43168 else if (Src.getValueType() != VT)
43169 Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
43170 SDLoc(Op));
43171 return TLO.CombineTo(Op, Src);
43173 if (!SrcVT.isVector())
43174 break;
43175 APInt SrcUndef, SrcZero;
43176 APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
43177 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
43178 Depth + 1))
43179 return true;
43180 // Aggressively peek through src to get at the demanded elt.
43181 // TODO - we should do this for all target/faux shuffles ops.
43182 if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
43183 Src, SrcElts, TLO.DAG, Depth + 1))
43184 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
43185 break;
43187 case X86ISD::VPERMV:
43188 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
43189 Depth))
43190 return true;
43191 break;
43192 case X86ISD::PSHUFB:
43193 case X86ISD::VPERMV3:
43194 case X86ISD::VPERMILPV:
43195 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
43196 Depth))
43197 return true;
43198 break;
43199 case X86ISD::VPPERM:
43200 case X86ISD::VPERMIL2:
43201 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
43202 Depth))
43203 return true;
43204 break;
43207 // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
43208 // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
43209 // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
43210 if ((VT.is256BitVector() || VT.is512BitVector()) &&
43211 DemandedElts.lshr(NumElts / 2) == 0) {
43212 unsigned SizeInBits = VT.getSizeInBits();
43213 unsigned ExtSizeInBits = SizeInBits / 2;
43215 // See if 512-bit ops only use the bottom 128-bits.
43216 if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
43217 ExtSizeInBits = SizeInBits / 4;
43219 switch (Opc) {
43220 // Scalar broadcast.
43221 case X86ISD::VBROADCAST: {
43222 SDLoc DL(Op);
43223 SDValue Src = Op.getOperand(0);
43224 if (Src.getValueSizeInBits() > ExtSizeInBits)
43225 Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
43226 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
43227 ExtSizeInBits / VT.getScalarSizeInBits());
43228 SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
43229 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
43230 TLO.DAG, DL, ExtSizeInBits));
43232 case X86ISD::VBROADCAST_LOAD: {
43233 SDLoc DL(Op);
43234 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
43235 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
43236 ExtSizeInBits / VT.getScalarSizeInBits());
43237 SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
43238 SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
43239 SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
43240 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
43241 MemIntr->getMemOperand());
43242 TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
43243 Bcst.getValue(1));
43244 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
43245 TLO.DAG, DL, ExtSizeInBits));
43247 // Subvector broadcast.
43248 case X86ISD::SUBV_BROADCAST_LOAD: {
43249 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
43250 EVT MemVT = MemIntr->getMemoryVT();
43251 if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
43252 SDLoc DL(Op);
43253 SDValue Ld =
43254 TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
43255 MemIntr->getBasePtr(), MemIntr->getMemOperand());
43256 TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
43257 Ld.getValue(1));
43258 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
43259 TLO.DAG, DL, ExtSizeInBits));
43260 } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
43261 SDLoc DL(Op);
43262 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
43263 ExtSizeInBits / VT.getScalarSizeInBits());
43264 if (SDValue BcstLd =
43265 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
43266 return TLO.CombineTo(Op,
43267 insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
43268 TLO.DAG, DL, ExtSizeInBits));
43270 break;
43272 // Byte shifts by immediate.
43273 case X86ISD::VSHLDQ:
43274 case X86ISD::VSRLDQ:
43275 // Shift by uniform.
43276 case X86ISD::VSHL:
43277 case X86ISD::VSRL:
43278 case X86ISD::VSRA:
43279 // Shift by immediate.
43280 case X86ISD::VSHLI:
43281 case X86ISD::VSRLI:
43282 case X86ISD::VSRAI: {
43283 SDLoc DL(Op);
43284 SDValue Ext0 =
43285 extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
43286 SDValue ExtOp =
43287 TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
43288 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
43289 SDValue Insert =
43290 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
43291 return TLO.CombineTo(Op, Insert);
43293 case X86ISD::VPERMI: {
43294 // Simplify PERMPD/PERMQ to extract_subvector.
43295 // TODO: This should be done in shuffle combining.
43296 if (VT == MVT::v4f64 || VT == MVT::v4i64) {
43297 SmallVector<int, 4> Mask;
43298 DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
43299 if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
43300 SDLoc DL(Op);
43301 SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
43302 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
43303 SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
43304 return TLO.CombineTo(Op, Insert);
43307 break;
43309 case X86ISD::VPERM2X128: {
43310 // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
43311 SDLoc DL(Op);
43312 unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
43313 if (LoMask & 0x8)
43314 return TLO.CombineTo(
43315 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
43316 unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
43317 unsigned SrcIdx = (LoMask & 0x2) >> 1;
43318 SDValue ExtOp =
43319 extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
43320 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
43321 SDValue Insert =
43322 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
43323 return TLO.CombineTo(Op, Insert);
43325 // Conversions.
43326 // TODO: Add more CVT opcodes when we have test coverage.
43327 case X86ISD::CVTTP2SI:
43328 case X86ISD::CVTTP2UI:
43329 case X86ISD::CVTPH2PS: {
43330 SDLoc DL(Op);
43331 unsigned Scale = SizeInBits / ExtSizeInBits;
43332 SDValue SrcOp = Op.getOperand(0);
43333 MVT SrcVT = SrcOp.getSimpleValueType();
43334 unsigned SrcExtSize =
43335 std::max<unsigned>(SrcVT.getSizeInBits() / Scale, 128);
43336 MVT ExtVT = MVT::getVectorVT(VT.getSimpleVT().getScalarType(),
43337 ExtSizeInBits / VT.getScalarSizeInBits());
43338 SDValue ExtOp = TLO.DAG.getNode(
43339 Opc, DL, ExtVT, extractSubVector(SrcOp, 0, TLO.DAG, DL, SrcExtSize));
43340 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
43341 SDValue Insert =
43342 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
43343 return TLO.CombineTo(Op, Insert);
43345 // Zero upper elements.
43346 case X86ISD::VZEXT_MOVL:
43347 // Variable blend.
43348 case X86ISD::BLENDV:
43349 // Target unary shuffles by immediate:
43350 case X86ISD::PSHUFD:
43351 case X86ISD::PSHUFLW:
43352 case X86ISD::PSHUFHW:
43353 case X86ISD::VPERMILPI:
43354 // (Non-Lane Crossing) Target Shuffles.
43355 case X86ISD::VPERMILPV:
43356 case X86ISD::VPERMIL2:
43357 case X86ISD::PSHUFB:
43358 case X86ISD::UNPCKL:
43359 case X86ISD::UNPCKH:
43360 case X86ISD::BLENDI:
43361 // Integer ops.
43362 case X86ISD::PACKSS:
43363 case X86ISD::PACKUS:
43364 case X86ISD::PCMPEQ:
43365 case X86ISD::PCMPGT:
43366 case X86ISD::PMULUDQ:
43367 case X86ISD::PMULDQ:
43368 case X86ISD::VSHLV:
43369 case X86ISD::VSRLV:
43370 case X86ISD::VSRAV:
43371 // Float ops.
43372 case X86ISD::FMAX:
43373 case X86ISD::FMIN:
43374 case X86ISD::FMAXC:
43375 case X86ISD::FMINC:
43376 case X86ISD::FRSQRT:
43377 case X86ISD::FRCP:
43378 // Horizontal Ops.
43379 case X86ISD::HADD:
43380 case X86ISD::HSUB:
43381 case X86ISD::FHADD:
43382 case X86ISD::FHSUB: {
43383 SDLoc DL(Op);
43384 SmallVector<SDValue, 4> Ops;
43385 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
43386 SDValue SrcOp = Op.getOperand(i);
43387 EVT SrcVT = SrcOp.getValueType();
43388 assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
43389 "Unsupported vector size");
43390 Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
43391 ExtSizeInBits)
43392 : SrcOp);
43394 MVT ExtVT = VT.getSimpleVT();
43395 ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
43396 ExtSizeInBits / ExtVT.getScalarSizeInBits());
43397 SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
43398 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
43399 SDValue Insert =
43400 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
43401 return TLO.CombineTo(Op, Insert);
43406 // For splats, unless we *only* demand the 0'th element,
43407 // stop attempts at simplification here, we aren't going to improve things,
43408 // this is better than any potential shuffle.
43409 if (!DemandedElts.isOne() && TLO.DAG.isSplatValue(Op, /*AllowUndefs*/false))
43410 return false;
43412 // Get target/faux shuffle mask.
43413 APInt OpUndef, OpZero;
43414 SmallVector<int, 64> OpMask;
43415 SmallVector<SDValue, 2> OpInputs;
43416 if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
43417 OpZero, TLO.DAG, Depth, false))
43418 return false;
43420 // Shuffle inputs must be the same size as the result.
43421 if (OpMask.size() != (unsigned)NumElts ||
43422 llvm::any_of(OpInputs, [VT](SDValue V) {
43423 return VT.getSizeInBits() != V.getValueSizeInBits() ||
43424 !V.getValueType().isVector();
43426 return false;
43428 KnownZero = OpZero;
43429 KnownUndef = OpUndef;
43431 // Check if shuffle mask can be simplified to undef/zero/identity.
43432 int NumSrcs = OpInputs.size();
43433 for (int i = 0; i != NumElts; ++i)
43434 if (!DemandedElts[i])
43435 OpMask[i] = SM_SentinelUndef;
43437 if (isUndefInRange(OpMask, 0, NumElts)) {
43438 KnownUndef.setAllBits();
43439 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
43441 if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
43442 KnownZero.setAllBits();
43443 return TLO.CombineTo(
43444 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
43446 for (int Src = 0; Src != NumSrcs; ++Src)
43447 if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
43448 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
43450 // Attempt to simplify inputs.
43451 for (int Src = 0; Src != NumSrcs; ++Src) {
43452 // TODO: Support inputs of different types.
43453 if (OpInputs[Src].getValueType() != VT)
43454 continue;
43456 int Lo = Src * NumElts;
43457 APInt SrcElts = APInt::getZero(NumElts);
43458 for (int i = 0; i != NumElts; ++i)
43459 if (DemandedElts[i]) {
43460 int M = OpMask[i] - Lo;
43461 if (0 <= M && M < NumElts)
43462 SrcElts.setBit(M);
43465 // TODO - Propagate input undef/zero elts.
43466 APInt SrcUndef, SrcZero;
43467 if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
43468 TLO, Depth + 1))
43469 return true;
43472 // If we don't demand all elements, then attempt to combine to a simpler
43473 // shuffle.
43474 // We need to convert the depth to something combineX86ShufflesRecursively
43475 // can handle - so pretend its Depth == 0 again, and reduce the max depth
43476 // to match. This prevents combineX86ShuffleChain from returning a
43477 // combined shuffle that's the same as the original root, causing an
43478 // infinite loop.
43479 if (!DemandedElts.isAllOnes()) {
43480 assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
43482 SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
43483 for (int i = 0; i != NumElts; ++i)
43484 if (DemandedElts[i])
43485 DemandedMask[i] = i;
43487 SDValue NewShuffle = combineX86ShufflesRecursively(
43488 {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
43489 /*HasVarMask*/ false,
43490 /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
43491 Subtarget);
43492 if (NewShuffle)
43493 return TLO.CombineTo(Op, NewShuffle);
43496 return false;
43499 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
43500 SDValue Op, const APInt &OriginalDemandedBits,
43501 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
43502 unsigned Depth) const {
43503 EVT VT = Op.getValueType();
43504 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
43505 unsigned Opc = Op.getOpcode();
43506 switch(Opc) {
43507 case X86ISD::VTRUNC: {
43508 KnownBits KnownOp;
43509 SDValue Src = Op.getOperand(0);
43510 MVT SrcVT = Src.getSimpleValueType();
43512 // Simplify the input, using demanded bit information.
43513 APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
43514 APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
43515 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
43516 return true;
43517 break;
43519 case X86ISD::PMULDQ:
43520 case X86ISD::PMULUDQ: {
43521 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
43522 KnownBits KnownLHS, KnownRHS;
43523 SDValue LHS = Op.getOperand(0);
43524 SDValue RHS = Op.getOperand(1);
43526 // Don't mask bits on 32-bit AVX512 targets which might lose a broadcast.
43527 // FIXME: Can we bound this better?
43528 APInt DemandedMask = APInt::getLowBitsSet(64, 32);
43529 APInt DemandedMaskLHS = APInt::getAllOnes(64);
43530 APInt DemandedMaskRHS = APInt::getAllOnes(64);
43532 bool Is32BitAVX512 = !Subtarget.is64Bit() && Subtarget.hasAVX512();
43533 if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(LHS))
43534 DemandedMaskLHS = DemandedMask;
43535 if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(RHS))
43536 DemandedMaskRHS = DemandedMask;
43538 if (SimplifyDemandedBits(LHS, DemandedMaskLHS, OriginalDemandedElts,
43539 KnownLHS, TLO, Depth + 1))
43540 return true;
43541 if (SimplifyDemandedBits(RHS, DemandedMaskRHS, OriginalDemandedElts,
43542 KnownRHS, TLO, Depth + 1))
43543 return true;
43545 // PMULUDQ(X,1) -> AND(X,(1<<32)-1) 'getZeroExtendInReg'.
43546 KnownRHS = KnownRHS.trunc(32);
43547 if (Opc == X86ISD::PMULUDQ && KnownRHS.isConstant() &&
43548 KnownRHS.getConstant().isOne()) {
43549 SDLoc DL(Op);
43550 SDValue Mask = TLO.DAG.getConstant(DemandedMask, DL, VT);
43551 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, DL, VT, LHS, Mask));
43554 // Aggressively peek through ops to get at the demanded low bits.
43555 SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
43556 LHS, DemandedMaskLHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
43557 SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
43558 RHS, DemandedMaskRHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
43559 if (DemandedLHS || DemandedRHS) {
43560 DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
43561 DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
43562 return TLO.CombineTo(
43563 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
43565 break;
43567 case X86ISD::ANDNP: {
43568 KnownBits Known2;
43569 SDValue Op0 = Op.getOperand(0);
43570 SDValue Op1 = Op.getOperand(1);
43572 if (SimplifyDemandedBits(Op1, OriginalDemandedBits, OriginalDemandedElts,
43573 Known, TLO, Depth + 1))
43574 return true;
43576 if (SimplifyDemandedBits(Op0, ~Known.Zero & OriginalDemandedBits,
43577 OriginalDemandedElts, Known2, TLO, Depth + 1))
43578 return true;
43580 // If the RHS is a constant, see if we can simplify it.
43581 if (ShrinkDemandedConstant(Op, ~Known2.One & OriginalDemandedBits,
43582 OriginalDemandedElts, TLO))
43583 return true;
43585 // ANDNP = (~Op0 & Op1);
43586 Known.One &= Known2.Zero;
43587 Known.Zero |= Known2.One;
43588 break;
43590 case X86ISD::VSHLI: {
43591 SDValue Op0 = Op.getOperand(0);
43592 SDValue Op1 = Op.getOperand(1);
43594 unsigned ShAmt = Op1->getAsZExtVal();
43595 if (ShAmt >= BitWidth)
43596 break;
43598 APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
43600 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
43601 // single shift. We can do this if the bottom bits (which are shifted
43602 // out) are never demanded.
43603 if (Op0.getOpcode() == X86ISD::VSRLI &&
43604 OriginalDemandedBits.countr_zero() >= ShAmt) {
43605 unsigned Shift2Amt = Op0.getConstantOperandVal(1);
43606 if (Shift2Amt < BitWidth) {
43607 int Diff = ShAmt - Shift2Amt;
43608 if (Diff == 0)
43609 return TLO.CombineTo(Op, Op0.getOperand(0));
43611 unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
43612 SDValue NewShift = TLO.DAG.getNode(
43613 NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
43614 TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
43615 return TLO.CombineTo(Op, NewShift);
43619 // If we are only demanding sign bits then we can use the shift source directly.
43620 unsigned NumSignBits =
43621 TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
43622 unsigned UpperDemandedBits = BitWidth - OriginalDemandedBits.countr_zero();
43623 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
43624 return TLO.CombineTo(Op, Op0);
43626 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
43627 TLO, Depth + 1))
43628 return true;
43630 Known.Zero <<= ShAmt;
43631 Known.One <<= ShAmt;
43633 // Low bits known zero.
43634 Known.Zero.setLowBits(ShAmt);
43636 if (!OriginalDemandedBits.isSubsetOf(Known.Zero | Known.One)) {
43637 // Attempt to avoid multi-use ops if we don't need anything from them.
43638 if (SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
43639 Op0, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1)) {
43640 SDValue NewOp =
43641 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedOp0, Op1);
43642 return TLO.CombineTo(Op, NewOp);
43645 return false;
43647 case X86ISD::VSRLI: {
43648 SDValue Op0 = Op.getOperand(0);
43649 SDValue Op1 = Op.getOperand(1);
43651 unsigned ShAmt = Op1->getAsZExtVal();
43652 if (ShAmt >= BitWidth)
43653 break;
43655 APInt DemandedMask = OriginalDemandedBits << ShAmt;
43657 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
43658 TLO, Depth + 1))
43659 return true;
43661 Known.Zero.lshrInPlace(ShAmt);
43662 Known.One.lshrInPlace(ShAmt);
43664 // High bits known zero.
43665 Known.Zero.setHighBits(ShAmt);
43667 if (!OriginalDemandedBits.isSubsetOf(Known.Zero | Known.One)) {
43668 // Attempt to avoid multi-use ops if we don't need anything from them.
43669 if (SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
43670 Op0, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1)) {
43671 SDValue NewOp =
43672 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedOp0, Op1);
43673 return TLO.CombineTo(Op, NewOp);
43676 return false;
43678 case X86ISD::VSRAI: {
43679 SDValue Op0 = Op.getOperand(0);
43680 SDValue Op1 = Op.getOperand(1);
43682 unsigned ShAmt = Op1->getAsZExtVal();
43683 if (ShAmt >= BitWidth)
43684 break;
43686 APInt DemandedMask = OriginalDemandedBits << ShAmt;
43688 // If we just want the sign bit then we don't need to shift it.
43689 if (OriginalDemandedBits.isSignMask())
43690 return TLO.CombineTo(Op, Op0);
43692 // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
43693 if (Op0.getOpcode() == X86ISD::VSHLI && Op1 == Op0.getOperand(1)) {
43694 SDValue Op00 = Op0.getOperand(0);
43695 unsigned NumSignBits =
43696 TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
43697 if (ShAmt < NumSignBits)
43698 return TLO.CombineTo(Op, Op00);
43701 // If any of the demanded bits are produced by the sign extension, we also
43702 // demand the input sign bit.
43703 if (OriginalDemandedBits.countl_zero() < ShAmt)
43704 DemandedMask.setSignBit();
43706 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
43707 TLO, Depth + 1))
43708 return true;
43710 Known.Zero.lshrInPlace(ShAmt);
43711 Known.One.lshrInPlace(ShAmt);
43713 // If the input sign bit is known to be zero, or if none of the top bits
43714 // are demanded, turn this into an unsigned shift right.
43715 if (Known.Zero[BitWidth - ShAmt - 1] ||
43716 OriginalDemandedBits.countl_zero() >= ShAmt)
43717 return TLO.CombineTo(
43718 Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
43720 // High bits are known one.
43721 if (Known.One[BitWidth - ShAmt - 1])
43722 Known.One.setHighBits(ShAmt);
43724 if (!OriginalDemandedBits.isSubsetOf(Known.Zero | Known.One)) {
43725 // Attempt to avoid multi-use ops if we don't need anything from them.
43726 if (SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
43727 Op0, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1)) {
43728 SDValue NewOp =
43729 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedOp0, Op1);
43730 return TLO.CombineTo(Op, NewOp);
43733 return false;
43735 case X86ISD::BLENDV: {
43736 SDValue Sel = Op.getOperand(0);
43737 SDValue LHS = Op.getOperand(1);
43738 SDValue RHS = Op.getOperand(2);
43740 APInt SignMask = APInt::getSignMask(BitWidth);
43741 SDValue NewSel = SimplifyMultipleUseDemandedBits(
43742 Sel, SignMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
43743 SDValue NewLHS = SimplifyMultipleUseDemandedBits(
43744 LHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
43745 SDValue NewRHS = SimplifyMultipleUseDemandedBits(
43746 RHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
43748 if (NewSel || NewLHS || NewRHS) {
43749 NewSel = NewSel ? NewSel : Sel;
43750 NewLHS = NewLHS ? NewLHS : LHS;
43751 NewRHS = NewRHS ? NewRHS : RHS;
43752 return TLO.CombineTo(Op, TLO.DAG.getNode(X86ISD::BLENDV, SDLoc(Op), VT,
43753 NewSel, NewLHS, NewRHS));
43755 break;
43757 case X86ISD::PEXTRB:
43758 case X86ISD::PEXTRW: {
43759 SDValue Vec = Op.getOperand(0);
43760 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
43761 MVT VecVT = Vec.getSimpleValueType();
43762 unsigned NumVecElts = VecVT.getVectorNumElements();
43764 if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
43765 unsigned Idx = CIdx->getZExtValue();
43766 unsigned VecBitWidth = VecVT.getScalarSizeInBits();
43768 // If we demand no bits from the vector then we must have demanded
43769 // bits from the implict zext - simplify to zero.
43770 APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
43771 if (DemandedVecBits == 0)
43772 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
43774 APInt KnownUndef, KnownZero;
43775 APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
43776 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
43777 KnownZero, TLO, Depth + 1))
43778 return true;
43780 KnownBits KnownVec;
43781 if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
43782 KnownVec, TLO, Depth + 1))
43783 return true;
43785 if (SDValue V = SimplifyMultipleUseDemandedBits(
43786 Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
43787 return TLO.CombineTo(
43788 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
43790 Known = KnownVec.zext(BitWidth);
43791 return false;
43793 break;
43795 case X86ISD::PINSRB:
43796 case X86ISD::PINSRW: {
43797 SDValue Vec = Op.getOperand(0);
43798 SDValue Scl = Op.getOperand(1);
43799 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
43800 MVT VecVT = Vec.getSimpleValueType();
43802 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
43803 unsigned Idx = CIdx->getZExtValue();
43804 if (!OriginalDemandedElts[Idx])
43805 return TLO.CombineTo(Op, Vec);
43807 KnownBits KnownVec;
43808 APInt DemandedVecElts(OriginalDemandedElts);
43809 DemandedVecElts.clearBit(Idx);
43810 if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
43811 KnownVec, TLO, Depth + 1))
43812 return true;
43814 KnownBits KnownScl;
43815 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
43816 APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
43817 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
43818 return true;
43820 KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
43821 Known = KnownVec.intersectWith(KnownScl);
43822 return false;
43824 break;
43826 case X86ISD::PACKSS:
43827 // PACKSS saturates to MIN/MAX integer values. So if we just want the
43828 // sign bit then we can just ask for the source operands sign bit.
43829 // TODO - add known bits handling.
43830 if (OriginalDemandedBits.isSignMask()) {
43831 APInt DemandedLHS, DemandedRHS;
43832 getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
43834 KnownBits KnownLHS, KnownRHS;
43835 APInt SignMask = APInt::getSignMask(BitWidth * 2);
43836 if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
43837 KnownLHS, TLO, Depth + 1))
43838 return true;
43839 if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
43840 KnownRHS, TLO, Depth + 1))
43841 return true;
43843 // Attempt to avoid multi-use ops if we don't need anything from them.
43844 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
43845 Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
43846 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
43847 Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
43848 if (DemandedOp0 || DemandedOp1) {
43849 SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
43850 SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
43851 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
43854 // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
43855 break;
43856 case X86ISD::VBROADCAST: {
43857 SDValue Src = Op.getOperand(0);
43858 MVT SrcVT = Src.getSimpleValueType();
43859 APInt DemandedElts = APInt::getOneBitSet(
43860 SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
43861 if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
43862 TLO, Depth + 1))
43863 return true;
43864 // If we don't need the upper bits, attempt to narrow the broadcast source.
43865 // Don't attempt this on AVX512 as it might affect broadcast folding.
43866 // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
43867 if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
43868 OriginalDemandedBits.countl_zero() >= (BitWidth / 2) &&
43869 Src->hasOneUse()) {
43870 MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
43871 SDValue NewSrc =
43872 TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
43873 MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
43874 SDValue NewBcst =
43875 TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
43876 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
43878 break;
43880 case X86ISD::PCMPGT:
43881 // icmp sgt(0, R) == ashr(R, BitWidth-1).
43882 // iff we only need the sign bit then we can use R directly.
43883 if (OriginalDemandedBits.isSignMask() &&
43884 ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
43885 return TLO.CombineTo(Op, Op.getOperand(1));
43886 break;
43887 case X86ISD::MOVMSK: {
43888 SDValue Src = Op.getOperand(0);
43889 MVT SrcVT = Src.getSimpleValueType();
43890 unsigned SrcBits = SrcVT.getScalarSizeInBits();
43891 unsigned NumElts = SrcVT.getVectorNumElements();
43893 // If we don't need the sign bits at all just return zero.
43894 if (OriginalDemandedBits.countr_zero() >= NumElts)
43895 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
43897 // See if we only demand bits from the lower 128-bit vector.
43898 if (SrcVT.is256BitVector() &&
43899 OriginalDemandedBits.getActiveBits() <= (NumElts / 2)) {
43900 SDValue NewSrc = extract128BitVector(Src, 0, TLO.DAG, SDLoc(Src));
43901 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
43904 // Only demand the vector elements of the sign bits we need.
43905 APInt KnownUndef, KnownZero;
43906 APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
43907 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
43908 TLO, Depth + 1))
43909 return true;
43911 Known.Zero = KnownZero.zext(BitWidth);
43912 Known.Zero.setHighBits(BitWidth - NumElts);
43914 // MOVMSK only uses the MSB from each vector element.
43915 KnownBits KnownSrc;
43916 APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
43917 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
43918 Depth + 1))
43919 return true;
43921 if (KnownSrc.One[SrcBits - 1])
43922 Known.One.setLowBits(NumElts);
43923 else if (KnownSrc.Zero[SrcBits - 1])
43924 Known.Zero.setLowBits(NumElts);
43926 // Attempt to avoid multi-use os if we don't need anything from it.
43927 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
43928 Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
43929 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
43930 return false;
43932 case X86ISD::TESTP: {
43933 SDValue Op0 = Op.getOperand(0);
43934 SDValue Op1 = Op.getOperand(1);
43935 MVT OpVT = Op0.getSimpleValueType();
43936 assert((OpVT.getVectorElementType() == MVT::f32 ||
43937 OpVT.getVectorElementType() == MVT::f64) &&
43938 "Illegal vector type for X86ISD::TESTP");
43940 // TESTPS/TESTPD only demands the sign bits of ALL the elements.
43941 KnownBits KnownSrc;
43942 APInt SignMask = APInt::getSignMask(OpVT.getScalarSizeInBits());
43943 bool AssumeSingleUse = (Op0 == Op1) && Op->isOnlyUserOf(Op0.getNode());
43944 return SimplifyDemandedBits(Op0, SignMask, KnownSrc, TLO, Depth + 1,
43945 AssumeSingleUse) ||
43946 SimplifyDemandedBits(Op1, SignMask, KnownSrc, TLO, Depth + 1,
43947 AssumeSingleUse);
43949 case X86ISD::CMOV: {
43950 KnownBits Known2;
43951 if (SimplifyDemandedBits(Op.getOperand(1), OriginalDemandedBits,
43952 OriginalDemandedElts, Known2, TLO, Depth + 1))
43953 return true;
43954 if (SimplifyDemandedBits(Op.getOperand(0), OriginalDemandedBits,
43955 OriginalDemandedElts, Known, TLO, Depth + 1))
43956 return true;
43958 // Only known if known in both the LHS and RHS.
43959 Known = Known.intersectWith(Known2);
43960 break;
43962 case X86ISD::BEXTR:
43963 case X86ISD::BEXTRI: {
43964 SDValue Op0 = Op.getOperand(0);
43965 SDValue Op1 = Op.getOperand(1);
43967 // Only bottom 16-bits of the control bits are required.
43968 if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
43969 // NOTE: SimplifyDemandedBits won't do this for constants.
43970 uint64_t Val1 = Cst1->getZExtValue();
43971 uint64_t MaskedVal1 = Val1 & 0xFFFF;
43972 if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
43973 SDLoc DL(Op);
43974 return TLO.CombineTo(
43975 Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
43976 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
43979 unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
43980 unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
43982 // If the length is 0, the result is 0.
43983 if (Length == 0) {
43984 Known.setAllZero();
43985 return false;
43988 if ((Shift + Length) <= BitWidth) {
43989 APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
43990 if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
43991 return true;
43993 Known = Known.extractBits(Length, Shift);
43994 Known = Known.zextOrTrunc(BitWidth);
43995 return false;
43997 } else {
43998 assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
43999 KnownBits Known1;
44000 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
44001 if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
44002 return true;
44004 // If the length is 0, replace with 0.
44005 KnownBits LengthBits = Known1.extractBits(8, 8);
44006 if (LengthBits.isZero())
44007 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
44010 break;
44012 case X86ISD::PDEP: {
44013 SDValue Op0 = Op.getOperand(0);
44014 SDValue Op1 = Op.getOperand(1);
44016 unsigned DemandedBitsLZ = OriginalDemandedBits.countl_zero();
44017 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
44019 // If the demanded bits has leading zeroes, we don't demand those from the
44020 // mask.
44021 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
44022 return true;
44024 // The number of possible 1s in the mask determines the number of LSBs of
44025 // operand 0 used. Undemanded bits from the mask don't matter so filter
44026 // them before counting.
44027 KnownBits Known2;
44028 uint64_t Count = (~Known.Zero & LoMask).popcount();
44029 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
44030 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
44031 return true;
44033 // Zeroes are retained from the mask, but not ones.
44034 Known.One.clearAllBits();
44035 // The result will have at least as many trailing zeros as the non-mask
44036 // operand since bits can only map to the same or higher bit position.
44037 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
44038 return false;
44042 return TargetLowering::SimplifyDemandedBitsForTargetNode(
44043 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
44046 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
44047 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
44048 SelectionDAG &DAG, unsigned Depth) const {
44049 int NumElts = DemandedElts.getBitWidth();
44050 unsigned Opc = Op.getOpcode();
44051 EVT VT = Op.getValueType();
44053 switch (Opc) {
44054 case X86ISD::PINSRB:
44055 case X86ISD::PINSRW: {
44056 // If we don't demand the inserted element, return the base vector.
44057 SDValue Vec = Op.getOperand(0);
44058 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
44059 MVT VecVT = Vec.getSimpleValueType();
44060 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
44061 !DemandedElts[CIdx->getZExtValue()])
44062 return Vec;
44063 break;
44065 case X86ISD::VSHLI: {
44066 // If we are only demanding sign bits then we can use the shift source
44067 // directly.
44068 SDValue Op0 = Op.getOperand(0);
44069 unsigned ShAmt = Op.getConstantOperandVal(1);
44070 unsigned BitWidth = DemandedBits.getBitWidth();
44071 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
44072 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
44073 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
44074 return Op0;
44075 break;
44077 case X86ISD::VSRAI:
44078 // iff we only need the sign bit then we can use the source directly.
44079 // TODO: generalize where we only demand extended signbits.
44080 if (DemandedBits.isSignMask())
44081 return Op.getOperand(0);
44082 break;
44083 case X86ISD::PCMPGT:
44084 // icmp sgt(0, R) == ashr(R, BitWidth-1).
44085 // iff we only need the sign bit then we can use R directly.
44086 if (DemandedBits.isSignMask() &&
44087 ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
44088 return Op.getOperand(1);
44089 break;
44090 case X86ISD::BLENDV: {
44091 // BLENDV: Cond (MSB) ? LHS : RHS
44092 SDValue Cond = Op.getOperand(0);
44093 SDValue LHS = Op.getOperand(1);
44094 SDValue RHS = Op.getOperand(2);
44096 KnownBits CondKnown = DAG.computeKnownBits(Cond, DemandedElts, Depth + 1);
44097 if (CondKnown.isNegative())
44098 return LHS;
44099 if (CondKnown.isNonNegative())
44100 return RHS;
44101 break;
44103 case X86ISD::ANDNP: {
44104 // ANDNP = (~LHS & RHS);
44105 SDValue LHS = Op.getOperand(0);
44106 SDValue RHS = Op.getOperand(1);
44108 KnownBits LHSKnown = DAG.computeKnownBits(LHS, DemandedElts, Depth + 1);
44109 KnownBits RHSKnown = DAG.computeKnownBits(RHS, DemandedElts, Depth + 1);
44111 // If all of the demanded bits are known 0 on LHS and known 0 on RHS, then
44112 // the (inverted) LHS bits cannot contribute to the result of the 'andn' in
44113 // this context, so return RHS.
44114 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero))
44115 return RHS;
44116 break;
44120 APInt ShuffleUndef, ShuffleZero;
44121 SmallVector<int, 16> ShuffleMask;
44122 SmallVector<SDValue, 2> ShuffleOps;
44123 if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
44124 ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
44125 // If all the demanded elts are from one operand and are inline,
44126 // then we can use the operand directly.
44127 int NumOps = ShuffleOps.size();
44128 if (ShuffleMask.size() == (unsigned)NumElts &&
44129 llvm::all_of(ShuffleOps, [VT](SDValue V) {
44130 return VT.getSizeInBits() == V.getValueSizeInBits();
44131 })) {
44133 if (DemandedElts.isSubsetOf(ShuffleUndef))
44134 return DAG.getUNDEF(VT);
44135 if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
44136 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
44138 // Bitmask that indicates which ops have only been accessed 'inline'.
44139 APInt IdentityOp = APInt::getAllOnes(NumOps);
44140 for (int i = 0; i != NumElts; ++i) {
44141 int M = ShuffleMask[i];
44142 if (!DemandedElts[i] || ShuffleUndef[i])
44143 continue;
44144 int OpIdx = M / NumElts;
44145 int EltIdx = M % NumElts;
44146 if (M < 0 || EltIdx != i) {
44147 IdentityOp.clearAllBits();
44148 break;
44150 IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
44151 if (IdentityOp == 0)
44152 break;
44154 assert((IdentityOp == 0 || IdentityOp.popcount() == 1) &&
44155 "Multiple identity shuffles detected");
44157 if (IdentityOp != 0)
44158 return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countr_zero()]);
44162 return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
44163 Op, DemandedBits, DemandedElts, DAG, Depth);
44166 bool X86TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
44167 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
44168 bool PoisonOnly, unsigned Depth) const {
44169 unsigned NumElts = DemandedElts.getBitWidth();
44171 switch (Op.getOpcode()) {
44172 case X86ISD::PSHUFD:
44173 case X86ISD::VPERMILPI:
44174 case X86ISD::VPERMV3: {
44175 SmallVector<int, 8> Mask;
44176 SmallVector<SDValue, 2> Ops;
44177 if (getTargetShuffleMask(Op, true, Ops, Mask)) {
44178 SmallVector<APInt, 2> DemandedSrcElts(Ops.size(),
44179 APInt::getZero(NumElts));
44180 for (auto M : enumerate(Mask)) {
44181 if (!DemandedElts[M.index()] || M.value() == SM_SentinelZero)
44182 continue;
44183 if (M.value() == SM_SentinelUndef)
44184 return false;
44185 assert(0 <= M.value() && M.value() < (int)(Ops.size() * NumElts) &&
44186 "Shuffle mask index out of range");
44187 DemandedSrcElts[M.value() / NumElts].setBit(M.value() % NumElts);
44189 for (auto Op : enumerate(Ops))
44190 if (!DemandedSrcElts[Op.index()].isZero() &&
44191 !DAG.isGuaranteedNotToBeUndefOrPoison(
44192 Op.value(), DemandedSrcElts[Op.index()], PoisonOnly, Depth + 1))
44193 return false;
44194 return true;
44196 break;
44199 return TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
44200 Op, DemandedElts, DAG, PoisonOnly, Depth);
44203 bool X86TargetLowering::canCreateUndefOrPoisonForTargetNode(
44204 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
44205 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
44207 switch (Op.getOpcode()) {
44208 // SSE vector multiplies are either inbounds or saturate.
44209 case X86ISD::VPMADDUBSW:
44210 case X86ISD::VPMADDWD:
44211 // SSE vector shifts handle out of bounds shift amounts.
44212 case X86ISD::VSHLI:
44213 case X86ISD::VSRLI:
44214 case X86ISD::VSRAI:
44215 return false;
44216 case X86ISD::PSHUFD:
44217 case X86ISD::VPERMILPI:
44218 case X86ISD::VPERMV3:
44219 case X86ISD::UNPCKH:
44220 case X86ISD::UNPCKL:
44221 return false;
44222 // SSE comparisons handle all fcmp cases.
44223 // TODO: Add PCMPEQ/GT and CMPM/MM with test coverage.
44224 case X86ISD::CMPP:
44225 return false;
44226 case ISD::INTRINSIC_WO_CHAIN:
44227 switch (Op->getConstantOperandVal(0)) {
44228 case Intrinsic::x86_sse2_pmadd_wd:
44229 case Intrinsic::x86_avx2_pmadd_wd:
44230 case Intrinsic::x86_avx512_pmaddw_d_512:
44231 case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
44232 case Intrinsic::x86_avx2_pmadd_ub_sw:
44233 case Intrinsic::x86_avx512_pmaddubs_w_512:
44234 return false;
44237 return TargetLowering::canCreateUndefOrPoisonForTargetNode(
44238 Op, DemandedElts, DAG, PoisonOnly, ConsiderFlags, Depth);
44241 bool X86TargetLowering::isSplatValueForTargetNode(SDValue Op,
44242 const APInt &DemandedElts,
44243 APInt &UndefElts,
44244 const SelectionDAG &DAG,
44245 unsigned Depth) const {
44246 unsigned NumElts = DemandedElts.getBitWidth();
44247 unsigned Opc = Op.getOpcode();
44249 switch (Opc) {
44250 case X86ISD::VBROADCAST:
44251 case X86ISD::VBROADCAST_LOAD:
44252 UndefElts = APInt::getZero(NumElts);
44253 return true;
44256 return TargetLowering::isSplatValueForTargetNode(Op, DemandedElts, UndefElts,
44257 DAG, Depth);
44260 // Helper to peek through bitops/trunc/setcc to determine size of source vector.
44261 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
44262 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
44263 bool AllowTruncate) {
44264 switch (Src.getOpcode()) {
44265 case ISD::TRUNCATE:
44266 if (!AllowTruncate)
44267 return false;
44268 [[fallthrough]];
44269 case ISD::SETCC:
44270 return Src.getOperand(0).getValueSizeInBits() == Size;
44271 case ISD::FREEZE:
44272 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate);
44273 case ISD::AND:
44274 case ISD::XOR:
44275 case ISD::OR:
44276 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
44277 checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
44278 case ISD::SELECT:
44279 case ISD::VSELECT:
44280 return Src.getOperand(0).getScalarValueSizeInBits() == 1 &&
44281 checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate) &&
44282 checkBitcastSrcVectorSize(Src.getOperand(2), Size, AllowTruncate);
44283 case ISD::BUILD_VECTOR:
44284 return ISD::isBuildVectorAllZeros(Src.getNode()) ||
44285 ISD::isBuildVectorAllOnes(Src.getNode());
44287 return false;
44290 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
44291 static unsigned getAltBitOpcode(unsigned Opcode) {
44292 switch(Opcode) {
44293 // clang-format off
44294 case ISD::AND: return X86ISD::FAND;
44295 case ISD::OR: return X86ISD::FOR;
44296 case ISD::XOR: return X86ISD::FXOR;
44297 case X86ISD::ANDNP: return X86ISD::FANDN;
44298 // clang-format on
44300 llvm_unreachable("Unknown bitwise opcode");
44303 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
44304 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
44305 const SDLoc &DL) {
44306 EVT SrcVT = Src.getValueType();
44307 if (SrcVT != MVT::v4i1)
44308 return SDValue();
44310 switch (Src.getOpcode()) {
44311 case ISD::SETCC:
44312 if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
44313 ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
44314 cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
44315 SDValue Op0 = Src.getOperand(0);
44316 if (ISD::isNormalLoad(Op0.getNode()))
44317 return DAG.getBitcast(MVT::v4f32, Op0);
44318 if (Op0.getOpcode() == ISD::BITCAST &&
44319 Op0.getOperand(0).getValueType() == MVT::v4f32)
44320 return Op0.getOperand(0);
44322 break;
44323 case ISD::AND:
44324 case ISD::XOR:
44325 case ISD::OR: {
44326 SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
44327 SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
44328 if (Op0 && Op1)
44329 return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
44330 Op1);
44331 break;
44334 return SDValue();
44337 // Helper to push sign extension of vXi1 SETCC result through bitops.
44338 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
44339 SDValue Src, const SDLoc &DL) {
44340 switch (Src.getOpcode()) {
44341 case ISD::SETCC:
44342 case ISD::FREEZE:
44343 case ISD::TRUNCATE:
44344 case ISD::BUILD_VECTOR:
44345 return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
44346 case ISD::AND:
44347 case ISD::XOR:
44348 case ISD::OR:
44349 return DAG.getNode(
44350 Src.getOpcode(), DL, SExtVT,
44351 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
44352 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
44353 case ISD::SELECT:
44354 case ISD::VSELECT:
44355 return DAG.getSelect(
44356 DL, SExtVT, Src.getOperand(0),
44357 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL),
44358 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(2), DL));
44360 llvm_unreachable("Unexpected node type for vXi1 sign extension");
44363 // Try to match patterns such as
44364 // (i16 bitcast (v16i1 x))
44365 // ->
44366 // (i16 movmsk (16i8 sext (v16i1 x)))
44367 // before the illegal vector is scalarized on subtargets that don't have legal
44368 // vxi1 types.
44369 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
44370 const SDLoc &DL,
44371 const X86Subtarget &Subtarget) {
44372 EVT SrcVT = Src.getValueType();
44373 if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
44374 return SDValue();
44376 // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
44377 // legalization destroys the v4i32 type.
44378 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
44379 if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
44380 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
44381 DAG.getBitcast(MVT::v4f32, V));
44382 return DAG.getZExtOrTrunc(V, DL, VT);
44386 // If the input is a truncate from v16i8 or v32i8 go ahead and use a
44387 // movmskb even with avx512. This will be better than truncating to vXi1 and
44388 // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
44389 // vpcmpeqb/vpcmpgtb.
44390 bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
44391 (Src.getOperand(0).getValueType() == MVT::v16i8 ||
44392 Src.getOperand(0).getValueType() == MVT::v32i8 ||
44393 Src.getOperand(0).getValueType() == MVT::v64i8);
44395 // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
44396 // directly with vpmovmskb/vmovmskps/vmovmskpd.
44397 if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
44398 cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
44399 ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
44400 EVT CmpVT = Src.getOperand(0).getValueType();
44401 EVT EltVT = CmpVT.getVectorElementType();
44402 if (CmpVT.getSizeInBits() <= 256 &&
44403 (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
44404 PreferMovMsk = true;
44407 // With AVX512 vxi1 types are legal and we prefer using k-regs.
44408 // MOVMSK is supported in SSE2 or later.
44409 if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
44410 return SDValue();
44412 // If the upper ops of a concatenation are undef, then try to bitcast the
44413 // lower op and extend.
44414 SmallVector<SDValue, 4> SubSrcOps;
44415 if (collectConcatOps(Src.getNode(), SubSrcOps, DAG) &&
44416 SubSrcOps.size() >= 2) {
44417 SDValue LowerOp = SubSrcOps[0];
44418 ArrayRef<SDValue> UpperOps(std::next(SubSrcOps.begin()), SubSrcOps.end());
44419 if (LowerOp.getOpcode() == ISD::SETCC &&
44420 all_of(UpperOps, [](SDValue Op) { return Op.isUndef(); })) {
44421 EVT SubVT = VT.getIntegerVT(
44422 *DAG.getContext(), LowerOp.getValueType().getVectorMinNumElements());
44423 if (SDValue V = combineBitcastvxi1(DAG, SubVT, LowerOp, DL, Subtarget)) {
44424 EVT IntVT = VT.getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
44425 return DAG.getBitcast(VT, DAG.getNode(ISD::ANY_EXTEND, DL, IntVT, V));
44430 // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
44431 // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
44432 // v8i16 and v16i16.
44433 // For these two cases, we can shuffle the upper element bytes to a
44434 // consecutive sequence at the start of the vector and treat the results as
44435 // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
44436 // for v16i16 this is not the case, because the shuffle is expensive, so we
44437 // avoid sign-extending to this type entirely.
44438 // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
44439 // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
44440 MVT SExtVT;
44441 bool PropagateSExt = false;
44442 switch (SrcVT.getSimpleVT().SimpleTy) {
44443 default:
44444 return SDValue();
44445 case MVT::v2i1:
44446 SExtVT = MVT::v2i64;
44447 break;
44448 case MVT::v4i1:
44449 SExtVT = MVT::v4i32;
44450 // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
44451 // sign-extend to a 256-bit operation to avoid truncation.
44452 if (Subtarget.hasAVX() &&
44453 checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
44454 SExtVT = MVT::v4i64;
44455 PropagateSExt = true;
44457 break;
44458 case MVT::v8i1:
44459 SExtVT = MVT::v8i16;
44460 // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
44461 // sign-extend to a 256-bit operation to match the compare.
44462 // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
44463 // 256-bit because the shuffle is cheaper than sign extending the result of
44464 // the compare.
44465 if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
44466 checkBitcastSrcVectorSize(Src, 512, true))) {
44467 SExtVT = MVT::v8i32;
44468 PropagateSExt = true;
44470 break;
44471 case MVT::v16i1:
44472 SExtVT = MVT::v16i8;
44473 // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
44474 // it is not profitable to sign-extend to 256-bit because this will
44475 // require an extra cross-lane shuffle which is more expensive than
44476 // truncating the result of the compare to 128-bits.
44477 break;
44478 case MVT::v32i1:
44479 SExtVT = MVT::v32i8;
44480 break;
44481 case MVT::v64i1:
44482 // If we have AVX512F, but not AVX512BW and the input is truncated from
44483 // v64i8 checked earlier. Then split the input and make two pmovmskbs.
44484 if (Subtarget.hasAVX512()) {
44485 if (Subtarget.hasBWI())
44486 return SDValue();
44487 SExtVT = MVT::v64i8;
44488 break;
44490 // Split if this is a <64 x i8> comparison result.
44491 if (checkBitcastSrcVectorSize(Src, 512, false)) {
44492 SExtVT = MVT::v64i8;
44493 break;
44495 return SDValue();
44498 SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
44499 : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
44501 if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
44502 V = getPMOVMSKB(DL, V, DAG, Subtarget);
44503 } else {
44504 if (SExtVT == MVT::v8i16) {
44505 V = widenSubVector(V, false, Subtarget, DAG, DL, 256);
44506 V = DAG.getNode(ISD::TRUNCATE, DL, MVT::v16i8, V);
44508 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
44511 EVT IntVT =
44512 EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
44513 V = DAG.getZExtOrTrunc(V, DL, IntVT);
44514 return DAG.getBitcast(VT, V);
44517 // Convert a vXi1 constant build vector to the same width scalar integer.
44518 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
44519 EVT SrcVT = Op.getValueType();
44520 assert(SrcVT.getVectorElementType() == MVT::i1 &&
44521 "Expected a vXi1 vector");
44522 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
44523 "Expected a constant build vector");
44525 APInt Imm(SrcVT.getVectorNumElements(), 0);
44526 for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
44527 SDValue In = Op.getOperand(Idx);
44528 if (!In.isUndef() && (In->getAsZExtVal() & 0x1))
44529 Imm.setBit(Idx);
44531 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
44532 return DAG.getConstant(Imm, SDLoc(Op), IntVT);
44535 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
44536 TargetLowering::DAGCombinerInfo &DCI,
44537 const X86Subtarget &Subtarget) {
44538 assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
44540 if (!DCI.isBeforeLegalizeOps())
44541 return SDValue();
44543 // Only do this if we have k-registers.
44544 if (!Subtarget.hasAVX512())
44545 return SDValue();
44547 EVT DstVT = N->getValueType(0);
44548 SDValue Op = N->getOperand(0);
44549 EVT SrcVT = Op.getValueType();
44551 if (!Op.hasOneUse())
44552 return SDValue();
44554 // Look for logic ops.
44555 if (Op.getOpcode() != ISD::AND &&
44556 Op.getOpcode() != ISD::OR &&
44557 Op.getOpcode() != ISD::XOR)
44558 return SDValue();
44560 // Make sure we have a bitcast between mask registers and a scalar type.
44561 if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
44562 DstVT.isScalarInteger()) &&
44563 !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
44564 SrcVT.isScalarInteger()))
44565 return SDValue();
44567 SDValue LHS = Op.getOperand(0);
44568 SDValue RHS = Op.getOperand(1);
44570 if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
44571 LHS.getOperand(0).getValueType() == DstVT)
44572 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
44573 DAG.getBitcast(DstVT, RHS));
44575 if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
44576 RHS.getOperand(0).getValueType() == DstVT)
44577 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
44578 DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
44580 // If the RHS is a vXi1 build vector, this is a good reason to flip too.
44581 // Most of these have to move a constant from the scalar domain anyway.
44582 if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
44583 RHS = combinevXi1ConstantToInteger(RHS, DAG);
44584 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
44585 DAG.getBitcast(DstVT, LHS), RHS);
44588 return SDValue();
44591 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
44592 const X86Subtarget &Subtarget) {
44593 SDLoc DL(BV);
44594 unsigned NumElts = BV->getNumOperands();
44595 SDValue Splat = BV->getSplatValue();
44597 // Build MMX element from integer GPR or SSE float values.
44598 auto CreateMMXElement = [&](SDValue V) {
44599 if (V.isUndef())
44600 return DAG.getUNDEF(MVT::x86mmx);
44601 if (V.getValueType().isFloatingPoint()) {
44602 if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
44603 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
44604 V = DAG.getBitcast(MVT::v2i64, V);
44605 return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
44607 V = DAG.getBitcast(MVT::i32, V);
44608 } else {
44609 V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
44611 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
44614 // Convert build vector ops to MMX data in the bottom elements.
44615 SmallVector<SDValue, 8> Ops;
44617 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44619 // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
44620 if (Splat) {
44621 if (Splat.isUndef())
44622 return DAG.getUNDEF(MVT::x86mmx);
44624 Splat = CreateMMXElement(Splat);
44626 if (Subtarget.hasSSE1()) {
44627 // Unpack v8i8 to splat i8 elements to lowest 16-bits.
44628 if (NumElts == 8)
44629 Splat = DAG.getNode(
44630 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
44631 DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
44632 TLI.getPointerTy(DAG.getDataLayout())),
44633 Splat, Splat);
44635 // Use PSHUFW to repeat 16-bit elements.
44636 unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
44637 return DAG.getNode(
44638 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
44639 DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
44640 TLI.getPointerTy(DAG.getDataLayout())),
44641 Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
44643 Ops.append(NumElts, Splat);
44644 } else {
44645 for (unsigned i = 0; i != NumElts; ++i)
44646 Ops.push_back(CreateMMXElement(BV->getOperand(i)));
44649 // Use tree of PUNPCKLs to build up general MMX vector.
44650 while (Ops.size() > 1) {
44651 unsigned NumOps = Ops.size();
44652 unsigned IntrinOp =
44653 (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
44654 : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
44655 : Intrinsic::x86_mmx_punpcklbw));
44656 SDValue Intrin = DAG.getTargetConstant(
44657 IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
44658 for (unsigned i = 0; i != NumOps; i += 2)
44659 Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
44660 Ops[i], Ops[i + 1]);
44661 Ops.resize(NumOps / 2);
44664 return Ops[0];
44667 // Recursive function that attempts to find if a bool vector node was originally
44668 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
44669 // integer. If so, replace the scalar ops with bool vector equivalents back down
44670 // the chain.
44671 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
44672 SelectionDAG &DAG,
44673 const X86Subtarget &Subtarget,
44674 unsigned Depth = 0) {
44675 if (Depth >= SelectionDAG::MaxRecursionDepth)
44676 return SDValue(); // Limit search depth.
44678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44679 unsigned Opc = V.getOpcode();
44680 switch (Opc) {
44681 case ISD::BITCAST: {
44682 // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
44683 SDValue Src = V.getOperand(0);
44684 EVT SrcVT = Src.getValueType();
44685 if (SrcVT.isVector() || SrcVT.isFloatingPoint())
44686 return DAG.getBitcast(VT, Src);
44687 break;
44689 case ISD::Constant: {
44690 auto *C = cast<ConstantSDNode>(V);
44691 if (C->isZero())
44692 return DAG.getConstant(0, DL, VT);
44693 if (C->isAllOnes())
44694 return DAG.getAllOnesConstant(DL, VT);
44695 break;
44697 case ISD::TRUNCATE: {
44698 // If we find a suitable source, a truncated scalar becomes a subvector.
44699 SDValue Src = V.getOperand(0);
44700 EVT NewSrcVT =
44701 EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
44702 if (TLI.isTypeLegal(NewSrcVT))
44703 if (SDValue N0 = combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG,
44704 Subtarget, Depth + 1))
44705 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
44706 DAG.getIntPtrConstant(0, DL));
44707 break;
44709 case ISD::ANY_EXTEND:
44710 case ISD::ZERO_EXTEND: {
44711 // If we find a suitable source, an extended scalar becomes a subvector.
44712 SDValue Src = V.getOperand(0);
44713 EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
44714 Src.getScalarValueSizeInBits());
44715 if (TLI.isTypeLegal(NewSrcVT))
44716 if (SDValue N0 = combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG,
44717 Subtarget, Depth + 1))
44718 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
44719 Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
44720 : DAG.getConstant(0, DL, VT),
44721 N0, DAG.getIntPtrConstant(0, DL));
44722 break;
44724 case ISD::OR:
44725 case ISD::XOR: {
44726 // If we find suitable sources, we can just move the op to the vector
44727 // domain.
44728 if (SDValue N0 = combineBitcastToBoolVector(VT, V.getOperand(0), DL, DAG,
44729 Subtarget, Depth + 1))
44730 if (SDValue N1 = combineBitcastToBoolVector(VT, V.getOperand(1), DL, DAG,
44731 Subtarget, Depth + 1))
44732 return DAG.getNode(Opc, DL, VT, N0, N1);
44733 break;
44735 case ISD::SHL: {
44736 // If we find a suitable source, a SHL becomes a KSHIFTL.
44737 SDValue Src0 = V.getOperand(0);
44738 if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
44739 ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
44740 break;
44742 if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
44743 if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget,
44744 Depth + 1))
44745 return DAG.getNode(
44746 X86ISD::KSHIFTL, DL, VT, N0,
44747 DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
44748 break;
44752 // Does the inner bitcast already exist?
44753 if (Depth > 0)
44754 if (SDNode *Alt = DAG.getNodeIfExists(ISD::BITCAST, DAG.getVTList(VT), {V}))
44755 return SDValue(Alt, 0);
44757 return SDValue();
44760 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
44761 TargetLowering::DAGCombinerInfo &DCI,
44762 const X86Subtarget &Subtarget) {
44763 SDValue N0 = N->getOperand(0);
44764 EVT VT = N->getValueType(0);
44765 EVT SrcVT = N0.getValueType();
44766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44768 // Try to match patterns such as
44769 // (i16 bitcast (v16i1 x))
44770 // ->
44771 // (i16 movmsk (16i8 sext (v16i1 x)))
44772 // before the setcc result is scalarized on subtargets that don't have legal
44773 // vxi1 types.
44774 if (DCI.isBeforeLegalize()) {
44775 SDLoc dl(N);
44776 if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
44777 return V;
44779 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
44780 // type, widen both sides to avoid a trip through memory.
44781 if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
44782 Subtarget.hasAVX512()) {
44783 N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
44784 N0 = DAG.getBitcast(MVT::v8i1, N0);
44785 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
44786 DAG.getIntPtrConstant(0, dl));
44789 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
44790 // type, widen both sides to avoid a trip through memory.
44791 if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
44792 Subtarget.hasAVX512()) {
44793 // Use zeros for the widening if we already have some zeroes. This can
44794 // allow SimplifyDemandedBits to remove scalar ANDs that may be down
44795 // stream of this.
44796 // FIXME: It might make sense to detect a concat_vectors with a mix of
44797 // zeroes and undef and turn it into insert_subvector for i1 vectors as
44798 // a separate combine. What we can't do is canonicalize the operands of
44799 // such a concat or we'll get into a loop with SimplifyDemandedBits.
44800 if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
44801 SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
44802 if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
44803 SrcVT = LastOp.getValueType();
44804 unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
44805 SmallVector<SDValue, 4> Ops(N0->ops());
44806 Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
44807 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
44808 N0 = DAG.getBitcast(MVT::i8, N0);
44809 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
44813 unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
44814 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
44815 Ops[0] = N0;
44816 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
44817 N0 = DAG.getBitcast(MVT::i8, N0);
44818 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
44820 } else {
44821 // If we're bitcasting from iX to vXi1, see if the integer originally
44822 // began as a vXi1 and whether we can remove the bitcast entirely.
44823 if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
44824 SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
44825 if (SDValue V =
44826 combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
44827 return V;
44831 // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
44832 // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
44833 // due to insert_subvector legalization on KNL. By promoting the copy to i16
44834 // we can help with known bits propagation from the vXi1 domain to the
44835 // scalar domain.
44836 if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
44837 !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
44838 N0.getOperand(0).getValueType() == MVT::v16i1 &&
44839 isNullConstant(N0.getOperand(1)))
44840 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
44841 DAG.getBitcast(MVT::i16, N0.getOperand(0)));
44843 // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
44844 // and the vbroadcast_load are both integer or both fp. In some cases this
44845 // will remove the bitcast entirely.
44846 if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
44847 VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
44848 auto *BCast = cast<MemIntrinsicSDNode>(N0);
44849 unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
44850 unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
44851 // Don't swap i8/i16 since don't have fp types that size.
44852 if (MemSize >= 32) {
44853 MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
44854 : MVT::getIntegerVT(MemSize);
44855 MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
44856 : MVT::getIntegerVT(SrcVTSize);
44857 LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
44859 SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
44860 SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
44861 SDValue ResNode =
44862 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
44863 MemVT, BCast->getMemOperand());
44864 DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
44865 return DAG.getBitcast(VT, ResNode);
44869 // Since MMX types are special and don't usually play with other vector types,
44870 // it's better to handle them early to be sure we emit efficient code by
44871 // avoiding store-load conversions.
44872 if (VT == MVT::x86mmx) {
44873 // Detect MMX constant vectors.
44874 APInt UndefElts;
44875 SmallVector<APInt, 1> EltBits;
44876 if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits,
44877 /*AllowWholeUndefs*/ true,
44878 /*AllowPartialUndefs*/ true)) {
44879 SDLoc DL(N0);
44880 // Handle zero-extension of i32 with MOVD.
44881 if (EltBits[0].countl_zero() >= 32)
44882 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
44883 DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
44884 // Else, bitcast to a double.
44885 // TODO - investigate supporting sext 32-bit immediates on x86_64.
44886 APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
44887 return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
44890 // Detect bitcasts to x86mmx low word.
44891 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
44892 (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
44893 N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
44894 bool LowUndef = true, AllUndefOrZero = true;
44895 for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
44896 SDValue Op = N0.getOperand(i);
44897 LowUndef &= Op.isUndef() || (i >= e/2);
44898 AllUndefOrZero &= isNullConstantOrUndef(Op);
44900 if (AllUndefOrZero) {
44901 SDValue N00 = N0.getOperand(0);
44902 SDLoc dl(N00);
44903 N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
44904 : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
44905 return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
44909 // Detect bitcasts of 64-bit build vectors and convert to a
44910 // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
44911 // lowest element.
44912 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
44913 (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
44914 SrcVT == MVT::v8i8))
44915 return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
44917 // Detect bitcasts between element or subvector extraction to x86mmx.
44918 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
44919 N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
44920 isNullConstant(N0.getOperand(1))) {
44921 SDValue N00 = N0.getOperand(0);
44922 if (N00.getValueType().is128BitVector())
44923 return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
44924 DAG.getBitcast(MVT::v2i64, N00));
44927 // Detect bitcasts from FP_TO_SINT to x86mmx.
44928 if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
44929 SDLoc DL(N0);
44930 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
44931 DAG.getUNDEF(MVT::v2i32));
44932 return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
44933 DAG.getBitcast(MVT::v2i64, Res));
44937 // Try to remove a bitcast of constant vXi1 vector. We have to legalize
44938 // most of these to scalar anyway.
44939 if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
44940 SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
44941 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
44942 return combinevXi1ConstantToInteger(N0, DAG);
44945 if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() && VT.isVector() &&
44946 VT.getVectorElementType() == MVT::i1) {
44947 if (auto *C = dyn_cast<ConstantSDNode>(N0)) {
44948 if (C->isAllOnes())
44949 return DAG.getConstant(1, SDLoc(N0), VT);
44950 if (C->isZero())
44951 return DAG.getConstant(0, SDLoc(N0), VT);
44955 // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
44956 // Turn it into a sign bit compare that produces a k-register. This avoids
44957 // a trip through a GPR.
44958 if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
44959 VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
44960 isPowerOf2_32(VT.getVectorNumElements())) {
44961 unsigned NumElts = VT.getVectorNumElements();
44962 SDValue Src = N0;
44964 // Peek through truncate.
44965 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
44966 Src = N0.getOperand(0);
44968 if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
44969 SDValue MovmskIn = Src.getOperand(0);
44970 MVT MovmskVT = MovmskIn.getSimpleValueType();
44971 unsigned MovMskElts = MovmskVT.getVectorNumElements();
44973 // We allow extra bits of the movmsk to be used since they are known zero.
44974 // We can't convert a VPMOVMSKB without avx512bw.
44975 if (MovMskElts <= NumElts &&
44976 (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
44977 EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
44978 MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
44979 SDLoc dl(N);
44980 MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
44981 SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
44982 DAG.getConstant(0, dl, IntVT), ISD::SETLT);
44983 if (EVT(CmpVT) == VT)
44984 return Cmp;
44986 // Pad with zeroes up to original VT to replace the zeroes that were
44987 // being used from the MOVMSK.
44988 unsigned NumConcats = NumElts / MovMskElts;
44989 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
44990 Ops[0] = Cmp;
44991 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
44996 // Try to remove bitcasts from input and output of mask arithmetic to
44997 // remove GPR<->K-register crossings.
44998 if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
44999 return V;
45001 // Convert a bitcasted integer logic operation that has one bitcasted
45002 // floating-point operand into a floating-point logic operation. This may
45003 // create a load of a constant, but that is cheaper than materializing the
45004 // constant in an integer register and transferring it to an SSE register or
45005 // transferring the SSE operand to integer register and back.
45006 unsigned FPOpcode;
45007 switch (N0.getOpcode()) {
45008 // clang-format off
45009 case ISD::AND: FPOpcode = X86ISD::FAND; break;
45010 case ISD::OR: FPOpcode = X86ISD::FOR; break;
45011 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
45012 default: return SDValue();
45013 // clang-format on
45016 // Check if we have a bitcast from another integer type as well.
45017 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
45018 (Subtarget.hasSSE2() && VT == MVT::f64) ||
45019 (Subtarget.hasFP16() && VT == MVT::f16) ||
45020 (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
45021 TLI.isTypeLegal(VT))))
45022 return SDValue();
45024 SDValue LogicOp0 = N0.getOperand(0);
45025 SDValue LogicOp1 = N0.getOperand(1);
45026 SDLoc DL0(N0);
45028 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
45029 if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
45030 LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
45031 LogicOp0.getOperand(0).getValueType() == VT &&
45032 !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
45033 SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
45034 unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
45035 return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
45037 // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
45038 if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
45039 LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
45040 LogicOp1.getOperand(0).getValueType() == VT &&
45041 !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
45042 SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
45043 unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
45044 return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
45047 return SDValue();
45050 // (mul (zext a), (sext, b))
45051 static bool detectExtMul(SelectionDAG &DAG, const SDValue &Mul, SDValue &Op0,
45052 SDValue &Op1) {
45053 Op0 = Mul.getOperand(0);
45054 Op1 = Mul.getOperand(1);
45056 // The operand1 should be signed extend
45057 if (Op0.getOpcode() == ISD::SIGN_EXTEND)
45058 std::swap(Op0, Op1);
45060 auto IsFreeTruncation = [](SDValue &Op) -> bool {
45061 if ((Op.getOpcode() == ISD::ZERO_EXTEND ||
45062 Op.getOpcode() == ISD::SIGN_EXTEND) &&
45063 Op.getOperand(0).getScalarValueSizeInBits() <= 8)
45064 return true;
45066 auto *BV = dyn_cast<BuildVectorSDNode>(Op);
45067 return (BV && BV->isConstant());
45070 // (dpbusd (zext a), (sext, b)). Since the first operand should be unsigned
45071 // value, we need to check Op0 is zero extended value. Op1 should be signed
45072 // value, so we just check the signed bits.
45073 if ((IsFreeTruncation(Op0) &&
45074 DAG.computeKnownBits(Op0).countMaxActiveBits() <= 8) &&
45075 (IsFreeTruncation(Op1) && DAG.ComputeMaxSignificantBits(Op1) <= 8))
45076 return true;
45078 return false;
45081 // Given a ABS node, detect the following pattern:
45082 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
45083 // This is useful as it is the input into a SAD pattern.
45084 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
45085 SDValue AbsOp1 = Abs->getOperand(0);
45086 if (AbsOp1.getOpcode() != ISD::SUB)
45087 return false;
45089 Op0 = AbsOp1.getOperand(0);
45090 Op1 = AbsOp1.getOperand(1);
45092 // Check if the operands of the sub are zero-extended from vectors of i8.
45093 if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
45094 Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
45095 Op1.getOpcode() != ISD::ZERO_EXTEND ||
45096 Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
45097 return false;
45099 return true;
45102 static SDValue createVPDPBUSD(SelectionDAG &DAG, SDValue LHS, SDValue RHS,
45103 unsigned &LogBias, const SDLoc &DL,
45104 const X86Subtarget &Subtarget) {
45105 // Extend or truncate to MVT::i8 first.
45106 MVT Vi8VT =
45107 MVT::getVectorVT(MVT::i8, LHS.getValueType().getVectorElementCount());
45108 LHS = DAG.getZExtOrTrunc(LHS, DL, Vi8VT);
45109 RHS = DAG.getSExtOrTrunc(RHS, DL, Vi8VT);
45111 // VPDPBUSD(<16 x i32>C, <16 x i8>A, <16 x i8>B). For each dst element
45112 // C[0] = C[0] + A[0]B[0] + A[1]B[1] + A[2]B[2] + A[3]B[3].
45113 // The src A, B element type is i8, but the dst C element type is i32.
45114 // When we calculate the reduce stage, we use src vector type vXi8 for it
45115 // so we need logbias 2 to avoid extra 2 stages.
45116 LogBias = 2;
45118 unsigned RegSize = std::max(128u, (unsigned)Vi8VT.getSizeInBits());
45119 if (Subtarget.hasVNNI() && !Subtarget.hasVLX())
45120 RegSize = std::max(512u, RegSize);
45122 // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
45123 // fill in the missing vector elements with 0.
45124 unsigned NumConcat = RegSize / Vi8VT.getSizeInBits();
45125 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, Vi8VT));
45126 Ops[0] = LHS;
45127 MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
45128 SDValue DpOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45129 Ops[0] = RHS;
45130 SDValue DpOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45132 // Actually build the DotProduct, split as 256/512 bits for
45133 // AVXVNNI/AVX512VNNI.
45134 auto DpBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45135 ArrayRef<SDValue> Ops) {
45136 MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
45137 return DAG.getNode(X86ISD::VPDPBUSD, DL, VT, Ops);
45139 MVT DpVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
45140 SDValue Zero = DAG.getConstant(0, DL, DpVT);
45142 return SplitOpsAndApply(DAG, Subtarget, DL, DpVT, {Zero, DpOp0, DpOp1},
45143 DpBuilder, false);
45146 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
45147 // to these zexts.
45148 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
45149 const SDValue &Zext1, const SDLoc &DL,
45150 const X86Subtarget &Subtarget) {
45151 // Find the appropriate width for the PSADBW.
45152 EVT InVT = Zext0.getOperand(0).getValueType();
45153 unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
45155 // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
45156 // fill in the missing vector elements with 0.
45157 unsigned NumConcat = RegSize / InVT.getSizeInBits();
45158 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
45159 Ops[0] = Zext0.getOperand(0);
45160 MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
45161 SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45162 Ops[0] = Zext1.getOperand(0);
45163 SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
45165 // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
45166 auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45167 ArrayRef<SDValue> Ops) {
45168 MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
45169 return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
45171 MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
45172 return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
45173 PSADBWBuilder);
45176 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
45177 // PHMINPOSUW.
45178 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
45179 const X86Subtarget &Subtarget) {
45180 // Bail without SSE41.
45181 if (!Subtarget.hasSSE41())
45182 return SDValue();
45184 EVT ExtractVT = Extract->getValueType(0);
45185 if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
45186 return SDValue();
45188 // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
45189 ISD::NodeType BinOp;
45190 SDValue Src = DAG.matchBinOpReduction(
45191 Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
45192 if (!Src)
45193 return SDValue();
45195 EVT SrcVT = Src.getValueType();
45196 EVT SrcSVT = SrcVT.getScalarType();
45197 if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
45198 return SDValue();
45200 SDLoc DL(Extract);
45201 SDValue MinPos = Src;
45203 // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
45204 while (SrcVT.getSizeInBits() > 128) {
45205 SDValue Lo, Hi;
45206 std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
45207 SrcVT = Lo.getValueType();
45208 MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
45210 assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
45211 (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
45212 "Unexpected value type");
45214 // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
45215 // to flip the value accordingly.
45216 SDValue Mask;
45217 unsigned MaskEltsBits = ExtractVT.getSizeInBits();
45218 if (BinOp == ISD::SMAX)
45219 Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
45220 else if (BinOp == ISD::SMIN)
45221 Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
45222 else if (BinOp == ISD::UMAX)
45223 Mask = DAG.getAllOnesConstant(DL, SrcVT);
45225 if (Mask)
45226 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
45228 // For v16i8 cases we need to perform UMIN on pairs of byte elements,
45229 // shuffling each upper element down and insert zeros. This means that the
45230 // v16i8 UMIN will leave the upper element as zero, performing zero-extension
45231 // ready for the PHMINPOS.
45232 if (ExtractVT == MVT::i8) {
45233 SDValue Upper = DAG.getVectorShuffle(
45234 SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
45235 {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
45236 MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
45239 // Perform the PHMINPOS on a v8i16 vector,
45240 MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
45241 MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
45242 MinPos = DAG.getBitcast(SrcVT, MinPos);
45244 if (Mask)
45245 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
45247 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
45248 DAG.getIntPtrConstant(0, DL));
45251 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
45252 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
45253 const X86Subtarget &Subtarget) {
45254 // Bail without SSE2.
45255 if (!Subtarget.hasSSE2())
45256 return SDValue();
45258 EVT ExtractVT = Extract->getValueType(0);
45259 unsigned BitWidth = ExtractVT.getSizeInBits();
45260 if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
45261 ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
45262 return SDValue();
45264 // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
45265 ISD::NodeType BinOp;
45266 SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
45267 if (!Match && ExtractVT == MVT::i1)
45268 Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
45269 if (!Match)
45270 return SDValue();
45272 // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
45273 // which we can't support here for now.
45274 if (Match.getScalarValueSizeInBits() != BitWidth)
45275 return SDValue();
45277 SDValue Movmsk;
45278 SDLoc DL(Extract);
45279 EVT MatchVT = Match.getValueType();
45280 unsigned NumElts = MatchVT.getVectorNumElements();
45281 unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
45282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45283 LLVMContext &Ctx = *DAG.getContext();
45285 if (ExtractVT == MVT::i1) {
45286 // Special case for (pre-legalization) vXi1 reductions.
45287 if (NumElts > 64 || !isPowerOf2_32(NumElts))
45288 return SDValue();
45289 if (Match.getOpcode() == ISD::SETCC) {
45290 ISD::CondCode CC = cast<CondCodeSDNode>(Match.getOperand(2))->get();
45291 if ((BinOp == ISD::AND && CC == ISD::CondCode::SETEQ) ||
45292 (BinOp == ISD::OR && CC == ISD::CondCode::SETNE)) {
45293 // For all_of(setcc(x,y,eq)) - use (iX)x == (iX)y.
45294 // For any_of(setcc(x,y,ne)) - use (iX)x != (iX)y.
45295 X86::CondCode X86CC;
45296 SDValue LHS = DAG.getFreeze(Match.getOperand(0));
45297 SDValue RHS = DAG.getFreeze(Match.getOperand(1));
45298 APInt Mask = APInt::getAllOnes(LHS.getScalarValueSizeInBits());
45299 if (SDValue V = LowerVectorAllEqual(DL, LHS, RHS, CC, Mask, Subtarget,
45300 DAG, X86CC))
45301 return DAG.getNode(ISD::TRUNCATE, DL, ExtractVT,
45302 getSETCC(X86CC, V, DL, DAG));
45305 if (TLI.isTypeLegal(MatchVT)) {
45306 // If this is a legal AVX512 predicate type then we can just bitcast.
45307 EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
45308 Movmsk = DAG.getBitcast(MovmskVT, Match);
45309 } else {
45310 // Use combineBitcastvxi1 to create the MOVMSK.
45311 while (NumElts > MaxElts) {
45312 SDValue Lo, Hi;
45313 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
45314 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
45315 NumElts /= 2;
45317 EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
45318 Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
45320 if (!Movmsk)
45321 return SDValue();
45322 Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
45323 } else {
45324 // FIXME: Better handling of k-registers or 512-bit vectors?
45325 unsigned MatchSizeInBits = Match.getValueSizeInBits();
45326 if (!(MatchSizeInBits == 128 ||
45327 (MatchSizeInBits == 256 && Subtarget.hasAVX())))
45328 return SDValue();
45330 // Make sure this isn't a vector of 1 element. The perf win from using
45331 // MOVMSK diminishes with less elements in the reduction, but it is
45332 // generally better to get the comparison over to the GPRs as soon as
45333 // possible to reduce the number of vector ops.
45334 if (Match.getValueType().getVectorNumElements() < 2)
45335 return SDValue();
45337 // Check that we are extracting a reduction of all sign bits.
45338 if (DAG.ComputeNumSignBits(Match) != BitWidth)
45339 return SDValue();
45341 if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
45342 SDValue Lo, Hi;
45343 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
45344 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
45345 MatchSizeInBits = Match.getValueSizeInBits();
45348 // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
45349 MVT MaskSrcVT;
45350 if (64 == BitWidth || 32 == BitWidth)
45351 MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
45352 MatchSizeInBits / BitWidth);
45353 else
45354 MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
45356 SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
45357 Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
45358 NumElts = MaskSrcVT.getVectorNumElements();
45360 assert((NumElts <= 32 || NumElts == 64) &&
45361 "Not expecting more than 64 elements");
45363 MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
45364 if (BinOp == ISD::XOR) {
45365 // parity -> (PARITY(MOVMSK X))
45366 SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
45367 return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
45370 SDValue CmpC;
45371 ISD::CondCode CondCode;
45372 if (BinOp == ISD::OR) {
45373 // any_of -> MOVMSK != 0
45374 CmpC = DAG.getConstant(0, DL, CmpVT);
45375 CondCode = ISD::CondCode::SETNE;
45376 } else {
45377 // all_of -> MOVMSK == ((1 << NumElts) - 1)
45378 CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
45379 DL, CmpVT);
45380 CondCode = ISD::CondCode::SETEQ;
45383 // The setcc produces an i8 of 0/1, so extend that to the result width and
45384 // negate to get the final 0/-1 mask value.
45385 EVT SetccVT = TLI.getSetCCResultType(DAG.getDataLayout(), Ctx, CmpVT);
45386 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
45387 SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
45388 return DAG.getNegative(Zext, DL, ExtractVT);
45391 static SDValue combineVPDPBUSDPattern(SDNode *Extract, SelectionDAG &DAG,
45392 const X86Subtarget &Subtarget) {
45393 if (!Subtarget.hasVNNI() && !Subtarget.hasAVXVNNI())
45394 return SDValue();
45396 EVT ExtractVT = Extract->getValueType(0);
45397 // Verify the type we're extracting is i32, as the output element type of
45398 // vpdpbusd is i32.
45399 if (ExtractVT != MVT::i32)
45400 return SDValue();
45402 EVT VT = Extract->getOperand(0).getValueType();
45403 if (!isPowerOf2_32(VT.getVectorNumElements()))
45404 return SDValue();
45406 // Match shuffle + add pyramid.
45407 ISD::NodeType BinOp;
45408 SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
45410 // We can't combine to vpdpbusd for zext, because each of the 4 multiplies
45411 // done by vpdpbusd compute a signed 16-bit product that will be sign extended
45412 // before adding into the accumulator.
45413 // TODO:
45414 // We also need to verify that the multiply has at least 2x the number of bits
45415 // of the input. We shouldn't match
45416 // (sign_extend (mul (vXi9 (zext (vXi8 X))), (vXi9 (zext (vXi8 Y)))).
45417 // if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND))
45418 // Root = Root.getOperand(0);
45420 // If there was a match, we want Root to be a mul.
45421 if (!Root || Root.getOpcode() != ISD::MUL)
45422 return SDValue();
45424 // Check whether we have an extend and mul pattern
45425 SDValue LHS, RHS;
45426 if (!detectExtMul(DAG, Root, LHS, RHS))
45427 return SDValue();
45429 // Create the dot product instruction.
45430 SDLoc DL(Extract);
45431 unsigned StageBias;
45432 SDValue DP = createVPDPBUSD(DAG, LHS, RHS, StageBias, DL, Subtarget);
45434 // If the original vector was wider than 4 elements, sum over the results
45435 // in the DP vector.
45436 unsigned Stages = Log2_32(VT.getVectorNumElements());
45437 EVT DpVT = DP.getValueType();
45439 if (Stages > StageBias) {
45440 unsigned DpElems = DpVT.getVectorNumElements();
45442 for (unsigned i = Stages - StageBias; i > 0; --i) {
45443 SmallVector<int, 16> Mask(DpElems, -1);
45444 for (unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
45445 Mask[j] = MaskEnd + j;
45447 SDValue Shuffle =
45448 DAG.getVectorShuffle(DpVT, DL, DP, DAG.getUNDEF(DpVT), Mask);
45449 DP = DAG.getNode(ISD::ADD, DL, DpVT, DP, Shuffle);
45453 // Return the lowest ExtractSizeInBits bits.
45454 EVT ResVT =
45455 EVT::getVectorVT(*DAG.getContext(), ExtractVT,
45456 DpVT.getSizeInBits() / ExtractVT.getSizeInBits());
45457 DP = DAG.getBitcast(ResVT, DP);
45458 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, DP,
45459 Extract->getOperand(1));
45462 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
45463 const X86Subtarget &Subtarget) {
45464 // PSADBW is only supported on SSE2 and up.
45465 if (!Subtarget.hasSSE2())
45466 return SDValue();
45468 EVT ExtractVT = Extract->getValueType(0);
45469 // Verify the type we're extracting is either i32 or i64.
45470 // FIXME: Could support other types, but this is what we have coverage for.
45471 if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
45472 return SDValue();
45474 EVT VT = Extract->getOperand(0).getValueType();
45475 if (!isPowerOf2_32(VT.getVectorNumElements()))
45476 return SDValue();
45478 // Match shuffle + add pyramid.
45479 ISD::NodeType BinOp;
45480 SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
45482 // The operand is expected to be zero extended from i8
45483 // (verified in detectZextAbsDiff).
45484 // In order to convert to i64 and above, additional any/zero/sign
45485 // extend is expected.
45486 // The zero extend from 32 bit has no mathematical effect on the result.
45487 // Also the sign extend is basically zero extend
45488 // (extends the sign bit which is zero).
45489 // So it is correct to skip the sign/zero extend instruction.
45490 if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
45491 Root.getOpcode() == ISD::ZERO_EXTEND ||
45492 Root.getOpcode() == ISD::ANY_EXTEND))
45493 Root = Root.getOperand(0);
45495 // If there was a match, we want Root to be a select that is the root of an
45496 // abs-diff pattern.
45497 if (!Root || Root.getOpcode() != ISD::ABS)
45498 return SDValue();
45500 // Check whether we have an abs-diff pattern feeding into the select.
45501 SDValue Zext0, Zext1;
45502 if (!detectZextAbsDiff(Root, Zext0, Zext1))
45503 return SDValue();
45505 // Create the SAD instruction.
45506 SDLoc DL(Extract);
45507 SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
45509 // If the original vector was wider than 8 elements, sum over the results
45510 // in the SAD vector.
45511 unsigned Stages = Log2_32(VT.getVectorNumElements());
45512 EVT SadVT = SAD.getValueType();
45513 if (Stages > 3) {
45514 unsigned SadElems = SadVT.getVectorNumElements();
45516 for(unsigned i = Stages - 3; i > 0; --i) {
45517 SmallVector<int, 16> Mask(SadElems, -1);
45518 for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
45519 Mask[j] = MaskEnd + j;
45521 SDValue Shuffle =
45522 DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
45523 SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
45527 unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
45528 // Return the lowest ExtractSizeInBits bits.
45529 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
45530 SadVT.getSizeInBits() / ExtractSizeInBits);
45531 SAD = DAG.getBitcast(ResVT, SAD);
45532 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
45533 Extract->getOperand(1));
45536 // If this extract is from a loaded vector value and will be used as an
45537 // integer, that requires a potentially expensive XMM -> GPR transfer.
45538 // Additionally, if we can convert to a scalar integer load, that will likely
45539 // be folded into a subsequent integer op.
45540 // Note: SrcVec might not have a VecVT type, but it must be the same size.
45541 // Note: Unlike the related fold for this in DAGCombiner, this is not limited
45542 // to a single-use of the loaded vector. For the reasons above, we
45543 // expect this to be profitable even if it creates an extra load.
45544 static SDValue
45545 combineExtractFromVectorLoad(SDNode *N, EVT VecVT, SDValue SrcVec, uint64_t Idx,
45546 const SDLoc &dl, SelectionDAG &DAG,
45547 TargetLowering::DAGCombinerInfo &DCI) {
45548 assert(N->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
45549 "Only EXTRACT_VECTOR_ELT supported so far");
45551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45552 EVT VT = N->getValueType(0);
45554 bool LikelyUsedAsVector = any_of(N->uses(), [](SDNode *Use) {
45555 return Use->getOpcode() == ISD::STORE ||
45556 Use->getOpcode() == ISD::INSERT_VECTOR_ELT ||
45557 Use->getOpcode() == ISD::SCALAR_TO_VECTOR;
45560 auto *LoadVec = dyn_cast<LoadSDNode>(SrcVec);
45561 if (LoadVec && ISD::isNormalLoad(LoadVec) && VT.isInteger() &&
45562 VecVT.getVectorElementType() == VT &&
45563 VecVT.getSizeInBits() == SrcVec.getValueSizeInBits() &&
45564 DCI.isAfterLegalizeDAG() && !LikelyUsedAsVector && LoadVec->isSimple()) {
45565 SDValue NewPtr = TLI.getVectorElementPointer(
45566 DAG, LoadVec->getBasePtr(), VecVT, DAG.getVectorIdxConstant(Idx, dl));
45567 unsigned PtrOff = VT.getSizeInBits() * Idx / 8;
45568 MachinePointerInfo MPI = LoadVec->getPointerInfo().getWithOffset(PtrOff);
45569 Align Alignment = commonAlignment(LoadVec->getAlign(), PtrOff);
45570 SDValue Load =
45571 DAG.getLoad(VT, dl, LoadVec->getChain(), NewPtr, MPI, Alignment,
45572 LoadVec->getMemOperand()->getFlags(), LoadVec->getAAInfo());
45573 DAG.makeEquivalentMemoryOrdering(LoadVec, Load);
45574 return Load;
45577 return SDValue();
45580 // Attempt to peek through a target shuffle and extract the scalar from the
45581 // source.
45582 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
45583 TargetLowering::DAGCombinerInfo &DCI,
45584 const X86Subtarget &Subtarget) {
45585 if (DCI.isBeforeLegalizeOps())
45586 return SDValue();
45588 SDLoc dl(N);
45589 SDValue Src = N->getOperand(0);
45590 SDValue Idx = N->getOperand(1);
45592 EVT VT = N->getValueType(0);
45593 EVT SrcVT = Src.getValueType();
45594 EVT SrcSVT = SrcVT.getVectorElementType();
45595 unsigned SrcEltBits = SrcSVT.getSizeInBits();
45596 unsigned NumSrcElts = SrcVT.getVectorNumElements();
45598 // Don't attempt this for boolean mask vectors or unknown extraction indices.
45599 if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
45600 return SDValue();
45602 const APInt &IdxC = N->getConstantOperandAPInt(1);
45603 if (IdxC.uge(NumSrcElts))
45604 return SDValue();
45606 SDValue SrcBC = peekThroughBitcasts(Src);
45608 // Handle extract(bitcast(broadcast(scalar_value))).
45609 if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
45610 SDValue SrcOp = SrcBC.getOperand(0);
45611 EVT SrcOpVT = SrcOp.getValueType();
45612 if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
45613 (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
45614 unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
45615 unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
45616 // TODO support non-zero offsets.
45617 if (Offset == 0) {
45618 SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
45619 SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
45620 return SrcOp;
45625 // If we're extracting a single element from a broadcast load and there are
45626 // no other users, just create a single load.
45627 if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
45628 auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
45629 unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
45630 if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
45631 VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
45632 SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
45633 MemIntr->getBasePtr(),
45634 MemIntr->getPointerInfo(),
45635 MemIntr->getOriginalAlign(),
45636 MemIntr->getMemOperand()->getFlags());
45637 DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
45638 return Load;
45642 // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
45643 // TODO: Move to DAGCombine?
45644 if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
45645 SrcBC.getValueType().isInteger() &&
45646 (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
45647 SrcBC.getScalarValueSizeInBits() ==
45648 SrcBC.getOperand(0).getValueSizeInBits()) {
45649 unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
45650 if (IdxC.ult(Scale)) {
45651 unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
45652 SDValue Scl = SrcBC.getOperand(0);
45653 EVT SclVT = Scl.getValueType();
45654 if (Offset) {
45655 Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
45656 DAG.getShiftAmountConstant(Offset, SclVT, dl));
45658 Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
45659 Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
45660 return Scl;
45664 // Handle extract(truncate(x)) for 0'th index.
45665 // TODO: Treat this as a faux shuffle?
45666 // TODO: When can we use this for general indices?
45667 if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
45668 (SrcVT.getSizeInBits() % 128) == 0) {
45669 Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
45670 MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
45671 return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
45672 Idx);
45675 // We can only legally extract other elements from 128-bit vectors and in
45676 // certain circumstances, depending on SSE-level.
45677 // TODO: Investigate float/double extraction if it will be just stored.
45678 auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
45679 unsigned Idx) {
45680 EVT VecSVT = VecVT.getScalarType();
45681 if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
45682 (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
45683 VecSVT == MVT::i64)) {
45684 unsigned EltSizeInBits = VecSVT.getSizeInBits();
45685 unsigned NumEltsPerLane = 128 / EltSizeInBits;
45686 unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
45687 unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
45688 VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
45689 Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
45690 Idx &= (NumEltsPerLane - 1);
45692 if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
45693 ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
45694 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
45695 DAG.getBitcast(VecVT, Vec),
45696 DAG.getIntPtrConstant(Idx, dl));
45698 if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
45699 (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
45700 unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
45701 return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
45702 DAG.getTargetConstant(Idx, dl, MVT::i8));
45704 return SDValue();
45707 // Resolve the target shuffle inputs and mask.
45708 SmallVector<int, 16> Mask;
45709 SmallVector<SDValue, 2> Ops;
45710 if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
45711 return SDValue();
45713 // Shuffle inputs must be the same size as the result.
45714 if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
45715 return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
45717 return SDValue();
45719 // Attempt to narrow/widen the shuffle mask to the correct size.
45720 if (Mask.size() != NumSrcElts) {
45721 if ((NumSrcElts % Mask.size()) == 0) {
45722 SmallVector<int, 16> ScaledMask;
45723 int Scale = NumSrcElts / Mask.size();
45724 narrowShuffleMaskElts(Scale, Mask, ScaledMask);
45725 Mask = std::move(ScaledMask);
45726 } else if ((Mask.size() % NumSrcElts) == 0) {
45727 // Simplify Mask based on demanded element.
45728 int ExtractIdx = (int)IdxC.getZExtValue();
45729 int Scale = Mask.size() / NumSrcElts;
45730 int Lo = Scale * ExtractIdx;
45731 int Hi = Scale * (ExtractIdx + 1);
45732 for (int i = 0, e = (int)Mask.size(); i != e; ++i)
45733 if (i < Lo || Hi <= i)
45734 Mask[i] = SM_SentinelUndef;
45736 SmallVector<int, 16> WidenedMask;
45737 while (Mask.size() > NumSrcElts &&
45738 canWidenShuffleElements(Mask, WidenedMask))
45739 Mask = std::move(WidenedMask);
45743 // If narrowing/widening failed, see if we can extract+zero-extend.
45744 int ExtractIdx;
45745 EVT ExtractVT;
45746 if (Mask.size() == NumSrcElts) {
45747 ExtractIdx = Mask[IdxC.getZExtValue()];
45748 ExtractVT = SrcVT;
45749 } else {
45750 unsigned Scale = Mask.size() / NumSrcElts;
45751 if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
45752 return SDValue();
45753 unsigned ScaledIdx = Scale * IdxC.getZExtValue();
45754 if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
45755 return SDValue();
45756 ExtractIdx = Mask[ScaledIdx];
45757 EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
45758 ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
45759 assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&
45760 "Failed to widen vector type");
45763 // If the shuffle source element is undef/zero then we can just accept it.
45764 if (ExtractIdx == SM_SentinelUndef)
45765 return DAG.getUNDEF(VT);
45767 if (ExtractIdx == SM_SentinelZero)
45768 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
45769 : DAG.getConstant(0, dl, VT);
45771 SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
45772 ExtractIdx = ExtractIdx % Mask.size();
45773 if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
45774 return DAG.getZExtOrTrunc(V, dl, VT);
45776 if (N->getOpcode() == ISD::EXTRACT_VECTOR_ELT && ExtractVT == SrcVT)
45777 if (SDValue V = combineExtractFromVectorLoad(
45778 N, SrcVT, peekThroughBitcasts(SrcOp), ExtractIdx, dl, DAG, DCI))
45779 return V;
45781 return SDValue();
45784 /// Extracting a scalar FP value from vector element 0 is free, so extract each
45785 /// operand first, then perform the math as a scalar op.
45786 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG,
45787 const X86Subtarget &Subtarget) {
45788 assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
45789 SDValue Vec = ExtElt->getOperand(0);
45790 SDValue Index = ExtElt->getOperand(1);
45791 EVT VT = ExtElt->getValueType(0);
45792 EVT VecVT = Vec.getValueType();
45794 // TODO: If this is a unary/expensive/expand op, allow extraction from a
45795 // non-zero element because the shuffle+scalar op will be cheaper?
45796 if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
45797 return SDValue();
45799 // Vector FP compares don't fit the pattern of FP math ops (propagate, not
45800 // extract, the condition code), so deal with those as a special-case.
45801 if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
45802 EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
45803 if (OpVT != MVT::f32 && OpVT != MVT::f64)
45804 return SDValue();
45806 // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
45807 SDLoc DL(ExtElt);
45808 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
45809 Vec.getOperand(0), Index);
45810 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
45811 Vec.getOperand(1), Index);
45812 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
45815 if (!(VT == MVT::f16 && Subtarget.hasFP16()) && VT != MVT::f32 &&
45816 VT != MVT::f64)
45817 return SDValue();
45819 // Vector FP selects don't fit the pattern of FP math ops (because the
45820 // condition has a different type and we have to change the opcode), so deal
45821 // with those here.
45822 // FIXME: This is restricted to pre type legalization by ensuring the setcc
45823 // has i1 elements. If we loosen this we need to convert vector bool to a
45824 // scalar bool.
45825 if (Vec.getOpcode() == ISD::VSELECT &&
45826 Vec.getOperand(0).getOpcode() == ISD::SETCC &&
45827 Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
45828 Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
45829 // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
45830 SDLoc DL(ExtElt);
45831 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
45832 Vec.getOperand(0).getValueType().getScalarType(),
45833 Vec.getOperand(0), Index);
45834 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
45835 Vec.getOperand(1), Index);
45836 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
45837 Vec.getOperand(2), Index);
45838 return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
45841 // TODO: This switch could include FNEG and the x86-specific FP logic ops
45842 // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
45843 // missed load folding and fma+fneg combining.
45844 switch (Vec.getOpcode()) {
45845 case ISD::FMA: // Begin 3 operands
45846 case ISD::FMAD:
45847 case ISD::FADD: // Begin 2 operands
45848 case ISD::FSUB:
45849 case ISD::FMUL:
45850 case ISD::FDIV:
45851 case ISD::FREM:
45852 case ISD::FCOPYSIGN:
45853 case ISD::FMINNUM:
45854 case ISD::FMAXNUM:
45855 case ISD::FMINNUM_IEEE:
45856 case ISD::FMAXNUM_IEEE:
45857 case ISD::FMAXIMUM:
45858 case ISD::FMINIMUM:
45859 case X86ISD::FMAX:
45860 case X86ISD::FMIN:
45861 case ISD::FABS: // Begin 1 operand
45862 case ISD::FSQRT:
45863 case ISD::FRINT:
45864 case ISD::FCEIL:
45865 case ISD::FTRUNC:
45866 case ISD::FNEARBYINT:
45867 case ISD::FROUNDEVEN:
45868 case ISD::FROUND:
45869 case ISD::FFLOOR:
45870 case X86ISD::FRCP:
45871 case X86ISD::FRSQRT: {
45872 // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
45873 SDLoc DL(ExtElt);
45874 SmallVector<SDValue, 4> ExtOps;
45875 for (SDValue Op : Vec->ops())
45876 ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
45877 return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
45879 default:
45880 return SDValue();
45882 llvm_unreachable("All opcodes should return within switch");
45885 /// Try to convert a vector reduction sequence composed of binops and shuffles
45886 /// into horizontal ops.
45887 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
45888 const X86Subtarget &Subtarget) {
45889 assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
45891 // We need at least SSE2 to anything here.
45892 if (!Subtarget.hasSSE2())
45893 return SDValue();
45895 ISD::NodeType Opc;
45896 SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
45897 {ISD::ADD, ISD::MUL, ISD::FADD}, true);
45898 if (!Rdx)
45899 return SDValue();
45901 SDValue Index = ExtElt->getOperand(1);
45902 assert(isNullConstant(Index) &&
45903 "Reduction doesn't end in an extract from index 0");
45905 EVT VT = ExtElt->getValueType(0);
45906 EVT VecVT = Rdx.getValueType();
45907 if (VecVT.getScalarType() != VT)
45908 return SDValue();
45910 SDLoc DL(ExtElt);
45911 unsigned NumElts = VecVT.getVectorNumElements();
45912 unsigned EltSizeInBits = VecVT.getScalarSizeInBits();
45914 // Extend v4i8/v8i8 vector to v16i8, with undef upper 64-bits.
45915 auto WidenToV16I8 = [&](SDValue V, bool ZeroExtend) {
45916 if (V.getValueType() == MVT::v4i8) {
45917 if (ZeroExtend && Subtarget.hasSSE41()) {
45918 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
45919 DAG.getConstant(0, DL, MVT::v4i32),
45920 DAG.getBitcast(MVT::i32, V),
45921 DAG.getIntPtrConstant(0, DL));
45922 return DAG.getBitcast(MVT::v16i8, V);
45924 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, V,
45925 ZeroExtend ? DAG.getConstant(0, DL, MVT::v4i8)
45926 : DAG.getUNDEF(MVT::v4i8));
45928 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V,
45929 DAG.getUNDEF(MVT::v8i8));
45932 // vXi8 mul reduction - promote to vXi16 mul reduction.
45933 if (Opc == ISD::MUL) {
45934 if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
45935 return SDValue();
45936 if (VecVT.getSizeInBits() >= 128) {
45937 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
45938 SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
45939 SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
45940 Lo = DAG.getBitcast(WideVT, Lo);
45941 Hi = DAG.getBitcast(WideVT, Hi);
45942 Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
45943 while (Rdx.getValueSizeInBits() > 128) {
45944 std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
45945 Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
45947 } else {
45948 Rdx = WidenToV16I8(Rdx, false);
45949 Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
45950 Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
45952 if (NumElts >= 8)
45953 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
45954 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
45955 {4, 5, 6, 7, -1, -1, -1, -1}));
45956 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
45957 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
45958 {2, 3, -1, -1, -1, -1, -1, -1}));
45959 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
45960 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
45961 {1, -1, -1, -1, -1, -1, -1, -1}));
45962 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
45963 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
45966 // vXi8 add reduction - sub 128-bit vector.
45967 if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
45968 Rdx = WidenToV16I8(Rdx, true);
45969 Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
45970 DAG.getConstant(0, DL, MVT::v16i8));
45971 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
45972 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
45975 // Must be a >=128-bit vector with pow2 elements.
45976 if ((VecVT.getSizeInBits() % 128) != 0 || !isPowerOf2_32(NumElts))
45977 return SDValue();
45979 // vXi8 add reduction - sum lo/hi halves then use PSADBW.
45980 if (VT == MVT::i8) {
45981 while (Rdx.getValueSizeInBits() > 128) {
45982 SDValue Lo, Hi;
45983 std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
45984 VecVT = Lo.getValueType();
45985 Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
45987 assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
45989 SDValue Hi = DAG.getVectorShuffle(
45990 MVT::v16i8, DL, Rdx, Rdx,
45991 {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
45992 Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
45993 Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
45994 getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
45995 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
45996 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
45999 // See if we can use vXi8 PSADBW add reduction for larger zext types.
46000 // If the source vector values are 0-255, then we can use PSADBW to
46001 // sum+zext v8i8 subvectors to vXi64, then perform the reduction.
46002 // TODO: See if its worth avoiding vXi16/i32 truncations?
46003 if (Opc == ISD::ADD && NumElts >= 4 && EltSizeInBits >= 16 &&
46004 DAG.computeKnownBits(Rdx).getMaxValue().ule(255) &&
46005 (EltSizeInBits == 16 || Rdx.getOpcode() == ISD::ZERO_EXTEND ||
46006 Subtarget.hasAVX512())) {
46007 if (Rdx.getValueType() == MVT::v8i16) {
46008 Rdx = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Rdx,
46009 DAG.getUNDEF(MVT::v8i16));
46010 } else {
46011 EVT ByteVT = VecVT.changeVectorElementType(MVT::i8);
46012 Rdx = DAG.getNode(ISD::TRUNCATE, DL, ByteVT, Rdx);
46013 if (ByteVT.getSizeInBits() < 128)
46014 Rdx = WidenToV16I8(Rdx, true);
46017 // Build the PSADBW, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
46018 auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46019 ArrayRef<SDValue> Ops) {
46020 MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
46021 SDValue Zero = DAG.getConstant(0, DL, Ops[0].getValueType());
46022 return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops[0], Zero);
46024 MVT SadVT = MVT::getVectorVT(MVT::i64, Rdx.getValueSizeInBits() / 64);
46025 Rdx = SplitOpsAndApply(DAG, Subtarget, DL, SadVT, {Rdx}, PSADBWBuilder);
46027 // TODO: We could truncate to vXi16/vXi32 before performing the reduction.
46028 while (Rdx.getValueSizeInBits() > 128) {
46029 SDValue Lo, Hi;
46030 std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
46031 VecVT = Lo.getValueType();
46032 Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
46034 assert(Rdx.getValueType() == MVT::v2i64 && "v2i64 reduction expected");
46036 if (NumElts > 8) {
46037 SDValue RdxHi = DAG.getVectorShuffle(MVT::v2i64, DL, Rdx, Rdx, {1, -1});
46038 Rdx = DAG.getNode(ISD::ADD, DL, MVT::v2i64, Rdx, RdxHi);
46041 VecVT = MVT::getVectorVT(VT.getSimpleVT(), 128 / VT.getSizeInBits());
46042 Rdx = DAG.getBitcast(VecVT, Rdx);
46043 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46046 // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
46047 if (!shouldUseHorizontalOp(true, DAG, Subtarget))
46048 return SDValue();
46050 unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
46052 // 256-bit horizontal instructions operate on 128-bit chunks rather than
46053 // across the whole vector, so we need an extract + hop preliminary stage.
46054 // This is the only step where the operands of the hop are not the same value.
46055 // TODO: We could extend this to handle 512-bit or even longer vectors.
46056 if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
46057 ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
46058 unsigned NumElts = VecVT.getVectorNumElements();
46059 SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
46060 SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
46061 Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
46062 VecVT = Rdx.getValueType();
46064 if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
46065 !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
46066 return SDValue();
46068 // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
46069 unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
46070 for (unsigned i = 0; i != ReductionSteps; ++i)
46071 Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
46073 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
46076 /// Detect vector gather/scatter index generation and convert it from being a
46077 /// bunch of shuffles and extracts into a somewhat faster sequence.
46078 /// For i686, the best sequence is apparently storing the value and loading
46079 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
46080 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
46081 TargetLowering::DAGCombinerInfo &DCI,
46082 const X86Subtarget &Subtarget) {
46083 if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
46084 return NewOp;
46086 SDValue InputVector = N->getOperand(0);
46087 SDValue EltIdx = N->getOperand(1);
46088 auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
46090 EVT SrcVT = InputVector.getValueType();
46091 EVT VT = N->getValueType(0);
46092 SDLoc dl(InputVector);
46093 bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
46094 unsigned NumSrcElts = SrcVT.getVectorNumElements();
46095 unsigned NumEltBits = VT.getScalarSizeInBits();
46096 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46098 if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
46099 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
46101 // Integer Constant Folding.
46102 if (CIdx && VT.isInteger()) {
46103 APInt UndefVecElts;
46104 SmallVector<APInt, 16> EltBits;
46105 unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
46106 if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
46107 EltBits, /*AllowWholeUndefs*/ true,
46108 /*AllowPartialUndefs*/ false)) {
46109 uint64_t Idx = CIdx->getZExtValue();
46110 if (UndefVecElts[Idx])
46111 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
46112 return DAG.getConstant(EltBits[Idx].zext(NumEltBits), dl, VT);
46115 // Convert extract_element(bitcast(<X x i1>) -> bitcast(extract_subvector()).
46116 // Improves lowering of bool masks on rust which splits them into byte array.
46117 if (InputVector.getOpcode() == ISD::BITCAST && (NumEltBits % 8) == 0) {
46118 SDValue Src = peekThroughBitcasts(InputVector);
46119 if (Src.getValueType().getScalarType() == MVT::i1 &&
46120 TLI.isTypeLegal(Src.getValueType())) {
46121 MVT SubVT = MVT::getVectorVT(MVT::i1, NumEltBits);
46122 SDValue Sub = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Src,
46123 DAG.getIntPtrConstant(CIdx->getZExtValue() * NumEltBits, dl));
46124 return DAG.getBitcast(VT, Sub);
46129 if (IsPextr) {
46130 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumEltBits),
46131 DCI))
46132 return SDValue(N, 0);
46134 // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
46135 if ((InputVector.getOpcode() == X86ISD::PINSRB ||
46136 InputVector.getOpcode() == X86ISD::PINSRW) &&
46137 InputVector.getOperand(2) == EltIdx) {
46138 assert(SrcVT == InputVector.getOperand(0).getValueType() &&
46139 "Vector type mismatch");
46140 SDValue Scl = InputVector.getOperand(1);
46141 Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
46142 return DAG.getZExtOrTrunc(Scl, dl, VT);
46145 // TODO - Remove this once we can handle the implicit zero-extension of
46146 // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
46147 // combineBasicSADPattern.
46148 return SDValue();
46151 // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
46152 if (VT == MVT::i64 && SrcVT == MVT::v1i64 &&
46153 InputVector.getOpcode() == ISD::BITCAST &&
46154 InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
46155 isNullConstant(EltIdx) && InputVector.hasOneUse())
46156 return DAG.getBitcast(VT, InputVector);
46158 // Detect mmx to i32 conversion through a v2i32 elt extract.
46159 if (VT == MVT::i32 && SrcVT == MVT::v2i32 &&
46160 InputVector.getOpcode() == ISD::BITCAST &&
46161 InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
46162 isNullConstant(EltIdx) && InputVector.hasOneUse())
46163 return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32,
46164 InputVector.getOperand(0));
46166 // Check whether this extract is the root of a sum of absolute differences
46167 // pattern. This has to be done here because we really want it to happen
46168 // pre-legalization,
46169 if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
46170 return SAD;
46172 if (SDValue VPDPBUSD = combineVPDPBUSDPattern(N, DAG, Subtarget))
46173 return VPDPBUSD;
46175 // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
46176 if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
46177 return Cmp;
46179 // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
46180 if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
46181 return MinMax;
46183 // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
46184 if (SDValue V = combineArithReduction(N, DAG, Subtarget))
46185 return V;
46187 if (SDValue V = scalarizeExtEltFP(N, DAG, Subtarget))
46188 return V;
46190 if (CIdx)
46191 if (SDValue V = combineExtractFromVectorLoad(
46192 N, InputVector.getValueType(), InputVector, CIdx->getZExtValue(),
46193 dl, DAG, DCI))
46194 return V;
46196 // Attempt to extract a i1 element by using MOVMSK to extract the signbits
46197 // and then testing the relevant element.
46199 // Note that we only combine extracts on the *same* result number, i.e.
46200 // t0 = merge_values a0, a1, a2, a3
46201 // i1 = extract_vector_elt t0, Constant:i64<2>
46202 // i1 = extract_vector_elt t0, Constant:i64<3>
46203 // but not
46204 // i1 = extract_vector_elt t0:1, Constant:i64<2>
46205 // since the latter would need its own MOVMSK.
46206 if (SrcVT.getScalarType() == MVT::i1) {
46207 bool IsVar = !CIdx;
46208 SmallVector<SDNode *, 16> BoolExtracts;
46209 unsigned ResNo = InputVector.getResNo();
46210 auto IsBoolExtract = [&BoolExtracts, &ResNo, &IsVar](SDNode *Use) {
46211 if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
46212 Use->getOperand(0).getResNo() == ResNo &&
46213 Use->getValueType(0) == MVT::i1) {
46214 BoolExtracts.push_back(Use);
46215 IsVar |= !isa<ConstantSDNode>(Use->getOperand(1));
46216 return true;
46218 return false;
46220 // TODO: Can we drop the oneuse check for constant extracts?
46221 if (all_of(InputVector->uses(), IsBoolExtract) &&
46222 (IsVar || BoolExtracts.size() > 1)) {
46223 EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
46224 if (SDValue BC =
46225 combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
46226 for (SDNode *Use : BoolExtracts) {
46227 // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
46228 // Mask = 1 << MaskIdx
46229 SDValue MaskIdx = DAG.getZExtOrTrunc(Use->getOperand(1), dl, MVT::i8);
46230 SDValue MaskBit = DAG.getConstant(1, dl, BCVT);
46231 SDValue Mask = DAG.getNode(ISD::SHL, dl, BCVT, MaskBit, MaskIdx);
46232 SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
46233 Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
46234 DCI.CombineTo(Use, Res);
46236 return SDValue(N, 0);
46241 // Attempt to fold extract(trunc(x),c) -> trunc(extract(x,c)).
46242 if (CIdx && InputVector.getOpcode() == ISD::TRUNCATE) {
46243 SDValue TruncSrc = InputVector.getOperand(0);
46244 EVT TruncSVT = TruncSrc.getValueType().getScalarType();
46245 if (DCI.isBeforeLegalize() && TLI.isTypeLegal(TruncSVT)) {
46246 SDValue NewExt =
46247 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TruncSVT, TruncSrc, EltIdx);
46248 return DAG.getAnyExtOrTrunc(NewExt, dl, VT);
46252 return SDValue();
46255 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
46256 // This is more or less the reverse of combineBitcastvxi1.
46257 static SDValue combineToExtendBoolVectorInReg(
46258 unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N0, SelectionDAG &DAG,
46259 TargetLowering::DAGCombinerInfo &DCI, const X86Subtarget &Subtarget) {
46260 if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
46261 Opcode != ISD::ANY_EXTEND)
46262 return SDValue();
46263 if (!DCI.isBeforeLegalizeOps())
46264 return SDValue();
46265 if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
46266 return SDValue();
46268 EVT SVT = VT.getScalarType();
46269 EVT InSVT = N0.getValueType().getScalarType();
46270 unsigned EltSizeInBits = SVT.getSizeInBits();
46272 // Input type must be extending a bool vector (bit-casted from a scalar
46273 // integer) to legal integer types.
46274 if (!VT.isVector())
46275 return SDValue();
46276 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
46277 return SDValue();
46278 if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
46279 return SDValue();
46281 SDValue N00 = N0.getOperand(0);
46282 EVT SclVT = N00.getValueType();
46283 if (!SclVT.isScalarInteger())
46284 return SDValue();
46286 SDValue Vec;
46287 SmallVector<int> ShuffleMask;
46288 unsigned NumElts = VT.getVectorNumElements();
46289 assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
46291 // Broadcast the scalar integer to the vector elements.
46292 if (NumElts > EltSizeInBits) {
46293 // If the scalar integer is greater than the vector element size, then we
46294 // must split it down into sub-sections for broadcasting. For example:
46295 // i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
46296 // i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
46297 assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
46298 unsigned Scale = NumElts / EltSizeInBits;
46299 EVT BroadcastVT = EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
46300 bool UseBroadcast = Subtarget.hasInt256() &&
46301 (!BroadcastVT.is128BitVector() || isa<LoadSDNode>(N00));
46302 Vec = UseBroadcast
46303 ? DAG.getSplat(BroadcastVT, DL, N00)
46304 : DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
46305 Vec = DAG.getBitcast(VT, Vec);
46307 for (unsigned i = 0; i != Scale; ++i) {
46308 int Offset = UseBroadcast ? (i * EltSizeInBits) : 0;
46309 ShuffleMask.append(EltSizeInBits, i + Offset);
46311 Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
46312 } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
46313 (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
46314 // If we have register broadcast instructions, use the scalar size as the
46315 // element type for the shuffle. Then cast to the wider element type. The
46316 // widened bits won't be used, and this might allow the use of a broadcast
46317 // load.
46318 assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
46319 EVT BroadcastVT = EVT::getVectorVT(*DAG.getContext(), SclVT,
46320 (NumElts * EltSizeInBits) / NumElts);
46321 Vec = DAG.getBitcast(VT, DAG.getSplat(BroadcastVT, DL, N00));
46322 } else {
46323 // For smaller scalar integers, we can simply any-extend it to the vector
46324 // element size (we don't care about the upper bits) and broadcast it to all
46325 // elements.
46326 Vec = DAG.getSplat(VT, DL, DAG.getAnyExtOrTrunc(N00, DL, SVT));
46329 // Now, mask the relevant bit in each element.
46330 SmallVector<SDValue, 32> Bits;
46331 for (unsigned i = 0; i != NumElts; ++i) {
46332 int BitIdx = (i % EltSizeInBits);
46333 APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
46334 Bits.push_back(DAG.getConstant(Bit, DL, SVT));
46336 SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
46337 Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
46339 // Compare against the bitmask and extend the result.
46340 EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
46341 Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
46342 Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
46344 // For SEXT, this is now done, otherwise shift the result down for
46345 // zero-extension.
46346 if (Opcode == ISD::SIGN_EXTEND)
46347 return Vec;
46348 return DAG.getNode(ISD::SRL, DL, VT, Vec,
46349 DAG.getConstant(EltSizeInBits - 1, DL, VT));
46352 /// If a vector select has an operand that is -1 or 0, try to simplify the
46353 /// select to a bitwise logic operation.
46354 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
46355 static SDValue
46356 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG, const SDLoc &DL,
46357 TargetLowering::DAGCombinerInfo &DCI,
46358 const X86Subtarget &Subtarget) {
46359 SDValue Cond = N->getOperand(0);
46360 SDValue LHS = N->getOperand(1);
46361 SDValue RHS = N->getOperand(2);
46362 EVT VT = LHS.getValueType();
46363 EVT CondVT = Cond.getValueType();
46364 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46366 if (N->getOpcode() != ISD::VSELECT)
46367 return SDValue();
46369 assert(CondVT.isVector() && "Vector select expects a vector selector!");
46371 // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
46372 // TODO: Can we assert that both operands are not zeros (because that should
46373 // get simplified at node creation time)?
46374 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
46375 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
46377 // If both inputs are 0/undef, create a complete zero vector.
46378 // FIXME: As noted above this should be handled by DAGCombiner/getNode.
46379 if (TValIsAllZeros && FValIsAllZeros) {
46380 if (VT.isFloatingPoint())
46381 return DAG.getConstantFP(0.0, DL, VT);
46382 return DAG.getConstant(0, DL, VT);
46385 // To use the condition operand as a bitwise mask, it must have elements that
46386 // are the same size as the select elements. Ie, the condition operand must
46387 // have already been promoted from the IR select condition type <N x i1>.
46388 // Don't check if the types themselves are equal because that excludes
46389 // vector floating-point selects.
46390 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
46391 return SDValue();
46393 // Try to invert the condition if true value is not all 1s and false value is
46394 // not all 0s. Only do this if the condition has one use.
46395 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
46396 if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
46397 // Check if the selector will be produced by CMPP*/PCMP*.
46398 Cond.getOpcode() == ISD::SETCC &&
46399 // Check if SETCC has already been promoted.
46400 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
46401 CondVT) {
46402 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
46404 if (TValIsAllZeros || FValIsAllOnes) {
46405 SDValue CC = Cond.getOperand(2);
46406 ISD::CondCode NewCC = ISD::getSetCCInverse(
46407 cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
46408 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
46409 NewCC);
46410 std::swap(LHS, RHS);
46411 TValIsAllOnes = FValIsAllOnes;
46412 FValIsAllZeros = TValIsAllZeros;
46416 // Cond value must be 'sign splat' to be converted to a logical op.
46417 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
46418 return SDValue();
46420 // vselect Cond, 111..., 000... -> Cond
46421 if (TValIsAllOnes && FValIsAllZeros)
46422 return DAG.getBitcast(VT, Cond);
46424 if (!TLI.isTypeLegal(CondVT))
46425 return SDValue();
46427 // vselect Cond, 111..., X -> or Cond, X
46428 if (TValIsAllOnes) {
46429 SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
46430 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
46431 return DAG.getBitcast(VT, Or);
46434 // vselect Cond, X, 000... -> and Cond, X
46435 if (FValIsAllZeros) {
46436 SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
46437 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
46438 return DAG.getBitcast(VT, And);
46441 // vselect Cond, 000..., X -> andn Cond, X
46442 if (TValIsAllZeros) {
46443 SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
46444 SDValue AndN;
46445 // The canonical form differs for i1 vectors - x86andnp is not used
46446 if (CondVT.getScalarType() == MVT::i1)
46447 AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
46448 CastRHS);
46449 else
46450 AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
46451 return DAG.getBitcast(VT, AndN);
46454 return SDValue();
46457 /// If both arms of a vector select are concatenated vectors, split the select,
46458 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
46459 /// vselect Cond, (concat T0, T1), (concat F0, F1) -->
46460 /// concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
46461 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG, const SDLoc &DL,
46462 const X86Subtarget &Subtarget) {
46463 unsigned Opcode = N->getOpcode();
46464 if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
46465 return SDValue();
46467 // TODO: Split 512-bit vectors too?
46468 EVT VT = N->getValueType(0);
46469 if (!VT.is256BitVector())
46470 return SDValue();
46472 // TODO: Split as long as any 2 of the 3 operands are concatenated?
46473 SDValue Cond = N->getOperand(0);
46474 SDValue TVal = N->getOperand(1);
46475 SDValue FVal = N->getOperand(2);
46476 if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
46477 !isFreeToSplitVector(TVal.getNode(), DAG) ||
46478 !isFreeToSplitVector(FVal.getNode(), DAG))
46479 return SDValue();
46481 auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
46482 ArrayRef<SDValue> Ops) {
46483 return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
46485 return SplitOpsAndApply(DAG, Subtarget, DL, VT, {Cond, TVal, FVal}, makeBlend,
46486 /*CheckBWI*/ false);
46489 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG,
46490 const SDLoc &DL) {
46491 SDValue Cond = N->getOperand(0);
46492 SDValue LHS = N->getOperand(1);
46493 SDValue RHS = N->getOperand(2);
46495 auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
46496 auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
46497 if (!TrueC || !FalseC)
46498 return SDValue();
46500 // Don't do this for crazy integer types.
46501 EVT VT = N->getValueType(0);
46502 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
46503 return SDValue();
46505 // We're going to use the condition bit in math or logic ops. We could allow
46506 // this with a wider condition value (post-legalization it becomes an i8),
46507 // but if nothing is creating selects that late, it doesn't matter.
46508 if (Cond.getValueType() != MVT::i1)
46509 return SDValue();
46511 // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
46512 // 3, 5, or 9 with i32/i64, so those get transformed too.
46513 // TODO: For constants that overflow or do not differ by power-of-2 or small
46514 // multiplier, convert to 'and' + 'add'.
46515 const APInt &TrueVal = TrueC->getAPIntValue();
46516 const APInt &FalseVal = FalseC->getAPIntValue();
46518 // We have a more efficient lowering for "(X == 0) ? Y : -1" using SBB.
46519 if ((TrueVal.isAllOnes() || FalseVal.isAllOnes()) &&
46520 Cond.getOpcode() == ISD::SETCC && isNullConstant(Cond.getOperand(1))) {
46521 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
46522 if (CC == ISD::SETEQ || CC == ISD::SETNE)
46523 return SDValue();
46526 bool OV;
46527 APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
46528 if (OV)
46529 return SDValue();
46531 APInt AbsDiff = Diff.abs();
46532 if (AbsDiff.isPowerOf2() ||
46533 ((VT == MVT::i32 || VT == MVT::i64) &&
46534 (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
46536 // We need a positive multiplier constant for shift/LEA codegen. The 'not'
46537 // of the condition can usually be folded into a compare predicate, but even
46538 // without that, the sequence should be cheaper than a CMOV alternative.
46539 if (TrueVal.slt(FalseVal)) {
46540 Cond = DAG.getNOT(DL, Cond, MVT::i1);
46541 std::swap(TrueC, FalseC);
46544 // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
46545 SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
46547 // Multiply condition by the difference if non-one.
46548 if (!AbsDiff.isOne())
46549 R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
46551 // Add the base if non-zero.
46552 if (!FalseC->isZero())
46553 R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
46555 return R;
46558 return SDValue();
46561 /// If this is a *dynamic* select (non-constant condition) and we can match
46562 /// this node with one of the variable blend instructions, restructure the
46563 /// condition so that blends can use the high (sign) bit of each element.
46564 /// This function will also call SimplifyDemandedBits on already created
46565 /// BLENDV to perform additional simplifications.
46566 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
46567 const SDLoc &DL,
46568 TargetLowering::DAGCombinerInfo &DCI,
46569 const X86Subtarget &Subtarget) {
46570 SDValue Cond = N->getOperand(0);
46571 if ((N->getOpcode() != ISD::VSELECT &&
46572 N->getOpcode() != X86ISD::BLENDV) ||
46573 ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
46574 return SDValue();
46576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46577 unsigned BitWidth = Cond.getScalarValueSizeInBits();
46578 EVT VT = N->getValueType(0);
46580 // We can only handle the cases where VSELECT is directly legal on the
46581 // subtarget. We custom lower VSELECT nodes with constant conditions and
46582 // this makes it hard to see whether a dynamic VSELECT will correctly
46583 // lower, so we both check the operation's status and explicitly handle the
46584 // cases where a *dynamic* blend will fail even though a constant-condition
46585 // blend could be custom lowered.
46586 // FIXME: We should find a better way to handle this class of problems.
46587 // Potentially, we should combine constant-condition vselect nodes
46588 // pre-legalization into shuffles and not mark as many types as custom
46589 // lowered.
46590 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
46591 return SDValue();
46592 // FIXME: We don't support i16-element blends currently. We could and
46593 // should support them by making *all* the bits in the condition be set
46594 // rather than just the high bit and using an i8-element blend.
46595 if (VT.getVectorElementType() == MVT::i16)
46596 return SDValue();
46597 // Dynamic blending was only available from SSE4.1 onward.
46598 if (VT.is128BitVector() && !Subtarget.hasSSE41())
46599 return SDValue();
46600 // Byte blends are only available in AVX2
46601 if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
46602 return SDValue();
46603 // There are no 512-bit blend instructions that use sign bits.
46604 if (VT.is512BitVector())
46605 return SDValue();
46607 // Don't optimize before the condition has been transformed to a legal type
46608 // and don't ever optimize vector selects that map to AVX512 mask-registers.
46609 if (BitWidth < 8 || BitWidth > 64)
46610 return SDValue();
46612 auto OnlyUsedAsSelectCond = [](SDValue Cond) {
46613 for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
46614 UI != UE; ++UI)
46615 if ((UI->getOpcode() != ISD::VSELECT &&
46616 UI->getOpcode() != X86ISD::BLENDV) ||
46617 UI.getOperandNo() != 0)
46618 return false;
46620 return true;
46623 APInt DemandedBits(APInt::getSignMask(BitWidth));
46625 if (OnlyUsedAsSelectCond(Cond)) {
46626 KnownBits Known;
46627 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
46628 !DCI.isBeforeLegalizeOps());
46629 if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
46630 return SDValue();
46632 // If we changed the computation somewhere in the DAG, this change will
46633 // affect all users of Cond. Update all the nodes so that we do not use
46634 // the generic VSELECT anymore. Otherwise, we may perform wrong
46635 // optimizations as we messed with the actual expectation for the vector
46636 // boolean values.
46637 for (SDNode *U : Cond->uses()) {
46638 if (U->getOpcode() == X86ISD::BLENDV)
46639 continue;
46641 SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
46642 Cond, U->getOperand(1), U->getOperand(2));
46643 DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
46644 DCI.AddToWorklist(U);
46646 DCI.CommitTargetLoweringOpt(TLO);
46647 return SDValue(N, 0);
46650 // Otherwise we can still at least try to simplify multiple use bits.
46651 if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
46652 return DAG.getNode(X86ISD::BLENDV, DL, N->getValueType(0), V,
46653 N->getOperand(1), N->getOperand(2));
46655 return SDValue();
46658 // Try to match:
46659 // (or (and (M, (sub 0, X)), (pandn M, X)))
46660 // which is a special case of:
46661 // (select M, (sub 0, X), X)
46662 // Per:
46663 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
46664 // We know that, if fNegate is 0 or 1:
46665 // (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
46667 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
46668 // ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
46669 // ( M ? -X : X) == ((X ^ M ) + (M & 1))
46670 // This lets us transform our vselect to:
46671 // (add (xor X, M), (and M, 1))
46672 // And further to:
46673 // (sub (xor X, M), M)
46674 static SDValue combineLogicBlendIntoConditionalNegate(
46675 EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
46676 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
46677 EVT MaskVT = Mask.getValueType();
46678 assert(MaskVT.isInteger() &&
46679 DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
46680 "Mask must be zero/all-bits");
46682 if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
46683 return SDValue();
46684 if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
46685 return SDValue();
46687 auto IsNegV = [](SDNode *N, SDValue V) {
46688 return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
46689 ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
46692 SDValue V;
46693 if (IsNegV(Y.getNode(), X))
46694 V = X;
46695 else if (IsNegV(X.getNode(), Y))
46696 V = Y;
46697 else
46698 return SDValue();
46700 SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
46701 SDValue SubOp2 = Mask;
46703 // If the negate was on the false side of the select, then
46704 // the operands of the SUB need to be swapped. PR 27251.
46705 // This is because the pattern being matched above is
46706 // (vselect M, (sub (0, X), X) -> (sub (xor X, M), M)
46707 // but if the pattern matched was
46708 // (vselect M, X, (sub (0, X))), that is really negation of the pattern
46709 // above, -(vselect M, (sub 0, X), X), and therefore the replacement
46710 // pattern also needs to be a negation of the replacement pattern above.
46711 // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
46712 // sub accomplishes the negation of the replacement pattern.
46713 if (V == Y)
46714 std::swap(SubOp1, SubOp2);
46716 SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
46717 return DAG.getBitcast(VT, Res);
46720 static SDValue commuteSelect(SDNode *N, SelectionDAG &DAG, const SDLoc &DL,
46721 const X86Subtarget &Subtarget) {
46722 if (!Subtarget.hasAVX512())
46723 return SDValue();
46724 if (N->getOpcode() != ISD::VSELECT)
46725 return SDValue();
46727 SDValue Cond = N->getOperand(0);
46728 SDValue LHS = N->getOperand(1);
46729 SDValue RHS = N->getOperand(2);
46731 if (canCombineAsMaskOperation(LHS, Subtarget))
46732 return SDValue();
46734 if (!canCombineAsMaskOperation(RHS, Subtarget))
46735 return SDValue();
46737 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
46738 return SDValue();
46740 // Commute LHS and RHS to create opportunity to select mask instruction.
46741 // (vselect M, L, R) -> (vselect ~M, R, L)
46742 ISD::CondCode NewCC =
46743 ISD::getSetCCInverse(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
46744 Cond.getOperand(0).getValueType());
46745 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), Cond.getOperand(0),
46746 Cond.getOperand(1), NewCC);
46747 return DAG.getSelect(DL, LHS.getValueType(), Cond, RHS, LHS);
46750 /// Do target-specific dag combines on SELECT and VSELECT nodes.
46751 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
46752 TargetLowering::DAGCombinerInfo &DCI,
46753 const X86Subtarget &Subtarget) {
46754 SDLoc DL(N);
46755 SDValue Cond = N->getOperand(0);
46756 SDValue LHS = N->getOperand(1);
46757 SDValue RHS = N->getOperand(2);
46759 // Try simplification again because we use this function to optimize
46760 // BLENDV nodes that are not handled by the generic combiner.
46761 if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
46762 return V;
46764 // When avx512 is available the lhs operand of select instruction can be
46765 // folded with mask instruction, while the rhs operand can't. Commute the
46766 // lhs and rhs of the select instruction to create the opportunity of
46767 // folding.
46768 if (SDValue V = commuteSelect(N, DAG, DL, Subtarget))
46769 return V;
46771 EVT VT = LHS.getValueType();
46772 EVT CondVT = Cond.getValueType();
46773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46774 bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
46776 // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
46777 // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
46778 // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
46779 if (CondVT.isVector() && CondVT.isInteger() &&
46780 CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
46781 (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
46782 DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
46783 if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
46784 DL, DAG, Subtarget))
46785 return V;
46787 // Convert vselects with constant condition into shuffles.
46788 if (CondConstantVector && DCI.isBeforeLegalizeOps() &&
46789 (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::BLENDV)) {
46790 SmallVector<int, 64> Mask;
46791 if (createShuffleMaskFromVSELECT(Mask, Cond,
46792 N->getOpcode() == X86ISD::BLENDV))
46793 return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
46796 // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
46797 // by forcing the unselected elements to zero.
46798 // TODO: Can we handle more shuffles with this?
46799 if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
46800 LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
46801 LHS.hasOneUse() && RHS.hasOneUse()) {
46802 MVT SimpleVT = VT.getSimpleVT();
46803 SmallVector<SDValue, 1> LHSOps, RHSOps;
46804 SmallVector<int, 64> LHSMask, RHSMask, CondMask;
46805 if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
46806 getTargetShuffleMask(LHS, true, LHSOps, LHSMask) &&
46807 getTargetShuffleMask(RHS, true, RHSOps, RHSMask)) {
46808 int NumElts = VT.getVectorNumElements();
46809 for (int i = 0; i != NumElts; ++i) {
46810 // getConstVector sets negative shuffle mask values as undef, so ensure
46811 // we hardcode SM_SentinelZero values to zero (0x80).
46812 if (CondMask[i] < NumElts) {
46813 LHSMask[i] = isUndefOrZero(LHSMask[i]) ? 0x80 : LHSMask[i];
46814 RHSMask[i] = 0x80;
46815 } else {
46816 LHSMask[i] = 0x80;
46817 RHSMask[i] = isUndefOrZero(RHSMask[i]) ? 0x80 : RHSMask[i];
46820 LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
46821 getConstVector(LHSMask, SimpleVT, DAG, DL, true));
46822 RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
46823 getConstVector(RHSMask, SimpleVT, DAG, DL, true));
46824 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
46828 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
46829 // instructions match the semantics of the common C idiom x<y?x:y but not
46830 // x<=y?x:y, because of how they handle negative zero (which can be
46831 // ignored in unsafe-math mode).
46832 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
46833 if ((Cond.getOpcode() == ISD::SETCC ||
46834 Cond.getOpcode() == ISD::STRICT_FSETCCS) &&
46835 VT.isFloatingPoint() && VT != MVT::f80 && VT != MVT::f128 &&
46836 !isSoftF16(VT, Subtarget) && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
46837 (Subtarget.hasSSE2() ||
46838 (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
46839 bool IsStrict = Cond->isStrictFPOpcode();
46840 ISD::CondCode CC =
46841 cast<CondCodeSDNode>(Cond.getOperand(IsStrict ? 3 : 2))->get();
46842 SDValue Op0 = Cond.getOperand(IsStrict ? 1 : 0);
46843 SDValue Op1 = Cond.getOperand(IsStrict ? 2 : 1);
46845 unsigned Opcode = 0;
46846 // Check for x CC y ? x : y.
46847 if (DAG.isEqualTo(LHS, Op0) && DAG.isEqualTo(RHS, Op1)) {
46848 switch (CC) {
46849 default: break;
46850 case ISD::SETULT:
46851 // Converting this to a min would handle NaNs incorrectly, and swapping
46852 // the operands would cause it to handle comparisons between positive
46853 // and negative zero incorrectly.
46854 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
46855 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46856 !(DAG.isKnownNeverZeroFloat(LHS) ||
46857 DAG.isKnownNeverZeroFloat(RHS)))
46858 break;
46859 std::swap(LHS, RHS);
46861 Opcode = X86ISD::FMIN;
46862 break;
46863 case ISD::SETOLE:
46864 // Converting this to a min would handle comparisons between positive
46865 // and negative zero incorrectly.
46866 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46867 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
46868 break;
46869 Opcode = X86ISD::FMIN;
46870 break;
46871 case ISD::SETULE:
46872 // Converting this to a min would handle both negative zeros and NaNs
46873 // incorrectly, but we can swap the operands to fix both.
46874 std::swap(LHS, RHS);
46875 [[fallthrough]];
46876 case ISD::SETOLT:
46877 case ISD::SETLT:
46878 case ISD::SETLE:
46879 Opcode = X86ISD::FMIN;
46880 break;
46882 case ISD::SETOGE:
46883 // Converting this to a max would handle comparisons between positive
46884 // and negative zero incorrectly.
46885 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46886 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
46887 break;
46888 Opcode = X86ISD::FMAX;
46889 break;
46890 case ISD::SETUGT:
46891 // Converting this to a max would handle NaNs incorrectly, and swapping
46892 // the operands would cause it to handle comparisons between positive
46893 // and negative zero incorrectly.
46894 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
46895 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46896 !(DAG.isKnownNeverZeroFloat(LHS) ||
46897 DAG.isKnownNeverZeroFloat(RHS)))
46898 break;
46899 std::swap(LHS, RHS);
46901 Opcode = X86ISD::FMAX;
46902 break;
46903 case ISD::SETUGE:
46904 // Converting this to a max would handle both negative zeros and NaNs
46905 // incorrectly, but we can swap the operands to fix both.
46906 std::swap(LHS, RHS);
46907 [[fallthrough]];
46908 case ISD::SETOGT:
46909 case ISD::SETGT:
46910 case ISD::SETGE:
46911 Opcode = X86ISD::FMAX;
46912 break;
46914 // Check for x CC y ? y : x -- a min/max with reversed arms.
46915 } else if (DAG.isEqualTo(LHS, Op1) && DAG.isEqualTo(RHS, Op0)) {
46916 switch (CC) {
46917 default: break;
46918 case ISD::SETOGE:
46919 // Converting this to a min would handle comparisons between positive
46920 // and negative zero incorrectly, and swapping the operands would
46921 // cause it to handle NaNs incorrectly.
46922 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46923 !(DAG.isKnownNeverZeroFloat(LHS) ||
46924 DAG.isKnownNeverZeroFloat(RHS))) {
46925 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
46926 break;
46927 std::swap(LHS, RHS);
46929 Opcode = X86ISD::FMIN;
46930 break;
46931 case ISD::SETUGT:
46932 // Converting this to a min would handle NaNs incorrectly.
46933 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
46934 break;
46935 Opcode = X86ISD::FMIN;
46936 break;
46937 case ISD::SETUGE:
46938 // Converting this to a min would handle both negative zeros and NaNs
46939 // incorrectly, but we can swap the operands to fix both.
46940 std::swap(LHS, RHS);
46941 [[fallthrough]];
46942 case ISD::SETOGT:
46943 case ISD::SETGT:
46944 case ISD::SETGE:
46945 Opcode = X86ISD::FMIN;
46946 break;
46948 case ISD::SETULT:
46949 // Converting this to a max would handle NaNs incorrectly.
46950 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
46951 break;
46952 Opcode = X86ISD::FMAX;
46953 break;
46954 case ISD::SETOLE:
46955 // Converting this to a max would handle comparisons between positive
46956 // and negative zero incorrectly, and swapping the operands would
46957 // cause it to handle NaNs incorrectly.
46958 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
46959 !DAG.isKnownNeverZeroFloat(LHS) &&
46960 !DAG.isKnownNeverZeroFloat(RHS)) {
46961 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
46962 break;
46963 std::swap(LHS, RHS);
46965 Opcode = X86ISD::FMAX;
46966 break;
46967 case ISD::SETULE:
46968 // Converting this to a max would handle both negative zeros and NaNs
46969 // incorrectly, but we can swap the operands to fix both.
46970 std::swap(LHS, RHS);
46971 [[fallthrough]];
46972 case ISD::SETOLT:
46973 case ISD::SETLT:
46974 case ISD::SETLE:
46975 Opcode = X86ISD::FMAX;
46976 break;
46980 if (Opcode) {
46981 if (IsStrict) {
46982 SDValue Ret = DAG.getNode(Opcode == X86ISD::FMIN ? X86ISD::STRICT_FMIN
46983 : X86ISD::STRICT_FMAX,
46984 DL, {N->getValueType(0), MVT::Other},
46985 {Cond.getOperand(0), LHS, RHS});
46986 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Ret.getValue(1));
46987 return Ret;
46989 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
46993 // Some mask scalar intrinsics rely on checking if only one bit is set
46994 // and implement it in C code like this:
46995 // A[0] = (U & 1) ? A[0] : W[0];
46996 // This creates some redundant instructions that break pattern matching.
46997 // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
46998 if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
46999 Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
47000 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47001 SDValue AndNode = Cond.getOperand(0);
47002 if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
47003 isNullConstant(Cond.getOperand(1)) &&
47004 isOneConstant(AndNode.getOperand(1))) {
47005 // LHS and RHS swapped due to
47006 // setcc outputting 1 when AND resulted in 0 and vice versa.
47007 AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
47008 return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
47012 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
47013 // lowering on KNL. In this case we convert it to
47014 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
47015 // The same situation all vectors of i8 and i16 without BWI.
47016 // Make sure we extend these even before type legalization gets a chance to
47017 // split wide vectors.
47018 // Since SKX these selects have a proper lowering.
47019 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
47020 CondVT.getVectorElementType() == MVT::i1 &&
47021 (VT.getVectorElementType() == MVT::i8 ||
47022 VT.getVectorElementType() == MVT::i16)) {
47023 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
47024 return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
47027 // AVX512 - Extend select to merge with target shuffle.
47028 // select(mask, extract_subvector(shuffle(x)), y) -->
47029 // extract_subvector(select(widen(mask), shuffle(x), widen(y)))
47030 // TODO - support non target shuffles as well with canCombineAsMaskOperation.
47031 if (Subtarget.hasAVX512() && CondVT.isVector() &&
47032 CondVT.getVectorElementType() == MVT::i1) {
47033 auto SelectableOp = [&TLI](SDValue Op, SDValue Alt) {
47034 return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
47035 isTargetShuffle(Op.getOperand(0).getOpcode()) &&
47036 isNullConstant(Op.getOperand(1)) &&
47037 TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
47038 Op.hasOneUse() && Op.getOperand(0).hasOneUse() &&
47039 (Op.getOperand(0).getOpcode() != X86ISD::VPERMV3 ||
47040 ISD::isBuildVectorAllZeros(Alt.getNode()));
47043 bool SelectableLHS = SelectableOp(LHS, RHS);
47044 bool SelectableRHS = SelectableOp(RHS, LHS);
47045 if (SelectableLHS || SelectableRHS) {
47046 EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
47047 : RHS.getOperand(0).getValueType();
47048 EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
47049 LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
47050 VT.getSizeInBits());
47051 RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
47052 VT.getSizeInBits());
47053 Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
47054 DAG.getUNDEF(SrcCondVT), Cond,
47055 DAG.getIntPtrConstant(0, DL));
47056 SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
47057 return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
47061 if (SDValue V = combineSelectOfTwoConstants(N, DAG, DL))
47062 return V;
47064 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
47065 Cond.hasOneUse()) {
47066 EVT CondVT = Cond.getValueType();
47067 SDValue Cond0 = Cond.getOperand(0);
47068 SDValue Cond1 = Cond.getOperand(1);
47069 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
47071 // Canonicalize min/max:
47072 // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
47073 // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
47074 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
47075 // the need for an extra compare against zero. e.g.
47076 // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
47077 // subl %esi, %edi
47078 // testl %edi, %edi
47079 // movl $0, %eax
47080 // cmovgl %edi, %eax
47081 // =>
47082 // xorl %eax, %eax
47083 // subl %esi, $edi
47084 // cmovsl %eax, %edi
47086 // We can also canonicalize
47087 // (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
47088 // (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
47089 // This allows the use of a test instruction for the compare.
47090 if (LHS == Cond0 && RHS == Cond1) {
47091 if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
47092 (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
47093 ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
47094 Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
47095 return DAG.getSelect(DL, VT, Cond, LHS, RHS);
47097 if (CC == ISD::SETUGT && isOneConstant(RHS)) {
47098 ISD::CondCode NewCC = ISD::SETUGE;
47099 Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
47100 return DAG.getSelect(DL, VT, Cond, LHS, RHS);
47104 // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
47105 // fold eq + gt/lt nested selects into ge/le selects
47106 // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
47107 // --> (select (cmpuge Cond0, Cond1), LHS, Y)
47108 // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
47109 // --> (select (cmpsle Cond0, Cond1), LHS, Y)
47110 // .. etc ..
47111 if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
47112 RHS.getOperand(0).getOpcode() == ISD::SETCC) {
47113 SDValue InnerSetCC = RHS.getOperand(0);
47114 ISD::CondCode InnerCC =
47115 cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
47116 if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
47117 Cond0 == InnerSetCC.getOperand(0) &&
47118 Cond1 == InnerSetCC.getOperand(1)) {
47119 ISD::CondCode NewCC;
47120 switch (CC == ISD::SETEQ ? InnerCC : CC) {
47121 // clang-format off
47122 case ISD::SETGT: NewCC = ISD::SETGE; break;
47123 case ISD::SETLT: NewCC = ISD::SETLE; break;
47124 case ISD::SETUGT: NewCC = ISD::SETUGE; break;
47125 case ISD::SETULT: NewCC = ISD::SETULE; break;
47126 default: NewCC = ISD::SETCC_INVALID; break;
47127 // clang-format on
47129 if (NewCC != ISD::SETCC_INVALID) {
47130 Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
47131 return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
47137 // Check if the first operand is all zeros and Cond type is vXi1.
47138 // If this an avx512 target we can improve the use of zero masking by
47139 // swapping the operands and inverting the condition.
47140 if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
47141 Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
47142 ISD::isBuildVectorAllZeros(LHS.getNode()) &&
47143 !ISD::isBuildVectorAllZeros(RHS.getNode())) {
47144 // Invert the cond to not(cond) : xor(op,allones)=not(op)
47145 SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
47146 // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
47147 return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
47150 // Attempt to convert a (vXi1 bitcast(iX Cond)) selection mask before it might
47151 // get split by legalization.
47152 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::BITCAST &&
47153 CondVT.getVectorElementType() == MVT::i1 &&
47154 TLI.isTypeLegal(VT.getScalarType())) {
47155 EVT ExtCondVT = VT.changeVectorElementTypeToInteger();
47156 if (SDValue ExtCond = combineToExtendBoolVectorInReg(
47157 ISD::SIGN_EXTEND, DL, ExtCondVT, Cond, DAG, DCI, Subtarget)) {
47158 ExtCond = DAG.getNode(ISD::TRUNCATE, DL, CondVT, ExtCond);
47159 return DAG.getSelect(DL, VT, ExtCond, LHS, RHS);
47163 // Exploits AVX2 VSHLV/VSRLV instructions for efficient unsigned vector shifts
47164 // with out-of-bounds clamping.
47166 // Unlike general shift instructions (SHL/SRL), AVX2's VSHLV/VSRLV handle
47167 // shift amounts exceeding the element bitwidth. VSHLV/VSRLV clamps the amount
47168 // to bitwidth-1 for unsigned shifts, effectively performing a maximum left
47169 // shift of bitwidth-1 positions. and returns zero for unsigned right shifts
47170 // exceeding bitwidth-1.
47171 if (N->getOpcode() == ISD::VSELECT) {
47172 using namespace llvm::SDPatternMatch;
47173 // fold select(icmp_ult(amt,BW),shl(x,amt),0) -> avx2 psllv(x,amt)
47174 // fold select(icmp_ult(amt,BW),srl(x,amt),0) -> avx2 psrlv(x,amt)
47175 if ((LHS.getOpcode() == ISD::SRL || LHS.getOpcode() == ISD::SHL) &&
47176 supportedVectorVarShift(VT, Subtarget, LHS.getOpcode()) &&
47177 ISD::isConstantSplatVectorAllZeros(RHS.getNode()) &&
47178 sd_match(Cond, m_SetCC(m_Specific(LHS.getOperand(1)),
47179 m_SpecificInt(VT.getScalarSizeInBits()),
47180 m_SpecificCondCode(ISD::SETULT)))) {
47181 return DAG.getNode(LHS.getOpcode() == ISD::SRL ? X86ISD::VSRLV
47182 : X86ISD::VSHLV,
47183 DL, VT, LHS.getOperand(0), LHS.getOperand(1));
47185 // fold select(icmp_uge(amt,BW),0,shl(x,amt)) -> avx2 psllv(x,amt)
47186 // fold select(icmp_uge(amt,BW),0,srl(x,amt)) -> avx2 psrlv(x,amt)
47187 if ((RHS.getOpcode() == ISD::SRL || RHS.getOpcode() == ISD::SHL) &&
47188 supportedVectorVarShift(VT, Subtarget, RHS.getOpcode()) &&
47189 ISD::isConstantSplatVectorAllZeros(LHS.getNode()) &&
47190 sd_match(Cond, m_SetCC(m_Specific(RHS.getOperand(1)),
47191 m_SpecificInt(VT.getScalarSizeInBits()),
47192 m_SpecificCondCode(ISD::SETUGE)))) {
47193 return DAG.getNode(RHS.getOpcode() == ISD::SRL ? X86ISD::VSRLV
47194 : X86ISD::VSHLV,
47195 DL, VT, RHS.getOperand(0), RHS.getOperand(1));
47199 // Early exit check
47200 if (!TLI.isTypeLegal(VT) || isSoftF16(VT, Subtarget))
47201 return SDValue();
47203 if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DL, DCI, Subtarget))
47204 return V;
47206 if (SDValue V = combineVSelectToBLENDV(N, DAG, DL, DCI, Subtarget))
47207 return V;
47209 if (SDValue V = narrowVectorSelect(N, DAG, DL, Subtarget))
47210 return V;
47212 // select(~Cond, X, Y) -> select(Cond, Y, X)
47213 if (CondVT.getScalarType() != MVT::i1) {
47214 if (SDValue CondNot = IsNOT(Cond, DAG))
47215 return DAG.getNode(N->getOpcode(), DL, VT,
47216 DAG.getBitcast(CondVT, CondNot), RHS, LHS);
47218 // select(pcmpeq(and(X,Pow2),0),A,B) -> select(pcmpeq(and(X,Pow2),Pow2),B,A)
47219 if (Cond.getOpcode() == X86ISD::PCMPEQ &&
47220 Cond.getOperand(0).getOpcode() == ISD::AND &&
47221 ISD::isBuildVectorAllZeros(Cond.getOperand(1).getNode()) &&
47222 isConstantPowerOf2(Cond.getOperand(0).getOperand(1),
47223 Cond.getScalarValueSizeInBits(),
47224 /*AllowUndefs=*/true) &&
47225 Cond.hasOneUse()) {
47226 Cond = DAG.getNode(X86ISD::PCMPEQ, DL, CondVT, Cond.getOperand(0),
47227 Cond.getOperand(0).getOperand(1));
47228 return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
47231 // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the
47232 // signbit.
47233 if (Cond.getOpcode() == X86ISD::PCMPGT &&
47234 ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode()) &&
47235 Cond.hasOneUse()) {
47236 Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
47237 DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
47238 return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
47242 // Try to optimize vXi1 selects if both operands are either all constants or
47243 // bitcasts from scalar integer type. In that case we can convert the operands
47244 // to integer and use an integer select which will be converted to a CMOV.
47245 // We need to take a little bit of care to avoid creating an i64 type after
47246 // type legalization.
47247 if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
47248 VT.getVectorElementType() == MVT::i1 &&
47249 (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
47250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
47251 if (DCI.isBeforeLegalize() || TLI.isTypeLegal(IntVT)) {
47252 bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
47253 bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
47255 if ((LHSIsConst || (LHS.getOpcode() == ISD::BITCAST &&
47256 LHS.getOperand(0).getValueType() == IntVT)) &&
47257 (RHSIsConst || (RHS.getOpcode() == ISD::BITCAST &&
47258 RHS.getOperand(0).getValueType() == IntVT))) {
47259 if (LHSIsConst)
47260 LHS = combinevXi1ConstantToInteger(LHS, DAG);
47261 else
47262 LHS = LHS.getOperand(0);
47264 if (RHSIsConst)
47265 RHS = combinevXi1ConstantToInteger(RHS, DAG);
47266 else
47267 RHS = RHS.getOperand(0);
47269 SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
47270 return DAG.getBitcast(VT, Select);
47275 // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
47276 // single bits, then invert the predicate and swap the select operands.
47277 // This can lower using a vector shift bit-hack rather than mask and compare.
47278 if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
47279 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
47280 Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
47281 Cond.getOperand(0).getOpcode() == ISD::AND &&
47282 isNullOrNullSplat(Cond.getOperand(1)) &&
47283 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
47284 Cond.getOperand(0).getValueType() == VT) {
47285 // The 'and' mask must be composed of power-of-2 constants.
47286 SDValue And = Cond.getOperand(0);
47287 auto *C = isConstOrConstSplat(And.getOperand(1));
47288 if (C && C->getAPIntValue().isPowerOf2()) {
47289 // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
47290 SDValue NotCond =
47291 DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
47292 return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
47295 // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
47296 // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
47297 // 16-bit lacks a proper blendv.
47298 unsigned EltBitWidth = VT.getScalarSizeInBits();
47299 bool CanShiftBlend =
47300 TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
47301 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
47302 (Subtarget.hasXOP()));
47303 if (CanShiftBlend &&
47304 ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
47305 return C->getAPIntValue().isPowerOf2();
47306 })) {
47307 // Create a left-shift constant to get the mask bits over to the sign-bit.
47308 SDValue Mask = And.getOperand(1);
47309 SmallVector<int, 32> ShlVals;
47310 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
47311 auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
47312 ShlVals.push_back(EltBitWidth - 1 -
47313 MaskVal->getAPIntValue().exactLogBase2());
47315 // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
47316 SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
47317 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
47318 SDValue NewCond =
47319 DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
47320 return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
47324 return SDValue();
47327 /// Combine:
47328 /// (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
47329 /// to:
47330 /// (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
47331 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
47332 /// Note that this is only legal for some op/cc combinations.
47333 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
47334 SelectionDAG &DAG,
47335 const X86Subtarget &Subtarget) {
47336 // This combine only operates on CMP-like nodes.
47337 if (!(Cmp.getOpcode() == X86ISD::CMP ||
47338 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
47339 return SDValue();
47341 // Can't replace the cmp if it has more uses than the one we're looking at.
47342 // FIXME: We would like to be able to handle this, but would need to make sure
47343 // all uses were updated.
47344 if (!Cmp.hasOneUse())
47345 return SDValue();
47347 // This only applies to variations of the common case:
47348 // (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
47349 // (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
47350 // (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
47351 // (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
47352 // Using the proper condcodes (see below), overflow is checked for.
47354 // FIXME: We can generalize both constraints:
47355 // - XOR/OR/AND (if they were made to survive AtomicExpand)
47356 // - LHS != 1
47357 // if the result is compared.
47359 SDValue CmpLHS = Cmp.getOperand(0);
47360 SDValue CmpRHS = Cmp.getOperand(1);
47361 EVT CmpVT = CmpLHS.getValueType();
47363 if (!CmpLHS.hasOneUse())
47364 return SDValue();
47366 unsigned Opc = CmpLHS.getOpcode();
47367 if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
47368 return SDValue();
47370 SDValue OpRHS = CmpLHS.getOperand(2);
47371 auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
47372 if (!OpRHSC)
47373 return SDValue();
47375 APInt Addend = OpRHSC->getAPIntValue();
47376 if (Opc == ISD::ATOMIC_LOAD_SUB)
47377 Addend = -Addend;
47379 auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
47380 if (!CmpRHSC)
47381 return SDValue();
47383 APInt Comparison = CmpRHSC->getAPIntValue();
47384 APInt NegAddend = -Addend;
47386 // See if we can adjust the CC to make the comparison match the negated
47387 // addend.
47388 if (Comparison != NegAddend) {
47389 APInt IncComparison = Comparison + 1;
47390 if (IncComparison == NegAddend) {
47391 if (CC == X86::COND_A && !Comparison.isMaxValue()) {
47392 Comparison = IncComparison;
47393 CC = X86::COND_AE;
47394 } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
47395 Comparison = IncComparison;
47396 CC = X86::COND_L;
47399 APInt DecComparison = Comparison - 1;
47400 if (DecComparison == NegAddend) {
47401 if (CC == X86::COND_AE && !Comparison.isMinValue()) {
47402 Comparison = DecComparison;
47403 CC = X86::COND_A;
47404 } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
47405 Comparison = DecComparison;
47406 CC = X86::COND_LE;
47411 // If the addend is the negation of the comparison value, then we can do
47412 // a full comparison by emitting the atomic arithmetic as a locked sub.
47413 if (Comparison == NegAddend) {
47414 // The CC is fine, but we need to rewrite the LHS of the comparison as an
47415 // atomic sub.
47416 auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
47417 auto AtomicSub = DAG.getAtomic(
47418 ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
47419 /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
47420 /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
47421 AN->getMemOperand());
47422 auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
47423 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
47424 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
47425 return LockOp;
47428 // We can handle comparisons with zero in a number of cases by manipulating
47429 // the CC used.
47430 if (!Comparison.isZero())
47431 return SDValue();
47433 if (CC == X86::COND_S && Addend == 1)
47434 CC = X86::COND_LE;
47435 else if (CC == X86::COND_NS && Addend == 1)
47436 CC = X86::COND_G;
47437 else if (CC == X86::COND_G && Addend == -1)
47438 CC = X86::COND_GE;
47439 else if (CC == X86::COND_LE && Addend == -1)
47440 CC = X86::COND_L;
47441 else
47442 return SDValue();
47444 SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
47445 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
47446 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
47447 return LockOp;
47450 // Check whether we're just testing the signbit, and whether we can simplify
47451 // this by tracking where the signbit came from.
47452 static SDValue checkSignTestSetCCCombine(SDValue Cmp, X86::CondCode &CC,
47453 SelectionDAG &DAG) {
47454 if (CC != X86::COND_S && CC != X86::COND_NS)
47455 return SDValue();
47457 if (!Cmp.hasOneUse())
47458 return SDValue();
47460 SDValue Src;
47461 if (Cmp.getOpcode() == X86ISD::CMP) {
47462 // CMP(X,0) -> signbit test
47463 if (!isNullConstant(Cmp.getOperand(1)))
47464 return SDValue();
47465 Src = Cmp.getOperand(0);
47466 // Peek through a SRA node as we just need the signbit.
47467 // TODO: Remove one use limit once sdiv-fix regressions are fixed.
47468 // TODO: Use SimplifyDemandedBits instead of just SRA?
47469 if (Src.getOpcode() != ISD::SRA || !Src.hasOneUse())
47470 return SDValue();
47471 Src = Src.getOperand(0);
47472 } else if (Cmp.getOpcode() == X86ISD::OR) {
47473 // OR(X,Y) -> see if only one operand contributes to the signbit.
47474 // TODO: XOR(X,Y) -> see if only one operand contributes to the signbit.
47475 if (DAG.SignBitIsZero(Cmp.getOperand(0)))
47476 Src = Cmp.getOperand(1);
47477 else if (DAG.SignBitIsZero(Cmp.getOperand(1)))
47478 Src = Cmp.getOperand(0);
47479 else
47480 return SDValue();
47481 } else {
47482 return SDValue();
47485 // Replace with a TEST on the MSB.
47486 SDLoc DL(Cmp);
47487 MVT SrcVT = Src.getSimpleValueType();
47488 APInt BitMask = APInt::getSignMask(SrcVT.getScalarSizeInBits());
47490 // If Src came from a SHL (probably from an expanded SIGN_EXTEND_INREG), then
47491 // peek through and adjust the TEST bit.
47492 if (Src.getOpcode() == ISD::SHL) {
47493 if (std::optional<uint64_t> ShiftAmt = DAG.getValidShiftAmount(Src)) {
47494 Src = Src.getOperand(0);
47495 BitMask.lshrInPlace(*ShiftAmt);
47499 SDValue Mask = DAG.getNode(ISD::AND, DL, SrcVT, Src,
47500 DAG.getConstant(BitMask, DL, SrcVT));
47501 CC = CC == X86::COND_S ? X86::COND_NE : X86::COND_E;
47502 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Mask,
47503 DAG.getConstant(0, DL, SrcVT));
47506 // Check whether a boolean test is testing a boolean value generated by
47507 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
47508 // code.
47510 // Simplify the following patterns:
47511 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
47512 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
47513 // to (Op EFLAGS Cond)
47515 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
47516 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
47517 // to (Op EFLAGS !Cond)
47519 // where Op could be BRCOND or CMOV.
47521 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
47522 // This combine only operates on CMP-like nodes.
47523 if (!(Cmp.getOpcode() == X86ISD::CMP ||
47524 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
47525 return SDValue();
47527 // Quit if not used as a boolean value.
47528 if (CC != X86::COND_E && CC != X86::COND_NE)
47529 return SDValue();
47531 // Check CMP operands. One of them should be 0 or 1 and the other should be
47532 // an SetCC or extended from it.
47533 SDValue Op1 = Cmp.getOperand(0);
47534 SDValue Op2 = Cmp.getOperand(1);
47536 SDValue SetCC;
47537 const ConstantSDNode* C = nullptr;
47538 bool needOppositeCond = (CC == X86::COND_E);
47539 bool checkAgainstTrue = false; // Is it a comparison against 1?
47541 if ((C = dyn_cast<ConstantSDNode>(Op1)))
47542 SetCC = Op2;
47543 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
47544 SetCC = Op1;
47545 else // Quit if all operands are not constants.
47546 return SDValue();
47548 if (C->getZExtValue() == 1) {
47549 needOppositeCond = !needOppositeCond;
47550 checkAgainstTrue = true;
47551 } else if (C->getZExtValue() != 0)
47552 // Quit if the constant is neither 0 or 1.
47553 return SDValue();
47555 bool truncatedToBoolWithAnd = false;
47556 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
47557 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
47558 SetCC.getOpcode() == ISD::TRUNCATE ||
47559 SetCC.getOpcode() == ISD::AND) {
47560 if (SetCC.getOpcode() == ISD::AND) {
47561 int OpIdx = -1;
47562 if (isOneConstant(SetCC.getOperand(0)))
47563 OpIdx = 1;
47564 if (isOneConstant(SetCC.getOperand(1)))
47565 OpIdx = 0;
47566 if (OpIdx < 0)
47567 break;
47568 SetCC = SetCC.getOperand(OpIdx);
47569 truncatedToBoolWithAnd = true;
47570 } else
47571 SetCC = SetCC.getOperand(0);
47574 switch (SetCC.getOpcode()) {
47575 case X86ISD::SETCC_CARRY:
47576 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
47577 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
47578 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
47579 // truncated to i1 using 'and'.
47580 if (checkAgainstTrue && !truncatedToBoolWithAnd)
47581 break;
47582 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
47583 "Invalid use of SETCC_CARRY!");
47584 [[fallthrough]];
47585 case X86ISD::SETCC:
47586 // Set the condition code or opposite one if necessary.
47587 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
47588 if (needOppositeCond)
47589 CC = X86::GetOppositeBranchCondition(CC);
47590 return SetCC.getOperand(1);
47591 case X86ISD::CMOV: {
47592 // Check whether false/true value has canonical one, i.e. 0 or 1.
47593 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
47594 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
47595 // Quit if true value is not a constant.
47596 if (!TVal)
47597 return SDValue();
47598 // Quit if false value is not a constant.
47599 if (!FVal) {
47600 SDValue Op = SetCC.getOperand(0);
47601 // Skip 'zext' or 'trunc' node.
47602 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
47603 Op.getOpcode() == ISD::TRUNCATE)
47604 Op = Op.getOperand(0);
47605 // A special case for rdrand/rdseed, where 0 is set if false cond is
47606 // found.
47607 if ((Op.getOpcode() != X86ISD::RDRAND &&
47608 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
47609 return SDValue();
47611 // Quit if false value is not the constant 0 or 1.
47612 bool FValIsFalse = true;
47613 if (FVal && FVal->getZExtValue() != 0) {
47614 if (FVal->getZExtValue() != 1)
47615 return SDValue();
47616 // If FVal is 1, opposite cond is needed.
47617 needOppositeCond = !needOppositeCond;
47618 FValIsFalse = false;
47620 // Quit if TVal is not the constant opposite of FVal.
47621 if (FValIsFalse && TVal->getZExtValue() != 1)
47622 return SDValue();
47623 if (!FValIsFalse && TVal->getZExtValue() != 0)
47624 return SDValue();
47625 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
47626 if (needOppositeCond)
47627 CC = X86::GetOppositeBranchCondition(CC);
47628 return SetCC.getOperand(3);
47632 return SDValue();
47635 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
47636 /// Match:
47637 /// (X86or (X86setcc) (X86setcc))
47638 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
47639 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
47640 X86::CondCode &CC1, SDValue &Flags,
47641 bool &isAnd) {
47642 if (Cond->getOpcode() == X86ISD::CMP) {
47643 if (!isNullConstant(Cond->getOperand(1)))
47644 return false;
47646 Cond = Cond->getOperand(0);
47649 isAnd = false;
47651 SDValue SetCC0, SetCC1;
47652 switch (Cond->getOpcode()) {
47653 default: return false;
47654 case ISD::AND:
47655 case X86ISD::AND:
47656 isAnd = true;
47657 [[fallthrough]];
47658 case ISD::OR:
47659 case X86ISD::OR:
47660 SetCC0 = Cond->getOperand(0);
47661 SetCC1 = Cond->getOperand(1);
47662 break;
47665 // Make sure we have SETCC nodes, using the same flags value.
47666 if (SetCC0.getOpcode() != X86ISD::SETCC ||
47667 SetCC1.getOpcode() != X86ISD::SETCC ||
47668 SetCC0->getOperand(1) != SetCC1->getOperand(1))
47669 return false;
47671 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
47672 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
47673 Flags = SetCC0->getOperand(1);
47674 return true;
47677 // When legalizing carry, we create carries via add X, -1
47678 // If that comes from an actual carry, via setcc, we use the
47679 // carry directly.
47680 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
47681 if (EFLAGS.getOpcode() == X86ISD::ADD) {
47682 if (isAllOnesConstant(EFLAGS.getOperand(1))) {
47683 bool FoundAndLSB = false;
47684 SDValue Carry = EFLAGS.getOperand(0);
47685 while (Carry.getOpcode() == ISD::TRUNCATE ||
47686 Carry.getOpcode() == ISD::ZERO_EXTEND ||
47687 (Carry.getOpcode() == ISD::AND &&
47688 isOneConstant(Carry.getOperand(1)))) {
47689 FoundAndLSB |= Carry.getOpcode() == ISD::AND;
47690 Carry = Carry.getOperand(0);
47692 if (Carry.getOpcode() == X86ISD::SETCC ||
47693 Carry.getOpcode() == X86ISD::SETCC_CARRY) {
47694 // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
47695 uint64_t CarryCC = Carry.getConstantOperandVal(0);
47696 SDValue CarryOp1 = Carry.getOperand(1);
47697 if (CarryCC == X86::COND_B)
47698 return CarryOp1;
47699 if (CarryCC == X86::COND_A) {
47700 // Try to convert COND_A into COND_B in an attempt to facilitate
47701 // materializing "setb reg".
47703 // Do not flip "e > c", where "c" is a constant, because Cmp
47704 // instruction cannot take an immediate as its first operand.
47706 if (CarryOp1.getOpcode() == X86ISD::SUB &&
47707 CarryOp1.getNode()->hasOneUse() &&
47708 CarryOp1.getValueType().isInteger() &&
47709 !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
47710 SDValue SubCommute =
47711 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
47712 CarryOp1.getOperand(1), CarryOp1.getOperand(0));
47713 return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
47716 // If this is a check of the z flag of an add with 1, switch to the
47717 // C flag.
47718 if (CarryCC == X86::COND_E &&
47719 CarryOp1.getOpcode() == X86ISD::ADD &&
47720 isOneConstant(CarryOp1.getOperand(1)))
47721 return CarryOp1;
47722 } else if (FoundAndLSB) {
47723 SDLoc DL(Carry);
47724 SDValue BitNo = DAG.getConstant(0, DL, Carry.getValueType());
47725 if (Carry.getOpcode() == ISD::SRL) {
47726 BitNo = Carry.getOperand(1);
47727 Carry = Carry.getOperand(0);
47729 return getBT(Carry, BitNo, DL, DAG);
47734 return SDValue();
47737 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
47738 /// to avoid the inversion.
47739 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
47740 SelectionDAG &DAG,
47741 const X86Subtarget &Subtarget) {
47742 // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
47743 if (EFLAGS.getOpcode() != X86ISD::PTEST &&
47744 EFLAGS.getOpcode() != X86ISD::TESTP)
47745 return SDValue();
47747 // PTEST/TESTP sets EFLAGS as:
47748 // TESTZ: ZF = (Op0 & Op1) == 0
47749 // TESTC: CF = (~Op0 & Op1) == 0
47750 // TESTNZC: ZF == 0 && CF == 0
47751 MVT VT = EFLAGS.getSimpleValueType();
47752 SDValue Op0 = EFLAGS.getOperand(0);
47753 SDValue Op1 = EFLAGS.getOperand(1);
47754 MVT OpVT = Op0.getSimpleValueType();
47755 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47757 // TEST*(~X,Y) == TEST*(X,Y)
47758 if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
47759 X86::CondCode InvCC;
47760 switch (CC) {
47761 case X86::COND_B:
47762 // testc -> testz.
47763 InvCC = X86::COND_E;
47764 break;
47765 case X86::COND_AE:
47766 // !testc -> !testz.
47767 InvCC = X86::COND_NE;
47768 break;
47769 case X86::COND_E:
47770 // testz -> testc.
47771 InvCC = X86::COND_B;
47772 break;
47773 case X86::COND_NE:
47774 // !testz -> !testc.
47775 InvCC = X86::COND_AE;
47776 break;
47777 case X86::COND_A:
47778 case X86::COND_BE:
47779 // testnzc -> testnzc (no change).
47780 InvCC = CC;
47781 break;
47782 default:
47783 InvCC = X86::COND_INVALID;
47784 break;
47787 if (InvCC != X86::COND_INVALID) {
47788 CC = InvCC;
47789 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
47790 DAG.getBitcast(OpVT, NotOp0), Op1);
47794 if (CC == X86::COND_B || CC == X86::COND_AE) {
47795 // TESTC(X,~X) == TESTC(X,-1)
47796 if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
47797 if (peekThroughBitcasts(NotOp1) == peekThroughBitcasts(Op0)) {
47798 SDLoc DL(EFLAGS);
47799 return DAG.getNode(
47800 EFLAGS.getOpcode(), DL, VT, DAG.getBitcast(OpVT, NotOp1),
47801 DAG.getBitcast(OpVT,
47802 DAG.getAllOnesConstant(DL, NotOp1.getValueType())));
47807 if (CC == X86::COND_E || CC == X86::COND_NE) {
47808 // TESTZ(X,~Y) == TESTC(Y,X)
47809 if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
47810 CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
47811 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
47812 DAG.getBitcast(OpVT, NotOp1), Op0);
47815 if (Op0 == Op1) {
47816 SDValue BC = peekThroughBitcasts(Op0);
47817 EVT BCVT = BC.getValueType();
47819 // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
47820 if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
47821 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
47822 DAG.getBitcast(OpVT, BC.getOperand(0)),
47823 DAG.getBitcast(OpVT, BC.getOperand(1)));
47826 // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
47827 if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
47828 CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
47829 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
47830 DAG.getBitcast(OpVT, BC.getOperand(0)),
47831 DAG.getBitcast(OpVT, BC.getOperand(1)));
47834 // If every element is an all-sign value, see if we can use TESTP/MOVMSK
47835 // to more efficiently extract the sign bits and compare that.
47836 // TODO: Handle TESTC with comparison inversion.
47837 // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
47838 // TESTP/MOVMSK combines to make sure its never worse than PTEST?
47839 if (BCVT.isVector() && TLI.isTypeLegal(BCVT)) {
47840 unsigned EltBits = BCVT.getScalarSizeInBits();
47841 if (DAG.ComputeNumSignBits(BC) == EltBits) {
47842 assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
47843 APInt SignMask = APInt::getSignMask(EltBits);
47844 if (SDValue Res =
47845 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
47846 // For vXi16 cases we need to use pmovmksb and extract every other
47847 // sign bit.
47848 SDLoc DL(EFLAGS);
47849 if ((EltBits == 32 || EltBits == 64) && Subtarget.hasAVX()) {
47850 MVT FloatSVT = MVT::getFloatingPointVT(EltBits);
47851 MVT FloatVT =
47852 MVT::getVectorVT(FloatSVT, OpVT.getSizeInBits() / EltBits);
47853 Res = DAG.getBitcast(FloatVT, Res);
47854 return DAG.getNode(X86ISD::TESTP, SDLoc(EFLAGS), VT, Res, Res);
47855 } else if (EltBits == 16) {
47856 MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
47857 Res = DAG.getBitcast(MovmskVT, Res);
47858 Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
47859 Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
47860 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
47861 } else {
47862 Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
47864 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
47865 DAG.getConstant(0, DL, MVT::i32));
47871 // TESTZ(-1,X) == TESTZ(X,X)
47872 if (ISD::isBuildVectorAllOnes(Op0.getNode()))
47873 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
47875 // TESTZ(X,-1) == TESTZ(X,X)
47876 if (ISD::isBuildVectorAllOnes(Op1.getNode()))
47877 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
47879 // TESTZ(OR(LO(X),HI(X)),OR(LO(Y),HI(Y))) -> TESTZ(X,Y)
47880 // TODO: Add COND_NE handling?
47881 if (CC == X86::COND_E && OpVT.is128BitVector() && Subtarget.hasAVX()) {
47882 SDValue Src0 = peekThroughBitcasts(Op0);
47883 SDValue Src1 = peekThroughBitcasts(Op1);
47884 if (Src0.getOpcode() == ISD::OR && Src1.getOpcode() == ISD::OR) {
47885 Src0 = getSplitVectorSrc(peekThroughBitcasts(Src0.getOperand(0)),
47886 peekThroughBitcasts(Src0.getOperand(1)), true);
47887 Src1 = getSplitVectorSrc(peekThroughBitcasts(Src1.getOperand(0)),
47888 peekThroughBitcasts(Src1.getOperand(1)), true);
47889 if (Src0 && Src1) {
47890 MVT OpVT2 = OpVT.getDoubleNumVectorElementsVT();
47891 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
47892 DAG.getBitcast(OpVT2, Src0),
47893 DAG.getBitcast(OpVT2, Src1));
47899 return SDValue();
47902 // Attempt to simplify the MOVMSK input based on the comparison type.
47903 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
47904 SelectionDAG &DAG,
47905 const X86Subtarget &Subtarget) {
47906 // Handle eq/ne against zero (any_of).
47907 // Handle eq/ne against -1 (all_of).
47908 if (!(CC == X86::COND_E || CC == X86::COND_NE))
47909 return SDValue();
47910 if (EFLAGS.getValueType() != MVT::i32)
47911 return SDValue();
47912 unsigned CmpOpcode = EFLAGS.getOpcode();
47913 if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
47914 return SDValue();
47915 auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
47916 if (!CmpConstant)
47917 return SDValue();
47918 const APInt &CmpVal = CmpConstant->getAPIntValue();
47920 SDValue CmpOp = EFLAGS.getOperand(0);
47921 unsigned CmpBits = CmpOp.getValueSizeInBits();
47922 assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
47924 // Peek through any truncate.
47925 if (CmpOp.getOpcode() == ISD::TRUNCATE)
47926 CmpOp = CmpOp.getOperand(0);
47928 // Bail if we don't find a MOVMSK.
47929 if (CmpOp.getOpcode() != X86ISD::MOVMSK)
47930 return SDValue();
47932 SDValue Vec = CmpOp.getOperand(0);
47933 MVT VecVT = Vec.getSimpleValueType();
47934 assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
47935 "Unexpected MOVMSK operand");
47936 unsigned NumElts = VecVT.getVectorNumElements();
47937 unsigned NumEltBits = VecVT.getScalarSizeInBits();
47939 bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isZero();
47940 bool IsAllOf = (CmpOpcode == X86ISD::SUB || CmpOpcode == X86ISD::CMP) &&
47941 NumElts <= CmpBits && CmpVal.isMask(NumElts);
47942 if (!IsAnyOf && !IsAllOf)
47943 return SDValue();
47945 // TODO: Check more combining cases for me.
47946 // Here we check the cmp use number to decide do combining or not.
47947 // Currently we only get 2 tests about combining "MOVMSK(CONCAT(..))"
47948 // and "MOVMSK(PCMPEQ(..))" are fit to use this constraint.
47949 bool IsOneUse = CmpOp.getNode()->hasOneUse();
47951 // See if we can peek through to a vector with a wider element type, if the
47952 // signbits extend down to all the sub-elements as well.
47953 // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
47954 // potential SimplifyDemandedBits/Elts cases.
47955 // If we looked through a truncate that discard bits, we can't do this
47956 // transform.
47957 // FIXME: We could do this transform for truncates that discarded bits by
47958 // inserting an AND mask between the new MOVMSK and the CMP.
47959 if (Vec.getOpcode() == ISD::BITCAST && NumElts <= CmpBits) {
47960 SDValue BC = peekThroughBitcasts(Vec);
47961 MVT BCVT = BC.getSimpleValueType();
47962 unsigned BCNumElts = BCVT.getVectorNumElements();
47963 unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
47964 if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
47965 BCNumEltBits > NumEltBits &&
47966 DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
47967 SDLoc DL(EFLAGS);
47968 APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : BCNumElts);
47969 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
47970 DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
47971 DAG.getConstant(CmpMask, DL, MVT::i32));
47975 // MOVMSK(CONCAT(X,Y)) == 0 -> MOVMSK(OR(X,Y)).
47976 // MOVMSK(CONCAT(X,Y)) != 0 -> MOVMSK(OR(X,Y)).
47977 // MOVMSK(CONCAT(X,Y)) == -1 -> MOVMSK(AND(X,Y)).
47978 // MOVMSK(CONCAT(X,Y)) != -1 -> MOVMSK(AND(X,Y)).
47979 if (VecVT.is256BitVector() && NumElts <= CmpBits && IsOneUse) {
47980 SmallVector<SDValue> Ops;
47981 if (collectConcatOps(peekThroughBitcasts(Vec).getNode(), Ops, DAG) &&
47982 Ops.size() == 2) {
47983 SDLoc DL(EFLAGS);
47984 EVT SubVT = Ops[0].getValueType().changeTypeToInteger();
47985 APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : NumElts / 2);
47986 SDValue V = DAG.getNode(IsAnyOf ? ISD::OR : ISD::AND, DL, SubVT,
47987 DAG.getBitcast(SubVT, Ops[0]),
47988 DAG.getBitcast(SubVT, Ops[1]));
47989 V = DAG.getBitcast(VecVT.getHalfNumVectorElementsVT(), V);
47990 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
47991 DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V),
47992 DAG.getConstant(CmpMask, DL, MVT::i32));
47996 // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
47997 // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
47998 // MOVMSK(PCMPEQ(X,Y)) == -1 -> PTESTZ(XOR(X,Y),XOR(X,Y)).
47999 // MOVMSK(PCMPEQ(X,Y)) != -1 -> !PTESTZ(XOR(X,Y),XOR(X,Y)).
48000 if (IsAllOf && Subtarget.hasSSE41() && IsOneUse) {
48001 MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
48002 SDValue BC = peekThroughBitcasts(Vec);
48003 // Ensure MOVMSK was testing every signbit of BC.
48004 if (BC.getValueType().getVectorNumElements() <= NumElts) {
48005 if (BC.getOpcode() == X86ISD::PCMPEQ) {
48006 SDValue V = DAG.getNode(ISD::XOR, SDLoc(BC), BC.getValueType(),
48007 BC.getOperand(0), BC.getOperand(1));
48008 V = DAG.getBitcast(TestVT, V);
48009 return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48011 // Check for 256-bit split vector cases.
48012 if (BC.getOpcode() == ISD::AND &&
48013 BC.getOperand(0).getOpcode() == X86ISD::PCMPEQ &&
48014 BC.getOperand(1).getOpcode() == X86ISD::PCMPEQ) {
48015 SDValue LHS = BC.getOperand(0);
48016 SDValue RHS = BC.getOperand(1);
48017 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), LHS.getValueType(),
48018 LHS.getOperand(0), LHS.getOperand(1));
48019 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), RHS.getValueType(),
48020 RHS.getOperand(0), RHS.getOperand(1));
48021 LHS = DAG.getBitcast(TestVT, LHS);
48022 RHS = DAG.getBitcast(TestVT, RHS);
48023 SDValue V = DAG.getNode(ISD::OR, SDLoc(EFLAGS), TestVT, LHS, RHS);
48024 return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48029 // See if we can avoid a PACKSS by calling MOVMSK on the sources.
48030 // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
48031 // sign bits prior to the comparison with zero unless we know that
48032 // the vXi16 splats the sign bit down to the lower i8 half.
48033 // TODO: Handle all_of patterns.
48034 if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
48035 SDValue VecOp0 = Vec.getOperand(0);
48036 SDValue VecOp1 = Vec.getOperand(1);
48037 bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
48038 bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
48039 // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
48040 if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
48041 SDLoc DL(EFLAGS);
48042 SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
48043 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48044 Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
48045 if (!SignExt0) {
48046 Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
48047 DAG.getConstant(0xAAAA, DL, MVT::i16));
48049 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
48050 DAG.getConstant(0, DL, MVT::i16));
48052 // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
48053 // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
48054 if (CmpBits >= 16 && Subtarget.hasInt256() &&
48055 (IsAnyOf || (SignExt0 && SignExt1))) {
48056 if (SDValue Src = getSplitVectorSrc(VecOp0, VecOp1, true)) {
48057 SDLoc DL(EFLAGS);
48058 SDValue Result = peekThroughBitcasts(Src);
48059 if (IsAllOf && Result.getOpcode() == X86ISD::PCMPEQ &&
48060 Result.getValueType().getVectorNumElements() <= NumElts) {
48061 SDValue V = DAG.getNode(ISD::XOR, DL, Result.getValueType(),
48062 Result.getOperand(0), Result.getOperand(1));
48063 V = DAG.getBitcast(MVT::v4i64, V);
48064 return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
48066 Result = DAG.getBitcast(MVT::v32i8, Result);
48067 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48068 unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
48069 if (!SignExt0 || !SignExt1) {
48070 assert(IsAnyOf &&
48071 "Only perform v16i16 signmasks for any_of patterns");
48072 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
48073 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
48075 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
48076 DAG.getConstant(CmpMask, DL, MVT::i32));
48081 // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
48082 // Since we peek through a bitcast, we need to be careful if the base vector
48083 // type has smaller elements than the MOVMSK type. In that case, even if
48084 // all the elements are demanded by the shuffle mask, only the "high"
48085 // elements which have highbits that align with highbits in the MOVMSK vec
48086 // elements are actually demanded. A simplification of spurious operations
48087 // on the "low" elements take place during other simplifications.
48089 // For example:
48090 // MOVMSK64(BITCAST(SHUF32 X, (1,0,3,2))) even though all the elements are
48091 // demanded, because we are swapping around the result can change.
48093 // To address this, we check that we can scale the shuffle mask to MOVMSK
48094 // element width (this will ensure "high" elements match). Its slightly overly
48095 // conservative, but fine for an edge case fold.
48096 SmallVector<int, 32> ShuffleMask;
48097 SmallVector<SDValue, 2> ShuffleInputs;
48098 if (NumElts <= CmpBits &&
48099 getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
48100 ShuffleMask, DAG) &&
48101 ShuffleInputs.size() == 1 && isCompletePermute(ShuffleMask) &&
48102 ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits() &&
48103 canScaleShuffleElements(ShuffleMask, NumElts)) {
48104 SDLoc DL(EFLAGS);
48105 SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
48106 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48107 Result =
48108 DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
48109 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result, EFLAGS.getOperand(1));
48112 // MOVMSKPS(V) !=/== 0 -> TESTPS(V,V)
48113 // MOVMSKPD(V) !=/== 0 -> TESTPD(V,V)
48114 // MOVMSKPS(V) !=/== -1 -> TESTPS(V,V)
48115 // MOVMSKPD(V) !=/== -1 -> TESTPD(V,V)
48116 // iff every element is referenced.
48117 if (NumElts <= CmpBits && Subtarget.hasAVX() &&
48118 !Subtarget.preferMovmskOverVTest() && IsOneUse &&
48119 (NumEltBits == 32 || NumEltBits == 64)) {
48120 SDLoc DL(EFLAGS);
48121 MVT FloatSVT = MVT::getFloatingPointVT(NumEltBits);
48122 MVT FloatVT = MVT::getVectorVT(FloatSVT, NumElts);
48123 MVT IntVT = FloatVT.changeVectorElementTypeToInteger();
48124 SDValue LHS = Vec;
48125 SDValue RHS = IsAnyOf ? Vec : DAG.getAllOnesConstant(DL, IntVT);
48126 CC = IsAnyOf ? CC : (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
48127 return DAG.getNode(X86ISD::TESTP, DL, MVT::i32,
48128 DAG.getBitcast(FloatVT, LHS),
48129 DAG.getBitcast(FloatVT, RHS));
48132 return SDValue();
48135 /// Optimize an EFLAGS definition used according to the condition code \p CC
48136 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
48137 /// uses of chain values.
48138 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
48139 SelectionDAG &DAG,
48140 const X86Subtarget &Subtarget) {
48141 if (CC == X86::COND_B)
48142 if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
48143 return Flags;
48145 if (SDValue R = checkSignTestSetCCCombine(EFLAGS, CC, DAG))
48146 return R;
48148 if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
48149 return R;
48151 if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
48152 return R;
48154 if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
48155 return R;
48157 return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
48160 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
48161 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
48162 TargetLowering::DAGCombinerInfo &DCI,
48163 const X86Subtarget &Subtarget) {
48164 SDLoc DL(N);
48166 SDValue FalseOp = N->getOperand(0);
48167 SDValue TrueOp = N->getOperand(1);
48168 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
48169 SDValue Cond = N->getOperand(3);
48171 // cmov X, X, ?, ? --> X
48172 if (TrueOp == FalseOp)
48173 return TrueOp;
48175 // Try to simplify the EFLAGS and condition code operands.
48176 // We can't always do this as FCMOV only supports a subset of X86 cond.
48177 if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
48178 if (!(FalseOp.getValueType() == MVT::f80 ||
48179 (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
48180 (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
48181 !Subtarget.canUseCMOV() || hasFPCMov(CC)) {
48182 SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
48183 Flags};
48184 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48188 // If this is a select between two integer constants, try to do some
48189 // optimizations. Note that the operands are ordered the opposite of SELECT
48190 // operands.
48191 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
48192 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
48193 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
48194 // larger than FalseC (the false value).
48195 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
48196 CC = X86::GetOppositeBranchCondition(CC);
48197 std::swap(TrueC, FalseC);
48198 std::swap(TrueOp, FalseOp);
48201 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
48202 // This is efficient for any integer data type (including i8/i16) and
48203 // shift amount.
48204 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
48205 Cond = getSETCC(CC, Cond, DL, DAG);
48207 // Zero extend the condition if needed.
48208 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
48210 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
48211 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
48212 DAG.getConstant(ShAmt, DL, MVT::i8));
48213 return Cond;
48216 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
48217 // for any integer data type, including i8/i16.
48218 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
48219 Cond = getSETCC(CC, Cond, DL, DAG);
48221 // Zero extend the condition if needed.
48222 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
48223 FalseC->getValueType(0), Cond);
48224 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
48225 SDValue(FalseC, 0));
48226 return Cond;
48229 // Optimize cases that will turn into an LEA instruction. This requires
48230 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
48231 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
48232 APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
48233 assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
48234 "Implicit constant truncation");
48236 bool isFastMultiplier = false;
48237 if (Diff.ult(10)) {
48238 switch (Diff.getZExtValue()) {
48239 default: break;
48240 case 1: // result = add base, cond
48241 case 2: // result = lea base( , cond*2)
48242 case 3: // result = lea base(cond, cond*2)
48243 case 4: // result = lea base( , cond*4)
48244 case 5: // result = lea base(cond, cond*4)
48245 case 8: // result = lea base( , cond*8)
48246 case 9: // result = lea base(cond, cond*8)
48247 isFastMultiplier = true;
48248 break;
48252 if (isFastMultiplier) {
48253 Cond = getSETCC(CC, Cond, DL ,DAG);
48254 // Zero extend the condition if needed.
48255 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
48256 Cond);
48257 // Scale the condition by the difference.
48258 if (Diff != 1)
48259 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
48260 DAG.getConstant(Diff, DL, Cond.getValueType()));
48262 // Add the base if non-zero.
48263 if (FalseC->getAPIntValue() != 0)
48264 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
48265 SDValue(FalseC, 0));
48266 return Cond;
48272 // Handle these cases:
48273 // (select (x != c), e, c) -> select (x != c), e, x),
48274 // (select (x == c), c, e) -> select (x == c), x, e)
48275 // where the c is an integer constant, and the "select" is the combination
48276 // of CMOV and CMP.
48278 // The rationale for this change is that the conditional-move from a constant
48279 // needs two instructions, however, conditional-move from a register needs
48280 // only one instruction.
48282 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
48283 // some instruction-combining opportunities. This opt needs to be
48284 // postponed as late as possible.
48286 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
48287 // the DCI.xxxx conditions are provided to postpone the optimization as
48288 // late as possible.
48290 ConstantSDNode *CmpAgainst = nullptr;
48291 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
48292 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
48293 !isa<ConstantSDNode>(Cond.getOperand(0))) {
48295 if (CC == X86::COND_NE &&
48296 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
48297 CC = X86::GetOppositeBranchCondition(CC);
48298 std::swap(TrueOp, FalseOp);
48301 if (CC == X86::COND_E &&
48302 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
48303 SDValue Ops[] = {FalseOp, Cond.getOperand(0),
48304 DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
48305 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48310 // Transform:
48312 // (cmov 1 T (uge T 2))
48314 // to:
48316 // (adc T 0 (sub T 1))
48317 if (CC == X86::COND_AE && isOneConstant(FalseOp) &&
48318 Cond.getOpcode() == X86ISD::SUB && Cond->hasOneUse()) {
48319 SDValue Cond0 = Cond.getOperand(0);
48320 if (Cond0.getOpcode() == ISD::TRUNCATE)
48321 Cond0 = Cond0.getOperand(0);
48322 auto *Sub1C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
48323 if (Cond0 == TrueOp && Sub1C && Sub1C->getZExtValue() == 2) {
48324 EVT CondVT = Cond->getValueType(0);
48325 EVT OuterVT = N->getValueType(0);
48326 // Subtract 1 and generate a carry.
48327 SDValue NewSub =
48328 DAG.getNode(X86ISD::SUB, DL, Cond->getVTList(), Cond.getOperand(0),
48329 DAG.getConstant(1, DL, CondVT));
48330 SDValue EFLAGS(NewSub.getNode(), 1);
48331 return DAG.getNode(X86ISD::ADC, DL, DAG.getVTList(OuterVT, MVT::i32),
48332 TrueOp, DAG.getConstant(0, DL, OuterVT), EFLAGS);
48336 // Fold and/or of setcc's to double CMOV:
48337 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
48338 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
48340 // This combine lets us generate:
48341 // cmovcc1 (jcc1 if we don't have CMOV)
48342 // cmovcc2 (same)
48343 // instead of:
48344 // setcc1
48345 // setcc2
48346 // and/or
48347 // cmovne (jne if we don't have CMOV)
48348 // When we can't use the CMOV instruction, it might increase branch
48349 // mispredicts.
48350 // When we can use CMOV, or when there is no mispredict, this improves
48351 // throughput and reduces register pressure.
48353 if (CC == X86::COND_NE) {
48354 SDValue Flags;
48355 X86::CondCode CC0, CC1;
48356 bool isAndSetCC;
48357 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
48358 if (isAndSetCC) {
48359 std::swap(FalseOp, TrueOp);
48360 CC0 = X86::GetOppositeBranchCondition(CC0);
48361 CC1 = X86::GetOppositeBranchCondition(CC1);
48364 SDValue LOps[] = {FalseOp, TrueOp,
48365 DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
48366 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
48367 SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
48368 Flags};
48369 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
48370 return CMOV;
48374 // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
48375 // (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
48376 // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
48377 // (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
48378 if ((CC == X86::COND_NE || CC == X86::COND_E) &&
48379 Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
48380 SDValue Add = TrueOp;
48381 SDValue Const = FalseOp;
48382 // Canonicalize the condition code for easier matching and output.
48383 if (CC == X86::COND_E)
48384 std::swap(Add, Const);
48386 // We might have replaced the constant in the cmov with the LHS of the
48387 // compare. If so change it to the RHS of the compare.
48388 if (Const == Cond.getOperand(0))
48389 Const = Cond.getOperand(1);
48391 // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
48392 if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
48393 Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
48394 (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
48395 Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
48396 Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
48397 EVT VT = N->getValueType(0);
48398 // This should constant fold.
48399 SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
48400 SDValue CMov =
48401 DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
48402 DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
48403 return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
48407 return SDValue();
48410 /// Different mul shrinking modes.
48411 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
48413 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
48414 EVT VT = N->getOperand(0).getValueType();
48415 if (VT.getScalarSizeInBits() != 32)
48416 return false;
48418 assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
48419 unsigned SignBits[2] = {1, 1};
48420 bool IsPositive[2] = {false, false};
48421 for (unsigned i = 0; i < 2; i++) {
48422 SDValue Opd = N->getOperand(i);
48424 SignBits[i] = DAG.ComputeNumSignBits(Opd);
48425 IsPositive[i] = DAG.SignBitIsZero(Opd);
48428 bool AllPositive = IsPositive[0] && IsPositive[1];
48429 unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
48430 // When ranges are from -128 ~ 127, use MULS8 mode.
48431 if (MinSignBits >= 25)
48432 Mode = ShrinkMode::MULS8;
48433 // When ranges are from 0 ~ 255, use MULU8 mode.
48434 else if (AllPositive && MinSignBits >= 24)
48435 Mode = ShrinkMode::MULU8;
48436 // When ranges are from -32768 ~ 32767, use MULS16 mode.
48437 else if (MinSignBits >= 17)
48438 Mode = ShrinkMode::MULS16;
48439 // When ranges are from 0 ~ 65535, use MULU16 mode.
48440 else if (AllPositive && MinSignBits >= 16)
48441 Mode = ShrinkMode::MULU16;
48442 else
48443 return false;
48444 return true;
48447 /// When the operands of vector mul are extended from smaller size values,
48448 /// like i8 and i16, the type of mul may be shrinked to generate more
48449 /// efficient code. Two typical patterns are handled:
48450 /// Pattern1:
48451 /// %2 = sext/zext <N x i8> %1 to <N x i32>
48452 /// %4 = sext/zext <N x i8> %3 to <N x i32>
48453 // or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
48454 /// %5 = mul <N x i32> %2, %4
48456 /// Pattern2:
48457 /// %2 = zext/sext <N x i16> %1 to <N x i32>
48458 /// %4 = zext/sext <N x i16> %3 to <N x i32>
48459 /// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
48460 /// %5 = mul <N x i32> %2, %4
48462 /// There are four mul shrinking modes:
48463 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
48464 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
48465 /// generate pmullw+sext32 for it (MULS8 mode).
48466 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
48467 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
48468 /// generate pmullw+zext32 for it (MULU8 mode).
48469 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
48470 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
48471 /// generate pmullw+pmulhw for it (MULS16 mode).
48472 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
48473 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
48474 /// generate pmullw+pmulhuw for it (MULU16 mode).
48475 static SDValue reduceVMULWidth(SDNode *N, const SDLoc &DL, SelectionDAG &DAG,
48476 const X86Subtarget &Subtarget) {
48477 // Check for legality
48478 // pmullw/pmulhw are not supported by SSE.
48479 if (!Subtarget.hasSSE2())
48480 return SDValue();
48482 // Check for profitability
48483 // pmulld is supported since SSE41. It is better to use pmulld
48484 // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
48485 // the expansion.
48486 bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
48487 if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
48488 return SDValue();
48490 ShrinkMode Mode;
48491 if (!canReduceVMulWidth(N, DAG, Mode))
48492 return SDValue();
48494 SDValue N0 = N->getOperand(0);
48495 SDValue N1 = N->getOperand(1);
48496 EVT VT = N->getOperand(0).getValueType();
48497 unsigned NumElts = VT.getVectorNumElements();
48498 if ((NumElts % 2) != 0)
48499 return SDValue();
48501 EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
48503 // Shrink the operands of mul.
48504 SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
48505 SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
48507 // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
48508 // lower part is needed.
48509 SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
48510 if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
48511 return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
48512 : ISD::SIGN_EXTEND,
48513 DL, VT, MulLo);
48515 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
48516 // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
48517 // the higher part is also needed.
48518 SDValue MulHi =
48519 DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
48520 ReducedVT, NewN0, NewN1);
48522 // Repack the lower part and higher part result of mul into a wider
48523 // result.
48524 // Generate shuffle functioning as punpcklwd.
48525 SmallVector<int, 16> ShuffleMask(NumElts);
48526 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
48527 ShuffleMask[2 * i] = i;
48528 ShuffleMask[2 * i + 1] = i + NumElts;
48530 SDValue ResLo =
48531 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
48532 ResLo = DAG.getBitcast(ResVT, ResLo);
48533 // Generate shuffle functioning as punpckhwd.
48534 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
48535 ShuffleMask[2 * i] = i + NumElts / 2;
48536 ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
48538 SDValue ResHi =
48539 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
48540 ResHi = DAG.getBitcast(ResVT, ResHi);
48541 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
48544 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
48545 EVT VT, const SDLoc &DL) {
48547 auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
48548 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
48549 DAG.getConstant(Mult, DL, VT));
48550 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
48551 DAG.getConstant(Shift, DL, MVT::i8));
48552 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
48553 N->getOperand(0));
48554 return Result;
48557 auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
48558 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
48559 DAG.getConstant(Mul1, DL, VT));
48560 Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
48561 DAG.getConstant(Mul2, DL, VT));
48562 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
48563 N->getOperand(0));
48564 return Result;
48567 switch (MulAmt) {
48568 default:
48569 break;
48570 case 11:
48571 // mul x, 11 => add ((shl (mul x, 5), 1), x)
48572 return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
48573 case 21:
48574 // mul x, 21 => add ((shl (mul x, 5), 2), x)
48575 return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
48576 case 41:
48577 // mul x, 41 => add ((shl (mul x, 5), 3), x)
48578 return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
48579 case 22:
48580 // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
48581 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
48582 combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
48583 case 19:
48584 // mul x, 19 => add ((shl (mul x, 9), 1), x)
48585 return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
48586 case 37:
48587 // mul x, 37 => add ((shl (mul x, 9), 2), x)
48588 return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
48589 case 73:
48590 // mul x, 73 => add ((shl (mul x, 9), 3), x)
48591 return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
48592 case 13:
48593 // mul x, 13 => add ((shl (mul x, 3), 2), x)
48594 return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
48595 case 23:
48596 // mul x, 23 => sub ((shl (mul x, 3), 3), x)
48597 return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
48598 case 26:
48599 // mul x, 26 => add ((mul (mul x, 5), 5), x)
48600 return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
48601 case 28:
48602 // mul x, 28 => add ((mul (mul x, 9), 3), x)
48603 return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
48604 case 29:
48605 // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
48606 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
48607 combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
48610 // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
48611 // by a single LEA.
48612 // First check if this a sum of two power of 2s because that's easy. Then
48613 // count how many zeros are up to the first bit.
48614 // TODO: We can do this even without LEA at a cost of two shifts and an add.
48615 if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
48616 unsigned ScaleShift = llvm::countr_zero(MulAmt);
48617 if (ScaleShift >= 1 && ScaleShift < 4) {
48618 unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
48619 SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48620 DAG.getConstant(ShiftAmt, DL, MVT::i8));
48621 SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48622 DAG.getConstant(ScaleShift, DL, MVT::i8));
48623 return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
48627 return SDValue();
48630 // If the upper 17 bits of either element are zero and the other element are
48631 // zero/sign bits then we can use PMADDWD, which is always at least as quick as
48632 // PMULLD, except on KNL.
48633 static SDValue combineMulToPMADDWD(SDNode *N, const SDLoc &DL,
48634 SelectionDAG &DAG,
48635 const X86Subtarget &Subtarget) {
48636 if (!Subtarget.hasSSE2())
48637 return SDValue();
48639 if (Subtarget.isPMADDWDSlow())
48640 return SDValue();
48642 EVT VT = N->getValueType(0);
48644 // Only support vXi32 vectors.
48645 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
48646 return SDValue();
48648 // Make sure the type is legal or can split/widen to a legal type.
48649 // With AVX512 but without BWI, we would need to split v32i16.
48650 unsigned NumElts = VT.getVectorNumElements();
48651 if (NumElts == 1 || !isPowerOf2_32(NumElts))
48652 return SDValue();
48654 // With AVX512 but without BWI, we would need to split v32i16.
48655 if (32 <= (2 * NumElts) && Subtarget.hasAVX512() && !Subtarget.hasBWI())
48656 return SDValue();
48658 SDValue N0 = N->getOperand(0);
48659 SDValue N1 = N->getOperand(1);
48661 // If we are zero/sign extending two steps without SSE4.1, its better to
48662 // reduce the vmul width instead.
48663 if (!Subtarget.hasSSE41() &&
48664 (((N0.getOpcode() == ISD::ZERO_EXTEND &&
48665 N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
48666 (N1.getOpcode() == ISD::ZERO_EXTEND &&
48667 N1.getOperand(0).getScalarValueSizeInBits() <= 8)) ||
48668 ((N0.getOpcode() == ISD::SIGN_EXTEND &&
48669 N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
48670 (N1.getOpcode() == ISD::SIGN_EXTEND &&
48671 N1.getOperand(0).getScalarValueSizeInBits() <= 8))))
48672 return SDValue();
48674 // If we are sign extending a wide vector without SSE4.1, its better to reduce
48675 // the vmul width instead.
48676 if (!Subtarget.hasSSE41() &&
48677 (N0.getOpcode() == ISD::SIGN_EXTEND &&
48678 N0.getOperand(0).getValueSizeInBits() > 128) &&
48679 (N1.getOpcode() == ISD::SIGN_EXTEND &&
48680 N1.getOperand(0).getValueSizeInBits() > 128))
48681 return SDValue();
48683 // Sign bits must extend down to the lowest i16.
48684 if (DAG.ComputeMaxSignificantBits(N1) > 16 ||
48685 DAG.ComputeMaxSignificantBits(N0) > 16)
48686 return SDValue();
48688 // At least one of the elements must be zero in the upper 17 bits, or can be
48689 // safely made zero without altering the final result.
48690 auto GetZeroableOp = [&](SDValue Op) {
48691 APInt Mask17 = APInt::getHighBitsSet(32, 17);
48692 if (DAG.MaskedValueIsZero(Op, Mask17))
48693 return Op;
48694 // Mask off upper 16-bits of sign-extended constants.
48695 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()))
48696 return DAG.getNode(ISD::AND, DL, VT, Op, DAG.getConstant(0xFFFF, DL, VT));
48697 if (Op.getOpcode() == ISD::SIGN_EXTEND && N->isOnlyUserOf(Op.getNode())) {
48698 SDValue Src = Op.getOperand(0);
48699 // Convert sext(vXi16) to zext(vXi16).
48700 if (Src.getScalarValueSizeInBits() == 16 && VT.getSizeInBits() <= 128)
48701 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Src);
48702 // Convert sext(vXi8) to zext(vXi16 sext(vXi8)) on pre-SSE41 targets
48703 // which will expand the extension.
48704 if (Src.getScalarValueSizeInBits() < 16 && !Subtarget.hasSSE41()) {
48705 EVT ExtVT = VT.changeVectorElementType(MVT::i16);
48706 Src = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, Src);
48707 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Src);
48710 // Convert SIGN_EXTEND_VECTOR_INREG to ZEXT_EXTEND_VECTOR_INREG.
48711 if (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG &&
48712 N->isOnlyUserOf(Op.getNode())) {
48713 SDValue Src = Op.getOperand(0);
48714 if (Src.getScalarValueSizeInBits() == 16)
48715 return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Src);
48717 // Convert VSRAI(Op, 16) to VSRLI(Op, 16).
48718 if (Op.getOpcode() == X86ISD::VSRAI && Op.getConstantOperandVal(1) == 16 &&
48719 N->isOnlyUserOf(Op.getNode())) {
48720 return DAG.getNode(X86ISD::VSRLI, DL, VT, Op.getOperand(0),
48721 Op.getOperand(1));
48723 return SDValue();
48725 SDValue ZeroN0 = GetZeroableOp(N0);
48726 SDValue ZeroN1 = GetZeroableOp(N1);
48727 if (!ZeroN0 && !ZeroN1)
48728 return SDValue();
48729 N0 = ZeroN0 ? ZeroN0 : N0;
48730 N1 = ZeroN1 ? ZeroN1 : N1;
48732 // Use SplitOpsAndApply to handle AVX splitting.
48733 auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48734 ArrayRef<SDValue> Ops) {
48735 MVT ResVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
48736 MVT OpVT = MVT::getVectorVT(MVT::i16, Ops[0].getValueSizeInBits() / 16);
48737 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
48738 DAG.getBitcast(OpVT, Ops[0]),
48739 DAG.getBitcast(OpVT, Ops[1]));
48741 return SplitOpsAndApply(DAG, Subtarget, DL, VT, {N0, N1}, PMADDWDBuilder);
48744 static SDValue combineMulToPMULDQ(SDNode *N, const SDLoc &DL, SelectionDAG &DAG,
48745 const X86Subtarget &Subtarget) {
48746 if (!Subtarget.hasSSE2())
48747 return SDValue();
48749 EVT VT = N->getValueType(0);
48751 // Only support vXi64 vectors.
48752 if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
48753 VT.getVectorNumElements() < 2 ||
48754 !isPowerOf2_32(VT.getVectorNumElements()))
48755 return SDValue();
48757 SDValue N0 = N->getOperand(0);
48758 SDValue N1 = N->getOperand(1);
48760 // MULDQ returns the 64-bit result of the signed multiplication of the lower
48761 // 32-bits. We can lower with this if the sign bits stretch that far.
48762 if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
48763 DAG.ComputeNumSignBits(N1) > 32) {
48764 auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48765 ArrayRef<SDValue> Ops) {
48766 return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
48768 return SplitOpsAndApply(DAG, Subtarget, DL, VT, {N0, N1}, PMULDQBuilder,
48769 /*CheckBWI*/ false);
48772 // If the upper bits are zero we can use a single pmuludq.
48773 APInt Mask = APInt::getHighBitsSet(64, 32);
48774 if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
48775 auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48776 ArrayRef<SDValue> Ops) {
48777 return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
48779 return SplitOpsAndApply(DAG, Subtarget, DL, VT, {N0, N1}, PMULUDQBuilder,
48780 /*CheckBWI*/ false);
48783 return SDValue();
48786 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
48787 TargetLowering::DAGCombinerInfo &DCI,
48788 const X86Subtarget &Subtarget) {
48789 EVT VT = N->getValueType(0);
48790 SDLoc DL(N);
48792 if (SDValue V = combineMulToPMADDWD(N, DL, DAG, Subtarget))
48793 return V;
48795 if (SDValue V = combineMulToPMULDQ(N, DL, DAG, Subtarget))
48796 return V;
48798 if (DCI.isBeforeLegalize() && VT.isVector())
48799 return reduceVMULWidth(N, DL, DAG, Subtarget);
48801 if (VT != MVT::i64 && VT != MVT::i32 &&
48802 (!VT.isVector() || !VT.isSimple() || !VT.isInteger()))
48803 return SDValue();
48805 KnownBits Known1 = DAG.computeKnownBits(N->getOperand(1));
48806 if (!Known1.isConstant())
48807 return SDValue();
48809 const APInt &C = Known1.getConstant();
48810 if (C.isZero())
48811 return DAG.getConstant(0, DL, VT);
48813 if (C.isAllOnes())
48814 return DAG.getNegative(N->getOperand(0), DL, VT);
48816 if (isPowerOf2_64(C.getZExtValue()))
48817 return SDValue();
48819 // Optimize a single multiply with constant into two operations in order to
48820 // implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
48821 if (!MulConstantOptimization)
48822 return SDValue();
48824 // An imul is usually smaller than the alternative sequence.
48825 if (DAG.getMachineFunction().getFunction().hasMinSize())
48826 return SDValue();
48828 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
48829 return SDValue();
48831 int64_t SignMulAmt = C.getSExtValue();
48832 assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
48833 uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
48835 SDValue NewMul = SDValue();
48836 if (VT == MVT::i64 || VT == MVT::i32) {
48837 if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
48838 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
48839 DAG.getConstant(AbsMulAmt, DL, VT));
48840 if (SignMulAmt < 0)
48841 NewMul = DAG.getNegative(NewMul, DL, VT);
48843 return NewMul;
48846 uint64_t MulAmt1 = 0;
48847 uint64_t MulAmt2 = 0;
48848 if ((AbsMulAmt % 9) == 0) {
48849 MulAmt1 = 9;
48850 MulAmt2 = AbsMulAmt / 9;
48851 } else if ((AbsMulAmt % 5) == 0) {
48852 MulAmt1 = 5;
48853 MulAmt2 = AbsMulAmt / 5;
48854 } else if ((AbsMulAmt % 3) == 0) {
48855 MulAmt1 = 3;
48856 MulAmt2 = AbsMulAmt / 3;
48859 // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
48860 if (MulAmt2 &&
48861 (isPowerOf2_64(MulAmt2) ||
48862 (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
48864 if (isPowerOf2_64(MulAmt2) && !(SignMulAmt >= 0 && N->hasOneUse() &&
48865 N->use_begin()->getOpcode() == ISD::ADD))
48866 // If second multiplifer is pow2, issue it first. We want the multiply
48867 // by 3, 5, or 9 to be folded into the addressing mode unless the lone
48868 // use is an add. Only do this for positive multiply amounts since the
48869 // negate would prevent it from being used as an address mode anyway.
48870 std::swap(MulAmt1, MulAmt2);
48872 if (isPowerOf2_64(MulAmt1))
48873 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48874 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
48875 else
48876 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
48877 DAG.getConstant(MulAmt1, DL, VT));
48879 if (isPowerOf2_64(MulAmt2))
48880 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
48881 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
48882 else
48883 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
48884 DAG.getConstant(MulAmt2, DL, VT));
48886 // Negate the result.
48887 if (SignMulAmt < 0)
48888 NewMul = DAG.getNegative(NewMul, DL, VT);
48889 } else if (!Subtarget.slowLEA())
48890 NewMul = combineMulSpecial(C.getZExtValue(), N, DAG, VT, DL);
48892 if (!NewMul) {
48893 EVT ShiftVT = VT.isVector() ? VT : MVT::i8;
48894 if (isPowerOf2_64(AbsMulAmt - 1)) {
48895 // (mul x, 2^N + 1) => (add (shl x, N), x)
48896 NewMul = DAG.getNode(
48897 ISD::ADD, DL, VT, N->getOperand(0),
48898 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48899 DAG.getConstant(Log2_64(AbsMulAmt - 1), DL, ShiftVT)));
48900 if (SignMulAmt < 0)
48901 NewMul = DAG.getNegative(NewMul, DL, VT);
48902 } else if (isPowerOf2_64(AbsMulAmt + 1)) {
48903 // (mul x, 2^N - 1) => (sub (shl x, N), x)
48904 NewMul =
48905 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48906 DAG.getConstant(Log2_64(AbsMulAmt + 1), DL, ShiftVT));
48907 // To negate, reverse the operands of the subtract.
48908 if (SignMulAmt < 0)
48909 NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
48910 else
48911 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
48912 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2) &&
48913 (!VT.isVector() || Subtarget.fastImmVectorShift())) {
48914 // (mul x, 2^N + 2) => (add (shl x, N), (add x, x))
48915 NewMul =
48916 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48917 DAG.getConstant(Log2_64(AbsMulAmt - 2), DL, ShiftVT));
48918 NewMul = DAG.getNode(
48919 ISD::ADD, DL, VT, NewMul,
48920 DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
48921 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2) &&
48922 (!VT.isVector() || Subtarget.fastImmVectorShift())) {
48923 // (mul x, 2^N - 2) => (sub (shl x, N), (add x, x))
48924 NewMul =
48925 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48926 DAG.getConstant(Log2_64(AbsMulAmt + 2), DL, ShiftVT));
48927 NewMul = DAG.getNode(
48928 ISD::SUB, DL, VT, NewMul,
48929 DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
48930 } else if (SignMulAmt >= 0 && VT.isVector() &&
48931 Subtarget.fastImmVectorShift()) {
48932 uint64_t AbsMulAmtLowBit = AbsMulAmt & (-AbsMulAmt);
48933 uint64_t ShiftAmt1;
48934 std::optional<unsigned> Opc;
48935 if (isPowerOf2_64(AbsMulAmt - AbsMulAmtLowBit)) {
48936 ShiftAmt1 = AbsMulAmt - AbsMulAmtLowBit;
48937 Opc = ISD::ADD;
48938 } else if (isPowerOf2_64(AbsMulAmt + AbsMulAmtLowBit)) {
48939 ShiftAmt1 = AbsMulAmt + AbsMulAmtLowBit;
48940 Opc = ISD::SUB;
48943 if (Opc) {
48944 SDValue Shift1 =
48945 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48946 DAG.getConstant(Log2_64(ShiftAmt1), DL, ShiftVT));
48947 SDValue Shift2 =
48948 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
48949 DAG.getConstant(Log2_64(AbsMulAmtLowBit), DL, ShiftVT));
48950 NewMul = DAG.getNode(*Opc, DL, VT, Shift1, Shift2);
48955 return NewMul;
48958 // Try to form a MULHU or MULHS node by looking for
48959 // (srl (mul ext, ext), 16)
48960 // TODO: This is X86 specific because we want to be able to handle wide types
48961 // before type legalization. But we can only do it if the vector will be
48962 // legalized via widening/splitting. Type legalization can't handle promotion
48963 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
48964 // combiner.
48965 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
48966 const SDLoc &DL,
48967 const X86Subtarget &Subtarget) {
48968 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
48969 "SRL or SRA node is required here!");
48971 if (!Subtarget.hasSSE2())
48972 return SDValue();
48974 // The operation feeding into the shift must be a multiply.
48975 SDValue ShiftOperand = N->getOperand(0);
48976 if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
48977 return SDValue();
48979 // Input type should be at least vXi32.
48980 EVT VT = N->getValueType(0);
48981 if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
48982 return SDValue();
48984 // Need a shift by 16.
48985 APInt ShiftAmt;
48986 if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
48987 ShiftAmt != 16)
48988 return SDValue();
48990 SDValue LHS = ShiftOperand.getOperand(0);
48991 SDValue RHS = ShiftOperand.getOperand(1);
48993 unsigned ExtOpc = LHS.getOpcode();
48994 if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
48995 RHS.getOpcode() != ExtOpc)
48996 return SDValue();
48998 // Peek through the extends.
48999 LHS = LHS.getOperand(0);
49000 RHS = RHS.getOperand(0);
49002 // Ensure the input types match.
49003 EVT MulVT = LHS.getValueType();
49004 if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
49005 return SDValue();
49007 unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
49008 SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
49010 ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
49011 return DAG.getNode(ExtOpc, DL, VT, Mulh);
49014 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG,
49015 const X86Subtarget &Subtarget) {
49016 using namespace llvm::SDPatternMatch;
49017 SDValue N0 = N->getOperand(0);
49018 SDValue N1 = N->getOperand(1);
49019 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
49020 EVT VT = N0.getValueType();
49021 unsigned EltSizeInBits = VT.getScalarSizeInBits();
49022 SDLoc DL(N);
49024 // Exploits AVX2 VSHLV/VSRLV instructions for efficient unsigned vector shifts
49025 // with out-of-bounds clamping.
49026 if (N0.getOpcode() == ISD::VSELECT &&
49027 supportedVectorVarShift(VT, Subtarget, ISD::SHL)) {
49028 SDValue Cond = N0.getOperand(0);
49029 SDValue N00 = N0.getOperand(1);
49030 SDValue N01 = N0.getOperand(2);
49031 // fold shl(select(icmp_ult(amt,BW),x,0),amt) -> avx2 psllv(x,amt)
49032 if (ISD::isConstantSplatVectorAllZeros(N01.getNode()) &&
49033 sd_match(Cond, m_SetCC(m_Specific(N1), m_SpecificInt(EltSizeInBits),
49034 m_SpecificCondCode(ISD::SETULT)))) {
49035 return DAG.getNode(X86ISD::VSHLV, DL, VT, N00, N1);
49037 // fold shl(select(icmp_uge(amt,BW),0,x),amt) -> avx2 psllv(x,amt)
49038 if (ISD::isConstantSplatVectorAllZeros(N00.getNode()) &&
49039 sd_match(Cond, m_SetCC(m_Specific(N1), m_SpecificInt(EltSizeInBits),
49040 m_SpecificCondCode(ISD::SETUGE)))) {
49041 return DAG.getNode(X86ISD::VSHLV, DL, VT, N01, N1);
49045 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
49046 // since the result of setcc_c is all zero's or all ones.
49047 if (VT.isInteger() && !VT.isVector() &&
49048 N1C && N0.getOpcode() == ISD::AND &&
49049 N0.getOperand(1).getOpcode() == ISD::Constant) {
49050 SDValue N00 = N0.getOperand(0);
49051 APInt Mask = N0.getConstantOperandAPInt(1);
49052 Mask <<= N1C->getAPIntValue();
49053 bool MaskOK = false;
49054 // We can handle cases concerning bit-widening nodes containing setcc_c if
49055 // we carefully interrogate the mask to make sure we are semantics
49056 // preserving.
49057 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
49058 // of the underlying setcc_c operation if the setcc_c was zero extended.
49059 // Consider the following example:
49060 // zext(setcc_c) -> i32 0x0000FFFF
49061 // c1 -> i32 0x0000FFFF
49062 // c2 -> i32 0x00000001
49063 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
49064 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
49065 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
49066 MaskOK = true;
49067 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
49068 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
49069 MaskOK = true;
49070 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
49071 N00.getOpcode() == ISD::ANY_EXTEND) &&
49072 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
49073 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
49075 if (MaskOK && Mask != 0)
49076 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
49079 return SDValue();
49082 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
49083 const X86Subtarget &Subtarget) {
49084 using namespace llvm::SDPatternMatch;
49085 SDValue N0 = N->getOperand(0);
49086 SDValue N1 = N->getOperand(1);
49087 EVT VT = N0.getValueType();
49088 unsigned Size = VT.getSizeInBits();
49089 SDLoc DL(N);
49091 if (SDValue V = combineShiftToPMULH(N, DAG, DL, Subtarget))
49092 return V;
49094 // fold sra(x,umin(amt,bw-1)) -> avx2 psrav(x,amt)
49095 if (supportedVectorVarShift(VT, Subtarget, ISD::SRA)) {
49096 SDValue ShrAmtVal;
49097 if (sd_match(N1, m_UMin(m_Value(ShrAmtVal),
49098 m_SpecificInt(VT.getScalarSizeInBits() - 1))))
49099 return DAG.getNode(X86ISD::VSRAV, DL, VT, N0, ShrAmtVal);
49102 // fold (SRA (SHL X, ShlConst), SraConst)
49103 // into (SHL (sext_in_reg X), ShlConst - SraConst)
49104 // or (sext_in_reg X)
49105 // or (SRA (sext_in_reg X), SraConst - ShlConst)
49106 // depending on relation between SraConst and ShlConst.
49107 // We only do this if (Size - ShlConst) is equal to 8, 16 or 32. That allows
49108 // us to do the sext_in_reg from corresponding bit.
49110 // sexts in X86 are MOVs. The MOVs have the same code size
49111 // as above SHIFTs (only SHIFT on 1 has lower code size).
49112 // However the MOVs have 2 advantages to a SHIFT:
49113 // 1. MOVs can write to a register that differs from source
49114 // 2. MOVs accept memory operands
49116 if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
49117 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
49118 N0.getOperand(1).getOpcode() != ISD::Constant)
49119 return SDValue();
49121 SDValue N00 = N0.getOperand(0);
49122 SDValue N01 = N0.getOperand(1);
49123 APInt ShlConst = N01->getAsAPIntVal();
49124 APInt SraConst = N1->getAsAPIntVal();
49125 EVT CVT = N1.getValueType();
49127 if (CVT != N01.getValueType())
49128 return SDValue();
49129 if (SraConst.isNegative())
49130 return SDValue();
49132 for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
49133 unsigned ShiftSize = SVT.getSizeInBits();
49134 // Only deal with (Size - ShlConst) being equal to 8, 16 or 32.
49135 if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
49136 continue;
49137 SDValue NN =
49138 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
49139 if (SraConst.eq(ShlConst))
49140 return NN;
49141 if (SraConst.ult(ShlConst))
49142 return DAG.getNode(ISD::SHL, DL, VT, NN,
49143 DAG.getConstant(ShlConst - SraConst, DL, CVT));
49144 return DAG.getNode(ISD::SRA, DL, VT, NN,
49145 DAG.getConstant(SraConst - ShlConst, DL, CVT));
49147 return SDValue();
49150 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
49151 TargetLowering::DAGCombinerInfo &DCI,
49152 const X86Subtarget &Subtarget) {
49153 using namespace llvm::SDPatternMatch;
49154 SDValue N0 = N->getOperand(0);
49155 SDValue N1 = N->getOperand(1);
49156 EVT VT = N0.getValueType();
49157 unsigned EltSizeInBits = VT.getScalarSizeInBits();
49158 SDLoc DL(N);
49160 if (SDValue V = combineShiftToPMULH(N, DAG, DL, Subtarget))
49161 return V;
49163 // Exploits AVX2 VSHLV/VSRLV instructions for efficient unsigned vector shifts
49164 // with out-of-bounds clamping.
49165 if (N0.getOpcode() == ISD::VSELECT &&
49166 supportedVectorVarShift(VT, Subtarget, ISD::SRL)) {
49167 SDValue Cond = N0.getOperand(0);
49168 SDValue N00 = N0.getOperand(1);
49169 SDValue N01 = N0.getOperand(2);
49170 // fold srl(select(icmp_ult(amt,BW),x,0),amt) -> avx2 psrlv(x,amt)
49171 if (ISD::isConstantSplatVectorAllZeros(N01.getNode()) &&
49172 sd_match(Cond, m_SetCC(m_Specific(N1), m_SpecificInt(EltSizeInBits),
49173 m_SpecificCondCode(ISD::SETULT)))) {
49174 return DAG.getNode(X86ISD::VSRLV, DL, VT, N00, N1);
49176 // fold srl(select(icmp_uge(amt,BW),0,x),amt) -> avx2 psrlv(x,amt)
49177 if (ISD::isConstantSplatVectorAllZeros(N00.getNode()) &&
49178 sd_match(Cond, m_SetCC(m_Specific(N1), m_SpecificInt(EltSizeInBits),
49179 m_SpecificCondCode(ISD::SETUGE)))) {
49180 return DAG.getNode(X86ISD::VSRLV, DL, VT, N01, N1);
49184 // Only do this on the last DAG combine as it can interfere with other
49185 // combines.
49186 if (!DCI.isAfterLegalizeDAG())
49187 return SDValue();
49189 // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
49190 // TODO: This is a generic DAG combine that became an x86-only combine to
49191 // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
49192 // and-not ('andn').
49193 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
49194 return SDValue();
49196 auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
49197 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
49198 if (!ShiftC || !AndC)
49199 return SDValue();
49201 // If we can shrink the constant mask below 8-bits or 32-bits, then this
49202 // transform should reduce code size. It may also enable secondary transforms
49203 // from improved known-bits analysis or instruction selection.
49204 APInt MaskVal = AndC->getAPIntValue();
49206 // If this can be matched by a zero extend, don't optimize.
49207 if (MaskVal.isMask()) {
49208 unsigned TO = MaskVal.countr_one();
49209 if (TO >= 8 && isPowerOf2_32(TO))
49210 return SDValue();
49213 APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
49214 unsigned OldMaskSize = MaskVal.getSignificantBits();
49215 unsigned NewMaskSize = NewMaskVal.getSignificantBits();
49216 if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
49217 (OldMaskSize > 32 && NewMaskSize <= 32)) {
49218 // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
49219 SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
49220 SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
49221 return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
49223 return SDValue();
49226 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
49227 const X86Subtarget &Subtarget) {
49228 unsigned Opcode = N->getOpcode();
49229 assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode");
49231 SDLoc DL(N);
49232 EVT VT = N->getValueType(0);
49233 SDValue N0 = N->getOperand(0);
49234 SDValue N1 = N->getOperand(1);
49235 EVT SrcVT = N0.getValueType();
49237 SDValue BC0 =
49238 N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
49239 SDValue BC1 =
49240 N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
49242 // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
49243 // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
49244 // truncation trees that help us avoid lane crossing shuffles.
49245 // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
49246 // TODO: We don't handle vXf64 shuffles yet.
49247 if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
49248 if (SDValue BCSrc = getSplitVectorSrc(BC0, BC1, false)) {
49249 SmallVector<SDValue> ShuffleOps;
49250 SmallVector<int> ShuffleMask, ScaledMask;
49251 SDValue Vec = peekThroughBitcasts(BCSrc);
49252 if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
49253 resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
49254 // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
49255 // shuffle to a v4X64 width - we can probably relax this in the future.
49256 if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
49257 ShuffleOps[0].getValueType().is256BitVector() &&
49258 scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
49259 SDValue Lo, Hi;
49260 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
49261 std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
49262 Lo = DAG.getBitcast(SrcVT, Lo);
49263 Hi = DAG.getBitcast(SrcVT, Hi);
49264 SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
49265 Res = DAG.getBitcast(ShufVT, Res);
49266 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
49267 return DAG.getBitcast(VT, Res);
49273 // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
49274 if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
49275 // If either/both ops are a shuffle that can scale to v2x64,
49276 // then see if we can perform this as a v4x32 post shuffle.
49277 SmallVector<SDValue> Ops0, Ops1;
49278 SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
49279 bool IsShuf0 =
49280 getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
49281 scaleShuffleElements(Mask0, 2, ScaledMask0) &&
49282 all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
49283 bool IsShuf1 =
49284 getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
49285 scaleShuffleElements(Mask1, 2, ScaledMask1) &&
49286 all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
49287 if (IsShuf0 || IsShuf1) {
49288 if (!IsShuf0) {
49289 Ops0.assign({BC0});
49290 ScaledMask0.assign({0, 1});
49292 if (!IsShuf1) {
49293 Ops1.assign({BC1});
49294 ScaledMask1.assign({0, 1});
49297 SDValue LHS, RHS;
49298 int PostShuffle[4] = {-1, -1, -1, -1};
49299 auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
49300 if (M < 0)
49301 return true;
49302 Idx = M % 2;
49303 SDValue Src = Ops[M / 2];
49304 if (!LHS || LHS == Src) {
49305 LHS = Src;
49306 return true;
49308 if (!RHS || RHS == Src) {
49309 Idx += 2;
49310 RHS = Src;
49311 return true;
49313 return false;
49315 if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
49316 FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
49317 FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
49318 FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
49319 LHS = DAG.getBitcast(SrcVT, LHS);
49320 RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
49321 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
49322 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
49323 Res = DAG.getBitcast(ShufVT, Res);
49324 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
49325 return DAG.getBitcast(VT, Res);
49330 // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
49331 if (VT.is256BitVector() && Subtarget.hasInt256()) {
49332 SmallVector<int> Mask0, Mask1;
49333 SmallVector<SDValue> Ops0, Ops1;
49334 SmallVector<int, 2> ScaledMask0, ScaledMask1;
49335 if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
49336 getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
49337 !Ops0.empty() && !Ops1.empty() &&
49338 all_of(Ops0,
49339 [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
49340 all_of(Ops1,
49341 [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
49342 scaleShuffleElements(Mask0, 2, ScaledMask0) &&
49343 scaleShuffleElements(Mask1, 2, ScaledMask1)) {
49344 SDValue Op00 = peekThroughBitcasts(Ops0.front());
49345 SDValue Op10 = peekThroughBitcasts(Ops1.front());
49346 SDValue Op01 = peekThroughBitcasts(Ops0.back());
49347 SDValue Op11 = peekThroughBitcasts(Ops1.back());
49348 if ((Op00 == Op11) && (Op01 == Op10)) {
49349 std::swap(Op10, Op11);
49350 ShuffleVectorSDNode::commuteMask(ScaledMask1);
49352 if ((Op00 == Op10) && (Op01 == Op11)) {
49353 const int Map[4] = {0, 2, 1, 3};
49354 SmallVector<int, 4> ShuffleMask(
49355 {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
49356 Map[ScaledMask1[1]]});
49357 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
49358 SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
49359 DAG.getBitcast(SrcVT, Op01));
49360 Res = DAG.getBitcast(ShufVT, Res);
49361 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
49362 return DAG.getBitcast(VT, Res);
49367 return SDValue();
49370 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
49371 TargetLowering::DAGCombinerInfo &DCI,
49372 const X86Subtarget &Subtarget) {
49373 unsigned Opcode = N->getOpcode();
49374 assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
49375 "Unexpected pack opcode");
49377 EVT VT = N->getValueType(0);
49378 SDValue N0 = N->getOperand(0);
49379 SDValue N1 = N->getOperand(1);
49380 unsigned NumDstElts = VT.getVectorNumElements();
49381 unsigned DstBitsPerElt = VT.getScalarSizeInBits();
49382 unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
49383 assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
49384 N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
49385 "Unexpected PACKSS/PACKUS input type");
49387 bool IsSigned = (X86ISD::PACKSS == Opcode);
49389 // Constant Folding.
49390 APInt UndefElts0, UndefElts1;
49391 SmallVector<APInt, 32> EltBits0, EltBits1;
49392 if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
49393 (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
49394 getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0,
49395 /*AllowWholeUndefs*/ true,
49396 /*AllowPartialUndefs*/ true) &&
49397 getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1,
49398 /*AllowWholeUndefs*/ true,
49399 /*AllowPartialUndefs*/ true)) {
49400 unsigned NumLanes = VT.getSizeInBits() / 128;
49401 unsigned NumSrcElts = NumDstElts / 2;
49402 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
49403 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
49405 APInt Undefs(NumDstElts, 0);
49406 SmallVector<APInt, 32> Bits(NumDstElts, APInt::getZero(DstBitsPerElt));
49407 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
49408 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
49409 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
49410 auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
49411 auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
49413 if (UndefElts[SrcIdx]) {
49414 Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
49415 continue;
49418 APInt &Val = EltBits[SrcIdx];
49419 if (IsSigned) {
49420 // PACKSS: Truncate signed value with signed saturation.
49421 // Source values less than dst minint are saturated to minint.
49422 // Source values greater than dst maxint are saturated to maxint.
49423 Val = Val.truncSSat(DstBitsPerElt);
49424 } else {
49425 // PACKUS: Truncate signed value with unsigned saturation.
49426 // Source values less than zero are saturated to zero.
49427 // Source values greater than dst maxuint are saturated to maxuint.
49428 // NOTE: This is different from APInt::truncUSat.
49429 if (Val.isIntN(DstBitsPerElt))
49430 Val = Val.trunc(DstBitsPerElt);
49431 else if (Val.isNegative())
49432 Val = APInt::getZero(DstBitsPerElt);
49433 else
49434 Val = APInt::getAllOnes(DstBitsPerElt);
49436 Bits[Lane * NumDstEltsPerLane + Elt] = Val;
49440 return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
49443 // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
49444 if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
49445 return V;
49447 // Try to fold PACKSS(NOT(X),NOT(Y)) -> NOT(PACKSS(X,Y)).
49448 // Currently limit this to allsignbits cases only.
49449 if (IsSigned &&
49450 (N0.isUndef() || DAG.ComputeNumSignBits(N0) == SrcBitsPerElt) &&
49451 (N1.isUndef() || DAG.ComputeNumSignBits(N1) == SrcBitsPerElt)) {
49452 SDValue Not0 = N0.isUndef() ? N0 : IsNOT(N0, DAG);
49453 SDValue Not1 = N1.isUndef() ? N1 : IsNOT(N1, DAG);
49454 if (Not0 && Not1) {
49455 SDLoc DL(N);
49456 MVT SrcVT = N0.getSimpleValueType();
49457 SDValue Pack =
49458 DAG.getNode(X86ISD::PACKSS, DL, VT, DAG.getBitcast(SrcVT, Not0),
49459 DAG.getBitcast(SrcVT, Not1));
49460 return DAG.getNOT(DL, Pack, VT);
49464 // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
49465 // truncate to create a larger truncate.
49466 if (Subtarget.hasAVX512() &&
49467 N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
49468 N0.getOperand(0).getValueType() == MVT::v8i32) {
49469 if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
49470 (!IsSigned &&
49471 DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
49472 if (Subtarget.hasVLX())
49473 return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
49475 // Widen input to v16i32 so we can truncate that.
49476 SDLoc dl(N);
49477 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
49478 N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
49479 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
49483 // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
49484 if (VT.is128BitVector()) {
49485 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
49486 SDValue Src0, Src1;
49487 if (N0.getOpcode() == ExtOpc &&
49488 N0.getOperand(0).getValueType().is64BitVector() &&
49489 N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
49490 Src0 = N0.getOperand(0);
49492 if (N1.getOpcode() == ExtOpc &&
49493 N1.getOperand(0).getValueType().is64BitVector() &&
49494 N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
49495 Src1 = N1.getOperand(0);
49497 if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
49498 assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
49499 Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
49500 Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
49501 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
49504 // Try again with pack(*_extend_vector_inreg, undef).
49505 unsigned VecInRegOpc = IsSigned ? ISD::SIGN_EXTEND_VECTOR_INREG
49506 : ISD::ZERO_EXTEND_VECTOR_INREG;
49507 if (N0.getOpcode() == VecInRegOpc && N1.isUndef() &&
49508 N0.getOperand(0).getScalarValueSizeInBits() < DstBitsPerElt)
49509 return getEXTEND_VECTOR_INREG(ExtOpc, SDLoc(N), VT, N0.getOperand(0),
49510 DAG);
49513 // Attempt to combine as shuffle.
49514 SDValue Op(N, 0);
49515 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49516 return Res;
49518 return SDValue();
49521 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
49522 TargetLowering::DAGCombinerInfo &DCI,
49523 const X86Subtarget &Subtarget) {
49524 assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
49525 X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
49526 "Unexpected horizontal add/sub opcode");
49528 if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
49529 MVT VT = N->getSimpleValueType(0);
49530 SDValue LHS = N->getOperand(0);
49531 SDValue RHS = N->getOperand(1);
49533 // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
49534 if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
49535 LHS.getOpcode() == RHS.getOpcode() &&
49536 LHS.getValueType() == RHS.getValueType() &&
49537 N->isOnlyUserOf(LHS.getNode()) && N->isOnlyUserOf(RHS.getNode())) {
49538 SDValue LHS0 = LHS.getOperand(0);
49539 SDValue LHS1 = LHS.getOperand(1);
49540 SDValue RHS0 = RHS.getOperand(0);
49541 SDValue RHS1 = RHS.getOperand(1);
49542 if ((LHS0 == LHS1 || LHS0.isUndef() || LHS1.isUndef()) &&
49543 (RHS0 == RHS1 || RHS0.isUndef() || RHS1.isUndef())) {
49544 SDLoc DL(N);
49545 SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
49546 LHS0.isUndef() ? LHS1 : LHS0,
49547 RHS0.isUndef() ? RHS1 : RHS0);
49548 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
49549 Res = DAG.getBitcast(ShufVT, Res);
49550 SDValue NewLHS =
49551 DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
49552 getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
49553 SDValue NewRHS =
49554 DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
49555 getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
49556 return DAG.getNode(N->getOpcode(), DL, VT, DAG.getBitcast(VT, NewLHS),
49557 DAG.getBitcast(VT, NewRHS));
49562 // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
49563 if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
49564 return V;
49566 return SDValue();
49569 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
49570 TargetLowering::DAGCombinerInfo &DCI,
49571 const X86Subtarget &Subtarget) {
49572 assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
49573 X86ISD::VSRL == N->getOpcode()) &&
49574 "Unexpected shift opcode");
49575 EVT VT = N->getValueType(0);
49576 SDValue N0 = N->getOperand(0);
49577 SDValue N1 = N->getOperand(1);
49579 // Shift zero -> zero.
49580 if (ISD::isBuildVectorAllZeros(N0.getNode()))
49581 return DAG.getConstant(0, SDLoc(N), VT);
49583 // Detect constant shift amounts.
49584 APInt UndefElts;
49585 SmallVector<APInt, 32> EltBits;
49586 if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits,
49587 /*AllowWholeUndefs*/ true,
49588 /*AllowPartialUndefs*/ false)) {
49589 unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
49590 return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
49591 EltBits[0].getZExtValue(), DAG);
49594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49595 APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
49596 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
49597 return SDValue(N, 0);
49599 return SDValue();
49602 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
49603 TargetLowering::DAGCombinerInfo &DCI,
49604 const X86Subtarget &Subtarget) {
49605 unsigned Opcode = N->getOpcode();
49606 assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
49607 X86ISD::VSRLI == Opcode) &&
49608 "Unexpected shift opcode");
49609 bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
49610 EVT VT = N->getValueType(0);
49611 SDValue N0 = N->getOperand(0);
49612 SDValue N1 = N->getOperand(1);
49613 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
49614 assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
49615 "Unexpected value type");
49616 assert(N1.getValueType() == MVT::i8 && "Unexpected shift amount type");
49618 // (shift undef, X) -> 0
49619 if (N0.isUndef())
49620 return DAG.getConstant(0, SDLoc(N), VT);
49622 // Out of range logical bit shifts are guaranteed to be zero.
49623 // Out of range arithmetic bit shifts splat the sign bit.
49624 unsigned ShiftVal = N->getConstantOperandVal(1);
49625 if (ShiftVal >= NumBitsPerElt) {
49626 if (LogicalShift)
49627 return DAG.getConstant(0, SDLoc(N), VT);
49628 ShiftVal = NumBitsPerElt - 1;
49631 // (shift X, 0) -> X
49632 if (!ShiftVal)
49633 return N0;
49635 // (shift 0, C) -> 0
49636 if (ISD::isBuildVectorAllZeros(N0.getNode()))
49637 // N0 is all zeros or undef. We guarantee that the bits shifted into the
49638 // result are all zeros, not undef.
49639 return DAG.getConstant(0, SDLoc(N), VT);
49641 // (VSRAI -1, C) -> -1
49642 if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
49643 // N0 is all ones or undef. We guarantee that the bits shifted into the
49644 // result are all ones, not undef.
49645 return DAG.getAllOnesConstant(SDLoc(N), VT);
49647 auto MergeShifts = [&](SDValue X, uint64_t Amt0, uint64_t Amt1) {
49648 unsigned NewShiftVal = Amt0 + Amt1;
49649 if (NewShiftVal >= NumBitsPerElt) {
49650 // Out of range logical bit shifts are guaranteed to be zero.
49651 // Out of range arithmetic bit shifts splat the sign bit.
49652 if (LogicalShift)
49653 return DAG.getConstant(0, SDLoc(N), VT);
49654 NewShiftVal = NumBitsPerElt - 1;
49656 return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
49657 DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
49660 // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
49661 if (Opcode == N0.getOpcode())
49662 return MergeShifts(N0.getOperand(0), ShiftVal, N0.getConstantOperandVal(1));
49664 // (shl (add X, X), C) -> (shl X, (C + 1))
49665 if (Opcode == X86ISD::VSHLI && N0.getOpcode() == ISD::ADD &&
49666 N0.getOperand(0) == N0.getOperand(1))
49667 return MergeShifts(N0.getOperand(0), ShiftVal, 1);
49669 // We can decode 'whole byte' logical bit shifts as shuffles.
49670 if (LogicalShift && (ShiftVal % 8) == 0) {
49671 SDValue Op(N, 0);
49672 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49673 return Res;
49676 // Attempt to detect an expanded vXi64 SIGN_EXTEND_INREG vXi1 pattern, and
49677 // convert to a splatted v2Xi32 SIGN_EXTEND_INREG pattern:
49678 // psrad(pshufd(psllq(X,63),1,1,3,3),31) ->
49679 // pshufd(psrad(pslld(X,31),31),0,0,2,2).
49680 if (Opcode == X86ISD::VSRAI && NumBitsPerElt == 32 && ShiftVal == 31 &&
49681 N0.getOpcode() == X86ISD::PSHUFD &&
49682 N0.getConstantOperandVal(1) == getV4X86ShuffleImm({1, 1, 3, 3}) &&
49683 N0->hasOneUse()) {
49684 SDValue BC = peekThroughOneUseBitcasts(N0.getOperand(0));
49685 if (BC.getOpcode() == X86ISD::VSHLI &&
49686 BC.getScalarValueSizeInBits() == 64 &&
49687 BC.getConstantOperandVal(1) == 63) {
49688 SDLoc DL(N);
49689 SDValue Src = BC.getOperand(0);
49690 Src = DAG.getBitcast(VT, Src);
49691 Src = DAG.getNode(X86ISD::PSHUFD, DL, VT, Src,
49692 getV4X86ShuffleImm8ForMask({0, 0, 2, 2}, DL, DAG));
49693 Src = DAG.getNode(X86ISD::VSHLI, DL, VT, Src, N1);
49694 Src = DAG.getNode(X86ISD::VSRAI, DL, VT, Src, N1);
49695 return Src;
49699 auto TryConstantFold = [&](SDValue V) {
49700 APInt UndefElts;
49701 SmallVector<APInt, 32> EltBits;
49702 if (!getTargetConstantBitsFromNode(V, NumBitsPerElt, UndefElts, EltBits,
49703 /*AllowWholeUndefs*/ true,
49704 /*AllowPartialUndefs*/ true))
49705 return SDValue();
49706 assert(EltBits.size() == VT.getVectorNumElements() &&
49707 "Unexpected shift value type");
49708 // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
49709 // created an undef input due to no input bits being demanded, but user
49710 // still expects 0 in other bits.
49711 for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
49712 APInt &Elt = EltBits[i];
49713 if (UndefElts[i])
49714 Elt = 0;
49715 else if (X86ISD::VSHLI == Opcode)
49716 Elt <<= ShiftVal;
49717 else if (X86ISD::VSRAI == Opcode)
49718 Elt.ashrInPlace(ShiftVal);
49719 else
49720 Elt.lshrInPlace(ShiftVal);
49722 // Reset undef elements since they were zeroed above.
49723 UndefElts = 0;
49724 return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
49727 // Constant Folding.
49728 if (N->isOnlyUserOf(N0.getNode())) {
49729 if (SDValue C = TryConstantFold(N0))
49730 return C;
49732 // Fold (shift (logic X, C2), C1) -> (logic (shift X, C1), (shift C2, C1))
49733 // Don't break NOT patterns.
49734 SDValue BC = peekThroughOneUseBitcasts(N0);
49735 if (ISD::isBitwiseLogicOp(BC.getOpcode()) &&
49736 BC->isOnlyUserOf(BC.getOperand(1).getNode()) &&
49737 !ISD::isBuildVectorAllOnes(BC.getOperand(1).getNode())) {
49738 if (SDValue RHS = TryConstantFold(BC.getOperand(1))) {
49739 SDLoc DL(N);
49740 SDValue LHS = DAG.getNode(Opcode, DL, VT,
49741 DAG.getBitcast(VT, BC.getOperand(0)), N1);
49742 return DAG.getNode(BC.getOpcode(), DL, VT, LHS, RHS);
49747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49748 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBitsPerElt),
49749 DCI))
49750 return SDValue(N, 0);
49752 return SDValue();
49755 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
49756 TargetLowering::DAGCombinerInfo &DCI,
49757 const X86Subtarget &Subtarget) {
49758 EVT VT = N->getValueType(0);
49759 unsigned Opcode = N->getOpcode();
49760 assert(((Opcode == X86ISD::PINSRB && VT == MVT::v16i8) ||
49761 (Opcode == X86ISD::PINSRW && VT == MVT::v8i16) ||
49762 Opcode == ISD::INSERT_VECTOR_ELT) &&
49763 "Unexpected vector insertion");
49765 SDValue Vec = N->getOperand(0);
49766 SDValue Scl = N->getOperand(1);
49767 SDValue Idx = N->getOperand(2);
49769 // Fold insert_vector_elt(undef, elt, 0) --> scalar_to_vector(elt).
49770 if (Opcode == ISD::INSERT_VECTOR_ELT && Vec.isUndef() && isNullConstant(Idx))
49771 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Scl);
49773 if (Opcode == X86ISD::PINSRB || Opcode == X86ISD::PINSRW) {
49774 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
49775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49776 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
49777 APInt::getAllOnes(NumBitsPerElt), DCI))
49778 return SDValue(N, 0);
49781 // Attempt to combine insertion patterns to a shuffle.
49782 if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
49783 SDValue Op(N, 0);
49784 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49785 return Res;
49788 return SDValue();
49791 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
49792 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
49793 /// OR -> CMPNEQSS.
49794 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
49795 TargetLowering::DAGCombinerInfo &DCI,
49796 const X86Subtarget &Subtarget) {
49797 unsigned opcode;
49799 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
49800 // we're requiring SSE2 for both.
49801 if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
49802 SDValue N0 = N->getOperand(0);
49803 SDValue N1 = N->getOperand(1);
49804 SDValue CMP0 = N0.getOperand(1);
49805 SDValue CMP1 = N1.getOperand(1);
49806 SDLoc DL(N);
49808 // The SETCCs should both refer to the same CMP.
49809 if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
49810 return SDValue();
49812 SDValue CMP00 = CMP0->getOperand(0);
49813 SDValue CMP01 = CMP0->getOperand(1);
49814 EVT VT = CMP00.getValueType();
49816 if (VT == MVT::f32 || VT == MVT::f64 ||
49817 (VT == MVT::f16 && Subtarget.hasFP16())) {
49818 bool ExpectingFlags = false;
49819 // Check for any users that want flags:
49820 for (const SDNode *U : N->uses()) {
49821 if (ExpectingFlags)
49822 break;
49824 switch (U->getOpcode()) {
49825 default:
49826 case ISD::BR_CC:
49827 case ISD::BRCOND:
49828 case ISD::SELECT:
49829 ExpectingFlags = true;
49830 break;
49831 case ISD::CopyToReg:
49832 case ISD::SIGN_EXTEND:
49833 case ISD::ZERO_EXTEND:
49834 case ISD::ANY_EXTEND:
49835 break;
49839 if (!ExpectingFlags) {
49840 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
49841 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
49843 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
49844 X86::CondCode tmp = cc0;
49845 cc0 = cc1;
49846 cc1 = tmp;
49849 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
49850 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
49851 // FIXME: need symbolic constants for these magic numbers.
49852 // See X86ATTInstPrinter.cpp:printSSECC().
49853 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
49854 if (Subtarget.hasAVX512()) {
49855 SDValue FSetCC =
49856 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
49857 DAG.getTargetConstant(x86cc, DL, MVT::i8));
49858 // Need to fill with zeros to ensure the bitcast will produce zeroes
49859 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
49860 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
49861 DAG.getConstant(0, DL, MVT::v16i1),
49862 FSetCC, DAG.getIntPtrConstant(0, DL));
49863 return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
49864 N->getSimpleValueType(0));
49866 SDValue OnesOrZeroesF =
49867 DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
49868 CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
49870 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
49871 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
49873 if (is64BitFP && !Subtarget.is64Bit()) {
49874 // On a 32-bit target, we cannot bitcast the 64-bit float to a
49875 // 64-bit integer, since that's not a legal type. Since
49876 // OnesOrZeroesF is all ones or all zeroes, we don't need all the
49877 // bits, but can do this little dance to extract the lowest 32 bits
49878 // and work with those going forward.
49879 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
49880 OnesOrZeroesF);
49881 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
49882 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
49883 Vector32, DAG.getIntPtrConstant(0, DL));
49884 IntVT = MVT::i32;
49887 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
49888 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
49889 DAG.getConstant(1, DL, IntVT));
49890 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
49891 ANDed);
49892 return OneBitOfTruth;
49897 return SDValue();
49900 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
49901 static SDValue combineAndNotIntoANDNP(SDNode *N, SelectionDAG &DAG) {
49902 assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
49904 MVT VT = N->getSimpleValueType(0);
49905 if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
49906 return SDValue();
49908 SDValue X, Y;
49909 SDValue N0 = N->getOperand(0);
49910 SDValue N1 = N->getOperand(1);
49912 if (SDValue Not = IsNOT(N0, DAG)) {
49913 X = Not;
49914 Y = N1;
49915 } else if (SDValue Not = IsNOT(N1, DAG)) {
49916 X = Not;
49917 Y = N0;
49918 } else
49919 return SDValue();
49921 X = DAG.getBitcast(VT, X);
49922 Y = DAG.getBitcast(VT, Y);
49923 return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
49926 /// Try to fold:
49927 /// and (vector_shuffle<Z,...,Z>
49928 /// (insert_vector_elt undef, (xor X, -1), Z), undef), Y
49929 /// ->
49930 /// andnp (vector_shuffle<Z,...,Z>
49931 /// (insert_vector_elt undef, X, Z), undef), Y
49932 static SDValue combineAndShuffleNot(SDNode *N, SelectionDAG &DAG,
49933 const X86Subtarget &Subtarget) {
49934 assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
49936 EVT VT = N->getValueType(0);
49937 // Do not split 256 and 512 bit vectors with SSE2 as they overwrite original
49938 // value and require extra moves.
49939 if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
49940 ((VT.is256BitVector() || VT.is512BitVector()) && Subtarget.hasAVX())))
49941 return SDValue();
49943 auto GetNot = [&DAG](SDValue V) {
49944 auto *SVN = dyn_cast<ShuffleVectorSDNode>(peekThroughOneUseBitcasts(V));
49945 // TODO: SVN->hasOneUse() is a strong condition. It can be relaxed if all
49946 // end-users are ISD::AND including cases
49947 // (and(extract_vector_element(SVN), Y)).
49948 if (!SVN || !SVN->hasOneUse() || !SVN->isSplat() ||
49949 !SVN->getOperand(1).isUndef()) {
49950 return SDValue();
49952 SDValue IVEN = SVN->getOperand(0);
49953 if (IVEN.getOpcode() != ISD::INSERT_VECTOR_ELT ||
49954 !IVEN.getOperand(0).isUndef() || !IVEN.hasOneUse())
49955 return SDValue();
49956 if (!isa<ConstantSDNode>(IVEN.getOperand(2)) ||
49957 IVEN.getConstantOperandAPInt(2) != SVN->getSplatIndex())
49958 return SDValue();
49959 SDValue Src = IVEN.getOperand(1);
49960 if (SDValue Not = IsNOT(Src, DAG)) {
49961 SDValue NotSrc = DAG.getBitcast(Src.getValueType(), Not);
49962 SDValue NotIVEN =
49963 DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(IVEN), IVEN.getValueType(),
49964 IVEN.getOperand(0), NotSrc, IVEN.getOperand(2));
49965 return DAG.getVectorShuffle(SVN->getValueType(0), SDLoc(SVN), NotIVEN,
49966 SVN->getOperand(1), SVN->getMask());
49968 return SDValue();
49971 SDValue X, Y;
49972 SDValue N0 = N->getOperand(0);
49973 SDValue N1 = N->getOperand(1);
49974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49976 if (SDValue Not = GetNot(N0)) {
49977 X = Not;
49978 Y = N1;
49979 } else if (SDValue Not = GetNot(N1)) {
49980 X = Not;
49981 Y = N0;
49982 } else
49983 return SDValue();
49985 X = DAG.getBitcast(VT, X);
49986 Y = DAG.getBitcast(VT, Y);
49987 SDLoc DL(N);
49989 // We do not split for SSE at all, but we need to split vectors for AVX1 and
49990 // AVX2.
49991 if (!Subtarget.useAVX512Regs() && VT.is512BitVector() &&
49992 TLI.isTypeLegal(VT.getHalfNumVectorElementsVT(*DAG.getContext()))) {
49993 SDValue LoX, HiX;
49994 std::tie(LoX, HiX) = splitVector(X, DAG, DL);
49995 SDValue LoY, HiY;
49996 std::tie(LoY, HiY) = splitVector(Y, DAG, DL);
49997 EVT SplitVT = LoX.getValueType();
49998 SDValue LoV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {LoX, LoY});
49999 SDValue HiV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {HiX, HiY});
50000 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, {LoV, HiV});
50003 if (TLI.isTypeLegal(VT))
50004 return DAG.getNode(X86ISD::ANDNP, DL, VT, {X, Y});
50006 return SDValue();
50009 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
50010 // logical operations, like in the example below.
50011 // or (and (truncate x, truncate y)),
50012 // (xor (truncate z, build_vector (constants)))
50013 // Given a target type \p VT, we generate
50014 // or (and x, y), (xor z, zext(build_vector (constants)))
50015 // given x, y and z are of type \p VT. We can do so, if operands are either
50016 // truncates from VT types, the second operand is a vector of constants or can
50017 // be recursively promoted.
50018 static SDValue PromoteMaskArithmetic(SDValue N, const SDLoc &DL, EVT VT,
50019 SelectionDAG &DAG, unsigned Depth) {
50020 // Limit recursion to avoid excessive compile times.
50021 if (Depth >= SelectionDAG::MaxRecursionDepth)
50022 return SDValue();
50024 if (!ISD::isBitwiseLogicOp(N.getOpcode()))
50025 return SDValue();
50027 SDValue N0 = N.getOperand(0);
50028 SDValue N1 = N.getOperand(1);
50030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50031 if (!TLI.isOperationLegalOrPromote(N.getOpcode(), VT))
50032 return SDValue();
50034 if (SDValue NN0 = PromoteMaskArithmetic(N0, DL, VT, DAG, Depth + 1))
50035 N0 = NN0;
50036 else {
50037 // The left side has to be a trunc.
50038 if (N0.getOpcode() != ISD::TRUNCATE)
50039 return SDValue();
50041 // The type of the truncated inputs.
50042 if (N0.getOperand(0).getValueType() != VT)
50043 return SDValue();
50045 N0 = N0.getOperand(0);
50048 if (SDValue NN1 = PromoteMaskArithmetic(N1, DL, VT, DAG, Depth + 1))
50049 N1 = NN1;
50050 else {
50051 // The right side has to be a 'trunc' or a (foldable) constant.
50052 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
50053 N1.getOperand(0).getValueType() == VT;
50054 if (RHSTrunc)
50055 N1 = N1.getOperand(0);
50056 else if (SDValue Cst =
50057 DAG.FoldConstantArithmetic(ISD::ZERO_EXTEND, DL, VT, {N1}))
50058 N1 = Cst;
50059 else
50060 return SDValue();
50063 return DAG.getNode(N.getOpcode(), DL, VT, N0, N1);
50066 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
50067 // register. In most cases we actually compare or select YMM-sized registers
50068 // and mixing the two types creates horrible code. This method optimizes
50069 // some of the transition sequences.
50070 // Even with AVX-512 this is still useful for removing casts around logical
50071 // operations on vXi1 mask types.
50072 static SDValue PromoteMaskArithmetic(SDValue N, const SDLoc &DL,
50073 SelectionDAG &DAG,
50074 const X86Subtarget &Subtarget) {
50075 EVT VT = N.getValueType();
50076 assert(VT.isVector() && "Expected vector type");
50077 assert((N.getOpcode() == ISD::ANY_EXTEND ||
50078 N.getOpcode() == ISD::ZERO_EXTEND ||
50079 N.getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
50081 SDValue Narrow = N.getOperand(0);
50082 EVT NarrowVT = Narrow.getValueType();
50084 // Generate the wide operation.
50085 SDValue Op = PromoteMaskArithmetic(Narrow, DL, VT, DAG, 0);
50086 if (!Op)
50087 return SDValue();
50088 switch (N.getOpcode()) {
50089 default: llvm_unreachable("Unexpected opcode");
50090 case ISD::ANY_EXTEND:
50091 return Op;
50092 case ISD::ZERO_EXTEND:
50093 return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
50094 case ISD::SIGN_EXTEND:
50095 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
50096 Op, DAG.getValueType(NarrowVT));
50100 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
50101 unsigned FPOpcode;
50102 switch (Opcode) {
50103 // clang-format off
50104 default: llvm_unreachable("Unexpected input node for FP logic conversion");
50105 case ISD::AND: FPOpcode = X86ISD::FAND; break;
50106 case ISD::OR: FPOpcode = X86ISD::FOR; break;
50107 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
50108 // clang-format on
50110 return FPOpcode;
50113 /// If both input operands of a logic op are being cast from floating-point
50114 /// types or FP compares, try to convert this into a floating-point logic node
50115 /// to avoid unnecessary moves from SSE to integer registers.
50116 static SDValue convertIntLogicToFPLogic(unsigned Opc, const SDLoc &DL, EVT VT,
50117 SDValue N0, SDValue N1,
50118 SelectionDAG &DAG,
50119 TargetLowering::DAGCombinerInfo &DCI,
50120 const X86Subtarget &Subtarget) {
50121 assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50122 "Unexpected bit opcode");
50124 if (!((N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) ||
50125 (N0.getOpcode() == ISD::SETCC && N1.getOpcode() == ISD::SETCC)))
50126 return SDValue();
50128 SDValue N00 = N0.getOperand(0);
50129 SDValue N10 = N1.getOperand(0);
50130 EVT N00Type = N00.getValueType();
50131 EVT N10Type = N10.getValueType();
50133 // Ensure that both types are the same and are legal scalar fp types.
50134 if (N00Type != N10Type || !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
50135 (Subtarget.hasSSE2() && N00Type == MVT::f64) ||
50136 (Subtarget.hasFP16() && N00Type == MVT::f16)))
50137 return SDValue();
50139 if (N0.getOpcode() == ISD::BITCAST && !DCI.isBeforeLegalizeOps()) {
50140 unsigned FPOpcode = convertIntLogicToFPLogicOpcode(Opc);
50141 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
50142 return DAG.getBitcast(VT, FPLogic);
50145 if (VT != MVT::i1 || N0.getOpcode() != ISD::SETCC || !N0.hasOneUse() ||
50146 !N1.hasOneUse())
50147 return SDValue();
50149 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0.getOperand(2))->get();
50150 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
50152 // The vector ISA for FP predicates is incomplete before AVX, so converting
50153 // COMIS* to CMPS* may not be a win before AVX.
50154 if (!Subtarget.hasAVX() &&
50155 !(cheapX86FSETCC_SSE(CC0) && cheapX86FSETCC_SSE(CC1)))
50156 return SDValue();
50158 // Convert scalar FP compares and logic to vector compares (COMIS* to CMPS*)
50159 // and vector logic:
50160 // logic (setcc N00, N01), (setcc N10, N11) -->
50161 // extelt (logic (setcc (s2v N00), (s2v N01)), setcc (s2v N10), (s2v N11))), 0
50162 unsigned NumElts = 128 / N00Type.getSizeInBits();
50163 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), N00Type, NumElts);
50164 EVT BoolVecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
50165 SDValue ZeroIndex = DAG.getVectorIdxConstant(0, DL);
50166 SDValue N01 = N0.getOperand(1);
50167 SDValue N11 = N1.getOperand(1);
50168 SDValue Vec00 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N00);
50169 SDValue Vec01 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N01);
50170 SDValue Vec10 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N10);
50171 SDValue Vec11 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N11);
50172 SDValue Setcc0 = DAG.getSetCC(DL, BoolVecVT, Vec00, Vec01, CC0);
50173 SDValue Setcc1 = DAG.getSetCC(DL, BoolVecVT, Vec10, Vec11, CC1);
50174 SDValue Logic = DAG.getNode(Opc, DL, BoolVecVT, Setcc0, Setcc1);
50175 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Logic, ZeroIndex);
50178 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
50179 // to reduce XMM->GPR traffic.
50180 static SDValue combineBitOpWithMOVMSK(unsigned Opc, const SDLoc &DL, SDValue N0,
50181 SDValue N1, SelectionDAG &DAG) {
50182 assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50183 "Unexpected bit opcode");
50185 // Both operands must be single use MOVMSK.
50186 if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
50187 N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
50188 return SDValue();
50190 SDValue Vec0 = N0.getOperand(0);
50191 SDValue Vec1 = N1.getOperand(0);
50192 EVT VecVT0 = Vec0.getValueType();
50193 EVT VecVT1 = Vec1.getValueType();
50195 // Both MOVMSK operands must be from vectors of the same size and same element
50196 // size, but its OK for a fp/int diff.
50197 if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
50198 VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
50199 return SDValue();
50201 unsigned VecOpc =
50202 VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
50203 SDValue Result =
50204 DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
50205 return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
50208 // Attempt to fold BITOP(SHIFT(X,Z),SHIFT(Y,Z)) -> SHIFT(BITOP(X,Y),Z).
50209 // NOTE: This is a very limited case of what SimplifyUsingDistributiveLaws
50210 // handles in InstCombine.
50211 static SDValue combineBitOpWithShift(unsigned Opc, const SDLoc &DL, EVT VT,
50212 SDValue N0, SDValue N1,
50213 SelectionDAG &DAG) {
50214 assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50215 "Unexpected bit opcode");
50217 // Both operands must be single use.
50218 if (!N0.hasOneUse() || !N1.hasOneUse())
50219 return SDValue();
50221 // Search for matching shifts.
50222 SDValue BC0 = peekThroughOneUseBitcasts(N0);
50223 SDValue BC1 = peekThroughOneUseBitcasts(N1);
50225 unsigned BCOpc = BC0.getOpcode();
50226 EVT BCVT = BC0.getValueType();
50227 if (BCOpc != BC1->getOpcode() || BCVT != BC1.getValueType())
50228 return SDValue();
50230 switch (BCOpc) {
50231 case X86ISD::VSHLI:
50232 case X86ISD::VSRLI:
50233 case X86ISD::VSRAI: {
50234 if (BC0.getOperand(1) != BC1.getOperand(1))
50235 return SDValue();
50236 SDValue BitOp =
50237 DAG.getNode(Opc, DL, BCVT, BC0.getOperand(0), BC1.getOperand(0));
50238 SDValue Shift = DAG.getNode(BCOpc, DL, BCVT, BitOp, BC0.getOperand(1));
50239 return DAG.getBitcast(VT, Shift);
50243 return SDValue();
50246 // Attempt to fold:
50247 // BITOP(PACKSS(X,Z),PACKSS(Y,W)) --> PACKSS(BITOP(X,Y),BITOP(Z,W)).
50248 // TODO: Handle PACKUS handling.
50249 static SDValue combineBitOpWithPACK(unsigned Opc, const SDLoc &DL, EVT VT,
50250 SDValue N0, SDValue N1, SelectionDAG &DAG) {
50251 assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
50252 "Unexpected bit opcode");
50254 // Both operands must be single use.
50255 if (!N0.hasOneUse() || !N1.hasOneUse())
50256 return SDValue();
50258 // Search for matching packs.
50259 N0 = peekThroughOneUseBitcasts(N0);
50260 N1 = peekThroughOneUseBitcasts(N1);
50262 if (N0.getOpcode() != X86ISD::PACKSS || N1.getOpcode() != X86ISD::PACKSS)
50263 return SDValue();
50265 MVT DstVT = N0.getSimpleValueType();
50266 if (DstVT != N1.getSimpleValueType())
50267 return SDValue();
50269 MVT SrcVT = N0.getOperand(0).getSimpleValueType();
50270 unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
50272 // Limit to allsignbits packing.
50273 if (DAG.ComputeNumSignBits(N0.getOperand(0)) != NumSrcBits ||
50274 DAG.ComputeNumSignBits(N0.getOperand(1)) != NumSrcBits ||
50275 DAG.ComputeNumSignBits(N1.getOperand(0)) != NumSrcBits ||
50276 DAG.ComputeNumSignBits(N1.getOperand(1)) != NumSrcBits)
50277 return SDValue();
50279 SDValue LHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(0), N1.getOperand(0));
50280 SDValue RHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(1), N1.getOperand(1));
50281 return DAG.getBitcast(VT, DAG.getNode(X86ISD::PACKSS, DL, DstVT, LHS, RHS));
50284 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
50285 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
50286 /// with a shift-right to eliminate loading the vector constant mask value.
50287 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
50288 const X86Subtarget &Subtarget) {
50289 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
50290 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
50291 EVT VT = Op0.getValueType();
50292 if (VT != Op1.getValueType() || !VT.isSimple() || !VT.isInteger())
50293 return SDValue();
50295 // Try to convert an "is positive" signbit masking operation into arithmetic
50296 // shift and "andn". This saves a materialization of a -1 vector constant.
50297 // The "is negative" variant should be handled more generally because it only
50298 // requires "and" rather than "andn":
50299 // and (pcmpgt X, -1), Y --> pandn (vsrai X, BitWidth - 1), Y
50301 // This is limited to the original type to avoid producing even more bitcasts.
50302 // If the bitcasts can't be eliminated, then it is unlikely that this fold
50303 // will be profitable.
50304 if (N->getValueType(0) == VT &&
50305 supportedVectorShiftWithImm(VT, Subtarget, ISD::SRA)) {
50306 SDValue X, Y;
50307 if (Op1.getOpcode() == X86ISD::PCMPGT &&
50308 isAllOnesOrAllOnesSplat(Op1.getOperand(1)) && Op1.hasOneUse()) {
50309 X = Op1.getOperand(0);
50310 Y = Op0;
50311 } else if (Op0.getOpcode() == X86ISD::PCMPGT &&
50312 isAllOnesOrAllOnesSplat(Op0.getOperand(1)) && Op0.hasOneUse()) {
50313 X = Op0.getOperand(0);
50314 Y = Op1;
50316 if (X && Y) {
50317 SDLoc DL(N);
50318 SDValue Sra =
50319 getTargetVShiftByConstNode(X86ISD::VSRAI, DL, VT.getSimpleVT(), X,
50320 VT.getScalarSizeInBits() - 1, DAG);
50321 return DAG.getNode(X86ISD::ANDNP, DL, VT, Sra, Y);
50325 APInt SplatVal;
50326 if (!X86::isConstantSplat(Op1, SplatVal, false) || !SplatVal.isMask())
50327 return SDValue();
50329 // Don't prevent creation of ANDN.
50330 if (isBitwiseNot(Op0))
50331 return SDValue();
50333 if (!supportedVectorShiftWithImm(VT, Subtarget, ISD::SRL))
50334 return SDValue();
50336 unsigned EltBitWidth = VT.getScalarSizeInBits();
50337 if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
50338 return SDValue();
50340 SDLoc DL(N);
50341 unsigned ShiftVal = SplatVal.countr_one();
50342 SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
50343 SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT, Op0, ShAmt);
50344 return DAG.getBitcast(N->getValueType(0), Shift);
50347 // Get the index node from the lowered DAG of a GEP IR instruction with one
50348 // indexing dimension.
50349 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
50350 if (Ld->isIndexed())
50351 return SDValue();
50353 SDValue Base = Ld->getBasePtr();
50354 if (Base.getOpcode() != ISD::ADD)
50355 return SDValue();
50357 SDValue ShiftedIndex = Base.getOperand(0);
50358 if (ShiftedIndex.getOpcode() != ISD::SHL)
50359 return SDValue();
50361 return ShiftedIndex.getOperand(0);
50364 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
50365 return Subtarget.hasBMI2() &&
50366 (VT == MVT::i32 || (VT == MVT::i64 && Subtarget.is64Bit()));
50369 /// Folds (and X, (or Y, ~Z)) --> (and X, ~(and ~Y, Z))
50370 /// This undoes the inverse fold performed in InstCombine
50371 static SDValue combineAndNotOrIntoAndNotAnd(SDNode *N, SelectionDAG &DAG) {
50373 using namespace llvm::SDPatternMatch;
50374 MVT VT = N->getSimpleValueType(0);
50375 SDLoc DL(N);
50376 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50377 if (!TLI.hasAndNot(SDValue(N, 0)))
50378 return SDValue();
50380 SDValue X, Y, Z;
50381 if (sd_match(N, m_And(m_Value(X),
50382 m_OneUse(m_Or(m_Value(Y), m_Not(m_Value(Z))))))) {
50383 // Don't fold if Y or Z are constants to prevent infinite loops.
50384 if (!DAG.isConstantIntBuildVectorOrConstantInt(Y) &&
50385 !DAG.isConstantIntBuildVectorOrConstantInt(Z))
50386 return DAG.getNode(
50387 ISD::AND, DL, VT, X,
50388 DAG.getNOT(
50389 DL, DAG.getNode(ISD::AND, DL, VT, DAG.getNOT(DL, Y, VT), Z), VT));
50392 return SDValue();
50395 // This function recognizes cases where X86 bzhi instruction can replace and
50396 // 'and-load' sequence.
50397 // In case of loading integer value from an array of constants which is defined
50398 // as follows:
50400 // int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
50402 // then applying a bitwise and on the result with another input.
50403 // It's equivalent to performing bzhi (zero high bits) on the input, with the
50404 // same index of the load.
50405 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
50406 const X86Subtarget &Subtarget) {
50407 MVT VT = Node->getSimpleValueType(0);
50408 SDLoc dl(Node);
50410 // Check if subtarget has BZHI instruction for the node's type
50411 if (!hasBZHI(Subtarget, VT))
50412 return SDValue();
50414 // Try matching the pattern for both operands.
50415 for (unsigned i = 0; i < 2; i++) {
50416 // continue if the operand is not a load instruction
50417 auto *Ld = dyn_cast<LoadSDNode>(Node->getOperand(i));
50418 if (!Ld)
50419 continue;
50420 const Value *MemOp = Ld->getMemOperand()->getValue();
50421 if (!MemOp)
50422 continue;
50423 // Get the Node which indexes into the array.
50424 SDValue Index = getIndexFromUnindexedLoad(Ld);
50425 if (!Index)
50426 continue;
50428 if (auto *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
50429 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
50430 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
50431 Constant *Init = GV->getInitializer();
50432 Type *Ty = Init->getType();
50433 if (!isa<ConstantDataArray>(Init) ||
50434 !Ty->getArrayElementType()->isIntegerTy() ||
50435 Ty->getArrayElementType()->getScalarSizeInBits() !=
50436 VT.getSizeInBits() ||
50437 Ty->getArrayNumElements() >
50438 Ty->getArrayElementType()->getScalarSizeInBits())
50439 continue;
50441 // Check if the array's constant elements are suitable to our case.
50442 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
50443 bool ConstantsMatch = true;
50444 for (uint64_t j = 0; j < ArrayElementCount; j++) {
50445 auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
50446 if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
50447 ConstantsMatch = false;
50448 break;
50451 if (!ConstantsMatch)
50452 continue;
50454 // Do the transformation (For 32-bit type):
50455 // -> (and (load arr[idx]), inp)
50456 // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
50457 // that will be replaced with one bzhi instruction.
50458 SDValue Inp = Node->getOperand(i == 0 ? 1 : 0);
50459 SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
50461 Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
50462 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
50463 Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
50465 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
50466 SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
50467 return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
50472 return SDValue();
50475 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
50476 // Where C is a mask containing the same number of bits as the setcc and
50477 // where the setcc will freely 0 upper bits of k-register. We can replace the
50478 // undef in the concat with 0s and remove the AND. This mainly helps with
50479 // v2i1/v4i1 setcc being casted to scalar.
50480 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
50481 const X86Subtarget &Subtarget) {
50482 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
50484 EVT VT = N->getValueType(0);
50486 // Make sure this is an AND with constant. We will check the value of the
50487 // constant later.
50488 auto *C1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
50489 if (!C1)
50490 return SDValue();
50492 // This is implied by the ConstantSDNode.
50493 assert(!VT.isVector() && "Expected scalar VT!");
50495 SDValue Src = N->getOperand(0);
50496 if (!Src.hasOneUse())
50497 return SDValue();
50499 // (Optionally) peek through any_extend().
50500 if (Src.getOpcode() == ISD::ANY_EXTEND) {
50501 if (!Src.getOperand(0).hasOneUse())
50502 return SDValue();
50503 Src = Src.getOperand(0);
50506 if (Src.getOpcode() != ISD::BITCAST || !Src.getOperand(0).hasOneUse())
50507 return SDValue();
50509 Src = Src.getOperand(0);
50510 EVT SrcVT = Src.getValueType();
50512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50513 if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
50514 !TLI.isTypeLegal(SrcVT))
50515 return SDValue();
50517 if (Src.getOpcode() != ISD::CONCAT_VECTORS)
50518 return SDValue();
50520 // We only care about the first subvector of the concat, we expect the
50521 // other subvectors to be ignored due to the AND if we make the change.
50522 SDValue SubVec = Src.getOperand(0);
50523 EVT SubVecVT = SubVec.getValueType();
50525 // The RHS of the AND should be a mask with as many bits as SubVec.
50526 if (!TLI.isTypeLegal(SubVecVT) ||
50527 !C1->getAPIntValue().isMask(SubVecVT.getVectorNumElements()))
50528 return SDValue();
50530 // First subvector should be a setcc with a legal result type or a
50531 // AND containing at least one setcc with a legal result type.
50532 auto IsLegalSetCC = [&](SDValue V) {
50533 if (V.getOpcode() != ISD::SETCC)
50534 return false;
50535 EVT SetccVT = V.getOperand(0).getValueType();
50536 if (!TLI.isTypeLegal(SetccVT) ||
50537 !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
50538 return false;
50539 if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
50540 return false;
50541 return true;
50543 if (!(IsLegalSetCC(SubVec) || (SubVec.getOpcode() == ISD::AND &&
50544 (IsLegalSetCC(SubVec.getOperand(0)) ||
50545 IsLegalSetCC(SubVec.getOperand(1))))))
50546 return SDValue();
50548 // We passed all the checks. Rebuild the concat_vectors with zeroes
50549 // and cast it back to VT.
50550 SDLoc dl(N);
50551 SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
50552 DAG.getConstant(0, dl, SubVecVT));
50553 Ops[0] = SubVec;
50554 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
50555 Ops);
50556 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcVT.getSizeInBits());
50557 return DAG.getZExtOrTrunc(DAG.getBitcast(IntVT, Concat), dl, VT);
50560 static SDValue getBMIMatchingOp(unsigned Opc, SelectionDAG &DAG,
50561 SDValue OpMustEq, SDValue Op, unsigned Depth) {
50562 // We don't want to go crazy with the recursion here. This isn't a super
50563 // important optimization.
50564 static constexpr unsigned kMaxDepth = 2;
50566 // Only do this re-ordering if op has one use.
50567 if (!Op.hasOneUse())
50568 return SDValue();
50570 SDLoc DL(Op);
50571 // If we hit another assosiative op, recurse further.
50572 if (Op.getOpcode() == Opc) {
50573 // Done recursing.
50574 if (Depth++ >= kMaxDepth)
50575 return SDValue();
50577 for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
50578 if (SDValue R =
50579 getBMIMatchingOp(Opc, DAG, OpMustEq, Op.getOperand(OpIdx), Depth))
50580 return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), R,
50581 Op.getOperand(1 - OpIdx));
50583 } else if (Op.getOpcode() == ISD::SUB) {
50584 if (Opc == ISD::AND) {
50585 // BLSI: (and x, (sub 0, x))
50586 if (isNullConstant(Op.getOperand(0)) && Op.getOperand(1) == OpMustEq)
50587 return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
50589 // Opc must be ISD::AND or ISD::XOR
50590 // BLSR: (and x, (sub x, 1))
50591 // BLSMSK: (xor x, (sub x, 1))
50592 if (isOneConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
50593 return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
50595 } else if (Op.getOpcode() == ISD::ADD) {
50596 // Opc must be ISD::AND or ISD::XOR
50597 // BLSR: (and x, (add x, -1))
50598 // BLSMSK: (xor x, (add x, -1))
50599 if (isAllOnesConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
50600 return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
50602 return SDValue();
50605 static SDValue combineBMILogicOp(SDNode *N, SelectionDAG &DAG,
50606 const X86Subtarget &Subtarget) {
50607 EVT VT = N->getValueType(0);
50608 // Make sure this node is a candidate for BMI instructions.
50609 if (!Subtarget.hasBMI() || !VT.isScalarInteger() ||
50610 (VT != MVT::i32 && VT != MVT::i64))
50611 return SDValue();
50613 assert(N->getOpcode() == ISD::AND || N->getOpcode() == ISD::XOR);
50615 // Try and match LHS and RHS.
50616 for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
50617 if (SDValue OpMatch =
50618 getBMIMatchingOp(N->getOpcode(), DAG, N->getOperand(OpIdx),
50619 N->getOperand(1 - OpIdx), 0))
50620 return OpMatch;
50621 return SDValue();
50624 static SDValue combineX86SubCmpForFlags(SDNode *N, SDValue Flag,
50625 SelectionDAG &DAG,
50626 TargetLowering::DAGCombinerInfo &DCI,
50627 const X86Subtarget &ST) {
50628 // cmp(setcc(cc, X), 0)
50629 // brcond ne
50630 // ->
50631 // X
50632 // brcond cc
50634 // sub(setcc(cc, X), 1)
50635 // brcond ne
50636 // ->
50637 // X
50638 // brcond ~cc
50640 // if only flag has users
50642 SDValue SetCC = N->getOperand(0);
50644 if (SetCC.getOpcode() != X86ISD::SETCC || !Flag.hasOneUse())
50645 return SDValue();
50647 // Check the only user of flag is `brcond ne`.
50648 SDNode *BrCond = *Flag->uses().begin();
50649 if (BrCond->getOpcode() != X86ISD::BRCOND)
50650 return SDValue();
50651 unsigned CondNo = 2;
50652 if (static_cast<X86::CondCode>(BrCond->getConstantOperandVal(CondNo)) !=
50653 X86::COND_NE)
50654 return SDValue();
50656 SDValue X = SetCC.getOperand(1);
50657 // sub has two results while X only have one. DAG combine assumes the value
50658 // type matches.
50659 if (N->getOpcode() == X86ISD::SUB)
50660 X = DAG.getMergeValues({N->getOperand(0), X}, SDLoc(N));
50662 SDValue CCN = SetCC.getOperand(0);
50663 X86::CondCode CC =
50664 static_cast<X86::CondCode>(CCN->getAsAPIntVal().getSExtValue());
50665 X86::CondCode OppositeCC = X86::GetOppositeBranchCondition(CC);
50666 // Update CC for the consumer of the flag.
50667 // The old CC is `ne`. Hence, when comparing the result with 0, we are
50668 // checking if the second condition evaluates to true. When comparing the
50669 // result with 1, we are checking uf the second condition evaluates to false.
50670 SmallVector<SDValue> Ops(BrCond->op_values());
50671 if (isNullConstant(N->getOperand(1)))
50672 Ops[CondNo] = CCN;
50673 else if (isOneConstant(N->getOperand(1)))
50674 Ops[CondNo] = DAG.getTargetConstant(OppositeCC, SDLoc(BrCond), MVT::i8);
50675 else
50676 llvm_unreachable("expect constant 0 or 1");
50678 SDValue NewBrCond =
50679 DAG.getNode(X86ISD::BRCOND, SDLoc(BrCond), BrCond->getValueType(0), Ops);
50680 // Avoid self-assign error b/c CC1 can be `e/ne`.
50681 if (BrCond != NewBrCond.getNode())
50682 DCI.CombineTo(BrCond, NewBrCond);
50683 return X;
50686 static SDValue combineAndOrForCcmpCtest(SDNode *N, SelectionDAG &DAG,
50687 TargetLowering::DAGCombinerInfo &DCI,
50688 const X86Subtarget &ST) {
50689 // and/or(setcc(cc0, flag0), setcc(cc1, sub (X, Y)))
50690 // ->
50691 // setcc(cc1, ccmp(X, Y, ~cflags/cflags, cc0/~cc0, flag0))
50693 // and/or(setcc(cc0, flag0), setcc(cc1, cmp (X, 0)))
50694 // ->
50695 // setcc(cc1, ctest(X, X, ~cflags/cflags, cc0/~cc0, flag0))
50697 // where cflags is determined by cc1.
50699 if (!ST.hasCCMP())
50700 return SDValue();
50702 SDValue SetCC0 = N->getOperand(0);
50703 SDValue SetCC1 = N->getOperand(1);
50704 if (SetCC0.getOpcode() != X86ISD::SETCC ||
50705 SetCC1.getOpcode() != X86ISD::SETCC)
50706 return SDValue();
50708 auto GetCombineToOpc = [&](SDValue V) -> unsigned {
50709 SDValue Op = V.getOperand(1);
50710 unsigned Opc = Op.getOpcode();
50711 if (Opc == X86ISD::SUB)
50712 return X86ISD::CCMP;
50713 if (Opc == X86ISD::CMP && isNullConstant(Op.getOperand(1)))
50714 return X86ISD::CTEST;
50715 return 0U;
50718 unsigned NewOpc = 0;
50720 // AND/OR is commutable. Canonicalize the operands to make SETCC with SUB/CMP
50721 // appear on the right.
50722 if (!(NewOpc = GetCombineToOpc(SetCC1))) {
50723 std::swap(SetCC0, SetCC1);
50724 if (!(NewOpc = GetCombineToOpc(SetCC1)))
50725 return SDValue();
50728 X86::CondCode CC0 =
50729 static_cast<X86::CondCode>(SetCC0.getConstantOperandVal(0));
50730 // CCMP/CTEST is not conditional when the source condition is COND_P/COND_NP.
50731 if (CC0 == X86::COND_P || CC0 == X86::COND_NP)
50732 return SDValue();
50734 bool IsOR = N->getOpcode() == ISD::OR;
50736 // CMP/TEST is executed and updates the EFLAGS normally only when SrcCC
50737 // evaluates to true. So we need to inverse CC0 as SrcCC when the logic
50738 // operator is OR. Similar for CC1.
50739 SDValue SrcCC =
50740 IsOR ? DAG.getTargetConstant(X86::GetOppositeBranchCondition(CC0),
50741 SDLoc(SetCC0.getOperand(0)), MVT::i8)
50742 : SetCC0.getOperand(0);
50743 SDValue CC1N = SetCC1.getOperand(0);
50744 X86::CondCode CC1 =
50745 static_cast<X86::CondCode>(CC1N->getAsAPIntVal().getSExtValue());
50746 X86::CondCode OppositeCC1 = X86::GetOppositeBranchCondition(CC1);
50747 X86::CondCode CFlagsCC = IsOR ? CC1 : OppositeCC1;
50748 SDLoc DL(N);
50749 SDValue CFlags = DAG.getTargetConstant(
50750 X86::getCCMPCondFlagsFromCondCode(CFlagsCC), DL, MVT::i8);
50751 SDValue Sub = SetCC1.getOperand(1);
50753 // Replace any uses of the old flag produced by SUB/CMP with the new one
50754 // produced by CCMP/CTEST.
50755 SDValue CCMP = (NewOpc == X86ISD::CCMP)
50756 ? DAG.getNode(X86ISD::CCMP, DL, MVT::i32,
50757 {Sub.getOperand(0), Sub.getOperand(1),
50758 CFlags, SrcCC, SetCC0.getOperand(1)})
50759 : DAG.getNode(X86ISD::CTEST, DL, MVT::i32,
50760 {Sub.getOperand(0), Sub.getOperand(0),
50761 CFlags, SrcCC, SetCC0.getOperand(1)});
50763 return DAG.getNode(X86ISD::SETCC, DL, MVT::i8, {CC1N, CCMP});
50766 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
50767 TargetLowering::DAGCombinerInfo &DCI,
50768 const X86Subtarget &Subtarget) {
50769 SDValue N0 = N->getOperand(0);
50770 SDValue N1 = N->getOperand(1);
50771 EVT VT = N->getValueType(0);
50772 SDLoc dl(N);
50773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50775 // If this is SSE1 only convert to FAND to avoid scalarization.
50776 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
50777 return DAG.getBitcast(MVT::v4i32,
50778 DAG.getNode(X86ISD::FAND, dl, MVT::v4f32,
50779 DAG.getBitcast(MVT::v4f32, N0),
50780 DAG.getBitcast(MVT::v4f32, N1)));
50783 // Use a 32-bit and+zext if upper bits known zero.
50784 if (VT == MVT::i64 && Subtarget.is64Bit() && !isa<ConstantSDNode>(N1)) {
50785 APInt HiMask = APInt::getHighBitsSet(64, 32);
50786 if (DAG.MaskedValueIsZero(N1, HiMask) ||
50787 DAG.MaskedValueIsZero(N0, HiMask)) {
50788 SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N0);
50789 SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N1);
50790 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
50791 DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
50795 // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
50796 // TODO: Support multiple SrcOps.
50797 if (VT == MVT::i1) {
50798 SmallVector<SDValue, 2> SrcOps;
50799 SmallVector<APInt, 2> SrcPartials;
50800 if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
50801 SrcOps.size() == 1) {
50802 unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
50803 EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
50804 SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
50805 if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
50806 Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
50807 if (Mask) {
50808 assert(SrcPartials[0].getBitWidth() == NumElts &&
50809 "Unexpected partial reduction mask");
50810 SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
50811 Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
50812 return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
50817 // InstCombine converts:
50818 // `(-x << C0) & C1`
50819 // to
50820 // `(x * (Pow2_Ceil(C1) - (1 << C0))) & C1`
50821 // This saves an IR instruction but on x86 the neg/shift version is preferable
50822 // so undo the transform.
50824 if (N0.getOpcode() == ISD::MUL && N0.hasOneUse()) {
50825 // TODO: We don't actually need a splat for this, we just need the checks to
50826 // hold for each element.
50827 ConstantSDNode *N1C = isConstOrConstSplat(N1, /*AllowUndefs*/ true,
50828 /*AllowTruncation*/ false);
50829 ConstantSDNode *N01C =
50830 isConstOrConstSplat(N0.getOperand(1), /*AllowUndefs*/ true,
50831 /*AllowTruncation*/ false);
50832 if (N1C && N01C) {
50833 const APInt &MulC = N01C->getAPIntValue();
50834 const APInt &AndC = N1C->getAPIntValue();
50835 APInt MulCLowBit = MulC & (-MulC);
50836 if (MulC.uge(AndC) && !MulC.isPowerOf2() &&
50837 (MulCLowBit + MulC).isPowerOf2()) {
50838 SDValue Neg = DAG.getNegative(N0.getOperand(0), dl, VT);
50839 int32_t MulCLowBitLog = MulCLowBit.exactLogBase2();
50840 assert(MulCLowBitLog != -1 &&
50841 "Isolated lowbit is somehow not a power of 2!");
50842 SDValue Shift = DAG.getNode(ISD::SHL, dl, VT, Neg,
50843 DAG.getConstant(MulCLowBitLog, dl, VT));
50844 return DAG.getNode(ISD::AND, dl, VT, Shift, N1);
50849 if (SDValue SetCC = combineAndOrForCcmpCtest(N, DAG, DCI, Subtarget))
50850 return SetCC;
50852 if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
50853 return V;
50855 if (SDValue R = combineBitOpWithMOVMSK(N->getOpcode(), dl, N0, N1, DAG))
50856 return R;
50858 if (SDValue R = combineBitOpWithShift(N->getOpcode(), dl, VT, N0, N1, DAG))
50859 return R;
50861 if (SDValue R = combineBitOpWithPACK(N->getOpcode(), dl, VT, N0, N1, DAG))
50862 return R;
50864 if (SDValue FPLogic = convertIntLogicToFPLogic(N->getOpcode(), dl, VT, N0, N1,
50865 DAG, DCI, Subtarget))
50866 return FPLogic;
50868 if (SDValue R = combineAndShuffleNot(N, DAG, Subtarget))
50869 return R;
50871 if (DCI.isBeforeLegalizeOps())
50872 return SDValue();
50874 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
50875 return R;
50877 if (SDValue R = combineAndNotIntoANDNP(N, DAG))
50878 return R;
50880 if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
50881 return ShiftRight;
50883 if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
50884 return R;
50886 if (SDValue R = combineAndNotOrIntoAndNotAnd(N, DAG))
50887 return R;
50889 // fold (and (mul x, c1), c2) -> (mul x, (and c1, c2))
50890 // iff c2 is all/no bits mask - i.e. a select-with-zero mask.
50891 // TODO: Handle PMULDQ/PMULUDQ/VPMADDWD/VPMADDUBSW?
50892 if (VT.isVector() && getTargetConstantFromNode(N1)) {
50893 unsigned Opc0 = N0.getOpcode();
50894 if ((Opc0 == ISD::MUL || Opc0 == ISD::MULHU || Opc0 == ISD::MULHS) &&
50895 getTargetConstantFromNode(N0.getOperand(1)) &&
50896 DAG.ComputeNumSignBits(N1) == VT.getScalarSizeInBits() &&
50897 N0->hasOneUse() && N0.getOperand(1)->hasOneUse()) {
50898 SDValue MaskMul = DAG.getNode(ISD::AND, dl, VT, N0.getOperand(1), N1);
50899 return DAG.getNode(Opc0, dl, VT, N0.getOperand(0), MaskMul);
50903 // Fold AND(SRL(X,Y),1) -> SETCC(BT(X,Y), COND_B) iff Y is not a constant
50904 // avoids slow variable shift (moving shift amount to ECX etc.)
50905 if (isOneConstant(N1) && N0->hasOneUse()) {
50906 SDValue Src = N0;
50907 while ((Src.getOpcode() == ISD::ZERO_EXTEND ||
50908 Src.getOpcode() == ISD::TRUNCATE) &&
50909 Src.getOperand(0)->hasOneUse())
50910 Src = Src.getOperand(0);
50911 bool ContainsNOT = false;
50912 X86::CondCode X86CC = X86::COND_B;
50913 // Peek through AND(NOT(SRL(X,Y)),1).
50914 if (isBitwiseNot(Src)) {
50915 Src = Src.getOperand(0);
50916 X86CC = X86::COND_AE;
50917 ContainsNOT = true;
50919 if (Src.getOpcode() == ISD::SRL &&
50920 !isa<ConstantSDNode>(Src.getOperand(1))) {
50921 SDValue BitNo = Src.getOperand(1);
50922 Src = Src.getOperand(0);
50923 // Peek through AND(SRL(NOT(X),Y),1).
50924 if (isBitwiseNot(Src)) {
50925 Src = Src.getOperand(0);
50926 X86CC = X86CC == X86::COND_AE ? X86::COND_B : X86::COND_AE;
50927 ContainsNOT = true;
50929 // If we have BMI2 then SHRX should be faster for i32/i64 cases.
50930 if (!(Subtarget.hasBMI2() && !ContainsNOT && VT.getSizeInBits() >= 32))
50931 if (SDValue BT = getBT(Src, BitNo, dl, DAG))
50932 return DAG.getZExtOrTrunc(getSETCC(X86CC, BT, dl, DAG), dl, VT);
50936 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
50937 // Attempt to recursively combine a bitmask AND with shuffles.
50938 SDValue Op(N, 0);
50939 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
50940 return Res;
50942 // If either operand is a constant mask, then only the elements that aren't
50943 // zero are actually demanded by the other operand.
50944 auto GetDemandedMasks = [&](SDValue Op) {
50945 APInt UndefElts;
50946 SmallVector<APInt> EltBits;
50947 int NumElts = VT.getVectorNumElements();
50948 int EltSizeInBits = VT.getScalarSizeInBits();
50949 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
50950 APInt DemandedElts = APInt::getAllOnes(NumElts);
50951 if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
50952 EltBits)) {
50953 DemandedBits.clearAllBits();
50954 DemandedElts.clearAllBits();
50955 for (int I = 0; I != NumElts; ++I) {
50956 if (UndefElts[I]) {
50957 // We can't assume an undef src element gives an undef dst - the
50958 // other src might be zero.
50959 DemandedBits.setAllBits();
50960 DemandedElts.setBit(I);
50961 } else if (!EltBits[I].isZero()) {
50962 DemandedBits |= EltBits[I];
50963 DemandedElts.setBit(I);
50967 return std::make_pair(DemandedBits, DemandedElts);
50969 APInt Bits0, Elts0;
50970 APInt Bits1, Elts1;
50971 std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
50972 std::tie(Bits1, Elts1) = GetDemandedMasks(N0);
50974 if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
50975 TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
50976 TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
50977 TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
50978 if (N->getOpcode() != ISD::DELETED_NODE)
50979 DCI.AddToWorklist(N);
50980 return SDValue(N, 0);
50983 SDValue NewN0 = TLI.SimplifyMultipleUseDemandedBits(N0, Bits0, Elts0, DAG);
50984 SDValue NewN1 = TLI.SimplifyMultipleUseDemandedBits(N1, Bits1, Elts1, DAG);
50985 if (NewN0 || NewN1)
50986 return DAG.getNode(ISD::AND, dl, VT, NewN0 ? NewN0 : N0,
50987 NewN1 ? NewN1 : N1);
50990 // Attempt to combine a scalar bitmask AND with an extracted shuffle.
50991 if ((VT.getScalarSizeInBits() % 8) == 0 &&
50992 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
50993 isa<ConstantSDNode>(N0.getOperand(1)) && N0->hasOneUse()) {
50994 SDValue BitMask = N1;
50995 SDValue SrcVec = N0.getOperand(0);
50996 EVT SrcVecVT = SrcVec.getValueType();
50998 // Check that the constant bitmask masks whole bytes.
50999 APInt UndefElts;
51000 SmallVector<APInt, 64> EltBits;
51001 if (VT == SrcVecVT.getScalarType() && N0->isOnlyUserOf(SrcVec.getNode()) &&
51002 getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
51003 llvm::all_of(EltBits, [](const APInt &M) {
51004 return M.isZero() || M.isAllOnes();
51005 })) {
51006 unsigned NumElts = SrcVecVT.getVectorNumElements();
51007 unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
51008 unsigned Idx = N0.getConstantOperandVal(1);
51010 // Create a root shuffle mask from the byte mask and the extracted index.
51011 SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
51012 for (unsigned i = 0; i != Scale; ++i) {
51013 if (UndefElts[i])
51014 continue;
51015 int VecIdx = Scale * Idx + i;
51016 ShuffleMask[VecIdx] = EltBits[i].isZero() ? SM_SentinelZero : VecIdx;
51019 if (SDValue Shuffle = combineX86ShufflesRecursively(
51020 {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
51021 X86::MaxShuffleCombineDepth,
51022 /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
51023 /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
51024 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Shuffle,
51025 N0.getOperand(1));
51029 if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
51030 return R;
51032 return SDValue();
51035 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
51036 static SDValue canonicalizeBitSelect(SDNode *N, const SDLoc &DL,
51037 SelectionDAG &DAG,
51038 const X86Subtarget &Subtarget) {
51039 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
51041 MVT VT = N->getSimpleValueType(0);
51042 unsigned EltSizeInBits = VT.getScalarSizeInBits();
51043 if (!VT.isVector() || (EltSizeInBits % 8) != 0)
51044 return SDValue();
51046 SDValue N0 = peekThroughBitcasts(N->getOperand(0));
51047 SDValue N1 = peekThroughBitcasts(N->getOperand(1));
51048 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
51049 return SDValue();
51051 // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
51052 // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
51053 if (!(Subtarget.hasXOP() || useVPTERNLOG(Subtarget, VT) ||
51054 !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
51055 return SDValue();
51057 // Attempt to extract constant byte masks.
51058 APInt UndefElts0, UndefElts1;
51059 SmallVector<APInt, 32> EltBits0, EltBits1;
51060 if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
51061 /*AllowWholeUndefs*/ false,
51062 /*AllowPartialUndefs*/ false))
51063 return SDValue();
51064 if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
51065 /*AllowWholeUndefs*/ false,
51066 /*AllowPartialUndefs*/ false))
51067 return SDValue();
51069 for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
51070 // TODO - add UNDEF elts support.
51071 if (UndefElts0[i] || UndefElts1[i])
51072 return SDValue();
51073 if (EltBits0[i] != ~EltBits1[i])
51074 return SDValue();
51077 if (useVPTERNLOG(Subtarget, VT)) {
51078 // Emit a VPTERNLOG node directly - 0xCA is the imm code for A?B:C.
51079 // VPTERNLOG is only available as vXi32/64-bit types.
51080 MVT OpSVT = EltSizeInBits <= 32 ? MVT::i32 : MVT::i64;
51081 MVT OpVT =
51082 MVT::getVectorVT(OpSVT, VT.getSizeInBits() / OpSVT.getSizeInBits());
51083 SDValue A = DAG.getBitcast(OpVT, N0.getOperand(1));
51084 SDValue B = DAG.getBitcast(OpVT, N0.getOperand(0));
51085 SDValue C = DAG.getBitcast(OpVT, N1.getOperand(0));
51086 SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
51087 SDValue Res = getAVX512Node(X86ISD::VPTERNLOG, DL, OpVT, {A, B, C, Imm},
51088 DAG, Subtarget);
51089 return DAG.getBitcast(VT, Res);
51092 SDValue X = N->getOperand(0);
51093 SDValue Y =
51094 DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
51095 DAG.getBitcast(VT, N1.getOperand(0)));
51096 return DAG.getNode(ISD::OR, DL, VT, X, Y);
51099 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
51100 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
51101 if (N->getOpcode() != ISD::OR)
51102 return false;
51104 SDValue N0 = N->getOperand(0);
51105 SDValue N1 = N->getOperand(1);
51107 // Canonicalize AND to LHS.
51108 if (N1.getOpcode() == ISD::AND)
51109 std::swap(N0, N1);
51111 // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
51112 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
51113 return false;
51115 Mask = N1.getOperand(0);
51116 X = N1.getOperand(1);
51118 // Check to see if the mask appeared in both the AND and ANDNP.
51119 if (N0.getOperand(0) == Mask)
51120 Y = N0.getOperand(1);
51121 else if (N0.getOperand(1) == Mask)
51122 Y = N0.getOperand(0);
51123 else
51124 return false;
51126 // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
51127 // ANDNP combine allows other combines to happen that prevent matching.
51128 return true;
51131 // Try to fold:
51132 // (or (and (m, y), (pandn m, x)))
51133 // into:
51134 // (vselect m, x, y)
51135 // As a special case, try to fold:
51136 // (or (and (m, (sub 0, x)), (pandn m, x)))
51137 // into:
51138 // (sub (xor X, M), M)
51139 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, const SDLoc &DL,
51140 SelectionDAG &DAG,
51141 const X86Subtarget &Subtarget) {
51142 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
51144 EVT VT = N->getValueType(0);
51145 if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
51146 (VT.is256BitVector() && Subtarget.hasInt256())))
51147 return SDValue();
51149 SDValue X, Y, Mask;
51150 if (!matchLogicBlend(N, X, Y, Mask))
51151 return SDValue();
51153 // Validate that X, Y, and Mask are bitcasts, and see through them.
51154 Mask = peekThroughBitcasts(Mask);
51155 X = peekThroughBitcasts(X);
51156 Y = peekThroughBitcasts(Y);
51158 EVT MaskVT = Mask.getValueType();
51159 unsigned EltBits = MaskVT.getScalarSizeInBits();
51161 // TODO: Attempt to handle floating point cases as well?
51162 if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
51163 return SDValue();
51165 // Attempt to combine to conditional negate: (sub (xor X, M), M)
51166 if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
51167 DAG, Subtarget))
51168 return Res;
51170 // PBLENDVB is only available on SSE 4.1.
51171 if (!Subtarget.hasSSE41())
51172 return SDValue();
51174 // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
51175 if (Subtarget.hasVLX())
51176 return SDValue();
51178 MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
51180 X = DAG.getBitcast(BlendVT, X);
51181 Y = DAG.getBitcast(BlendVT, Y);
51182 Mask = DAG.getBitcast(BlendVT, Mask);
51183 Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
51184 return DAG.getBitcast(VT, Mask);
51187 // Helper function for combineOrCmpEqZeroToCtlzSrl
51188 // Transforms:
51189 // seteq(cmp x, 0)
51190 // into:
51191 // srl(ctlz x), log2(bitsize(x))
51192 // Input pattern is checked by caller.
51193 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) {
51194 SDValue Cmp = Op.getOperand(1);
51195 EVT VT = Cmp.getOperand(0).getValueType();
51196 unsigned Log2b = Log2_32(VT.getSizeInBits());
51197 SDLoc dl(Op);
51198 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
51199 // The result of the shift is true or false, and on X86, the 32-bit
51200 // encoding of shr and lzcnt is more desirable.
51201 SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
51202 SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
51203 DAG.getConstant(Log2b, dl, MVT::i8));
51204 return Scc;
51207 // Try to transform:
51208 // zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
51209 // into:
51210 // srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
51211 // Will also attempt to match more generic cases, eg:
51212 // zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
51213 // Only applies if the target supports the FastLZCNT feature.
51214 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
51215 TargetLowering::DAGCombinerInfo &DCI,
51216 const X86Subtarget &Subtarget) {
51217 if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
51218 return SDValue();
51220 auto isORCandidate = [](SDValue N) {
51221 return (N->getOpcode() == ISD::OR && N->hasOneUse());
51224 // Check the zero extend is extending to 32-bit or more. The code generated by
51225 // srl(ctlz) for 16-bit or less variants of the pattern would require extra
51226 // instructions to clear the upper bits.
51227 if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
51228 !isORCandidate(N->getOperand(0)))
51229 return SDValue();
51231 // Check the node matches: setcc(eq, cmp 0)
51232 auto isSetCCCandidate = [](SDValue N) {
51233 return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
51234 X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
51235 N->getOperand(1).getOpcode() == X86ISD::CMP &&
51236 isNullConstant(N->getOperand(1).getOperand(1)) &&
51237 N->getOperand(1).getValueType().bitsGE(MVT::i32);
51240 SDNode *OR = N->getOperand(0).getNode();
51241 SDValue LHS = OR->getOperand(0);
51242 SDValue RHS = OR->getOperand(1);
51244 // Save nodes matching or(or, setcc(eq, cmp 0)).
51245 SmallVector<SDNode *, 2> ORNodes;
51246 while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
51247 (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
51248 ORNodes.push_back(OR);
51249 OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
51250 LHS = OR->getOperand(0);
51251 RHS = OR->getOperand(1);
51254 // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
51255 if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
51256 !isORCandidate(SDValue(OR, 0)))
51257 return SDValue();
51259 // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
51260 // to
51261 // or(srl(ctlz),srl(ctlz)).
51262 // The dag combiner can then fold it into:
51263 // srl(or(ctlz, ctlz)).
51264 SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, DAG);
51265 SDValue Ret, NewRHS;
51266 if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG)))
51267 Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, NewLHS, NewRHS);
51269 if (!Ret)
51270 return SDValue();
51272 // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
51273 while (!ORNodes.empty()) {
51274 OR = ORNodes.pop_back_val();
51275 LHS = OR->getOperand(0);
51276 RHS = OR->getOperand(1);
51277 // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
51278 if (RHS->getOpcode() == ISD::OR)
51279 std::swap(LHS, RHS);
51280 NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG);
51281 if (!NewRHS)
51282 return SDValue();
51283 Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, Ret, NewRHS);
51286 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
51289 static SDValue foldMaskedMergeImpl(SDValue And0_L, SDValue And0_R,
51290 SDValue And1_L, SDValue And1_R,
51291 const SDLoc &DL, SelectionDAG &DAG) {
51292 if (!isBitwiseNot(And0_L, true) || !And0_L->hasOneUse())
51293 return SDValue();
51294 SDValue NotOp = And0_L->getOperand(0);
51295 if (NotOp == And1_R)
51296 std::swap(And1_R, And1_L);
51297 if (NotOp != And1_L)
51298 return SDValue();
51300 // (~(NotOp) & And0_R) | (NotOp & And1_R)
51301 // --> ((And0_R ^ And1_R) & NotOp) ^ And1_R
51302 EVT VT = And1_L->getValueType(0);
51303 SDValue Freeze_And0_R = DAG.getNode(ISD::FREEZE, SDLoc(), VT, And0_R);
51304 SDValue Xor0 = DAG.getNode(ISD::XOR, DL, VT, And1_R, Freeze_And0_R);
51305 SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor0, NotOp);
51306 SDValue Xor1 = DAG.getNode(ISD::XOR, DL, VT, And, Freeze_And0_R);
51307 return Xor1;
51310 /// Fold "masked merge" expressions like `(m & x) | (~m & y)` into the
51311 /// equivalent `((x ^ y) & m) ^ y)` pattern.
51312 /// This is typically a better representation for targets without a fused
51313 /// "and-not" operation. This function is intended to be called from a
51314 /// `TargetLowering::PerformDAGCombine` callback on `ISD::OR` nodes.
51315 static SDValue foldMaskedMerge(SDNode *Node, SelectionDAG &DAG) {
51316 // Note that masked-merge variants using XOR or ADD expressions are
51317 // normalized to OR by InstCombine so we only check for OR.
51318 assert(Node->getOpcode() == ISD::OR && "Must be called with ISD::OR node");
51319 SDValue N0 = Node->getOperand(0);
51320 if (N0->getOpcode() != ISD::AND || !N0->hasOneUse())
51321 return SDValue();
51322 SDValue N1 = Node->getOperand(1);
51323 if (N1->getOpcode() != ISD::AND || !N1->hasOneUse())
51324 return SDValue();
51326 SDLoc DL(Node);
51327 SDValue N00 = N0->getOperand(0);
51328 SDValue N01 = N0->getOperand(1);
51329 SDValue N10 = N1->getOperand(0);
51330 SDValue N11 = N1->getOperand(1);
51331 if (SDValue Result = foldMaskedMergeImpl(N00, N01, N10, N11, DL, DAG))
51332 return Result;
51333 if (SDValue Result = foldMaskedMergeImpl(N01, N00, N10, N11, DL, DAG))
51334 return Result;
51335 if (SDValue Result = foldMaskedMergeImpl(N10, N11, N00, N01, DL, DAG))
51336 return Result;
51337 if (SDValue Result = foldMaskedMergeImpl(N11, N10, N00, N01, DL, DAG))
51338 return Result;
51339 return SDValue();
51342 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
51343 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
51344 /// with CMP+{ADC, SBB}.
51345 /// Also try (ADD/SUB)+(AND(SRL,1)) bit extraction pattern with BT+{ADC, SBB}.
51346 static SDValue combineAddOrSubToADCOrSBB(bool IsSub, const SDLoc &DL, EVT VT,
51347 SDValue X, SDValue Y,
51348 SelectionDAG &DAG,
51349 bool ZeroSecondOpOnly = false) {
51350 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
51351 return SDValue();
51353 // Look through a one-use zext.
51354 if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse())
51355 Y = Y.getOperand(0);
51357 X86::CondCode CC;
51358 SDValue EFLAGS;
51359 if (Y.getOpcode() == X86ISD::SETCC && Y.hasOneUse()) {
51360 CC = (X86::CondCode)Y.getConstantOperandVal(0);
51361 EFLAGS = Y.getOperand(1);
51362 } else if (Y.getOpcode() == ISD::AND && isOneConstant(Y.getOperand(1)) &&
51363 Y.hasOneUse()) {
51364 EFLAGS = LowerAndToBT(Y, ISD::SETNE, DL, DAG, CC);
51367 if (!EFLAGS)
51368 return SDValue();
51370 // If X is -1 or 0, then we have an opportunity to avoid constants required in
51371 // the general case below.
51372 auto *ConstantX = dyn_cast<ConstantSDNode>(X);
51373 if (ConstantX && !ZeroSecondOpOnly) {
51374 if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnes()) ||
51375 (IsSub && CC == X86::COND_B && ConstantX->isZero())) {
51376 // This is a complicated way to get -1 or 0 from the carry flag:
51377 // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51378 // 0 - SETB --> 0 - (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
51379 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51380 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51381 EFLAGS);
51384 if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnes()) ||
51385 (IsSub && CC == X86::COND_A && ConstantX->isZero())) {
51386 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
51387 EFLAGS.getValueType().isInteger() &&
51388 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51389 // Swap the operands of a SUB, and we have the same pattern as above.
51390 // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
51391 // 0 - SETA (SUB A, B) --> 0 - SETB (SUB B, A) --> SUB + SBB
51392 SDValue NewSub = DAG.getNode(
51393 X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51394 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51395 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
51396 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51397 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51398 NewEFLAGS);
51403 if (CC == X86::COND_B) {
51404 // X + SETB Z --> adc X, 0
51405 // X - SETB Z --> sbb X, 0
51406 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51407 DAG.getVTList(VT, MVT::i32), X,
51408 DAG.getConstant(0, DL, VT), EFLAGS);
51411 if (ZeroSecondOpOnly)
51412 return SDValue();
51414 if (CC == X86::COND_A) {
51415 // Try to convert COND_A into COND_B in an attempt to facilitate
51416 // materializing "setb reg".
51418 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
51419 // cannot take an immediate as its first operand.
51421 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51422 EFLAGS.getValueType().isInteger() &&
51423 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51424 SDValue NewSub =
51425 DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51426 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51427 SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51428 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
51429 DAG.getVTList(VT, MVT::i32), X,
51430 DAG.getConstant(0, DL, VT), NewEFLAGS);
51434 if (CC == X86::COND_AE) {
51435 // X + SETAE --> sbb X, -1
51436 // X - SETAE --> adc X, -1
51437 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51438 DAG.getVTList(VT, MVT::i32), X,
51439 DAG.getAllOnesConstant(DL, VT), EFLAGS);
51442 if (CC == X86::COND_BE) {
51443 // X + SETBE --> sbb X, -1
51444 // X - SETBE --> adc X, -1
51445 // Try to convert COND_BE into COND_AE in an attempt to facilitate
51446 // materializing "setae reg".
51448 // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
51449 // cannot take an immediate as its first operand.
51451 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
51452 EFLAGS.getValueType().isInteger() &&
51453 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
51454 SDValue NewSub =
51455 DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
51456 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
51457 SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
51458 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
51459 DAG.getVTList(VT, MVT::i32), X,
51460 DAG.getAllOnesConstant(DL, VT), NewEFLAGS);
51464 if (CC != X86::COND_E && CC != X86::COND_NE)
51465 return SDValue();
51467 if (EFLAGS.getOpcode() != X86ISD::CMP || !EFLAGS.hasOneUse() ||
51468 !X86::isZeroNode(EFLAGS.getOperand(1)) ||
51469 !EFLAGS.getOperand(0).getValueType().isInteger())
51470 return SDValue();
51472 SDValue Z = EFLAGS.getOperand(0);
51473 EVT ZVT = Z.getValueType();
51475 // If X is -1 or 0, then we have an opportunity to avoid constants required in
51476 // the general case below.
51477 if (ConstantX) {
51478 // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
51479 // fake operands:
51480 // 0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
51481 // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
51482 if ((IsSub && CC == X86::COND_NE && ConstantX->isZero()) ||
51483 (!IsSub && CC == X86::COND_E && ConstantX->isAllOnes())) {
51484 SDValue Zero = DAG.getConstant(0, DL, ZVT);
51485 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51486 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
51487 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51488 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51489 SDValue(Neg.getNode(), 1));
51492 // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
51493 // with fake operands:
51494 // 0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
51495 // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
51496 if ((IsSub && CC == X86::COND_E && ConstantX->isZero()) ||
51497 (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnes())) {
51498 SDValue One = DAG.getConstant(1, DL, ZVT);
51499 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51500 SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51501 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
51502 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
51503 Cmp1.getValue(1));
51507 // (cmp Z, 1) sets the carry flag if Z is 0.
51508 SDValue One = DAG.getConstant(1, DL, ZVT);
51509 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
51510 SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
51512 // Add the flags type for ADC/SBB nodes.
51513 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
51515 // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
51516 // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
51517 if (CC == X86::COND_NE)
51518 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
51519 DAG.getAllOnesConstant(DL, VT), Cmp1.getValue(1));
51521 // X - (Z == 0) --> sub X, (zext(sete Z, 0)) --> sbb X, 0, (cmp Z, 1)
51522 // X + (Z == 0) --> add X, (zext(sete Z, 0)) --> adc X, 0, (cmp Z, 1)
51523 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
51524 DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
51527 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
51528 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
51529 /// with CMP+{ADC, SBB}.
51530 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, const SDLoc &DL,
51531 SelectionDAG &DAG) {
51532 bool IsSub = N->getOpcode() == ISD::SUB;
51533 SDValue X = N->getOperand(0);
51534 SDValue Y = N->getOperand(1);
51535 EVT VT = N->getValueType(0);
51537 if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, X, Y, DAG))
51538 return ADCOrSBB;
51540 // Commute and try again (negate the result for subtracts).
51541 if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, Y, X, DAG)) {
51542 if (IsSub)
51543 ADCOrSBB = DAG.getNegative(ADCOrSBB, DL, VT);
51544 return ADCOrSBB;
51547 return SDValue();
51550 static SDValue combineOrXorWithSETCC(unsigned Opc, const SDLoc &DL, EVT VT,
51551 SDValue N0, SDValue N1,
51552 SelectionDAG &DAG) {
51553 assert((Opc == ISD::XOR || Opc == ISD::OR) && "Unexpected opcode");
51555 // Delegate to combineAddOrSubToADCOrSBB if we have:
51557 // (xor/or (zero_extend (setcc)) imm)
51559 // where imm is odd if and only if we have xor, in which case the XOR/OR are
51560 // equivalent to a SUB/ADD, respectively.
51561 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
51562 N0.getOperand(0).getOpcode() == X86ISD::SETCC && N0.hasOneUse()) {
51563 if (auto *N1C = dyn_cast<ConstantSDNode>(N1)) {
51564 bool IsSub = Opc == ISD::XOR;
51565 bool N1COdd = N1C->getZExtValue() & 1;
51566 if (IsSub ? N1COdd : !N1COdd)
51567 if (SDValue R = combineAddOrSubToADCOrSBB(IsSub, DL, VT, N1, N0, DAG))
51568 return R;
51572 // not(pcmpeq(and(X,CstPow2),0)) -> pcmpeq(and(X,CstPow2),CstPow2)
51573 if (Opc == ISD::XOR && N0.getOpcode() == X86ISD::PCMPEQ &&
51574 N0.getOperand(0).getOpcode() == ISD::AND &&
51575 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()) &&
51576 ISD::isBuildVectorAllOnes(N1.getNode()) &&
51577 isConstantPowerOf2(N0.getOperand(0).getOperand(1),
51578 VT.getScalarSizeInBits(), /*AllowUndefs=*/true)) {
51579 return DAG.getNode(X86ISD::PCMPEQ, DL, VT, N0.getOperand(0),
51580 N0.getOperand(0).getOperand(1));
51583 return SDValue();
51586 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
51587 TargetLowering::DAGCombinerInfo &DCI,
51588 const X86Subtarget &Subtarget) {
51589 SDValue N0 = N->getOperand(0);
51590 SDValue N1 = N->getOperand(1);
51591 EVT VT = N->getValueType(0);
51592 SDLoc dl(N);
51593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51595 // If this is SSE1 only convert to FOR to avoid scalarization.
51596 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
51597 return DAG.getBitcast(MVT::v4i32,
51598 DAG.getNode(X86ISD::FOR, dl, MVT::v4f32,
51599 DAG.getBitcast(MVT::v4f32, N0),
51600 DAG.getBitcast(MVT::v4f32, N1)));
51603 // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
51604 // TODO: Support multiple SrcOps.
51605 if (VT == MVT::i1) {
51606 SmallVector<SDValue, 2> SrcOps;
51607 SmallVector<APInt, 2> SrcPartials;
51608 if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
51609 SrcOps.size() == 1) {
51610 unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
51611 EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
51612 SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
51613 if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
51614 Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
51615 if (Mask) {
51616 assert(SrcPartials[0].getBitWidth() == NumElts &&
51617 "Unexpected partial reduction mask");
51618 SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
51619 SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
51620 Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
51621 return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
51626 if (SDValue SetCC = combineAndOrForCcmpCtest(N, DAG, DCI, Subtarget))
51627 return SetCC;
51629 if (SDValue R = combineBitOpWithMOVMSK(N->getOpcode(), dl, N0, N1, DAG))
51630 return R;
51632 if (SDValue R = combineBitOpWithShift(N->getOpcode(), dl, VT, N0, N1, DAG))
51633 return R;
51635 if (SDValue R = combineBitOpWithPACK(N->getOpcode(), dl, VT, N0, N1, DAG))
51636 return R;
51638 if (SDValue FPLogic = convertIntLogicToFPLogic(N->getOpcode(), dl, VT, N0, N1,
51639 DAG, DCI, Subtarget))
51640 return FPLogic;
51642 if (DCI.isBeforeLegalizeOps())
51643 return SDValue();
51645 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
51646 return R;
51648 if (SDValue R = canonicalizeBitSelect(N, dl, DAG, Subtarget))
51649 return R;
51651 if (SDValue R = combineLogicBlendIntoPBLENDV(N, dl, DAG, Subtarget))
51652 return R;
51654 // (0 - SetCC) | C -> (zext (not SetCC)) * (C + 1) - 1 if we can get a LEA out of it.
51655 if ((VT == MVT::i32 || VT == MVT::i64) &&
51656 N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
51657 isNullConstant(N0.getOperand(0))) {
51658 SDValue Cond = N0.getOperand(1);
51659 if (Cond.getOpcode() == ISD::ZERO_EXTEND && Cond.hasOneUse())
51660 Cond = Cond.getOperand(0);
51662 if (Cond.getOpcode() == X86ISD::SETCC && Cond.hasOneUse()) {
51663 if (auto *CN = dyn_cast<ConstantSDNode>(N1)) {
51664 uint64_t Val = CN->getZExtValue();
51665 if (Val == 1 || Val == 2 || Val == 3 || Val == 4 || Val == 7 || Val == 8) {
51666 X86::CondCode CCode = (X86::CondCode)Cond.getConstantOperandVal(0);
51667 CCode = X86::GetOppositeBranchCondition(CCode);
51668 SDValue NotCond = getSETCC(CCode, Cond.getOperand(1), SDLoc(Cond), DAG);
51670 SDValue R = DAG.getZExtOrTrunc(NotCond, dl, VT);
51671 R = DAG.getNode(ISD::MUL, dl, VT, R, DAG.getConstant(Val + 1, dl, VT));
51672 R = DAG.getNode(ISD::SUB, dl, VT, R, DAG.getConstant(1, dl, VT));
51673 return R;
51679 // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
51680 // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
51681 // iff the upper elements of the non-shifted arg are zero.
51682 // KUNPCK require 16+ bool vector elements.
51683 if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
51684 unsigned NumElts = VT.getVectorNumElements();
51685 unsigned HalfElts = NumElts / 2;
51686 APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
51687 if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
51688 N1.getConstantOperandAPInt(1) == HalfElts &&
51689 DAG.MaskedVectorIsZero(N0, UpperElts)) {
51690 return DAG.getNode(
51691 ISD::CONCAT_VECTORS, dl, VT,
51692 extractSubVector(N0, 0, DAG, dl, HalfElts),
51693 extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
51695 if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
51696 N0.getConstantOperandAPInt(1) == HalfElts &&
51697 DAG.MaskedVectorIsZero(N1, UpperElts)) {
51698 return DAG.getNode(
51699 ISD::CONCAT_VECTORS, dl, VT,
51700 extractSubVector(N1, 0, DAG, dl, HalfElts),
51701 extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
51705 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
51706 // Attempt to recursively combine an OR of shuffles.
51707 SDValue Op(N, 0);
51708 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
51709 return Res;
51711 // If either operand is a constant mask, then only the elements that aren't
51712 // allones are actually demanded by the other operand.
51713 auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
51714 APInt UndefElts;
51715 SmallVector<APInt> EltBits;
51716 int NumElts = VT.getVectorNumElements();
51717 int EltSizeInBits = VT.getScalarSizeInBits();
51718 if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
51719 return false;
51721 APInt DemandedElts = APInt::getZero(NumElts);
51722 for (int I = 0; I != NumElts; ++I)
51723 if (!EltBits[I].isAllOnes())
51724 DemandedElts.setBit(I);
51726 return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, DCI);
51728 if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
51729 if (N->getOpcode() != ISD::DELETED_NODE)
51730 DCI.AddToWorklist(N);
51731 return SDValue(N, 0);
51735 // We should fold "masked merge" patterns when `andn` is not available.
51736 if (!Subtarget.hasBMI() && VT.isScalarInteger() && VT != MVT::i1)
51737 if (SDValue R = foldMaskedMerge(N, DAG))
51738 return R;
51740 if (SDValue R = combineOrXorWithSETCC(N->getOpcode(), dl, VT, N0, N1, DAG))
51741 return R;
51743 return SDValue();
51746 /// Try to turn tests against the signbit in the form of:
51747 /// XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
51748 /// into:
51749 /// SETGT(X, -1)
51750 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
51751 // This is only worth doing if the output type is i8 or i1.
51752 EVT ResultType = N->getValueType(0);
51753 if (ResultType != MVT::i8 && ResultType != MVT::i1)
51754 return SDValue();
51756 SDValue N0 = N->getOperand(0);
51757 SDValue N1 = N->getOperand(1);
51759 // We should be performing an xor against a truncated shift.
51760 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
51761 return SDValue();
51763 // Make sure we are performing an xor against one.
51764 if (!isOneConstant(N1))
51765 return SDValue();
51767 // SetCC on x86 zero extends so only act on this if it's a logical shift.
51768 SDValue Shift = N0.getOperand(0);
51769 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
51770 return SDValue();
51772 // Make sure we are truncating from one of i16, i32 or i64.
51773 EVT ShiftTy = Shift.getValueType();
51774 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
51775 return SDValue();
51777 // Make sure the shift amount extracts the sign bit.
51778 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
51779 Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
51780 return SDValue();
51782 // Create a greater-than comparison against -1.
51783 // N.B. Using SETGE against 0 works but we want a canonical looking
51784 // comparison, using SETGT matches up with what TranslateX86CC.
51785 SDLoc DL(N);
51786 SDValue ShiftOp = Shift.getOperand(0);
51787 EVT ShiftOpTy = ShiftOp.getValueType();
51788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51789 EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
51790 *DAG.getContext(), ResultType);
51791 SDValue Cond =
51792 DAG.getSetCC(DL, SetCCResultType, ShiftOp,
51793 DAG.getAllOnesConstant(DL, ShiftOpTy), ISD::SETGT);
51794 if (SetCCResultType != ResultType)
51795 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
51796 return Cond;
51799 /// Turn vector tests of the signbit in the form of:
51800 /// xor (sra X, elt_size(X)-1), -1
51801 /// into:
51802 /// pcmpgt X, -1
51804 /// This should be called before type legalization because the pattern may not
51805 /// persist after that.
51806 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
51807 const X86Subtarget &Subtarget) {
51808 EVT VT = N->getValueType(0);
51809 if (!VT.isSimple())
51810 return SDValue();
51812 switch (VT.getSimpleVT().SimpleTy) {
51813 // clang-format off
51814 default: return SDValue();
51815 case MVT::v16i8:
51816 case MVT::v8i16:
51817 case MVT::v4i32:
51818 case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
51819 case MVT::v32i8:
51820 case MVT::v16i16:
51821 case MVT::v8i32:
51822 case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
51823 // clang-format on
51826 // There must be a shift right algebraic before the xor, and the xor must be a
51827 // 'not' operation.
51828 SDValue Shift = N->getOperand(0);
51829 SDValue Ones = N->getOperand(1);
51830 if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
51831 !ISD::isBuildVectorAllOnes(Ones.getNode()))
51832 return SDValue();
51834 // The shift should be smearing the sign bit across each vector element.
51835 auto *ShiftAmt =
51836 isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
51837 if (!ShiftAmt ||
51838 ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
51839 return SDValue();
51841 // Create a greater-than comparison against -1. We don't use the more obvious
51842 // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
51843 return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
51846 /// Detect patterns of truncation with unsigned saturation:
51848 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
51849 /// Return the source value x to be truncated or SDValue() if the pattern was
51850 /// not matched.
51852 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
51853 /// where C1 >= 0 and C2 is unsigned max of destination type.
51855 /// (truncate (smax (smin (x, C2), C1)) to dest_type)
51856 /// where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
51858 /// These two patterns are equivalent to:
51859 /// (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
51860 /// So return the smax(x, C1) value to be truncated or SDValue() if the
51861 /// pattern was not matched.
51862 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
51863 const SDLoc &DL) {
51864 using namespace llvm::SDPatternMatch;
51865 EVT InVT = In.getValueType();
51867 // Saturation with truncation. We truncate from InVT to VT.
51868 assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
51869 "Unexpected types for truncate operation");
51871 APInt C1, C2;
51872 SDValue UMin, SMin, SMax;
51874 // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
51875 // the element size of the destination type.
51876 if (sd_match(In, m_UMin(m_Value(UMin), m_ConstInt(C2))) &&
51877 C2.isMask(VT.getScalarSizeInBits()))
51878 return UMin;
51880 if (sd_match(In, m_SMin(m_Value(SMin), m_ConstInt(C2))) &&
51881 sd_match(SMin, m_SMax(m_Value(SMax), m_ConstInt(C1))) &&
51882 C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
51883 return SMin;
51885 if (sd_match(In, m_SMax(m_Value(SMax), m_ConstInt(C1))) &&
51886 sd_match(SMax, m_SMin(m_Value(SMin), m_ConstInt(C2))) &&
51887 C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) && C2.uge(C1))
51888 return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
51890 return SDValue();
51893 /// Detect patterns of truncation with signed saturation:
51894 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
51895 /// signed_max_of_dest_type)) to dest_type)
51896 /// or:
51897 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
51898 /// signed_min_of_dest_type)) to dest_type).
51899 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
51900 /// Return the source value to be truncated or SDValue() if the pattern was not
51901 /// matched.
51902 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
51903 using namespace llvm::SDPatternMatch;
51904 unsigned NumDstBits = VT.getScalarSizeInBits();
51905 unsigned NumSrcBits = In.getScalarValueSizeInBits();
51906 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
51908 APInt SignedMax, SignedMin;
51909 if (MatchPackUS) {
51910 SignedMax = APInt::getAllOnes(NumDstBits).zext(NumSrcBits);
51911 SignedMin = APInt::getZero(NumSrcBits);
51912 } else {
51913 SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
51914 SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
51917 SDValue SMin, SMax;
51918 if (sd_match(In, m_SMin(m_Value(SMin), m_SpecificInt(SignedMax))) &&
51919 sd_match(SMin, m_SMax(m_Value(SMax), m_SpecificInt(SignedMin))))
51920 return SMax;
51922 if (sd_match(In, m_SMax(m_Value(SMax), m_SpecificInt(SignedMin))) &&
51923 sd_match(SMax, m_SMin(m_Value(SMin), m_SpecificInt(SignedMax))))
51924 return SMin;
51926 return SDValue();
51929 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
51930 SelectionDAG &DAG,
51931 const X86Subtarget &Subtarget) {
51932 if (!Subtarget.hasSSE2() || !VT.isVector())
51933 return SDValue();
51935 EVT SVT = VT.getVectorElementType();
51936 EVT InVT = In.getValueType();
51937 EVT InSVT = InVT.getVectorElementType();
51939 // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
51940 // split across two registers. We can use a packusdw+perm to clamp to 0-65535
51941 // and concatenate at the same time. Then we can use a final vpmovuswb to
51942 // clip to 0-255.
51943 if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
51944 InVT == MVT::v16i32 && VT == MVT::v16i8) {
51945 if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
51946 // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
51947 SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
51948 DL, DAG, Subtarget);
51949 assert(Mid && "Failed to pack!");
51950 return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
51954 // vXi32 truncate instructions are available with AVX512F.
51955 // vXi16 truncate instructions are only available with AVX512BW.
51956 // For 256-bit or smaller vectors, we require VLX.
51957 // FIXME: We could widen truncates to 512 to remove the VLX restriction.
51958 // If the result type is 256-bits or larger and we have disable 512-bit
51959 // registers, we should go ahead and use the pack instructions if possible.
51960 bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
51961 (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
51962 (InVT.getSizeInBits() > 128) &&
51963 (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
51964 !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
51966 if (!PreferAVX512 && VT.getVectorNumElements() > 1 &&
51967 isPowerOf2_32(VT.getVectorNumElements()) &&
51968 (SVT == MVT::i8 || SVT == MVT::i16) &&
51969 (InSVT == MVT::i16 || InSVT == MVT::i32)) {
51970 if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
51971 // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
51972 if (SVT == MVT::i8 && InSVT == MVT::i32) {
51973 EVT MidVT = VT.changeVectorElementType(MVT::i16);
51974 SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
51975 DAG, Subtarget);
51976 assert(Mid && "Failed to pack!");
51977 SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
51978 Subtarget);
51979 assert(V && "Failed to pack!");
51980 return V;
51981 } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
51982 return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
51983 Subtarget);
51985 if (SDValue SSatVal = detectSSatPattern(In, VT))
51986 return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
51987 Subtarget);
51990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51991 if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
51992 Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
51993 (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
51994 unsigned TruncOpc = 0;
51995 SDValue SatVal;
51996 if (SDValue SSatVal = detectSSatPattern(In, VT)) {
51997 SatVal = SSatVal;
51998 TruncOpc = X86ISD::VTRUNCS;
51999 } else if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL)) {
52000 SatVal = USatVal;
52001 TruncOpc = X86ISD::VTRUNCUS;
52003 if (SatVal) {
52004 unsigned ResElts = VT.getVectorNumElements();
52005 // If the input type is less than 512 bits and we don't have VLX, we need
52006 // to widen to 512 bits.
52007 if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
52008 unsigned NumConcats = 512 / InVT.getSizeInBits();
52009 ResElts *= NumConcats;
52010 SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
52011 ConcatOps[0] = SatVal;
52012 InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
52013 NumConcats * InVT.getVectorNumElements());
52014 SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
52016 // Widen the result if its narrower than 128 bits.
52017 if (ResElts * SVT.getSizeInBits() < 128)
52018 ResElts = 128 / SVT.getSizeInBits();
52019 EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
52020 SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
52021 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
52022 DAG.getIntPtrConstant(0, DL));
52026 return SDValue();
52029 static SDValue combineConstantPoolLoads(SDNode *N, const SDLoc &dl,
52030 SelectionDAG &DAG,
52031 TargetLowering::DAGCombinerInfo &DCI,
52032 const X86Subtarget &Subtarget) {
52033 auto *Ld = cast<LoadSDNode>(N);
52034 EVT RegVT = Ld->getValueType(0);
52035 SDValue Ptr = Ld->getBasePtr();
52036 SDValue Chain = Ld->getChain();
52037 ISD::LoadExtType Ext = Ld->getExtensionType();
52039 if (Ext != ISD::NON_EXTLOAD || !Subtarget.hasAVX() || !Ld->isSimple())
52040 return SDValue();
52042 if (!(RegVT.is128BitVector() || RegVT.is256BitVector()))
52043 return SDValue();
52045 const Constant *LdC = getTargetConstantFromBasePtr(Ptr);
52046 if (!LdC)
52047 return SDValue();
52049 auto MatchingBits = [](const APInt &Undefs, const APInt &UserUndefs,
52050 ArrayRef<APInt> Bits, ArrayRef<APInt> UserBits) {
52051 for (unsigned I = 0, E = Undefs.getBitWidth(); I != E; ++I) {
52052 if (Undefs[I])
52053 continue;
52054 if (UserUndefs[I] || Bits[I] != UserBits[I])
52055 return false;
52057 return true;
52060 // Look through all other loads/broadcasts in the chain for another constant
52061 // pool entry.
52062 for (SDNode *User : Chain->uses()) {
52063 auto *UserLd = dyn_cast<MemSDNode>(User);
52064 if (User != N && UserLd &&
52065 (User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD ||
52066 User->getOpcode() == X86ISD::VBROADCAST_LOAD ||
52067 ISD::isNormalLoad(User)) &&
52068 UserLd->getChain() == Chain && !User->hasAnyUseOfValue(1) &&
52069 User->getValueSizeInBits(0).getFixedValue() >
52070 RegVT.getFixedSizeInBits()) {
52071 EVT UserVT = User->getValueType(0);
52072 SDValue UserPtr = UserLd->getBasePtr();
52073 const Constant *UserC = getTargetConstantFromBasePtr(UserPtr);
52075 // See if we are loading a constant that matches in the lower
52076 // bits of a longer constant (but from a different constant pool ptr).
52077 if (UserC && UserPtr != Ptr) {
52078 unsigned LdSize = LdC->getType()->getPrimitiveSizeInBits();
52079 unsigned UserSize = UserC->getType()->getPrimitiveSizeInBits();
52080 if (LdSize < UserSize || !ISD::isNormalLoad(User)) {
52081 APInt Undefs, UserUndefs;
52082 SmallVector<APInt> Bits, UserBits;
52083 unsigned NumBits = std::min(RegVT.getScalarSizeInBits(),
52084 UserVT.getScalarSizeInBits());
52085 if (getTargetConstantBitsFromNode(SDValue(N, 0), NumBits, Undefs,
52086 Bits) &&
52087 getTargetConstantBitsFromNode(SDValue(User, 0), NumBits,
52088 UserUndefs, UserBits)) {
52089 if (MatchingBits(Undefs, UserUndefs, Bits, UserBits)) {
52090 SDValue Extract = extractSubVector(
52091 SDValue(User, 0), 0, DAG, SDLoc(N), RegVT.getSizeInBits());
52092 Extract = DAG.getBitcast(RegVT, Extract);
52093 return DCI.CombineTo(N, Extract, SDValue(User, 1));
52101 return SDValue();
52104 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
52105 TargetLowering::DAGCombinerInfo &DCI,
52106 const X86Subtarget &Subtarget) {
52107 auto *Ld = cast<LoadSDNode>(N);
52108 EVT RegVT = Ld->getValueType(0);
52109 EVT MemVT = Ld->getMemoryVT();
52110 SDLoc dl(Ld);
52111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52113 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
52114 // into two 16-byte operations. Also split non-temporal aligned loads on
52115 // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
52116 ISD::LoadExtType Ext = Ld->getExtensionType();
52117 unsigned Fast;
52118 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
52119 Ext == ISD::NON_EXTLOAD &&
52120 ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
52121 Ld->getAlign() >= Align(16)) ||
52122 (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
52123 *Ld->getMemOperand(), &Fast) &&
52124 !Fast))) {
52125 unsigned NumElems = RegVT.getVectorNumElements();
52126 if (NumElems < 2)
52127 return SDValue();
52129 unsigned HalfOffset = 16;
52130 SDValue Ptr1 = Ld->getBasePtr();
52131 SDValue Ptr2 =
52132 DAG.getMemBasePlusOffset(Ptr1, TypeSize::getFixed(HalfOffset), dl);
52133 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
52134 NumElems / 2);
52135 SDValue Load1 =
52136 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
52137 Ld->getOriginalAlign(),
52138 Ld->getMemOperand()->getFlags());
52139 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
52140 Ld->getPointerInfo().getWithOffset(HalfOffset),
52141 Ld->getOriginalAlign(),
52142 Ld->getMemOperand()->getFlags());
52143 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
52144 Load1.getValue(1), Load2.getValue(1));
52146 SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
52147 return DCI.CombineTo(N, NewVec, TF, true);
52150 // Bool vector load - attempt to cast to an integer, as we have good
52151 // (vXiY *ext(vXi1 bitcast(iX))) handling.
52152 if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
52153 RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
52154 unsigned NumElts = RegVT.getVectorNumElements();
52155 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
52156 if (TLI.isTypeLegal(IntVT)) {
52157 SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
52158 Ld->getPointerInfo(),
52159 Ld->getOriginalAlign(),
52160 Ld->getMemOperand()->getFlags());
52161 SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
52162 return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
52166 // If we also broadcast this vector to a wider type, then just extract the
52167 // lowest subvector.
52168 if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
52169 (RegVT.is128BitVector() || RegVT.is256BitVector())) {
52170 SDValue Ptr = Ld->getBasePtr();
52171 SDValue Chain = Ld->getChain();
52172 for (SDNode *User : Chain->uses()) {
52173 auto *UserLd = dyn_cast<MemSDNode>(User);
52174 if (User != N && UserLd &&
52175 User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
52176 UserLd->getChain() == Chain && UserLd->getBasePtr() == Ptr &&
52177 UserLd->getMemoryVT().getSizeInBits() == MemVT.getSizeInBits() &&
52178 !User->hasAnyUseOfValue(1) &&
52179 User->getValueSizeInBits(0).getFixedValue() >
52180 RegVT.getFixedSizeInBits()) {
52181 SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, dl,
52182 RegVT.getSizeInBits());
52183 Extract = DAG.getBitcast(RegVT, Extract);
52184 return DCI.CombineTo(N, Extract, SDValue(User, 1));
52189 if (SDValue V = combineConstantPoolLoads(Ld, dl, DAG, DCI, Subtarget))
52190 return V;
52192 // Cast ptr32 and ptr64 pointers to the default address space before a load.
52193 unsigned AddrSpace = Ld->getAddressSpace();
52194 if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
52195 AddrSpace == X86AS::PTR32_UPTR) {
52196 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
52197 if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
52198 SDValue Cast =
52199 DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
52200 return DAG.getExtLoad(Ext, dl, RegVT, Ld->getChain(), Cast,
52201 Ld->getPointerInfo(), MemVT, Ld->getOriginalAlign(),
52202 Ld->getMemOperand()->getFlags());
52206 return SDValue();
52209 /// If V is a build vector of boolean constants and exactly one of those
52210 /// constants is true, return the operand index of that true element.
52211 /// Otherwise, return -1.
52212 static int getOneTrueElt(SDValue V) {
52213 // This needs to be a build vector of booleans.
52214 // TODO: Checking for the i1 type matches the IR definition for the mask,
52215 // but the mask check could be loosened to i8 or other types. That might
52216 // also require checking more than 'allOnesValue'; eg, the x86 HW
52217 // instructions only require that the MSB is set for each mask element.
52218 // The ISD::MSTORE comments/definition do not specify how the mask operand
52219 // is formatted.
52220 auto *BV = dyn_cast<BuildVectorSDNode>(V);
52221 if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
52222 return -1;
52224 int TrueIndex = -1;
52225 unsigned NumElts = BV->getValueType(0).getVectorNumElements();
52226 for (unsigned i = 0; i < NumElts; ++i) {
52227 const SDValue &Op = BV->getOperand(i);
52228 if (Op.isUndef())
52229 continue;
52230 auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
52231 if (!ConstNode)
52232 return -1;
52233 if (ConstNode->getAPIntValue().countr_one() >= 1) {
52234 // If we already found a one, this is too many.
52235 if (TrueIndex >= 0)
52236 return -1;
52237 TrueIndex = i;
52240 return TrueIndex;
52243 /// Given a masked memory load/store operation, return true if it has one mask
52244 /// bit set. If it has one mask bit set, then also return the memory address of
52245 /// the scalar element to load/store, the vector index to insert/extract that
52246 /// scalar element, and the alignment for the scalar memory access.
52247 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
52248 SelectionDAG &DAG, SDValue &Addr,
52249 SDValue &Index, Align &Alignment,
52250 unsigned &Offset) {
52251 int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
52252 if (TrueMaskElt < 0)
52253 return false;
52255 // Get the address of the one scalar element that is specified by the mask
52256 // using the appropriate offset from the base pointer.
52257 EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
52258 Offset = 0;
52259 Addr = MaskedOp->getBasePtr();
52260 if (TrueMaskElt != 0) {
52261 Offset = TrueMaskElt * EltVT.getStoreSize();
52262 Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::getFixed(Offset),
52263 SDLoc(MaskedOp));
52266 Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
52267 Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
52268 EltVT.getStoreSize());
52269 return true;
52272 /// If exactly one element of the mask is set for a non-extending masked load,
52273 /// it is a scalar load and vector insert.
52274 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
52275 /// mask have already been optimized in IR, so we don't bother with those here.
52276 static SDValue
52277 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
52278 TargetLowering::DAGCombinerInfo &DCI,
52279 const X86Subtarget &Subtarget) {
52280 assert(ML->isUnindexed() && "Unexpected indexed masked load!");
52281 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
52282 // However, some target hooks may need to be added to know when the transform
52283 // is profitable. Endianness would also have to be considered.
52285 SDValue Addr, VecIndex;
52286 Align Alignment;
52287 unsigned Offset;
52288 if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
52289 return SDValue();
52291 // Load the one scalar element that is specified by the mask using the
52292 // appropriate offset from the base pointer.
52293 SDLoc DL(ML);
52294 EVT VT = ML->getValueType(0);
52295 EVT EltVT = VT.getVectorElementType();
52297 EVT CastVT = VT;
52298 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
52299 EltVT = MVT::f64;
52300 CastVT = VT.changeVectorElementType(EltVT);
52303 SDValue Load =
52304 DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
52305 ML->getPointerInfo().getWithOffset(Offset),
52306 Alignment, ML->getMemOperand()->getFlags());
52308 SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
52310 // Insert the loaded element into the appropriate place in the vector.
52311 SDValue Insert =
52312 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
52313 Insert = DAG.getBitcast(VT, Insert);
52314 return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
52317 static SDValue
52318 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
52319 TargetLowering::DAGCombinerInfo &DCI) {
52320 assert(ML->isUnindexed() && "Unexpected indexed masked load!");
52321 if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
52322 return SDValue();
52324 SDLoc DL(ML);
52325 EVT VT = ML->getValueType(0);
52327 // If we are loading the first and last elements of a vector, it is safe and
52328 // always faster to load the whole vector. Replace the masked load with a
52329 // vector load and select.
52330 unsigned NumElts = VT.getVectorNumElements();
52331 BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
52332 bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
52333 bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
52334 if (LoadFirstElt && LoadLastElt) {
52335 SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
52336 ML->getMemOperand());
52337 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
52338 ML->getPassThru());
52339 return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
52342 // Convert a masked load with a constant mask into a masked load and a select.
52343 // This allows the select operation to use a faster kind of select instruction
52344 // (for example, vblendvps -> vblendps).
52346 // Don't try this if the pass-through operand is already undefined. That would
52347 // cause an infinite loop because that's what we're about to create.
52348 if (ML->getPassThru().isUndef())
52349 return SDValue();
52351 if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
52352 return SDValue();
52354 // The new masked load has an undef pass-through operand. The select uses the
52355 // original pass-through operand.
52356 SDValue NewML = DAG.getMaskedLoad(
52357 VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
52358 DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
52359 ML->getAddressingMode(), ML->getExtensionType());
52360 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
52361 ML->getPassThru());
52363 return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
52366 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
52367 TargetLowering::DAGCombinerInfo &DCI,
52368 const X86Subtarget &Subtarget) {
52369 auto *Mld = cast<MaskedLoadSDNode>(N);
52371 // TODO: Expanding load with constant mask may be optimized as well.
52372 if (Mld->isExpandingLoad())
52373 return SDValue();
52375 if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
52376 if (SDValue ScalarLoad =
52377 reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
52378 return ScalarLoad;
52380 // TODO: Do some AVX512 subsets benefit from this transform?
52381 if (!Subtarget.hasAVX512())
52382 if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
52383 return Blend;
52386 // If the mask value has been legalized to a non-boolean vector, try to
52387 // simplify ops leading up to it. We only demand the MSB of each lane.
52388 SDValue Mask = Mld->getMask();
52389 if (Mask.getScalarValueSizeInBits() != 1) {
52390 EVT VT = Mld->getValueType(0);
52391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52392 APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
52393 if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
52394 if (N->getOpcode() != ISD::DELETED_NODE)
52395 DCI.AddToWorklist(N);
52396 return SDValue(N, 0);
52398 if (SDValue NewMask =
52399 TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
52400 return DAG.getMaskedLoad(
52401 VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
52402 NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
52403 Mld->getAddressingMode(), Mld->getExtensionType());
52406 return SDValue();
52409 /// If exactly one element of the mask is set for a non-truncating masked store,
52410 /// it is a vector extract and scalar store.
52411 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
52412 /// mask have already been optimized in IR, so we don't bother with those here.
52413 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
52414 SelectionDAG &DAG,
52415 const X86Subtarget &Subtarget) {
52416 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
52417 // However, some target hooks may need to be added to know when the transform
52418 // is profitable. Endianness would also have to be considered.
52420 SDValue Addr, VecIndex;
52421 Align Alignment;
52422 unsigned Offset;
52423 if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
52424 return SDValue();
52426 // Extract the one scalar element that is actually being stored.
52427 SDLoc DL(MS);
52428 SDValue Value = MS->getValue();
52429 EVT VT = Value.getValueType();
52430 EVT EltVT = VT.getVectorElementType();
52431 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
52432 EltVT = MVT::f64;
52433 EVT CastVT = VT.changeVectorElementType(EltVT);
52434 Value = DAG.getBitcast(CastVT, Value);
52436 SDValue Extract =
52437 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
52439 // Store that element at the appropriate offset from the base pointer.
52440 return DAG.getStore(MS->getChain(), DL, Extract, Addr,
52441 MS->getPointerInfo().getWithOffset(Offset),
52442 Alignment, MS->getMemOperand()->getFlags());
52445 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
52446 TargetLowering::DAGCombinerInfo &DCI,
52447 const X86Subtarget &Subtarget) {
52448 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
52449 if (Mst->isCompressingStore())
52450 return SDValue();
52452 EVT VT = Mst->getValue().getValueType();
52453 SDLoc dl(Mst);
52454 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52456 if (Mst->isTruncatingStore())
52457 return SDValue();
52459 if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
52460 return ScalarStore;
52462 // If the mask value has been legalized to a non-boolean vector, try to
52463 // simplify ops leading up to it. We only demand the MSB of each lane.
52464 SDValue Mask = Mst->getMask();
52465 if (Mask.getScalarValueSizeInBits() != 1) {
52466 APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
52467 if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
52468 if (N->getOpcode() != ISD::DELETED_NODE)
52469 DCI.AddToWorklist(N);
52470 return SDValue(N, 0);
52472 if (SDValue NewMask =
52473 TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
52474 return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
52475 Mst->getBasePtr(), Mst->getOffset(), NewMask,
52476 Mst->getMemoryVT(), Mst->getMemOperand(),
52477 Mst->getAddressingMode());
52480 SDValue Value = Mst->getValue();
52481 if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
52482 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
52483 Mst->getMemoryVT())) {
52484 return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
52485 Mst->getBasePtr(), Mst->getOffset(), Mask,
52486 Mst->getMemoryVT(), Mst->getMemOperand(),
52487 Mst->getAddressingMode(), true);
52490 return SDValue();
52493 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
52494 TargetLowering::DAGCombinerInfo &DCI,
52495 const X86Subtarget &Subtarget) {
52496 StoreSDNode *St = cast<StoreSDNode>(N);
52497 EVT StVT = St->getMemoryVT();
52498 SDLoc dl(St);
52499 SDValue StoredVal = St->getValue();
52500 EVT VT = StoredVal.getValueType();
52501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52503 // Convert a store of vXi1 into a store of iX and a bitcast.
52504 if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
52505 VT.getVectorElementType() == MVT::i1) {
52507 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
52508 StoredVal = DAG.getBitcast(NewVT, StoredVal);
52510 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52511 St->getPointerInfo(), St->getOriginalAlign(),
52512 St->getMemOperand()->getFlags());
52515 // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
52516 // This will avoid a copy to k-register.
52517 if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
52518 StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
52519 StoredVal.getOperand(0).getValueType() == MVT::i8) {
52520 SDValue Val = StoredVal.getOperand(0);
52521 // We must store zeros to the unused bits.
52522 Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
52523 return DAG.getStore(St->getChain(), dl, Val,
52524 St->getBasePtr(), St->getPointerInfo(),
52525 St->getOriginalAlign(),
52526 St->getMemOperand()->getFlags());
52529 // Widen v2i1/v4i1 stores to v8i1.
52530 if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
52531 Subtarget.hasAVX512()) {
52532 unsigned NumConcats = 8 / VT.getVectorNumElements();
52533 // We must store zeros to the unused bits.
52534 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
52535 Ops[0] = StoredVal;
52536 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
52537 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52538 St->getPointerInfo(), St->getOriginalAlign(),
52539 St->getMemOperand()->getFlags());
52542 // Turn vXi1 stores of constants into a scalar store.
52543 if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
52544 VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
52545 ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
52546 // If its a v64i1 store without 64-bit support, we need two stores.
52547 if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
52548 SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
52549 StoredVal->ops().slice(0, 32));
52550 Lo = combinevXi1ConstantToInteger(Lo, DAG);
52551 SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
52552 StoredVal->ops().slice(32, 32));
52553 Hi = combinevXi1ConstantToInteger(Hi, DAG);
52555 SDValue Ptr0 = St->getBasePtr();
52556 SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::getFixed(4), dl);
52558 SDValue Ch0 =
52559 DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
52560 St->getOriginalAlign(),
52561 St->getMemOperand()->getFlags());
52562 SDValue Ch1 =
52563 DAG.getStore(St->getChain(), dl, Hi, Ptr1,
52564 St->getPointerInfo().getWithOffset(4),
52565 St->getOriginalAlign(),
52566 St->getMemOperand()->getFlags());
52567 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
52570 StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
52571 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
52572 St->getPointerInfo(), St->getOriginalAlign(),
52573 St->getMemOperand()->getFlags());
52576 // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
52577 // Sandy Bridge, perform two 16-byte stores.
52578 unsigned Fast;
52579 if (VT.is256BitVector() && StVT == VT &&
52580 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
52581 *St->getMemOperand(), &Fast) &&
52582 !Fast) {
52583 unsigned NumElems = VT.getVectorNumElements();
52584 if (NumElems < 2)
52585 return SDValue();
52587 return splitVectorStore(St, DAG);
52590 // Split under-aligned vector non-temporal stores.
52591 if (St->isNonTemporal() && StVT == VT &&
52592 St->getAlign().value() < VT.getStoreSize()) {
52593 // ZMM/YMM nt-stores - either it can be stored as a series of shorter
52594 // vectors or the legalizer can scalarize it to use MOVNTI.
52595 if (VT.is256BitVector() || VT.is512BitVector()) {
52596 unsigned NumElems = VT.getVectorNumElements();
52597 if (NumElems < 2)
52598 return SDValue();
52599 return splitVectorStore(St, DAG);
52602 // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
52603 // to use MOVNTI.
52604 if (VT.is128BitVector() && Subtarget.hasSSE2()) {
52605 MVT NTVT = Subtarget.hasSSE4A()
52606 ? MVT::v2f64
52607 : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
52608 return scalarizeVectorStore(St, NTVT, DAG);
52612 // Try to optimize v16i16->v16i8 truncating stores when BWI is not
52613 // supported, but avx512f is by extending to v16i32 and truncating.
52614 if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
52615 St->getValue().getOpcode() == ISD::TRUNCATE &&
52616 St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
52617 TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
52618 St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
52619 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32,
52620 St->getValue().getOperand(0));
52621 return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
52622 MVT::v16i8, St->getMemOperand());
52625 // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
52626 if (!St->isTruncatingStore() &&
52627 (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
52628 StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
52629 StoredVal.hasOneUse() &&
52630 TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
52631 bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
52632 return EmitTruncSStore(IsSigned, St->getChain(),
52633 dl, StoredVal.getOperand(0), St->getBasePtr(),
52634 VT, St->getMemOperand(), DAG);
52637 // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
52638 if (!St->isTruncatingStore()) {
52639 auto IsExtractedElement = [](SDValue V) {
52640 if (V.getOpcode() == ISD::TRUNCATE && V.hasOneUse())
52641 V = V.getOperand(0);
52642 unsigned Opc = V.getOpcode();
52643 if ((Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) &&
52644 isNullConstant(V.getOperand(1)) && V.hasOneUse() &&
52645 V.getOperand(0).hasOneUse())
52646 return V.getOperand(0);
52647 return SDValue();
52649 if (SDValue Extract = IsExtractedElement(StoredVal)) {
52650 SDValue Trunc = peekThroughOneUseBitcasts(Extract);
52651 if (Trunc.getOpcode() == X86ISD::VTRUNC) {
52652 SDValue Src = Trunc.getOperand(0);
52653 MVT DstVT = Trunc.getSimpleValueType();
52654 MVT SrcVT = Src.getSimpleValueType();
52655 unsigned NumSrcElts = SrcVT.getVectorNumElements();
52656 unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
52657 MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
52658 if (NumTruncBits == VT.getSizeInBits() &&
52659 TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
52660 return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
52661 TruncVT, St->getMemOperand());
52667 // Optimize trunc store (of multiple scalars) to shuffle and store.
52668 // First, pack all of the elements in one place. Next, store to memory
52669 // in fewer chunks.
52670 if (St->isTruncatingStore() && VT.isVector()) {
52671 if (TLI.isTruncStoreLegal(VT, StVT)) {
52672 if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
52673 return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
52674 dl, Val, St->getBasePtr(),
52675 St->getMemoryVT(), St->getMemOperand(), DAG);
52676 if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
52677 DAG, dl))
52678 return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
52679 dl, Val, St->getBasePtr(),
52680 St->getMemoryVT(), St->getMemOperand(), DAG);
52683 return SDValue();
52686 // Cast ptr32 and ptr64 pointers to the default address space before a store.
52687 unsigned AddrSpace = St->getAddressSpace();
52688 if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
52689 AddrSpace == X86AS::PTR32_UPTR) {
52690 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
52691 if (PtrVT != St->getBasePtr().getSimpleValueType()) {
52692 SDValue Cast =
52693 DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
52694 return DAG.getTruncStore(
52695 St->getChain(), dl, StoredVal, Cast, St->getPointerInfo(), StVT,
52696 St->getOriginalAlign(), St->getMemOperand()->getFlags(),
52697 St->getAAInfo());
52701 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
52702 // the FP state in cases where an emms may be missing.
52703 // A preferable solution to the general problem is to figure out the right
52704 // places to insert EMMS. This qualifies as a quick hack.
52706 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
52707 if (VT.getSizeInBits() != 64)
52708 return SDValue();
52710 const Function &F = DAG.getMachineFunction().getFunction();
52711 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
52712 bool F64IsLegal =
52713 !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
52715 if (!F64IsLegal || Subtarget.is64Bit())
52716 return SDValue();
52718 if (VT == MVT::i64 && isa<LoadSDNode>(St->getValue()) &&
52719 cast<LoadSDNode>(St->getValue())->isSimple() &&
52720 St->getChain().hasOneUse() && St->isSimple()) {
52721 auto *Ld = cast<LoadSDNode>(St->getValue());
52723 if (!ISD::isNormalLoad(Ld))
52724 return SDValue();
52726 // Avoid the transformation if there are multiple uses of the loaded value.
52727 if (!Ld->hasNUsesOfValue(1, 0))
52728 return SDValue();
52730 SDLoc LdDL(Ld);
52731 SDLoc StDL(N);
52732 // Lower to a single movq load/store pair.
52733 SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
52734 Ld->getBasePtr(), Ld->getMemOperand());
52736 // Make sure new load is placed in same chain order.
52737 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
52738 return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
52739 St->getMemOperand());
52742 // This is similar to the above case, but here we handle a scalar 64-bit
52743 // integer store that is extracted from a vector on a 32-bit target.
52744 // If we have SSE2, then we can treat it like a floating-point double
52745 // to get past legalization. The execution dependencies fixup pass will
52746 // choose the optimal machine instruction for the store if this really is
52747 // an integer or v2f32 rather than an f64.
52748 if (VT == MVT::i64 &&
52749 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
52750 SDValue OldExtract = St->getOperand(1);
52751 SDValue ExtOp0 = OldExtract.getOperand(0);
52752 unsigned VecSize = ExtOp0.getValueSizeInBits();
52753 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
52754 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
52755 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
52756 BitCast, OldExtract.getOperand(1));
52757 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
52758 St->getPointerInfo(), St->getOriginalAlign(),
52759 St->getMemOperand()->getFlags());
52762 return SDValue();
52765 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
52766 TargetLowering::DAGCombinerInfo &DCI,
52767 const X86Subtarget &Subtarget) {
52768 auto *St = cast<MemIntrinsicSDNode>(N);
52770 SDValue StoredVal = N->getOperand(1);
52771 MVT VT = StoredVal.getSimpleValueType();
52772 EVT MemVT = St->getMemoryVT();
52774 // Figure out which elements we demand.
52775 unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
52776 APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
52778 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52779 if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, DCI)) {
52780 if (N->getOpcode() != ISD::DELETED_NODE)
52781 DCI.AddToWorklist(N);
52782 return SDValue(N, 0);
52785 return SDValue();
52788 /// Return 'true' if this vector operation is "horizontal"
52789 /// and return the operands for the horizontal operation in LHS and RHS. A
52790 /// horizontal operation performs the binary operation on successive elements
52791 /// of its first operand, then on successive elements of its second operand,
52792 /// returning the resulting values in a vector. For example, if
52793 /// A = < float a0, float a1, float a2, float a3 >
52794 /// and
52795 /// B = < float b0, float b1, float b2, float b3 >
52796 /// then the result of doing a horizontal operation on A and B is
52797 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
52798 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
52799 /// A horizontal-op B, for some already available A and B, and if so then LHS is
52800 /// set to A, RHS to B, and the routine returns 'true'.
52801 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
52802 SelectionDAG &DAG, const X86Subtarget &Subtarget,
52803 bool IsCommutative,
52804 SmallVectorImpl<int> &PostShuffleMask,
52805 bool ForceHorizOp) {
52806 // If either operand is undef, bail out. The binop should be simplified.
52807 if (LHS.isUndef() || RHS.isUndef())
52808 return false;
52810 // Look for the following pattern:
52811 // A = < float a0, float a1, float a2, float a3 >
52812 // B = < float b0, float b1, float b2, float b3 >
52813 // and
52814 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
52815 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
52816 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
52817 // which is A horizontal-op B.
52819 MVT VT = LHS.getSimpleValueType();
52820 assert((VT.is128BitVector() || VT.is256BitVector()) &&
52821 "Unsupported vector type for horizontal add/sub");
52822 unsigned NumElts = VT.getVectorNumElements();
52824 auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
52825 SmallVectorImpl<int> &ShuffleMask) {
52826 bool UseSubVector = false;
52827 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
52828 Op.getOperand(0).getValueType().is256BitVector() &&
52829 llvm::isNullConstant(Op.getOperand(1))) {
52830 Op = Op.getOperand(0);
52831 UseSubVector = true;
52833 SmallVector<SDValue, 2> SrcOps;
52834 SmallVector<int, 16> SrcMask, ScaledMask;
52835 SDValue BC = peekThroughBitcasts(Op);
52836 if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
52837 !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
52838 return Op.getValueSizeInBits() == BC.getValueSizeInBits();
52839 })) {
52840 resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
52841 if (!UseSubVector && SrcOps.size() <= 2 &&
52842 scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
52843 N0 = !SrcOps.empty() ? SrcOps[0] : SDValue();
52844 N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
52845 ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
52847 if (UseSubVector && SrcOps.size() == 1 &&
52848 scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
52849 std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
52850 ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
52851 ShuffleMask.assign(Mask.begin(), Mask.end());
52856 // View LHS in the form
52857 // LHS = VECTOR_SHUFFLE A, B, LMask
52858 // If LHS is not a shuffle, then pretend it is the identity shuffle:
52859 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
52860 // NOTE: A default initialized SDValue represents an UNDEF of type VT.
52861 SDValue A, B;
52862 SmallVector<int, 16> LMask;
52863 GetShuffle(LHS, A, B, LMask);
52865 // Likewise, view RHS in the form
52866 // RHS = VECTOR_SHUFFLE C, D, RMask
52867 SDValue C, D;
52868 SmallVector<int, 16> RMask;
52869 GetShuffle(RHS, C, D, RMask);
52871 // At least one of the operands should be a vector shuffle.
52872 unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
52873 if (NumShuffles == 0)
52874 return false;
52876 if (LMask.empty()) {
52877 A = LHS;
52878 for (unsigned i = 0; i != NumElts; ++i)
52879 LMask.push_back(i);
52882 if (RMask.empty()) {
52883 C = RHS;
52884 for (unsigned i = 0; i != NumElts; ++i)
52885 RMask.push_back(i);
52888 // If we have an unary mask, ensure the other op is set to null.
52889 if (isUndefOrInRange(LMask, 0, NumElts))
52890 B = SDValue();
52891 else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
52892 A = SDValue();
52894 if (isUndefOrInRange(RMask, 0, NumElts))
52895 D = SDValue();
52896 else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
52897 C = SDValue();
52899 // If A and B occur in reverse order in RHS, then canonicalize by commuting
52900 // RHS operands and shuffle mask.
52901 if (A != C) {
52902 std::swap(C, D);
52903 ShuffleVectorSDNode::commuteMask(RMask);
52905 // Check that the shuffles are both shuffling the same vectors.
52906 if (!(A == C && B == D))
52907 return false;
52909 PostShuffleMask.clear();
52910 PostShuffleMask.append(NumElts, SM_SentinelUndef);
52912 // LHS and RHS are now:
52913 // LHS = shuffle A, B, LMask
52914 // RHS = shuffle A, B, RMask
52915 // Check that the masks correspond to performing a horizontal operation.
52916 // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
52917 // so we just repeat the inner loop if this is a 256-bit op.
52918 unsigned Num128BitChunks = VT.getSizeInBits() / 128;
52919 unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
52920 unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
52921 assert((NumEltsPer128BitChunk % 2 == 0) &&
52922 "Vector type should have an even number of elements in each lane");
52923 for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
52924 for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
52925 // Ignore undefined components.
52926 int LIdx = LMask[i + j], RIdx = RMask[i + j];
52927 if (LIdx < 0 || RIdx < 0 ||
52928 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
52929 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
52930 continue;
52932 // Check that successive odd/even elements are being operated on. If not,
52933 // this is not a horizontal operation.
52934 if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
52935 !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
52936 return false;
52938 // Compute the post-shuffle mask index based on where the element
52939 // is stored in the HOP result, and where it needs to be moved to.
52940 int Base = LIdx & ~1u;
52941 int Index = ((Base % NumEltsPer128BitChunk) / 2) +
52942 ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
52944 // The low half of the 128-bit result must choose from A.
52945 // The high half of the 128-bit result must choose from B,
52946 // unless B is undef. In that case, we are always choosing from A.
52947 if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
52948 Index += NumEltsPer64BitChunk;
52949 PostShuffleMask[i + j] = Index;
52953 SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
52954 SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
52956 bool IsIdentityPostShuffle =
52957 isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
52958 if (IsIdentityPostShuffle)
52959 PostShuffleMask.clear();
52961 // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
52962 if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
52963 isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
52964 return false;
52966 // If the source nodes are already used in HorizOps then always accept this.
52967 // Shuffle folding should merge these back together.
52968 auto FoundHorizUser = [&](SDNode *User) {
52969 return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
52971 ForceHorizOp =
52972 ForceHorizOp || (llvm::any_of(NewLHS->uses(), FoundHorizUser) &&
52973 llvm::any_of(NewRHS->uses(), FoundHorizUser));
52975 // Assume a SingleSource HOP if we only shuffle one input and don't need to
52976 // shuffle the result.
52977 if (!ForceHorizOp &&
52978 !shouldUseHorizontalOp(NewLHS == NewRHS &&
52979 (NumShuffles < 2 || !IsIdentityPostShuffle),
52980 DAG, Subtarget))
52981 return false;
52983 LHS = DAG.getBitcast(VT, NewLHS);
52984 RHS = DAG.getBitcast(VT, NewRHS);
52985 return true;
52988 // Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
52989 static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
52990 const X86Subtarget &Subtarget) {
52991 EVT VT = N->getValueType(0);
52992 unsigned Opcode = N->getOpcode();
52993 bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
52994 SmallVector<int, 8> PostShuffleMask;
52996 auto MergableHorizOp = [N](unsigned HorizOpcode) {
52997 return N->hasOneUse() &&
52998 N->use_begin()->getOpcode() == ISD::VECTOR_SHUFFLE &&
52999 (N->use_begin()->getOperand(0).getOpcode() == HorizOpcode ||
53000 N->use_begin()->getOperand(1).getOpcode() == HorizOpcode);
53003 switch (Opcode) {
53004 case ISD::FADD:
53005 case ISD::FSUB:
53006 if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
53007 (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
53008 SDValue LHS = N->getOperand(0);
53009 SDValue RHS = N->getOperand(1);
53010 auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
53011 if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
53012 PostShuffleMask, MergableHorizOp(HorizOpcode))) {
53013 SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
53014 if (!PostShuffleMask.empty())
53015 HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
53016 DAG.getUNDEF(VT), PostShuffleMask);
53017 return HorizBinOp;
53020 break;
53021 case ISD::ADD:
53022 case ISD::SUB:
53023 if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
53024 VT == MVT::v16i16 || VT == MVT::v8i32)) {
53025 SDValue LHS = N->getOperand(0);
53026 SDValue RHS = N->getOperand(1);
53027 auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
53028 if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
53029 PostShuffleMask, MergableHorizOp(HorizOpcode))) {
53030 auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
53031 ArrayRef<SDValue> Ops) {
53032 return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
53034 SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
53035 {LHS, RHS}, HOpBuilder);
53036 if (!PostShuffleMask.empty())
53037 HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
53038 DAG.getUNDEF(VT), PostShuffleMask);
53039 return HorizBinOp;
53042 break;
53045 return SDValue();
53048 // Try to combine the following nodes
53049 // t29: i64 = X86ISD::Wrapper TargetConstantPool:i64
53050 // <i32 -2147483648[float -0.000000e+00]> 0
53051 // t27: v16i32[v16f32],ch = X86ISD::VBROADCAST_LOAD
53052 // <(load 4 from constant-pool)> t0, t29
53053 // [t30: v16i32 = bitcast t27]
53054 // t6: v16i32 = xor t7, t27[t30]
53055 // t11: v16f32 = bitcast t6
53056 // t21: v16f32 = X86ISD::VFMULC[X86ISD::VCFMULC] t11, t8
53057 // into X86ISD::VFCMULC[X86ISD::VFMULC] if possible:
53058 // t22: v16f32 = bitcast t7
53059 // t23: v16f32 = X86ISD::VFCMULC[X86ISD::VFMULC] t8, t22
53060 // t24: v32f16 = bitcast t23
53061 static SDValue combineFMulcFCMulc(SDNode *N, SelectionDAG &DAG,
53062 const X86Subtarget &Subtarget) {
53063 EVT VT = N->getValueType(0);
53064 SDValue LHS = N->getOperand(0);
53065 SDValue RHS = N->getOperand(1);
53066 int CombineOpcode =
53067 N->getOpcode() == X86ISD::VFCMULC ? X86ISD::VFMULC : X86ISD::VFCMULC;
53068 auto combineConjugation = [&](SDValue &r) {
53069 if (LHS->getOpcode() == ISD::BITCAST && RHS.hasOneUse()) {
53070 SDValue XOR = LHS.getOperand(0);
53071 if (XOR->getOpcode() == ISD::XOR && XOR.hasOneUse()) {
53072 KnownBits XORRHS = DAG.computeKnownBits(XOR.getOperand(1));
53073 if (XORRHS.isConstant()) {
53074 APInt ConjugationInt32 = APInt(32, 0x80000000);
53075 APInt ConjugationInt64 = APInt(64, 0x8000000080000000ULL);
53076 if ((XORRHS.getBitWidth() == 32 &&
53077 XORRHS.getConstant() == ConjugationInt32) ||
53078 (XORRHS.getBitWidth() == 64 &&
53079 XORRHS.getConstant() == ConjugationInt64)) {
53080 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
53081 SDValue I2F = DAG.getBitcast(VT, LHS.getOperand(0).getOperand(0));
53082 SDValue FCMulC = DAG.getNode(CombineOpcode, SDLoc(N), VT, RHS, I2F);
53083 r = DAG.getBitcast(VT, FCMulC);
53084 return true;
53089 return false;
53091 SDValue Res;
53092 if (combineConjugation(Res))
53093 return Res;
53094 std::swap(LHS, RHS);
53095 if (combineConjugation(Res))
53096 return Res;
53097 return Res;
53100 // Try to combine the following nodes:
53101 // FADD(A, FMA(B, C, 0)) and FADD(A, FMUL(B, C)) to FMA(B, C, A)
53102 static SDValue combineFaddCFmul(SDNode *N, SelectionDAG &DAG,
53103 const X86Subtarget &Subtarget) {
53104 auto AllowContract = [&DAG](const SDNodeFlags &Flags) {
53105 return DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
53106 Flags.hasAllowContract();
53109 auto HasNoSignedZero = [&DAG](const SDNodeFlags &Flags) {
53110 return DAG.getTarget().Options.NoSignedZerosFPMath ||
53111 Flags.hasNoSignedZeros();
53113 auto IsVectorAllNegativeZero = [&DAG](SDValue Op) {
53114 APInt AI = APInt(32, 0x80008000);
53115 KnownBits Bits = DAG.computeKnownBits(Op);
53116 return Bits.getBitWidth() == 32 && Bits.isConstant() &&
53117 Bits.getConstant() == AI;
53120 if (N->getOpcode() != ISD::FADD || !Subtarget.hasFP16() ||
53121 !AllowContract(N->getFlags()))
53122 return SDValue();
53124 EVT VT = N->getValueType(0);
53125 if (VT != MVT::v8f16 && VT != MVT::v16f16 && VT != MVT::v32f16)
53126 return SDValue();
53128 SDValue LHS = N->getOperand(0);
53129 SDValue RHS = N->getOperand(1);
53130 bool IsConj;
53131 SDValue FAddOp1, MulOp0, MulOp1;
53132 auto GetCFmulFrom = [&MulOp0, &MulOp1, &IsConj, &AllowContract,
53133 &IsVectorAllNegativeZero,
53134 &HasNoSignedZero](SDValue N) -> bool {
53135 if (!N.hasOneUse() || N.getOpcode() != ISD::BITCAST)
53136 return false;
53137 SDValue Op0 = N.getOperand(0);
53138 unsigned Opcode = Op0.getOpcode();
53139 if (Op0.hasOneUse() && AllowContract(Op0->getFlags())) {
53140 if ((Opcode == X86ISD::VFMULC || Opcode == X86ISD::VFCMULC)) {
53141 MulOp0 = Op0.getOperand(0);
53142 MulOp1 = Op0.getOperand(1);
53143 IsConj = Opcode == X86ISD::VFCMULC;
53144 return true;
53146 if ((Opcode == X86ISD::VFMADDC || Opcode == X86ISD::VFCMADDC) &&
53147 ((ISD::isBuildVectorAllZeros(Op0->getOperand(2).getNode()) &&
53148 HasNoSignedZero(Op0->getFlags())) ||
53149 IsVectorAllNegativeZero(Op0->getOperand(2)))) {
53150 MulOp0 = Op0.getOperand(0);
53151 MulOp1 = Op0.getOperand(1);
53152 IsConj = Opcode == X86ISD::VFCMADDC;
53153 return true;
53156 return false;
53159 if (GetCFmulFrom(LHS))
53160 FAddOp1 = RHS;
53161 else if (GetCFmulFrom(RHS))
53162 FAddOp1 = LHS;
53163 else
53164 return SDValue();
53166 MVT CVT = MVT::getVectorVT(MVT::f32, VT.getVectorNumElements() / 2);
53167 FAddOp1 = DAG.getBitcast(CVT, FAddOp1);
53168 unsigned NewOp = IsConj ? X86ISD::VFCMADDC : X86ISD::VFMADDC;
53169 // FIXME: How do we handle when fast math flags of FADD are different from
53170 // CFMUL's?
53171 SDValue CFmul =
53172 DAG.getNode(NewOp, SDLoc(N), CVT, MulOp0, MulOp1, FAddOp1, N->getFlags());
53173 return DAG.getBitcast(VT, CFmul);
53176 /// Do target-specific dag combines on floating-point adds/subs.
53177 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
53178 const X86Subtarget &Subtarget) {
53179 if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
53180 return HOp;
53182 if (SDValue COp = combineFaddCFmul(N, DAG, Subtarget))
53183 return COp;
53185 return SDValue();
53188 static SDValue combineLRINT_LLRINT(SDNode *N, SelectionDAG &DAG,
53189 const X86Subtarget &Subtarget) {
53190 EVT VT = N->getValueType(0);
53191 SDValue Src = N->getOperand(0);
53192 EVT SrcVT = Src.getValueType();
53193 SDLoc DL(N);
53195 if (!Subtarget.hasDQI() || !Subtarget.hasVLX() || VT != MVT::v2i64 ||
53196 SrcVT != MVT::v2f32)
53197 return SDValue();
53199 return DAG.getNode(X86ISD::CVTP2SI, DL, VT,
53200 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, Src,
53201 DAG.getUNDEF(SrcVT)));
53204 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
53205 /// the codegen.
53206 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
53207 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
53208 /// anything that is guaranteed to be transformed by DAGCombiner.
53209 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
53210 const X86Subtarget &Subtarget,
53211 const SDLoc &DL) {
53212 assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
53213 SDValue Src = N->getOperand(0);
53214 unsigned SrcOpcode = Src.getOpcode();
53215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53217 EVT VT = N->getValueType(0);
53218 EVT SrcVT = Src.getValueType();
53220 auto IsFreeTruncation = [VT](SDValue Op) {
53221 unsigned TruncSizeInBits = VT.getScalarSizeInBits();
53223 // See if this has been extended from a smaller/equal size to
53224 // the truncation size, allowing a truncation to combine with the extend.
53225 unsigned Opcode = Op.getOpcode();
53226 if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
53227 Opcode == ISD::ZERO_EXTEND) &&
53228 Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
53229 return true;
53231 // See if this is a single use constant which can be constant folded.
53232 // NOTE: We don't peek throught bitcasts here because there is currently
53233 // no support for constant folding truncate+bitcast+vector_of_constants. So
53234 // we'll just send up with a truncate on both operands which will
53235 // get turned back into (truncate (binop)) causing an infinite loop.
53236 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
53239 auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
53240 SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
53241 SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
53242 return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
53245 // Don't combine if the operation has other uses.
53246 if (!Src.hasOneUse())
53247 return SDValue();
53249 // Only support vector truncation for now.
53250 // TODO: i64 scalar math would benefit as well.
53251 if (!VT.isVector())
53252 return SDValue();
53254 // In most cases its only worth pre-truncating if we're only facing the cost
53255 // of one truncation.
53256 // i.e. if one of the inputs will constant fold or the input is repeated.
53257 switch (SrcOpcode) {
53258 case ISD::MUL:
53259 // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
53260 // better to truncate if we have the chance.
53261 if (SrcVT.getScalarType() == MVT::i64 &&
53262 TLI.isOperationLegal(SrcOpcode, VT) &&
53263 !TLI.isOperationLegal(SrcOpcode, SrcVT))
53264 return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
53265 [[fallthrough]];
53266 case ISD::AND:
53267 case ISD::XOR:
53268 case ISD::OR:
53269 case ISD::ADD:
53270 case ISD::SUB: {
53271 SDValue Op0 = Src.getOperand(0);
53272 SDValue Op1 = Src.getOperand(1);
53273 if (TLI.isOperationLegal(SrcOpcode, VT) &&
53274 (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
53275 return TruncateArithmetic(Op0, Op1);
53276 break;
53280 return SDValue();
53283 // Try to form a MULHU or MULHS node by looking for
53284 // (trunc (srl (mul ext, ext), 16))
53285 // TODO: This is X86 specific because we want to be able to handle wide types
53286 // before type legalization. But we can only do it if the vector will be
53287 // legalized via widening/splitting. Type legalization can't handle promotion
53288 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
53289 // combiner.
53290 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
53291 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
53292 using namespace llvm::SDPatternMatch;
53294 if (!Subtarget.hasSSE2())
53295 return SDValue();
53297 // Only handle vXi16 types that are at least 128-bits unless they will be
53298 // widened.
53299 if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
53300 return SDValue();
53302 // Input type should be at least vXi32.
53303 EVT InVT = Src.getValueType();
53304 if (InVT.getVectorElementType().getSizeInBits() < 32)
53305 return SDValue();
53307 // First instruction should be a right shift by 16 of a multiply.
53308 SDValue LHS, RHS;
53309 if (!sd_match(Src,
53310 m_Srl(m_Mul(m_Value(LHS), m_Value(RHS)), m_SpecificInt(16))))
53311 return SDValue();
53313 // Count leading sign/zero bits on both inputs - if there are enough then
53314 // truncation back to vXi16 will be cheap - either as a pack/shuffle
53315 // sequence or using AVX512 truncations. If the inputs are sext/zext then the
53316 // truncations may actually be free by peeking through to the ext source.
53317 auto IsSext = [&DAG](SDValue V) {
53318 return DAG.ComputeMaxSignificantBits(V) <= 16;
53320 auto IsZext = [&DAG](SDValue V) {
53321 return DAG.computeKnownBits(V).countMaxActiveBits() <= 16;
53324 bool IsSigned = IsSext(LHS) && IsSext(RHS);
53325 bool IsUnsigned = IsZext(LHS) && IsZext(RHS);
53326 if (!IsSigned && !IsUnsigned)
53327 return SDValue();
53329 // Check if both inputs are extensions, which will be removed by truncation.
53330 auto isOpTruncateFree = [](SDValue Op) {
53331 if (Op.getOpcode() == ISD::SIGN_EXTEND ||
53332 Op.getOpcode() == ISD::ZERO_EXTEND)
53333 return Op.getOperand(0).getScalarValueSizeInBits() <= 16;
53334 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
53336 bool IsTruncateFree = isOpTruncateFree(LHS) && isOpTruncateFree(RHS);
53338 // For AVX2+ targets, with the upper bits known zero, we can perform MULHU on
53339 // the (bitcasted) inputs directly, and then cheaply pack/truncate the result
53340 // (upper elts will be zero). Don't attempt this with just AVX512F as MULHU
53341 // will have to split anyway.
53342 unsigned InSizeInBits = InVT.getSizeInBits();
53343 if (IsUnsigned && !IsTruncateFree && Subtarget.hasInt256() &&
53344 !(Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.is256BitVector()) &&
53345 (InSizeInBits % 16) == 0) {
53346 EVT BCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53347 InVT.getSizeInBits() / 16);
53348 SDValue Res = DAG.getNode(ISD::MULHU, DL, BCVT, DAG.getBitcast(BCVT, LHS),
53349 DAG.getBitcast(BCVT, RHS));
53350 return DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getBitcast(InVT, Res));
53353 // Truncate back to source type.
53354 LHS = DAG.getNode(ISD::TRUNCATE, DL, VT, LHS);
53355 RHS = DAG.getNode(ISD::TRUNCATE, DL, VT, RHS);
53357 unsigned Opc = IsSigned ? ISD::MULHS : ISD::MULHU;
53358 return DAG.getNode(Opc, DL, VT, LHS, RHS);
53361 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
53362 // from one vector with signed bytes from another vector, adds together
53363 // adjacent pairs of 16-bit products, and saturates the result before
53364 // truncating to 16-bits.
53366 // Which looks something like this:
53367 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
53368 // (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
53369 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
53370 const X86Subtarget &Subtarget,
53371 const SDLoc &DL) {
53372 if (!VT.isVector() || !Subtarget.hasSSSE3())
53373 return SDValue();
53375 unsigned NumElems = VT.getVectorNumElements();
53376 EVT ScalarVT = VT.getVectorElementType();
53377 if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
53378 return SDValue();
53380 SDValue SSatVal = detectSSatPattern(In, VT);
53381 if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
53382 return SDValue();
53384 // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
53385 // of multiplies from even/odd elements.
53386 SDValue N0 = SSatVal.getOperand(0);
53387 SDValue N1 = SSatVal.getOperand(1);
53389 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
53390 return SDValue();
53392 SDValue N00 = N0.getOperand(0);
53393 SDValue N01 = N0.getOperand(1);
53394 SDValue N10 = N1.getOperand(0);
53395 SDValue N11 = N1.getOperand(1);
53397 // TODO: Handle constant vectors and use knownbits/computenumsignbits?
53398 // Canonicalize zero_extend to LHS.
53399 if (N01.getOpcode() == ISD::ZERO_EXTEND)
53400 std::swap(N00, N01);
53401 if (N11.getOpcode() == ISD::ZERO_EXTEND)
53402 std::swap(N10, N11);
53404 // Ensure we have a zero_extend and a sign_extend.
53405 if (N00.getOpcode() != ISD::ZERO_EXTEND ||
53406 N01.getOpcode() != ISD::SIGN_EXTEND ||
53407 N10.getOpcode() != ISD::ZERO_EXTEND ||
53408 N11.getOpcode() != ISD::SIGN_EXTEND)
53409 return SDValue();
53411 // Peek through the extends.
53412 N00 = N00.getOperand(0);
53413 N01 = N01.getOperand(0);
53414 N10 = N10.getOperand(0);
53415 N11 = N11.getOperand(0);
53417 // Ensure the extend is from vXi8.
53418 if (N00.getValueType().getVectorElementType() != MVT::i8 ||
53419 N01.getValueType().getVectorElementType() != MVT::i8 ||
53420 N10.getValueType().getVectorElementType() != MVT::i8 ||
53421 N11.getValueType().getVectorElementType() != MVT::i8)
53422 return SDValue();
53424 // All inputs should be build_vectors.
53425 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
53426 N01.getOpcode() != ISD::BUILD_VECTOR ||
53427 N10.getOpcode() != ISD::BUILD_VECTOR ||
53428 N11.getOpcode() != ISD::BUILD_VECTOR)
53429 return SDValue();
53431 // N00/N10 are zero extended. N01/N11 are sign extended.
53433 // For each element, we need to ensure we have an odd element from one vector
53434 // multiplied by the odd element of another vector and the even element from
53435 // one of the same vectors being multiplied by the even element from the
53436 // other vector. So we need to make sure for each element i, this operator
53437 // is being performed:
53438 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
53439 SDValue ZExtIn, SExtIn;
53440 for (unsigned i = 0; i != NumElems; ++i) {
53441 SDValue N00Elt = N00.getOperand(i);
53442 SDValue N01Elt = N01.getOperand(i);
53443 SDValue N10Elt = N10.getOperand(i);
53444 SDValue N11Elt = N11.getOperand(i);
53445 // TODO: Be more tolerant to undefs.
53446 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53447 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53448 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53449 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
53450 return SDValue();
53451 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
53452 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
53453 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
53454 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
53455 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
53456 return SDValue();
53457 unsigned IdxN00 = ConstN00Elt->getZExtValue();
53458 unsigned IdxN01 = ConstN01Elt->getZExtValue();
53459 unsigned IdxN10 = ConstN10Elt->getZExtValue();
53460 unsigned IdxN11 = ConstN11Elt->getZExtValue();
53461 // Add is commutative so indices can be reordered.
53462 if (IdxN00 > IdxN10) {
53463 std::swap(IdxN00, IdxN10);
53464 std::swap(IdxN01, IdxN11);
53466 // N0 indices be the even element. N1 indices must be the next odd element.
53467 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
53468 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
53469 return SDValue();
53470 SDValue N00In = N00Elt.getOperand(0);
53471 SDValue N01In = N01Elt.getOperand(0);
53472 SDValue N10In = N10Elt.getOperand(0);
53473 SDValue N11In = N11Elt.getOperand(0);
53474 // First time we find an input capture it.
53475 if (!ZExtIn) {
53476 ZExtIn = N00In;
53477 SExtIn = N01In;
53479 if (ZExtIn != N00In || SExtIn != N01In ||
53480 ZExtIn != N10In || SExtIn != N11In)
53481 return SDValue();
53484 auto ExtractVec = [&DAG, &DL, NumElems](SDValue &Ext) {
53485 EVT ExtVT = Ext.getValueType();
53486 if (ExtVT.getVectorNumElements() != NumElems * 2) {
53487 MVT NVT = MVT::getVectorVT(MVT::i8, NumElems * 2);
53488 Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT, Ext,
53489 DAG.getIntPtrConstant(0, DL));
53492 ExtractVec(ZExtIn);
53493 ExtractVec(SExtIn);
53495 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
53496 ArrayRef<SDValue> Ops) {
53497 // Shrink by adding truncate nodes and let DAGCombine fold with the
53498 // sources.
53499 EVT InVT = Ops[0].getValueType();
53500 assert(InVT.getScalarType() == MVT::i8 &&
53501 "Unexpected scalar element type");
53502 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
53503 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
53504 InVT.getVectorNumElements() / 2);
53505 return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
53507 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
53508 PMADDBuilder);
53511 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
53512 const X86Subtarget &Subtarget) {
53513 EVT VT = N->getValueType(0);
53514 SDValue Src = N->getOperand(0);
53515 SDLoc DL(N);
53517 // Attempt to pre-truncate inputs to arithmetic ops instead.
53518 if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
53519 return V;
53521 // Try to detect PMADD
53522 if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
53523 return PMAdd;
53525 // Try to combine truncation with signed/unsigned saturation.
53526 if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
53527 return Val;
53529 // Try to combine PMULHUW/PMULHW for vXi16.
53530 if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
53531 return V;
53533 // The bitcast source is a direct mmx result.
53534 // Detect bitcasts between i32 to x86mmx
53535 if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
53536 SDValue BCSrc = Src.getOperand(0);
53537 if (BCSrc.getValueType() == MVT::x86mmx)
53538 return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
53541 // Try to combine (trunc (vNi64 (lrint x))) to (vNi32 (lrint x)).
53542 if (Src.getOpcode() == ISD::LRINT && VT.getScalarType() == MVT::i32 &&
53543 Src.hasOneUse())
53544 return DAG.getNode(ISD::LRINT, DL, VT, Src.getOperand(0));
53546 return SDValue();
53549 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
53550 TargetLowering::DAGCombinerInfo &DCI) {
53551 EVT VT = N->getValueType(0);
53552 SDValue In = N->getOperand(0);
53553 SDLoc DL(N);
53555 if (SDValue SSatVal = detectSSatPattern(In, VT))
53556 return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
53557 if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL))
53558 return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
53560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53561 APInt DemandedMask(APInt::getAllOnes(VT.getScalarSizeInBits()));
53562 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
53563 return SDValue(N, 0);
53565 return SDValue();
53568 /// Returns the negated value if the node \p N flips sign of FP value.
53570 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
53571 /// or FSUB(0, x)
53572 /// AVX512F does not have FXOR, so FNEG is lowered as
53573 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
53574 /// In this case we go though all bitcasts.
53575 /// This also recognizes splat of a negated value and returns the splat of that
53576 /// value.
53577 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
53578 if (N->getOpcode() == ISD::FNEG)
53579 return N->getOperand(0);
53581 // Don't recurse exponentially.
53582 if (Depth > SelectionDAG::MaxRecursionDepth)
53583 return SDValue();
53585 unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
53587 SDValue Op = peekThroughBitcasts(SDValue(N, 0));
53588 EVT VT = Op->getValueType(0);
53590 // Make sure the element size doesn't change.
53591 if (VT.getScalarSizeInBits() != ScalarSize)
53592 return SDValue();
53594 unsigned Opc = Op.getOpcode();
53595 switch (Opc) {
53596 case ISD::VECTOR_SHUFFLE: {
53597 // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
53598 // of this is VECTOR_SHUFFLE(-VEC1, UNDEF). The mask can be anything here.
53599 if (!Op.getOperand(1).isUndef())
53600 return SDValue();
53601 if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
53602 if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
53603 return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
53604 cast<ShuffleVectorSDNode>(Op)->getMask());
53605 break;
53607 case ISD::INSERT_VECTOR_ELT: {
53608 // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
53609 // -V, INDEX).
53610 SDValue InsVector = Op.getOperand(0);
53611 SDValue InsVal = Op.getOperand(1);
53612 if (!InsVector.isUndef())
53613 return SDValue();
53614 if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
53615 if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
53616 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
53617 NegInsVal, Op.getOperand(2));
53618 break;
53620 case ISD::FSUB:
53621 case ISD::XOR:
53622 case X86ISD::FXOR: {
53623 SDValue Op1 = Op.getOperand(1);
53624 SDValue Op0 = Op.getOperand(0);
53626 // For XOR and FXOR, we want to check if constant
53627 // bits of Op1 are sign bit masks. For FSUB, we
53628 // have to check if constant bits of Op0 are sign
53629 // bit masks and hence we swap the operands.
53630 if (Opc == ISD::FSUB)
53631 std::swap(Op0, Op1);
53633 APInt UndefElts;
53634 SmallVector<APInt, 16> EltBits;
53635 // Extract constant bits and see if they are all
53636 // sign bit masks. Ignore the undef elements.
53637 if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
53638 /* AllowWholeUndefs */ true,
53639 /* AllowPartialUndefs */ false)) {
53640 for (unsigned I = 0, E = EltBits.size(); I < E; I++)
53641 if (!UndefElts[I] && !EltBits[I].isSignMask())
53642 return SDValue();
53644 // Only allow bitcast from correctly-sized constant.
53645 Op0 = peekThroughBitcasts(Op0);
53646 if (Op0.getScalarValueSizeInBits() == ScalarSize)
53647 return Op0;
53649 break;
53650 } // case
53651 } // switch
53653 return SDValue();
53656 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
53657 bool NegRes) {
53658 if (NegMul) {
53659 switch (Opcode) {
53660 // clang-format off
53661 default: llvm_unreachable("Unexpected opcode");
53662 case ISD::FMA: Opcode = X86ISD::FNMADD; break;
53663 case ISD::STRICT_FMA: Opcode = X86ISD::STRICT_FNMADD; break;
53664 case X86ISD::FMADD_RND: Opcode = X86ISD::FNMADD_RND; break;
53665 case X86ISD::FMSUB: Opcode = X86ISD::FNMSUB; break;
53666 case X86ISD::STRICT_FMSUB: Opcode = X86ISD::STRICT_FNMSUB; break;
53667 case X86ISD::FMSUB_RND: Opcode = X86ISD::FNMSUB_RND; break;
53668 case X86ISD::FNMADD: Opcode = ISD::FMA; break;
53669 case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA; break;
53670 case X86ISD::FNMADD_RND: Opcode = X86ISD::FMADD_RND; break;
53671 case X86ISD::FNMSUB: Opcode = X86ISD::FMSUB; break;
53672 case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB; break;
53673 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FMSUB_RND; break;
53674 // clang-format on
53678 if (NegAcc) {
53679 switch (Opcode) {
53680 // clang-format off
53681 default: llvm_unreachable("Unexpected opcode");
53682 case ISD::FMA: Opcode = X86ISD::FMSUB; break;
53683 case ISD::STRICT_FMA: Opcode = X86ISD::STRICT_FMSUB; break;
53684 case X86ISD::FMADD_RND: Opcode = X86ISD::FMSUB_RND; break;
53685 case X86ISD::FMSUB: Opcode = ISD::FMA; break;
53686 case X86ISD::STRICT_FMSUB: Opcode = ISD::STRICT_FMA; break;
53687 case X86ISD::FMSUB_RND: Opcode = X86ISD::FMADD_RND; break;
53688 case X86ISD::FNMADD: Opcode = X86ISD::FNMSUB; break;
53689 case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
53690 case X86ISD::FNMADD_RND: Opcode = X86ISD::FNMSUB_RND; break;
53691 case X86ISD::FNMSUB: Opcode = X86ISD::FNMADD; break;
53692 case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
53693 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FNMADD_RND; break;
53694 case X86ISD::FMADDSUB: Opcode = X86ISD::FMSUBADD; break;
53695 case X86ISD::FMADDSUB_RND: Opcode = X86ISD::FMSUBADD_RND; break;
53696 case X86ISD::FMSUBADD: Opcode = X86ISD::FMADDSUB; break;
53697 case X86ISD::FMSUBADD_RND: Opcode = X86ISD::FMADDSUB_RND; break;
53698 // clang-format on
53702 if (NegRes) {
53703 switch (Opcode) {
53704 // For accuracy reason, we never combine fneg and fma under strict FP.
53705 // clang-format off
53706 default: llvm_unreachable("Unexpected opcode");
53707 case ISD::FMA: Opcode = X86ISD::FNMSUB; break;
53708 case X86ISD::FMADD_RND: Opcode = X86ISD::FNMSUB_RND; break;
53709 case X86ISD::FMSUB: Opcode = X86ISD::FNMADD; break;
53710 case X86ISD::FMSUB_RND: Opcode = X86ISD::FNMADD_RND; break;
53711 case X86ISD::FNMADD: Opcode = X86ISD::FMSUB; break;
53712 case X86ISD::FNMADD_RND: Opcode = X86ISD::FMSUB_RND; break;
53713 case X86ISD::FNMSUB: Opcode = ISD::FMA; break;
53714 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FMADD_RND; break;
53715 // clang-format on
53719 return Opcode;
53722 /// Do target-specific dag combines on floating point negations.
53723 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
53724 TargetLowering::DAGCombinerInfo &DCI,
53725 const X86Subtarget &Subtarget) {
53726 EVT OrigVT = N->getValueType(0);
53727 SDValue Arg = isFNEG(DAG, N);
53728 if (!Arg)
53729 return SDValue();
53731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53732 EVT VT = Arg.getValueType();
53733 EVT SVT = VT.getScalarType();
53734 SDLoc DL(N);
53736 // Let legalize expand this if it isn't a legal type yet.
53737 if (!TLI.isTypeLegal(VT))
53738 return SDValue();
53740 // If we're negating a FMUL node on a target with FMA, then we can avoid the
53741 // use of a constant by performing (-0 - A*B) instead.
53742 // FIXME: Check rounding control flags as well once it becomes available.
53743 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
53744 Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
53745 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
53746 SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
53747 Arg.getOperand(1), Zero);
53748 return DAG.getBitcast(OrigVT, NewNode);
53751 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
53752 bool LegalOperations = !DCI.isBeforeLegalizeOps();
53753 if (SDValue NegArg =
53754 TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
53755 return DAG.getBitcast(OrigVT, NegArg);
53757 return SDValue();
53760 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
53761 bool LegalOperations,
53762 bool ForCodeSize,
53763 NegatibleCost &Cost,
53764 unsigned Depth) const {
53765 // fneg patterns are removable even if they have multiple uses.
53766 if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
53767 Cost = NegatibleCost::Cheaper;
53768 return DAG.getBitcast(Op.getValueType(), Arg);
53771 EVT VT = Op.getValueType();
53772 EVT SVT = VT.getScalarType();
53773 unsigned Opc = Op.getOpcode();
53774 SDNodeFlags Flags = Op.getNode()->getFlags();
53775 switch (Opc) {
53776 case ISD::FMA:
53777 case X86ISD::FMSUB:
53778 case X86ISD::FNMADD:
53779 case X86ISD::FNMSUB:
53780 case X86ISD::FMADD_RND:
53781 case X86ISD::FMSUB_RND:
53782 case X86ISD::FNMADD_RND:
53783 case X86ISD::FNMSUB_RND: {
53784 if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
53785 !(SVT == MVT::f32 || SVT == MVT::f64) ||
53786 !isOperationLegal(ISD::FMA, VT))
53787 break;
53789 // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
53790 // if it may have signed zeros.
53791 if (!Flags.hasNoSignedZeros())
53792 break;
53794 // This is always negatible for free but we might be able to remove some
53795 // extra operand negations as well.
53796 SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
53797 for (int i = 0; i != 3; ++i)
53798 NewOps[i] = getCheaperNegatedExpression(
53799 Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
53801 bool NegA = !!NewOps[0];
53802 bool NegB = !!NewOps[1];
53803 bool NegC = !!NewOps[2];
53804 unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
53806 Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
53807 : NegatibleCost::Neutral;
53809 // Fill in the non-negated ops with the original values.
53810 for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
53811 if (!NewOps[i])
53812 NewOps[i] = Op.getOperand(i);
53813 return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
53815 case X86ISD::FRCP:
53816 if (SDValue NegOp0 =
53817 getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
53818 ForCodeSize, Cost, Depth + 1))
53819 return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
53820 break;
53823 return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
53824 ForCodeSize, Cost, Depth);
53827 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
53828 const X86Subtarget &Subtarget) {
53829 MVT VT = N->getSimpleValueType(0);
53830 // If we have integer vector types available, use the integer opcodes.
53831 if (!VT.isVector() || !Subtarget.hasSSE2())
53832 return SDValue();
53834 SDLoc dl(N);
53836 unsigned IntBits = VT.getScalarSizeInBits();
53837 MVT IntSVT = MVT::getIntegerVT(IntBits);
53838 MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
53840 SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
53841 SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
53842 unsigned IntOpcode;
53843 switch (N->getOpcode()) {
53844 // clang-format off
53845 default: llvm_unreachable("Unexpected FP logic op");
53846 case X86ISD::FOR: IntOpcode = ISD::OR; break;
53847 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
53848 case X86ISD::FAND: IntOpcode = ISD::AND; break;
53849 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
53850 // clang-format on
53852 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
53853 return DAG.getBitcast(VT, IntOp);
53857 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
53858 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
53859 if (N->getOpcode() != ISD::XOR)
53860 return SDValue();
53862 SDValue LHS = N->getOperand(0);
53863 if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
53864 return SDValue();
53866 X86::CondCode NewCC = X86::GetOppositeBranchCondition(
53867 X86::CondCode(LHS->getConstantOperandVal(0)));
53868 SDLoc DL(N);
53869 return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
53872 static SDValue combineXorSubCTLZ(SDNode *N, const SDLoc &DL, SelectionDAG &DAG,
53873 const X86Subtarget &Subtarget) {
53874 assert((N->getOpcode() == ISD::XOR || N->getOpcode() == ISD::SUB) &&
53875 "Invalid opcode for combing with CTLZ");
53876 if (Subtarget.hasFastLZCNT())
53877 return SDValue();
53879 EVT VT = N->getValueType(0);
53880 if (VT != MVT::i8 && VT != MVT::i16 && VT != MVT::i32 &&
53881 (VT != MVT::i64 || !Subtarget.is64Bit()))
53882 return SDValue();
53884 SDValue N0 = N->getOperand(0);
53885 SDValue N1 = N->getOperand(1);
53887 if (N0.getOpcode() != ISD::CTLZ_ZERO_UNDEF &&
53888 N1.getOpcode() != ISD::CTLZ_ZERO_UNDEF)
53889 return SDValue();
53891 SDValue OpCTLZ;
53892 SDValue OpSizeTM1;
53894 if (N1.getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
53895 OpCTLZ = N1;
53896 OpSizeTM1 = N0;
53897 } else if (N->getOpcode() == ISD::SUB) {
53898 return SDValue();
53899 } else {
53900 OpCTLZ = N0;
53901 OpSizeTM1 = N1;
53904 if (!OpCTLZ.hasOneUse())
53905 return SDValue();
53906 auto *C = dyn_cast<ConstantSDNode>(OpSizeTM1);
53907 if (!C)
53908 return SDValue();
53910 if (C->getZExtValue() != uint64_t(OpCTLZ.getValueSizeInBits() - 1))
53911 return SDValue();
53912 EVT OpVT = VT;
53913 SDValue Op = OpCTLZ.getOperand(0);
53914 if (VT == MVT::i8) {
53915 // Zero extend to i32 since there is not an i8 bsr.
53916 OpVT = MVT::i32;
53917 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, OpVT, Op);
53920 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
53921 Op = DAG.getNode(X86ISD::BSR, DL, VTs, Op);
53922 if (VT == MVT::i8)
53923 Op = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Op);
53925 return Op;
53928 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
53929 TargetLowering::DAGCombinerInfo &DCI,
53930 const X86Subtarget &Subtarget) {
53931 SDValue N0 = N->getOperand(0);
53932 SDValue N1 = N->getOperand(1);
53933 EVT VT = N->getValueType(0);
53934 SDLoc DL(N);
53936 // If this is SSE1 only convert to FXOR to avoid scalarization.
53937 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
53938 return DAG.getBitcast(MVT::v4i32,
53939 DAG.getNode(X86ISD::FXOR, DL, MVT::v4f32,
53940 DAG.getBitcast(MVT::v4f32, N0),
53941 DAG.getBitcast(MVT::v4f32, N1)));
53944 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
53945 return Cmp;
53947 if (SDValue R = combineBitOpWithMOVMSK(N->getOpcode(), DL, N0, N1, DAG))
53948 return R;
53950 if (SDValue R = combineBitOpWithShift(N->getOpcode(), DL, VT, N0, N1, DAG))
53951 return R;
53953 if (SDValue R = combineBitOpWithPACK(N->getOpcode(), DL, VT, N0, N1, DAG))
53954 return R;
53956 if (SDValue FPLogic = convertIntLogicToFPLogic(N->getOpcode(), DL, VT, N0, N1,
53957 DAG, DCI, Subtarget))
53958 return FPLogic;
53960 if (SDValue R = combineXorSubCTLZ(N, DL, DAG, Subtarget))
53961 return R;
53963 if (DCI.isBeforeLegalizeOps())
53964 return SDValue();
53966 if (SDValue SetCC = foldXor1SetCC(N, DAG))
53967 return SetCC;
53969 if (SDValue R = combineOrXorWithSETCC(N->getOpcode(), DL, VT, N0, N1, DAG))
53970 return R;
53972 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
53973 return RV;
53975 // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
53976 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53977 if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
53978 N0.getOperand(0).getValueType().isVector() &&
53979 N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
53980 TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
53981 return DAG.getBitcast(
53982 VT, DAG.getNOT(DL, N0.getOperand(0), N0.getOperand(0).getValueType()));
53985 // Handle AVX512 mask widening.
53986 // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
53987 if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
53988 VT.getVectorElementType() == MVT::i1 &&
53989 N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
53990 TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
53991 return DAG.getNode(
53992 ISD::INSERT_SUBVECTOR, DL, VT, N0.getOperand(0),
53993 DAG.getNOT(DL, N0.getOperand(1), N0.getOperand(1).getValueType()),
53994 N0.getOperand(2));
53997 // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
53998 // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
53999 // TODO: Under what circumstances could this be performed in DAGCombine?
54000 if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
54001 N0.getOperand(0).getOpcode() == N->getOpcode()) {
54002 SDValue TruncExtSrc = N0.getOperand(0);
54003 auto *N1C = dyn_cast<ConstantSDNode>(N1);
54004 auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
54005 if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
54006 SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
54007 SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
54008 return DAG.getNode(ISD::XOR, DL, VT, LHS,
54009 DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
54013 if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
54014 return R;
54016 return combineFneg(N, DAG, DCI, Subtarget);
54019 static SDValue combineBITREVERSE(SDNode *N, SelectionDAG &DAG,
54020 TargetLowering::DAGCombinerInfo &DCI,
54021 const X86Subtarget &Subtarget) {
54022 SDValue N0 = N->getOperand(0);
54023 EVT VT = N->getValueType(0);
54025 // Convert a (iX bitreverse(bitcast(vXi1 X))) -> (iX bitcast(shuffle(X)))
54026 if (VT.isInteger() && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
54027 SDValue Src = N0.getOperand(0);
54028 EVT SrcVT = Src.getValueType();
54029 if (SrcVT.isVector() && SrcVT.getScalarType() == MVT::i1 &&
54030 (DCI.isBeforeLegalize() ||
54031 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)) &&
54032 Subtarget.hasSSSE3()) {
54033 unsigned NumElts = SrcVT.getVectorNumElements();
54034 SmallVector<int, 32> ReverseMask(NumElts);
54035 for (unsigned I = 0; I != NumElts; ++I)
54036 ReverseMask[I] = (NumElts - 1) - I;
54037 SDValue Rev =
54038 DAG.getVectorShuffle(SrcVT, SDLoc(N), Src, Src, ReverseMask);
54039 return DAG.getBitcast(VT, Rev);
54043 return SDValue();
54046 // Various combines to try to convert to avgceilu.
54047 static SDValue combineAVG(SDNode *N, SelectionDAG &DAG,
54048 TargetLowering::DAGCombinerInfo &DCI,
54049 const X86Subtarget &Subtarget) {
54050 unsigned Opcode = N->getOpcode();
54051 SDValue N0 = N->getOperand(0);
54052 SDValue N1 = N->getOperand(1);
54053 EVT VT = N->getValueType(0);
54054 EVT SVT = VT.getScalarType();
54055 SDLoc DL(N);
54057 // avgceils(x,y) -> flipsign(avgceilu(flipsign(x),flipsign(y)))
54058 // Only useful on vXi8 which doesn't have good SRA handling.
54059 if (Opcode == ISD::AVGCEILS && VT.isVector() && SVT == MVT::i8) {
54060 APInt SignBit = APInt::getSignMask(VT.getScalarSizeInBits());
54061 SDValue SignMask = DAG.getConstant(SignBit, DL, VT);
54062 N0 = DAG.getNode(ISD::XOR, DL, VT, N0, SignMask);
54063 N1 = DAG.getNode(ISD::XOR, DL, VT, N1, SignMask);
54064 return DAG.getNode(ISD::XOR, DL, VT,
54065 DAG.getNode(ISD::AVGCEILU, DL, VT, N0, N1), SignMask);
54068 return SDValue();
54071 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
54072 TargetLowering::DAGCombinerInfo &DCI,
54073 const X86Subtarget &Subtarget) {
54074 EVT VT = N->getValueType(0);
54075 unsigned NumBits = VT.getSizeInBits();
54077 // TODO - Constant Folding.
54079 // Simplify the inputs.
54080 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54081 APInt DemandedMask(APInt::getAllOnes(NumBits));
54082 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
54083 return SDValue(N, 0);
54085 return SDValue();
54088 static bool isNullFPScalarOrVectorConst(SDValue V) {
54089 return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
54092 /// If a value is a scalar FP zero or a vector FP zero (potentially including
54093 /// undefined elements), return a zero constant that may be used to fold away
54094 /// that value. In the case of a vector, the returned constant will not contain
54095 /// undefined elements even if the input parameter does. This makes it suitable
54096 /// to be used as a replacement operand with operations (eg, bitwise-and) where
54097 /// an undef should not propagate.
54098 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
54099 const X86Subtarget &Subtarget) {
54100 if (!isNullFPScalarOrVectorConst(V))
54101 return SDValue();
54103 if (V.getValueType().isVector())
54104 return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
54106 return V;
54109 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
54110 const X86Subtarget &Subtarget) {
54111 SDValue N0 = N->getOperand(0);
54112 SDValue N1 = N->getOperand(1);
54113 EVT VT = N->getValueType(0);
54114 SDLoc DL(N);
54116 // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
54117 if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
54118 (VT == MVT::f64 && Subtarget.hasSSE2()) ||
54119 (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
54120 return SDValue();
54122 auto isAllOnesConstantFP = [](SDValue V) {
54123 if (V.getSimpleValueType().isVector())
54124 return ISD::isBuildVectorAllOnes(V.getNode());
54125 auto *C = dyn_cast<ConstantFPSDNode>(V);
54126 return C && C->getConstantFPValue()->isAllOnesValue();
54129 // fand (fxor X, -1), Y --> fandn X, Y
54130 if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
54131 return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
54133 // fand X, (fxor Y, -1) --> fandn Y, X
54134 if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
54135 return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
54137 return SDValue();
54140 /// Do target-specific dag combines on X86ISD::FAND nodes.
54141 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
54142 const X86Subtarget &Subtarget) {
54143 // FAND(0.0, x) -> 0.0
54144 if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
54145 return V;
54147 // FAND(x, 0.0) -> 0.0
54148 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
54149 return V;
54151 if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
54152 return V;
54154 return lowerX86FPLogicOp(N, DAG, Subtarget);
54157 /// Do target-specific dag combines on X86ISD::FANDN nodes.
54158 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
54159 const X86Subtarget &Subtarget) {
54160 // FANDN(0.0, x) -> x
54161 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
54162 return N->getOperand(1);
54164 // FANDN(x, 0.0) -> 0.0
54165 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
54166 return V;
54168 return lowerX86FPLogicOp(N, DAG, Subtarget);
54171 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
54172 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
54173 TargetLowering::DAGCombinerInfo &DCI,
54174 const X86Subtarget &Subtarget) {
54175 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
54177 // F[X]OR(0.0, x) -> x
54178 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
54179 return N->getOperand(1);
54181 // F[X]OR(x, 0.0) -> x
54182 if (isNullFPScalarOrVectorConst(N->getOperand(1)))
54183 return N->getOperand(0);
54185 if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
54186 return NewVal;
54188 return lowerX86FPLogicOp(N, DAG, Subtarget);
54191 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
54192 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
54193 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
54195 // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
54196 if (!DAG.getTarget().Options.NoNaNsFPMath ||
54197 !DAG.getTarget().Options.NoSignedZerosFPMath)
54198 return SDValue();
54200 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
54201 // into FMINC and FMAXC, which are Commutative operations.
54202 unsigned NewOp = 0;
54203 switch (N->getOpcode()) {
54204 default: llvm_unreachable("unknown opcode");
54205 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
54206 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
54209 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
54210 N->getOperand(0), N->getOperand(1));
54213 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
54214 const X86Subtarget &Subtarget) {
54215 EVT VT = N->getValueType(0);
54216 if (Subtarget.useSoftFloat() || isSoftF16(VT, Subtarget))
54217 return SDValue();
54219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54221 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
54222 (Subtarget.hasSSE2() && VT == MVT::f64) ||
54223 (Subtarget.hasFP16() && VT == MVT::f16) ||
54224 (VT.isVector() && TLI.isTypeLegal(VT))))
54225 return SDValue();
54227 SDValue Op0 = N->getOperand(0);
54228 SDValue Op1 = N->getOperand(1);
54229 SDLoc DL(N);
54230 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
54232 // If we don't have to respect NaN inputs, this is a direct translation to x86
54233 // min/max instructions.
54234 if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
54235 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
54237 // If one of the operands is known non-NaN use the native min/max instructions
54238 // with the non-NaN input as second operand.
54239 if (DAG.isKnownNeverNaN(Op1))
54240 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
54241 if (DAG.isKnownNeverNaN(Op0))
54242 return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
54244 // If we have to respect NaN inputs, this takes at least 3 instructions.
54245 // Favor a library call when operating on a scalar and minimizing code size.
54246 if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
54247 return SDValue();
54249 EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
54250 VT);
54252 // There are 4 possibilities involving NaN inputs, and these are the required
54253 // outputs:
54254 // Op1
54255 // Num NaN
54256 // ----------------
54257 // Num | Max | Op0 |
54258 // Op0 ----------------
54259 // NaN | Op1 | NaN |
54260 // ----------------
54262 // The SSE FP max/min instructions were not designed for this case, but rather
54263 // to implement:
54264 // Min = Op1 < Op0 ? Op1 : Op0
54265 // Max = Op1 > Op0 ? Op1 : Op0
54267 // So they always return Op0 if either input is a NaN. However, we can still
54268 // use those instructions for fmaxnum by selecting away a NaN input.
54270 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
54271 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
54272 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
54274 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
54275 // are NaN, the NaN value of Op1 is the result.
54276 return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
54279 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
54280 TargetLowering::DAGCombinerInfo &DCI) {
54281 EVT VT = N->getValueType(0);
54282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54284 APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
54285 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
54286 return SDValue(N, 0);
54288 // Convert a full vector load into vzload when not all bits are needed.
54289 SDValue In = N->getOperand(0);
54290 MVT InVT = In.getSimpleValueType();
54291 if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
54292 ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
54293 assert(InVT.is128BitVector() && "Expected 128-bit input vector");
54294 LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
54295 unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
54296 MVT MemVT = MVT::getIntegerVT(NumBits);
54297 MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
54298 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
54299 SDLoc dl(N);
54300 SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
54301 DAG.getBitcast(InVT, VZLoad));
54302 DCI.CombineTo(N, Convert);
54303 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54304 DCI.recursivelyDeleteUnusedNodes(LN);
54305 return SDValue(N, 0);
54309 return SDValue();
54312 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
54313 TargetLowering::DAGCombinerInfo &DCI) {
54314 bool IsStrict = N->isTargetStrictFPOpcode();
54315 EVT VT = N->getValueType(0);
54317 // Convert a full vector load into vzload when not all bits are needed.
54318 SDValue In = N->getOperand(IsStrict ? 1 : 0);
54319 MVT InVT = In.getSimpleValueType();
54320 if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
54321 ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
54322 assert(InVT.is128BitVector() && "Expected 128-bit input vector");
54323 LoadSDNode *LN = cast<LoadSDNode>(In);
54324 unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
54325 MVT MemVT = MVT::getFloatingPointVT(NumBits);
54326 MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
54327 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
54328 SDLoc dl(N);
54329 if (IsStrict) {
54330 SDValue Convert =
54331 DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
54332 {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
54333 DCI.CombineTo(N, Convert, Convert.getValue(1));
54334 } else {
54335 SDValue Convert =
54336 DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
54337 DCI.CombineTo(N, Convert);
54339 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54340 DCI.recursivelyDeleteUnusedNodes(LN);
54341 return SDValue(N, 0);
54345 return SDValue();
54348 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
54349 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
54350 TargetLowering::DAGCombinerInfo &DCI,
54351 const X86Subtarget &Subtarget) {
54352 SDValue N0 = N->getOperand(0);
54353 SDValue N1 = N->getOperand(1);
54354 MVT VT = N->getSimpleValueType(0);
54355 int NumElts = VT.getVectorNumElements();
54356 unsigned EltSizeInBits = VT.getScalarSizeInBits();
54357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54358 SDLoc DL(N);
54360 // ANDNP(undef, x) -> 0
54361 // ANDNP(x, undef) -> 0
54362 if (N0.isUndef() || N1.isUndef())
54363 return DAG.getConstant(0, DL, VT);
54365 // ANDNP(0, x) -> x
54366 if (ISD::isBuildVectorAllZeros(N0.getNode()))
54367 return N1;
54369 // ANDNP(x, 0) -> 0
54370 if (ISD::isBuildVectorAllZeros(N1.getNode()))
54371 return DAG.getConstant(0, DL, VT);
54373 // ANDNP(x, -1) -> NOT(x) -> XOR(x, -1)
54374 if (ISD::isBuildVectorAllOnes(N1.getNode()))
54375 return DAG.getNOT(DL, N0, VT);
54377 // Turn ANDNP back to AND if input is inverted.
54378 if (SDValue Not = IsNOT(N0, DAG))
54379 return DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, Not), N1);
54381 // On AVX512 targets, attempt to reverse foldVSelectToSignBitSplatMask.
54382 // to make use of predicated selects.
54383 // ANDN(SEXT(SETCC()),X) -> SELECT(NOT(SETCC()),X,0)
54384 if (DCI.isAfterLegalizeDAG() && N0.getOpcode() == ISD::SIGN_EXTEND) {
54385 SDValue Src = N0.getOperand(0);
54386 EVT SrcVT = Src.getValueType();
54387 if (Src.getOpcode() == ISD::SETCC && SrcVT.getScalarType() == MVT::i1 &&
54388 TLI.isTypeLegal(SrcVT) && N0.hasOneUse() && Src.hasOneUse())
54389 return DAG.getSelect(DL, VT, DAG.getNOT(DL, Src, SrcVT), N1,
54390 getZeroVector(VT, Subtarget, DAG, DL));
54393 // Constant Folding
54394 APInt Undefs0, Undefs1;
54395 SmallVector<APInt> EltBits0, EltBits1;
54396 if (getTargetConstantBitsFromNode(N0, EltSizeInBits, Undefs0, EltBits0,
54397 /*AllowWholeUndefs*/ true,
54398 /*AllowPartialUndefs*/ true)) {
54399 if (getTargetConstantBitsFromNode(N1, EltSizeInBits, Undefs1, EltBits1,
54400 /*AllowWholeUndefs*/ true,
54401 /*AllowPartialUndefs*/ true)) {
54402 SmallVector<APInt> ResultBits;
54403 for (int I = 0; I != NumElts; ++I)
54404 ResultBits.push_back(~EltBits0[I] & EltBits1[I]);
54405 return getConstVector(ResultBits, VT, DAG, DL);
54408 // Constant fold NOT(N0) to allow us to use AND.
54409 // Ensure this is only performed if we can confirm that the bitcasted source
54410 // has oneuse to prevent an infinite loop with canonicalizeBitSelect.
54411 if (N0->hasOneUse()) {
54412 SDValue BC0 = peekThroughOneUseBitcasts(N0);
54413 if (BC0.getOpcode() != ISD::BITCAST) {
54414 for (APInt &Elt : EltBits0)
54415 Elt = ~Elt;
54416 SDValue Not = getConstVector(EltBits0, VT, DAG, DL);
54417 return DAG.getNode(ISD::AND, DL, VT, Not, N1);
54422 // Attempt to recursively combine a bitmask ANDNP with shuffles.
54423 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
54424 SDValue Op(N, 0);
54425 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
54426 return Res;
54428 // If either operand is a constant mask, then only the elements that aren't
54429 // zero are actually demanded by the other operand.
54430 auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
54431 APInt UndefElts;
54432 SmallVector<APInt> EltBits;
54433 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
54434 APInt DemandedElts = APInt::getAllOnes(NumElts);
54435 if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
54436 EltBits)) {
54437 DemandedBits.clearAllBits();
54438 DemandedElts.clearAllBits();
54439 for (int I = 0; I != NumElts; ++I) {
54440 if (UndefElts[I]) {
54441 // We can't assume an undef src element gives an undef dst - the
54442 // other src might be zero.
54443 DemandedBits.setAllBits();
54444 DemandedElts.setBit(I);
54445 } else if ((Invert && !EltBits[I].isAllOnes()) ||
54446 (!Invert && !EltBits[I].isZero())) {
54447 DemandedBits |= Invert ? ~EltBits[I] : EltBits[I];
54448 DemandedElts.setBit(I);
54452 return std::make_pair(DemandedBits, DemandedElts);
54454 APInt Bits0, Elts0;
54455 APInt Bits1, Elts1;
54456 std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
54457 std::tie(Bits1, Elts1) = GetDemandedMasks(N0, true);
54459 if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
54460 TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
54461 TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
54462 TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
54463 if (N->getOpcode() != ISD::DELETED_NODE)
54464 DCI.AddToWorklist(N);
54465 return SDValue(N, 0);
54469 // Folds for better commutativity:
54470 if (N1->hasOneUse()) {
54471 // ANDNP(x,NOT(y)) -> AND(NOT(x),NOT(y)) -> NOT(OR(X,Y)).
54472 if (SDValue Not = IsNOT(N1, DAG))
54473 return DAG.getNOT(
54474 DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)), VT);
54476 // ANDNP(x,PSHUFB(y,z)) -> PSHUFB(y,OR(z,x))
54477 // Zero out elements by setting the PSHUFB mask value to 0xFF.
54478 if (DAG.ComputeNumSignBits(N0) == EltSizeInBits) {
54479 SDValue BC1 = peekThroughOneUseBitcasts(N1);
54480 if (BC1.getOpcode() == X86ISD::PSHUFB) {
54481 EVT ShufVT = BC1.getValueType();
54482 SDValue NewMask = DAG.getNode(ISD::OR, DL, ShufVT, BC1.getOperand(1),
54483 DAG.getBitcast(ShufVT, N0));
54484 SDValue NewShuf =
54485 DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, BC1.getOperand(0), NewMask);
54486 return DAG.getBitcast(VT, NewShuf);
54491 return SDValue();
54494 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
54495 TargetLowering::DAGCombinerInfo &DCI) {
54496 SDValue N1 = N->getOperand(1);
54498 // BT ignores high bits in the bit index operand.
54499 unsigned BitWidth = N1.getValueSizeInBits();
54500 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
54501 if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
54502 if (N->getOpcode() != ISD::DELETED_NODE)
54503 DCI.AddToWorklist(N);
54504 return SDValue(N, 0);
54507 return SDValue();
54510 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
54511 TargetLowering::DAGCombinerInfo &DCI) {
54512 bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
54513 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
54515 if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
54516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54517 APInt DemandedElts = APInt::getLowBitsSet(8, 4);
54518 if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, DCI)) {
54519 if (N->getOpcode() != ISD::DELETED_NODE)
54520 DCI.AddToWorklist(N);
54521 return SDValue(N, 0);
54524 // Convert a full vector load into vzload when not all bits are needed.
54525 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
54526 LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
54527 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
54528 SDLoc dl(N);
54529 if (IsStrict) {
54530 SDValue Convert = DAG.getNode(
54531 N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
54532 {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
54533 DCI.CombineTo(N, Convert, Convert.getValue(1));
54534 } else {
54535 SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
54536 DAG.getBitcast(MVT::v8i16, VZLoad));
54537 DCI.CombineTo(N, Convert);
54540 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
54541 DCI.recursivelyDeleteUnusedNodes(LN);
54542 return SDValue(N, 0);
54547 return SDValue();
54550 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
54551 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
54552 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
54554 EVT DstVT = N->getValueType(0);
54556 SDValue N0 = N->getOperand(0);
54557 SDValue N1 = N->getOperand(1);
54558 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
54560 if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
54561 return SDValue();
54563 // Look through single use any_extends / truncs.
54564 SDValue IntermediateBitwidthOp;
54565 if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
54566 N0.hasOneUse()) {
54567 IntermediateBitwidthOp = N0;
54568 N0 = N0.getOperand(0);
54571 // See if we have a single use cmov.
54572 if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
54573 return SDValue();
54575 SDValue CMovOp0 = N0.getOperand(0);
54576 SDValue CMovOp1 = N0.getOperand(1);
54578 // Make sure both operands are constants.
54579 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
54580 !isa<ConstantSDNode>(CMovOp1.getNode()))
54581 return SDValue();
54583 SDLoc DL(N);
54585 // If we looked through an any_extend/trunc above, add one to the constants.
54586 if (IntermediateBitwidthOp) {
54587 unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
54588 CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
54589 CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
54592 CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
54593 CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
54595 EVT CMovVT = DstVT;
54596 // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
54597 if (DstVT == MVT::i16) {
54598 CMovVT = MVT::i32;
54599 CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
54600 CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
54603 SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
54604 N0.getOperand(2), N0.getOperand(3));
54606 if (CMovVT != DstVT)
54607 CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
54609 return CMov;
54612 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
54613 const X86Subtarget &Subtarget) {
54614 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
54616 if (SDValue V = combineSextInRegCmov(N, DAG))
54617 return V;
54619 EVT VT = N->getValueType(0);
54620 SDValue N0 = N->getOperand(0);
54621 SDValue N1 = N->getOperand(1);
54622 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
54623 SDLoc dl(N);
54625 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
54626 // both SSE and AVX2 since there is no sign-extended shift right
54627 // operation on a vector with 64-bit elements.
54628 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
54629 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
54630 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
54631 N0.getOpcode() == ISD::SIGN_EXTEND)) {
54632 SDValue N00 = N0.getOperand(0);
54634 // EXTLOAD has a better solution on AVX2,
54635 // it may be replaced with X86ISD::VSEXT node.
54636 if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
54637 if (!ISD::isNormalLoad(N00.getNode()))
54638 return SDValue();
54640 // Attempt to promote any comparison mask ops before moving the
54641 // SIGN_EXTEND_INREG in the way.
54642 if (SDValue Promote = PromoteMaskArithmetic(N0, dl, DAG, Subtarget))
54643 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
54645 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
54646 SDValue Tmp =
54647 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
54648 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
54651 return SDValue();
54654 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
54655 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
54656 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
54657 /// opportunities to combine math ops, use an LEA, or use a complex addressing
54658 /// mode. This can eliminate extend, add, and shift instructions.
54659 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
54660 const X86Subtarget &Subtarget) {
54661 if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
54662 Ext->getOpcode() != ISD::ZERO_EXTEND)
54663 return SDValue();
54665 // TODO: This should be valid for other integer types.
54666 EVT VT = Ext->getValueType(0);
54667 if (VT != MVT::i64)
54668 return SDValue();
54670 SDValue Add = Ext->getOperand(0);
54671 if (Add.getOpcode() != ISD::ADD)
54672 return SDValue();
54674 SDValue AddOp0 = Add.getOperand(0);
54675 SDValue AddOp1 = Add.getOperand(1);
54676 bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
54677 bool NSW = Add->getFlags().hasNoSignedWrap();
54678 bool NUW = Add->getFlags().hasNoUnsignedWrap();
54679 NSW = NSW || (Sext && DAG.willNotOverflowAdd(true, AddOp0, AddOp1));
54680 NUW = NUW || (!Sext && DAG.willNotOverflowAdd(false, AddOp0, AddOp1));
54682 // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
54683 // into the 'zext'
54684 if ((Sext && !NSW) || (!Sext && !NUW))
54685 return SDValue();
54687 // Having a constant operand to the 'add' ensures that we are not increasing
54688 // the instruction count because the constant is extended for free below.
54689 // A constant operand can also become the displacement field of an LEA.
54690 auto *AddOp1C = dyn_cast<ConstantSDNode>(AddOp1);
54691 if (!AddOp1C)
54692 return SDValue();
54694 // Don't make the 'add' bigger if there's no hope of combining it with some
54695 // other 'add' or 'shl' instruction.
54696 // TODO: It may be profitable to generate simpler LEA instructions in place
54697 // of single 'add' instructions, but the cost model for selecting an LEA
54698 // currently has a high threshold.
54699 bool HasLEAPotential = false;
54700 for (auto *User : Ext->uses()) {
54701 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
54702 HasLEAPotential = true;
54703 break;
54706 if (!HasLEAPotential)
54707 return SDValue();
54709 // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
54710 int64_t AddC = Sext ? AddOp1C->getSExtValue() : AddOp1C->getZExtValue();
54711 SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
54712 SDValue NewConstant = DAG.getConstant(AddC, SDLoc(Add), VT);
54714 // The wider add is guaranteed to not wrap because both operands are
54715 // sign-extended.
54716 SDNodeFlags Flags;
54717 Flags.setNoSignedWrap(NSW);
54718 Flags.setNoUnsignedWrap(NUW);
54719 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
54722 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
54723 // operands and the result of CMOV is not used anywhere else - promote CMOV
54724 // itself instead of promoting its result. This could be beneficial, because:
54725 // 1) X86TargetLowering::EmitLoweredSelect later can do merging of two
54726 // (or more) pseudo-CMOVs only when they go one-after-another and
54727 // getting rid of result extension code after CMOV will help that.
54728 // 2) Promotion of constant CMOV arguments is free, hence the
54729 // {ANY,SIGN,ZERO}_EXTEND will just be deleted.
54730 // 3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
54731 // promotion is also good in terms of code-size.
54732 // (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
54733 // promotion).
54734 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
54735 SDValue CMovN = Extend->getOperand(0);
54736 if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
54737 return SDValue();
54739 EVT TargetVT = Extend->getValueType(0);
54740 unsigned ExtendOpcode = Extend->getOpcode();
54741 SDLoc DL(Extend);
54743 EVT VT = CMovN.getValueType();
54744 SDValue CMovOp0 = CMovN.getOperand(0);
54745 SDValue CMovOp1 = CMovN.getOperand(1);
54747 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
54748 !isa<ConstantSDNode>(CMovOp1.getNode()))
54749 return SDValue();
54751 // Only extend to i32 or i64.
54752 if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
54753 return SDValue();
54755 // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
54756 // are free.
54757 if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
54758 return SDValue();
54760 // If this a zero extend to i64, we should only extend to i32 and use a free
54761 // zero extend to finish.
54762 EVT ExtendVT = TargetVT;
54763 if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
54764 ExtendVT = MVT::i32;
54766 CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
54767 CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
54769 SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
54770 CMovN.getOperand(2), CMovN.getOperand(3));
54772 // Finish extending if needed.
54773 if (ExtendVT != TargetVT)
54774 Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
54776 return Res;
54779 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
54780 // result type.
54781 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
54782 const X86Subtarget &Subtarget) {
54783 SDValue N0 = N->getOperand(0);
54784 EVT VT = N->getValueType(0);
54785 SDLoc dl(N);
54787 // Only do this combine with AVX512 for vector extends.
54788 if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
54789 return SDValue();
54791 // Only combine legal element types.
54792 EVT SVT = VT.getVectorElementType();
54793 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
54794 SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
54795 return SDValue();
54797 // We don't have CMPP Instruction for vxf16
54798 if (N0.getOperand(0).getValueType().getVectorElementType() == MVT::f16)
54799 return SDValue();
54800 // We can only do this if the vector size in 256 bits or less.
54801 unsigned Size = VT.getSizeInBits();
54802 if (Size > 256 && Subtarget.useAVX512Regs())
54803 return SDValue();
54805 // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
54806 // that's the only integer compares with we have.
54807 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
54808 if (ISD::isUnsignedIntSetCC(CC))
54809 return SDValue();
54811 // Only do this combine if the extension will be fully consumed by the setcc.
54812 EVT N00VT = N0.getOperand(0).getValueType();
54813 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
54814 if (Size != MatchingVecType.getSizeInBits())
54815 return SDValue();
54817 SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
54819 if (N->getOpcode() == ISD::ZERO_EXTEND)
54820 Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
54822 return Res;
54825 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
54826 TargetLowering::DAGCombinerInfo &DCI,
54827 const X86Subtarget &Subtarget) {
54828 SDValue N0 = N->getOperand(0);
54829 EVT VT = N->getValueType(0);
54830 SDLoc DL(N);
54832 // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
54833 if (!DCI.isBeforeLegalizeOps() &&
54834 N0.getOpcode() == X86ISD::SETCC_CARRY) {
54835 SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
54836 N0->getOperand(1));
54837 bool ReplaceOtherUses = !N0.hasOneUse();
54838 DCI.CombineTo(N, Setcc);
54839 // Replace other uses with a truncate of the widened setcc_carry.
54840 if (ReplaceOtherUses) {
54841 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
54842 N0.getValueType(), Setcc);
54843 DCI.CombineTo(N0.getNode(), Trunc);
54846 return SDValue(N, 0);
54849 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
54850 return NewCMov;
54852 if (!DCI.isBeforeLegalizeOps())
54853 return SDValue();
54855 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
54856 return V;
54858 if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), DL, VT, N0,
54859 DAG, DCI, Subtarget))
54860 return V;
54862 if (VT.isVector()) {
54863 if (SDValue R = PromoteMaskArithmetic(SDValue(N, 0), DL, DAG, Subtarget))
54864 return R;
54866 if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
54867 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
54870 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
54871 return NewAdd;
54873 return SDValue();
54876 // Inverting a constant vector is profitable if it can be eliminated and the
54877 // inverted vector is already present in DAG. Otherwise, it will be loaded
54878 // anyway.
54880 // We determine which of the values can be completely eliminated and invert it.
54881 // If both are eliminable, select a vector with the first negative element.
54882 static SDValue getInvertedVectorForFMA(SDValue V, SelectionDAG &DAG) {
54883 assert(ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()) &&
54884 "ConstantFP build vector expected");
54885 // Check if we can eliminate V. We assume if a value is only used in FMAs, we
54886 // can eliminate it. Since this function is invoked for each FMA with this
54887 // vector.
54888 auto IsNotFMA = [](SDNode *Use) {
54889 return Use->getOpcode() != ISD::FMA && Use->getOpcode() != ISD::STRICT_FMA;
54891 if (llvm::any_of(V->uses(), IsNotFMA))
54892 return SDValue();
54894 SmallVector<SDValue, 8> Ops;
54895 EVT VT = V.getValueType();
54896 EVT EltVT = VT.getVectorElementType();
54897 for (const SDValue &Op : V->op_values()) {
54898 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
54899 Ops.push_back(DAG.getConstantFP(-Cst->getValueAPF(), SDLoc(Op), EltVT));
54900 } else {
54901 assert(Op.isUndef());
54902 Ops.push_back(DAG.getUNDEF(EltVT));
54906 SDNode *NV = DAG.getNodeIfExists(ISD::BUILD_VECTOR, DAG.getVTList(VT), Ops);
54907 if (!NV)
54908 return SDValue();
54910 // If an inverted version cannot be eliminated, choose it instead of the
54911 // original version.
54912 if (llvm::any_of(NV->uses(), IsNotFMA))
54913 return SDValue(NV, 0);
54915 // If the inverted version also can be eliminated, we have to consistently
54916 // prefer one of the values. We prefer a constant with a negative value on
54917 // the first place.
54918 // N.B. We need to skip undefs that may precede a value.
54919 for (const SDValue &Op : V->op_values()) {
54920 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
54921 if (Cst->isNegative())
54922 return SDValue();
54923 break;
54926 return SDValue(NV, 0);
54929 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
54930 TargetLowering::DAGCombinerInfo &DCI,
54931 const X86Subtarget &Subtarget) {
54932 SDLoc dl(N);
54933 EVT VT = N->getValueType(0);
54934 bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
54936 // Let legalize expand this if it isn't a legal type yet.
54937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54938 if (!TLI.isTypeLegal(VT))
54939 return SDValue();
54941 SDValue A = N->getOperand(IsStrict ? 1 : 0);
54942 SDValue B = N->getOperand(IsStrict ? 2 : 1);
54943 SDValue C = N->getOperand(IsStrict ? 3 : 2);
54945 // If the operation allows fast-math and the target does not support FMA,
54946 // split this into mul+add to avoid libcall(s).
54947 SDNodeFlags Flags = N->getFlags();
54948 if (!IsStrict && Flags.hasAllowReassociation() &&
54949 TLI.isOperationExpand(ISD::FMA, VT)) {
54950 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
54951 return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
54954 EVT ScalarVT = VT.getScalarType();
54955 if (((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
54956 !Subtarget.hasAnyFMA()) &&
54957 !(ScalarVT == MVT::f16 && Subtarget.hasFP16()) &&
54958 !(ScalarVT == MVT::bf16 && Subtarget.hasAVX10_2()))
54959 return SDValue();
54961 auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
54962 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
54963 bool LegalOperations = !DCI.isBeforeLegalizeOps();
54964 if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
54965 CodeSize)) {
54966 V = NegV;
54967 return true;
54969 // Look through extract_vector_elts. If it comes from an FNEG, create a
54970 // new extract from the FNEG input.
54971 if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
54972 isNullConstant(V.getOperand(1))) {
54973 SDValue Vec = V.getOperand(0);
54974 if (SDValue NegV = TLI.getCheaperNegatedExpression(
54975 Vec, DAG, LegalOperations, CodeSize)) {
54976 V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
54977 NegV, V.getOperand(1));
54978 return true;
54981 // Lookup if there is an inverted version of constant vector V in DAG.
54982 if (ISD::isBuildVectorOfConstantFPSDNodes(V.getNode())) {
54983 if (SDValue NegV = getInvertedVectorForFMA(V, DAG)) {
54984 V = NegV;
54985 return true;
54988 return false;
54991 // Do not convert the passthru input of scalar intrinsics.
54992 // FIXME: We could allow negations of the lower element only.
54993 bool NegA = invertIfNegative(A);
54994 bool NegB = invertIfNegative(B);
54995 bool NegC = invertIfNegative(C);
54997 if (!NegA && !NegB && !NegC)
54998 return SDValue();
55000 unsigned NewOpcode =
55001 negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
55003 // Propagate fast-math-flags to new FMA node.
55004 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
55005 if (IsStrict) {
55006 assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
55007 return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
55008 {N->getOperand(0), A, B, C});
55009 } else {
55010 if (N->getNumOperands() == 4)
55011 return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
55012 return DAG.getNode(NewOpcode, dl, VT, A, B, C);
55016 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
55017 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
55018 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
55019 TargetLowering::DAGCombinerInfo &DCI) {
55020 SDLoc dl(N);
55021 EVT VT = N->getValueType(0);
55022 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55023 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
55024 bool LegalOperations = !DCI.isBeforeLegalizeOps();
55026 SDValue N2 = N->getOperand(2);
55028 SDValue NegN2 =
55029 TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
55030 if (!NegN2)
55031 return SDValue();
55032 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
55034 if (N->getNumOperands() == 4)
55035 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
55036 NegN2, N->getOperand(3));
55037 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
55038 NegN2);
55041 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
55042 TargetLowering::DAGCombinerInfo &DCI,
55043 const X86Subtarget &Subtarget) {
55044 SDLoc dl(N);
55045 SDValue N0 = N->getOperand(0);
55046 EVT VT = N->getValueType(0);
55048 // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
55049 // FIXME: Is this needed? We don't seem to have any tests for it.
55050 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
55051 N0.getOpcode() == X86ISD::SETCC_CARRY) {
55052 SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
55053 N0->getOperand(1));
55054 bool ReplaceOtherUses = !N0.hasOneUse();
55055 DCI.CombineTo(N, Setcc);
55056 // Replace other uses with a truncate of the widened setcc_carry.
55057 if (ReplaceOtherUses) {
55058 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
55059 N0.getValueType(), Setcc);
55060 DCI.CombineTo(N0.getNode(), Trunc);
55063 return SDValue(N, 0);
55066 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
55067 return NewCMov;
55069 if (DCI.isBeforeLegalizeOps())
55070 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
55071 return V;
55073 if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), dl, VT, N0,
55074 DAG, DCI, Subtarget))
55075 return V;
55077 if (VT.isVector())
55078 if (SDValue R = PromoteMaskArithmetic(SDValue(N, 0), dl, DAG, Subtarget))
55079 return R;
55081 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
55082 return NewAdd;
55084 if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
55085 return R;
55087 // TODO: Combine with any target/faux shuffle.
55088 if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
55089 VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
55090 SDValue N00 = N0.getOperand(0);
55091 SDValue N01 = N0.getOperand(1);
55092 unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
55093 APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
55094 if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
55095 (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
55096 return concatSubVectors(N00, N01, DAG, dl);
55100 return SDValue();
55103 /// If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
55104 /// pre-promote its result type since vXi1 vectors don't get promoted
55105 /// during type legalization.
55106 static SDValue truncateAVX512SetCCNoBWI(EVT VT, EVT OpVT, SDValue LHS,
55107 SDValue RHS, ISD::CondCode CC,
55108 const SDLoc &DL, SelectionDAG &DAG,
55109 const X86Subtarget &Subtarget) {
55110 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
55111 VT.getVectorElementType() == MVT::i1 &&
55112 (OpVT.getVectorElementType() == MVT::i8 ||
55113 OpVT.getVectorElementType() == MVT::i16)) {
55114 SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
55115 return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
55117 return SDValue();
55120 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
55121 TargetLowering::DAGCombinerInfo &DCI,
55122 const X86Subtarget &Subtarget) {
55123 const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
55124 const SDValue LHS = N->getOperand(0);
55125 const SDValue RHS = N->getOperand(1);
55126 EVT VT = N->getValueType(0);
55127 EVT OpVT = LHS.getValueType();
55128 SDLoc DL(N);
55130 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
55131 if (SDValue V = combineVectorSizedSetCCEquality(VT, LHS, RHS, CC, DL, DAG,
55132 Subtarget))
55133 return V;
55135 if (VT == MVT::i1) {
55136 X86::CondCode X86CC;
55137 if (SDValue V =
55138 MatchVectorAllEqualTest(LHS, RHS, CC, DL, Subtarget, DAG, X86CC))
55139 return DAG.getNode(ISD::TRUNCATE, DL, VT, getSETCC(X86CC, V, DL, DAG));
55142 if (OpVT.isScalarInteger()) {
55143 // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
55144 // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
55145 auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
55146 if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
55147 if (N0.getOperand(0) == N1)
55148 return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
55149 N0.getOperand(1));
55150 if (N0.getOperand(1) == N1)
55151 return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
55152 N0.getOperand(0));
55154 return SDValue();
55156 if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
55157 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55158 if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
55159 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55161 // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
55162 // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
55163 auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
55164 if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
55165 if (N0.getOperand(0) == N1)
55166 return DAG.getNode(ISD::AND, DL, OpVT, N1,
55167 DAG.getNOT(DL, N0.getOperand(1), OpVT));
55168 if (N0.getOperand(1) == N1)
55169 return DAG.getNode(ISD::AND, DL, OpVT, N1,
55170 DAG.getNOT(DL, N0.getOperand(0), OpVT));
55172 return SDValue();
55174 if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
55175 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55176 if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
55177 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
55179 // cmpeq(trunc(x),C) --> cmpeq(x,C)
55180 // cmpne(trunc(x),C) --> cmpne(x,C)
55181 // iff x upper bits are zero.
55182 if (LHS.getOpcode() == ISD::TRUNCATE &&
55183 LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
55184 isa<ConstantSDNode>(RHS) && !DCI.isBeforeLegalize()) {
55185 EVT SrcVT = LHS.getOperand(0).getValueType();
55186 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
55187 OpVT.getScalarSizeInBits());
55188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55189 if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
55190 TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
55191 return DAG.getSetCC(DL, VT, LHS.getOperand(0),
55192 DAG.getZExtOrTrunc(RHS, DL, SrcVT), CC);
55195 // With C as a power of 2 and C != 0 and C != INT_MIN:
55196 // icmp eq Abs(X) C ->
55197 // (icmp eq A, C) | (icmp eq A, -C)
55198 // icmp ne Abs(X) C ->
55199 // (icmp ne A, C) & (icmp ne A, -C)
55200 // Both of these patterns can be better optimized in
55201 // DAGCombiner::foldAndOrOfSETCC. Note this only applies for scalar
55202 // integers which is checked above.
55203 if (LHS.getOpcode() == ISD::ABS && LHS.hasOneUse()) {
55204 if (auto *C = dyn_cast<ConstantSDNode>(RHS)) {
55205 const APInt &CInt = C->getAPIntValue();
55206 // We can better optimize this case in DAGCombiner::foldAndOrOfSETCC.
55207 if (CInt.isPowerOf2() && !CInt.isMinSignedValue()) {
55208 SDValue BaseOp = LHS.getOperand(0);
55209 SDValue SETCC0 = DAG.getSetCC(DL, VT, BaseOp, RHS, CC);
55210 SDValue SETCC1 = DAG.getSetCC(
55211 DL, VT, BaseOp, DAG.getConstant(-CInt, DL, OpVT), CC);
55212 return DAG.getNode(CC == ISD::SETEQ ? ISD::OR : ISD::AND, DL, VT,
55213 SETCC0, SETCC1);
55220 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
55221 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
55222 // Using temporaries to avoid messing up operand ordering for later
55223 // transformations if this doesn't work.
55224 SDValue Op0 = LHS;
55225 SDValue Op1 = RHS;
55226 ISD::CondCode TmpCC = CC;
55227 // Put build_vector on the right.
55228 if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
55229 std::swap(Op0, Op1);
55230 TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
55233 bool IsSEXT0 =
55234 (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
55235 (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
55236 bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
55238 if (IsSEXT0 && IsVZero1) {
55239 assert(VT == Op0.getOperand(0).getValueType() &&
55240 "Unexpected operand type");
55241 if (TmpCC == ISD::SETGT)
55242 return DAG.getConstant(0, DL, VT);
55243 if (TmpCC == ISD::SETLE)
55244 return DAG.getConstant(1, DL, VT);
55245 if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
55246 return DAG.getNOT(DL, Op0.getOperand(0), VT);
55248 assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
55249 "Unexpected condition code!");
55250 return Op0.getOperand(0);
55254 // Try and make unsigned vector comparison signed. On pre AVX512 targets there
55255 // only are unsigned comparisons (`PCMPGT`) and on AVX512 its often better to
55256 // use `PCMPGT` if the result is mean to stay in a vector (and if its going to
55257 // a mask, there are signed AVX512 comparisons).
55258 if (VT.isVector() && OpVT.isVector() && OpVT.isInteger()) {
55259 bool CanMakeSigned = false;
55260 if (ISD::isUnsignedIntSetCC(CC)) {
55261 KnownBits CmpKnown =
55262 DAG.computeKnownBits(LHS).intersectWith(DAG.computeKnownBits(RHS));
55263 // If we know LHS/RHS share the same sign bit at each element we can
55264 // make this signed.
55265 // NOTE: `computeKnownBits` on a vector type aggregates common bits
55266 // across all lanes. So a pattern where the sign varies from lane to
55267 // lane, but at each lane Sign(LHS) is known to equal Sign(RHS), will be
55268 // missed. We could get around this by demanding each lane
55269 // independently, but this isn't the most important optimization and
55270 // that may eat into compile time.
55271 CanMakeSigned =
55272 CmpKnown.Zero.isSignBitSet() || CmpKnown.One.isSignBitSet();
55274 if (CanMakeSigned || ISD::isSignedIntSetCC(CC)) {
55275 SDValue LHSOut = LHS;
55276 SDValue RHSOut = RHS;
55277 ISD::CondCode NewCC = CC;
55278 switch (CC) {
55279 case ISD::SETGE:
55280 case ISD::SETUGE:
55281 if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ true,
55282 /*NSW*/ true))
55283 LHSOut = NewLHS;
55284 else if (SDValue NewRHS = incDecVectorConstant(
55285 RHS, DAG, /*IsInc*/ false, /*NSW*/ true))
55286 RHSOut = NewRHS;
55287 else
55288 break;
55290 [[fallthrough]];
55291 case ISD::SETUGT:
55292 NewCC = ISD::SETGT;
55293 break;
55295 case ISD::SETLE:
55296 case ISD::SETULE:
55297 if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ false,
55298 /*NSW*/ true))
55299 LHSOut = NewLHS;
55300 else if (SDValue NewRHS = incDecVectorConstant(RHS, DAG, /*IsInc*/ true,
55301 /*NSW*/ true))
55302 RHSOut = NewRHS;
55303 else
55304 break;
55306 [[fallthrough]];
55307 case ISD::SETULT:
55308 // Will be swapped to SETGT in LowerVSETCC*.
55309 NewCC = ISD::SETLT;
55310 break;
55311 default:
55312 break;
55314 if (NewCC != CC) {
55315 if (SDValue R = truncateAVX512SetCCNoBWI(VT, OpVT, LHSOut, RHSOut,
55316 NewCC, DL, DAG, Subtarget))
55317 return R;
55318 return DAG.getSetCC(DL, VT, LHSOut, RHSOut, NewCC);
55323 if (SDValue R =
55324 truncateAVX512SetCCNoBWI(VT, OpVT, LHS, RHS, CC, DL, DAG, Subtarget))
55325 return R;
55327 // In the middle end transforms:
55328 // `(or (icmp eq X, C), (icmp eq X, C+1))`
55329 // -> `(icmp ult (add x, -C), 2)`
55330 // Likewise inverted cases with `ugt`.
55332 // Since x86, pre avx512, doesn't have unsigned vector compares, this results
55333 // in worse codegen. So, undo the middle-end transform and go back to `(or
55334 // (icmp eq), (icmp eq))` form.
55335 // Also skip AVX1 with ymm vectors, as the umin approach combines better than
55336 // the xmm approach.
55338 // NB: We don't handle the similiar simplication of `(and (icmp ne), (icmp
55339 // ne))` as it doesn't end up instruction positive.
55340 // TODO: We might want to do this for avx512 as well if we `sext` the result.
55341 if (VT.isVector() && OpVT.isVector() && OpVT.isInteger() &&
55342 ISD::isUnsignedIntSetCC(CC) && LHS.getOpcode() == ISD::ADD &&
55343 !Subtarget.hasAVX512() &&
55344 (OpVT.getSizeInBits() <= 128 || !Subtarget.hasAVX() ||
55345 Subtarget.hasAVX2()) &&
55346 LHS.hasOneUse()) {
55348 APInt CmpC;
55349 SDValue AddC = LHS.getOperand(1);
55350 if (ISD::isConstantSplatVector(RHS.getNode(), CmpC) &&
55351 DAG.isConstantIntBuildVectorOrConstantInt(AddC)) {
55352 // See which form we have depending on the constant/condition.
55353 SDValue C0 = SDValue();
55354 SDValue C1 = SDValue();
55356 // If we had `(add x, -1)` and can lower with `umin`, don't transform as
55357 // we will end up generating an additional constant. Keeping in the
55358 // current form has a slight latency cost, but it probably worth saving a
55359 // constant.
55360 if (ISD::isConstantSplatVectorAllOnes(AddC.getNode()) &&
55361 DAG.getTargetLoweringInfo().isOperationLegal(ISD::UMIN, OpVT)) {
55362 // Pass
55364 // Normal Cases
55365 else if ((CC == ISD::SETULT && CmpC == 2) ||
55366 (CC == ISD::SETULE && CmpC == 1)) {
55367 // These will constant fold.
55368 C0 = DAG.getNegative(AddC, DL, OpVT);
55369 C1 = DAG.getNode(ISD::SUB, DL, OpVT, C0,
55370 DAG.getAllOnesConstant(DL, OpVT));
55372 // Inverted Cases
55373 else if ((CC == ISD::SETUGT && (-CmpC) == 3) ||
55374 (CC == ISD::SETUGE && (-CmpC) == 2)) {
55375 // These will constant fold.
55376 C0 = DAG.getNOT(DL, AddC, OpVT);
55377 C1 = DAG.getNode(ISD::ADD, DL, OpVT, C0,
55378 DAG.getAllOnesConstant(DL, OpVT));
55380 if (C0 && C1) {
55381 SDValue NewLHS =
55382 DAG.getSetCC(DL, VT, LHS.getOperand(0), C0, ISD::SETEQ);
55383 SDValue NewRHS =
55384 DAG.getSetCC(DL, VT, LHS.getOperand(0), C1, ISD::SETEQ);
55385 return DAG.getNode(ISD::OR, DL, VT, NewLHS, NewRHS);
55390 // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
55391 // to avoid scalarization via legalization because v4i32 is not a legal type.
55392 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
55393 LHS.getValueType() == MVT::v4f32)
55394 return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
55396 // X pred 0.0 --> X pred -X
55397 // If the negation of X already exists, use it in the comparison. This removes
55398 // the need to materialize 0.0 and allows matching to SSE's MIN/MAX
55399 // instructions in patterns with a 'select' node.
55400 if (isNullFPScalarOrVectorConst(RHS)) {
55401 SDVTList FNegVT = DAG.getVTList(OpVT);
55402 if (SDNode *FNeg = DAG.getNodeIfExists(ISD::FNEG, FNegVT, {LHS}))
55403 return DAG.getSetCC(DL, VT, LHS, SDValue(FNeg, 0), CC);
55406 return SDValue();
55409 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
55410 TargetLowering::DAGCombinerInfo &DCI,
55411 const X86Subtarget &Subtarget) {
55412 SDValue Src = N->getOperand(0);
55413 MVT SrcVT = Src.getSimpleValueType();
55414 MVT VT = N->getSimpleValueType(0);
55415 unsigned NumBits = VT.getScalarSizeInBits();
55416 unsigned NumElts = SrcVT.getVectorNumElements();
55417 unsigned NumBitsPerElt = SrcVT.getScalarSizeInBits();
55418 assert(VT == MVT::i32 && NumElts <= NumBits && "Unexpected MOVMSK types");
55420 // Perform constant folding.
55421 APInt UndefElts;
55422 SmallVector<APInt, 32> EltBits;
55423 if (getTargetConstantBitsFromNode(Src, NumBitsPerElt, UndefElts, EltBits,
55424 /*AllowWholeUndefs*/ true,
55425 /*AllowPartialUndefs*/ true)) {
55426 APInt Imm(32, 0);
55427 for (unsigned Idx = 0; Idx != NumElts; ++Idx)
55428 if (!UndefElts[Idx] && EltBits[Idx].isNegative())
55429 Imm.setBit(Idx);
55431 return DAG.getConstant(Imm, SDLoc(N), VT);
55434 // Look through int->fp bitcasts that don't change the element width.
55435 unsigned EltWidth = SrcVT.getScalarSizeInBits();
55436 if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
55437 Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
55438 return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
55440 // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
55441 // with scalar comparisons.
55442 if (SDValue NotSrc = IsNOT(Src, DAG)) {
55443 SDLoc DL(N);
55444 APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
55445 NotSrc = DAG.getBitcast(SrcVT, NotSrc);
55446 return DAG.getNode(ISD::XOR, DL, VT,
55447 DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
55448 DAG.getConstant(NotMask, DL, VT));
55451 // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
55452 // results with scalar comparisons.
55453 if (Src.getOpcode() == X86ISD::PCMPGT &&
55454 ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
55455 SDLoc DL(N);
55456 APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
55457 return DAG.getNode(ISD::XOR, DL, VT,
55458 DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
55459 DAG.getConstant(NotMask, DL, VT));
55462 // Fold movmsk(icmp_eq(and(x,c1),c1)) -> movmsk(shl(x,c2))
55463 // Fold movmsk(icmp_eq(and(x,c1),0)) -> movmsk(not(shl(x,c2)))
55464 // iff pow2splat(c1).
55465 // Use KnownBits to determine if only a single bit is non-zero
55466 // in each element (pow2 or zero), and shift that bit to the msb.
55467 if (Src.getOpcode() == X86ISD::PCMPEQ) {
55468 KnownBits KnownLHS = DAG.computeKnownBits(Src.getOperand(0));
55469 KnownBits KnownRHS = DAG.computeKnownBits(Src.getOperand(1));
55470 unsigned ShiftAmt = KnownLHS.countMinLeadingZeros();
55471 if (KnownLHS.countMaxPopulation() == 1 &&
55472 (KnownRHS.isZero() || (KnownRHS.countMaxPopulation() == 1 &&
55473 ShiftAmt == KnownRHS.countMinLeadingZeros()))) {
55474 SDLoc DL(N);
55475 MVT ShiftVT = SrcVT;
55476 SDValue ShiftLHS = Src.getOperand(0);
55477 SDValue ShiftRHS = Src.getOperand(1);
55478 if (ShiftVT.getScalarType() == MVT::i8) {
55479 // vXi8 shifts - we only care about the signbit so can use PSLLW.
55480 ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
55481 ShiftLHS = DAG.getBitcast(ShiftVT, ShiftLHS);
55482 ShiftRHS = DAG.getBitcast(ShiftVT, ShiftRHS);
55484 ShiftLHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
55485 ShiftLHS, ShiftAmt, DAG);
55486 ShiftRHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
55487 ShiftRHS, ShiftAmt, DAG);
55488 ShiftLHS = DAG.getBitcast(SrcVT, ShiftLHS);
55489 ShiftRHS = DAG.getBitcast(SrcVT, ShiftRHS);
55490 SDValue Res = DAG.getNode(ISD::XOR, DL, SrcVT, ShiftLHS, ShiftRHS);
55491 return DAG.getNode(X86ISD::MOVMSK, DL, VT, DAG.getNOT(DL, Res, SrcVT));
55495 // Fold movmsk(logic(X,C)) -> logic(movmsk(X),C)
55496 if (N->isOnlyUserOf(Src.getNode())) {
55497 SDValue SrcBC = peekThroughOneUseBitcasts(Src);
55498 if (ISD::isBitwiseLogicOp(SrcBC.getOpcode())) {
55499 APInt UndefElts;
55500 SmallVector<APInt, 32> EltBits;
55501 if (getTargetConstantBitsFromNode(SrcBC.getOperand(1), NumBitsPerElt,
55502 UndefElts, EltBits)) {
55503 APInt Mask = APInt::getZero(NumBits);
55504 for (unsigned Idx = 0; Idx != NumElts; ++Idx) {
55505 if (!UndefElts[Idx] && EltBits[Idx].isNegative())
55506 Mask.setBit(Idx);
55508 SDLoc DL(N);
55509 SDValue NewSrc = DAG.getBitcast(SrcVT, SrcBC.getOperand(0));
55510 SDValue NewMovMsk = DAG.getNode(X86ISD::MOVMSK, DL, VT, NewSrc);
55511 return DAG.getNode(SrcBC.getOpcode(), DL, VT, NewMovMsk,
55512 DAG.getConstant(Mask, DL, VT));
55517 // Simplify the inputs.
55518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55519 APInt DemandedMask(APInt::getAllOnes(NumBits));
55520 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
55521 return SDValue(N, 0);
55523 return SDValue();
55526 static SDValue combineTESTP(SDNode *N, SelectionDAG &DAG,
55527 TargetLowering::DAGCombinerInfo &DCI,
55528 const X86Subtarget &Subtarget) {
55529 MVT VT = N->getSimpleValueType(0);
55530 unsigned NumBits = VT.getScalarSizeInBits();
55532 // Simplify the inputs.
55533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55534 APInt DemandedMask(APInt::getAllOnes(NumBits));
55535 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
55536 return SDValue(N, 0);
55538 return SDValue();
55541 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
55542 TargetLowering::DAGCombinerInfo &DCI) {
55543 auto *MemOp = cast<X86MaskedGatherScatterSDNode>(N);
55544 SDValue Mask = MemOp->getMask();
55546 // With vector masks we only demand the upper bit of the mask.
55547 if (Mask.getScalarValueSizeInBits() != 1) {
55548 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55549 APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
55550 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
55551 if (N->getOpcode() != ISD::DELETED_NODE)
55552 DCI.AddToWorklist(N);
55553 return SDValue(N, 0);
55557 return SDValue();
55560 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
55561 SDValue Index, SDValue Base, SDValue Scale,
55562 SelectionDAG &DAG) {
55563 SDLoc DL(GorS);
55565 if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
55566 SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
55567 Gather->getMask(), Base, Index, Scale } ;
55568 return DAG.getMaskedGather(Gather->getVTList(),
55569 Gather->getMemoryVT(), DL, Ops,
55570 Gather->getMemOperand(),
55571 Gather->getIndexType(),
55572 Gather->getExtensionType());
55574 auto *Scatter = cast<MaskedScatterSDNode>(GorS);
55575 SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
55576 Scatter->getMask(), Base, Index, Scale };
55577 return DAG.getMaskedScatter(Scatter->getVTList(),
55578 Scatter->getMemoryVT(), DL,
55579 Ops, Scatter->getMemOperand(),
55580 Scatter->getIndexType(),
55581 Scatter->isTruncatingStore());
55584 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
55585 TargetLowering::DAGCombinerInfo &DCI) {
55586 SDLoc DL(N);
55587 auto *GorS = cast<MaskedGatherScatterSDNode>(N);
55588 SDValue Index = GorS->getIndex();
55589 SDValue Base = GorS->getBasePtr();
55590 SDValue Scale = GorS->getScale();
55591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55593 if (DCI.isBeforeLegalize()) {
55594 unsigned IndexWidth = Index.getScalarValueSizeInBits();
55596 // Shrink constant indices if they are larger than 32-bits.
55597 // Only do this before legalize types since v2i64 could become v2i32.
55598 // FIXME: We could check that the type is legal if we're after legalize
55599 // types, but then we would need to construct test cases where that happens.
55600 // FIXME: We could support more than just constant vectors, but we need to
55601 // careful with costing. A truncate that can be optimized out would be fine.
55602 // Otherwise we might only want to create a truncate if it avoids a split.
55603 if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
55604 if (BV->isConstant() && IndexWidth > 32 &&
55605 DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
55606 EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
55607 Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
55608 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55612 // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
55613 // there are sufficient sign bits. Only do this before legalize types to
55614 // avoid creating illegal types in truncate.
55615 if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
55616 Index.getOpcode() == ISD::ZERO_EXTEND) &&
55617 IndexWidth > 32 &&
55618 Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
55619 DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
55620 EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
55621 Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
55622 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55626 EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
55627 // Try to move splat constant adders from the index operand to the base
55628 // pointer operand. Taking care to multiply by the scale. We can only do
55629 // this when index element type is the same as the pointer type.
55630 // Otherwise we need to be sure the math doesn't wrap before the scale.
55631 if (Index.getOpcode() == ISD::ADD &&
55632 Index.getValueType().getVectorElementType() == PtrVT &&
55633 isa<ConstantSDNode>(Scale)) {
55634 uint64_t ScaleAmt = Scale->getAsZExtVal();
55635 if (auto *BV = dyn_cast<BuildVectorSDNode>(Index.getOperand(1))) {
55636 BitVector UndefElts;
55637 if (ConstantSDNode *C = BV->getConstantSplatNode(&UndefElts)) {
55638 // FIXME: Allow non-constant?
55639 if (UndefElts.none()) {
55640 // Apply the scale.
55641 APInt Adder = C->getAPIntValue() * ScaleAmt;
55642 // Add it to the existing base.
55643 Base = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
55644 DAG.getConstant(Adder, DL, PtrVT));
55645 Index = Index.getOperand(0);
55646 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55650 // It's also possible base is just a constant. In that case, just
55651 // replace it with 0 and move the displacement into the index.
55652 if (BV->isConstant() && isa<ConstantSDNode>(Base) &&
55653 isOneConstant(Scale)) {
55654 SDValue Splat = DAG.getSplatBuildVector(Index.getValueType(), DL, Base);
55655 // Combine the constant build_vector and the constant base.
55656 Splat = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
55657 Index.getOperand(1), Splat);
55658 // Add to the LHS of the original Index add.
55659 Index = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
55660 Index.getOperand(0), Splat);
55661 Base = DAG.getConstant(0, DL, Base.getValueType());
55662 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55667 if (DCI.isBeforeLegalizeOps()) {
55668 unsigned IndexWidth = Index.getScalarValueSizeInBits();
55670 // Make sure the index is either i32 or i64
55671 if (IndexWidth != 32 && IndexWidth != 64) {
55672 MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
55673 EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
55674 Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
55675 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
55679 // With vector masks we only demand the upper bit of the mask.
55680 SDValue Mask = GorS->getMask();
55681 if (Mask.getScalarValueSizeInBits() != 1) {
55682 APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
55683 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
55684 if (N->getOpcode() != ISD::DELETED_NODE)
55685 DCI.AddToWorklist(N);
55686 return SDValue(N, 0);
55690 return SDValue();
55693 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
55694 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
55695 const X86Subtarget &Subtarget) {
55696 SDLoc DL(N);
55697 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
55698 SDValue EFLAGS = N->getOperand(1);
55700 // Try to simplify the EFLAGS and condition code operands.
55701 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
55702 return getSETCC(CC, Flags, DL, DAG);
55704 return SDValue();
55707 /// Optimize branch condition evaluation.
55708 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
55709 const X86Subtarget &Subtarget) {
55710 SDLoc DL(N);
55711 SDValue EFLAGS = N->getOperand(3);
55712 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
55714 // Try to simplify the EFLAGS and condition code operands.
55715 // Make sure to not keep references to operands, as combineSetCCEFLAGS can
55716 // RAUW them under us.
55717 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
55718 SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
55719 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
55720 N->getOperand(1), Cond, Flags);
55723 return SDValue();
55726 // TODO: Could we move this to DAGCombine?
55727 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
55728 SelectionDAG &DAG) {
55729 // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
55730 // to optimize away operation when it's from a constant.
55732 // The general transformation is:
55733 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
55734 // AND(VECTOR_CMP(x,y), constant2)
55735 // constant2 = UNARYOP(constant)
55737 // Early exit if this isn't a vector operation, the operand of the
55738 // unary operation isn't a bitwise AND, or if the sizes of the operations
55739 // aren't the same.
55740 EVT VT = N->getValueType(0);
55741 bool IsStrict = N->isStrictFPOpcode();
55742 unsigned NumEltBits = VT.getScalarSizeInBits();
55743 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
55744 if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
55745 DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
55746 VT.getSizeInBits() != Op0.getValueSizeInBits())
55747 return SDValue();
55749 // Now check that the other operand of the AND is a constant. We could
55750 // make the transformation for non-constant splats as well, but it's unclear
55751 // that would be a benefit as it would not eliminate any operations, just
55752 // perform one more step in scalar code before moving to the vector unit.
55753 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
55754 // Bail out if the vector isn't a constant.
55755 if (!BV->isConstant())
55756 return SDValue();
55758 // Everything checks out. Build up the new and improved node.
55759 SDLoc DL(N);
55760 EVT IntVT = BV->getValueType(0);
55761 // Create a new constant of the appropriate type for the transformed
55762 // DAG.
55763 SDValue SourceConst;
55764 if (IsStrict)
55765 SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
55766 {N->getOperand(0), SDValue(BV, 0)});
55767 else
55768 SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
55769 // The AND node needs bitcasts to/from an integer vector type around it.
55770 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
55771 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
55772 MaskConst);
55773 SDValue Res = DAG.getBitcast(VT, NewAnd);
55774 if (IsStrict)
55775 return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
55776 return Res;
55779 return SDValue();
55782 /// If we are converting a value to floating-point, try to replace scalar
55783 /// truncate of an extracted vector element with a bitcast. This tries to keep
55784 /// the sequence on XMM registers rather than moving between vector and GPRs.
55785 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
55786 // TODO: This is currently only used by combineSIntToFP, but it is generalized
55787 // to allow being called by any similar cast opcode.
55788 // TODO: Consider merging this into lowering: vectorizeExtractedCast().
55789 SDValue Trunc = N->getOperand(0);
55790 if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
55791 return SDValue();
55793 SDValue ExtElt = Trunc.getOperand(0);
55794 if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
55795 !isNullConstant(ExtElt.getOperand(1)))
55796 return SDValue();
55798 EVT TruncVT = Trunc.getValueType();
55799 EVT SrcVT = ExtElt.getValueType();
55800 unsigned DestWidth = TruncVT.getSizeInBits();
55801 unsigned SrcWidth = SrcVT.getSizeInBits();
55802 if (SrcWidth % DestWidth != 0)
55803 return SDValue();
55805 // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
55806 EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
55807 unsigned VecWidth = SrcVecVT.getSizeInBits();
55808 unsigned NumElts = VecWidth / DestWidth;
55809 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
55810 SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
55811 SDLoc DL(N);
55812 SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
55813 BitcastVec, ExtElt.getOperand(1));
55814 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
55817 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
55818 const X86Subtarget &Subtarget) {
55819 bool IsStrict = N->isStrictFPOpcode();
55820 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
55821 EVT VT = N->getValueType(0);
55822 EVT InVT = Op0.getValueType();
55824 // Using i16 as an intermediate type is a bad idea, unless we have HW support
55825 // for it. Therefore for type sizes equal or smaller than 32 just go with i32.
55826 // if hasFP16 support:
55827 // UINT_TO_FP(vXi1~15) -> SINT_TO_FP(ZEXT(vXi1~15 to vXi16))
55828 // UINT_TO_FP(vXi17~31) -> SINT_TO_FP(ZEXT(vXi17~31 to vXi32))
55829 // else
55830 // UINT_TO_FP(vXi1~31) -> SINT_TO_FP(ZEXT(vXi1~31 to vXi32))
55831 // UINT_TO_FP(vXi33~63) -> SINT_TO_FP(ZEXT(vXi33~63 to vXi64))
55832 if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
55833 unsigned ScalarSize = InVT.getScalarSizeInBits();
55834 if ((ScalarSize == 16 && Subtarget.hasFP16()) || ScalarSize == 32 ||
55835 ScalarSize >= 64)
55836 return SDValue();
55837 SDLoc dl(N);
55838 EVT DstVT =
55839 EVT::getVectorVT(*DAG.getContext(),
55840 (Subtarget.hasFP16() && ScalarSize < 16) ? MVT::i16
55841 : ScalarSize < 32 ? MVT::i32
55842 : MVT::i64,
55843 InVT.getVectorNumElements());
55844 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
55845 if (IsStrict)
55846 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
55847 {N->getOperand(0), P});
55848 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
55851 // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
55852 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
55853 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
55854 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
55855 VT.getScalarType() != MVT::f16) {
55856 SDLoc dl(N);
55857 EVT DstVT = InVT.changeVectorElementType(MVT::i32);
55858 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
55860 // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
55861 if (IsStrict)
55862 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
55863 {N->getOperand(0), P});
55864 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
55867 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
55868 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
55869 // the optimization here.
55870 SDNodeFlags Flags = N->getFlags();
55871 if (Flags.hasNonNeg() || DAG.SignBitIsZero(Op0)) {
55872 if (IsStrict)
55873 return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
55874 {N->getOperand(0), Op0});
55875 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
55878 return SDValue();
55881 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
55882 TargetLowering::DAGCombinerInfo &DCI,
55883 const X86Subtarget &Subtarget) {
55884 // First try to optimize away the conversion entirely when it's
55885 // conditionally from a constant. Vectors only.
55886 bool IsStrict = N->isStrictFPOpcode();
55887 if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
55888 return Res;
55890 // Now move on to more general possibilities.
55891 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
55892 EVT VT = N->getValueType(0);
55893 EVT InVT = Op0.getValueType();
55895 // Using i16 as an intermediate type is a bad idea, unless we have HW support
55896 // for it. Therefore for type sizes equal or smaller than 32 just go with i32.
55897 // if hasFP16 support:
55898 // SINT_TO_FP(vXi1~15) -> SINT_TO_FP(SEXT(vXi1~15 to vXi16))
55899 // SINT_TO_FP(vXi17~31) -> SINT_TO_FP(SEXT(vXi17~31 to vXi32))
55900 // else
55901 // SINT_TO_FP(vXi1~31) -> SINT_TO_FP(ZEXT(vXi1~31 to vXi32))
55902 // SINT_TO_FP(vXi33~63) -> SINT_TO_FP(SEXT(vXi33~63 to vXi64))
55903 if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
55904 unsigned ScalarSize = InVT.getScalarSizeInBits();
55905 if ((ScalarSize == 16 && Subtarget.hasFP16()) || ScalarSize == 32 ||
55906 ScalarSize >= 64)
55907 return SDValue();
55908 SDLoc dl(N);
55909 EVT DstVT =
55910 EVT::getVectorVT(*DAG.getContext(),
55911 (Subtarget.hasFP16() && ScalarSize < 16) ? MVT::i16
55912 : ScalarSize < 32 ? MVT::i32
55913 : MVT::i64,
55914 InVT.getVectorNumElements());
55915 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
55916 if (IsStrict)
55917 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
55918 {N->getOperand(0), P});
55919 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
55922 // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
55923 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
55924 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
55925 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
55926 VT.getScalarType() != MVT::f16) {
55927 SDLoc dl(N);
55928 EVT DstVT = InVT.changeVectorElementType(MVT::i32);
55929 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
55930 if (IsStrict)
55931 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
55932 {N->getOperand(0), P});
55933 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
55936 // Without AVX512DQ we only support i64 to float scalar conversion. For both
55937 // vectors and scalars, see if we know that the upper bits are all the sign
55938 // bit, in which case we can truncate the input to i32 and convert from that.
55939 if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
55940 unsigned BitWidth = InVT.getScalarSizeInBits();
55941 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
55942 if (NumSignBits >= (BitWidth - 31)) {
55943 EVT TruncVT = MVT::i32;
55944 if (InVT.isVector())
55945 TruncVT = InVT.changeVectorElementType(TruncVT);
55946 SDLoc dl(N);
55947 if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
55948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
55949 if (IsStrict)
55950 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
55951 {N->getOperand(0), Trunc});
55952 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
55954 // If we're after legalize and the type is v2i32 we need to shuffle and
55955 // use CVTSI2P.
55956 assert(InVT == MVT::v2i64 && "Unexpected VT!");
55957 SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
55958 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
55959 { 0, 2, -1, -1 });
55960 if (IsStrict)
55961 return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
55962 {N->getOperand(0), Shuf});
55963 return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
55967 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
55968 // a 32-bit target where SSE doesn't support i64->FP operations.
55969 if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
55970 Op0.getOpcode() == ISD::LOAD) {
55971 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
55973 // This transformation is not supported if the result type is f16 or f128.
55974 if (VT == MVT::f16 || VT == MVT::f128)
55975 return SDValue();
55977 // If we have AVX512DQ we can use packed conversion instructions unless
55978 // the VT is f80.
55979 if (Subtarget.hasDQI() && VT != MVT::f80)
55980 return SDValue();
55982 if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
55983 Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
55984 std::pair<SDValue, SDValue> Tmp =
55985 Subtarget.getTargetLowering()->BuildFILD(
55986 VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
55987 Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
55988 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
55989 return Tmp.first;
55993 if (IsStrict)
55994 return SDValue();
55996 if (SDValue V = combineToFPTruncExtElt(N, DAG))
55997 return V;
55999 return SDValue();
56002 static bool needCarryOrOverflowFlag(SDValue Flags) {
56003 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
56005 for (const SDNode *User : Flags->uses()) {
56006 X86::CondCode CC;
56007 switch (User->getOpcode()) {
56008 default:
56009 // Be conservative.
56010 return true;
56011 case X86ISD::SETCC:
56012 case X86ISD::SETCC_CARRY:
56013 CC = (X86::CondCode)User->getConstantOperandVal(0);
56014 break;
56015 case X86ISD::BRCOND:
56016 case X86ISD::CMOV:
56017 CC = (X86::CondCode)User->getConstantOperandVal(2);
56018 break;
56021 switch (CC) {
56022 // clang-format off
56023 default: break;
56024 case X86::COND_A: case X86::COND_AE:
56025 case X86::COND_B: case X86::COND_BE:
56026 case X86::COND_O: case X86::COND_NO:
56027 case X86::COND_G: case X86::COND_GE:
56028 case X86::COND_L: case X86::COND_LE:
56029 return true;
56030 // clang-format on
56034 return false;
56037 static bool onlyZeroFlagUsed(SDValue Flags) {
56038 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
56040 for (const SDNode *User : Flags->uses()) {
56041 unsigned CCOpNo;
56042 switch (User->getOpcode()) {
56043 default:
56044 // Be conservative.
56045 return false;
56046 case X86ISD::SETCC:
56047 case X86ISD::SETCC_CARRY:
56048 CCOpNo = 0;
56049 break;
56050 case X86ISD::BRCOND:
56051 case X86ISD::CMOV:
56052 CCOpNo = 2;
56053 break;
56056 X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
56057 if (CC != X86::COND_E && CC != X86::COND_NE)
56058 return false;
56061 return true;
56064 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG,
56065 TargetLowering::DAGCombinerInfo &DCI,
56066 const X86Subtarget &Subtarget) {
56067 // Only handle test patterns.
56068 if (!isNullConstant(N->getOperand(1)))
56069 return SDValue();
56071 // If we have a CMP of a truncated binop, see if we can make a smaller binop
56072 // and use its flags directly.
56073 // TODO: Maybe we should try promoting compares that only use the zero flag
56074 // first if we can prove the upper bits with computeKnownBits?
56075 SDLoc dl(N);
56076 SDValue Op = N->getOperand(0);
56077 EVT VT = Op.getValueType();
56078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
56080 if (SDValue CMP =
56081 combineX86SubCmpForFlags(N, SDValue(N, 0), DAG, DCI, Subtarget))
56082 return CMP;
56084 // If we have a constant logical shift that's only used in a comparison
56085 // against zero turn it into an equivalent AND. This allows turning it into
56086 // a TEST instruction later.
56087 if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
56088 Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
56089 onlyZeroFlagUsed(SDValue(N, 0))) {
56090 unsigned BitWidth = VT.getSizeInBits();
56091 const APInt &ShAmt = Op.getConstantOperandAPInt(1);
56092 if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
56093 unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
56094 APInt Mask = Op.getOpcode() == ISD::SRL
56095 ? APInt::getHighBitsSet(BitWidth, MaskBits)
56096 : APInt::getLowBitsSet(BitWidth, MaskBits);
56097 if (Mask.isSignedIntN(32)) {
56098 Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
56099 DAG.getConstant(Mask, dl, VT));
56100 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56101 DAG.getConstant(0, dl, VT));
56106 // If we're extracting from a avx512 bool vector and comparing against zero,
56107 // then try to just bitcast the vector to an integer to use TEST/BT directly.
56108 // (and (extract_elt (kshiftr vXi1, C), 0), 1) -> (and (bc vXi1), 1<<C)
56109 if (Op.getOpcode() == ISD::AND && isOneConstant(Op.getOperand(1)) &&
56110 Op.hasOneUse() && onlyZeroFlagUsed(SDValue(N, 0))) {
56111 SDValue Src = Op.getOperand(0);
56112 if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
56113 isNullConstant(Src.getOperand(1)) &&
56114 Src.getOperand(0).getValueType().getScalarType() == MVT::i1) {
56115 SDValue BoolVec = Src.getOperand(0);
56116 unsigned ShAmt = 0;
56117 if (BoolVec.getOpcode() == X86ISD::KSHIFTR) {
56118 ShAmt = BoolVec.getConstantOperandVal(1);
56119 BoolVec = BoolVec.getOperand(0);
56121 BoolVec = widenMaskVector(BoolVec, false, Subtarget, DAG, dl);
56122 EVT VecVT = BoolVec.getValueType();
56123 unsigned BitWidth = VecVT.getVectorNumElements();
56124 EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), BitWidth);
56125 if (TLI.isTypeLegal(VecVT) && TLI.isTypeLegal(BCVT)) {
56126 APInt Mask = APInt::getOneBitSet(BitWidth, ShAmt);
56127 Op = DAG.getBitcast(BCVT, BoolVec);
56128 Op = DAG.getNode(ISD::AND, dl, BCVT, Op,
56129 DAG.getConstant(Mask, dl, BCVT));
56130 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56131 DAG.getConstant(0, dl, BCVT));
56136 // Peek through any zero-extend if we're only testing for a zero result.
56137 if (Op.getOpcode() == ISD::ZERO_EXTEND && onlyZeroFlagUsed(SDValue(N, 0))) {
56138 SDValue Src = Op.getOperand(0);
56139 EVT SrcVT = Src.getValueType();
56140 if (SrcVT.getScalarSizeInBits() >= 8 && TLI.isTypeLegal(SrcVT))
56141 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Src,
56142 DAG.getConstant(0, dl, SrcVT));
56145 // Look for a truncate.
56146 if (Op.getOpcode() != ISD::TRUNCATE)
56147 return SDValue();
56149 SDValue Trunc = Op;
56150 Op = Op.getOperand(0);
56152 // See if we can compare with zero against the truncation source,
56153 // which should help using the Z flag from many ops. Only do this for
56154 // i32 truncated op to prevent partial-reg compares of promoted ops.
56155 EVT OpVT = Op.getValueType();
56156 APInt UpperBits =
56157 APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
56158 if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
56159 onlyZeroFlagUsed(SDValue(N, 0))) {
56160 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56161 DAG.getConstant(0, dl, OpVT));
56164 // After this the truncate and arithmetic op must have a single use.
56165 if (!Trunc.hasOneUse() || !Op.hasOneUse())
56166 return SDValue();
56168 unsigned NewOpc;
56169 switch (Op.getOpcode()) {
56170 default: return SDValue();
56171 case ISD::AND:
56172 // Skip and with constant. We have special handling for and with immediate
56173 // during isel to generate test instructions.
56174 if (isa<ConstantSDNode>(Op.getOperand(1)))
56175 return SDValue();
56176 NewOpc = X86ISD::AND;
56177 break;
56178 case ISD::OR: NewOpc = X86ISD::OR; break;
56179 case ISD::XOR: NewOpc = X86ISD::XOR; break;
56180 case ISD::ADD:
56181 // If the carry or overflow flag is used, we can't truncate.
56182 if (needCarryOrOverflowFlag(SDValue(N, 0)))
56183 return SDValue();
56184 NewOpc = X86ISD::ADD;
56185 break;
56186 case ISD::SUB:
56187 // If the carry or overflow flag is used, we can't truncate.
56188 if (needCarryOrOverflowFlag(SDValue(N, 0)))
56189 return SDValue();
56190 NewOpc = X86ISD::SUB;
56191 break;
56194 // We found an op we can narrow. Truncate its inputs.
56195 SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
56196 SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
56198 // Use a X86 specific opcode to avoid DAG combine messing with it.
56199 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56200 Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
56202 // For AND, keep a CMP so that we can match the test pattern.
56203 if (NewOpc == X86ISD::AND)
56204 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
56205 DAG.getConstant(0, dl, VT));
56207 // Return the flags.
56208 return Op.getValue(1);
56211 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
56212 TargetLowering::DAGCombinerInfo &DCI,
56213 const X86Subtarget &ST) {
56214 assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
56215 "Expected X86ISD::ADD or X86ISD::SUB");
56217 SDLoc DL(N);
56218 SDValue LHS = N->getOperand(0);
56219 SDValue RHS = N->getOperand(1);
56220 MVT VT = LHS.getSimpleValueType();
56221 bool IsSub = X86ISD::SUB == N->getOpcode();
56222 unsigned GenericOpc = IsSub ? ISD::SUB : ISD::ADD;
56224 if (IsSub && isOneConstant(N->getOperand(1)) && !N->hasAnyUseOfValue(0))
56225 if (SDValue CMP = combineX86SubCmpForFlags(N, SDValue(N, 1), DAG, DCI, ST))
56226 return CMP;
56228 // If we don't use the flag result, simplify back to a generic ADD/SUB.
56229 if (!N->hasAnyUseOfValue(1)) {
56230 SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
56231 return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
56234 // Fold any similar generic ADD/SUB opcodes to reuse this node.
56235 auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
56236 SDValue Ops[] = {N0, N1};
56237 SDVTList VTs = DAG.getVTList(N->getValueType(0));
56238 if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
56239 SDValue Op(N, 0);
56240 if (Negate) {
56241 // Bail if this is only used by a user of the x86 add/sub.
56242 if (GenericAddSub->hasOneUse() &&
56243 GenericAddSub->use_begin()->isOnlyUserOf(N))
56244 return;
56245 Op = DAG.getNegative(Op, DL, VT);
56247 DCI.CombineTo(GenericAddSub, Op);
56250 MatchGeneric(LHS, RHS, false);
56251 MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
56253 // TODO: Can we drop the ZeroSecondOpOnly limit? This is to guarantee that the
56254 // EFLAGS result doesn't change.
56255 return combineAddOrSubToADCOrSBB(IsSub, DL, VT, LHS, RHS, DAG,
56256 /*ZeroSecondOpOnly*/ true);
56259 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
56260 SDValue LHS = N->getOperand(0);
56261 SDValue RHS = N->getOperand(1);
56262 SDValue BorrowIn = N->getOperand(2);
56264 if (SDValue Flags = combineCarryThroughADD(BorrowIn, DAG)) {
56265 MVT VT = N->getSimpleValueType(0);
56266 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56267 return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs, LHS, RHS, Flags);
56270 // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
56271 // iff the flag result is dead.
56272 if (LHS.getOpcode() == ISD::SUB && isNullConstant(RHS) &&
56273 !N->hasAnyUseOfValue(1))
56274 return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), LHS.getOperand(0),
56275 LHS.getOperand(1), BorrowIn);
56277 return SDValue();
56280 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
56281 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
56282 TargetLowering::DAGCombinerInfo &DCI) {
56283 SDValue LHS = N->getOperand(0);
56284 SDValue RHS = N->getOperand(1);
56285 SDValue CarryIn = N->getOperand(2);
56286 auto *LHSC = dyn_cast<ConstantSDNode>(LHS);
56287 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
56289 // Canonicalize constant to RHS.
56290 if (LHSC && !RHSC)
56291 return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), RHS, LHS,
56292 CarryIn);
56294 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
56295 // the result is either zero or one (depending on the input carry bit).
56296 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
56297 if (LHSC && RHSC && LHSC->isZero() && RHSC->isZero() &&
56298 // We don't have a good way to replace an EFLAGS use, so only do this when
56299 // dead right now.
56300 SDValue(N, 1).use_empty()) {
56301 SDLoc DL(N);
56302 EVT VT = N->getValueType(0);
56303 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
56304 SDValue Res1 = DAG.getNode(
56305 ISD::AND, DL, VT,
56306 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
56307 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), CarryIn),
56308 DAG.getConstant(1, DL, VT));
56309 return DCI.CombineTo(N, Res1, CarryOut);
56312 // Fold ADC(C1,C2,Carry) -> ADC(0,C1+C2,Carry)
56313 // iff the flag result is dead.
56314 // TODO: Allow flag result if C1+C2 doesn't signed/unsigned overflow.
56315 if (LHSC && RHSC && !LHSC->isZero() && !N->hasAnyUseOfValue(1)) {
56316 SDLoc DL(N);
56317 APInt Sum = LHSC->getAPIntValue() + RHSC->getAPIntValue();
56318 return DAG.getNode(X86ISD::ADC, DL, N->getVTList(),
56319 DAG.getConstant(0, DL, LHS.getValueType()),
56320 DAG.getConstant(Sum, DL, LHS.getValueType()), CarryIn);
56323 if (SDValue Flags = combineCarryThroughADD(CarryIn, DAG)) {
56324 MVT VT = N->getSimpleValueType(0);
56325 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
56326 return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs, LHS, RHS, Flags);
56329 // Fold ADC(ADD(X,Y),0,Carry) -> ADC(X,Y,Carry)
56330 // iff the flag result is dead.
56331 if (LHS.getOpcode() == ISD::ADD && RHSC && RHSC->isZero() &&
56332 !N->hasAnyUseOfValue(1))
56333 return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), LHS.getOperand(0),
56334 LHS.getOperand(1), CarryIn);
56336 return SDValue();
56339 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
56340 const SDLoc &DL, EVT VT,
56341 const X86Subtarget &Subtarget) {
56342 // Example of pattern we try to detect:
56343 // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
56344 //(add (build_vector (extract_elt t, 0),
56345 // (extract_elt t, 2),
56346 // (extract_elt t, 4),
56347 // (extract_elt t, 6)),
56348 // (build_vector (extract_elt t, 1),
56349 // (extract_elt t, 3),
56350 // (extract_elt t, 5),
56351 // (extract_elt t, 7)))
56353 if (!Subtarget.hasSSE2())
56354 return SDValue();
56356 if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
56357 Op1.getOpcode() != ISD::BUILD_VECTOR)
56358 return SDValue();
56360 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
56361 VT.getVectorNumElements() < 4 ||
56362 !isPowerOf2_32(VT.getVectorNumElements()))
56363 return SDValue();
56365 // Check if one of Op0,Op1 is of the form:
56366 // (build_vector (extract_elt Mul, 0),
56367 // (extract_elt Mul, 2),
56368 // (extract_elt Mul, 4),
56369 // ...
56370 // the other is of the form:
56371 // (build_vector (extract_elt Mul, 1),
56372 // (extract_elt Mul, 3),
56373 // (extract_elt Mul, 5),
56374 // ...
56375 // and identify Mul.
56376 SDValue Mul;
56377 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
56378 SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
56379 Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
56380 // TODO: Be more tolerant to undefs.
56381 if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56382 Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56383 Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56384 Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
56385 return SDValue();
56386 auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
56387 auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
56388 auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
56389 auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
56390 if (!Const0L || !Const1L || !Const0H || !Const1H)
56391 return SDValue();
56392 unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
56393 Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
56394 // Commutativity of mul allows factors of a product to reorder.
56395 if (Idx0L > Idx1L)
56396 std::swap(Idx0L, Idx1L);
56397 if (Idx0H > Idx1H)
56398 std::swap(Idx0H, Idx1H);
56399 // Commutativity of add allows pairs of factors to reorder.
56400 if (Idx0L > Idx0H) {
56401 std::swap(Idx0L, Idx0H);
56402 std::swap(Idx1L, Idx1H);
56404 if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
56405 Idx1H != 2 * i + 3)
56406 return SDValue();
56407 if (!Mul) {
56408 // First time an extract_elt's source vector is visited. Must be a MUL
56409 // with 2X number of vector elements than the BUILD_VECTOR.
56410 // Both extracts must be from same MUL.
56411 Mul = Op0L->getOperand(0);
56412 if (Mul->getOpcode() != ISD::MUL ||
56413 Mul.getValueType().getVectorNumElements() != 2 * e)
56414 return SDValue();
56416 // Check that the extract is from the same MUL previously seen.
56417 if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
56418 Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
56419 return SDValue();
56422 // Check if the Mul source can be safely shrunk.
56423 ShrinkMode Mode;
56424 if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
56425 Mode == ShrinkMode::MULU16)
56426 return SDValue();
56428 EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
56429 VT.getVectorNumElements() * 2);
56430 SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
56431 SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
56433 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
56434 ArrayRef<SDValue> Ops) {
56435 EVT InVT = Ops[0].getValueType();
56436 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
56437 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
56438 InVT.getVectorNumElements() / 2);
56439 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
56441 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
56444 // Attempt to turn this pattern into PMADDWD.
56445 // (add (mul (sext (build_vector)), (sext (build_vector))),
56446 // (mul (sext (build_vector)), (sext (build_vector)))
56447 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
56448 const SDLoc &DL, EVT VT,
56449 const X86Subtarget &Subtarget) {
56450 if (!Subtarget.hasSSE2())
56451 return SDValue();
56453 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
56454 return SDValue();
56456 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
56457 VT.getVectorNumElements() < 4 ||
56458 !isPowerOf2_32(VT.getVectorNumElements()))
56459 return SDValue();
56461 SDValue N00 = N0.getOperand(0);
56462 SDValue N01 = N0.getOperand(1);
56463 SDValue N10 = N1.getOperand(0);
56464 SDValue N11 = N1.getOperand(1);
56466 // All inputs need to be sign extends.
56467 // TODO: Support ZERO_EXTEND from known positive?
56468 if (N00.getOpcode() != ISD::SIGN_EXTEND ||
56469 N01.getOpcode() != ISD::SIGN_EXTEND ||
56470 N10.getOpcode() != ISD::SIGN_EXTEND ||
56471 N11.getOpcode() != ISD::SIGN_EXTEND)
56472 return SDValue();
56474 // Peek through the extends.
56475 N00 = N00.getOperand(0);
56476 N01 = N01.getOperand(0);
56477 N10 = N10.getOperand(0);
56478 N11 = N11.getOperand(0);
56480 // Must be extending from vXi16.
56481 EVT InVT = N00.getValueType();
56482 if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
56483 N10.getValueType() != InVT || N11.getValueType() != InVT)
56484 return SDValue();
56486 // All inputs should be build_vectors.
56487 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
56488 N01.getOpcode() != ISD::BUILD_VECTOR ||
56489 N10.getOpcode() != ISD::BUILD_VECTOR ||
56490 N11.getOpcode() != ISD::BUILD_VECTOR)
56491 return SDValue();
56493 // For each element, we need to ensure we have an odd element from one vector
56494 // multiplied by the odd element of another vector and the even element from
56495 // one of the same vectors being multiplied by the even element from the
56496 // other vector. So we need to make sure for each element i, this operator
56497 // is being performed:
56498 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
56499 SDValue In0, In1;
56500 for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
56501 SDValue N00Elt = N00.getOperand(i);
56502 SDValue N01Elt = N01.getOperand(i);
56503 SDValue N10Elt = N10.getOperand(i);
56504 SDValue N11Elt = N11.getOperand(i);
56505 // TODO: Be more tolerant to undefs.
56506 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56507 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56508 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
56509 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
56510 return SDValue();
56511 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
56512 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
56513 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
56514 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
56515 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
56516 return SDValue();
56517 unsigned IdxN00 = ConstN00Elt->getZExtValue();
56518 unsigned IdxN01 = ConstN01Elt->getZExtValue();
56519 unsigned IdxN10 = ConstN10Elt->getZExtValue();
56520 unsigned IdxN11 = ConstN11Elt->getZExtValue();
56521 // Add is commutative so indices can be reordered.
56522 if (IdxN00 > IdxN10) {
56523 std::swap(IdxN00, IdxN10);
56524 std::swap(IdxN01, IdxN11);
56526 // N0 indices be the even element. N1 indices must be the next odd element.
56527 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
56528 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
56529 return SDValue();
56530 SDValue N00In = N00Elt.getOperand(0);
56531 SDValue N01In = N01Elt.getOperand(0);
56532 SDValue N10In = N10Elt.getOperand(0);
56533 SDValue N11In = N11Elt.getOperand(0);
56535 // First time we find an input capture it.
56536 if (!In0) {
56537 In0 = N00In;
56538 In1 = N01In;
56540 // The input vectors must be at least as wide as the output.
56541 // If they are larger than the output, we extract subvector below.
56542 if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
56543 In1.getValueSizeInBits() < VT.getSizeInBits())
56544 return SDValue();
56546 // Mul is commutative so the input vectors can be in any order.
56547 // Canonicalize to make the compares easier.
56548 if (In0 != N00In)
56549 std::swap(N00In, N01In);
56550 if (In0 != N10In)
56551 std::swap(N10In, N11In);
56552 if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
56553 return SDValue();
56556 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
56557 ArrayRef<SDValue> Ops) {
56558 EVT OpVT = Ops[0].getValueType();
56559 assert(OpVT.getScalarType() == MVT::i16 &&
56560 "Unexpected scalar element type");
56561 assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
56562 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
56563 OpVT.getVectorNumElements() / 2);
56564 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
56567 // If the output is narrower than an input, extract the low part of the input
56568 // vector.
56569 EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
56570 VT.getVectorNumElements() * 2);
56571 if (OutVT16.bitsLT(In0.getValueType())) {
56572 In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
56573 DAG.getIntPtrConstant(0, DL));
56575 if (OutVT16.bitsLT(In1.getValueType())) {
56576 In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
56577 DAG.getIntPtrConstant(0, DL));
56579 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
56580 PMADDBuilder);
56583 // ADD(VPMADDWD(X,Y),VPMADDWD(Z,W)) -> VPMADDWD(SHUFFLE(X,Z), SHUFFLE(Y,W))
56584 // If upper element in each pair of both VPMADDWD are zero then we can merge
56585 // the operand elements and use the implicit add of VPMADDWD.
56586 // TODO: Add support for VPMADDUBSW (which isn't commutable).
56587 static SDValue combineAddOfPMADDWD(SelectionDAG &DAG, SDValue N0, SDValue N1,
56588 const SDLoc &DL, EVT VT) {
56589 if (N0.getOpcode() != N1.getOpcode() || N0.getOpcode() != X86ISD::VPMADDWD)
56590 return SDValue();
56592 // TODO: Add 256/512-bit support once VPMADDWD combines with shuffles.
56593 if (VT.getSizeInBits() > 128)
56594 return SDValue();
56596 unsigned NumElts = VT.getVectorNumElements();
56597 MVT OpVT = N0.getOperand(0).getSimpleValueType();
56598 APInt DemandedBits = APInt::getAllOnes(OpVT.getScalarSizeInBits());
56599 APInt DemandedHiElts = APInt::getSplat(2 * NumElts, APInt(2, 2));
56601 bool Op0HiZero =
56602 DAG.MaskedValueIsZero(N0.getOperand(0), DemandedBits, DemandedHiElts) ||
56603 DAG.MaskedValueIsZero(N0.getOperand(1), DemandedBits, DemandedHiElts);
56604 bool Op1HiZero =
56605 DAG.MaskedValueIsZero(N1.getOperand(0), DemandedBits, DemandedHiElts) ||
56606 DAG.MaskedValueIsZero(N1.getOperand(1), DemandedBits, DemandedHiElts);
56608 // TODO: Check for zero lower elements once we have actual codegen that
56609 // creates them.
56610 if (!Op0HiZero || !Op1HiZero)
56611 return SDValue();
56613 // Create a shuffle mask packing the lower elements from each VPMADDWD.
56614 SmallVector<int> Mask;
56615 for (int i = 0; i != (int)NumElts; ++i) {
56616 Mask.push_back(2 * i);
56617 Mask.push_back(2 * (i + NumElts));
56620 SDValue LHS =
56621 DAG.getVectorShuffle(OpVT, DL, N0.getOperand(0), N1.getOperand(0), Mask);
56622 SDValue RHS =
56623 DAG.getVectorShuffle(OpVT, DL, N0.getOperand(1), N1.getOperand(1), Mask);
56624 return DAG.getNode(X86ISD::VPMADDWD, DL, VT, LHS, RHS);
56627 /// CMOV of constants requires materializing constant operands in registers.
56628 /// Try to fold those constants into an 'add' instruction to reduce instruction
56629 /// count. We do this with CMOV rather the generic 'select' because there are
56630 /// earlier folds that may be used to turn select-of-constants into logic hacks.
56631 static SDValue pushAddIntoCmovOfConsts(SDNode *N, const SDLoc &DL,
56632 SelectionDAG &DAG,
56633 const X86Subtarget &Subtarget) {
56634 // If an operand is zero, add-of-0 gets simplified away, so that's clearly
56635 // better because we eliminate 1-2 instructions. This transform is still
56636 // an improvement without zero operands because we trade 2 move constants and
56637 // 1 add for 2 adds (LEA) as long as the constants can be represented as
56638 // immediate asm operands (fit in 32-bits).
56639 auto isSuitableCmov = [](SDValue V) {
56640 if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
56641 return false;
56642 if (!isa<ConstantSDNode>(V.getOperand(0)) ||
56643 !isa<ConstantSDNode>(V.getOperand(1)))
56644 return false;
56645 return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
56646 (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
56647 V.getConstantOperandAPInt(1).isSignedIntN(32));
56650 // Match an appropriate CMOV as the first operand of the add.
56651 SDValue Cmov = N->getOperand(0);
56652 SDValue OtherOp = N->getOperand(1);
56653 if (!isSuitableCmov(Cmov))
56654 std::swap(Cmov, OtherOp);
56655 if (!isSuitableCmov(Cmov))
56656 return SDValue();
56658 // Don't remove a load folding opportunity for the add. That would neutralize
56659 // any improvements from removing constant materializations.
56660 if (X86::mayFoldLoad(OtherOp, Subtarget))
56661 return SDValue();
56663 EVT VT = N->getValueType(0);
56664 SDValue FalseOp = Cmov.getOperand(0);
56665 SDValue TrueOp = Cmov.getOperand(1);
56667 // We will push the add through the select, but we can potentially do better
56668 // if we know there is another add in the sequence and this is pointer math.
56669 // In that case, we can absorb an add into the trailing memory op and avoid
56670 // a 3-operand LEA which is likely slower than a 2-operand LEA.
56671 // TODO: If target has "slow3OpsLEA", do this even without the trailing memop?
56672 if (OtherOp.getOpcode() == ISD::ADD && OtherOp.hasOneUse() &&
56673 !isa<ConstantSDNode>(OtherOp.getOperand(0)) &&
56674 all_of(N->uses(), [&](SDNode *Use) {
56675 auto *MemNode = dyn_cast<MemSDNode>(Use);
56676 return MemNode && MemNode->getBasePtr().getNode() == N;
56677 })) {
56678 // add (cmov C1, C2), add (X, Y) --> add (cmov (add X, C1), (add X, C2)), Y
56679 // TODO: We are arbitrarily choosing op0 as the 1st piece of the sum, but
56680 // it is possible that choosing op1 might be better.
56681 SDValue X = OtherOp.getOperand(0), Y = OtherOp.getOperand(1);
56682 FalseOp = DAG.getNode(ISD::ADD, DL, VT, X, FalseOp);
56683 TrueOp = DAG.getNode(ISD::ADD, DL, VT, X, TrueOp);
56684 Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp,
56685 Cmov.getOperand(2), Cmov.getOperand(3));
56686 return DAG.getNode(ISD::ADD, DL, VT, Cmov, Y);
56689 // add (cmov C1, C2), OtherOp --> cmov (add OtherOp, C1), (add OtherOp, C2)
56690 FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
56691 TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
56692 return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
56693 Cmov.getOperand(3));
56696 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
56697 TargetLowering::DAGCombinerInfo &DCI,
56698 const X86Subtarget &Subtarget) {
56699 EVT VT = N->getValueType(0);
56700 SDValue Op0 = N->getOperand(0);
56701 SDValue Op1 = N->getOperand(1);
56702 SDLoc DL(N);
56704 if (SDValue Select = pushAddIntoCmovOfConsts(N, DL, DAG, Subtarget))
56705 return Select;
56707 if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, DL, VT, Subtarget))
56708 return MAdd;
56709 if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, DL, VT, Subtarget))
56710 return MAdd;
56711 if (SDValue MAdd = combineAddOfPMADDWD(DAG, Op0, Op1, DL, VT))
56712 return MAdd;
56714 // Try to synthesize horizontal adds from adds of shuffles.
56715 if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
56716 return V;
56718 // add(psadbw(X,0),psadbw(Y,0)) -> psadbw(add(X,Y),0)
56719 // iff X and Y won't overflow.
56720 if (Op0.getOpcode() == X86ISD::PSADBW && Op1.getOpcode() == X86ISD::PSADBW &&
56721 ISD::isBuildVectorAllZeros(Op0.getOperand(1).getNode()) &&
56722 ISD::isBuildVectorAllZeros(Op1.getOperand(1).getNode())) {
56723 if (DAG.willNotOverflowAdd(false, Op0.getOperand(0), Op1.getOperand(0))) {
56724 MVT OpVT = Op0.getOperand(1).getSimpleValueType();
56725 SDValue Sum =
56726 DAG.getNode(ISD::ADD, DL, OpVT, Op0.getOperand(0), Op1.getOperand(0));
56727 return DAG.getNode(X86ISD::PSADBW, DL, VT, Sum,
56728 getZeroVector(OpVT, Subtarget, DAG, DL));
56732 // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
56733 // (sub Y, (sext (vXi1 X))).
56734 // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
56735 // generic DAG combine without a legal type check, but adding this there
56736 // caused regressions.
56737 if (VT.isVector()) {
56738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
56739 if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
56740 Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
56741 TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
56742 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
56743 return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
56746 if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
56747 Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
56748 TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
56749 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
56750 return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
56754 // Fold ADD(ADC(Y,0,W),X) -> ADC(X,Y,W)
56755 if (Op0.getOpcode() == X86ISD::ADC && Op0->hasOneUse() &&
56756 X86::isZeroNode(Op0.getOperand(1))) {
56757 assert(!Op0->hasAnyUseOfValue(1) && "Overflow bit in use");
56758 return DAG.getNode(X86ISD::ADC, SDLoc(Op0), Op0->getVTList(), Op1,
56759 Op0.getOperand(0), Op0.getOperand(2));
56762 return combineAddOrSubToADCOrSBB(N, DL, DAG);
56765 // Try to fold (sub Y, cmovns X, -X) -> (add Y, cmovns -X, X) if the cmov
56766 // condition comes from the subtract node that produced -X. This matches the
56767 // cmov expansion for absolute value. By swapping the operands we convert abs
56768 // to nabs.
56769 static SDValue combineSubABS(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1,
56770 SelectionDAG &DAG) {
56771 if (N1.getOpcode() != X86ISD::CMOV || !N1.hasOneUse())
56772 return SDValue();
56774 SDValue Cond = N1.getOperand(3);
56775 if (Cond.getOpcode() != X86ISD::SUB)
56776 return SDValue();
56777 assert(Cond.getResNo() == 1 && "Unexpected result number");
56779 SDValue FalseOp = N1.getOperand(0);
56780 SDValue TrueOp = N1.getOperand(1);
56781 X86::CondCode CC = (X86::CondCode)N1.getConstantOperandVal(2);
56783 // ABS condition should come from a negate operation.
56784 if ((CC == X86::COND_S || CC == X86::COND_NS) &&
56785 isNullConstant(Cond.getOperand(0))) {
56786 // Get the X and -X from the negate.
56787 SDValue NegX = Cond.getValue(0);
56788 SDValue X = Cond.getOperand(1);
56790 // Cmov operands should be X and NegX. Order doesn't matter.
56791 if (!(TrueOp == X && FalseOp == NegX) && !(TrueOp == NegX && FalseOp == X))
56792 return SDValue();
56794 // Build a new CMOV with the operands swapped.
56795 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp,
56796 N1.getOperand(2), Cond);
56797 // Convert sub to add.
56798 return DAG.getNode(ISD::ADD, DL, VT, N0, Cmov);
56801 // Handle ABD special case:
56802 // NEG(ABD(X,Y)) -> NEG(CMOV(SUB(X,Y),SUB(Y,X))) -> CMOV(SUB(Y,X),SUB(X,Y)).
56803 // ABD condition should come from a pair of matching subtracts.
56804 if ((CC == X86::COND_L || CC == X86::COND_B) && isNullConstant(N0) &&
56805 (FalseOp == Cond.getValue(0) || TrueOp == Cond.getValue(0)) &&
56806 (TrueOp.getOpcode() == ISD::SUB || TrueOp.getOpcode() == X86ISD::SUB) &&
56807 (FalseOp.getOpcode() == ISD::SUB || FalseOp.getOpcode() == X86ISD::SUB) &&
56808 (TrueOp.getOperand(0) == FalseOp.getOperand(1)) &&
56809 (TrueOp.getOperand(1) == FalseOp.getOperand(0))) {
56810 // Build a new CMOV with the operands swapped.
56811 return DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp, N1.getOperand(2),
56812 Cond);
56815 return SDValue();
56818 static SDValue combineSubSetcc(SDNode *N, SelectionDAG &DAG) {
56819 SDValue Op0 = N->getOperand(0);
56820 SDValue Op1 = N->getOperand(1);
56822 // (sub C (zero_extend (setcc)))
56823 // =>
56824 // (add (zero_extend (setcc inverted) C-1)) if C is a nonzero immediate
56825 // Don't disturb (sub 0 setcc), which is easily done with neg.
56826 EVT VT = N->getValueType(0);
56827 auto *Op0C = dyn_cast<ConstantSDNode>(Op0);
56828 if (Op1.getOpcode() == ISD::ZERO_EXTEND && Op1.hasOneUse() && Op0C &&
56829 !Op0C->isZero() && Op1.getOperand(0).getOpcode() == X86ISD::SETCC &&
56830 Op1.getOperand(0).hasOneUse()) {
56831 SDValue SetCC = Op1.getOperand(0);
56832 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
56833 X86::CondCode NewCC = X86::GetOppositeBranchCondition(CC);
56834 APInt NewImm = Op0C->getAPIntValue() - 1;
56835 SDLoc DL(Op1);
56836 SDValue NewSetCC = getSETCC(NewCC, SetCC.getOperand(1), DL, DAG);
56837 NewSetCC = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NewSetCC);
56838 return DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(VT, VT), NewSetCC,
56839 DAG.getConstant(NewImm, DL, VT));
56842 return SDValue();
56845 static SDValue combineX86CloadCstore(SDNode *N, SelectionDAG &DAG) {
56846 // res, flags2 = sub 0, (setcc cc, flag)
56847 // cload/cstore ..., cond_ne, flag2
56848 // ->
56849 // cload/cstore cc, flag
56850 if (N->getConstantOperandVal(3) != X86::COND_NE)
56851 return SDValue();
56853 SDValue Sub = N->getOperand(4);
56854 if (Sub.getOpcode() != X86ISD::SUB)
56855 return SDValue();
56857 SDValue SetCC = Sub.getOperand(1);
56859 if (!X86::isZeroNode(Sub.getOperand(0)) || SetCC.getOpcode() != X86ISD::SETCC)
56860 return SDValue();
56862 SmallVector<SDValue, 5> Ops(N->op_values());
56863 Ops[3] = SetCC.getOperand(0);
56864 Ops[4] = SetCC.getOperand(1);
56866 return DAG.getMemIntrinsicNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops,
56867 cast<MemSDNode>(N)->getMemoryVT(),
56868 cast<MemSDNode>(N)->getMemOperand());
56871 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
56872 TargetLowering::DAGCombinerInfo &DCI,
56873 const X86Subtarget &Subtarget) {
56874 EVT VT = N->getValueType(0);
56875 SDValue Op0 = N->getOperand(0);
56876 SDValue Op1 = N->getOperand(1);
56877 SDLoc DL(N);
56879 auto IsNonOpaqueConstant = [&](SDValue Op) {
56880 return DAG.isConstantIntBuildVectorOrConstantInt(Op,
56881 /*AllowOpaques*/ false);
56884 // X86 can't encode an immediate LHS of a sub. See if we can push the
56885 // negation into a preceding instruction. If the RHS of the sub is a XOR with
56886 // one use and a constant, invert the immediate, saving one register.
56887 // However, ignore cases where C1 is 0, as those will become a NEG.
56888 // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
56889 if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
56890 !isNullConstant(Op0) && IsNonOpaqueConstant(Op1.getOperand(1)) &&
56891 Op1->hasOneUse()) {
56892 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
56893 DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
56894 SDValue NewAdd =
56895 DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
56896 return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
56899 if (SDValue V = combineSubABS(VT, DL, Op0, Op1, DAG))
56900 return V;
56902 // Try to synthesize horizontal subs from subs of shuffles.
56903 if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
56904 return V;
56906 // Fold SUB(X,ADC(Y,0,W)) -> SBB(X,Y,W)
56907 if (Op1.getOpcode() == X86ISD::ADC && Op1->hasOneUse() &&
56908 X86::isZeroNode(Op1.getOperand(1))) {
56909 assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
56910 return DAG.getNode(X86ISD::SBB, SDLoc(Op1), Op1->getVTList(), Op0,
56911 Op1.getOperand(0), Op1.getOperand(2));
56914 // Fold SUB(X,SBB(Y,Z,W)) -> SUB(ADC(X,Z,W),Y)
56915 // Don't fold to ADC(0,0,W)/SETCC_CARRY pattern which will prevent more folds.
56916 if (Op1.getOpcode() == X86ISD::SBB && Op1->hasOneUse() &&
56917 !(X86::isZeroNode(Op0) && X86::isZeroNode(Op1.getOperand(1)))) {
56918 assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
56919 SDValue ADC = DAG.getNode(X86ISD::ADC, SDLoc(Op1), Op1->getVTList(), Op0,
56920 Op1.getOperand(1), Op1.getOperand(2));
56921 return DAG.getNode(ISD::SUB, DL, VT, ADC.getValue(0), Op1.getOperand(0));
56924 if (SDValue V = combineXorSubCTLZ(N, DL, DAG, Subtarget))
56925 return V;
56927 if (SDValue V = combineAddOrSubToADCOrSBB(N, DL, DAG))
56928 return V;
56930 return combineSubSetcc(N, DAG);
56933 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
56934 const X86Subtarget &Subtarget) {
56935 unsigned Opcode = N->getOpcode();
56936 assert((Opcode == X86ISD::PCMPEQ || Opcode == X86ISD::PCMPGT) &&
56937 "Unknown PCMP opcode");
56939 SDValue LHS = N->getOperand(0);
56940 SDValue RHS = N->getOperand(1);
56941 MVT VT = N->getSimpleValueType(0);
56942 unsigned EltBits = VT.getScalarSizeInBits();
56943 unsigned NumElts = VT.getVectorNumElements();
56944 SDLoc DL(N);
56946 if (LHS == RHS)
56947 return (Opcode == X86ISD::PCMPEQ) ? DAG.getAllOnesConstant(DL, VT)
56948 : DAG.getConstant(0, DL, VT);
56950 // Constant Folding.
56951 // PCMPEQ(X,UNDEF) -> UNDEF
56952 // PCMPGT(X,UNDEF) -> 0
56953 // PCMPGT(UNDEF,X) -> 0
56954 APInt LHSUndefs, RHSUndefs;
56955 SmallVector<APInt> LHSBits, RHSBits;
56956 if (getTargetConstantBitsFromNode(LHS, EltBits, LHSUndefs, LHSBits) &&
56957 getTargetConstantBitsFromNode(RHS, EltBits, RHSUndefs, RHSBits)) {
56958 APInt Ones = APInt::getAllOnes(EltBits);
56959 APInt Zero = APInt::getZero(EltBits);
56960 SmallVector<APInt> Results(NumElts);
56961 for (unsigned I = 0; I != NumElts; ++I) {
56962 if (Opcode == X86ISD::PCMPEQ) {
56963 Results[I] = (LHSBits[I] == RHSBits[I]) ? Ones : Zero;
56964 } else {
56965 bool AnyUndef = LHSUndefs[I] || RHSUndefs[I];
56966 Results[I] = (!AnyUndef && LHSBits[I].sgt(RHSBits[I])) ? Ones : Zero;
56969 if (Opcode == X86ISD::PCMPEQ)
56970 return getConstVector(Results, LHSUndefs | RHSUndefs, VT, DAG, DL);
56971 return getConstVector(Results, VT, DAG, DL);
56974 return SDValue();
56977 // Helper to determine if we can convert an integer comparison to a float
56978 // comparison byt casting the operands.
56979 static std::optional<unsigned>
56980 CastIntSETCCtoFP(MVT VT, ISD::CondCode CC, unsigned NumSignificantBitsLHS,
56981 unsigned NumSignificantBitsRHS) {
56982 MVT SVT = VT.getScalarType();
56983 assert(SVT == MVT::f32 && "Only tested for float so far");
56984 const fltSemantics &Sem = SVT.getFltSemantics();
56985 assert((CC == ISD::SETEQ || CC == ISD::SETGT) &&
56986 "Only PCMPEQ/PCMPGT currently supported");
56988 // TODO: Handle bitcastable integers.
56990 // For cvt + signed compare we need lhs and rhs to be exactly representable as
56991 // a fp value.
56992 unsigned FPPrec = APFloat::semanticsPrecision(Sem);
56993 if (FPPrec >= NumSignificantBitsLHS && FPPrec >= NumSignificantBitsRHS)
56994 return ISD::SINT_TO_FP;
56996 return std::nullopt;
56999 /// Helper that combines an array of subvector ops as if they were the operands
57000 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
57001 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
57002 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
57003 ArrayRef<SDValue> Ops, SelectionDAG &DAG,
57004 TargetLowering::DAGCombinerInfo &DCI,
57005 const X86Subtarget &Subtarget) {
57006 assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
57007 unsigned EltSizeInBits = VT.getScalarSizeInBits();
57009 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
57010 return DAG.getUNDEF(VT);
57012 if (llvm::all_of(Ops, [](SDValue Op) {
57013 return ISD::isBuildVectorAllZeros(Op.getNode());
57015 return getZeroVector(VT, Subtarget, DAG, DL);
57017 SDValue Op0 = Ops[0];
57018 bool IsSplat = llvm::all_equal(Ops);
57019 unsigned NumOps = Ops.size();
57020 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
57021 LLVMContext &Ctx = *DAG.getContext();
57023 // Repeated subvectors.
57024 if (IsSplat &&
57025 (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
57026 // If this broadcast is inserted into both halves, use a larger broadcast.
57027 if (Op0.getOpcode() == X86ISD::VBROADCAST)
57028 return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
57030 // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
57031 if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
57032 (Subtarget.hasAVX2() ||
57033 X86::mayFoldLoadIntoBroadcastFromMem(Op0.getOperand(0),
57034 VT.getScalarType(), Subtarget)))
57035 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
57036 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
57037 Op0.getOperand(0),
57038 DAG.getIntPtrConstant(0, DL)));
57040 // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
57041 if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
57042 (Subtarget.hasAVX2() ||
57043 (EltSizeInBits >= 32 &&
57044 X86::mayFoldLoad(Op0.getOperand(0), Subtarget))) &&
57045 Op0.getOperand(0).getValueType() == VT.getScalarType())
57046 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
57048 // concat_vectors(extract_subvector(broadcast(x)),
57049 // extract_subvector(broadcast(x))) -> broadcast(x)
57050 // concat_vectors(extract_subvector(subv_broadcast(x)),
57051 // extract_subvector(subv_broadcast(x))) -> subv_broadcast(x)
57052 if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57053 Op0.getOperand(0).getValueType() == VT) {
57054 SDValue SrcVec = Op0.getOperand(0);
57055 if (SrcVec.getOpcode() == X86ISD::VBROADCAST ||
57056 SrcVec.getOpcode() == X86ISD::VBROADCAST_LOAD)
57057 return Op0.getOperand(0);
57058 if (SrcVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
57059 Op0.getValueType() == cast<MemSDNode>(SrcVec)->getMemoryVT())
57060 return Op0.getOperand(0);
57063 // concat_vectors(permq(x),permq(x)) -> permq(concat_vectors(x,x))
57064 if (Op0.getOpcode() == X86ISD::VPERMI && Subtarget.useAVX512Regs() &&
57065 !X86::mayFoldLoad(Op0.getOperand(0), Subtarget))
57066 return DAG.getNode(Op0.getOpcode(), DL, VT,
57067 DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
57068 Op0.getOperand(0), Op0.getOperand(0)),
57069 Op0.getOperand(1));
57072 // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
57073 // Only concat of subvector high halves which vperm2x128 is best at.
57074 // TODO: This should go in combineX86ShufflesRecursively eventually.
57075 if (VT.is256BitVector() && NumOps == 2) {
57076 SDValue Src0 = peekThroughBitcasts(Ops[0]);
57077 SDValue Src1 = peekThroughBitcasts(Ops[1]);
57078 if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57079 Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
57080 EVT SrcVT0 = Src0.getOperand(0).getValueType();
57081 EVT SrcVT1 = Src1.getOperand(0).getValueType();
57082 unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
57083 unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
57084 if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
57085 Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
57086 Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
57087 return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
57088 DAG.getBitcast(VT, Src0.getOperand(0)),
57089 DAG.getBitcast(VT, Src1.getOperand(0)),
57090 DAG.getTargetConstant(0x31, DL, MVT::i8));
57095 // Repeated opcode.
57096 // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
57097 // but it currently struggles with different vector widths.
57098 if (llvm::all_of(Ops, [Op0](SDValue Op) {
57099 return Op.getOpcode() == Op0.getOpcode() && Op.hasOneUse();
57100 })) {
57101 auto ConcatSubOperand = [&](EVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
57102 SmallVector<SDValue> Subs;
57103 for (SDValue SubOp : SubOps)
57104 Subs.push_back(SubOp.getOperand(I));
57105 // Attempt to peek through bitcasts and concat the original subvectors.
57106 EVT SubVT = peekThroughBitcasts(Subs[0]).getValueType();
57107 if (SubVT.isSimple() && SubVT.isVector()) {
57108 EVT ConcatVT =
57109 EVT::getVectorVT(*DAG.getContext(), SubVT.getScalarType(),
57110 SubVT.getVectorElementCount() * Subs.size());
57111 for (SDValue &Sub : Subs)
57112 Sub = DAG.getBitcast(SubVT, Sub);
57113 return DAG.getBitcast(
57114 VT, DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, Subs));
57116 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
57118 auto IsConcatFree = [](MVT VT, ArrayRef<SDValue> SubOps, unsigned Op) {
57119 bool AllConstants = true;
57120 bool AllSubs = true;
57121 unsigned VecSize = VT.getSizeInBits();
57122 SDValue BC0 = peekThroughBitcasts(SubOps[0].getOperand(Op));
57123 if (isa<LoadSDNode>(BC0) && all_of(SubOps, [&](SDValue SubOp) {
57124 return BC0 == peekThroughBitcasts(SubOp.getOperand(Op));
57126 return true;
57127 for (unsigned I = 0, E = SubOps.size(); I != E; ++I) {
57128 SDValue BC = peekThroughBitcasts(SubOps[I].getOperand(Op));
57129 unsigned SubSize = BC.getValueSizeInBits();
57130 unsigned EltSize = BC.getScalarValueSizeInBits();
57131 AllConstants &= ISD::isBuildVectorOfConstantSDNodes(BC.getNode()) ||
57132 ISD::isBuildVectorOfConstantFPSDNodes(BC.getNode());
57133 AllSubs &= BC.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57134 BC.getOperand(0).getValueSizeInBits() == VecSize &&
57135 (BC.getConstantOperandVal(1) * EltSize) == (I * SubSize);
57137 return AllConstants || AllSubs;
57140 switch (Op0.getOpcode()) {
57141 case ISD::VECTOR_SHUFFLE: {
57142 if (NumOps == 2 && VT.is256BitVector() &&
57143 (EltSizeInBits >= 32 || Subtarget.hasInt256()) &&
57144 (IsConcatFree(VT, Ops, 0) || IsConcatFree(VT, Ops, 1))) {
57145 int NumSubElts = Op0.getValueType().getVectorNumElements();
57146 SmallVector<int> NewMask;
57147 for (int M : cast<ShuffleVectorSDNode>(Ops[0])->getMask()) {
57148 M = M >= NumSubElts ? M + NumSubElts : M;
57149 NewMask.push_back(M);
57151 for (int M : cast<ShuffleVectorSDNode>(Ops[1])->getMask()) {
57152 if (0 <= M)
57153 M = (M >= NumSubElts ? M + NumSubElts : M) + NumSubElts;
57154 NewMask.push_back(M);
57156 return DAG.getVectorShuffle(VT, DL, ConcatSubOperand(VT, Ops, 0),
57157 ConcatSubOperand(VT, Ops, 1), NewMask);
57159 break;
57161 case X86ISD::VBROADCAST: {
57162 if (!IsSplat && llvm::all_of(Ops, [](SDValue Op) {
57163 return Op.getOperand(0).getValueType().is128BitVector();
57164 })) {
57165 if (VT == MVT::v4f64 || VT == MVT::v4i64)
57166 return DAG.getNode(X86ISD::UNPCKL, DL, VT,
57167 ConcatSubOperand(VT, Ops, 0),
57168 ConcatSubOperand(VT, Ops, 0));
57169 // TODO: Add pseudo v8i32 PSHUFD handling to AVX1Only targets.
57170 if (VT == MVT::v8f32 || (VT == MVT::v8i32 && Subtarget.hasInt256()))
57171 return DAG.getNode(VT == MVT::v8f32 ? X86ISD::VPERMILPI
57172 : X86ISD::PSHUFD,
57173 DL, VT, ConcatSubOperand(VT, Ops, 0),
57174 getV4X86ShuffleImm8ForMask({0, 0, 0, 0}, DL, DAG));
57176 break;
57178 case X86ISD::MOVDDUP:
57179 case X86ISD::MOVSHDUP:
57180 case X86ISD::MOVSLDUP: {
57181 if (!IsSplat)
57182 return DAG.getNode(Op0.getOpcode(), DL, VT,
57183 ConcatSubOperand(VT, Ops, 0));
57184 break;
57186 case X86ISD::SHUFP: {
57187 // Add SHUFPD support if/when necessary.
57188 if (!IsSplat && VT.getScalarType() == MVT::f32 &&
57189 llvm::all_of(Ops, [Op0](SDValue Op) {
57190 return Op.getOperand(2) == Op0.getOperand(2);
57191 })) {
57192 return DAG.getNode(Op0.getOpcode(), DL, VT,
57193 ConcatSubOperand(VT, Ops, 0),
57194 ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57196 break;
57198 case X86ISD::UNPCKH:
57199 case X86ISD::UNPCKL: {
57200 // Don't concatenate build_vector patterns.
57201 if (!IsSplat && EltSizeInBits >= 32 &&
57202 ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57203 (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57204 none_of(Ops, [](SDValue Op) {
57205 return peekThroughBitcasts(Op.getOperand(0)).getOpcode() ==
57206 ISD::SCALAR_TO_VECTOR ||
57207 peekThroughBitcasts(Op.getOperand(1)).getOpcode() ==
57208 ISD::SCALAR_TO_VECTOR;
57209 })) {
57210 return DAG.getNode(Op0.getOpcode(), DL, VT,
57211 ConcatSubOperand(VT, Ops, 0),
57212 ConcatSubOperand(VT, Ops, 1));
57214 break;
57216 case X86ISD::PSHUFHW:
57217 case X86ISD::PSHUFLW:
57218 case X86ISD::PSHUFD:
57219 if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
57220 Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
57221 return DAG.getNode(Op0.getOpcode(), DL, VT,
57222 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57224 [[fallthrough]];
57225 case X86ISD::VPERMILPI:
57226 if (!IsSplat && EltSizeInBits == 32 &&
57227 (VT.is256BitVector() ||
57228 (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57229 all_of(Ops, [&Op0](SDValue Op) {
57230 return Op0.getOperand(1) == Op.getOperand(1);
57231 })) {
57232 MVT FloatVT = VT.changeVectorElementType(MVT::f32);
57233 SDValue Res = DAG.getBitcast(FloatVT, ConcatSubOperand(VT, Ops, 0));
57234 Res =
57235 DAG.getNode(X86ISD::VPERMILPI, DL, FloatVT, Res, Op0.getOperand(1));
57236 return DAG.getBitcast(VT, Res);
57238 if (!IsSplat && NumOps == 2 && VT == MVT::v4f64) {
57239 uint64_t Idx0 = Ops[0].getConstantOperandVal(1);
57240 uint64_t Idx1 = Ops[1].getConstantOperandVal(1);
57241 uint64_t Idx = ((Idx1 & 3) << 2) | (Idx0 & 3);
57242 return DAG.getNode(Op0.getOpcode(), DL, VT,
57243 ConcatSubOperand(VT, Ops, 0),
57244 DAG.getTargetConstant(Idx, DL, MVT::i8));
57246 break;
57247 case X86ISD::PSHUFB:
57248 case X86ISD::PSADBW:
57249 case X86ISD::VPMADDUBSW:
57250 case X86ISD::VPMADDWD:
57251 if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57252 (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
57253 MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57254 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57255 NumOps * SrcVT.getVectorNumElements());
57256 return DAG.getNode(Op0.getOpcode(), DL, VT,
57257 ConcatSubOperand(SrcVT, Ops, 0),
57258 ConcatSubOperand(SrcVT, Ops, 1));
57260 break;
57261 case X86ISD::VPERMV:
57262 if (!IsSplat && NumOps == 2 &&
57263 (VT.is512BitVector() && Subtarget.useAVX512Regs())) {
57264 MVT OpVT = Op0.getSimpleValueType();
57265 int NumSrcElts = OpVT.getVectorNumElements();
57266 SmallVector<int, 64> ConcatMask;
57267 for (unsigned i = 0; i != NumOps; ++i) {
57268 SmallVector<int, 64> SubMask;
57269 SmallVector<SDValue, 2> SubOps;
57270 if (!getTargetShuffleMask(Ops[i], false, SubOps, SubMask))
57271 break;
57272 for (int M : SubMask) {
57273 if (0 <= M)
57274 M += i * NumSrcElts;
57275 ConcatMask.push_back(M);
57278 if (ConcatMask.size() == (NumOps * NumSrcElts)) {
57279 SDValue Src = concatSubVectors(Ops[0].getOperand(1),
57280 Ops[1].getOperand(1), DAG, DL);
57281 MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
57282 MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
57283 SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
57284 return DAG.getNode(X86ISD::VPERMV, DL, VT, Mask, Src);
57287 break;
57288 case X86ISD::VPERMV3:
57289 if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
57290 MVT OpVT = Op0.getSimpleValueType();
57291 int NumSrcElts = OpVT.getVectorNumElements();
57292 SmallVector<int, 64> ConcatMask;
57293 for (unsigned i = 0; i != NumOps; ++i) {
57294 SmallVector<int, 64> SubMask;
57295 SmallVector<SDValue, 2> SubOps;
57296 if (!getTargetShuffleMask(Ops[i], false, SubOps, SubMask))
57297 break;
57298 for (int M : SubMask) {
57299 if (0 <= M) {
57300 int Src = M < NumSrcElts ? 0 : 2;
57301 M += M < NumSrcElts ? 0 : NumSrcElts;
57303 // Reference the lowest sub if they upper sub is the same.
57304 if (Ops[0].getOperand(Src) != Ops[i].getOperand(Src))
57305 M += i * NumSrcElts;
57307 ConcatMask.push_back(M);
57310 if (ConcatMask.size() == (NumOps * NumSrcElts)) {
57311 SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
57312 Ops[1].getOperand(0), DAG, DL);
57313 SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
57314 Ops[1].getOperand(2), DAG, DL);
57315 MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
57316 MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
57317 SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
57318 return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
57321 break;
57322 case X86ISD::VPERM2X128: {
57323 if (!IsSplat && VT.is512BitVector() && Subtarget.useAVX512Regs()) {
57324 assert(NumOps == 2 && "Bad concat_vectors operands");
57325 unsigned Imm0 = Ops[0].getConstantOperandVal(2);
57326 unsigned Imm1 = Ops[1].getConstantOperandVal(2);
57327 // TODO: Handle zero'd subvectors.
57328 if ((Imm0 & 0x88) == 0 && (Imm1 & 0x88) == 0) {
57329 int Mask[4] = {(int)(Imm0 & 0x03), (int)((Imm0 >> 4) & 0x3), (int)(Imm1 & 0x03),
57330 (int)((Imm1 >> 4) & 0x3)};
57331 MVT ShuffleVT = VT.isFloatingPoint() ? MVT::v8f64 : MVT::v8i64;
57332 SDValue LHS = concatSubVectors(Ops[0].getOperand(0),
57333 Ops[0].getOperand(1), DAG, DL);
57334 SDValue RHS = concatSubVectors(Ops[1].getOperand(0),
57335 Ops[1].getOperand(1), DAG, DL);
57336 SDValue Res = DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
57337 DAG.getBitcast(ShuffleVT, LHS),
57338 DAG.getBitcast(ShuffleVT, RHS),
57339 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
57340 return DAG.getBitcast(VT, Res);
57343 break;
57345 case X86ISD::SHUF128: {
57346 if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
57347 unsigned Imm0 = Ops[0].getConstantOperandVal(2);
57348 unsigned Imm1 = Ops[1].getConstantOperandVal(2);
57349 unsigned Imm = ((Imm0 & 1) << 0) | ((Imm0 & 2) << 1) | 0x08 |
57350 ((Imm1 & 1) << 4) | ((Imm1 & 2) << 5) | 0x80;
57351 SDValue LHS = concatSubVectors(Ops[0].getOperand(0),
57352 Ops[0].getOperand(1), DAG, DL);
57353 SDValue RHS = concatSubVectors(Ops[1].getOperand(0),
57354 Ops[1].getOperand(1), DAG, DL);
57355 return DAG.getNode(X86ISD::SHUF128, DL, VT, LHS, RHS,
57356 DAG.getTargetConstant(Imm, DL, MVT::i8));
57358 break;
57360 case ISD::TRUNCATE:
57361 if (!IsSplat && NumOps == 2 && VT.is256BitVector()) {
57362 EVT SrcVT = Ops[0].getOperand(0).getValueType();
57363 if (SrcVT.is256BitVector() && SrcVT.isSimple() &&
57364 SrcVT == Ops[1].getOperand(0).getValueType() &&
57365 Subtarget.useAVX512Regs() &&
57366 Subtarget.getPreferVectorWidth() >= 512 &&
57367 (SrcVT.getScalarSizeInBits() > 16 || Subtarget.useBWIRegs())) {
57368 EVT NewSrcVT = SrcVT.getDoubleNumVectorElementsVT(Ctx);
57369 return DAG.getNode(ISD::TRUNCATE, DL, VT,
57370 ConcatSubOperand(NewSrcVT, Ops, 0));
57373 break;
57374 case ISD::ANY_EXTEND:
57375 case ISD::SIGN_EXTEND:
57376 case ISD::ZERO_EXTEND:
57377 // TODO: Handle ANY_EXTEND combos with SIGN/ZERO_EXTEND.
57378 if (!IsSplat && NumOps == 2 &&
57379 ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57380 (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57381 (EltSizeInBits >= 32 || Subtarget.useBWIRegs())))) {
57382 EVT SrcVT = Ops[0].getOperand(0).getValueType();
57383 if (SrcVT.isSimple() && SrcVT.is128BitVector() &&
57384 SrcVT == Ops[1].getOperand(0).getValueType()) {
57385 EVT NewSrcVT = SrcVT.getDoubleNumVectorElementsVT(Ctx);
57386 return DAG.getNode(Op0.getOpcode(), DL, VT,
57387 ConcatSubOperand(NewSrcVT, Ops, 0));
57390 break;
57391 case X86ISD::VSHLI:
57392 case X86ISD::VSRLI:
57393 // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
57394 // TODO: Move this to LowerShiftByScalarImmediate?
57395 if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
57396 llvm::all_of(Ops, [](SDValue Op) {
57397 return Op.getConstantOperandAPInt(1) == 32;
57398 })) {
57399 SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
57400 SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
57401 if (Op0.getOpcode() == X86ISD::VSHLI) {
57402 Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
57403 {8, 0, 8, 2, 8, 4, 8, 6});
57404 } else {
57405 Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
57406 {1, 8, 3, 8, 5, 8, 7, 8});
57408 return DAG.getBitcast(VT, Res);
57410 [[fallthrough]];
57411 case X86ISD::VSRAI:
57412 case X86ISD::VSHL:
57413 case X86ISD::VSRL:
57414 case X86ISD::VSRA:
57415 if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
57416 (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57417 (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
57418 llvm::all_of(Ops, [Op0](SDValue Op) {
57419 return Op0.getOperand(1) == Op.getOperand(1);
57420 })) {
57421 return DAG.getNode(Op0.getOpcode(), DL, VT,
57422 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57424 break;
57425 case X86ISD::VPERMI:
57426 case X86ISD::VROTLI:
57427 case X86ISD::VROTRI:
57428 if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57429 llvm::all_of(Ops, [Op0](SDValue Op) {
57430 return Op0.getOperand(1) == Op.getOperand(1);
57431 })) {
57432 return DAG.getNode(Op0.getOpcode(), DL, VT,
57433 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
57435 break;
57436 case ISD::AND:
57437 case ISD::OR:
57438 case ISD::XOR:
57439 case X86ISD::ANDNP:
57440 if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57441 (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
57442 return DAG.getNode(Op0.getOpcode(), DL, VT,
57443 ConcatSubOperand(VT, Ops, 0),
57444 ConcatSubOperand(VT, Ops, 1));
57446 break;
57447 case X86ISD::PCMPEQ:
57448 case X86ISD::PCMPGT:
57449 if (!IsSplat && VT.is256BitVector() &&
57450 (Subtarget.hasInt256() || VT == MVT::v8i32) &&
57451 (IsConcatFree(VT, Ops, 0) || IsConcatFree(VT, Ops, 1))) {
57452 if (Subtarget.hasInt256())
57453 return DAG.getNode(Op0.getOpcode(), DL, VT,
57454 ConcatSubOperand(VT, Ops, 0),
57455 ConcatSubOperand(VT, Ops, 1));
57457 // Without AVX2, see if we can cast the values to v8f32 and use fcmp.
57458 // TODO: Handle v4f64 as well?
57459 unsigned MaxSigBitsLHS = 0, MaxSigBitsRHS = 0;
57460 for (unsigned I = 0; I != NumOps; ++I) {
57461 MaxSigBitsLHS =
57462 std::max(MaxSigBitsLHS,
57463 DAG.ComputeMaxSignificantBits(Ops[I].getOperand(0)));
57464 MaxSigBitsRHS =
57465 std::max(MaxSigBitsRHS,
57466 DAG.ComputeMaxSignificantBits(Ops[I].getOperand(1)));
57467 if (MaxSigBitsLHS == EltSizeInBits && MaxSigBitsRHS == EltSizeInBits)
57468 break;
57471 ISD::CondCode ICC =
57472 Op0.getOpcode() == X86ISD::PCMPEQ ? ISD::SETEQ : ISD::SETGT;
57473 ISD::CondCode FCC =
57474 Op0.getOpcode() == X86ISD::PCMPEQ ? ISD::SETOEQ : ISD::SETOGT;
57476 MVT FpSVT = MVT::getFloatingPointVT(EltSizeInBits);
57477 MVT FpVT = VT.changeVectorElementType(FpSVT);
57479 if (std::optional<unsigned> CastOpc =
57480 CastIntSETCCtoFP(FpVT, ICC, MaxSigBitsLHS, MaxSigBitsRHS)) {
57481 SDValue LHS = ConcatSubOperand(VT, Ops, 0);
57482 SDValue RHS = ConcatSubOperand(VT, Ops, 1);
57483 LHS = DAG.getNode(*CastOpc, DL, FpVT, LHS);
57484 RHS = DAG.getNode(*CastOpc, DL, FpVT, RHS);
57486 bool IsAlwaysSignaling;
57487 unsigned FSETCC =
57488 translateX86FSETCC(FCC, LHS, RHS, IsAlwaysSignaling);
57489 return DAG.getBitcast(
57490 VT, DAG.getNode(X86ISD::CMPP, DL, FpVT, LHS, RHS,
57491 DAG.getTargetConstant(FSETCC, DL, MVT::i8)));
57494 break;
57495 case ISD::CTPOP:
57496 case ISD::CTTZ:
57497 case ISD::CTLZ:
57498 case ISD::CTTZ_ZERO_UNDEF:
57499 case ISD::CTLZ_ZERO_UNDEF:
57500 if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57501 (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
57502 return DAG.getNode(Op0.getOpcode(), DL, VT,
57503 ConcatSubOperand(VT, Ops, 0));
57505 break;
57506 case X86ISD::GF2P8AFFINEQB:
57507 if (!IsSplat &&
57508 (VT.is256BitVector() ||
57509 (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57510 llvm::all_of(Ops, [Op0](SDValue Op) {
57511 return Op0.getOperand(2) == Op.getOperand(2);
57512 })) {
57513 return DAG.getNode(Op0.getOpcode(), DL, VT,
57514 ConcatSubOperand(VT, Ops, 0),
57515 ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57517 break;
57518 case ISD::ADD:
57519 case ISD::SUB:
57520 case ISD::MUL:
57521 if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57522 (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
57523 (EltSizeInBits >= 32 || Subtarget.useBWIRegs())))) {
57524 return DAG.getNode(Op0.getOpcode(), DL, VT,
57525 ConcatSubOperand(VT, Ops, 0),
57526 ConcatSubOperand(VT, Ops, 1));
57528 break;
57529 // Due to VADD, VSUB, VMUL can executed on more ports than VINSERT and
57530 // their latency are short, so here we don't replace them unless we won't
57531 // introduce extra VINSERT.
57532 case ISD::FADD:
57533 case ISD::FSUB:
57534 case ISD::FMUL:
57535 if (!IsSplat && (IsConcatFree(VT, Ops, 0) || IsConcatFree(VT, Ops, 1)) &&
57536 (VT.is256BitVector() ||
57537 (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
57538 return DAG.getNode(Op0.getOpcode(), DL, VT,
57539 ConcatSubOperand(VT, Ops, 0),
57540 ConcatSubOperand(VT, Ops, 1));
57542 break;
57543 case ISD::FDIV:
57544 if (!IsSplat && (VT.is256BitVector() ||
57545 (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
57546 return DAG.getNode(Op0.getOpcode(), DL, VT,
57547 ConcatSubOperand(VT, Ops, 0),
57548 ConcatSubOperand(VT, Ops, 1));
57550 break;
57551 case X86ISD::HADD:
57552 case X86ISD::HSUB:
57553 case X86ISD::FHADD:
57554 case X86ISD::FHSUB:
57555 if (!IsSplat && VT.is256BitVector() &&
57556 (VT.isFloatingPoint() || Subtarget.hasInt256())) {
57557 return DAG.getNode(Op0.getOpcode(), DL, VT,
57558 ConcatSubOperand(VT, Ops, 0),
57559 ConcatSubOperand(VT, Ops, 1));
57561 break;
57562 case X86ISD::PACKSS:
57563 case X86ISD::PACKUS:
57564 if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57565 (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
57566 MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
57567 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
57568 NumOps * SrcVT.getVectorNumElements());
57569 return DAG.getNode(Op0.getOpcode(), DL, VT,
57570 ConcatSubOperand(SrcVT, Ops, 0),
57571 ConcatSubOperand(SrcVT, Ops, 1));
57573 break;
57574 case X86ISD::PALIGNR:
57575 if (!IsSplat &&
57576 ((VT.is256BitVector() && Subtarget.hasInt256()) ||
57577 (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
57578 llvm::all_of(Ops, [Op0](SDValue Op) {
57579 return Op0.getOperand(2) == Op.getOperand(2);
57580 })) {
57581 return DAG.getNode(Op0.getOpcode(), DL, VT,
57582 ConcatSubOperand(VT, Ops, 0),
57583 ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
57585 break;
57586 case X86ISD::BLENDI:
57587 if (NumOps == 2 && VT.is512BitVector() && Subtarget.useBWIRegs()) {
57588 uint64_t Mask0 = Ops[0].getConstantOperandVal(2);
57589 uint64_t Mask1 = Ops[1].getConstantOperandVal(2);
57590 // MVT::v16i16 has repeated blend mask.
57591 if (Op0.getSimpleValueType() == MVT::v16i16) {
57592 Mask0 = (Mask0 << 8) | Mask0;
57593 Mask1 = (Mask1 << 8) | Mask1;
57595 uint64_t Mask = (Mask1 << (VT.getVectorNumElements() / 2)) | Mask0;
57596 MVT MaskSVT = MVT::getIntegerVT(VT.getVectorNumElements());
57597 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
57598 SDValue Sel =
57599 DAG.getBitcast(MaskVT, DAG.getConstant(Mask, DL, MaskSVT));
57600 return DAG.getSelect(DL, VT, Sel, ConcatSubOperand(VT, Ops, 1),
57601 ConcatSubOperand(VT, Ops, 0));
57603 break;
57604 case ISD::VSELECT:
57605 if (!IsSplat && Subtarget.hasAVX512() &&
57606 (VT.is256BitVector() ||
57607 (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
57608 (EltSizeInBits >= 32 || Subtarget.hasBWI())) {
57609 EVT SelVT = Ops[0].getOperand(0).getValueType();
57610 if (SelVT.getVectorElementType() == MVT::i1) {
57611 SelVT = EVT::getVectorVT(Ctx, MVT::i1,
57612 NumOps * SelVT.getVectorNumElements());
57613 if (TLI.isTypeLegal(SelVT))
57614 return DAG.getNode(Op0.getOpcode(), DL, VT,
57615 ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
57616 ConcatSubOperand(VT, Ops, 1),
57617 ConcatSubOperand(VT, Ops, 2));
57620 [[fallthrough]];
57621 case X86ISD::BLENDV:
57622 if (!IsSplat && VT.is256BitVector() && NumOps == 2 &&
57623 (EltSizeInBits >= 32 || Subtarget.hasInt256()) &&
57624 IsConcatFree(VT, Ops, 1) && IsConcatFree(VT, Ops, 2)) {
57625 EVT SelVT = Ops[0].getOperand(0).getValueType();
57626 SelVT = SelVT.getDoubleNumVectorElementsVT(Ctx);
57627 if (TLI.isTypeLegal(SelVT))
57628 return DAG.getNode(Op0.getOpcode(), DL, VT,
57629 ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
57630 ConcatSubOperand(VT, Ops, 1),
57631 ConcatSubOperand(VT, Ops, 2));
57633 break;
57637 // Fold subvector loads into one.
57638 // If needed, look through bitcasts to get to the load.
57639 if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
57640 unsigned Fast;
57641 const X86TargetLowering *TLI = Subtarget.getTargetLowering();
57642 if (TLI->allowsMemoryAccess(Ctx, DAG.getDataLayout(), VT,
57643 *FirstLd->getMemOperand(), &Fast) &&
57644 Fast) {
57645 if (SDValue Ld =
57646 EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
57647 return Ld;
57651 // Attempt to fold target constant loads.
57652 if (all_of(Ops, [](SDValue Op) { return getTargetConstantFromNode(Op); })) {
57653 SmallVector<APInt> EltBits;
57654 APInt UndefElts = APInt::getZero(VT.getVectorNumElements());
57655 for (unsigned I = 0; I != NumOps; ++I) {
57656 APInt OpUndefElts;
57657 SmallVector<APInt> OpEltBits;
57658 if (!getTargetConstantBitsFromNode(Ops[I], EltSizeInBits, OpUndefElts,
57659 OpEltBits, /*AllowWholeUndefs*/ true,
57660 /*AllowPartialUndefs*/ false))
57661 break;
57662 EltBits.append(OpEltBits);
57663 UndefElts.insertBits(OpUndefElts, I * OpUndefElts.getBitWidth());
57665 if (EltBits.size() == VT.getVectorNumElements()) {
57666 Constant *C = getConstantVector(VT, EltBits, UndefElts, Ctx);
57667 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
57668 SDValue CV = DAG.getConstantPool(C, PVT);
57669 MachineFunction &MF = DAG.getMachineFunction();
57670 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
57671 SDValue Ld = DAG.getLoad(VT, DL, DAG.getEntryNode(), CV, MPI);
57672 SDValue Sub = extractSubVector(Ld, 0, DAG, DL, Op0.getValueSizeInBits());
57673 DAG.ReplaceAllUsesOfValueWith(Op0, Sub);
57674 return Ld;
57678 // If this simple subvector or scalar/subvector broadcast_load is inserted
57679 // into both halves, use a larger broadcast_load. Update other uses to use
57680 // an extracted subvector.
57681 if (IsSplat &&
57682 (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
57683 if (ISD::isNormalLoad(Op0.getNode()) ||
57684 Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
57685 Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
57686 auto *Mem = cast<MemSDNode>(Op0);
57687 unsigned Opc = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
57688 ? X86ISD::VBROADCAST_LOAD
57689 : X86ISD::SUBV_BROADCAST_LOAD;
57690 if (SDValue BcastLd =
57691 getBROADCAST_LOAD(Opc, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
57692 SDValue BcastSrc =
57693 extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits());
57694 DAG.ReplaceAllUsesOfValueWith(Op0, BcastSrc);
57695 return BcastLd;
57700 // If we're splatting a 128-bit subvector to 512-bits, use SHUF128 directly.
57701 if (IsSplat && NumOps == 4 && VT.is512BitVector() &&
57702 Subtarget.useAVX512Regs()) {
57703 MVT ShuffleVT = VT.isFloatingPoint() ? MVT::v8f64 : MVT::v8i64;
57704 SDValue Res = widenSubVector(Op0, false, Subtarget, DAG, DL, 512);
57705 Res = DAG.getBitcast(ShuffleVT, Res);
57706 Res = DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT, Res, Res,
57707 getV4X86ShuffleImm8ForMask({0, 0, 0, 0}, DL, DAG));
57708 return DAG.getBitcast(VT, Res);
57711 return SDValue();
57714 static SDValue combineCONCAT_VECTORS(SDNode *N, SelectionDAG &DAG,
57715 TargetLowering::DAGCombinerInfo &DCI,
57716 const X86Subtarget &Subtarget) {
57717 EVT VT = N->getValueType(0);
57718 EVT SrcVT = N->getOperand(0).getValueType();
57719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
57720 SmallVector<SDValue, 4> Ops(N->ops());
57722 if (VT.getVectorElementType() == MVT::i1) {
57723 // Attempt to constant fold.
57724 unsigned SubSizeInBits = SrcVT.getSizeInBits();
57725 APInt Constant = APInt::getZero(VT.getSizeInBits());
57726 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
57727 auto *C = dyn_cast<ConstantSDNode>(peekThroughBitcasts(Ops[I]));
57728 if (!C) break;
57729 Constant.insertBits(C->getAPIntValue(), I * SubSizeInBits);
57730 if (I == (E - 1)) {
57731 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
57732 if (TLI.isTypeLegal(IntVT))
57733 return DAG.getBitcast(VT, DAG.getConstant(Constant, SDLoc(N), IntVT));
57737 // Don't do anything else for i1 vectors.
57738 return SDValue();
57741 if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
57742 if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
57743 DCI, Subtarget))
57744 return R;
57747 return SDValue();
57750 static SDValue combineINSERT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
57751 TargetLowering::DAGCombinerInfo &DCI,
57752 const X86Subtarget &Subtarget) {
57753 if (DCI.isBeforeLegalizeOps())
57754 return SDValue();
57756 MVT OpVT = N->getSimpleValueType(0);
57758 bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
57760 SDLoc dl(N);
57761 SDValue Vec = N->getOperand(0);
57762 SDValue SubVec = N->getOperand(1);
57764 uint64_t IdxVal = N->getConstantOperandVal(2);
57765 MVT SubVecVT = SubVec.getSimpleValueType();
57767 if (Vec.isUndef() && SubVec.isUndef())
57768 return DAG.getUNDEF(OpVT);
57770 // Inserting undefs/zeros into zeros/undefs is a zero vector.
57771 if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
57772 (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
57773 return getZeroVector(OpVT, Subtarget, DAG, dl);
57775 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
57776 // If we're inserting into a zero vector and then into a larger zero vector,
57777 // just insert into the larger zero vector directly.
57778 if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
57779 ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
57780 uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
57781 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57782 getZeroVector(OpVT, Subtarget, DAG, dl),
57783 SubVec.getOperand(1),
57784 DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
57787 // If we're inserting into a zero vector and our input was extracted from an
57788 // insert into a zero vector of the same type and the extraction was at
57789 // least as large as the original insertion. Just insert the original
57790 // subvector into a zero vector.
57791 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
57792 isNullConstant(SubVec.getOperand(1)) &&
57793 SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
57794 SDValue Ins = SubVec.getOperand(0);
57795 if (isNullConstant(Ins.getOperand(2)) &&
57796 ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
57797 Ins.getOperand(1).getValueSizeInBits().getFixedValue() <=
57798 SubVecVT.getFixedSizeInBits())
57799 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57800 getZeroVector(OpVT, Subtarget, DAG, dl),
57801 Ins.getOperand(1), N->getOperand(2));
57805 // Stop here if this is an i1 vector.
57806 if (IsI1Vector)
57807 return SDValue();
57809 // Eliminate an intermediate vector widening:
57810 // insert_subvector X, (insert_subvector undef, Y, 0), Idx -->
57811 // insert_subvector X, Y, Idx
57812 // TODO: This is a more general version of a DAGCombiner fold, can we move it
57813 // there?
57814 if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
57815 SubVec.getOperand(0).isUndef() && isNullConstant(SubVec.getOperand(2)))
57816 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Vec,
57817 SubVec.getOperand(1), N->getOperand(2));
57819 // If this is an insert of an extract, combine to a shuffle. Don't do this
57820 // if the insert or extract can be represented with a subregister operation.
57821 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
57822 SubVec.getOperand(0).getSimpleValueType() == OpVT &&
57823 (IdxVal != 0 ||
57824 !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
57825 int ExtIdxVal = SubVec.getConstantOperandVal(1);
57826 if (ExtIdxVal != 0) {
57827 int VecNumElts = OpVT.getVectorNumElements();
57828 int SubVecNumElts = SubVecVT.getVectorNumElements();
57829 SmallVector<int, 64> Mask(VecNumElts);
57830 // First create an identity shuffle mask.
57831 for (int i = 0; i != VecNumElts; ++i)
57832 Mask[i] = i;
57833 // Now insert the extracted portion.
57834 for (int i = 0; i != SubVecNumElts; ++i)
57835 Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
57837 return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
57841 // Match concat_vector style patterns.
57842 SmallVector<SDValue, 2> SubVectorOps;
57843 if (collectConcatOps(N, SubVectorOps, DAG)) {
57844 if (SDValue Fold =
57845 combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
57846 return Fold;
57848 // If we're inserting all zeros into the upper half, change this to
57849 // a concat with zero. We will match this to a move
57850 // with implicit upper bit zeroing during isel.
57851 // We do this here because we don't want combineConcatVectorOps to
57852 // create INSERT_SUBVECTOR from CONCAT_VECTORS.
57853 if (SubVectorOps.size() == 2 &&
57854 ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
57855 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
57856 getZeroVector(OpVT, Subtarget, DAG, dl),
57857 SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
57859 // Attempt to recursively combine to a shuffle.
57860 if (all_of(SubVectorOps, [](SDValue SubOp) {
57861 return isTargetShuffle(SubOp.getOpcode());
57862 })) {
57863 SDValue Op(N, 0);
57864 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
57865 return Res;
57869 // If this is a broadcast insert into an upper undef, use a larger broadcast.
57870 if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
57871 return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
57873 // If this is a broadcast load inserted into an upper undef, use a larger
57874 // broadcast load.
57875 if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
57876 SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
57877 auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
57878 SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
57879 SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
57880 SDValue BcastLd =
57881 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
57882 MemIntr->getMemoryVT(),
57883 MemIntr->getMemOperand());
57884 DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
57885 return BcastLd;
57888 // If we're splatting the lower half subvector of a full vector load into the
57889 // upper half, attempt to create a subvector broadcast.
57890 if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
57891 Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
57892 auto *VecLd = dyn_cast<LoadSDNode>(Vec);
57893 auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
57894 if (VecLd && SubLd &&
57895 DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
57896 SubVec.getValueSizeInBits() / 8, 0))
57897 return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
57898 SubLd, 0, DAG);
57901 return SDValue();
57904 /// If we are extracting a subvector of a vector select and the select condition
57905 /// is composed of concatenated vectors, try to narrow the select width. This
57906 /// is a common pattern for AVX1 integer code because 256-bit selects may be
57907 /// legal, but there is almost no integer math/logic available for 256-bit.
57908 /// This function should only be called with legal types (otherwise, the calls
57909 /// to get simple value types will assert).
57910 static SDValue narrowExtractedVectorSelect(SDNode *Ext, const SDLoc &DL,
57911 SelectionDAG &DAG) {
57912 SDValue Sel = Ext->getOperand(0);
57913 if (Sel.getOpcode() != ISD::VSELECT ||
57914 !isFreeToSplitVector(Sel.getOperand(0).getNode(), DAG))
57915 return SDValue();
57917 // Note: We assume simple value types because this should only be called with
57918 // legal operations/types.
57919 // TODO: This can be extended to handle extraction to 256-bits.
57920 MVT VT = Ext->getSimpleValueType(0);
57921 if (!VT.is128BitVector())
57922 return SDValue();
57924 MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
57925 if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
57926 return SDValue();
57928 MVT WideVT = Ext->getOperand(0).getSimpleValueType();
57929 MVT SelVT = Sel.getSimpleValueType();
57930 assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
57931 "Unexpected vector type with legal operations");
57933 unsigned SelElts = SelVT.getVectorNumElements();
57934 unsigned CastedElts = WideVT.getVectorNumElements();
57935 unsigned ExtIdx = Ext->getConstantOperandVal(1);
57936 if (SelElts % CastedElts == 0) {
57937 // The select has the same or more (narrower) elements than the extract
57938 // operand. The extraction index gets scaled by that factor.
57939 ExtIdx *= (SelElts / CastedElts);
57940 } else if (CastedElts % SelElts == 0) {
57941 // The select has less (wider) elements than the extract operand. Make sure
57942 // that the extraction index can be divided evenly.
57943 unsigned IndexDivisor = CastedElts / SelElts;
57944 if (ExtIdx % IndexDivisor != 0)
57945 return SDValue();
57946 ExtIdx /= IndexDivisor;
57947 } else {
57948 llvm_unreachable("Element count of simple vector types are not divisible?");
57951 unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
57952 unsigned NarrowElts = SelElts / NarrowingFactor;
57953 MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
57954 SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
57955 SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
57956 SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
57957 SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
57958 return DAG.getBitcast(VT, NarrowSel);
57961 static SDValue combineEXTRACT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
57962 TargetLowering::DAGCombinerInfo &DCI,
57963 const X86Subtarget &Subtarget) {
57964 // For AVX1 only, if we are extracting from a 256-bit and+not (which will
57965 // eventually get combined/lowered into ANDNP) with a concatenated operand,
57966 // split the 'and' into 128-bit ops to avoid the concatenate and extract.
57967 // We let generic combining take over from there to simplify the
57968 // insert/extract and 'not'.
57969 // This pattern emerges during AVX1 legalization. We handle it before lowering
57970 // to avoid complications like splitting constant vector loads.
57972 // Capture the original wide type in the likely case that we need to bitcast
57973 // back to this type.
57974 if (!N->getValueType(0).isSimple())
57975 return SDValue();
57977 MVT VT = N->getSimpleValueType(0);
57978 SDValue InVec = N->getOperand(0);
57979 unsigned IdxVal = N->getConstantOperandVal(1);
57980 SDValue InVecBC = peekThroughBitcasts(InVec);
57981 EVT InVecVT = InVec.getValueType();
57982 unsigned SizeInBits = VT.getSizeInBits();
57983 unsigned InSizeInBits = InVecVT.getSizeInBits();
57984 unsigned NumSubElts = VT.getVectorNumElements();
57985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
57986 SDLoc DL(N);
57988 if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
57989 TLI.isTypeLegal(InVecVT) &&
57990 InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
57991 auto isConcatenatedNot = [](SDValue V) {
57992 V = peekThroughBitcasts(V);
57993 if (!isBitwiseNot(V))
57994 return false;
57995 SDValue NotOp = V->getOperand(0);
57996 return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
57998 if (isConcatenatedNot(InVecBC.getOperand(0)) ||
57999 isConcatenatedNot(InVecBC.getOperand(1))) {
58000 // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
58001 SDValue Concat = splitVectorIntBinary(InVecBC, DAG, SDLoc(InVecBC));
58002 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT,
58003 DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
58007 if (DCI.isBeforeLegalizeOps())
58008 return SDValue();
58010 if (SDValue V = narrowExtractedVectorSelect(N, DL, DAG))
58011 return V;
58013 if (ISD::isBuildVectorAllZeros(InVec.getNode()))
58014 return getZeroVector(VT, Subtarget, DAG, DL);
58016 if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
58017 if (VT.getScalarType() == MVT::i1)
58018 return DAG.getConstant(1, DL, VT);
58019 return getOnesVector(VT, DAG, DL);
58022 if (InVec.getOpcode() == ISD::BUILD_VECTOR)
58023 return DAG.getBuildVector(VT, DL, InVec->ops().slice(IdxVal, NumSubElts));
58025 // EXTRACT_SUBVECTOR(EXTRACT_SUBVECTOR(V,C1)),C2) - EXTRACT_SUBVECTOR(V,C1+C2)
58026 if (IdxVal != 0 && InVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
58027 InVec.hasOneUse() && TLI.isTypeLegal(VT) &&
58028 TLI.isTypeLegal(InVec.getOperand(0).getValueType())) {
58029 unsigned NewIdx = IdxVal + InVec.getConstantOperandVal(1);
58030 return extractSubVector(InVec.getOperand(0), NewIdx, DAG, DL, SizeInBits);
58033 // If we are extracting from an insert into a larger vector, replace with a
58034 // smaller insert if we don't access less than the original subvector. Don't
58035 // do this for i1 vectors.
58036 // TODO: Relax the matching indices requirement?
58037 if (VT.getVectorElementType() != MVT::i1 &&
58038 InVec.getOpcode() == ISD::INSERT_SUBVECTOR && InVec.hasOneUse() &&
58039 IdxVal == InVec.getConstantOperandVal(2) &&
58040 InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
58041 SDValue NewExt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT,
58042 InVec.getOperand(0), N->getOperand(1));
58043 unsigned NewIdxVal = InVec.getConstantOperandVal(2) - IdxVal;
58044 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, NewExt,
58045 InVec.getOperand(1),
58046 DAG.getVectorIdxConstant(NewIdxVal, DL));
58049 // If we're extracting an upper subvector from a broadcast we should just
58050 // extract the lowest subvector instead which should allow
58051 // SimplifyDemandedVectorElts do more simplifications.
58052 if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
58053 InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
58054 DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
58055 return extractSubVector(InVec, 0, DAG, DL, SizeInBits);
58057 // If we're extracting a broadcasted subvector, just use the lowest subvector.
58058 if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
58059 cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
58060 return extractSubVector(InVec, 0, DAG, DL, SizeInBits);
58062 // Attempt to extract from the source of a shuffle vector.
58063 if ((InSizeInBits % SizeInBits) == 0 && (IdxVal % NumSubElts) == 0) {
58064 SmallVector<int, 32> ShuffleMask;
58065 SmallVector<int, 32> ScaledMask;
58066 SmallVector<SDValue, 2> ShuffleInputs;
58067 unsigned NumSubVecs = InSizeInBits / SizeInBits;
58068 // Decode the shuffle mask and scale it so its shuffling subvectors.
58069 if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
58070 scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
58071 unsigned SubVecIdx = IdxVal / NumSubElts;
58072 if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
58073 return DAG.getUNDEF(VT);
58074 if (ScaledMask[SubVecIdx] == SM_SentinelZero)
58075 return getZeroVector(VT, Subtarget, DAG, DL);
58076 SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
58077 if (Src.getValueSizeInBits() == InSizeInBits) {
58078 unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
58079 unsigned SrcEltIdx = SrcSubVecIdx * NumSubElts;
58080 return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
58081 DL, SizeInBits);
58086 auto IsExtractFree = [](SDValue V) {
58087 if (V.hasOneUse()) {
58088 V = peekThroughOneUseBitcasts(V);
58089 if (V.getOpcode() == ISD::LOAD)
58090 return true;
58092 V = peekThroughBitcasts(V);
58093 if (ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
58094 return true;
58095 if (ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()))
58096 return true;
58097 return V.isUndef();
58100 // If we're extracting the lowest subvector and we're the only user,
58101 // we may be able to perform this with a smaller vector width.
58102 unsigned InOpcode = InVec.getOpcode();
58103 if (InVec.hasOneUse()) {
58104 if (IdxVal == 0 && VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
58105 // v2f64 CVTDQ2PD(v4i32).
58106 if (InOpcode == ISD::SINT_TO_FP &&
58107 InVec.getOperand(0).getValueType() == MVT::v4i32) {
58108 return DAG.getNode(X86ISD::CVTSI2P, DL, VT, InVec.getOperand(0));
58110 // v2f64 CVTUDQ2PD(v4i32).
58111 if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
58112 InVec.getOperand(0).getValueType() == MVT::v4i32) {
58113 return DAG.getNode(X86ISD::CVTUI2P, DL, VT, InVec.getOperand(0));
58115 // v2f64 CVTPS2PD(v4f32).
58116 if (InOpcode == ISD::FP_EXTEND &&
58117 InVec.getOperand(0).getValueType() == MVT::v4f32) {
58118 return DAG.getNode(X86ISD::VFPEXT, DL, VT, InVec.getOperand(0));
58121 // v4i32 CVTPS2DQ(v4f32) / CVTPS2UDQ(v4f32).
58122 // v4f32 CVTDQ2PS(v4i32) / CVTUDQ2PS(v4i32).
58123 if ((InOpcode == ISD::FP_TO_SINT || InOpcode == ISD::SINT_TO_FP ||
58124 ((InOpcode == ISD::FP_TO_UINT || InOpcode == ISD::UINT_TO_FP) &&
58125 Subtarget.hasVLX())) &&
58126 (VT == MVT::v4i32 || VT == MVT::v4f32)) {
58127 SDValue Src = InVec.getOperand(0);
58128 if (Src.getValueType().getScalarSizeInBits() == 32)
58129 return DAG.getNode(InOpcode, DL, VT,
58130 extractSubVector(Src, IdxVal, DAG, DL, SizeInBits));
58132 if (IdxVal == 0 &&
58133 (ISD::isExtOpcode(InOpcode) || ISD::isExtVecInRegOpcode(InOpcode)) &&
58134 (SizeInBits == 128 || SizeInBits == 256) &&
58135 InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
58136 SDValue Ext = InVec.getOperand(0);
58137 if (Ext.getValueSizeInBits() > SizeInBits)
58138 Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
58139 unsigned ExtOp = DAG.getOpcode_EXTEND_VECTOR_INREG(InOpcode);
58140 return DAG.getNode(ExtOp, DL, VT, Ext);
58142 if (IdxVal == 0 && InOpcode == ISD::VSELECT &&
58143 InVec.getOperand(0).getValueType().is256BitVector() &&
58144 InVec.getOperand(1).getValueType().is256BitVector() &&
58145 InVec.getOperand(2).getValueType().is256BitVector()) {
58146 SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
58147 SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
58148 SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
58149 return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
58151 if (IdxVal == 0 && InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
58152 (SizeInBits == 128 || SizeInBits == 256)) {
58153 SDValue InVecSrc = InVec.getOperand(0);
58154 unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
58155 SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
58156 return DAG.getNode(InOpcode, DL, VT, Ext);
58159 if (SizeInBits == 128 || SizeInBits == 256) {
58160 switch (InOpcode) {
58161 case X86ISD::MOVDDUP:
58162 return DAG.getNode(
58163 InOpcode, DL, VT,
58164 extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits));
58165 case X86ISD::PCMPEQ:
58166 case X86ISD::PCMPGT:
58167 case X86ISD::UNPCKH:
58168 case X86ISD::UNPCKL:
58169 if (IsExtractFree(InVec.getOperand(0)) ||
58170 IsExtractFree(InVec.getOperand(1)))
58171 return DAG.getNode(InOpcode, DL, VT,
58172 extractSubVector(InVec.getOperand(0), IdxVal, DAG,
58173 DL, SizeInBits),
58174 extractSubVector(InVec.getOperand(1), IdxVal, DAG,
58175 DL, SizeInBits));
58176 break;
58177 case X86ISD::CMPP:
58178 if (IsExtractFree(InVec.getOperand(0)) ||
58179 IsExtractFree(InVec.getOperand(1)))
58180 return DAG.getNode(InOpcode, DL, VT,
58181 extractSubVector(InVec.getOperand(0), IdxVal, DAG,
58182 DL, SizeInBits),
58183 extractSubVector(InVec.getOperand(1), IdxVal, DAG,
58184 DL, SizeInBits),
58185 InVec.getOperand(2));
58186 break;
58187 case X86ISD::BLENDI:
58188 if (IsExtractFree(InVec.getOperand(0)) ||
58189 IsExtractFree(InVec.getOperand(1))) {
58190 uint64_t M = InVec.getConstantOperandVal(2) & 255;
58191 M = VT.getScalarType() == MVT::i16 ? M : (M >> IdxVal);
58192 return DAG.getNode(InOpcode, DL, VT,
58193 extractSubVector(InVec.getOperand(0), IdxVal, DAG,
58194 DL, SizeInBits),
58195 extractSubVector(InVec.getOperand(1), IdxVal, DAG,
58196 DL, SizeInBits),
58197 DAG.getTargetConstant(M, DL, MVT::i8));
58199 break;
58200 case X86ISD::VPERMV3:
58201 if (IdxVal != 0) {
58202 SDValue Src0 = InVec.getOperand(0);
58203 SDValue Mask = InVec.getOperand(1);
58204 SDValue Src1 = InVec.getOperand(2);
58205 Mask = extractSubVector(Mask, IdxVal, DAG, DL, SizeInBits);
58206 Mask = widenSubVector(Mask, /*ZeroNewElements=*/false, Subtarget, DAG,
58207 DL, InSizeInBits);
58208 SDValue Shuffle =
58209 DAG.getNode(InOpcode, DL, InVecVT, Src0, Mask, Src1);
58210 return extractSubVector(Shuffle, 0, DAG, DL, SizeInBits);
58212 break;
58217 // Always split vXi64 logical shifts where we're extracting the upper 32-bits
58218 // as this is very likely to fold into a shuffle/truncation.
58219 if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
58220 InVecVT.getScalarSizeInBits() == 64 &&
58221 InVec.getConstantOperandAPInt(1) == 32) {
58222 SDValue Ext =
58223 extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
58224 return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
58227 return SDValue();
58230 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG,
58231 const X86Subtarget &Subtarget) {
58232 EVT VT = N->getValueType(0);
58233 SDValue Src = N->getOperand(0);
58234 SDLoc DL(N);
58236 // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
58237 // This occurs frequently in our masked scalar intrinsic code and our
58238 // floating point select lowering with AVX512.
58239 // TODO: SimplifyDemandedBits instead?
58240 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse() &&
58241 isOneConstant(Src.getOperand(1)))
58242 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Src.getOperand(0));
58244 // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
58245 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
58246 Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
58247 Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
58248 isNullConstant(Src.getOperand(1)))
58249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
58250 Src.getOperand(1));
58252 // Reduce v2i64 to v4i32 if we don't need the upper bits or are known zero.
58253 // TODO: Move to DAGCombine/SimplifyDemandedBits?
58254 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && Src.hasOneUse()) {
58255 auto IsExt64 = [&DAG](SDValue Op, bool IsZeroExt) {
58256 if (Op.getValueType() != MVT::i64)
58257 return SDValue();
58258 unsigned Opc = IsZeroExt ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND;
58259 if (Op.getOpcode() == Opc &&
58260 Op.getOperand(0).getScalarValueSizeInBits() <= 32)
58261 return Op.getOperand(0);
58262 unsigned Ext = IsZeroExt ? ISD::ZEXTLOAD : ISD::EXTLOAD;
58263 if (auto *Ld = dyn_cast<LoadSDNode>(Op))
58264 if (Ld->getExtensionType() == Ext &&
58265 Ld->getMemoryVT().getScalarSizeInBits() <= 32)
58266 return Op;
58267 if (IsZeroExt) {
58268 KnownBits Known = DAG.computeKnownBits(Op);
58269 if (!Known.isConstant() && Known.countMinLeadingZeros() >= 32)
58270 return Op;
58272 return SDValue();
58275 if (SDValue AnyExt = IsExt64(peekThroughOneUseBitcasts(Src), false))
58276 return DAG.getBitcast(
58277 VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
58278 DAG.getAnyExtOrTrunc(AnyExt, DL, MVT::i32)));
58280 if (SDValue ZeroExt = IsExt64(peekThroughOneUseBitcasts(Src), true))
58281 return DAG.getBitcast(
58283 DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32,
58284 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
58285 DAG.getZExtOrTrunc(ZeroExt, DL, MVT::i32))));
58288 // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
58289 if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
58290 Src.getOperand(0).getValueType() == MVT::x86mmx)
58291 return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
58293 // See if we're broadcasting the scalar value, in which case just reuse that.
58294 // Ensure the same SDValue from the SDNode use is being used.
58295 if (VT.getScalarType() == Src.getValueType())
58296 for (SDNode *User : Src->uses())
58297 if (User->getOpcode() == X86ISD::VBROADCAST &&
58298 Src == User->getOperand(0)) {
58299 unsigned SizeInBits = VT.getFixedSizeInBits();
58300 unsigned BroadcastSizeInBits =
58301 User->getValueSizeInBits(0).getFixedValue();
58302 if (BroadcastSizeInBits == SizeInBits)
58303 return SDValue(User, 0);
58304 if (BroadcastSizeInBits > SizeInBits)
58305 return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
58306 // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
58307 // coverage.
58310 // Check for cases where we've ended up with a scalarized shift, typically
58311 // during type legalization.
58312 switch (Src.getOpcode()) {
58313 case ISD::SHL:
58314 case ISD::SRL:
58315 case ISD::SRA:
58316 if (auto *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {
58317 if (supportedVectorShiftWithImm(VT, Subtarget, Src.getOpcode()) &&
58318 Src.hasOneUse()) {
58319 SDValue SrcVec =
58320 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Src.getOperand(0));
58321 unsigned Opc = getTargetVShiftUniformOpcode(Src.getOpcode(), false);
58322 return getTargetVShiftByConstNode(Opc, DL, VT.getSimpleVT(), SrcVec,
58323 Amt->getZExtValue(), DAG);
58326 break;
58327 case ISD::FSHL:
58328 case ISD::FSHR:
58329 if (auto *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(2))) {
58330 if (supportedVectorShiftWithImm(VT, Subtarget, ISD::SHL) &&
58331 Src.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
58332 Src.getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
58333 Src.hasOneUse()) {
58334 uint64_t AmtVal =
58335 Amt->getAPIntValue().urem(Src.getScalarValueSizeInBits());
58336 SDValue SrcVec0 =
58337 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Src.getOperand(0));
58338 SDValue SrcVec1 =
58339 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Src.getOperand(1));
58340 return DAG.getNode(Src.getOpcode(), DL, VT, SrcVec0, SrcVec1,
58341 DAG.getConstant(AmtVal, DL, VT));
58344 break;
58347 return SDValue();
58350 // Simplify PMULDQ and PMULUDQ operations.
58351 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
58352 TargetLowering::DAGCombinerInfo &DCI,
58353 const X86Subtarget &Subtarget) {
58354 SDValue LHS = N->getOperand(0);
58355 SDValue RHS = N->getOperand(1);
58357 // Canonicalize constant to RHS.
58358 if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
58359 !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
58360 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
58362 // Multiply by zero.
58363 // Don't return RHS as it may contain UNDEFs.
58364 if (ISD::isBuildVectorAllZeros(RHS.getNode()))
58365 return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
58367 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
58368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58369 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(64), DCI))
58370 return SDValue(N, 0);
58372 // If the input is an extend_invec and the SimplifyDemandedBits call didn't
58373 // convert it to any_extend_invec, due to the LegalOperations check, do the
58374 // conversion directly to a vector shuffle manually. This exposes combine
58375 // opportunities missed by combineEXTEND_VECTOR_INREG not calling
58376 // combineX86ShufflesRecursively on SSE4.1 targets.
58377 // FIXME: This is basically a hack around several other issues related to
58378 // ANY_EXTEND_VECTOR_INREG.
58379 if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
58380 (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
58381 LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
58382 LHS.getOperand(0).getValueType() == MVT::v4i32) {
58383 SDLoc dl(N);
58384 LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
58385 LHS.getOperand(0), { 0, -1, 1, -1 });
58386 LHS = DAG.getBitcast(MVT::v2i64, LHS);
58387 return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
58389 if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
58390 (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
58391 RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
58392 RHS.getOperand(0).getValueType() == MVT::v4i32) {
58393 SDLoc dl(N);
58394 RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
58395 RHS.getOperand(0), { 0, -1, 1, -1 });
58396 RHS = DAG.getBitcast(MVT::v2i64, RHS);
58397 return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
58400 return SDValue();
58403 // Simplify VPMADDUBSW/VPMADDWD operations.
58404 static SDValue combineVPMADD(SDNode *N, SelectionDAG &DAG,
58405 TargetLowering::DAGCombinerInfo &DCI) {
58406 MVT VT = N->getSimpleValueType(0);
58407 SDValue LHS = N->getOperand(0);
58408 SDValue RHS = N->getOperand(1);
58409 unsigned Opc = N->getOpcode();
58410 bool IsPMADDWD = Opc == X86ISD::VPMADDWD;
58411 assert((Opc == X86ISD::VPMADDWD || Opc == X86ISD::VPMADDUBSW) &&
58412 "Unexpected PMADD opcode");
58414 // Multiply by zero.
58415 // Don't return LHS/RHS as it may contain UNDEFs.
58416 if (ISD::isBuildVectorAllZeros(LHS.getNode()) ||
58417 ISD::isBuildVectorAllZeros(RHS.getNode()))
58418 return DAG.getConstant(0, SDLoc(N), VT);
58420 // Constant folding.
58421 APInt LHSUndefs, RHSUndefs;
58422 SmallVector<APInt> LHSBits, RHSBits;
58423 unsigned SrcEltBits = LHS.getScalarValueSizeInBits();
58424 unsigned DstEltBits = VT.getScalarSizeInBits();
58425 if (getTargetConstantBitsFromNode(LHS, SrcEltBits, LHSUndefs, LHSBits) &&
58426 getTargetConstantBitsFromNode(RHS, SrcEltBits, RHSUndefs, RHSBits)) {
58427 SmallVector<APInt> Result;
58428 for (unsigned I = 0, E = LHSBits.size(); I != E; I += 2) {
58429 APInt LHSLo = LHSBits[I + 0], LHSHi = LHSBits[I + 1];
58430 APInt RHSLo = RHSBits[I + 0], RHSHi = RHSBits[I + 1];
58431 LHSLo = IsPMADDWD ? LHSLo.sext(DstEltBits) : LHSLo.zext(DstEltBits);
58432 LHSHi = IsPMADDWD ? LHSHi.sext(DstEltBits) : LHSHi.zext(DstEltBits);
58433 APInt Lo = LHSLo * RHSLo.sext(DstEltBits);
58434 APInt Hi = LHSHi * RHSHi.sext(DstEltBits);
58435 APInt Res = IsPMADDWD ? (Lo + Hi) : Lo.sadd_sat(Hi);
58436 Result.push_back(Res);
58438 return getConstVector(Result, VT, DAG, SDLoc(N));
58441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58442 APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
58443 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
58444 return SDValue(N, 0);
58446 return SDValue();
58449 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
58450 TargetLowering::DAGCombinerInfo &DCI,
58451 const X86Subtarget &Subtarget) {
58452 EVT VT = N->getValueType(0);
58453 SDValue In = N->getOperand(0);
58454 unsigned Opcode = N->getOpcode();
58455 unsigned InOpcode = In.getOpcode();
58456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58457 SDLoc DL(N);
58459 // Try to merge vector loads and extend_inreg to an extload.
58460 if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
58461 In.hasOneUse()) {
58462 auto *Ld = cast<LoadSDNode>(In);
58463 if (Ld->isSimple()) {
58464 MVT SVT = In.getSimpleValueType().getVectorElementType();
58465 ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
58466 ? ISD::SEXTLOAD
58467 : ISD::ZEXTLOAD;
58468 EVT MemVT = VT.changeVectorElementType(SVT);
58469 if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
58470 SDValue Load = DAG.getExtLoad(
58471 Ext, DL, VT, Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
58472 MemVT, Ld->getOriginalAlign(), Ld->getMemOperand()->getFlags());
58473 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
58474 return Load;
58479 // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
58480 if (Opcode == InOpcode)
58481 return DAG.getNode(Opcode, DL, VT, In.getOperand(0));
58483 // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
58484 // -> EXTEND_VECTOR_INREG(X).
58485 // TODO: Handle non-zero subvector indices.
58486 if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
58487 In.getOperand(0).getOpcode() == DAG.getOpcode_EXTEND(Opcode) &&
58488 In.getOperand(0).getOperand(0).getValueSizeInBits() ==
58489 In.getValueSizeInBits())
58490 return DAG.getNode(Opcode, DL, VT, In.getOperand(0).getOperand(0));
58492 // Fold EXTEND_VECTOR_INREG(BUILD_VECTOR(X,Y,?,?)) -> BUILD_VECTOR(X,0,Y,0).
58493 // TODO: Move to DAGCombine?
58494 if (!DCI.isBeforeLegalizeOps() && Opcode == ISD::ZERO_EXTEND_VECTOR_INREG &&
58495 In.getOpcode() == ISD::BUILD_VECTOR && In.hasOneUse() &&
58496 In.getValueSizeInBits() == VT.getSizeInBits()) {
58497 unsigned NumElts = VT.getVectorNumElements();
58498 unsigned Scale = VT.getScalarSizeInBits() / In.getScalarValueSizeInBits();
58499 EVT EltVT = In.getOperand(0).getValueType();
58500 SmallVector<SDValue> Elts(Scale * NumElts, DAG.getConstant(0, DL, EltVT));
58501 for (unsigned I = 0; I != NumElts; ++I)
58502 Elts[I * Scale] = In.getOperand(I);
58503 return DAG.getBitcast(VT, DAG.getBuildVector(In.getValueType(), DL, Elts));
58506 // Attempt to combine as a shuffle on SSE41+ targets.
58507 if (Subtarget.hasSSE41()) {
58508 SDValue Op(N, 0);
58509 if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
58510 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
58511 return Res;
58514 return SDValue();
58517 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
58518 TargetLowering::DAGCombinerInfo &DCI) {
58519 EVT VT = N->getValueType(0);
58521 if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
58522 return DAG.getConstant(0, SDLoc(N), VT);
58524 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58525 APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
58526 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
58527 return SDValue(N, 0);
58529 return SDValue();
58532 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
58533 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
58534 // extra instructions between the conversion due to going to scalar and back.
58535 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
58536 const X86Subtarget &Subtarget) {
58537 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
58538 return SDValue();
58540 if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
58541 return SDValue();
58543 if (N->getValueType(0) != MVT::f32 ||
58544 N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
58545 return SDValue();
58547 SDLoc dl(N);
58548 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
58549 N->getOperand(0).getOperand(0));
58550 Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
58551 DAG.getTargetConstant(4, dl, MVT::i32));
58552 Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
58553 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
58554 DAG.getIntPtrConstant(0, dl));
58557 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
58558 TargetLowering::DAGCombinerInfo &DCI,
58559 const X86Subtarget &Subtarget) {
58560 EVT VT = N->getValueType(0);
58561 bool IsStrict = N->isStrictFPOpcode();
58562 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
58563 EVT SrcVT = Src.getValueType();
58565 SDLoc dl(N);
58566 if (SrcVT.getScalarType() == MVT::bf16) {
58567 if (DCI.isAfterLegalizeDAG() && Src.getOpcode() == ISD::FP_ROUND &&
58568 !IsStrict && Src.getOperand(0).getValueType() == VT)
58569 return Src.getOperand(0);
58571 if (!SrcVT.isVector())
58572 return SDValue();
58574 assert(!IsStrict && "Strict FP doesn't support BF16");
58575 if (VT.getVectorElementType() == MVT::f64) {
58576 EVT TmpVT = VT.changeVectorElementType(MVT::f32);
58577 return DAG.getNode(ISD::FP_EXTEND, dl, VT,
58578 DAG.getNode(ISD::FP_EXTEND, dl, TmpVT, Src));
58580 assert(VT.getVectorElementType() == MVT::f32 && "Unexpected fpext");
58581 EVT NVT = SrcVT.changeVectorElementType(MVT::i32);
58582 Src = DAG.getBitcast(SrcVT.changeTypeToInteger(), Src);
58583 Src = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Src);
58584 Src = DAG.getNode(ISD::SHL, dl, NVT, Src, DAG.getConstant(16, dl, NVT));
58585 return DAG.getBitcast(VT, Src);
58588 if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
58589 return SDValue();
58591 if (Subtarget.hasFP16())
58592 return SDValue();
58594 if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
58595 return SDValue();
58597 if (VT.getVectorElementType() != MVT::f32 &&
58598 VT.getVectorElementType() != MVT::f64)
58599 return SDValue();
58601 unsigned NumElts = VT.getVectorNumElements();
58602 if (NumElts == 1 || !isPowerOf2_32(NumElts))
58603 return SDValue();
58605 // Convert the input to vXi16.
58606 EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
58607 Src = DAG.getBitcast(IntVT, Src);
58609 // Widen to at least 8 input elements.
58610 if (NumElts < 8) {
58611 unsigned NumConcats = 8 / NumElts;
58612 SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
58613 : DAG.getConstant(0, dl, IntVT);
58614 SmallVector<SDValue, 4> Ops(NumConcats, Fill);
58615 Ops[0] = Src;
58616 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
58619 // Destination is vXf32 with at least 4 elements.
58620 EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
58621 std::max(4U, NumElts));
58622 SDValue Cvt, Chain;
58623 if (IsStrict) {
58624 Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
58625 {N->getOperand(0), Src});
58626 Chain = Cvt.getValue(1);
58627 } else {
58628 Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
58631 if (NumElts < 4) {
58632 assert(NumElts == 2 && "Unexpected size");
58633 Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
58634 DAG.getIntPtrConstant(0, dl));
58637 if (IsStrict) {
58638 // Extend to the original VT if necessary.
58639 if (Cvt.getValueType() != VT) {
58640 Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
58641 {Chain, Cvt});
58642 Chain = Cvt.getValue(1);
58644 return DAG.getMergeValues({Cvt, Chain}, dl);
58647 // Extend to the original VT if necessary.
58648 return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
58651 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
58652 // from. Limit this to cases where the loads have the same input chain and the
58653 // output chains are unused. This avoids any memory ordering issues.
58654 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
58655 TargetLowering::DAGCombinerInfo &DCI) {
58656 assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
58657 N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
58658 "Unknown broadcast load type");
58660 // Only do this if the chain result is unused.
58661 if (N->hasAnyUseOfValue(1))
58662 return SDValue();
58664 auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
58666 SDValue Ptr = MemIntrin->getBasePtr();
58667 SDValue Chain = MemIntrin->getChain();
58668 EVT VT = N->getSimpleValueType(0);
58669 EVT MemVT = MemIntrin->getMemoryVT();
58671 // Look at other users of our base pointer and try to find a wider broadcast.
58672 // The input chain and the size of the memory VT must match.
58673 for (SDNode *User : Ptr->uses())
58674 if (User != N && User->getOpcode() == N->getOpcode() &&
58675 cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
58676 cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
58677 cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
58678 MemVT.getSizeInBits() &&
58679 !User->hasAnyUseOfValue(1) &&
58680 User->getValueSizeInBits(0).getFixedValue() > VT.getFixedSizeInBits()) {
58681 SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
58682 VT.getSizeInBits());
58683 Extract = DAG.getBitcast(VT, Extract);
58684 return DCI.CombineTo(N, Extract, SDValue(User, 1));
58687 return SDValue();
58690 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
58691 const X86Subtarget &Subtarget) {
58692 if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
58693 return SDValue();
58695 bool IsStrict = N->isStrictFPOpcode();
58696 EVT VT = N->getValueType(0);
58697 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
58698 EVT SrcVT = Src.getValueType();
58700 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
58701 SrcVT.getVectorElementType() != MVT::f32)
58702 return SDValue();
58704 SDLoc dl(N);
58706 SDValue Cvt, Chain;
58707 unsigned NumElts = VT.getVectorNumElements();
58708 if (Subtarget.hasFP16()) {
58709 // Combine (v8f16 fp_round(concat_vectors(v4f32 (xint_to_fp v4i64),
58710 // v4f32 (xint_to_fp v4i64))))
58711 // into (v8f16 vector_shuffle(v8f16 (CVTXI2P v4i64),
58712 // v8f16 (CVTXI2P v4i64)))
58713 if (NumElts == 8 && Src.getOpcode() == ISD::CONCAT_VECTORS &&
58714 Src.getNumOperands() == 2) {
58715 SDValue Cvt0, Cvt1;
58716 SDValue Op0 = Src.getOperand(0);
58717 SDValue Op1 = Src.getOperand(1);
58718 bool IsOp0Strict = Op0->isStrictFPOpcode();
58719 if (Op0.getOpcode() != Op1.getOpcode() ||
58720 Op0.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64 ||
58721 Op1.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64) {
58722 return SDValue();
58724 int Mask[8] = {0, 1, 2, 3, 8, 9, 10, 11};
58725 if (IsStrict) {
58726 assert(IsOp0Strict && "Op0 must be strict node");
58727 unsigned Opc = Op0.getOpcode() == ISD::STRICT_SINT_TO_FP
58728 ? X86ISD::STRICT_CVTSI2P
58729 : X86ISD::STRICT_CVTUI2P;
58730 Cvt0 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
58731 {Op0.getOperand(0), Op0.getOperand(1)});
58732 Cvt1 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
58733 {Op1.getOperand(0), Op1.getOperand(1)});
58734 Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
58735 return DAG.getMergeValues({Cvt, Cvt0.getValue(1)}, dl);
58737 unsigned Opc = Op0.getOpcode() == ISD::SINT_TO_FP ? X86ISD::CVTSI2P
58738 : X86ISD::CVTUI2P;
58739 Cvt0 = DAG.getNode(Opc, dl, MVT::v8f16, Op0.getOperand(0));
58740 Cvt1 = DAG.getNode(Opc, dl, MVT::v8f16, Op1.getOperand(0));
58741 return Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
58743 return SDValue();
58746 if (NumElts == 1 || !isPowerOf2_32(NumElts))
58747 return SDValue();
58749 // Widen to at least 4 input elements.
58750 if (NumElts < 4)
58751 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
58752 DAG.getConstantFP(0.0, dl, SrcVT));
58754 // Destination is v8i16 with at least 8 elements.
58755 EVT CvtVT =
58756 EVT::getVectorVT(*DAG.getContext(), MVT::i16, std::max(8U, NumElts));
58757 SDValue Rnd = DAG.getTargetConstant(4, dl, MVT::i32);
58758 if (IsStrict) {
58759 Cvt = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {CvtVT, MVT::Other},
58760 {N->getOperand(0), Src, Rnd});
58761 Chain = Cvt.getValue(1);
58762 } else {
58763 Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src, Rnd);
58766 // Extract down to real number of elements.
58767 if (NumElts < 8) {
58768 EVT IntVT = VT.changeVectorElementTypeToInteger();
58769 Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
58770 DAG.getIntPtrConstant(0, dl));
58773 Cvt = DAG.getBitcast(VT, Cvt);
58775 if (IsStrict)
58776 return DAG.getMergeValues({Cvt, Chain}, dl);
58778 return Cvt;
58781 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
58782 SDValue Src = N->getOperand(0);
58784 // Turn MOVDQ2Q+simple_load into an mmx load.
58785 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
58786 LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
58788 if (LN->isSimple()) {
58789 SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
58790 LN->getBasePtr(),
58791 LN->getPointerInfo(),
58792 LN->getOriginalAlign(),
58793 LN->getMemOperand()->getFlags());
58794 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
58795 return NewLd;
58799 return SDValue();
58802 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
58803 TargetLowering::DAGCombinerInfo &DCI) {
58804 unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
58805 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
58806 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBits), DCI))
58807 return SDValue(N, 0);
58809 return SDValue();
58812 // Fixup the MMX intrinsics' types: in IR they are expressed with <1 x i64>,
58813 // and so SelectionDAGBuilder creates them with v1i64 types, but they need to
58814 // use x86mmx instead.
58815 static SDValue FixupMMXIntrinsicTypes(SDNode *N, SelectionDAG &DAG) {
58816 SDLoc dl(N);
58818 bool MadeChange = false, CastReturnVal = false;
58819 SmallVector<SDValue, 8> Args;
58820 for (const SDValue &Arg : N->op_values()) {
58821 if (Arg.getValueType() == MVT::v1i64) {
58822 MadeChange = true;
58823 Args.push_back(DAG.getBitcast(MVT::x86mmx, Arg));
58824 } else
58825 Args.push_back(Arg);
58827 SDVTList VTs = N->getVTList();
58828 SDVTList NewVTs = VTs;
58829 if (VTs.NumVTs > 0 && VTs.VTs[0] == MVT::v1i64) {
58830 SmallVector<EVT> NewVTArr(ArrayRef<EVT>(VTs.VTs, VTs.NumVTs));
58831 NewVTArr[0] = MVT::x86mmx;
58832 NewVTs = DAG.getVTList(NewVTArr);
58833 MadeChange = true;
58834 CastReturnVal = true;
58837 if (MadeChange) {
58838 SDValue Result = DAG.getNode(N->getOpcode(), dl, NewVTs, Args);
58839 if (CastReturnVal) {
58840 SmallVector<SDValue, 2> Returns;
58841 for (unsigned i = 0, e = Result->getNumValues(); i != e; ++i)
58842 Returns.push_back(Result.getValue(i));
58843 Returns[0] = DAG.getBitcast(MVT::v1i64, Returns[0]);
58844 return DAG.getMergeValues(Returns, dl);
58846 return Result;
58848 return SDValue();
58850 static SDValue combineINTRINSIC_WO_CHAIN(SDNode *N, SelectionDAG &DAG,
58851 TargetLowering::DAGCombinerInfo &DCI) {
58852 if (!DCI.isBeforeLegalize())
58853 return SDValue();
58855 unsigned IntNo = N->getConstantOperandVal(0);
58856 const IntrinsicData *IntrData = getIntrinsicWithoutChain(IntNo);
58858 if (IntrData && IntrData->Type == INTR_TYPE_CAST_MMX)
58859 return FixupMMXIntrinsicTypes(N, DAG);
58861 return SDValue();
58864 static SDValue combineINTRINSIC_W_CHAIN(SDNode *N, SelectionDAG &DAG,
58865 TargetLowering::DAGCombinerInfo &DCI) {
58866 if (!DCI.isBeforeLegalize())
58867 return SDValue();
58869 unsigned IntNo = N->getConstantOperandVal(1);
58870 const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
58872 if (IntrData && IntrData->Type == INTR_TYPE_CAST_MMX)
58873 return FixupMMXIntrinsicTypes(N, DAG);
58875 return SDValue();
58878 static SDValue combineINTRINSIC_VOID(SDNode *N, SelectionDAG &DAG,
58879 TargetLowering::DAGCombinerInfo &DCI) {
58880 if (!DCI.isBeforeLegalize())
58881 return SDValue();
58883 unsigned IntNo = N->getConstantOperandVal(1);
58884 const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
58886 if (IntrData && IntrData->Type == INTR_TYPE_CAST_MMX)
58887 return FixupMMXIntrinsicTypes(N, DAG);
58889 return SDValue();
58892 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
58893 DAGCombinerInfo &DCI) const {
58894 SelectionDAG &DAG = DCI.DAG;
58895 switch (N->getOpcode()) {
58896 // clang-format off
58897 default: break;
58898 case ISD::SCALAR_TO_VECTOR:
58899 return combineScalarToVector(N, DAG, Subtarget);
58900 case ISD::EXTRACT_VECTOR_ELT:
58901 case X86ISD::PEXTRW:
58902 case X86ISD::PEXTRB:
58903 return combineExtractVectorElt(N, DAG, DCI, Subtarget);
58904 case ISD::CONCAT_VECTORS:
58905 return combineCONCAT_VECTORS(N, DAG, DCI, Subtarget);
58906 case ISD::INSERT_SUBVECTOR:
58907 return combineINSERT_SUBVECTOR(N, DAG, DCI, Subtarget);
58908 case ISD::EXTRACT_SUBVECTOR:
58909 return combineEXTRACT_SUBVECTOR(N, DAG, DCI, Subtarget);
58910 case ISD::VSELECT:
58911 case ISD::SELECT:
58912 case X86ISD::BLENDV: return combineSelect(N, DAG, DCI, Subtarget);
58913 case ISD::BITCAST: return combineBitcast(N, DAG, DCI, Subtarget);
58914 case X86ISD::CMOV: return combineCMov(N, DAG, DCI, Subtarget);
58915 case X86ISD::CMP: return combineCMP(N, DAG, DCI, Subtarget);
58916 case ISD::ADD: return combineAdd(N, DAG, DCI, Subtarget);
58917 case ISD::SUB: return combineSub(N, DAG, DCI, Subtarget);
58918 case X86ISD::ADD:
58919 case X86ISD::SUB: return combineX86AddSub(N, DAG, DCI, Subtarget);
58920 case X86ISD::CLOAD:
58921 case X86ISD::CSTORE: return combineX86CloadCstore(N, DAG);
58922 case X86ISD::SBB: return combineSBB(N, DAG);
58923 case X86ISD::ADC: return combineADC(N, DAG, DCI);
58924 case ISD::MUL: return combineMul(N, DAG, DCI, Subtarget);
58925 case ISD::SHL: return combineShiftLeft(N, DAG, Subtarget);
58926 case ISD::SRA: return combineShiftRightArithmetic(N, DAG, Subtarget);
58927 case ISD::SRL: return combineShiftRightLogical(N, DAG, DCI, Subtarget);
58928 case ISD::AND: return combineAnd(N, DAG, DCI, Subtarget);
58929 case ISD::OR: return combineOr(N, DAG, DCI, Subtarget);
58930 case ISD::XOR: return combineXor(N, DAG, DCI, Subtarget);
58931 case ISD::BITREVERSE: return combineBITREVERSE(N, DAG, DCI, Subtarget);
58932 case ISD::AVGCEILS:
58933 case ISD::AVGCEILU:
58934 case ISD::AVGFLOORS:
58935 case ISD::AVGFLOORU: return combineAVG(N, DAG, DCI, Subtarget);
58936 case X86ISD::BEXTR:
58937 case X86ISD::BEXTRI: return combineBEXTR(N, DAG, DCI, Subtarget);
58938 case ISD::LOAD: return combineLoad(N, DAG, DCI, Subtarget);
58939 case ISD::MLOAD: return combineMaskedLoad(N, DAG, DCI, Subtarget);
58940 case ISD::STORE: return combineStore(N, DAG, DCI, Subtarget);
58941 case ISD::MSTORE: return combineMaskedStore(N, DAG, DCI, Subtarget);
58942 case X86ISD::VEXTRACT_STORE:
58943 return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
58944 case ISD::SINT_TO_FP:
58945 case ISD::STRICT_SINT_TO_FP:
58946 return combineSIntToFP(N, DAG, DCI, Subtarget);
58947 case ISD::UINT_TO_FP:
58948 case ISD::STRICT_UINT_TO_FP:
58949 return combineUIntToFP(N, DAG, Subtarget);
58950 case ISD::LRINT:
58951 case ISD::LLRINT: return combineLRINT_LLRINT(N, DAG, Subtarget);
58952 case ISD::FADD:
58953 case ISD::FSUB: return combineFaddFsub(N, DAG, Subtarget);
58954 case X86ISD::VFCMULC:
58955 case X86ISD::VFMULC: return combineFMulcFCMulc(N, DAG, Subtarget);
58956 case ISD::FNEG: return combineFneg(N, DAG, DCI, Subtarget);
58957 case ISD::TRUNCATE: return combineTruncate(N, DAG, Subtarget);
58958 case X86ISD::VTRUNC: return combineVTRUNC(N, DAG, DCI);
58959 case X86ISD::ANDNP: return combineAndnp(N, DAG, DCI, Subtarget);
58960 case X86ISD::FAND: return combineFAnd(N, DAG, Subtarget);
58961 case X86ISD::FANDN: return combineFAndn(N, DAG, Subtarget);
58962 case X86ISD::FXOR:
58963 case X86ISD::FOR: return combineFOr(N, DAG, DCI, Subtarget);
58964 case X86ISD::FMIN:
58965 case X86ISD::FMAX: return combineFMinFMax(N, DAG);
58966 case ISD::FMINNUM:
58967 case ISD::FMAXNUM: return combineFMinNumFMaxNum(N, DAG, Subtarget);
58968 case X86ISD::CVTSI2P:
58969 case X86ISD::CVTUI2P: return combineX86INT_TO_FP(N, DAG, DCI);
58970 case X86ISD::CVTP2SI:
58971 case X86ISD::CVTP2UI:
58972 case X86ISD::STRICT_CVTTP2SI:
58973 case X86ISD::CVTTP2SI:
58974 case X86ISD::STRICT_CVTTP2UI:
58975 case X86ISD::CVTTP2UI:
58976 return combineCVTP2I_CVTTP2I(N, DAG, DCI);
58977 case X86ISD::STRICT_CVTPH2PS:
58978 case X86ISD::CVTPH2PS: return combineCVTPH2PS(N, DAG, DCI);
58979 case X86ISD::BT: return combineBT(N, DAG, DCI);
58980 case ISD::ANY_EXTEND:
58981 case ISD::ZERO_EXTEND: return combineZext(N, DAG, DCI, Subtarget);
58982 case ISD::SIGN_EXTEND: return combineSext(N, DAG, DCI, Subtarget);
58983 case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
58984 case ISD::ANY_EXTEND_VECTOR_INREG:
58985 case ISD::SIGN_EXTEND_VECTOR_INREG:
58986 case ISD::ZERO_EXTEND_VECTOR_INREG:
58987 return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
58988 case ISD::SETCC: return combineSetCC(N, DAG, DCI, Subtarget);
58989 case X86ISD::SETCC: return combineX86SetCC(N, DAG, Subtarget);
58990 case X86ISD::BRCOND: return combineBrCond(N, DAG, Subtarget);
58991 case X86ISD::PACKSS:
58992 case X86ISD::PACKUS: return combineVectorPack(N, DAG, DCI, Subtarget);
58993 case X86ISD::HADD:
58994 case X86ISD::HSUB:
58995 case X86ISD::FHADD:
58996 case X86ISD::FHSUB: return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
58997 case X86ISD::VSHL:
58998 case X86ISD::VSRA:
58999 case X86ISD::VSRL:
59000 return combineVectorShiftVar(N, DAG, DCI, Subtarget);
59001 case X86ISD::VSHLI:
59002 case X86ISD::VSRAI:
59003 case X86ISD::VSRLI:
59004 return combineVectorShiftImm(N, DAG, DCI, Subtarget);
59005 case ISD::INSERT_VECTOR_ELT:
59006 case X86ISD::PINSRB:
59007 case X86ISD::PINSRW: return combineVectorInsert(N, DAG, DCI, Subtarget);
59008 case X86ISD::SHUFP: // Handle all target specific shuffles
59009 case X86ISD::INSERTPS:
59010 case X86ISD::EXTRQI:
59011 case X86ISD::INSERTQI:
59012 case X86ISD::VALIGN:
59013 case X86ISD::PALIGNR:
59014 case X86ISD::VSHLDQ:
59015 case X86ISD::VSRLDQ:
59016 case X86ISD::BLENDI:
59017 case X86ISD::UNPCKH:
59018 case X86ISD::UNPCKL:
59019 case X86ISD::MOVHLPS:
59020 case X86ISD::MOVLHPS:
59021 case X86ISD::PSHUFB:
59022 case X86ISD::PSHUFD:
59023 case X86ISD::PSHUFHW:
59024 case X86ISD::PSHUFLW:
59025 case X86ISD::MOVSHDUP:
59026 case X86ISD::MOVSLDUP:
59027 case X86ISD::MOVDDUP:
59028 case X86ISD::MOVSS:
59029 case X86ISD::MOVSD:
59030 case X86ISD::MOVSH:
59031 case X86ISD::VBROADCAST:
59032 case X86ISD::VPPERM:
59033 case X86ISD::VPERMI:
59034 case X86ISD::VPERMV:
59035 case X86ISD::VPERMV3:
59036 case X86ISD::VPERMIL2:
59037 case X86ISD::VPERMILPI:
59038 case X86ISD::VPERMILPV:
59039 case X86ISD::VPERM2X128:
59040 case X86ISD::SHUF128:
59041 case X86ISD::VZEXT_MOVL:
59042 case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
59043 case X86ISD::FMADD_RND:
59044 case X86ISD::FMSUB:
59045 case X86ISD::STRICT_FMSUB:
59046 case X86ISD::FMSUB_RND:
59047 case X86ISD::FNMADD:
59048 case X86ISD::STRICT_FNMADD:
59049 case X86ISD::FNMADD_RND:
59050 case X86ISD::FNMSUB:
59051 case X86ISD::STRICT_FNMSUB:
59052 case X86ISD::FNMSUB_RND:
59053 case ISD::FMA:
59054 case ISD::STRICT_FMA: return combineFMA(N, DAG, DCI, Subtarget);
59055 case X86ISD::FMADDSUB_RND:
59056 case X86ISD::FMSUBADD_RND:
59057 case X86ISD::FMADDSUB:
59058 case X86ISD::FMSUBADD: return combineFMADDSUB(N, DAG, DCI);
59059 case X86ISD::MOVMSK: return combineMOVMSK(N, DAG, DCI, Subtarget);
59060 case X86ISD::TESTP: return combineTESTP(N, DAG, DCI, Subtarget);
59061 case X86ISD::MGATHER:
59062 case X86ISD::MSCATTER: return combineX86GatherScatter(N, DAG, DCI);
59063 case ISD::MGATHER:
59064 case ISD::MSCATTER: return combineGatherScatter(N, DAG, DCI);
59065 case X86ISD::PCMPEQ:
59066 case X86ISD::PCMPGT: return combineVectorCompare(N, DAG, Subtarget);
59067 case X86ISD::PMULDQ:
59068 case X86ISD::PMULUDQ: return combinePMULDQ(N, DAG, DCI, Subtarget);
59069 case X86ISD::VPMADDUBSW:
59070 case X86ISD::VPMADDWD: return combineVPMADD(N, DAG, DCI);
59071 case X86ISD::KSHIFTL:
59072 case X86ISD::KSHIFTR: return combineKSHIFT(N, DAG, DCI);
59073 case ISD::FP16_TO_FP: return combineFP16_TO_FP(N, DAG, Subtarget);
59074 case ISD::STRICT_FP_EXTEND:
59075 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DAG, DCI, Subtarget);
59076 case ISD::STRICT_FP_ROUND:
59077 case ISD::FP_ROUND: return combineFP_ROUND(N, DAG, Subtarget);
59078 case X86ISD::VBROADCAST_LOAD:
59079 case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
59080 case X86ISD::MOVDQ2Q: return combineMOVDQ2Q(N, DAG);
59081 case X86ISD::PDEP: return combinePDEP(N, DAG, DCI);
59082 case ISD::INTRINSIC_WO_CHAIN: return combineINTRINSIC_WO_CHAIN(N, DAG, DCI);
59083 case ISD::INTRINSIC_W_CHAIN: return combineINTRINSIC_W_CHAIN(N, DAG, DCI);
59084 case ISD::INTRINSIC_VOID: return combineINTRINSIC_VOID(N, DAG, DCI);
59085 // clang-format on
59088 return SDValue();
59091 bool X86TargetLowering::preferABDSToABSWithNSW(EVT VT) const {
59092 return Subtarget.canUseCMOV() && (VT == MVT::i32 || VT == MVT::i64);
59095 // Prefer (non-AVX512) vector TRUNCATE(SIGN_EXTEND_INREG(X)) to use of PACKSS.
59096 bool X86TargetLowering::preferSextInRegOfTruncate(EVT TruncVT, EVT VT,
59097 EVT ExtVT) const {
59098 return Subtarget.hasAVX512() || !VT.isVector();
59101 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
59102 if (!isTypeLegal(VT))
59103 return false;
59105 // There are no vXi8 shifts.
59106 if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
59107 return false;
59109 // TODO: Almost no 8-bit ops are desirable because they have no actual
59110 // size/speed advantages vs. 32-bit ops, but they do have a major
59111 // potential disadvantage by causing partial register stalls.
59113 // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
59114 // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
59115 // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
59116 // check for a constant operand to the multiply.
59117 if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
59118 return false;
59120 // i16 instruction encodings are longer and some i16 instructions are slow,
59121 // so those are not desirable.
59122 if (VT == MVT::i16) {
59123 switch (Opc) {
59124 default:
59125 break;
59126 case ISD::LOAD:
59127 case ISD::SIGN_EXTEND:
59128 case ISD::ZERO_EXTEND:
59129 case ISD::ANY_EXTEND:
59130 case ISD::MUL:
59131 return false;
59132 case ISD::SHL:
59133 case ISD::SRA:
59134 case ISD::SRL:
59135 case ISD::SUB:
59136 case ISD::ADD:
59137 case ISD::AND:
59138 case ISD::OR:
59139 case ISD::XOR:
59140 // NDD instruction never has "partial register write" issue b/c it has
59141 // destination register's upper bits [63:OSIZE]) zeroed even when
59142 // OSIZE=8/16.
59143 return Subtarget.hasNDD();
59147 // Any legal type not explicitly accounted for above here is desirable.
59148 return true;
59151 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc &dl,
59152 SDValue Value, SDValue Addr,
59153 int JTI,
59154 SelectionDAG &DAG) const {
59155 const Module *M = DAG.getMachineFunction().getFunction().getParent();
59156 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
59157 if (IsCFProtectionSupported) {
59158 // In case control-flow branch protection is enabled, we need to add
59159 // notrack prefix to the indirect branch.
59160 // In order to do that we create NT_BRIND SDNode.
59161 // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
59162 SDValue JTInfo = DAG.getJumpTableDebugInfo(JTI, Value, dl);
59163 return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, JTInfo, Addr);
59166 return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, JTI, DAG);
59169 TargetLowering::AndOrSETCCFoldKind
59170 X86TargetLowering::isDesirableToCombineLogicOpOfSETCC(
59171 const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
59172 using AndOrSETCCFoldKind = TargetLowering::AndOrSETCCFoldKind;
59173 EVT VT = LogicOp->getValueType(0);
59174 EVT OpVT = SETCC0->getOperand(0).getValueType();
59175 if (!VT.isInteger())
59176 return AndOrSETCCFoldKind::None;
59178 if (VT.isVector())
59179 return AndOrSETCCFoldKind(AndOrSETCCFoldKind::NotAnd |
59180 (isOperationLegal(ISD::ABS, OpVT)
59181 ? AndOrSETCCFoldKind::ABS
59182 : AndOrSETCCFoldKind::None));
59184 // Don't use `NotAnd` as even though `not` is generally shorter code size than
59185 // `add`, `add` can lower to LEA which can save moves / spills. Any case where
59186 // `NotAnd` applies, `AddAnd` does as well.
59187 // TODO: Currently we lower (icmp eq/ne (and ~X, Y), 0) -> `test (not X), Y`,
59188 // if we change that to `andn Y, X` it may be worth prefering `NotAnd` here.
59189 return AndOrSETCCFoldKind::AddAnd;
59192 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
59193 EVT VT = Op.getValueType();
59194 bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
59195 isa<ConstantSDNode>(Op.getOperand(1));
59197 // i16 is legal, but undesirable since i16 instruction encodings are longer
59198 // and some i16 instructions are slow.
59199 // 8-bit multiply-by-constant can usually be expanded to something cheaper
59200 // using LEA and/or other ALU ops.
59201 if (VT != MVT::i16 && !Is8BitMulByConstant)
59202 return false;
59204 auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
59205 if (!Op.hasOneUse())
59206 return false;
59207 SDNode *User = *Op->use_begin();
59208 if (!ISD::isNormalStore(User))
59209 return false;
59210 auto *Ld = cast<LoadSDNode>(Load);
59211 auto *St = cast<StoreSDNode>(User);
59212 return Ld->getBasePtr() == St->getBasePtr();
59215 auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
59216 if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
59217 return false;
59218 if (!Op.hasOneUse())
59219 return false;
59220 SDNode *User = *Op->use_begin();
59221 if (User->getOpcode() != ISD::ATOMIC_STORE)
59222 return false;
59223 auto *Ld = cast<AtomicSDNode>(Load);
59224 auto *St = cast<AtomicSDNode>(User);
59225 return Ld->getBasePtr() == St->getBasePtr();
59228 bool Commute = false;
59229 switch (Op.getOpcode()) {
59230 default: return false;
59231 case ISD::SIGN_EXTEND:
59232 case ISD::ZERO_EXTEND:
59233 case ISD::ANY_EXTEND:
59234 break;
59235 case ISD::SHL:
59236 case ISD::SRA:
59237 case ISD::SRL: {
59238 SDValue N0 = Op.getOperand(0);
59239 // Look out for (store (shl (load), x)).
59240 if (X86::mayFoldLoad(N0, Subtarget) && IsFoldableRMW(N0, Op))
59241 return false;
59242 break;
59244 case ISD::ADD:
59245 case ISD::MUL:
59246 case ISD::AND:
59247 case ISD::OR:
59248 case ISD::XOR:
59249 Commute = true;
59250 [[fallthrough]];
59251 case ISD::SUB: {
59252 SDValue N0 = Op.getOperand(0);
59253 SDValue N1 = Op.getOperand(1);
59254 // Avoid disabling potential load folding opportunities.
59255 if (X86::mayFoldLoad(N1, Subtarget) &&
59256 (!Commute || !isa<ConstantSDNode>(N0) ||
59257 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
59258 return false;
59259 if (X86::mayFoldLoad(N0, Subtarget) &&
59260 ((Commute && !isa<ConstantSDNode>(N1)) ||
59261 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
59262 return false;
59263 if (IsFoldableAtomicRMW(N0, Op) ||
59264 (Commute && IsFoldableAtomicRMW(N1, Op)))
59265 return false;
59269 PVT = MVT::i32;
59270 return true;
59273 //===----------------------------------------------------------------------===//
59274 // X86 Inline Assembly Support
59275 //===----------------------------------------------------------------------===//
59277 // Helper to match a string separated by whitespace.
59278 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
59279 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
59281 for (StringRef Piece : Pieces) {
59282 if (!S.starts_with(Piece)) // Check if the piece matches.
59283 return false;
59285 S = S.substr(Piece.size());
59286 StringRef::size_type Pos = S.find_first_not_of(" \t");
59287 if (Pos == 0) // We matched a prefix.
59288 return false;
59290 S = S.substr(Pos);
59293 return S.empty();
59296 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
59298 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
59299 if (llvm::is_contained(AsmPieces, "~{cc}") &&
59300 llvm::is_contained(AsmPieces, "~{flags}") &&
59301 llvm::is_contained(AsmPieces, "~{fpsr}")) {
59303 if (AsmPieces.size() == 3)
59304 return true;
59305 else if (llvm::is_contained(AsmPieces, "~{dirflag}"))
59306 return true;
59309 return false;
59312 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
59313 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
59315 const std::string &AsmStr = IA->getAsmString();
59317 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
59318 if (!Ty || Ty->getBitWidth() % 16 != 0)
59319 return false;
59321 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
59322 SmallVector<StringRef, 4> AsmPieces;
59323 SplitString(AsmStr, AsmPieces, ";\n");
59325 switch (AsmPieces.size()) {
59326 default: return false;
59327 case 1:
59328 // FIXME: this should verify that we are targeting a 486 or better. If not,
59329 // we will turn this bswap into something that will be lowered to logical
59330 // ops instead of emitting the bswap asm. For now, we don't support 486 or
59331 // lower so don't worry about this.
59332 // bswap $0
59333 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
59334 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
59335 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
59336 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
59337 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
59338 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
59339 // No need to check constraints, nothing other than the equivalent of
59340 // "=r,0" would be valid here.
59341 return IntrinsicLowering::LowerToByteSwap(CI);
59344 // rorw $$8, ${0:w} --> llvm.bswap.i16
59345 if (CI->getType()->isIntegerTy(16) &&
59346 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
59347 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
59348 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
59349 AsmPieces.clear();
59350 StringRef ConstraintsStr = IA->getConstraintString();
59351 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
59352 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
59353 if (clobbersFlagRegisters(AsmPieces))
59354 return IntrinsicLowering::LowerToByteSwap(CI);
59356 break;
59357 case 3:
59358 if (CI->getType()->isIntegerTy(32) &&
59359 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
59360 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
59361 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
59362 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
59363 AsmPieces.clear();
59364 StringRef ConstraintsStr = IA->getConstraintString();
59365 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
59366 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
59367 if (clobbersFlagRegisters(AsmPieces))
59368 return IntrinsicLowering::LowerToByteSwap(CI);
59371 if (CI->getType()->isIntegerTy(64)) {
59372 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
59373 if (Constraints.size() >= 2 &&
59374 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
59375 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
59376 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
59377 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
59378 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
59379 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
59380 return IntrinsicLowering::LowerToByteSwap(CI);
59383 break;
59385 return false;
59388 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
59389 X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
59390 .Case("{@cca}", X86::COND_A)
59391 .Case("{@ccae}", X86::COND_AE)
59392 .Case("{@ccb}", X86::COND_B)
59393 .Case("{@ccbe}", X86::COND_BE)
59394 .Case("{@ccc}", X86::COND_B)
59395 .Case("{@cce}", X86::COND_E)
59396 .Case("{@ccz}", X86::COND_E)
59397 .Case("{@ccg}", X86::COND_G)
59398 .Case("{@ccge}", X86::COND_GE)
59399 .Case("{@ccl}", X86::COND_L)
59400 .Case("{@ccle}", X86::COND_LE)
59401 .Case("{@ccna}", X86::COND_BE)
59402 .Case("{@ccnae}", X86::COND_B)
59403 .Case("{@ccnb}", X86::COND_AE)
59404 .Case("{@ccnbe}", X86::COND_A)
59405 .Case("{@ccnc}", X86::COND_AE)
59406 .Case("{@ccne}", X86::COND_NE)
59407 .Case("{@ccnz}", X86::COND_NE)
59408 .Case("{@ccng}", X86::COND_LE)
59409 .Case("{@ccnge}", X86::COND_L)
59410 .Case("{@ccnl}", X86::COND_GE)
59411 .Case("{@ccnle}", X86::COND_G)
59412 .Case("{@ccno}", X86::COND_NO)
59413 .Case("{@ccnp}", X86::COND_NP)
59414 .Case("{@ccns}", X86::COND_NS)
59415 .Case("{@cco}", X86::COND_O)
59416 .Case("{@ccp}", X86::COND_P)
59417 .Case("{@ccs}", X86::COND_S)
59418 .Default(X86::COND_INVALID);
59419 return Cond;
59422 /// Given a constraint letter, return the type of constraint for this target.
59423 X86TargetLowering::ConstraintType
59424 X86TargetLowering::getConstraintType(StringRef Constraint) const {
59425 if (Constraint.size() == 1) {
59426 switch (Constraint[0]) {
59427 case 'R':
59428 case 'q':
59429 case 'Q':
59430 case 'f':
59431 case 't':
59432 case 'u':
59433 case 'y':
59434 case 'x':
59435 case 'v':
59436 case 'l':
59437 case 'k': // AVX512 masking registers.
59438 return C_RegisterClass;
59439 case 'a':
59440 case 'b':
59441 case 'c':
59442 case 'd':
59443 case 'S':
59444 case 'D':
59445 case 'A':
59446 return C_Register;
59447 case 'I':
59448 case 'J':
59449 case 'K':
59450 case 'N':
59451 case 'G':
59452 case 'L':
59453 case 'M':
59454 return C_Immediate;
59455 case 'C':
59456 case 'e':
59457 case 'Z':
59458 return C_Other;
59459 default:
59460 break;
59463 else if (Constraint.size() == 2) {
59464 switch (Constraint[0]) {
59465 default:
59466 break;
59467 case 'W':
59468 if (Constraint[1] != 's')
59469 break;
59470 return C_Other;
59471 case 'Y':
59472 switch (Constraint[1]) {
59473 default:
59474 break;
59475 case 'z':
59476 return C_Register;
59477 case 'i':
59478 case 'm':
59479 case 'k':
59480 case 't':
59481 case '2':
59482 return C_RegisterClass;
59484 break;
59485 case 'j':
59486 switch (Constraint[1]) {
59487 default:
59488 break;
59489 case 'r':
59490 case 'R':
59491 return C_RegisterClass;
59494 } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
59495 return C_Other;
59496 return TargetLowering::getConstraintType(Constraint);
59499 /// Examine constraint type and operand type and determine a weight value.
59500 /// This object must already have been set up with the operand type
59501 /// and the current alternative constraint selected.
59502 TargetLowering::ConstraintWeight
59503 X86TargetLowering::getSingleConstraintMatchWeight(
59504 AsmOperandInfo &Info, const char *Constraint) const {
59505 ConstraintWeight Wt = CW_Invalid;
59506 Value *CallOperandVal = Info.CallOperandVal;
59507 // If we don't have a value, we can't do a match,
59508 // but allow it at the lowest weight.
59509 if (!CallOperandVal)
59510 return CW_Default;
59511 Type *Ty = CallOperandVal->getType();
59512 // Look at the constraint type.
59513 switch (*Constraint) {
59514 default:
59515 Wt = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
59516 [[fallthrough]];
59517 case 'R':
59518 case 'q':
59519 case 'Q':
59520 case 'a':
59521 case 'b':
59522 case 'c':
59523 case 'd':
59524 case 'S':
59525 case 'D':
59526 case 'A':
59527 if (CallOperandVal->getType()->isIntegerTy())
59528 Wt = CW_SpecificReg;
59529 break;
59530 case 'f':
59531 case 't':
59532 case 'u':
59533 if (Ty->isFloatingPointTy())
59534 Wt = CW_SpecificReg;
59535 break;
59536 case 'y':
59537 if (Ty->getPrimitiveSizeInBits() == 64 && Subtarget.hasMMX())
59538 Wt = CW_SpecificReg;
59539 break;
59540 case 'Y':
59541 if (StringRef(Constraint).size() != 2)
59542 break;
59543 switch (Constraint[1]) {
59544 default:
59545 return CW_Invalid;
59546 // XMM0
59547 case 'z':
59548 if (((Ty->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
59549 ((Ty->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
59550 ((Ty->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
59551 return CW_SpecificReg;
59552 return CW_Invalid;
59553 // Conditional OpMask regs (AVX512)
59554 case 'k':
59555 if ((Ty->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
59556 return CW_Register;
59557 return CW_Invalid;
59558 // Any MMX reg
59559 case 'm':
59560 if (Ty->getPrimitiveSizeInBits() == 64 && Subtarget.hasMMX())
59561 return CW_SpecificReg;
59562 return CW_Invalid;
59563 // Any SSE reg when ISA >= SSE2, same as 'x'
59564 case 'i':
59565 case 't':
59566 case '2':
59567 if (!Subtarget.hasSSE2())
59568 return CW_Invalid;
59569 break;
59571 break;
59572 case 'j':
59573 if (StringRef(Constraint).size() != 2)
59574 break;
59575 switch (Constraint[1]) {
59576 default:
59577 return CW_Invalid;
59578 case 'r':
59579 case 'R':
59580 if (CallOperandVal->getType()->isIntegerTy())
59581 Wt = CW_SpecificReg;
59582 break;
59584 break;
59585 case 'v':
59586 if ((Ty->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
59587 Wt = CW_Register;
59588 [[fallthrough]];
59589 case 'x':
59590 if (((Ty->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
59591 ((Ty->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
59592 Wt = CW_Register;
59593 break;
59594 case 'k':
59595 // Enable conditional vector operations using %k<#> registers.
59596 if ((Ty->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
59597 Wt = CW_Register;
59598 break;
59599 case 'I':
59600 if (auto *C = dyn_cast<ConstantInt>(Info.CallOperandVal))
59601 if (C->getZExtValue() <= 31)
59602 Wt = CW_Constant;
59603 break;
59604 case 'J':
59605 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59606 if (C->getZExtValue() <= 63)
59607 Wt = CW_Constant;
59608 break;
59609 case 'K':
59610 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59611 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
59612 Wt = CW_Constant;
59613 break;
59614 case 'L':
59615 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59616 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
59617 Wt = CW_Constant;
59618 break;
59619 case 'M':
59620 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59621 if (C->getZExtValue() <= 3)
59622 Wt = CW_Constant;
59623 break;
59624 case 'N':
59625 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59626 if (C->getZExtValue() <= 0xff)
59627 Wt = CW_Constant;
59628 break;
59629 case 'G':
59630 case 'C':
59631 if (isa<ConstantFP>(CallOperandVal))
59632 Wt = CW_Constant;
59633 break;
59634 case 'e':
59635 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59636 if ((C->getSExtValue() >= -0x80000000LL) &&
59637 (C->getSExtValue() <= 0x7fffffffLL))
59638 Wt = CW_Constant;
59639 break;
59640 case 'Z':
59641 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
59642 if (C->getZExtValue() <= 0xffffffff)
59643 Wt = CW_Constant;
59644 break;
59646 return Wt;
59649 /// Try to replace an X constraint, which matches anything, with another that
59650 /// has more specific requirements based on the type of the corresponding
59651 /// operand.
59652 const char *X86TargetLowering::
59653 LowerXConstraint(EVT ConstraintVT) const {
59654 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
59655 // 'f' like normal targets.
59656 if (ConstraintVT.isFloatingPoint()) {
59657 if (Subtarget.hasSSE1())
59658 return "x";
59661 return TargetLowering::LowerXConstraint(ConstraintVT);
59664 // Lower @cc targets via setcc.
59665 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
59666 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
59667 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
59668 X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
59669 if (Cond == X86::COND_INVALID)
59670 return SDValue();
59671 // Check that return type is valid.
59672 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
59673 OpInfo.ConstraintVT.getSizeInBits() < 8)
59674 report_fatal_error("Glue output operand is of invalid type");
59676 // Get EFLAGS register. Only update chain when copyfrom is glued.
59677 if (Glue.getNode()) {
59678 Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Glue);
59679 Chain = Glue.getValue(1);
59680 } else
59681 Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
59682 // Extract CC code.
59683 SDValue CC = getSETCC(Cond, Glue, DL, DAG);
59684 // Extend to 32-bits
59685 SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
59687 return Result;
59690 /// Lower the specified operand into the Ops vector.
59691 /// If it is invalid, don't add anything to Ops.
59692 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
59693 StringRef Constraint,
59694 std::vector<SDValue> &Ops,
59695 SelectionDAG &DAG) const {
59696 SDValue Result;
59697 char ConstraintLetter = Constraint[0];
59698 switch (ConstraintLetter) {
59699 default: break;
59700 case 'I':
59701 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59702 if (C->getZExtValue() <= 31) {
59703 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59704 Op.getValueType());
59705 break;
59708 return;
59709 case 'J':
59710 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59711 if (C->getZExtValue() <= 63) {
59712 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59713 Op.getValueType());
59714 break;
59717 return;
59718 case 'K':
59719 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59720 if (isInt<8>(C->getSExtValue())) {
59721 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59722 Op.getValueType());
59723 break;
59726 return;
59727 case 'L':
59728 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59729 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
59730 (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
59731 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
59732 Op.getValueType());
59733 break;
59736 return;
59737 case 'M':
59738 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59739 if (C->getZExtValue() <= 3) {
59740 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59741 Op.getValueType());
59742 break;
59745 return;
59746 case 'N':
59747 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59748 if (C->getZExtValue() <= 255) {
59749 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59750 Op.getValueType());
59751 break;
59754 return;
59755 case 'O':
59756 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59757 if (C->getZExtValue() <= 127) {
59758 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59759 Op.getValueType());
59760 break;
59763 return;
59764 case 'e': {
59765 // 32-bit signed value
59766 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59767 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
59768 C->getSExtValue())) {
59769 // Widen to 64 bits here to get it sign extended.
59770 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
59771 break;
59773 // FIXME gcc accepts some relocatable values here too, but only in certain
59774 // memory models; it's complicated.
59776 return;
59778 case 'W': {
59779 assert(Constraint[1] == 's');
59780 // Op is a BlockAddressSDNode or a GlobalAddressSDNode with an optional
59781 // offset.
59782 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
59783 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
59784 BA->getValueType(0)));
59785 } else {
59786 int64_t Offset = 0;
59787 if (Op->getOpcode() == ISD::ADD &&
59788 isa<ConstantSDNode>(Op->getOperand(1))) {
59789 Offset = cast<ConstantSDNode>(Op->getOperand(1))->getSExtValue();
59790 Op = Op->getOperand(0);
59792 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
59793 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
59794 GA->getValueType(0), Offset));
59796 return;
59798 case 'Z': {
59799 // 32-bit unsigned value
59800 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
59801 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
59802 C->getZExtValue())) {
59803 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
59804 Op.getValueType());
59805 break;
59808 // FIXME gcc accepts some relocatable values here too, but only in certain
59809 // memory models; it's complicated.
59810 return;
59812 case 'i': {
59813 // Literal immediates are always ok.
59814 if (auto *CST = dyn_cast<ConstantSDNode>(Op)) {
59815 bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
59816 BooleanContent BCont = getBooleanContents(MVT::i64);
59817 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
59818 : ISD::SIGN_EXTEND;
59819 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
59820 : CST->getSExtValue();
59821 Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
59822 break;
59825 // In any sort of PIC mode addresses need to be computed at runtime by
59826 // adding in a register or some sort of table lookup. These can't
59827 // be used as immediates. BlockAddresses and BasicBlocks are fine though.
59828 if ((Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC()) &&
59829 !(isa<BlockAddressSDNode>(Op) || isa<BasicBlockSDNode>(Op)))
59830 return;
59832 // If we are in non-pic codegen mode, we allow the address of a global (with
59833 // an optional displacement) to be used with 'i'.
59834 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
59835 // If we require an extra load to get this address, as in PIC mode, we
59836 // can't accept it.
59837 if (isGlobalStubReference(
59838 Subtarget.classifyGlobalReference(GA->getGlobal())))
59839 return;
59840 break;
59844 if (Result.getNode()) {
59845 Ops.push_back(Result);
59846 return;
59848 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
59851 /// Check if \p RC is a general purpose register class.
59852 /// I.e., GR* or one of their variant.
59853 static bool isGRClass(const TargetRegisterClass &RC) {
59854 return RC.hasSuperClassEq(&X86::GR8RegClass) ||
59855 RC.hasSuperClassEq(&X86::GR16RegClass) ||
59856 RC.hasSuperClassEq(&X86::GR32RegClass) ||
59857 RC.hasSuperClassEq(&X86::GR64RegClass) ||
59858 RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
59861 /// Check if \p RC is a vector register class.
59862 /// I.e., FR* / VR* or one of their variant.
59863 static bool isFRClass(const TargetRegisterClass &RC) {
59864 return RC.hasSuperClassEq(&X86::FR16XRegClass) ||
59865 RC.hasSuperClassEq(&X86::FR32XRegClass) ||
59866 RC.hasSuperClassEq(&X86::FR64XRegClass) ||
59867 RC.hasSuperClassEq(&X86::VR128XRegClass) ||
59868 RC.hasSuperClassEq(&X86::VR256XRegClass) ||
59869 RC.hasSuperClassEq(&X86::VR512RegClass);
59872 /// Check if \p RC is a mask register class.
59873 /// I.e., VK* or one of their variant.
59874 static bool isVKClass(const TargetRegisterClass &RC) {
59875 return RC.hasSuperClassEq(&X86::VK1RegClass) ||
59876 RC.hasSuperClassEq(&X86::VK2RegClass) ||
59877 RC.hasSuperClassEq(&X86::VK4RegClass) ||
59878 RC.hasSuperClassEq(&X86::VK8RegClass) ||
59879 RC.hasSuperClassEq(&X86::VK16RegClass) ||
59880 RC.hasSuperClassEq(&X86::VK32RegClass) ||
59881 RC.hasSuperClassEq(&X86::VK64RegClass);
59884 static bool useEGPRInlineAsm(const X86Subtarget &Subtarget) {
59885 return Subtarget.hasEGPR() && Subtarget.useInlineAsmGPR32();
59888 std::pair<unsigned, const TargetRegisterClass *>
59889 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
59890 StringRef Constraint,
59891 MVT VT) const {
59892 // First, see if this is a constraint that directly corresponds to an LLVM
59893 // register class.
59894 if (Constraint.size() == 1) {
59895 // GCC Constraint Letters
59896 switch (Constraint[0]) {
59897 default: break;
59898 // 'A' means [ER]AX + [ER]DX.
59899 case 'A':
59900 if (Subtarget.is64Bit())
59901 return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
59902 assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
59903 "Expecting 64, 32 or 16 bit subtarget");
59904 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
59906 // TODO: Slight differences here in allocation order and leaving
59907 // RIP in the class. Do they matter any more here than they do
59908 // in the normal allocation?
59909 case 'k':
59910 if (Subtarget.hasAVX512()) {
59911 if (VT == MVT::v1i1 || VT == MVT::i1)
59912 return std::make_pair(0U, &X86::VK1RegClass);
59913 if (VT == MVT::v8i1 || VT == MVT::i8)
59914 return std::make_pair(0U, &X86::VK8RegClass);
59915 if (VT == MVT::v16i1 || VT == MVT::i16)
59916 return std::make_pair(0U, &X86::VK16RegClass);
59918 if (Subtarget.hasBWI()) {
59919 if (VT == MVT::v32i1 || VT == MVT::i32)
59920 return std::make_pair(0U, &X86::VK32RegClass);
59921 if (VT == MVT::v64i1 || VT == MVT::i64)
59922 return std::make_pair(0U, &X86::VK64RegClass);
59924 break;
59925 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
59926 if (Subtarget.is64Bit()) {
59927 if (VT == MVT::i8 || VT == MVT::i1)
59928 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59929 ? &X86::GR8RegClass
59930 : &X86::GR8_NOREX2RegClass);
59931 if (VT == MVT::i16)
59932 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59933 ? &X86::GR16RegClass
59934 : &X86::GR16_NOREX2RegClass);
59935 if (VT == MVT::i32 || VT == MVT::f32)
59936 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59937 ? &X86::GR32RegClass
59938 : &X86::GR32_NOREX2RegClass);
59939 if (VT != MVT::f80 && !VT.isVector())
59940 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59941 ? &X86::GR64RegClass
59942 : &X86::GR64_NOREX2RegClass);
59943 break;
59945 [[fallthrough]];
59946 // 32-bit fallthrough
59947 case 'Q': // Q_REGS
59948 if (VT == MVT::i8 || VT == MVT::i1)
59949 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
59950 if (VT == MVT::i16)
59951 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
59952 if (VT == MVT::i32 || VT == MVT::f32 ||
59953 (!VT.isVector() && !Subtarget.is64Bit()))
59954 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
59955 if (VT != MVT::f80 && !VT.isVector())
59956 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
59957 break;
59958 case 'r': // GENERAL_REGS
59959 case 'l': // INDEX_REGS
59960 if (VT == MVT::i8 || VT == MVT::i1)
59961 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59962 ? &X86::GR8RegClass
59963 : &X86::GR8_NOREX2RegClass);
59964 if (VT == MVT::i16)
59965 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59966 ? &X86::GR16RegClass
59967 : &X86::GR16_NOREX2RegClass);
59968 if (VT == MVT::i32 || VT == MVT::f32 ||
59969 (!VT.isVector() && !Subtarget.is64Bit()))
59970 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59971 ? &X86::GR32RegClass
59972 : &X86::GR32_NOREX2RegClass);
59973 if (VT != MVT::f80 && !VT.isVector())
59974 return std::make_pair(0U, useEGPRInlineAsm(Subtarget)
59975 ? &X86::GR64RegClass
59976 : &X86::GR64_NOREX2RegClass);
59977 break;
59978 case 'R': // LEGACY_REGS
59979 if (VT == MVT::i8 || VT == MVT::i1)
59980 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
59981 if (VT == MVT::i16)
59982 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
59983 if (VT == MVT::i32 || VT == MVT::f32 ||
59984 (!VT.isVector() && !Subtarget.is64Bit()))
59985 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
59986 if (VT != MVT::f80 && !VT.isVector())
59987 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
59988 break;
59989 case 'f': // FP Stack registers.
59990 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
59991 // value to the correct fpstack register class.
59992 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
59993 return std::make_pair(0U, &X86::RFP32RegClass);
59994 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
59995 return std::make_pair(0U, &X86::RFP64RegClass);
59996 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
59997 return std::make_pair(0U, &X86::RFP80RegClass);
59998 break;
59999 case 'y': // MMX_REGS if MMX allowed.
60000 if (!Subtarget.hasMMX()) break;
60001 return std::make_pair(0U, &X86::VR64RegClass);
60002 case 'v':
60003 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
60004 if (!Subtarget.hasSSE1()) break;
60005 bool VConstraint = (Constraint[0] == 'v');
60007 switch (VT.SimpleTy) {
60008 default: break;
60009 // Scalar SSE types.
60010 case MVT::f16:
60011 if (VConstraint && Subtarget.hasFP16())
60012 return std::make_pair(0U, &X86::FR16XRegClass);
60013 break;
60014 case MVT::f32:
60015 case MVT::i32:
60016 if (VConstraint && Subtarget.hasVLX())
60017 return std::make_pair(0U, &X86::FR32XRegClass);
60018 return std::make_pair(0U, &X86::FR32RegClass);
60019 case MVT::f64:
60020 case MVT::i64:
60021 if (VConstraint && Subtarget.hasVLX())
60022 return std::make_pair(0U, &X86::FR64XRegClass);
60023 return std::make_pair(0U, &X86::FR64RegClass);
60024 case MVT::i128:
60025 if (Subtarget.is64Bit()) {
60026 if (VConstraint && Subtarget.hasVLX())
60027 return std::make_pair(0U, &X86::VR128XRegClass);
60028 return std::make_pair(0U, &X86::VR128RegClass);
60030 break;
60031 // Vector types and fp128.
60032 case MVT::v8f16:
60033 if (!Subtarget.hasFP16())
60034 break;
60035 if (VConstraint)
60036 return std::make_pair(0U, &X86::VR128XRegClass);
60037 return std::make_pair(0U, &X86::VR128RegClass);
60038 case MVT::v8bf16:
60039 if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
60040 break;
60041 if (VConstraint)
60042 return std::make_pair(0U, &X86::VR128XRegClass);
60043 return std::make_pair(0U, &X86::VR128RegClass);
60044 case MVT::f128:
60045 case MVT::v16i8:
60046 case MVT::v8i16:
60047 case MVT::v4i32:
60048 case MVT::v2i64:
60049 case MVT::v4f32:
60050 case MVT::v2f64:
60051 if (VConstraint && Subtarget.hasVLX())
60052 return std::make_pair(0U, &X86::VR128XRegClass);
60053 return std::make_pair(0U, &X86::VR128RegClass);
60054 // AVX types.
60055 case MVT::v16f16:
60056 if (!Subtarget.hasFP16())
60057 break;
60058 if (VConstraint)
60059 return std::make_pair(0U, &X86::VR256XRegClass);
60060 return std::make_pair(0U, &X86::VR256RegClass);
60061 case MVT::v16bf16:
60062 if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
60063 break;
60064 if (VConstraint)
60065 return std::make_pair(0U, &X86::VR256XRegClass);
60066 return std::make_pair(0U, &X86::VR256RegClass);
60067 case MVT::v32i8:
60068 case MVT::v16i16:
60069 case MVT::v8i32:
60070 case MVT::v4i64:
60071 case MVT::v8f32:
60072 case MVT::v4f64:
60073 if (VConstraint && Subtarget.hasVLX())
60074 return std::make_pair(0U, &X86::VR256XRegClass);
60075 if (Subtarget.hasAVX())
60076 return std::make_pair(0U, &X86::VR256RegClass);
60077 break;
60078 case MVT::v32f16:
60079 if (!Subtarget.hasFP16())
60080 break;
60081 if (VConstraint)
60082 return std::make_pair(0U, &X86::VR512RegClass);
60083 return std::make_pair(0U, &X86::VR512_0_15RegClass);
60084 case MVT::v32bf16:
60085 if (!Subtarget.hasBF16())
60086 break;
60087 if (VConstraint)
60088 return std::make_pair(0U, &X86::VR512RegClass);
60089 return std::make_pair(0U, &X86::VR512_0_15RegClass);
60090 case MVT::v64i8:
60091 case MVT::v32i16:
60092 case MVT::v8f64:
60093 case MVT::v16f32:
60094 case MVT::v16i32:
60095 case MVT::v8i64:
60096 if (!Subtarget.hasAVX512()) break;
60097 if (VConstraint)
60098 return std::make_pair(0U, &X86::VR512RegClass);
60099 return std::make_pair(0U, &X86::VR512_0_15RegClass);
60101 break;
60103 } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
60104 switch (Constraint[1]) {
60105 default:
60106 break;
60107 case 'i':
60108 case 't':
60109 case '2':
60110 return getRegForInlineAsmConstraint(TRI, "x", VT);
60111 case 'm':
60112 if (!Subtarget.hasMMX()) break;
60113 return std::make_pair(0U, &X86::VR64RegClass);
60114 case 'z':
60115 if (!Subtarget.hasSSE1()) break;
60116 switch (VT.SimpleTy) {
60117 default: break;
60118 // Scalar SSE types.
60119 case MVT::f16:
60120 if (!Subtarget.hasFP16())
60121 break;
60122 return std::make_pair(X86::XMM0, &X86::FR16XRegClass);
60123 case MVT::f32:
60124 case MVT::i32:
60125 return std::make_pair(X86::XMM0, &X86::FR32RegClass);
60126 case MVT::f64:
60127 case MVT::i64:
60128 return std::make_pair(X86::XMM0, &X86::FR64RegClass);
60129 case MVT::v8f16:
60130 if (!Subtarget.hasFP16())
60131 break;
60132 return std::make_pair(X86::XMM0, &X86::VR128RegClass);
60133 case MVT::v8bf16:
60134 if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
60135 break;
60136 return std::make_pair(X86::XMM0, &X86::VR128RegClass);
60137 case MVT::f128:
60138 case MVT::v16i8:
60139 case MVT::v8i16:
60140 case MVT::v4i32:
60141 case MVT::v2i64:
60142 case MVT::v4f32:
60143 case MVT::v2f64:
60144 return std::make_pair(X86::XMM0, &X86::VR128RegClass);
60145 // AVX types.
60146 case MVT::v16f16:
60147 if (!Subtarget.hasFP16())
60148 break;
60149 return std::make_pair(X86::YMM0, &X86::VR256RegClass);
60150 case MVT::v16bf16:
60151 if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
60152 break;
60153 return std::make_pair(X86::YMM0, &X86::VR256RegClass);
60154 case MVT::v32i8:
60155 case MVT::v16i16:
60156 case MVT::v8i32:
60157 case MVT::v4i64:
60158 case MVT::v8f32:
60159 case MVT::v4f64:
60160 if (Subtarget.hasAVX())
60161 return std::make_pair(X86::YMM0, &X86::VR256RegClass);
60162 break;
60163 case MVT::v32f16:
60164 if (!Subtarget.hasFP16())
60165 break;
60166 return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
60167 case MVT::v32bf16:
60168 if (!Subtarget.hasBF16())
60169 break;
60170 return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
60171 case MVT::v64i8:
60172 case MVT::v32i16:
60173 case MVT::v8f64:
60174 case MVT::v16f32:
60175 case MVT::v16i32:
60176 case MVT::v8i64:
60177 if (Subtarget.hasAVX512())
60178 return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
60179 break;
60181 break;
60182 case 'k':
60183 // This register class doesn't allocate k0 for masked vector operation.
60184 if (Subtarget.hasAVX512()) {
60185 if (VT == MVT::v1i1 || VT == MVT::i1)
60186 return std::make_pair(0U, &X86::VK1WMRegClass);
60187 if (VT == MVT::v8i1 || VT == MVT::i8)
60188 return std::make_pair(0U, &X86::VK8WMRegClass);
60189 if (VT == MVT::v16i1 || VT == MVT::i16)
60190 return std::make_pair(0U, &X86::VK16WMRegClass);
60192 if (Subtarget.hasBWI()) {
60193 if (VT == MVT::v32i1 || VT == MVT::i32)
60194 return std::make_pair(0U, &X86::VK32WMRegClass);
60195 if (VT == MVT::v64i1 || VT == MVT::i64)
60196 return std::make_pair(0U, &X86::VK64WMRegClass);
60198 break;
60200 } else if (Constraint.size() == 2 && Constraint[0] == 'j') {
60201 switch (Constraint[1]) {
60202 default:
60203 break;
60204 case 'r':
60205 if (VT == MVT::i8 || VT == MVT::i1)
60206 return std::make_pair(0U, &X86::GR8_NOREX2RegClass);
60207 if (VT == MVT::i16)
60208 return std::make_pair(0U, &X86::GR16_NOREX2RegClass);
60209 if (VT == MVT::i32 || VT == MVT::f32)
60210 return std::make_pair(0U, &X86::GR32_NOREX2RegClass);
60211 if (VT != MVT::f80 && !VT.isVector())
60212 return std::make_pair(0U, &X86::GR64_NOREX2RegClass);
60213 break;
60214 case 'R':
60215 if (VT == MVT::i8 || VT == MVT::i1)
60216 return std::make_pair(0U, &X86::GR8RegClass);
60217 if (VT == MVT::i16)
60218 return std::make_pair(0U, &X86::GR16RegClass);
60219 if (VT == MVT::i32 || VT == MVT::f32)
60220 return std::make_pair(0U, &X86::GR32RegClass);
60221 if (VT != MVT::f80 && !VT.isVector())
60222 return std::make_pair(0U, &X86::GR64RegClass);
60223 break;
60227 if (parseConstraintCode(Constraint) != X86::COND_INVALID)
60228 return std::make_pair(0U, &X86::GR32RegClass);
60230 // Use the default implementation in TargetLowering to convert the register
60231 // constraint into a member of a register class.
60232 std::pair<Register, const TargetRegisterClass*> Res;
60233 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
60235 // Not found as a standard register?
60236 if (!Res.second) {
60237 // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
60238 // to/from f80.
60239 if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
60240 // Map st(0) -> st(7) -> ST0
60241 if (Constraint.size() == 7 && Constraint[0] == '{' &&
60242 tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
60243 Constraint[3] == '(' &&
60244 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
60245 Constraint[5] == ')' && Constraint[6] == '}') {
60246 // st(7) is not allocatable and thus not a member of RFP80. Return
60247 // singleton class in cases where we have a reference to it.
60248 if (Constraint[4] == '7')
60249 return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
60250 return std::make_pair(X86::FP0 + Constraint[4] - '0',
60251 &X86::RFP80RegClass);
60254 // GCC allows "st(0)" to be called just plain "st".
60255 if (StringRef("{st}").equals_insensitive(Constraint))
60256 return std::make_pair(X86::FP0, &X86::RFP80RegClass);
60259 // flags -> EFLAGS
60260 if (StringRef("{flags}").equals_insensitive(Constraint))
60261 return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
60263 // dirflag -> DF
60264 // Only allow for clobber.
60265 if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
60266 VT == MVT::Other)
60267 return std::make_pair(X86::DF, &X86::DFCCRRegClass);
60269 // fpsr -> FPSW
60270 // Only allow for clobber.
60271 if (StringRef("{fpsr}").equals_insensitive(Constraint) && VT == MVT::Other)
60272 return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
60274 return Res;
60277 // Make sure it isn't a register that requires 64-bit mode.
60278 if (!Subtarget.is64Bit() &&
60279 (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
60280 TRI->getEncodingValue(Res.first) >= 8) {
60281 // Register requires REX prefix, but we're in 32-bit mode.
60282 return std::make_pair(0, nullptr);
60285 // Make sure it isn't a register that requires AVX512.
60286 if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
60287 TRI->getEncodingValue(Res.first) & 0x10) {
60288 // Register requires EVEX prefix.
60289 return std::make_pair(0, nullptr);
60292 // Otherwise, check to see if this is a register class of the wrong value
60293 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
60294 // turn into {ax},{dx}.
60295 // MVT::Other is used to specify clobber names.
60296 if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
60297 return Res; // Correct type already, nothing to do.
60299 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
60300 // return "eax". This should even work for things like getting 64bit integer
60301 // registers when given an f64 type.
60302 const TargetRegisterClass *Class = Res.second;
60303 // The generic code will match the first register class that contains the
60304 // given register. Thus, based on the ordering of the tablegened file,
60305 // the "plain" GR classes might not come first.
60306 // Therefore, use a helper method.
60307 if (isGRClass(*Class)) {
60308 unsigned Size = VT.getSizeInBits();
60309 if (Size == 1) Size = 8;
60310 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
60311 return std::make_pair(0, nullptr);
60312 Register DestReg = getX86SubSuperRegister(Res.first, Size);
60313 if (DestReg.isValid()) {
60314 bool is64Bit = Subtarget.is64Bit();
60315 const TargetRegisterClass *RC =
60316 Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
60317 : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
60318 : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
60319 : /*Size == 64*/ (is64Bit ? &X86::GR64RegClass : nullptr);
60320 if (Size == 64 && !is64Bit) {
60321 // Model GCC's behavior here and select a fixed pair of 32-bit
60322 // registers.
60323 switch (DestReg) {
60324 case X86::RAX:
60325 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
60326 case X86::RDX:
60327 return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
60328 case X86::RCX:
60329 return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
60330 case X86::RBX:
60331 return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
60332 case X86::RSI:
60333 return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
60334 case X86::RDI:
60335 return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
60336 case X86::RBP:
60337 return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
60338 default:
60339 return std::make_pair(0, nullptr);
60342 if (RC && RC->contains(DestReg))
60343 return std::make_pair(DestReg, RC);
60344 return Res;
60346 // No register found/type mismatch.
60347 return std::make_pair(0, nullptr);
60348 } else if (isFRClass(*Class)) {
60349 // Handle references to XMM physical registers that got mapped into the
60350 // wrong class. This can happen with constraints like {xmm0} where the
60351 // target independent register mapper will just pick the first match it can
60352 // find, ignoring the required type.
60354 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
60355 if (VT == MVT::f16)
60356 Res.second = &X86::FR16XRegClass;
60357 else if (VT == MVT::f32 || VT == MVT::i32)
60358 Res.second = &X86::FR32XRegClass;
60359 else if (VT == MVT::f64 || VT == MVT::i64)
60360 Res.second = &X86::FR64XRegClass;
60361 else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
60362 Res.second = &X86::VR128XRegClass;
60363 else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
60364 Res.second = &X86::VR256XRegClass;
60365 else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
60366 Res.second = &X86::VR512RegClass;
60367 else {
60368 // Type mismatch and not a clobber: Return an error;
60369 Res.first = 0;
60370 Res.second = nullptr;
60372 } else if (isVKClass(*Class)) {
60373 if (VT == MVT::v1i1 || VT == MVT::i1)
60374 Res.second = &X86::VK1RegClass;
60375 else if (VT == MVT::v8i1 || VT == MVT::i8)
60376 Res.second = &X86::VK8RegClass;
60377 else if (VT == MVT::v16i1 || VT == MVT::i16)
60378 Res.second = &X86::VK16RegClass;
60379 else if (VT == MVT::v32i1 || VT == MVT::i32)
60380 Res.second = &X86::VK32RegClass;
60381 else if (VT == MVT::v64i1 || VT == MVT::i64)
60382 Res.second = &X86::VK64RegClass;
60383 else {
60384 // Type mismatch and not a clobber: Return an error;
60385 Res.first = 0;
60386 Res.second = nullptr;
60390 return Res;
60393 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
60394 // Integer division on x86 is expensive. However, when aggressively optimizing
60395 // for code size, we prefer to use a div instruction, as it is usually smaller
60396 // than the alternative sequence.
60397 // The exception to this is vector division. Since x86 doesn't have vector
60398 // integer division, leaving the division as-is is a loss even in terms of
60399 // size, because it will have to be scalarized, while the alternative code
60400 // sequence can be performed in vector form.
60401 bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
60402 return OptSize && !VT.isVector();
60405 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
60406 if (!Subtarget.is64Bit())
60407 return;
60409 // Update IsSplitCSR in X86MachineFunctionInfo.
60410 X86MachineFunctionInfo *AFI =
60411 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
60412 AFI->setIsSplitCSR(true);
60415 void X86TargetLowering::insertCopiesSplitCSR(
60416 MachineBasicBlock *Entry,
60417 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
60418 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
60419 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
60420 if (!IStart)
60421 return;
60423 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
60424 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
60425 MachineBasicBlock::iterator MBBI = Entry->begin();
60426 for (const MCPhysReg *I = IStart; *I; ++I) {
60427 const TargetRegisterClass *RC = nullptr;
60428 if (X86::GR64RegClass.contains(*I))
60429 RC = &X86::GR64RegClass;
60430 else
60431 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
60433 Register NewVR = MRI->createVirtualRegister(RC);
60434 // Create copy from CSR to a virtual register.
60435 // FIXME: this currently does not emit CFI pseudo-instructions, it works
60436 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
60437 // nounwind. If we want to generalize this later, we may need to emit
60438 // CFI pseudo-instructions.
60439 assert(
60440 Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
60441 "Function should be nounwind in insertCopiesSplitCSR!");
60442 Entry->addLiveIn(*I);
60443 BuildMI(*Entry, MBBI, MIMetadata(), TII->get(TargetOpcode::COPY), NewVR)
60444 .addReg(*I);
60446 // Insert the copy-back instructions right before the terminator.
60447 for (auto *Exit : Exits)
60448 BuildMI(*Exit, Exit->getFirstTerminator(), MIMetadata(),
60449 TII->get(TargetOpcode::COPY), *I)
60450 .addReg(NewVR);
60454 bool X86TargetLowering::supportSwiftError() const {
60455 return Subtarget.is64Bit();
60458 MachineInstr *
60459 X86TargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
60460 MachineBasicBlock::instr_iterator &MBBI,
60461 const TargetInstrInfo *TII) const {
60462 assert(MBBI->isCall() && MBBI->getCFIType() &&
60463 "Invalid call instruction for a KCFI check");
60465 MachineFunction &MF = *MBB.getParent();
60466 // If the call target is a memory operand, unfold it and use R11 for the
60467 // call, so KCFI_CHECK won't have to recompute the address.
60468 switch (MBBI->getOpcode()) {
60469 case X86::CALL64m:
60470 case X86::CALL64m_NT:
60471 case X86::TAILJMPm64:
60472 case X86::TAILJMPm64_REX: {
60473 MachineBasicBlock::instr_iterator OrigCall = MBBI;
60474 SmallVector<MachineInstr *, 2> NewMIs;
60475 if (!TII->unfoldMemoryOperand(MF, *OrigCall, X86::R11, /*UnfoldLoad=*/true,
60476 /*UnfoldStore=*/false, NewMIs))
60477 report_fatal_error("Failed to unfold memory operand for a KCFI check");
60478 for (auto *NewMI : NewMIs)
60479 MBBI = MBB.insert(OrigCall, NewMI);
60480 assert(MBBI->isCall() &&
60481 "Unexpected instruction after memory operand unfolding");
60482 if (OrigCall->shouldUpdateCallSiteInfo())
60483 MF.moveCallSiteInfo(&*OrigCall, &*MBBI);
60484 MBBI->setCFIType(MF, OrigCall->getCFIType());
60485 OrigCall->eraseFromParent();
60486 break;
60488 default:
60489 break;
60492 MachineOperand &Target = MBBI->getOperand(0);
60493 Register TargetReg;
60494 switch (MBBI->getOpcode()) {
60495 case X86::CALL64r:
60496 case X86::CALL64r_NT:
60497 case X86::TAILJMPr64:
60498 case X86::TAILJMPr64_REX:
60499 assert(Target.isReg() && "Unexpected target operand for an indirect call");
60500 Target.setIsRenamable(false);
60501 TargetReg = Target.getReg();
60502 break;
60503 case X86::CALL64pcrel32:
60504 case X86::TAILJMPd64:
60505 assert(Target.isSymbol() && "Unexpected target operand for a direct call");
60506 // X86TargetLowering::EmitLoweredIndirectThunk always uses r11 for
60507 // 64-bit indirect thunk calls.
60508 assert(StringRef(Target.getSymbolName()).ends_with("_r11") &&
60509 "Unexpected register for an indirect thunk call");
60510 TargetReg = X86::R11;
60511 break;
60512 default:
60513 llvm_unreachable("Unexpected CFI call opcode");
60514 break;
60517 return BuildMI(MBB, MBBI, MIMetadata(*MBBI), TII->get(X86::KCFI_CHECK))
60518 .addReg(TargetReg)
60519 .addImm(MBBI->getCFIType())
60520 .getInstr();
60523 /// Returns true if stack probing through a function call is requested.
60524 bool X86TargetLowering::hasStackProbeSymbol(const MachineFunction &MF) const {
60525 return !getStackProbeSymbolName(MF).empty();
60528 /// Returns true if stack probing through inline assembly is requested.
60529 bool X86TargetLowering::hasInlineStackProbe(const MachineFunction &MF) const {
60531 // No inline stack probe for Windows, they have their own mechanism.
60532 if (Subtarget.isOSWindows() ||
60533 MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
60534 return false;
60536 // If the function specifically requests inline stack probes, emit them.
60537 if (MF.getFunction().hasFnAttribute("probe-stack"))
60538 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
60539 "inline-asm";
60541 return false;
60544 /// Returns the name of the symbol used to emit stack probes or the empty
60545 /// string if not applicable.
60546 StringRef
60547 X86TargetLowering::getStackProbeSymbolName(const MachineFunction &MF) const {
60548 // Inline Stack probes disable stack probe call
60549 if (hasInlineStackProbe(MF))
60550 return "";
60552 // If the function specifically requests stack probes, emit them.
60553 if (MF.getFunction().hasFnAttribute("probe-stack"))
60554 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
60556 // Generally, if we aren't on Windows, the platform ABI does not include
60557 // support for stack probes, so don't emit them.
60558 if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
60559 MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
60560 return "";
60562 // We need a stack probe to conform to the Windows ABI. Choose the right
60563 // symbol.
60564 if (Subtarget.is64Bit())
60565 return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
60566 return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
60569 unsigned
60570 X86TargetLowering::getStackProbeSize(const MachineFunction &MF) const {
60571 // The default stack probe size is 4096 if the function has no stackprobesize
60572 // attribute.
60573 return MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size",
60574 4096);
60577 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
60578 if (ML && ML->isInnermost() &&
60579 ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
60580 return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
60581 return TargetLowering::getPrefLoopAlignment();