LLVM 24.0.0git
X86ISelLowering.cpp
Go to the documentation of this file.
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that X86 uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86ISelLowering.h"
16#include "X86.h"
17#include "X86FrameLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86IntrinsicsInfo.h"
21#include "X86TargetMachine.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/Intrinsics.h"
54#include "llvm/MC/MCAsmInfo.h"
55#include "llvm/MC/MCContext.h"
56#include "llvm/MC/MCExpr.h"
57#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <bitset>
66#include <cctype>
67#include <numeric>
68using namespace llvm;
69
70#define DEBUG_TYPE "x86-isel"
71
73 "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
75 "Sets the preferable loop alignment for experiments (as log2 bytes) "
76 "for innermost loops only. If specified, this option overrides "
77 "alignment set by x86-experimental-pref-loop-alignment."),
79
81 "x86-br-merging-base-cost", cl::init(2),
83 "Sets the cost threshold for when multiple conditionals will be merged "
84 "into one branch versus be split in multiple branches. Merging "
85 "conditionals saves branches at the cost of additional instructions. "
86 "This value sets the instruction cost limit, below which conditionals "
87 "will be merged, and above which conditionals will be split. Set to -1 "
88 "to never merge branches."),
90
92 "x86-br-merging-ccmp-bias", cl::init(6),
93 cl::desc("Increases 'x86-br-merging-base-cost' in cases that the target "
94 "supports conditional compare instructions."),
96
97static cl::opt<bool>
98 WidenShift("x86-widen-shift", cl::init(true),
99 cl::desc("Replace narrow shifts with wider shifts."),
100 cl::Hidden);
101
103 "x86-br-merging-likely-bias", cl::init(0),
104 cl::desc("Increases 'x86-br-merging-base-cost' in cases that it is likely "
105 "that all conditionals will be executed. For example for merging "
106 "the conditionals (a == b && c > d), if its known that a == b is "
107 "likely, then it is likely that if the conditionals are split "
108 "both sides will be executed, so it may be desirable to increase "
109 "the instruction cost threshold. Set to -1 to never merge likely "
110 "branches."),
111 cl::Hidden);
112
114 "x86-br-merging-unlikely-bias", cl::init(-1),
115 cl::desc(
116 "Decreases 'x86-br-merging-base-cost' in cases that it is unlikely "
117 "that all conditionals will be executed. For example for merging "
118 "the conditionals (a == b && c > d), if its known that a == b is "
119 "unlikely, then it is unlikely that if the conditionals are split "
120 "both sides will be executed, so it may be desirable to decrease "
121 "the instruction cost threshold. Set to -1 to never merge unlikely "
122 "branches."),
123 cl::Hidden);
124
126 "mul-constant-optimization", cl::init(true),
127 cl::desc("Replace 'mul x, Const' with more effective instructions like "
128 "SHIFT, LEA, etc."),
129 cl::Hidden);
130
132 const X86Subtarget &STI)
133 : TargetLowering(TM, STI), Subtarget(STI) {
134 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
135 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
136
137 // Set up the TargetLowering object.
138
139 // X86 is weird. It always uses i8 for shift amounts and setcc results.
141 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
143
144 // X86 instruction cache is coherent with its data cache so we can use the
145 // default expansion to a no-op.
147
148 // For 64-bit, since we have so many registers, use the ILP scheduler.
149 // For 32-bit, use the register pressure specific scheduling.
150 // For Atom, always use ILP scheduling.
151 if (Subtarget.isAtom())
153 else if (Subtarget.is64Bit())
155 else
157 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
158 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
159
160 // Bypass expensive divides and use cheaper ones.
161 if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
162 if (Subtarget.hasSlowDivide32())
163 addBypassSlowDiv(32, 8);
164 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
165 addBypassSlowDiv(64, 32);
166 }
167
168 if (Subtarget.canUseCMPXCHG16B())
170 else if (Subtarget.canUseCMPXCHG8B())
172 else
174
175 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
176
178
179 // Set up the register classes.
180 addRegisterClass(MVT::i8, &X86::GR8RegClass);
181 addRegisterClass(MVT::i16, &X86::GR16RegClass);
182 addRegisterClass(MVT::i32, &X86::GR32RegClass);
183 if (Subtarget.is64Bit())
184 addRegisterClass(MVT::i64, &X86::GR64RegClass);
185
186 for (MVT VT : MVT::integer_valuetypes())
188
189 // We don't accept any truncstore of integer registers.
190 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
191 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
192 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
193 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
194 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
195 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
196
197 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
198
199 // SETOEQ and SETUNE require checking two conditions.
200 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
203 }
204
205 // Integer absolute.
206 if (Subtarget.canUseCMOV()) {
207 setOperationAction(ISD::ABS , MVT::i16 , Custom);
208 setOperationAction(ISD::ABS , MVT::i32 , Custom);
209 if (Subtarget.is64Bit())
210 setOperationAction(ISD::ABS , MVT::i64 , Custom);
211 }
212
213 // Absolute difference.
214 for (auto Op : {ISD::ABDS, ISD::ABDU}) {
215 setOperationAction(Op , MVT::i8 , Custom);
216 setOperationAction(Op , MVT::i16 , Custom);
217 setOperationAction(Op , MVT::i32 , Custom);
218 if (Subtarget.is64Bit())
219 setOperationAction(Op , MVT::i64 , Custom);
220 }
221
222 // Signed saturation subtraction.
226 if (Subtarget.is64Bit())
228
229 // Funnel shifts.
230 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
231 // For slow shld targets we only lower for code size.
232 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
233
234 setOperationAction(ShiftOp , MVT::i8 , Custom);
235 setOperationAction(ShiftOp , MVT::i16 , Custom);
236 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
237 if (Subtarget.is64Bit())
238 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
239 }
240
241 if (!Subtarget.useSoftFloat()) {
242 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
243 // operation.
248 // We have an algorithm for SSE2, and we turn this into a 64-bit
249 // FILD or VCVTUSI2SS/SD for other targets.
252 // We have an algorithm for SSE2->double, and we turn this into a
253 // 64-bit FILD followed by conditional FADD for other targets.
256
257 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
258 // this operation.
261 // SSE has no i16 to fp conversion, only i32. We promote in the handler
262 // to allow f80 to use i16 and f64 to use i16 with sse1 only
265 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
268 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
269 // are Legal, f80 is custom lowered.
272
273 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
274 // this operation.
276 // FIXME: This doesn't generate invalid exception when it should. PR44019.
282 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
283 // are Legal, f80 is custom lowered.
286
287 // Handle FP_TO_UINT by promoting the destination to a larger signed
288 // conversion.
290 // FIXME: This doesn't generate invalid exception when it should. PR44019.
293 // FIXME: This doesn't generate invalid exception when it should. PR44019.
299
304
305 if (!Subtarget.is64Bit() && Subtarget.hasX87()) {
308 }
309 }
310
311 if (Subtarget.hasSSE2()) {
312 // Custom lowering for saturating float to int conversions.
313 // We handle promotion to larger result types manually.
314 for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
317 }
318 if (Subtarget.is64Bit()) {
321 }
322 }
323 if (Subtarget.hasAVX10_2()) {
324 for (MVT VT : {MVT::v8i8, MVT::v16i8, MVT::v32i8}) {
327 }
332 for (MVT VT : {MVT::i32, MVT::v4i32, MVT::v8i32, MVT::v16i32, MVT::v2i64,
333 MVT::v4i64}) {
336 }
337 if (Subtarget.is64Bit()) {
340 }
341 }
342
343 // Handle address space casts between mixed sized pointers.
346
347 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
348 if (!Subtarget.hasSSE2()) {
351 if (Subtarget.is64Bit()) {
353 // Without SSE, i64->f64 goes through memory.
355 }
356 } else if (!Subtarget.is64Bit())
358
359 // Scalar integer divide and remainder are lowered to use operations that
360 // produce two results, to match the available instructions. This exposes
361 // the two-result form to trivial CSE, which is able to combine x/y and x%y
362 // into a single instruction.
363 //
364 // Scalar integer multiply-high is also lowered to use two-result
365 // operations, to match the available instructions. However, plain multiply
366 // (low) operations are left as Legal, as there are single-result
367 // instructions for this in x86. Using the two-result multiply instructions
368 // when both high and low results are needed must be arranged by dagcombine.
369 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
376 }
377
378 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
380 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
381 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
384 }
385 if (Subtarget.is64Bit())
390
395
396 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
402 }
403
404 // Promote the i8 variants and force them on up to i32 which has a shorter
405 // encoding.
406 setOperationPromotedToType(ISD::CTTZ, MVT::i8, MVT::i32);
408 // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
409 // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
410 // promote that too.
411 setOperationPromotedToType(ISD::CTTZ, MVT::i16, MVT::i32);
413
414 if (!Subtarget.hasBMI()) {
417 if (Subtarget.is64Bit()) {
420 }
421 }
422
423 if (Subtarget.hasLZCNT()) {
424 // When promoting the i8 variants, force them to i32 for a shorter
425 // encoding.
426 setOperationPromotedToType(ISD::CTLZ, MVT::i8, MVT::i32);
428 } else {
429 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
430 if (VT == MVT::i64 && !Subtarget.is64Bit())
431 continue;
434 }
435 }
436
439 // Special handling for half-precision floating point conversions.
440 // If we don't have F16C support, then lower half float conversions
441 // into library calls.
443 Op, MVT::f32,
444 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
445 // There's never any support for operations beyond MVT::f32.
446 setOperationAction(Op, MVT::f64, Expand);
447 setOperationAction(Op, MVT::f80, Expand);
448 setOperationAction(Op, MVT::f128, Expand);
449 }
450
451 for (auto VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
454 }
455
456 for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
457 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
458 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
459 setTruncStoreAction(VT, MVT::f16, Expand);
460 setTruncStoreAction(VT, MVT::bf16, Expand);
461
464 }
465
469 if (Subtarget.is64Bit())
471 if (Subtarget.hasPOPCNT()) {
472 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
473 // popcntw is longer to encode than popcntl and also has a false dependency
474 // on the dest that popcntl hasn't had since Cannon Lake.
475 setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
476 } else {
481 }
482
483 if (Subtarget.hasBMI2()) {
487 if (Subtarget.is64Bit())
489 }
490
492
493 if (!Subtarget.hasMOVBE())
495
496 // X86 wants to expand cmov itself.
497 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
502 }
503 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
504 if (VT == MVT::i64 && !Subtarget.is64Bit())
505 continue;
508 }
509
511
512 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
515
517 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
518 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
522
523 // Darwin ABI issue.
524 for (auto VT : { MVT::i32, MVT::i64 }) {
525 if (VT == MVT::i64 && !Subtarget.is64Bit())
526 continue;
533 }
534
535 // 64-bit shl, sra, srl (iff 32-bit x86)
536 for (auto VT : { MVT::i32, MVT::i64 }) {
537 if (VT == MVT::i64 && !Subtarget.is64Bit())
538 continue;
542 }
543
544 if (Subtarget.hasSSEPrefetch())
546
548
549 // Expand certain atomics
550 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
558 }
559
560 if (!Subtarget.is64Bit())
562
563 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
564 // All CPUs supporting AVX will atomically load/store aligned 128-bit
565 // values, so we can emit [V]MOVAPS/[V]MOVDQA.
568 }
569
570 if (Subtarget.canUseCMPXCHG16B())
572
573 // 32-bit Windows non-GNU EH (MSVC/Itanium SEH) does not use per-invoke EH
574 // labels, so expand them away. SjLj EH does use them.
575 if (Subtarget.isTargetWin32() && !Subtarget.isTargetCygMing() &&
576 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
578 }
579
582
585
586 setOperationAction(ISD::TRAP, MVT::Other, Legal);
588 if (Subtarget.isTargetPS())
590 else
592
593 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
595 setOperationAction(ISD::VAEND , MVT::Other, Expand);
596 bool Is64Bit = Subtarget.is64Bit();
597 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
598 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
599
602
604
605 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
608
610
611 auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
612 setOperationAction(ISD::FABS, VT, Action);
613 setOperationAction(ISD::FNEG, VT, Action);
615 setOperationAction(ISD::FREM, VT, Action);
616 setOperationAction(ISD::FMA, VT, Action);
617 setOperationAction(ISD::FMINNUM, VT, Action);
618 setOperationAction(ISD::FMAXNUM, VT, Action);
623 setOperationAction(ISD::FSIN, VT, Action);
624 setOperationAction(ISD::FCOS, VT, Action);
625 setOperationAction(ISD::FSINCOS, VT, Action);
626 setOperationAction(ISD::FTAN, VT, Action);
627 setOperationAction(ISD::FSQRT, VT, Action);
628 setOperationAction(ISD::FPOW, VT, Action);
629 setOperationAction(ISD::FPOWI, VT, Action);
630 setOperationAction(ISD::FLOG, VT, Action);
631 setOperationAction(ISD::FLOG2, VT, Action);
632 setOperationAction(ISD::FLOG10, VT, Action);
633 setOperationAction(ISD::FEXP, VT, Action);
634 setOperationAction(ISD::FEXP2, VT, Action);
635 setOperationAction(ISD::FEXP10, VT, Action);
636 setOperationAction(ISD::FCEIL, VT, Action);
637 setOperationAction(ISD::FFLOOR, VT, Action);
639 setOperationAction(ISD::FRINT, VT, Action);
640 setOperationAction(ISD::BR_CC, VT, Action);
641 setOperationAction(ISD::SETCC, VT, Action);
644 setOperationAction(ISD::FROUND, VT, Action);
646 setOperationAction(ISD::FTRUNC, VT, Action);
647 setOperationAction(ISD::FLDEXP, VT, Action);
648 setOperationAction(ISD::FFREXP, VT, Action);
650 };
651
652 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
653 // f16, f32 and f64 use SSE.
654 // Set up the FP register classes.
655 addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
656 : &X86::FR16RegClass);
657 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
658 : &X86::FR32RegClass);
659 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
660 : &X86::FR64RegClass);
661
662 // Disable f32->f64 extload as we can only generate this in one instruction
663 // under optsize. So its easier to pattern match (fpext (load)) for that
664 // case instead of needing to emit 2 instructions for extload in the
665 // non-optsize case.
666 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
667
668 for (auto VT : { MVT::f32, MVT::f64 }) {
669 // Use ANDPD to simulate FABS.
671
672 // Use XORP to simulate FNEG.
674
675 // Use ANDPD and ORPD to simulate FCOPYSIGN.
677
678 // These might be better off as horizontal vector ops.
681
682 // We don't support sin/cos/fmod
686 }
687
688 // Half type will be promoted by default.
689 setF16Action(MVT::f16, Promote);
700
730
735
740
743
744 // Lower this to MOVMSK plus an AND.
747
748 } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
749 (UseX87 || Is64Bit)) {
750 // Use SSE for f32, x87 for f64.
751 // Set up the FP register classes.
752 addRegisterClass(MVT::f32, &X86::FR32RegClass);
753 if (UseX87)
754 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
755
756 // Use ANDPS to simulate FABS.
758
759 // Use XORP to simulate FNEG.
761
762 if (UseX87)
764
765 // Use ANDPS and ORPS to simulate FCOPYSIGN.
766 if (UseX87)
769
770 // We don't support sin/cos/fmod
774
775 if (UseX87) {
776 // Always expand sin/cos functions even though x87 has an instruction.
780 }
781 } else if (UseX87) {
782 // f32 and f64 in x87.
783 // Set up the FP register classes.
784 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
785 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
786
787 for (auto VT : { MVT::f32, MVT::f64 }) {
790
791 // Always expand sin/cos functions even though x87 has an instruction.
795 }
796 }
797
798 // Expand FP32 immediates into loads from the stack, save special cases.
799 if (isTypeLegal(MVT::f32)) {
800 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
801 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
802 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
803 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
804 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
805 } else // SSE immediates.
806 addLegalFPImmediate(APFloat(+0.0f)); // xorps
807 }
808 // Expand FP64 immediates into loads from the stack, save special cases.
809 if (isTypeLegal(MVT::f64)) {
810 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
811 addLegalFPImmediate(APFloat(+0.0)); // FLD0
812 addLegalFPImmediate(APFloat(+1.0)); // FLD1
813 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
814 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
815 } else // SSE immediates.
816 addLegalFPImmediate(APFloat(+0.0)); // xorpd
817 }
818 // Support fp16 0 immediate.
819 if (isTypeLegal(MVT::f16))
820 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
821
822 // Handle constrained floating-point operations of scalar.
835
836 // We don't support FMA.
839
840 // f80 always uses X87.
841 if (UseX87) {
842 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
845 {
847 addLegalFPImmediate(TmpFlt); // FLD0
848 TmpFlt.changeSign();
849 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
850
851 bool ignored;
852 APFloat TmpFlt2(+1.0);
854 &ignored);
855 addLegalFPImmediate(TmpFlt2); // FLD1
856 TmpFlt2.changeSign();
857 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
858 }
859
860 // Always expand sin/cos functions even though x87 has an instruction.
861 // clang-format off
873 // clang-format on
874
886
887 // Handle constrained floating-point operations of scalar.
894 if (isTypeLegal(MVT::f16)) {
897 } else {
899 }
900 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
901 // as Custom.
903 }
904
905 // f128 uses xmm registers, but most operations require libcalls.
906 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
907 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
908 : &X86::VR128RegClass);
909
910 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
911
922
926
927 // clang-format off
935 // clang-format on
936 // No STRICT_FSINCOS
939
942 // We need to custom handle any FP_ROUND with an f128 input, but
943 // LegalizeDAG uses the result type to know when to run a custom handler.
944 // So we have to list all legal floating point result types here.
945 if (isTypeLegal(MVT::f32)) {
948 }
949 if (isTypeLegal(MVT::f64)) {
952 }
953 if (isTypeLegal(MVT::f80)) {
957 }
958
960
961 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
962 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
963 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
964 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
965 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
966 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
967 }
968
969 // Always use a library call for pow.
970 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
971 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
972 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
973 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
974
983
984 // Some FP actions are always expanded for vector types.
985 for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
986 MVT::v4f32, MVT::v8f32, MVT::v16f32,
987 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
988 // clang-format off
1002 // clang-format on
1003 }
1004
1005 // First set operation action for all vector types to either promote
1006 // (for widening) or expand (for scalarization). Then we will selectively
1007 // turn on ones that can be effectively codegen'd.
1047 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1048 setTruncStoreAction(InnerVT, VT, Expand);
1049
1050 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
1051 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
1052
1053 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
1054 // types, we have to deal with them whether we ask for Expansion or not.
1055 // Setting Expand causes its own optimisation problems though, so leave
1056 // them legal.
1057 if (VT.getVectorElementType() == MVT::i1)
1058 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1059
1060 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
1061 // split/scalarized right now.
1062 if (VT.getVectorElementType() == MVT::f16 ||
1063 VT.getVectorElementType() == MVT::bf16)
1064 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1065 }
1066 }
1067
1068 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
1069 // with -msoft-float, disable use of MMX as well.
1070 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
1071 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
1072 // No operations on x86mmx supported, everything uses intrinsics.
1073 }
1074
1075 auto SetFPMinMaxAction = [&](MVT VT) {
1084 };
1085
1086 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
1087 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1088 : &X86::VR128RegClass);
1089
1090 SetFPMinMaxAction(MVT::f32);
1091
1092 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
1093 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
1101
1102 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
1103 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
1105
1111 }
1112
1113 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1114 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1115 : &X86::VR128RegClass);
1116
1117 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1118 // registers cannot be used even for integer operations.
1119 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1120 : &X86::VR128RegClass);
1121 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1122 : &X86::VR128RegClass);
1123 addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1124 : &X86::VR128RegClass);
1125 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1126 : &X86::VR128RegClass);
1127 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1128 : &X86::VR128RegClass);
1129
1130 for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 })
1131 SetFPMinMaxAction(VT);
1132
1133 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
1134 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
1135 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
1136
1137 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1138 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1139 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1140 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
1141 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
1142 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
1143 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
1144 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
1145 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
1146 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1149
1150 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
1151 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
1152 setOperationAction(ISD::UMULO, MVT::v2i32, Custom);
1153
1154 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
1156 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
1158
1159 setOperationAction(ISD::LRINT, MVT::v4f32, Custom);
1160 setOperationAction(ISD::LRINT, MVT::v2i32, Custom);
1161
1162 setOperationAction(ISD::AND, MVT::i128, Custom);
1163 setOperationAction(ISD::OR, MVT::i128, Custom);
1164 setOperationAction(ISD::XOR, MVT::i128, Custom);
1166
1167 if (Subtarget.hasPCLMUL()) {
1168 for (auto VT : {MVT::i64, MVT::v4i32, MVT::v2i64}) {
1171 }
1175 }
1176
1177 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1178 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1179 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1180 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1181 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1182 }
1183
1184 // SSE2 can use basic vector unrolling.
1185 // SSE41 can use PHMINPOS to perform v16i8/v8i16 minmax reductions.
1186 // Fallback to ReplaceNodeResults for vXi64 reductions on 32-bit targets.
1187 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::i64}) {
1196 }
1197
1208
1213
1214 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1220
1221 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1222 // setcc all the way to isel and prefer SETGT in some isel patterns.
1225 }
1226
1227 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
1228 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
1233
1234 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1240 }
1241
1242 for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1246
1247 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1248 continue;
1249
1252 }
1253 setF16Action(MVT::v8f16, Expand);
1254 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1255 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1256 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1257 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1258 setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1259 setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1261
1262 // Custom lower v2i64 and v2f64 selects.
1269
1276
1277 // Custom legalize these to avoid over promotion or custom promotion.
1278 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1283 }
1284
1289
1292
1295
1296 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1301
1306
1307 // We want to legalize this to an f64 load rather than an i64 load on
1308 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1309 // store.
1310 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1311 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1312 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1313 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1314 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1316
1317 // Add 32-bit vector stores to help vectorization opportunities.
1318 setOperationAction(ISD::STORE, MVT::v2i16, Custom);
1320
1324 if (!Subtarget.hasAVX512())
1326
1330
1332
1349
1350 // In the customized shift lowering, the legal v4i32/v2i64 cases
1351 // in AVX2 will be recognized.
1352 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1356 if (VT == MVT::v2i64) continue;
1361 }
1362
1368 }
1369
1370 if (!Subtarget.useSoftFloat() && Subtarget.hasGFNI()) {
1375
1376 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1378 }
1379
1380 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1381 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
1382 }
1383
1384 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1385 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1386 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1387 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1388
1389 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1392 }
1394
1395 // These might be better off as horizontal vector ops.
1400 }
1401 if (Subtarget.hasNDD()) {
1402 // Enable custom lowering for scalar USUBSAT to optimize usub.sat(X,1)
1403 // with cmp+adc when NDD is available.
1408 }
1409 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1410 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1413 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1417 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1423
1425 }
1426
1427 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1428 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1429 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1430 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1431 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1432 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1433 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1434 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1435
1439
1440 // FIXME: Do we need to handle scalar-to-vector here?
1441 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1442 setOperationAction(ISD::SMULO, MVT::v2i32, Custom);
1443
1444 // We directly match byte blends in the backend as they match the VSELECT
1445 // condition form.
1447
1448 // SSE41 brings specific instructions for doing vector sign extend even in
1449 // cases where we don't have SRA.
1450 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1453 }
1454
1455 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1456 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1457 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1458 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1459 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1460 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1461 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1462 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1463 }
1464
1465 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1466 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1467 // do the pre and post work in the vector domain.
1470 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1471 // so that DAG combine doesn't try to turn it into uint_to_fp.
1474 }
1475 }
1476
1477 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1479 }
1480
1481 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1482 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1483 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1486 }
1487
1488 // XOP can efficiently perform BITREVERSE with VPPERM.
1489 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1491 }
1492
1493 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1494 bool HasInt256 = Subtarget.hasInt256();
1495
1496 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1497 : &X86::VR256RegClass);
1498 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1499 : &X86::VR256RegClass);
1500 addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1501 : &X86::VR256RegClass);
1502 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1503 : &X86::VR256RegClass);
1504 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1505 : &X86::VR256RegClass);
1506 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1507 : &X86::VR256RegClass);
1508 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1509 : &X86::VR256RegClass);
1510
1511 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1524
1526
1531 SetFPMinMaxAction(VT);
1532 }
1533
1534 setOperationAction(ISD::LRINT, MVT::v8f32, Custom);
1535 setOperationAction(ISD::LRINT, MVT::v4f64, Custom);
1536
1537 setOperationAction(ISD::AND, MVT::i256, Custom);
1538 setOperationAction(ISD::OR, MVT::i256, Custom);
1539 setOperationAction(ISD::XOR, MVT::i256, Custom);
1542
1543 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1544 // even though v8i16 is a legal type.
1545 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1546 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1547 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1548 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1552
1559
1571
1572 if (!Subtarget.hasAVX512())
1574
1575 // In the customized shift lowering, the legal v8i32/v4i64 cases
1576 // in AVX2 will be recognized.
1577 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1591 if (VT == MVT::v4i64) continue;
1596 }
1597
1598 // These types need custom splitting if their input is a 128-bit vector.
1603
1607 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1608 setOperationAction(ISD::SELECT, MVT::v16f16, Custom);
1611
1612 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1616 }
1617
1622
1623 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1628
1629 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1630 // setcc all the way to isel and prefer SETGT in some isel patterns.
1633 }
1634
1635 setOperationAction(ISD::SETCC, MVT::v4f64, Custom);
1636 setOperationAction(ISD::SETCC, MVT::v8f32, Custom);
1641
1642 if (Subtarget.hasAnyFMA()) {
1643 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1644 MVT::v2f64, MVT::v4f64 }) {
1647 }
1648 }
1649
1650 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1651 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1652 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1653 }
1654
1655 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1656 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1657 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1658 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1659
1660 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1661 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1662 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1663 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1664 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1665 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1666 setOperationAction(ISD::AVGCEILU, MVT::v16i16, HasInt256 ? Legal : Custom);
1667 setOperationAction(ISD::AVGCEILU, MVT::v32i8, HasInt256 ? Legal : Custom);
1668
1669 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1670 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1671
1672 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1673 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1674 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1675 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1676 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1677
1678 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1679 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1680 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1681 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1682 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1683 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1684 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1685 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1690
1691 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1692 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1693 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1694 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1695 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1696 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1697 }
1698
1699 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1702 }
1703
1704 if (HasInt256) {
1705 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1706 // when we have a 256bit-wide blend with immediate.
1709
1710 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1711 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1712 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1713 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1714 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1715 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1716 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1717 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1718 }
1719 }
1720
1721 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1722 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1723 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1725 }
1726
1727 // Extract subvector is special because the value type
1728 // (result) is 128-bit but the source is 256-bit wide.
1729 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1730 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1732 }
1733
1734 // Custom lower several nodes for 256-bit types.
1735 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1736 MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1746 }
1747 setF16Action(MVT::v16f16, Expand);
1748 setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1749 setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1751 setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1752 setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1753 setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1754 setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1755
1756 // Only PCLMUL required as we always unroll clmul vectors.
1757 if (Subtarget.hasPCLMUL()) {
1758 for (auto VT : {MVT::v8i32, MVT::v4i64}) {
1761 }
1762 }
1763
1764 if (HasInt256) {
1765 setOperationAction(ISD::MULHU, MVT::v4i64, Custom);
1766 // Custom so the combiner keeps full products as [SU]MUL_LOHI, not
1767 // MULH[SU].
1771
1772 // Custom legalize 2x32 to get a little better code.
1775
1776 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1777 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1779 }
1780
1781 if (Subtarget.hasGFNI()) {
1782 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1783 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1784 }
1785 }
1786
1787 if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1788 Subtarget.hasF16C()) {
1789 for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1792 }
1793 for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1796 }
1797 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1798 setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1799 setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1800 }
1801 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
1802 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
1803 }
1804
1805 // This block controls legalization of the mask vector sizes that are
1806 // available with AVX512. 512-bit vectors are in a separate block controlled
1807 // by useAVX512Regs.
1808 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1809 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1810 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1811 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1812 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1813 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1814
1818
1819 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1820 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1821 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1822 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1823 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1824 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1825 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1826 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1834
1835 // There is no byte sized k-register load or store without AVX512DQ.
1836 if (!Subtarget.hasDQI()) {
1837 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1838 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1839 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1840 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1841
1846 }
1847
1848 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1849 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1853 }
1854
1855 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1857
1858 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1862
1869 }
1870
1871 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1873 }
1874 if (Subtarget.hasDQI() && Subtarget.hasVLX()) {
1875 for (MVT VT : {MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1878 }
1879 }
1880
1881 // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1882 // elements. 512-bits can be disabled based on prefer-vector-width and
1883 // required-vector-width function attributes.
1884 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1885 bool HasBWI = Subtarget.hasBWI();
1886
1887 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1888 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1889 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1890 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1891 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1892 addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1893 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1894
1895 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1896 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1897 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1898 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1899 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1900 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1901 if (HasBWI)
1902 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1903 }
1904
1905 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1906 SetFPMinMaxAction(VT);
1914 }
1915 setOperationAction(ISD::LRINT, MVT::v16f32,
1916 Subtarget.hasDQI() ? Legal : Custom);
1917 setOperationAction(ISD::LRINT, MVT::v8f64,
1918 Subtarget.hasDQI() ? Legal : Custom);
1919 if (Subtarget.hasDQI())
1920 setOperationAction(ISD::LLRINT, MVT::v8f64, Legal);
1921
1922 setOperationAction(ISD::AND, MVT::i512, Custom);
1923 setOperationAction(ISD::OR, MVT::i512, Custom);
1924 setOperationAction(ISD::XOR, MVT::i512, Custom);
1925 setOperationAction(ISD::ADD, MVT::i512, Custom);
1926 setOperationAction(ISD::SUB, MVT::i512, Custom);
1927 setOperationAction(ISD::SRL, MVT::i512, Custom);
1928 setOperationAction(ISD::SHL, MVT::i512, Custom);
1929 setOperationAction(ISD::SRA, MVT::i512, Custom);
1930 setOperationAction(ISD::FSHR, MVT::i512, Custom);
1931 setOperationAction(ISD::FSHL, MVT::i512, Custom);
1932 setOperationAction(ISD::FSHR, MVT::i256, Custom);
1933 setOperationAction(ISD::FSHL, MVT::i256, Custom);
1936
1937 for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1942 }
1943
1944 for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1949 }
1950
1957
1969
1970 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1971 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1972 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1973 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1974 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1975 if (HasBWI)
1976 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1977
1978 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1979 // to 512-bit rather than use the AVX2 instructions so that we can use
1980 // k-masks.
1981 if (!Subtarget.hasVLX()) {
1982 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1983 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1986 }
1987 }
1988
1990 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1991 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
2001
2002 if (HasBWI) {
2003 // Extends from v64i1 masks to 512-bit vectors.
2007 }
2008
2009 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
2022
2024 }
2025
2026 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2029 }
2030
2031 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
2032 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
2033 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
2034 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
2035
2036 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
2037 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
2038 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
2039 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
2040
2041 setOperationAction(ISD::MULHU, MVT::v8i64, Custom);
2044 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
2045 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
2046 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
2047 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
2048 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
2049 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
2050 setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
2051 setOperationAction(ISD::AVGCEILU, MVT::v64i8, HasBWI ? Legal : Custom);
2052
2053 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
2054 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
2055
2056 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
2074
2075 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
2076 // setcc all the way to isel and prefer SETGT in some isel patterns.
2079 }
2080
2081 setOperationAction(ISD::SETCC, MVT::v8f64, Custom);
2082 setOperationAction(ISD::SETCC, MVT::v16f32, Custom);
2087
2088 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
2097 }
2098
2099 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2100 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
2101 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
2103 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
2104 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
2105 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
2106 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
2111 }
2112
2113 setOperationAction(ISD::FSHL, MVT::v64i8, Custom);
2114 setOperationAction(ISD::FSHR, MVT::v64i8, Custom);
2115 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
2116 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
2117 setOperationAction(ISD::FSHL, MVT::v16i32, Custom);
2118 setOperationAction(ISD::FSHR, MVT::v16i32, Custom);
2119
2120 if (Subtarget.hasDQI() || Subtarget.hasFP16())
2124 setOperationAction(Opc, MVT::v8i64, Custom);
2125
2126 if (Subtarget.hasDQI()) {
2127 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
2128
2129 // MULHS needs vpmullq (AVX512DQ) for its low multiply to be a win.
2130 setOperationAction(ISD::MULHS, MVT::v8i64, Custom);
2131 }
2132
2133 if (Subtarget.hasCDI()) {
2134 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
2135 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
2137 }
2138 } // Subtarget.hasCDI()
2139
2140 if (Subtarget.hasVPOPCNTDQ()) {
2141 for (auto VT : { MVT::v16i32, MVT::v8i64 })
2144 }
2145
2146 // Extract subvector is special because the value type
2147 // (result) is 256-bit but the source is 512-bit wide.
2148 // 128-bit was made Legal under AVX1.
2149 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
2150 MVT::v16f16, MVT::v8f32, MVT::v4f64 })
2152
2153 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
2154 MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
2164 }
2165 setF16Action(MVT::v32f16, Expand);
2170 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2171 setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
2172 setOperationAction(ISD::SETCC, MVT::v32f16, Custom);
2173
2174 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
2179 }
2180 if (HasBWI) {
2181 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2184 }
2185 } else {
2186 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
2187 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
2188 }
2189
2190 if (Subtarget.hasVBMI2()) {
2191 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2194 }
2195
2196 setOperationAction(ISD::ROTL, MVT::v32i16, Legal);
2197 setOperationAction(ISD::ROTR, MVT::v32i16, Legal);
2198 }
2199
2200 // Only PCLMUL required as we always unroll clmul vectors.
2201 if (Subtarget.hasPCLMUL()) {
2202 for (auto VT : {MVT::v16i32, MVT::v8i64}) {
2205 }
2206 }
2207
2208 setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2209 setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2211 setOperationAction(ISD::FLDEXP, MVT::v32f16, Custom);
2212
2213 if (Subtarget.hasGFNI()) {
2214 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
2215 setOperationAction(ISD::CTTZ, MVT::v64i8, Custom);
2216 }
2217 }// useAVX512Regs
2218
2219 if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
2220 for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
2221 MVT::v4i64}) {
2224 }
2225
2226 setOperationAction(ISD::ROTL, MVT::v16i16, Legal);
2227 setOperationAction(ISD::ROTR, MVT::v16i16, Legal);
2228 setOperationAction(ISD::ROTL, MVT::v8i16, Legal);
2229 setOperationAction(ISD::ROTR, MVT::v8i16, Legal);
2230 }
2231
2232 // This block controls legalization for operations that don't have
2233 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2234 // narrower widths.
2235 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2236 for (MVT VT : {MVT::f16, MVT::f32, MVT::f64, MVT::v8f16, MVT::v4f32,
2237 MVT::v2f64, MVT::v16f16, MVT::v8f32, MVT::v4f64})
2239
2240 // These operations are handled on non-VLX by artificially widening in
2241 // isel patterns.
2245
2246 if (Subtarget.hasDQI()) {
2247 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2248 // v2f32 UINT_TO_FP is already custom under SSE2.
2251 "Unexpected operation action!");
2252 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2257 }
2258
2259 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2265 }
2266
2267 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2270 }
2271
2272 // Custom legalize 2x32 to get a little better code.
2275
2276 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2277 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2279
2280 if (Subtarget.hasDQI()) {
2284 setOperationAction(Opc, MVT::v2i64, Custom);
2285 setOperationAction(Opc, MVT::v4i64, Custom);
2286 }
2287 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2288 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2289
2290 // MULHS is only a win when the low multiply can use vpmullq; non-VLX
2291 // targets handle VPMULLQ by implicit widening.
2292 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
2293 }
2294
2295 if (Subtarget.hasCDI()) {
2296 for (auto VT : {MVT::i256, MVT::i512}) {
2297 if (VT == MVT::i512 && !Subtarget.useAVX512Regs())
2298 continue;
2303 }
2304 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2306 }
2307 } // Subtarget.hasCDI()
2308
2309 if (Subtarget.hasVPOPCNTDQ()) {
2310 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
2313 }
2314
2315 // We can try to convert vectors to different sizes to leverage legal
2316 // `vpcompress` cases. So we mark these supported vector sizes as Custom and
2317 // then specialize to Legal below.
2318 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2319 MVT::v4f64, MVT::v2i64, MVT::v2f64, MVT::v16i8, MVT::v8i16,
2320 MVT::v16i16, MVT::v8i8})
2322
2323 // Legal vpcompress depends on various AVX512 extensions.
2324 // Legal in AVX512F
2325 for (MVT VT : {MVT::v16i32, MVT::v16f32, MVT::v8i64, MVT::v8f64})
2327
2328 // Legal in AVX512F + AVX512VL
2329 if (Subtarget.hasVLX())
2330 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2331 MVT::v4f64, MVT::v2i64, MVT::v2f64})
2333
2334 // Legal in AVX512F + AVX512VBMI2
2335 if (Subtarget.hasVBMI2())
2336 for (MVT VT : {MVT::v32i16, MVT::v64i8})
2338
2339 // Legal in AVX512F + AVX512VL + AVX512VBMI2
2340 if (Subtarget.hasVBMI2() && Subtarget.hasVLX())
2341 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v32i8, MVT::v16i16})
2343 }
2344
2345 // This block control legalization of v32i1/v64i1 which are available with
2346 // AVX512BW..
2347 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2348 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
2349 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
2350
2351 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2362 }
2363
2364 for (auto VT : { MVT::v16i1, MVT::v32i1 })
2366
2367 // Extends from v32i1 masks to 256-bit vectors.
2371
2372 for (auto VT : {MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16,
2373 MVT::v16f16, MVT::v8f16}) {
2374 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
2375 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2376 }
2377
2378 // These operations are handled on non-VLX by artificially widening in
2379 // isel patterns.
2380 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2381
2382 if (Subtarget.hasBITALG()) {
2383 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2385 }
2386
2387 if (Subtarget.hasBMM()) {
2392
2393 for (auto VT : {MVT::v16i8, MVT::v32i8, MVT::v64i8})
2395 }
2396 }
2397
2398 if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2399 auto setGroup = [&] (MVT VT) {
2410
2423
2425
2428
2434
2440
2444 };
2445
2446 // AVX512_FP16 scalar operations
2447 setGroup(MVT::f16);
2448 SetFPMinMaxAction(MVT::f16);
2462
2465
2466 if (Subtarget.useAVX512Regs()) {
2467 setGroup(MVT::v32f16);
2473 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Legal);
2480
2485 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i8, MVT::v32i16);
2487 MVT::v32i16);
2488 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i8, MVT::v32i16);
2490 MVT::v32i16);
2491 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i1, MVT::v32i16);
2493 MVT::v32i16);
2494 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i1, MVT::v32i16);
2496 MVT::v32i16);
2497
2501
2502 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Legal);
2503 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2504
2505 SetFPMinMaxAction(MVT::v32f16);
2506 setOperationAction(ISD::LRINT, MVT::v32f16, Legal);
2507 setOperationAction(ISD::LLRINT, MVT::v8f16, Legal);
2508 }
2509
2514
2515 if (Subtarget.hasVLX()) {
2516 setGroup(MVT::v8f16);
2517 setGroup(MVT::v16f16);
2518
2529
2536
2537 // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2540
2544
2545 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2546 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2547 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2548 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2549
2550 // Need to custom widen these to prevent scalarization.
2551 setOperationAction(ISD::LOAD, MVT::v4f16, Custom);
2552 setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2553
2554 SetFPMinMaxAction(MVT::v8f16);
2555 SetFPMinMaxAction(MVT::v16f16);
2556
2557 setOperationAction(ISD::LRINT, MVT::v8f16, Legal);
2558 setOperationAction(ISD::LRINT, MVT::v16f16, Legal);
2559 }
2560 }
2561
2562 if (!Subtarget.useSoftFloat() &&
2563 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2564 addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2565 : &X86::VR128RegClass);
2566 addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2567 : &X86::VR256RegClass);
2568 // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2569 // provide the method to promote BUILD_VECTOR and INSERT_VECTOR_ELT.
2570 // Set the operation action Custom to do the customization later.
2573 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2574 setF16Action(VT, Expand);
2575 if (!Subtarget.hasBF16())
2581 }
2582 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
2583 setOperationPromotedToType(Opc, MVT::v8bf16, MVT::v8f32);
2584 setOperationPromotedToType(Opc, MVT::v16bf16, MVT::v16f32);
2585 }
2586 setOperationAction(ISD::SETCC, MVT::v8bf16, Custom);
2587 setOperationAction(ISD::SETCC, MVT::v16bf16, Custom);
2589 addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2590 }
2591
2592 if (!Subtarget.useSoftFloat() && Subtarget.hasBF16() &&
2593 Subtarget.useAVX512Regs()) {
2594 addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2595 setF16Action(MVT::v32bf16, Expand);
2596 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2597 setOperationPromotedToType(Opc, MVT::v32bf16, MVT::v32f32);
2598 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2600 setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2604 }
2605
2606 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX10_2()) {
2607 // Lower scalar bf16 arithmetic by widening to a vector op and extracting
2608 // the low element.
2609 setOperationAction(ISD::FADD, MVT::bf16, Custom);
2610 setOperationAction(ISD::FSUB, MVT::bf16, Custom);
2611 setOperationAction(ISD::FMUL, MVT::bf16, Custom);
2612 setOperationAction(ISD::FDIV, MVT::bf16, Custom);
2614 setOperationAction(ISD::FMA, MVT::bf16, Custom);
2615
2616 setOperationAction(ISD::FADD, MVT::v32bf16, Legal);
2617 setOperationAction(ISD::FSUB, MVT::v32bf16, Legal);
2618 setOperationAction(ISD::FMUL, MVT::v32bf16, Legal);
2619 setOperationAction(ISD::FDIV, MVT::v32bf16, Legal);
2620 setOperationAction(ISD::FSQRT, MVT::v32bf16, Legal);
2621 setOperationAction(ISD::FMA, MVT::v32bf16, Legal);
2622 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2623 SetFPMinMaxAction(MVT::v32bf16);
2624 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2632 SetFPMinMaxAction(VT);
2633 }
2634 for (auto VT : {MVT::f16, MVT::f32, MVT::f64}) {
2637 }
2638 }
2639
2640 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2641 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
2642 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2643 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2644 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
2645 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2646
2647 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
2648 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2649 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2650 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
2651 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2652
2653 if (Subtarget.hasBWI()) {
2654 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
2655 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
2656 }
2657
2658 if (Subtarget.hasFP16()) {
2659 // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2668 // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2677 // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2682 // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2687 }
2688 }
2689
2690 if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2691 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2692 }
2693
2694 // We want to custom lower some of our intrinsics.
2698 if (!Subtarget.is64Bit()) {
2700 }
2701
2702 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2703 // handle type legalization for these operations here.
2704 //
2705 // FIXME: We really should do custom legalization for addition and
2706 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
2707 // than generic legalization for 64-bit multiplication-with-overflow, though.
2708 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2709 if (VT == MVT::i64 && !Subtarget.is64Bit())
2710 continue;
2711 // Add/Sub/Mul with overflow operations are custom lowered.
2718
2719 // Support carry in as value rather than glue.
2725 }
2726
2727 // Combine sin / cos into _sincos_stret if it is available.
2730
2731 if (Subtarget.isTargetWin64()) {
2732 setOperationAction(ISD::SDIV, MVT::i128, Custom);
2733 setOperationAction(ISD::UDIV, MVT::i128, Custom);
2734 setOperationAction(ISD::SREM, MVT::i128, Custom);
2735 setOperationAction(ISD::UREM, MVT::i128, Custom);
2744 }
2745
2746 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2747 // is. We should promote the value to 64-bits to solve this.
2748 // This is what the CRT headers do - `fmodf` is an inline header
2749 // function casting to f64 and calling `fmod`.
2750 if (Subtarget.is32Bit() &&
2751 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2752 // clang-format off
2753 for (ISD::NodeType Op :
2771 // TODO: Add ISD:::STRICT_FMODF too once implemented.
2772 ISD::FMODF})
2773 if (isOperationExpandOrLibCall(Op, MVT::f32))
2774 setOperationAction(Op, MVT::f32, Promote);
2775 // clang-format on
2776
2777 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
2778 // it, but it's just a wrapper around ldexp.
2779 if (Subtarget.isOSWindows()) {
2781 if (isOperationExpand(Op, MVT::f32))
2782 setOperationAction(Op, MVT::f32, Promote);
2783 }
2784
2785 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f16, MVT::i16);
2786 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f32, MVT::i32);
2787 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f64, MVT::i64);
2788
2789 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f16, MVT::i16);
2790 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f32, MVT::i32);
2791 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f64, MVT::i64);
2792
2793 // We have target-specific dag combine patterns for the following nodes:
2804 ISD::SHL,
2805 ISD::SRA,
2806 ISD::SRL,
2807 ISD::OR,
2808 ISD::AND,
2814 ISD::ADD,
2817 ISD::FADD,
2818 ISD::FSUB,
2819 ISD::FNEG,
2820 ISD::FMA,
2826 ISD::SUB,
2828 ISD::LOAD,
2829 ISD::LRINT,
2831 ISD::MLOAD,
2832 ISD::STORE,
2853 ISD::SETCC,
2854 ISD::MUL,
2855 ISD::UDIV,
2856 ISD::SDIV,
2857 ISD::UREM,
2858 ISD::SREM,
2863 ISD::XOR,
2871 ISD::ROTL,
2872 ISD::ROTR,
2873 ISD::FSHL,
2874 ISD::FSHR,
2878
2879 computeRegisterProperties(Subtarget.getRegisterInfo());
2880
2881 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2883 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2885 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2887
2888 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2889 // that needs to benchmarked and balanced with the potential use of vector
2890 // load/store types (PR33329, PR33914).
2893
2894 // Default loop alignment, which can be overridden by -align-loops.
2896
2897 // An out-of-order CPU can speculatively execute past a predictable branch,
2898 // but a conditional move could be stalled by an expensive earlier operation.
2899 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2900 EnableExtLdPromotion = true;
2902
2904
2905 // Default to having -disable-strictnode-mutation on
2906 IsStrictFPEnabled = true;
2907}
2908
2909// This has so far only been implemented for 64-bit MachO.
2911 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2912}
2913
2915 // Currently only MSVC CRTs mix the frame pointer into the stack guard value.
2916 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2917}
2918
2920 const SDLoc &DL) const {
2921 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2922 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2923 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2924 return SDValue(Node, 0);
2925}
2926
2929 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2930 !Subtarget.hasBWI())
2931 return TypeSplitVector;
2932
2933 // Since v8f16 is legal, widen anything over v4f16.
2934 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2935 VT.getVectorNumElements() <= 4 && !Subtarget.hasF16C() &&
2936 VT.getVectorElementType() == MVT::f16)
2937 return TypeSplitVector;
2938
2939 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2940 VT.getVectorElementType() != MVT::i1)
2941 return TypeWidenVector;
2942
2944}
2945
2947 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
2948 const LibcallLoweringInfo *libcallLowering) const {
2949 return X86::createFastISel(funcInfo, libInfo, libcallLowering);
2950}
2951
2952//===----------------------------------------------------------------------===//
2953// Other Lowering Hooks
2954//===----------------------------------------------------------------------===//
2955
2957 bool AssumeSingleUse, bool IgnoreAlignment) {
2958 if (!AssumeSingleUse && !Op.hasOneUse())
2959 return false;
2960 if (!ISD::isNormalLoad(Op.getNode()))
2961 return false;
2962
2963 // If this is an unaligned vector, make sure the target supports folding it.
2964 auto *Ld = cast<LoadSDNode>(Op.getNode());
2965 if (!IgnoreAlignment && !Subtarget.hasAVX() &&
2966 !Subtarget.hasSSEUnalignedMem() && Ld->getValueSizeInBits(0) == 128 &&
2967 Ld->getAlign() < Align(16))
2968 return false;
2969
2970 // TODO: If this is a non-temporal load and the target has an instruction
2971 // for it, it should not be folded. See "useNonTemporalLoad()".
2972
2973 return true;
2974}
2975
2977 const X86Subtarget &Subtarget,
2978 bool AssumeSingleUse) {
2979 assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2980 if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2981 return false;
2982
2983 // We can not replace a wide volatile load with a broadcast-from-memory,
2984 // because that would narrow the load, which isn't legal for volatiles.
2985 auto *Ld = cast<LoadSDNode>(Op.getNode());
2986 return !Ld->isVolatile() ||
2987 Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
2988}
2989
2991 if (!Op.hasOneUse())
2992 return false;
2993 // Peek through (oneuse) bitcast users
2994 SDNode *User = *Op->user_begin();
2995 while (User->getOpcode() == ISD::BITCAST) {
2996 if (!User->hasOneUse())
2997 return false;
2998 User = *User->user_begin();
2999 }
3000 return ISD::isNormalStore(User) || User->getOpcode() == ISD::ATOMIC_STORE;
3001}
3002
3004 if (Op.hasOneUse()) {
3005 unsigned Opcode = Op.getNode()->user_begin()->getOpcode();
3006 return (ISD::ZERO_EXTEND == Opcode);
3007 }
3008 return false;
3009}
3010
3011// Return true if its cheap to bitcast this to a vector type.
3013 const X86Subtarget &Subtarget) {
3014 if (peekThroughBitcasts(Op).getValueType().isVector())
3015 return true;
3017 return true;
3018
3019 EVT VT = Op.getValueType();
3020 unsigned Opcode = Op.getOpcode();
3021 if ((VT == MVT::i128 || VT == MVT::i256 || VT == MVT::i512) &&
3022 DAG.getTargetLoweringInfo().getOperationAction(Opcode, VT) ==
3024 // Check for larger than legal scalar integer ops that might have been
3025 // custom lowered to vector instruction.
3026 switch (Opcode) {
3027 case ISD::BITREVERSE:
3028 return true;
3029 case ISD::SHL:
3030 case ISD::SRL:
3031 case ISD::SRA:
3032 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget);
3033 case ISD::AND:
3034 case ISD::OR:
3035 case ISD::XOR:
3036 case ISD::ADD:
3037 case ISD::SUB:
3038 case ISD::FSHL:
3039 case ISD::FSHR:
3040 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget) &&
3041 mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget);
3042 case ISD::SELECT:
3043 return mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget) &&
3044 mayFoldIntoVector(Op.getOperand(2), DAG, Subtarget);
3045 }
3046 }
3047 return X86::mayFoldLoad(Op, Subtarget, /*AssumeSingleUse=*/true,
3048 /*IgnoreAlignment=*/true);
3049}
3050
3051static bool isLogicOp(unsigned Opcode) {
3052 // TODO: Add support for X86ISD::FAND/FOR/FXOR/FANDN with test coverage.
3053 return ISD::isBitwiseLogicOp(Opcode) || X86ISD::ANDNP == Opcode;
3054}
3055
3056static bool isTargetShuffle(unsigned Opcode) {
3057 switch(Opcode) {
3058 default: return false;
3059 case X86ISD::BLENDI:
3060 case X86ISD::PSHUFB:
3061 case X86ISD::PSHUFD:
3062 case X86ISD::PSHUFHW:
3063 case X86ISD::PSHUFLW:
3064 case X86ISD::SHUFP:
3065 case X86ISD::INSERTPS:
3066 case X86ISD::EXTRQI:
3067 case X86ISD::INSERTQI:
3068 case X86ISD::VALIGN:
3069 case X86ISD::PALIGNR:
3070 case X86ISD::VSHLDQ:
3071 case X86ISD::VSRLDQ:
3072 case X86ISD::MOVLHPS:
3073 case X86ISD::MOVHLPS:
3074 case X86ISD::MOVSHDUP:
3075 case X86ISD::MOVSLDUP:
3076 case X86ISD::MOVDDUP:
3077 case X86ISD::MOVSS:
3078 case X86ISD::MOVSD:
3079 case X86ISD::MOVSH:
3080 case X86ISD::UNPCKL:
3081 case X86ISD::UNPCKH:
3082 case X86ISD::VBROADCAST:
3083 case X86ISD::VPERMILPI:
3084 case X86ISD::VPERMILPV:
3085 case X86ISD::VPERM2X128:
3086 case X86ISD::SHUF128:
3087 case X86ISD::VPERMIL2:
3088 case X86ISD::VPERMI:
3089 case X86ISD::VPPERM:
3090 case X86ISD::VPERMV:
3091 case X86ISD::VPERMV3:
3092 case X86ISD::VZEXT_MOVL:
3093 case X86ISD::COMPRESS:
3094 case X86ISD::EXPAND:
3095 return true;
3096 }
3097}
3098
3099static bool isTargetShuffleVariableMask(unsigned Opcode) {
3100 switch (Opcode) {
3101 default: return false;
3102 // Target Shuffles.
3103 case X86ISD::PSHUFB:
3104 case X86ISD::VPERMILPV:
3105 case X86ISD::VPERMIL2:
3106 case X86ISD::VPPERM:
3107 case X86ISD::VPERMV:
3108 case X86ISD::VPERMV3:
3109 return true;
3110 // 'Faux' Target Shuffles.
3111 case ISD::OR:
3112 case ISD::AND:
3113 case X86ISD::ANDNP:
3114 return true;
3115 }
3116}
3117
3120 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3122 int ReturnAddrIndex = FuncInfo->getRAIndex();
3123
3124 if (ReturnAddrIndex == 0) {
3125 // Set up a frame object for the return address.
3126 unsigned SlotSize = RegInfo->getSlotSize();
3127 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
3128 -(int64_t)SlotSize,
3129 false);
3130 FuncInfo->setRAIndex(ReturnAddrIndex);
3131 }
3132
3133 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3134}
3135
3137 bool HasSymbolicDisplacement) {
3138 // Offset should fit into 32 bit immediate field.
3139 if (!isInt<32>(Offset))
3140 return false;
3141
3142 // If we don't have a symbolic displacement - we don't have any extra
3143 // restrictions.
3144 if (!HasSymbolicDisplacement)
3145 return true;
3146
3147 // We can fold large offsets in the large code model because we always use
3148 // 64-bit offsets.
3149 if (CM == CodeModel::Large)
3150 return true;
3151
3152 // For kernel code model we know that all object resist in the negative half
3153 // of 32bits address space. We may not accept negative offsets, since they may
3154 // be just off and we may accept pretty large positive ones.
3155 if (CM == CodeModel::Kernel)
3156 return Offset >= 0;
3157
3158 // For other non-large code models we assume that latest small object is 16MB
3159 // before end of 31 bits boundary. We may also accept pretty large negative
3160 // constants knowing that all objects are in the positive half of address
3161 // space.
3162 return Offset < 16 * 1024 * 1024;
3163}
3164
3165/// Return true if the condition is an signed comparison operation.
3166static bool isX86CCSigned(X86::CondCode X86CC) {
3167 switch (X86CC) {
3168 default:
3169 llvm_unreachable("Invalid integer condition!");
3170 case X86::COND_E:
3171 case X86::COND_NE:
3172 case X86::COND_B:
3173 case X86::COND_A:
3174 case X86::COND_BE:
3175 case X86::COND_AE:
3176 return false;
3177 case X86::COND_G:
3178 case X86::COND_GE:
3179 case X86::COND_L:
3180 case X86::COND_LE:
3181 return true;
3182 }
3183}
3184
3186 switch (SetCCOpcode) {
3187 // clang-format off
3188 default: llvm_unreachable("Invalid integer condition!");
3189 case ISD::SETEQ: return X86::COND_E;
3190 case ISD::SETGT: return X86::COND_G;
3191 case ISD::SETGE: return X86::COND_GE;
3192 case ISD::SETLT: return X86::COND_L;
3193 case ISD::SETLE: return X86::COND_LE;
3194 case ISD::SETNE: return X86::COND_NE;
3195 case ISD::SETULT: return X86::COND_B;
3196 case ISD::SETUGT: return X86::COND_A;
3197 case ISD::SETULE: return X86::COND_BE;
3198 case ISD::SETUGE: return X86::COND_AE;
3199 // clang-format on
3200 }
3201}
3202
3203/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3204/// condition code, returning the condition code and the LHS/RHS of the
3205/// comparison to make.
3207 bool isFP, SDValue &LHS, SDValue &RHS,
3208 SelectionDAG &DAG) {
3209 if (!isFP) {
3211 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
3212 // X > -1 -> X == 0, jump !sign.
3213 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3214 return X86::COND_NS;
3215 }
3216 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
3217 // X < 0 -> X == 0, jump on sign.
3218 return X86::COND_S;
3219 }
3220 if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
3221 // X >= 0 -> X == 0, jump on !sign.
3222 return X86::COND_NS;
3223 }
3224 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
3225 // X < 1 -> X <= 0
3226 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3227 return X86::COND_LE;
3228 }
3229 }
3230
3231 return TranslateIntegerX86CC(SetCCOpcode);
3232 }
3233
3234 // First determine if it is required or is profitable to flip the operands.
3235
3236 // If LHS is a foldable load, but RHS is not, flip the condition.
3237 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3238 !ISD::isNON_EXTLoad(RHS.getNode())) {
3239 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3240 std::swap(LHS, RHS);
3241 }
3242
3243 switch (SetCCOpcode) {
3244 default: break;
3245 case ISD::SETOLT:
3246 case ISD::SETOLE:
3247 case ISD::SETUGT:
3248 case ISD::SETUGE:
3249 std::swap(LHS, RHS);
3250 break;
3251 }
3252
3253 // On a floating point condition, the flags are set as follows:
3254 // ZF PF CF op
3255 // 0 | 0 | 0 | X > Y
3256 // 0 | 0 | 1 | X < Y
3257 // 1 | 0 | 0 | X == Y
3258 // 1 | 1 | 1 | unordered
3259 switch (SetCCOpcode) {
3260 // clang-format off
3261 default: llvm_unreachable("Condcode should be pre-legalized away");
3262 case ISD::SETUEQ:
3263 case ISD::SETEQ: return X86::COND_E;
3264 case ISD::SETOLT: // flipped
3265 case ISD::SETOGT:
3266 case ISD::SETGT: return X86::COND_A;
3267 case ISD::SETOLE: // flipped
3268 case ISD::SETOGE:
3269 case ISD::SETGE: return X86::COND_AE;
3270 case ISD::SETUGT: // flipped
3271 case ISD::SETULT:
3272 case ISD::SETLT: return X86::COND_B;
3273 case ISD::SETUGE: // flipped
3274 case ISD::SETULE:
3275 case ISD::SETLE: return X86::COND_BE;
3276 case ISD::SETONE:
3277 case ISD::SETNE: return X86::COND_NE;
3278 case ISD::SETUO: return X86::COND_P;
3279 case ISD::SETO: return X86::COND_NP;
3280 case ISD::SETOEQ:
3281 case ISD::SETUNE: return X86::COND_INVALID;
3282 // clang-format on
3283 }
3284}
3285
3286/// Is there a floating point cmov for the specific X86 condition code?
3287/// Current x86 isa includes the following FP cmov instructions:
3288/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3289static bool hasFPCMov(unsigned X86CC) {
3290 switch (X86CC) {
3291 default:
3292 return false;
3293 case X86::COND_B:
3294 case X86::COND_BE:
3295 case X86::COND_E:
3296 case X86::COND_P:
3297 case X86::COND_A:
3298 case X86::COND_AE:
3299 case X86::COND_NE:
3300 case X86::COND_NP:
3301 return true;
3302 }
3303}
3304
3305static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
3306 return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
3307 VT.is512BitVector();
3308}
3309
3312 MachineFunction &MF, unsigned Intrinsic) const {
3313 IntrinsicInfo Info;
3315 Info.offset = 0;
3316
3318 if (!IntrData) {
3319 switch (Intrinsic) {
3320 case Intrinsic::x86_aesenc128kl:
3321 case Intrinsic::x86_aesdec128kl:
3322 Info.opc = ISD::INTRINSIC_W_CHAIN;
3323 Info.ptrVal = I.getArgOperand(1);
3324 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3325 Info.align = Align(1);
3326 Info.flags |= MachineMemOperand::MOLoad;
3327 Infos.push_back(Info);
3328 return;
3329 case Intrinsic::x86_aesenc256kl:
3330 case Intrinsic::x86_aesdec256kl:
3331 Info.opc = ISD::INTRINSIC_W_CHAIN;
3332 Info.ptrVal = I.getArgOperand(1);
3333 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3334 Info.align = Align(1);
3335 Info.flags |= MachineMemOperand::MOLoad;
3336 Infos.push_back(Info);
3337 return;
3338 case Intrinsic::x86_aesencwide128kl:
3339 case Intrinsic::x86_aesdecwide128kl:
3340 Info.opc = ISD::INTRINSIC_W_CHAIN;
3341 Info.ptrVal = I.getArgOperand(0);
3342 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3343 Info.align = Align(1);
3344 Info.flags |= MachineMemOperand::MOLoad;
3345 Infos.push_back(Info);
3346 return;
3347 case Intrinsic::x86_aesencwide256kl:
3348 case Intrinsic::x86_aesdecwide256kl:
3349 Info.opc = ISD::INTRINSIC_W_CHAIN;
3350 Info.ptrVal = I.getArgOperand(0);
3351 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3352 Info.align = Align(1);
3353 Info.flags |= MachineMemOperand::MOLoad;
3354 Infos.push_back(Info);
3355 return;
3356 case Intrinsic::x86_cmpccxadd32:
3357 case Intrinsic::x86_cmpccxadd64:
3358 case Intrinsic::x86_atomic_bts:
3359 case Intrinsic::x86_atomic_btc:
3360 case Intrinsic::x86_atomic_btr: {
3361 Info.opc = ISD::INTRINSIC_W_CHAIN;
3362 Info.ptrVal = I.getArgOperand(0);
3363 unsigned Size = I.getType()->getScalarSizeInBits();
3364 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3365 Info.align = Align(Size);
3368 Infos.push_back(Info);
3369 return;
3370 }
3371 case Intrinsic::x86_atomic_bts_rm:
3372 case Intrinsic::x86_atomic_btc_rm:
3373 case Intrinsic::x86_atomic_btr_rm: {
3374 Info.opc = ISD::INTRINSIC_W_CHAIN;
3375 Info.ptrVal = I.getArgOperand(0);
3376 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3377 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3378 Info.align = Align(Size);
3381 Infos.push_back(Info);
3382 return;
3383 }
3384 case Intrinsic::x86_aadd32:
3385 case Intrinsic::x86_aadd64:
3386 case Intrinsic::x86_aand32:
3387 case Intrinsic::x86_aand64:
3388 case Intrinsic::x86_aor32:
3389 case Intrinsic::x86_aor64:
3390 case Intrinsic::x86_axor32:
3391 case Intrinsic::x86_axor64:
3392 case Intrinsic::x86_atomic_add_cc:
3393 case Intrinsic::x86_atomic_sub_cc:
3394 case Intrinsic::x86_atomic_or_cc:
3395 case Intrinsic::x86_atomic_and_cc:
3396 case Intrinsic::x86_atomic_xor_cc: {
3397 Info.opc = ISD::INTRINSIC_W_CHAIN;
3398 Info.ptrVal = I.getArgOperand(0);
3399 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3400 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3401 Info.align = Align(Size);
3404 Infos.push_back(Info);
3405 return;
3406 }
3407 }
3408 return;
3409 }
3410
3411 switch (IntrData->Type) {
3414 case TRUNCATE_TO_MEM_VI32: {
3415 Info.opc = ISD::INTRINSIC_VOID;
3416 Info.ptrVal = I.getArgOperand(0);
3417 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
3419 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
3420 ScalarVT = MVT::i8;
3421 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
3422 ScalarVT = MVT::i16;
3423 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
3424 ScalarVT = MVT::i32;
3425
3426 Info.memVT = VT.changeElementType(ScalarVT);
3427 Info.align = Align(1);
3428 Info.flags |= MachineMemOperand::MOStore;
3429 Infos.push_back(Info);
3430 return;
3431 }
3432 case GATHER:
3433 case GATHER_AVX2: {
3434 Info.opc = ISD::INTRINSIC_W_CHAIN;
3435 Info.ptrVal = nullptr;
3436 MVT DataVT = MVT::getVT(I.getType());
3437 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3438 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3439 IndexVT.getVectorNumElements());
3440 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3441 Info.align = Align(1);
3442 Info.flags |= MachineMemOperand::MOLoad;
3443 Infos.push_back(Info);
3444 return;
3445 }
3446 case SCATTER: {
3447 Info.opc = ISD::INTRINSIC_VOID;
3448 Info.ptrVal = nullptr;
3449 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
3450 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3451 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3452 IndexVT.getVectorNumElements());
3453 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3454 Info.align = Align(1);
3455 Info.flags |= MachineMemOperand::MOStore;
3456 Infos.push_back(Info);
3457 return;
3458 }
3459 default:
3460 return;
3461 }
3462}
3463
3464/// Returns true if the target can instruction select the
3465/// specified FP immediate natively. If false, the legalizer will
3466/// materialize the FP immediate as a load from a constant pool.
3468 bool ForCodeSize) const {
3469 for (const APFloat &FPImm : LegalFPImmediates)
3470 if (Imm.bitwiseIsEqual(FPImm))
3471 return true;
3472 return false;
3473}
3474
3476 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
3477 std::optional<unsigned> ByteOffset) const {
3478 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3479
3480 auto PeekThroughOneUserBitcasts = [](const SDNode *N) {
3481 while (N->getOpcode() == ISD::BITCAST && N->hasOneUse())
3482 N = *N->user_begin();
3483 return N;
3484 };
3485
3486 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3487 // relocation target a movq or addq instruction: don't let the load shrink.
3488 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3489 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3490 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3491 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3492
3493 // If this is a (1) 128-bit or wider vector load, and any use will be used by
3494 // a legal full width instruction, then the load can typically be memory
3495 // folded into that instruction, so it's probably not worth splitting the
3496 // load. Additionally, for (2) AVX vector loads with (3) multiple uses where
3497 // (4) all of those uses are extracted directly into a store, the extract +
3498 // store can be store-folded, so it's again not worth splitting.
3499 EVT VT = Load->getValueType(0);
3500 if (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) {
3501 bool FullWidthUse = false;
3502 // The extract + store folding only helps the AVX split case, which requires
3503 // multiple uses of the load.
3504 bool AllExtractStores = (VT.is256BitVector() || VT.is512BitVector()) &&
3505 !SDValue(Load, 0).hasOneUse();
3506 for (SDUse &Use : Load->uses()) {
3507 // Skip uses of the chain value. Result 0 of the node is the load value.
3508 if (Use.getResNo() != 0)
3509 continue;
3510
3511 const SDNode *User = PeekThroughOneUserBitcasts(Use.getUser());
3512
3513 // If this use is an extract + store, it's probably not worth splitting.
3514 if (AllExtractStores && User->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
3515 all_of(User->uses(), [&](const SDUse &U) {
3516 const SDNode *Inner = PeekThroughOneUserBitcasts(U.getUser());
3517 return Inner->getOpcode() == ISD::STORE;
3518 }))
3519 continue;
3520
3521 AllExtractStores = false;
3522
3523 // If any use is a full width legal/target bin op, then assume its legal
3524 // and won't split.
3525 if (isBinOp(User->getOpcode()) &&
3526 (isOperationLegal(User->getOpcode(), User->getValueType(0)) ||
3527 User->getOpcode() > ISD::BUILTIN_OP_END))
3528 FullWidthUse = true;
3529 }
3530
3531 if (AllExtractStores)
3532 return false;
3533
3534 // If we have an user that uses the full vector width, then this use is
3535 // only worth splitting if the offset isn't 0 (to avoid an
3536 // EXTRACT_SUBVECTOR) or we're loading a scalar integer.
3537 if (FullWidthUse)
3538 return (ByteOffset.value_or(0) > 0) || NewVT.isScalarInteger();
3539 }
3540
3541 return true;
3542}
3543
3544/// Returns true if it is beneficial to convert a load of a constant
3545/// to just the constant itself.
3547 Type *Ty) const {
3548 assert(Ty->isIntegerTy());
3549
3550 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3551 if (BitSize == 0 || BitSize > 64)
3552 return false;
3553 return true;
3554}
3555
3557 // If we are using XMM registers in the ABI and the condition of the select is
3558 // a floating-point compare and we have blendv or conditional move, then it is
3559 // cheaper to select instead of doing a cross-register move and creating a
3560 // load that depends on the compare result.
3561 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3562 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3563}
3564
3566 // TODO: It might be a win to ease or lift this restriction, but the generic
3567 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3568 if (VT.isVector() && Subtarget.hasAVX512())
3569 return false;
3570
3571 return true;
3572}
3573
3575 EVT) const {
3576 // With CCMP, keep and/or(setcc, setcc) trees intact so LowerSELECT can
3577 // emit them as CCMP chains rather than splitting into chained selects.
3578 return !(Subtarget.hasCCMP() && VT.isScalarInteger());
3579}
3580
3582 SDValue C) const {
3583 // TODO: We handle scalars using custom code, but generic combining could make
3584 // that unnecessary.
3585 APInt MulC;
3586 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3587 return false;
3588
3589 if (VT.isVector() && VT.getScalarSizeInBits() == 8) {
3590 // Check whether a vXi8 multiply can be decomposed into two shifts
3591 // (decomposing 2^m ± 2^n as 2^(a+b) ± 2^b). Similar to
3592 // DAGCombiner::visitMUL, consider the constant `2` decomposable as
3593 // (2^0 + 1).
3594 APInt ShiftedMulC = MulC.abs();
3595 unsigned TZeros = ShiftedMulC == 2 ? 0 : ShiftedMulC.countr_zero();
3596 ShiftedMulC.lshrInPlace(TZeros);
3597 if ((ShiftedMulC - 1).isPowerOf2() || (ShiftedMulC + 1).isPowerOf2())
3598 return true;
3599 }
3600
3601 // Find the type this will be legalized too. Otherwise we might prematurely
3602 // convert this to shl+add/sub and then still have to type legalize those ops.
3603 // Another choice would be to defer the decision for illegal types until
3604 // after type legalization. But constant splat vectors of i64 can't make it
3605 // through type legalization on 32-bit targets so we would need to special
3606 // case vXi64.
3607 while (getTypeAction(Context, VT) != TypeLegal)
3608 VT = getTypeToTransformTo(Context, VT);
3609
3610 // If vector multiply is legal, assume that's faster than shl + add/sub.
3611 // Multiply is a complex op with higher latency and lower throughput in
3612 // most implementations, sub-vXi32 vector multiplies are always fast,
3613 // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3614 // is always going to be slow.
3615 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3616 if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3617 (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3618 return false;
3619
3620 // shl+add, shl+sub, shl+add+neg
3621 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3622 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3623}
3624
3627 unsigned Index) const {
3630
3631 // Mask vectors support all subregister combinations and operations that
3632 // extract half of vector.
3633 if (ResVT.getVectorElementType() == MVT::i1) {
3634 if (Index == 0 || ((ResVT.getSizeInBits() * 2 == SrcVT.getSizeInBits()) &&
3635 (Index == ResVT.getVectorNumElements())))
3638 }
3639
3640 if (Index == 0)
3642 else if ((Index % ResVT.getVectorNumElements()) == 0)
3645}
3646
3648 unsigned Opc = VecOp.getOpcode();
3649
3650 // Assume target opcodes can't be scalarized.
3651 // TODO - do we have any exceptions?
3652 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
3653 return false;
3654
3655 // If the vector op is not supported, try to convert to scalar.
3656 EVT VecVT = VecOp.getValueType();
3658 return true;
3659
3660 // If the vector op is supported, but the scalar op is not, the transform may
3661 // not be worthwhile.
3662 EVT ScalarVT = VecVT.getScalarType();
3663 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3664}
3665
3667 bool) const {
3668 // TODO: Allow vectors?
3669 if (VT.isVector())
3670 return false;
3671 return VT.isSimple() || !isOperationExpand(Opcode, VT);
3672}
3673
3675 // Speculate cttz only if we can directly use TZCNT/CMOV, can promote to
3676 // i32/i64 or can rely on BSF passthrough value.
3677 return Subtarget.hasBMI() || Subtarget.canUseCMOV() ||
3678 Subtarget.hasBitScanPassThrough() ||
3679 (!Ty->isVectorTy() &&
3680 Ty->getScalarSizeInBits() < (Subtarget.is64Bit() ? 64u : 32u));
3681}
3682
3684 // Speculate ctlz only if we can directly use LZCNT/CMOV, or can rely on BSR
3685 // passthrough value.
3686 return Subtarget.hasLZCNT() || Subtarget.canUseCMOV() ||
3687 Subtarget.hasBitScanPassThrough();
3688}
3689
3691 // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3692 // expensive than a straight movsd. On the other hand, it's important to
3693 // shrink long double fp constant since fldt is very slow.
3694 return !Subtarget.hasSSE2() || VT == MVT::f80;
3695}
3696
3698 return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3699 (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3700}
3701
3703 const SelectionDAG &DAG,
3704 const MachineMemOperand &MMO) const {
3705 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3706 BitcastVT.getVectorElementType() == MVT::i1)
3707 return false;
3708
3709 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3710 return false;
3711
3712 if (LoadVT.isVector() && BitcastVT.isVector()) {
3713 // If both types are legal vectors, it's always ok to convert them.
3714 // Don't convert to an illegal type.
3715 if (isTypeLegal(LoadVT))
3716 return isTypeLegal(BitcastVT);
3717 }
3718
3719 // If we have a large vector type (even if illegal), don't bitcast to large
3720 // (illegal) scalar types. Better to load fewer vectors and extract.
3721 if (LoadVT.isVector() && !BitcastVT.isVector() && LoadVT.isInteger() &&
3722 BitcastVT.isInteger() && (LoadVT.getSizeInBits() % 128) == 0)
3723 return false;
3724
3725 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3726}
3727
3729 const MachineFunction &MF) const {
3730 // Do not merge to float value size (128 bytes) if no implicit
3731 // float attribute is set.
3732 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3733
3734 if (NoFloat) {
3735 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3736 return (MemVT.getSizeInBits() <= MaxIntSize);
3737 }
3738 // Make sure we don't merge greater than our preferred vector
3739 // width.
3740 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3741 return false;
3742
3743 return true;
3744}
3745
3747 return Subtarget.hasFastLZCNT();
3748}
3749
3751 const Instruction &AndI) const {
3752 return true;
3753}
3754
3756 // Scalar integer and-not compares are efficiently handled by NOT+TEST (or
3757 // BMI ANDN).
3758 return Y.getValueType().isScalarInteger();
3759}
3760
3762 EVT VT = Y.getValueType();
3763
3764 if (!VT.isVector()) {
3765 if (!Subtarget.hasBMI())
3766 return false;
3767
3768 // There are only 32-bit and 64-bit forms for 'andn'.
3769 if (VT != MVT::i32 && VT != MVT::i64)
3770 return false;
3771 return !isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque();
3772 }
3773
3774 // Vector.
3775 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3776 return false;
3777
3778 if (VT == MVT::v4i32)
3779 return true;
3780
3781 return Subtarget.hasSSE2();
3782}
3783
3785 return X.getValueType().isScalarInteger(); // 'bt'
3786}
3787
3791 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3792 SelectionDAG &DAG) const {
3793 // Does baseline recommend not to perform the fold by default?
3795 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3796 return false;
3797 // For scalars this transform is always beneficial.
3798 if (X.getValueType().isScalarInteger())
3799 return true;
3800 // If all the shift amounts are identical, then transform is beneficial even
3801 // with rudimentary SSE2 shifts.
3802 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3803 return true;
3804 // If we have AVX2 with it's powerful shift operations, then it's also good.
3805 if (Subtarget.hasAVX2())
3806 return true;
3807 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3808 return NewShiftOpcode == ISD::SHL;
3809}
3810
3812 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3813 const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3814 if (!VT.isInteger())
3815 return ShiftOpc;
3816
3817 bool PreferRotate = false;
3818 if (VT.isVector()) {
3819 // For vectors, if we have rotate instruction support, then its definetly
3820 // best. Otherwise its not clear what the best so just don't make changed.
3821 PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3822 VT.getScalarType() == MVT::i64);
3823 } else {
3824 // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3825 // rotate unless we have a zext mask+shr.
3826 PreferRotate = Subtarget.hasBMI2();
3827 if (!PreferRotate) {
3828 unsigned MaskBits =
3829 VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3830 PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3831 }
3832 }
3833
3834 if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3835 assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3836
3837 if (PreferRotate && MayTransformRotate)
3838 return ISD::ROTL;
3839
3840 // If vector we don't really get much benefit swapping around constants.
3841 // Maybe we could check if the DAG has the flipped node already in the
3842 // future.
3843 if (VT.isVector())
3844 return ShiftOpc;
3845
3846 // See if the beneficial to swap shift type.
3847 if (ShiftOpc == ISD::SHL) {
3848 // If the current setup has imm64 mask, then inverse will have
3849 // at least imm32 mask (or be zext i32 -> i64).
3850 if (VT == MVT::i64)
3851 return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3852 : ShiftOpc;
3853
3854 // We can only benefit if req at least 7-bit for the mask. We
3855 // don't want to replace shl of 1,2,3 as they can be implemented
3856 // with lea/add.
3857 return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3858 }
3859
3860 if (VT == MVT::i64)
3861 // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3862 // extremely efficient.
3863 return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3864
3865 // Keep small shifts as shl so we can generate add/lea.
3866 return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3867 }
3868
3869 // We prefer rotate for vectors of if we won't get a zext mask with SRL
3870 // (PreferRotate will be set in the latter case).
3871 if (PreferRotate || !MayTransformRotate || VT.isVector())
3872 return ShiftOpc;
3873
3874 // Non-vector type and we have a zext mask with SRL.
3875 return ISD::SRL;
3876}
3877
3880 const Value *Lhs,
3881 const Value *Rhs,
3882 const Function *) const {
3883 using namespace llvm::PatternMatch;
3884 int BaseCost = BrMergingBaseCostThresh.getValue();
3885 // With CCMP, branches can be merged in a more efficient way.
3886 if (BaseCost >= 0 && Subtarget.hasCCMP())
3887 BaseCost += BrMergingCcmpBias;
3888 // a == b && a == c is a fast pattern on x86.
3889 if (BaseCost >= 0 && Opc == Instruction::And &&
3892 BaseCost += 1;
3893
3894 // For OR conditions with EQ comparisons, prefer splitting into branches
3895 // (unless CCMP is available). OR+EQ cannot be optimized via bitwise ops,
3896 // unlike OR+NE which becomes (P|Q)!=0. Similarly, don't split signed
3897 // comparisons (SLT, SGT) that can be optimized.
3898 if (BaseCost >= 0 && !Subtarget.hasCCMP() && Opc == Instruction::Or &&
3901 return {-1, -1, -1};
3902
3903 return {BaseCost, BrMergingLikelyBias.getValue(),
3904 BrMergingUnlikelyBias.getValue()};
3905}
3906
3908 return N->getOpcode() != ISD::FP_EXTEND;
3909}
3910
3912 const SDNode *N) const {
3913 assert(((N->getOpcode() == ISD::SHL &&
3914 N->getOperand(0).getOpcode() == ISD::SRL) ||
3915 (N->getOpcode() == ISD::SRL &&
3916 N->getOperand(0).getOpcode() == ISD::SHL)) &&
3917 "Expected shift-shift mask");
3918 // TODO: Should we always create i64 masks? Or only folded immediates?
3919 EVT VT = N->getValueType(0);
3920 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3921 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3922 // Only fold if the shift values are equal - so it folds to AND.
3923 // TODO - we should fold if either is a non-uniform vector but we don't do
3924 // the fold for non-splats yet.
3925 return N->getOperand(1) == N->getOperand(0).getOperand(1);
3926 }
3928}
3929
3931 EVT VT = Y.getValueType();
3932
3933 // For vectors, we don't have a preference, but we probably want a mask.
3934 if (VT.isVector())
3935 return false;
3936
3937 unsigned MaxWidth = Subtarget.is64Bit() ? 64 : 32;
3938 return VT.getScalarSizeInBits() <= MaxWidth;
3939}
3940
3943 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3945 !Subtarget.isOSWindows())
3948 ExpansionFactor);
3949}
3950
3952 // Any legal vector type can be splatted more efficiently than
3953 // loading/spilling from memory.
3954 return isTypeLegal(VT);
3955}
3956
3958 MVT VT = MVT::getIntegerVT(NumBits);
3959 if (isTypeLegal(VT))
3960 return VT;
3961
3962 // PMOVMSKB can handle this.
3963 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
3964 return MVT::v16i8;
3965
3966 // VPMOVMSKB can handle this.
3967 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
3968 return MVT::v32i8;
3969
3970 // TODO: Allow 64-bit type for 32-bit target.
3971 // TODO: 512-bit types should be allowed, but make sure that those
3972 // cases are handled in combineVectorSizedSetCCEquality().
3973
3975}
3976
3977/// Val is the undef sentinel value or equal to the specified value.
3978static bool isUndefOrEqual(int Val, int CmpVal) {
3979 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
3980}
3981
3982/// Return true if every element in Mask is the undef sentinel value or equal to
3983/// the specified value.
3984static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
3985 return llvm::all_of(Mask, [CmpVal](int M) {
3986 return (M == SM_SentinelUndef) || (M == CmpVal);
3987 });
3988}
3989
3990/// Return true if every element in Mask, beginning from position Pos and ending
3991/// in Pos+Size is the undef sentinel value or equal to the specified value.
3992static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
3993 unsigned Size) {
3994 return llvm::all_of(Mask.slice(Pos, Size),
3995 [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
3996}
3997
3998/// Val is either the undef or zero sentinel value.
3999static bool isUndefOrZero(int Val) {
4000 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
4001}
4002
4003/// Return true if every element in Mask, beginning from position Pos and ending
4004/// in Pos+Size is the undef sentinel value.
4005static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4006 return llvm::all_of(Mask.slice(Pos, Size), equal_to(SM_SentinelUndef));
4007}
4008
4009/// Return true if the mask creates a vector whose lower half is undefined.
4011 unsigned NumElts = Mask.size();
4012 return isUndefInRange(Mask, 0, NumElts / 2);
4013}
4014
4015/// Return true if the mask creates a vector whose upper half is undefined.
4017 unsigned NumElts = Mask.size();
4018 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
4019}
4020
4021/// Return true if Val falls within the specified range (L, H].
4022static bool isInRange(int Val, int Low, int Hi) {
4023 return (Val >= Low && Val < Hi);
4024}
4025
4026/// Return true if the value of any element in Mask falls within the specified
4027/// range (L, H].
4028static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
4029 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
4030}
4031
4032/// Return true if the value of any element in Mask is the zero sentinel value.
4033static bool isAnyZero(ArrayRef<int> Mask) {
4034 return llvm::any_of(Mask, equal_to(SM_SentinelZero));
4035}
4036
4037/// Return true if Val is undef or if its value falls within the
4038/// specified range (L, H].
4039static bool isUndefOrInRange(int Val, int Low, int Hi) {
4040 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
4041}
4042
4043/// Return true if every element in Mask is undef or if its value
4044/// falls within the specified range (L, H].
4045static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4046 return llvm::all_of(
4047 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
4048}
4049
4050/// Return true if Val is undef, zero or if its value falls within the
4051/// specified range (L, H].
4052static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4053 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
4054}
4055
4056/// Return true if every element in Mask is undef, zero or if its value
4057/// falls within the specified range (L, H].
4058static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4059 return llvm::all_of(
4060 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
4061}
4062
4063/// Return true if every element in Mask, is an in-place blend/select mask or is
4064/// undef.
4065[[maybe_unused]] static bool isBlendOrUndef(ArrayRef<int> Mask) {
4066 unsigned NumElts = Mask.size();
4067 for (auto [I, M] : enumerate(Mask))
4068 if (!isUndefOrEqual(M, I) && !isUndefOrEqual(M, I + NumElts))
4069 return false;
4070 return true;
4071}
4072
4073/// Return true if every element in Mask, beginning
4074/// from position Pos and ending in Pos + Size, falls within the specified
4075/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
4076static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
4077 unsigned Size, int Low, int Step = 1) {
4078 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4079 if (!isUndefOrEqual(Mask[i], Low))
4080 return false;
4081 return true;
4082}
4083
4084/// Return true if every element in Mask, beginning
4085/// from position Pos and ending in Pos+Size, falls within the specified
4086/// sequential range (Low, Low+Size], or is undef or is zero.
4088 unsigned Size, int Low,
4089 int Step = 1) {
4090 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4091 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4092 return false;
4093 return true;
4094}
4095
4096/// Return true if every element in Mask, beginning
4097/// from position Pos and ending in Pos+Size is undef or is zero.
4098static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4099 unsigned Size) {
4100 return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
4101}
4102
4103/// Return true if every element of a single input is referenced by the shuffle
4104/// mask. i.e. it just permutes them all.
4106 unsigned NumElts = Mask.size();
4107 APInt DemandedElts = APInt::getZero(NumElts);
4108 for (int M : Mask)
4109 if (isInRange(M, 0, NumElts))
4110 DemandedElts.setBit(M);
4111 return DemandedElts.isAllOnes();
4112}
4113
4114/// Helper function to test whether a shuffle mask could be
4115/// simplified by widening the elements being shuffled.
4116///
4117/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4118/// leaves it in an unspecified state.
4119///
4120/// NOTE: This must handle normal vector shuffle masks and *target* vector
4121/// shuffle masks. The latter have the special property of a '-2' representing
4122/// a zero-ed lane of a vector.
4124 SmallVectorImpl<int> &WidenedMask) {
4125 WidenedMask.assign(Mask.size() / 2, 0);
4126 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4127 int M0 = Mask[i];
4128 int M1 = Mask[i + 1];
4129
4130 // If both elements are undef, its trivial.
4131 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4132 WidenedMask[i / 2] = SM_SentinelUndef;
4133 continue;
4134 }
4135
4136 // Check for an undef mask and a mask value properly aligned to fit with
4137 // a pair of values. If we find such a case, use the non-undef mask's value.
4138 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4139 WidenedMask[i / 2] = M1 / 2;
4140 continue;
4141 }
4142 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4143 WidenedMask[i / 2] = M0 / 2;
4144 continue;
4145 }
4146
4147 // When zeroing, we need to spread the zeroing across both lanes to widen.
4148 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4149 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4151 WidenedMask[i / 2] = SM_SentinelZero;
4152 continue;
4153 }
4154 return false;
4155 }
4156
4157 // Finally check if the two mask values are adjacent and aligned with
4158 // a pair.
4159 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4160 WidenedMask[i / 2] = M0 / 2;
4161 continue;
4162 }
4163
4164 // Otherwise we can't safely widen the elements used in this shuffle.
4165 return false;
4166 }
4167 assert(WidenedMask.size() == Mask.size() / 2 &&
4168 "Incorrect size of mask after widening the elements!");
4169
4170 return true;
4171}
4172
4174 const APInt &Zeroable,
4175 bool V2IsZero,
4176 SmallVectorImpl<int> &WidenedMask) {
4177 // Create an alternative mask with info about zeroable elements.
4178 // Here we do not set undef elements as zeroable.
4179 SmallVector<int, 64> ZeroableMask(Mask);
4180 if (V2IsZero) {
4181 assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
4182 for (int i = 0, Size = Mask.size(); i != Size; ++i)
4183 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
4184 ZeroableMask[i] = SM_SentinelZero;
4185 }
4186 return canWidenShuffleElements(ZeroableMask, WidenedMask);
4187}
4188
4190 SmallVector<int, 32> WidenedMask;
4191 return canWidenShuffleElements(Mask, WidenedMask);
4192}
4193
4194// Attempt to narrow/widen shuffle mask until it matches the target number of
4195// elements.
4196static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
4197 SmallVectorImpl<int> &ScaledMask) {
4198 unsigned NumSrcElts = Mask.size();
4199 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
4200 "Illegal shuffle scale factor");
4201
4202 // Narrowing is guaranteed to work.
4203 if (NumDstElts >= NumSrcElts) {
4204 int Scale = NumDstElts / NumSrcElts;
4205 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
4206 return true;
4207 }
4208
4209 // We have to repeat the widening until we reach the target size, but we can
4210 // split out the first widening as it sets up ScaledMask for us.
4211 if (canWidenShuffleElements(Mask, ScaledMask)) {
4212 while (ScaledMask.size() > NumDstElts) {
4213 SmallVector<int, 16> WidenedMask;
4214 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
4215 return false;
4216 ScaledMask = std::move(WidenedMask);
4217 }
4218 return true;
4219 }
4220
4221 return false;
4222}
4223
4224static bool canScaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts) {
4225 SmallVector<int, 32> ScaledMask;
4226 return scaleShuffleElements(Mask, NumDstElts, ScaledMask);
4227}
4228
4229// Helper to grow the shuffle mask for a larger value type.
4230// NOTE: This is different to scaleShuffleElements which is a same size type.
4231static void growShuffleMask(ArrayRef<int> SrcMask,
4232 SmallVectorImpl<int> &DstMask,
4233 unsigned SrcSizeInBits, unsigned DstSizeInBits) {
4234 assert(DstMask.empty() && "Expected an empty shuffle mas");
4235 assert((DstSizeInBits % SrcSizeInBits) == 0 && "Illegal shuffle scale");
4236 unsigned Scale = DstSizeInBits / SrcSizeInBits;
4237 unsigned NumSrcElts = SrcMask.size();
4238 DstMask.assign(SrcMask.begin(), SrcMask.end());
4239 for (int &M : DstMask) {
4240 if (M < 0)
4241 continue;
4242 M = (M % NumSrcElts) + ((M / NumSrcElts) * Scale * NumSrcElts);
4243 }
4244 DstMask.append((Scale - 1) * NumSrcElts, SM_SentinelUndef);
4245}
4246
4247/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4249 return isNullConstant(Elt) || isNullFPConstant(Elt);
4250}
4251
4252// Build a vector of constants.
4253// Use an UNDEF node if MaskElt == -1.
4254// Split 64-bit constants in the 32-bit mode.
4256 const SDLoc &dl, bool IsMask = false) {
4257
4259 bool Split = false;
4260
4261 MVT ConstVecVT = VT;
4262 unsigned NumElts = VT.getVectorNumElements();
4263 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4264 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4265 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4266 Split = true;
4267 }
4268
4269 MVT EltVT = ConstVecVT.getVectorElementType();
4270 for (unsigned i = 0; i < NumElts; ++i) {
4271 bool IsUndef = Values[i] < 0 && IsMask;
4272 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4273 DAG.getConstant(Values[i], dl, EltVT);
4274 Ops.push_back(OpNode);
4275 if (Split)
4276 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4277 DAG.getConstant(0, dl, EltVT));
4278 }
4279 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4280 if (Split)
4281 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4282 return ConstsNode;
4283}
4284
4285static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
4286 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4287 assert(Bits.size() == Undefs.getBitWidth() &&
4288 "Unequal constant and undef arrays");
4290 bool Split = false;
4291
4292 MVT ConstVecVT = VT;
4293 unsigned NumElts = VT.getVectorNumElements();
4294 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4295 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4296 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4297 Split = true;
4298 }
4299
4300 MVT EltVT = ConstVecVT.getVectorElementType();
4301 MVT EltIntVT = EltVT.changeTypeToInteger();
4302 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
4303 if (Undefs[i]) {
4304 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
4305 continue;
4306 }
4307 const APInt &V = Bits[i];
4308 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
4309 if (Split) {
4310 Ops.push_back(DAG.getConstant(V.extractBits(32, 0), dl, EltVT));
4311 Ops.push_back(DAG.getConstant(V.extractBits(32, 32), dl, EltVT));
4312 } else {
4313 Ops.push_back(DAG.getBitcast(EltVT, DAG.getConstant(V, dl, EltIntVT)));
4314 }
4315 }
4316
4317 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4318 return DAG.getBitcast(VT, ConstsNode);
4319}
4320
4322 SelectionDAG &DAG, const SDLoc &dl) {
4323 APInt Undefs = APInt::getZero(Bits.size());
4324 return getConstVector(Bits, Undefs, VT, DAG, dl);
4325}
4326
4327/// Returns a vector of specified type with all zero elements.
4328static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
4329 SelectionDAG &DAG, const SDLoc &dl) {
4330 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
4331 VT.getVectorElementType() == MVT::i1) &&
4332 "Unexpected vector type");
4333
4334 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4335 // type. This ensures they get CSE'd. But if the integer type is not
4336 // available, use a floating-point +0.0 instead.
4337 SDValue Vec;
4338 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4339 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4340 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4341 } else if (VT.isFloatingPoint() &&
4343 Vec = DAG.getConstantFP(+0.0, dl, VT);
4344 } else if (VT.getVectorElementType() == MVT::i1) {
4345 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
4346 "Unexpected vector type");
4347 Vec = DAG.getConstant(0, dl, VT);
4348 } else {
4349 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4350 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4351 }
4352 return DAG.getBitcast(VT, Vec);
4353}
4354
4355// Helper to determine if the ops are all the extracted subvectors come from a
4356// single source. If we allow commute they don't have to be in order (Lo/Hi).
4357static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
4358 if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4359 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4360 LHS.getValueType() != RHS.getValueType() ||
4361 LHS.getOperand(0) != RHS.getOperand(0))
4362 return SDValue();
4363
4364 SDValue Src = LHS.getOperand(0);
4365 if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
4366 return SDValue();
4367
4368 unsigned NumElts = LHS.getValueType().getVectorNumElements();
4369 if ((LHS.getConstantOperandAPInt(1) == 0 &&
4370 RHS.getConstantOperandAPInt(1) == NumElts) ||
4371 (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
4372 LHS.getConstantOperandAPInt(1) == NumElts))
4373 return Src;
4374
4375 return SDValue();
4376}
4377
4378static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4379 const SDLoc &dl, unsigned vectorWidth) {
4380 EVT VT = Vec.getValueType();
4381 EVT ElVT = VT.getVectorElementType();
4382 unsigned ResultNumElts =
4383 (VT.getVectorNumElements() * vectorWidth) / VT.getSizeInBits();
4384 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, ResultNumElts);
4385
4386 assert(ResultVT.getSizeInBits() == vectorWidth &&
4387 "Illegal subvector extraction");
4388
4389 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4390 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4391 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4392
4393 // This is the index of the first element of the vectorWidth-bit chunk
4394 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4395 IdxVal &= ~(ElemsPerChunk - 1);
4396
4397 // If the input is a buildvector just emit a smaller one.
4398 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4399 return DAG.getBuildVector(ResultVT, dl,
4400 Vec->ops().slice(IdxVal, ElemsPerChunk));
4401
4402 // Check if we're extracting the upper undef of a widening pattern.
4403 if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
4404 Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
4405 isNullConstant(Vec.getOperand(2)))
4406 return DAG.getUNDEF(ResultVT);
4407
4408 return DAG.getExtractSubvector(dl, ResultVT, Vec, IdxVal);
4409}
4410
4411/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4412/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4413/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4414/// instructions or a simple subregister reference. Idx is an index in the
4415/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4416/// lowering EXTRACT_VECTOR_ELT operations easier.
4417static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4418 SelectionDAG &DAG, const SDLoc &dl) {
4420 Vec.getValueType().is512BitVector()) &&
4421 "Unexpected vector size!");
4422 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4423}
4424
4425/// Generate a DAG to grab 256-bits from a 512-bit vector.
4426static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4427 SelectionDAG &DAG, const SDLoc &dl) {
4428 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4429 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4430}
4431
4432static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4433 SelectionDAG &DAG, const SDLoc &dl,
4434 unsigned vectorWidth) {
4435 assert((vectorWidth == 128 || vectorWidth == 256) &&
4436 "Unsupported vector width");
4437 // Inserting UNDEF is Result
4438 if (Vec.isUndef())
4439 return Result;
4440
4441 // Insert the relevant vectorWidth bits.
4442 EVT VT = Vec.getValueType();
4443 unsigned ElemsPerChunk = vectorWidth / VT.getScalarSizeInBits();
4444 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4445
4446 // This is the index of the first element of the vectorWidth-bit chunk
4447 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4448 IdxVal &= ~(ElemsPerChunk - 1);
4449 return DAG.getInsertSubvector(dl, Result, Vec, IdxVal);
4450}
4451
4452/// Generate a DAG to put 128-bits into a vector > 128 bits. This
4453/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4454/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4455/// simple superregister reference. Idx is an index in the 128 bits
4456/// we want. It need not be aligned to a 128-bit boundary. That makes
4457/// lowering INSERT_VECTOR_ELT operations easier.
4458static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4459 SelectionDAG &DAG, const SDLoc &dl) {
4460 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4461 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4462}
4463
4464/// Widen a vector to a larger size with the same scalar type, with the new
4465/// elements either zero or undef.
4466static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
4467 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4468 const SDLoc &dl) {
4469 EVT VecVT = Vec.getValueType();
4471 VecVT.getScalarType() == VT.getScalarType() &&
4472 "Unsupported vector widening type");
4473 // If the upper 128-bits of a build vector are already undef/zero, then try to
4474 // widen from the lower 128-bits.
4475 if (Vec.getOpcode() == ISD::BUILD_VECTOR && VecVT.is256BitVector()) {
4476 unsigned NumSrcElts = VecVT.getVectorNumElements();
4477 ArrayRef<SDUse> Hi = Vec->ops().drop_front(NumSrcElts / 2);
4478 if (all_of(Hi, [&](SDValue V) {
4479 return V.isUndef() || (ZeroNewElements && X86::isZeroNode(V));
4480 }))
4481 Vec = extract128BitVector(Vec, 0, DAG, dl);
4482 }
4483 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
4484 : DAG.getUNDEF(VT);
4485 return DAG.getInsertSubvector(dl, Res, Vec, 0);
4486}
4487
4488/// Widen a vector to a larger size with the same scalar type, with the new
4489/// elements either zero or undef.
4490static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
4491 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4492 const SDLoc &dl, unsigned WideSizeInBits) {
4493 assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
4494 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
4495 "Unsupported vector widening type");
4496 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
4497 MVT SVT = Vec.getSimpleValueType().getScalarType();
4498 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
4499 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4500}
4501
4502/// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
4503/// and bitcast with integer types.
4504static MVT widenMaskVectorType(MVT VT, const X86Subtarget &Subtarget) {
4505 assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
4506 unsigned NumElts = VT.getVectorNumElements();
4507 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
4508 return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4509 return VT;
4510}
4511
4512/// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
4513/// bitcast with integer types.
4514static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
4515 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4516 const SDLoc &dl) {
4517 MVT VT = widenMaskVectorType(Vec.getSimpleValueType(), Subtarget);
4518 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4519}
4520
4521// Helper function to collect subvector ops that are concatenated together,
4522// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
4523// The subvectors in Ops are guaranteed to be the same type.
4525 SelectionDAG &DAG) {
4526 assert(Ops.empty() && "Expected an empty ops vector");
4527
4528 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
4529 Ops.append(N->op_begin(), N->op_end());
4530 return true;
4531 }
4532
4533 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
4534 SDValue Src = N->getOperand(0);
4535 SDValue Sub = N->getOperand(1);
4536 const APInt &Idx = N->getConstantOperandAPInt(2);
4537 EVT VT = Src.getValueType();
4538 EVT SubVT = Sub.getValueType();
4539
4540 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
4541 // insert_subvector(undef, x, lo)
4542 if (Idx == 0 && Src.isUndef()) {
4543 Ops.push_back(Sub);
4544 Ops.push_back(DAG.getUNDEF(SubVT));
4545 return true;
4546 }
4547 if (Idx == (VT.getVectorNumElements() / 2)) {
4548 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
4549 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
4550 Src.getOperand(1).getValueType() == SubVT &&
4551 isNullConstant(Src.getOperand(2))) {
4552 // Attempt to recurse into inner (matching) concats.
4553 SDValue Lo = Src.getOperand(1);
4554 SDValue Hi = Sub;
4555 SmallVector<SDValue, 2> LoOps, HiOps;
4556 if (collectConcatOps(Lo.getNode(), LoOps, DAG) &&
4557 collectConcatOps(Hi.getNode(), HiOps, DAG) &&
4558 LoOps.size() == HiOps.size()) {
4559 Ops.append(LoOps);
4560 Ops.append(HiOps);
4561 return true;
4562 }
4563 Ops.push_back(Lo);
4564 Ops.push_back(Hi);
4565 return true;
4566 }
4567 // insert_subvector(x, extract_subvector(x, lo), hi)
4568 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4569 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
4570 Ops.append(2, Sub);
4571 return true;
4572 }
4573 // insert_subvector(undef, x, hi)
4574 if (Src.isUndef()) {
4575 Ops.push_back(DAG.getUNDEF(SubVT));
4576 Ops.push_back(Sub);
4577 return true;
4578 }
4579 }
4580 }
4581 }
4582
4583 if (N->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4584 EVT VT = N->getValueType(0);
4585 SDValue Src = N->getOperand(0);
4586 uint64_t Idx = N->getConstantOperandVal(1);
4587
4588 // Collect all the subvectors from the source vector and slice off the
4589 // extraction.
4591 if (collectConcatOps(Src.getNode(), SrcOps, DAG) &&
4592 VT.getSizeInBits() > SrcOps[0].getValueSizeInBits() &&
4593 (VT.getSizeInBits() % SrcOps[0].getValueSizeInBits()) == 0 &&
4594 (Idx % SrcOps[0].getValueType().getVectorNumElements()) == 0) {
4595 unsigned SubIdx = Idx / SrcOps[0].getValueType().getVectorNumElements();
4596 unsigned NumSubs = VT.getSizeInBits() / SrcOps[0].getValueSizeInBits();
4597 Ops.append(SrcOps.begin() + SubIdx, SrcOps.begin() + SubIdx + NumSubs);
4598 return true;
4599 }
4600 }
4601
4602 assert(Ops.empty() && "Expected an empty ops vector");
4603 return false;
4604}
4605
4606// Helper to check if \p V can be split into subvectors and the upper subvectors
4607// are all undef. In which case return the lower subvector.
4609 SelectionDAG &DAG) {
4610 SmallVector<SDValue> SubOps;
4611 if (!collectConcatOps(V.getNode(), SubOps, DAG))
4612 return SDValue();
4613
4614 unsigned NumSubOps = SubOps.size();
4615 unsigned HalfNumSubOps = NumSubOps / 2;
4616 assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
4617
4618 ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
4619 if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
4620 return SDValue();
4621
4622 EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
4623 ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
4624 return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
4625}
4626
4627// Helper to check if we can access all the constituent subvectors without any
4628// extract ops.
4631 return collectConcatOps(V.getNode(), Ops, DAG);
4632}
4633
4634static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4635 const SDLoc &dl) {
4636 EVT VT = Op.getValueType();
4637 unsigned NumElems = VT.getVectorNumElements();
4638 unsigned SizeInBits = VT.getSizeInBits();
4639 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4640 "Can't split odd sized vector");
4641
4643 if (collectConcatOps(Op.getNode(), SubOps, DAG)) {
4644 assert((SubOps.size() % 2) == 0 && "Can't split odd sized vector concat");
4645 unsigned HalfOps = SubOps.size() / 2;
4646 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
4647 SmallVector<SDValue, 2> LoOps(SubOps.begin(), SubOps.begin() + HalfOps);
4648 SmallVector<SDValue, 2> HiOps(SubOps.begin() + HalfOps, SubOps.end());
4649 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, LoOps);
4650 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, HiOps);
4651 return std::make_pair(Lo, Hi);
4652 }
4653
4654 // If this is a splat value (with no-undefs) then use the lower subvector,
4655 // which should be a free extraction.
4656 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4657 if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4658 return std::make_pair(Lo, Lo);
4659
4660 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4661 return std::make_pair(Lo, Hi);
4662}
4663
4664/// Break an operation into 2 half sized ops and then concatenate the results.
4666 unsigned NumOps = Op.getNumOperands();
4667 EVT VT = Op.getValueType();
4668
4669 // Extract the LHS Lo/Hi vectors
4672 for (unsigned I = 0; I != NumOps; ++I) {
4673 SDValue SrcOp = Op.getOperand(I);
4674 if (!SrcOp.getValueType().isVector()) {
4675 LoOps[I] = HiOps[I] = SrcOp;
4676 continue;
4677 }
4678 std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4679 }
4680
4681 EVT LoVT, HiVT;
4682 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4683 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4684 DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4685 DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4686}
4687
4688/// Break an unary integer operation into 2 half sized ops and then
4689/// concatenate the result back.
4691 const SDLoc &dl) {
4692 // Make sure we only try to split 256/512-bit types to avoid creating
4693 // narrow vectors.
4694 [[maybe_unused]] EVT VT = Op.getValueType();
4695 assert((Op.getOperand(0).getValueType().is256BitVector() ||
4696 Op.getOperand(0).getValueType().is512BitVector()) &&
4697 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4698 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4699 VT.getVectorNumElements() &&
4700 "Unexpected VTs!");
4701 return splitVectorOp(Op, DAG, dl);
4702}
4703
4704/// Break a binary integer operation into 2 half sized ops and then
4705/// concatenate the result back.
4707 const SDLoc &dl) {
4708 // Assert that all the types match.
4709 [[maybe_unused]] EVT VT = Op.getValueType();
4710 assert(Op.getOperand(0).getValueType() == VT &&
4711 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4712 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4713 return splitVectorOp(Op, DAG, dl);
4714}
4715
4716// Helper for splitting operands of an operation to legal target size and
4717// apply a function on each part.
4718// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4719// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4720// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4721// The argument Builder is a function that will be applied on each split part:
4722// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4723template <typename F>
4725 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4726 F Builder, bool CheckBWI = true,
4727 bool AllowAVX512 = true) {
4728 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4729 unsigned NumSubs = 1;
4730 if (AllowAVX512 && ((CheckBWI && Subtarget.useBWIRegs()) ||
4731 (!CheckBWI && Subtarget.useAVX512Regs()))) {
4732 if (VT.getSizeInBits() > 512) {
4733 NumSubs = VT.getSizeInBits() / 512;
4734 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4735 }
4736 } else if (Subtarget.hasAVX2()) {
4737 if (VT.getSizeInBits() > 256) {
4738 NumSubs = VT.getSizeInBits() / 256;
4739 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4740 }
4741 } else {
4742 if (VT.getSizeInBits() > 128) {
4743 NumSubs = VT.getSizeInBits() / 128;
4744 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4745 }
4746 }
4747
4748 if (NumSubs == 1)
4749 return Builder(DAG, DL, Ops);
4750
4752 for (unsigned i = 0; i != NumSubs; ++i) {
4754 for (SDValue Op : Ops) {
4755 EVT OpVT = Op.getValueType();
4756 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4757 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4758 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4759 }
4760 Subs.push_back(Builder(DAG, DL, SubOps));
4761 }
4762 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4763}
4764
4765// Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4766// targets.
4767static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4769 const X86Subtarget &Subtarget) {
4770 assert(Subtarget.hasAVX512() && "AVX512 target expected");
4771 MVT SVT = VT.getScalarType();
4772
4773 // If we have a 32/64 splatted constant, splat it to DstTy to
4774 // encourage a foldable broadcast'd operand.
4775 auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4776 unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4777 // AVX512 broadcasts 32/64-bit operands.
4778 // TODO: Support float once getAVX512Node is used by fp-ops.
4779 if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4781 return SDValue();
4782 // If we're not widening, don't bother if we're not bitcasting.
4783 if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4784 return SDValue();
4786 APInt SplatValue, SplatUndef;
4787 unsigned SplatBitSize;
4788 bool HasAnyUndefs;
4789 if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4790 HasAnyUndefs, OpEltSizeInBits) &&
4791 !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4792 return DAG.getConstant(SplatValue, DL, DstVT);
4793 }
4794 return SDValue();
4795 };
4796
4797 bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4798
4799 MVT DstVT = VT;
4800 if (Widen)
4801 DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4802
4803 // Canonicalize src operands.
4804 SmallVector<SDValue> SrcOps(Ops);
4805 for (SDValue &Op : SrcOps) {
4806 MVT OpVT = Op.getSimpleValueType();
4807 // Just pass through scalar operands.
4808 if (!OpVT.isVector())
4809 continue;
4810 assert(OpVT == VT && "Vector type mismatch");
4811
4812 if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4813 Op = BroadcastOp;
4814 continue;
4815 }
4816
4817 // Just widen the subvector by inserting into an undef wide vector.
4818 if (Widen)
4819 Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4820 }
4821
4822 SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4823
4824 // Perform the 512-bit op then extract the bottom subvector.
4825 if (Widen)
4826 Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4827 return Res;
4828}
4829
4830/// Insert i1-subvector to i1-vector.
4832 const X86Subtarget &Subtarget) {
4833
4834 SDLoc dl(Op);
4835 SDValue Vec = Op.getOperand(0);
4836 SDValue SubVec = Op.getOperand(1);
4837 SDValue Idx = Op.getOperand(2);
4838 unsigned IdxVal = Op.getConstantOperandVal(2);
4839
4840 // Inserting undef is a nop. We can just return the original vector.
4841 if (SubVec.isUndef())
4842 return Vec;
4843
4844 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4845 return Op;
4846
4847 MVT OpVT = Op.getSimpleValueType();
4848 unsigned NumElems = OpVT.getVectorNumElements();
4849 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, dl);
4850
4851 // Extend to natively supported kshift.
4852 MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4853
4854 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4855 // if necessary.
4856 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4857 // May need to promote to a legal type.
4858 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4859 DAG.getConstant(0, dl, WideOpVT),
4860 SubVec, Idx);
4861 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4862 }
4863
4864 MVT SubVecVT = SubVec.getSimpleValueType();
4865 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4866 assert(IdxVal + SubVecNumElems <= NumElems &&
4867 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4868 "Unexpected index value in INSERT_SUBVECTOR");
4869
4870 SDValue Undef = DAG.getUNDEF(WideOpVT);
4871
4872 if (IdxVal == 0) {
4873 // Zero lower bits of the Vec
4874 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4875 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4876 ZeroIdx);
4877 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4878 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4879 // Merge them together, SubVec should be zero extended.
4880 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4881 DAG.getConstant(0, dl, WideOpVT),
4882 SubVec, ZeroIdx);
4883 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4884 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4885 }
4886
4887 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4888 Undef, SubVec, ZeroIdx);
4889
4890 if (Vec.isUndef()) {
4891 assert(IdxVal != 0 && "Unexpected index");
4892 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4893 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4894 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4895 }
4896
4898 assert(IdxVal != 0 && "Unexpected index");
4899 // If upper elements of Vec are known undef, then just shift into place.
4900 if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4901 [](SDValue V) { return V.isUndef(); })) {
4902 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4903 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4904 } else {
4905 NumElems = WideOpVT.getVectorNumElements();
4906 unsigned ShiftLeft = NumElems - SubVecNumElems;
4907 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4908 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4909 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4910 if (ShiftRight != 0)
4911 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4912 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4913 }
4914 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4915 }
4916
4917 // Simple case when we put subvector in the upper part
4918 if (IdxVal + SubVecNumElems == NumElems) {
4919 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4920 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4921 if (SubVecNumElems * 2 == NumElems) {
4922 // Special case, use legal zero extending insert_subvector. This allows
4923 // isel to optimize when bits are known zero.
4924 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4925 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4926 DAG.getConstant(0, dl, WideOpVT),
4927 Vec, ZeroIdx);
4928 } else {
4929 // Otherwise use explicit shifts to zero the bits.
4930 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4931 Undef, Vec, ZeroIdx);
4932 NumElems = WideOpVT.getVectorNumElements();
4933 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4934 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4935 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4936 }
4937 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4938 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4939 }
4940
4941 // Inserting into the middle is more complicated.
4942
4943 NumElems = WideOpVT.getVectorNumElements();
4944
4945 // Widen the vector if needed.
4946 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4947
4948 unsigned ShiftLeft = NumElems - SubVecNumElems;
4949 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4950
4951 // Do an optimization for the most frequently used types.
4952 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4953 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4954 Mask0.flipAllBits();
4955 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4956 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4957 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4958 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4959 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4960 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4961 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4962 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4963
4964 // Reduce to original width if needed.
4965 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4966 }
4967
4968 // Clear the upper bits of the subvector and move it to its insert position.
4969 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4970 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4971 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4972 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4973
4974 // Isolate the bits below the insertion point.
4975 unsigned LowShift = NumElems - IdxVal;
4976 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
4977 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4978 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
4979 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4980
4981 // Isolate the bits after the last inserted bit.
4982 unsigned HighShift = IdxVal + SubVecNumElems;
4983 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
4984 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4985 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
4986 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4987
4988 // Now OR all 3 pieces together.
4989 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
4990 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
4991
4992 // Reduce to original width if needed.
4993 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4994}
4995
4997 const SDLoc &dl) {
4998 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
4999 EVT SubVT = V1.getValueType();
5000 EVT SubSVT = SubVT.getScalarType();
5001 unsigned SubNumElts = SubVT.getVectorNumElements();
5002 unsigned SubVectorWidth = SubVT.getSizeInBits();
5003 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
5004 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
5005 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
5006}
5007
5008/// Returns a vector of specified type with all bits set.
5009/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5010/// Then bitcast to their original type, ensuring they get CSE'd.
5011static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5012 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5013 "Expected a 128/256/512-bit vector type");
5014 unsigned NumElts = VT.getSizeInBits() / 32;
5015 SDValue Vec = DAG.getAllOnesConstant(dl, MVT::getVectorVT(MVT::i32, NumElts));
5016 return DAG.getBitcast(VT, Vec);
5017}
5018
5019// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
5020static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
5021 switch (Opc) {
5022 case ISD::SHL:
5023 case X86ISD::VSHL:
5024 case X86ISD::VSHLI:
5025 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
5026 case ISD::SRL:
5027 case X86ISD::VSRL:
5028 case X86ISD::VSRLI:
5029 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
5030 case ISD::SRA:
5031 case X86ISD::VSRA:
5032 case X86ISD::VSRAI:
5033 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
5034 }
5035 llvm_unreachable("Unknown target vector shift node");
5036}
5037
5038/// Handle vector element shifts where the shift amount is a constant.
5039/// Takes immediate version of shift as input.
5040static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
5041 SDValue SrcOp, uint64_t ShiftAmt,
5042 SelectionDAG &DAG) {
5043 assert(
5044 (Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) &&
5045 "Unknown target vector shift-by-constant node");
5046
5047 // Bitcast the source vector to the output type, this is mainly necessary for
5048 // vXi8/vXi64 shifts.
5049 SrcOp = DAG.getBitcast(VT, SrcOp);
5050
5051 // Fold this packed shift into its first operand if ShiftAmt is 0.
5052 if (ShiftAmt == 0)
5053 return SrcOp;
5054
5055 // Check for ShiftAmt >= element width
5056 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5057 if (ShiftAmt >= EltSizeInBits) {
5058 if (Opc == X86ISD::VSRAI)
5059 ShiftAmt = EltSizeInBits - 1;
5060 else
5061 return DAG.getConstant(0, dl, VT);
5062 }
5063
5064 // Fold this packed vector shift into a build vector if SrcOp is a
5065 // vector of Constants or UNDEFs.
5067 unsigned ShiftOpc;
5068 switch (Opc) {
5069 default:
5070 llvm_unreachable("Unknown opcode!");
5071 case X86ISD::VSHLI:
5072 ShiftOpc = ISD::SHL;
5073 break;
5074 case X86ISD::VSRLI:
5075 ShiftOpc = ISD::SRL;
5076 break;
5077 case X86ISD::VSRAI:
5078 ShiftOpc = ISD::SRA;
5079 break;
5080 }
5081
5082 SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
5083 if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
5084 return C;
5085 }
5086
5087 return DAG.getNode(Opc, dl, VT, SrcOp,
5088 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
5089}
5090
5091/// Handle vector element shifts by a splat shift amount
5092static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
5093 SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
5094 const X86Subtarget &Subtarget,
5095 SelectionDAG &DAG) {
5096 MVT AmtVT = ShAmt.getSimpleValueType();
5097 assert(AmtVT.isVector() && "Vector shift type mismatch");
5098 assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
5099 "Illegal vector splat index");
5100
5101 // Move the splat element to the bottom element.
5102 if (ShAmtIdx != 0) {
5103 SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
5104 Mask[0] = ShAmtIdx;
5105 ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
5106 }
5107
5108 // Peek through any zext node if we can get back to a 128-bit source.
5109 if (AmtVT.getScalarSizeInBits() == 64 &&
5110 (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
5112 ShAmt.getOperand(0).getValueType().isSimple() &&
5113 ShAmt.getOperand(0).getValueType().is128BitVector()) {
5114 ShAmt = ShAmt.getOperand(0);
5115 AmtVT = ShAmt.getSimpleValueType();
5116 }
5117
5118 // See if we can mask off the upper elements using the existing source node.
5119 // The shift uses the entire lower 64-bits of the amount vector, so no need to
5120 // do this for vXi64 types.
5121 bool IsMasked = false;
5122 if (AmtVT.getScalarSizeInBits() < 64) {
5123 if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
5124 ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5125 // If the shift amount has come from a scalar, then zero-extend the scalar
5126 // before moving to the vector.
5127 ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
5128 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
5129 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
5130 AmtVT = MVT::v4i32;
5131 IsMasked = true;
5132 } else if (ShAmt.getOpcode() == ISD::AND) {
5133 // See if the shift amount is already masked (e.g. for rotation modulo),
5134 // then we can zero-extend it by setting all the other mask elements to
5135 // zero.
5136 SmallVector<SDValue> MaskElts(
5137 AmtVT.getVectorNumElements(),
5138 DAG.getConstant(0, dl, AmtVT.getScalarType()));
5139 MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
5140 SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
5141 if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
5142 {ShAmt.getOperand(1), Mask}))) {
5143 ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
5144 IsMasked = true;
5145 }
5146 }
5147 }
5148
5149 // Extract if the shift amount vector is larger than 128-bits.
5150 if (AmtVT.getSizeInBits() > 128) {
5151 ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
5152 AmtVT = ShAmt.getSimpleValueType();
5153 }
5154
5155 // Zero-extend bottom element to v2i64 vector type, either by extension or
5156 // shuffle masking.
5157 if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
5158 if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
5159 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
5160 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
5161 } else if (Subtarget.hasSSE41()) {
5162 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
5163 MVT::v2i64, ShAmt);
5164 } else {
5165 SDValue ByteShift = DAG.getTargetConstant(
5166 (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
5167 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
5168 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5169 ByteShift);
5170 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5171 ByteShift);
5172 }
5173 }
5174
5175 // Change opcode to non-immediate version.
5177
5178 // The return type has to be a 128-bit type with the same element
5179 // type as the input type.
5180 MVT EltVT = VT.getVectorElementType();
5181 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
5182
5183 ShAmt = DAG.getBitcast(ShVT, ShAmt);
5184 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
5185}
5186
5187static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
5188 SDValue In, SelectionDAG &DAG) {
5189 EVT InVT = In.getValueType();
5190 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
5191
5192 // Canonicalize Opcode to general extension version.
5193 switch (Opcode) {
5194 case ISD::ANY_EXTEND:
5196 Opcode = ISD::ANY_EXTEND;
5197 break;
5198 case ISD::SIGN_EXTEND:
5200 Opcode = ISD::SIGN_EXTEND;
5201 break;
5202 case ISD::ZERO_EXTEND:
5204 Opcode = ISD::ZERO_EXTEND;
5205 break;
5206 default:
5207 llvm_unreachable("Unknown extension opcode");
5208 }
5209
5210 // For 256-bit vectors, we only need the lower (128-bit) input half.
5211 // For 512-bit vectors, we only need the lower input half or quarter.
5212 if (InVT.getSizeInBits() > 128) {
5213 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
5214 "Expected VTs to be the same size!");
5215 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5216 In = extractSubVector(In, 0, DAG, DL,
5217 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
5218 InVT = In.getValueType();
5219 }
5220
5221 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
5222 Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
5223
5224 return DAG.getNode(Opcode, DL, VT, In);
5225}
5226
5227// Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
5229 SDValue Mask, SelectionDAG &DAG) {
5230 LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
5231 RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
5232 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5233}
5234
5236 bool Lo, bool Unary) {
5237 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
5238 "Illegal vector type to unpack");
5239 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5240 int NumElts = VT.getVectorNumElements();
5241 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
5242 for (int i = 0; i < NumElts; ++i) {
5243 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
5244 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
5245 Pos += (Unary ? 0 : NumElts * (i % 2));
5246 Pos += (Lo ? 0 : NumEltsInLane / 2);
5247 Mask.push_back(Pos);
5248 }
5249}
5250
5251/// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
5252/// imposed by AVX and specific to the unary pattern. Example:
5253/// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
5254/// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
5256 bool Lo) {
5257 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5258 int NumElts = VT.getVectorNumElements();
5259 for (int i = 0; i < NumElts; ++i) {
5260 int Pos = i / 2;
5261 Pos += (Lo ? 0 : NumElts / 2);
5262 Mask.push_back(Pos);
5263 }
5264}
5265
5266// Attempt to constant fold, else just create a VECTOR_SHUFFLE.
5267static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
5268 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
5269 if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
5271 SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
5272 for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
5273 int M = Mask[I];
5274 if (M < 0)
5275 continue;
5276 SDValue V = (M < NumElts) ? V1 : V2;
5277 if (V.isUndef())
5278 continue;
5279 Ops[I] = V.getOperand(M % NumElts);
5280 }
5281 return DAG.getBuildVector(VT, dl, Ops);
5282 }
5283
5284 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5285}
5286
5287/// Returns a vector_shuffle node for an unpackl operation.
5288static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5289 SDValue V1, SDValue V2) {
5291 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5292 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5293}
5294
5295/// Returns a vector_shuffle node for an unpackh operation.
5296static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5297 SDValue V1, SDValue V2) {
5299 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5300 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5301}
5302
5303/// Returns a node that packs the LHS + RHS nodes together at half width.
5304/// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
5305/// TODO: Add subvector splitting if/when we have a need for it.
5306static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5307 const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
5308 bool PackHiHalf = false) {
5309 MVT OpVT = LHS.getSimpleValueType();
5310 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5311 bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
5312 assert(OpVT == RHS.getSimpleValueType() &&
5313 VT.getSizeInBits() == OpVT.getSizeInBits() &&
5314 (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
5315 "Unexpected PACK operand types");
5316 assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
5317 "Unexpected PACK result type");
5318
5319 // Rely on vector shuffles for vXi64 -> vXi32 packing.
5320 if (EltSizeInBits == 32) {
5321 SmallVector<int> PackMask;
5322 int Offset = PackHiHalf ? 1 : 0;
5323 int NumElts = VT.getVectorNumElements();
5324 for (int I = 0; I != NumElts; I += 4) {
5325 PackMask.push_back(I + Offset);
5326 PackMask.push_back(I + Offset + 2);
5327 PackMask.push_back(I + Offset + NumElts);
5328 PackMask.push_back(I + Offset + NumElts + 2);
5329 }
5330 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
5331 DAG.getBitcast(VT, RHS), PackMask);
5332 }
5333
5334 // See if we already have sufficient leading bits for PACKSS/PACKUS.
5335 if (!PackHiHalf) {
5336 if (UsePackUS &&
5337 DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
5338 DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
5339 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5340
5341 if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
5342 DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
5343 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5344 }
5345
5346 // Fallback to sign/zero extending the requested half and pack.
5347 SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
5348 if (UsePackUS) {
5349 if (PackHiHalf) {
5350 LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
5351 RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
5352 } else {
5353 SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
5354 LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
5355 RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
5356 };
5357 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5358 };
5359
5360 if (!PackHiHalf) {
5361 LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
5362 RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
5363 }
5364 LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
5365 RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
5366 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5367}
5368
5369/// Return a vector_shuffle of the specified vector of zero or undef vector.
5370/// This produces a shuffle where the low element of V2 is swizzled into the
5371/// zero/undef vector, landing at element Idx.
5372/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5374 bool IsZero,
5375 const X86Subtarget &Subtarget,
5376 SelectionDAG &DAG) {
5377 MVT VT = V2.getSimpleValueType();
5378 SDValue V1 = IsZero
5379 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5380 int NumElems = VT.getVectorNumElements();
5381 SmallVector<int, 16> MaskVec(NumElems);
5382 for (int i = 0; i != NumElems; ++i)
5383 // If this is the insertion idx, put the low elt of V2 here.
5384 MaskVec[i] = (i == Idx) ? NumElems : i;
5385 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5386}
5387
5389 if (Ptr.getOpcode() == X86ISD::Wrapper ||
5390 Ptr.getOpcode() == X86ISD::WrapperRIP)
5391 Ptr = Ptr.getOperand(0);
5392 return dyn_cast<ConstantPoolSDNode>(Ptr);
5393}
5394
5395// TODO: Add support for non-zero offsets.
5398 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5399 return nullptr;
5400 return CNode->getConstVal();
5401}
5402
5404 if (!Load || !ISD::isNormalLoad(Load))
5405 return nullptr;
5406 return getTargetConstantFromBasePtr(Load->getBasePtr());
5407}
5408
5413
5414const Constant *
5416 assert(LD && "Unexpected null LoadSDNode");
5417 return getTargetConstantFromNode(LD);
5418}
5419
5421 // Do not fold (vselect not(C), X, 0s) to (vselect C, Os, X)
5422 SDValue Cond = N->getOperand(0);
5423 SDValue RHS = N->getOperand(2);
5424 EVT CondVT = Cond.getValueType();
5425 return N->getOpcode() == ISD::VSELECT && Subtarget.hasAVX512() &&
5426 CondVT.getVectorElementType() == MVT::i1 &&
5427 ISD::isBuildVectorAllZeros(RHS.getNode());
5428}
5429
5430// Extract raw constant bits from constant pools.
5431static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5432 APInt &UndefElts,
5433 SmallVectorImpl<APInt> &EltBits,
5434 bool AllowWholeUndefs = true,
5435 bool AllowPartialUndefs = false) {
5436 assert(EltBits.empty() && "Expected an empty EltBits vector");
5437
5439
5440 EVT VT = Op.getValueType();
5441 unsigned SizeInBits = VT.getSizeInBits();
5442 unsigned NumElts = SizeInBits / EltSizeInBits;
5443
5444 // Can't split constant.
5445 if ((SizeInBits % EltSizeInBits) != 0)
5446 return false;
5447
5448 // Bitcast a source array of element bits to the target size.
5449 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5450 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5451 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5452 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
5453 "Constant bit sizes don't match");
5454
5455 // Don't split if we don't allow undef bits.
5456 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5457 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5458 return false;
5459
5460 // If we're already the right size, don't bother bitcasting.
5461 if (NumSrcElts == NumElts) {
5462 UndefElts = UndefSrcElts;
5463 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5464 return true;
5465 }
5466
5467 // Extract all the undef/constant element data and pack into single bitsets.
5468 APInt UndefBits(SizeInBits, 0);
5469 APInt MaskBits(SizeInBits, 0);
5470
5471 for (unsigned i = 0; i != NumSrcElts; ++i) {
5472 unsigned BitOffset = i * SrcEltSizeInBits;
5473 if (UndefSrcElts[i])
5474 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5475 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5476 }
5477
5478 // Split the undef/constant single bitset data into the target elements.
5479 UndefElts = APInt(NumElts, 0);
5480 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5481
5482 for (unsigned i = 0; i != NumElts; ++i) {
5483 unsigned BitOffset = i * EltSizeInBits;
5484 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5485
5486 // Only treat an element as UNDEF if all bits are UNDEF.
5487 if (UndefEltBits.isAllOnes()) {
5488 if (!AllowWholeUndefs)
5489 return false;
5490 UndefElts.setBit(i);
5491 continue;
5492 }
5493
5494 // If only some bits are UNDEF then treat them as zero (or bail if not
5495 // supported).
5496 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5497 return false;
5498
5499 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
5500 }
5501 return true;
5502 };
5503
5504 // Collect constant bits and insert into mask/undef bit masks.
5505 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5506 unsigned UndefBitIndex) {
5507 if (!Cst)
5508 return false;
5509 if (isa<UndefValue>(Cst)) {
5510 Undefs.setBit(UndefBitIndex);
5511 return true;
5512 }
5513 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5514 Mask = APInt::getSplat(CInt->getType()->getPrimitiveSizeInBits(),
5515 CInt->getValue());
5516 return true;
5517 }
5518 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5519 Mask = APInt::getSplat(CFP->getType()->getPrimitiveSizeInBits(),
5520 CFP->getValueAPF().bitcastToAPInt());
5521 return true;
5522 }
5523 if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
5524 Type *Ty = CDS->getType();
5525 if (Ty->isVectorTy()) {
5526 Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
5527 Type *EltTy = CDS->getElementType();
5528 bool IsInteger = EltTy->isIntegerTy();
5529 bool IsFP =
5530 EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
5531 if (!IsInteger && !IsFP)
5532 return false;
5533 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
5534 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
5535 if (IsInteger)
5536 Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
5537 else
5538 Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
5539 I * EltBits);
5540 return true;
5541 }
5542 }
5543 return false;
5544 };
5545
5546 // Handle UNDEFs.
5547 if (Op.isUndef()) {
5548 APInt UndefSrcElts = APInt::getAllOnes(NumElts);
5549 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5550 return CastBitData(UndefSrcElts, SrcEltBits);
5551 }
5552
5553 // Extract scalar constant bits.
5554 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5555 APInt UndefSrcElts = APInt::getZero(1);
5556 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5557 return CastBitData(UndefSrcElts, SrcEltBits);
5558 }
5559 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5560 APInt UndefSrcElts = APInt::getZero(1);
5561 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5562 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5563 return CastBitData(UndefSrcElts, SrcEltBits);
5564 }
5565
5566 // Extract constant bits from build vector.
5567 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5568 BitVector Undefs;
5569 SmallVector<APInt> SrcEltBits;
5570 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5571 if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
5572 APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
5573 for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
5574 if (Undefs[I])
5575 UndefSrcElts.setBit(I);
5576 return CastBitData(UndefSrcElts, SrcEltBits);
5577 }
5578 }
5579
5580 // Extract constant bits from constant pool vector.
5581 if (auto *Cst = getTargetConstantFromNode(Op)) {
5582 Type *CstTy = Cst->getType();
5583 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5584 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5585 return false;
5586
5587 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5588 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5589 if ((SizeInBits % SrcEltSizeInBits) != 0)
5590 return false;
5591
5592 APInt UndefSrcElts(NumSrcElts, 0);
5593 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5594 for (unsigned i = 0; i != NumSrcElts; ++i)
5595 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5596 UndefSrcElts, i))
5597 return false;
5598
5599 return CastBitData(UndefSrcElts, SrcEltBits);
5600 }
5601
5602 // Extract constant bits from a broadcasted constant pool scalar.
5603 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
5604 EltSizeInBits <= VT.getScalarSizeInBits()) {
5605 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5606 if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
5607 return false;
5608
5609 SDValue Ptr = MemIntr->getBasePtr();
5610 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
5611 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5612 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5613
5614 APInt UndefSrcElts(NumSrcElts, 0);
5615 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5616 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
5617 if (UndefSrcElts[0])
5618 UndefSrcElts.setBits(0, NumSrcElts);
5619 if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
5620 SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
5621 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5622 return CastBitData(UndefSrcElts, SrcEltBits);
5623 }
5624 }
5625 }
5626
5627 // Extract constant bits from a subvector broadcast.
5628 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
5629 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5630 SDValue Ptr = MemIntr->getBasePtr();
5631 // The source constant may be larger than the subvector broadcast,
5632 // ensure we extract the correct subvector constants.
5633 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
5634 Type *CstTy = Cst->getType();
5635 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5636 unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
5637 if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
5638 (SizeInBits % SubVecSizeInBits) != 0)
5639 return false;
5640 unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
5641 unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
5642 unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
5643 APInt UndefSubElts(NumSubElts, 0);
5644 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
5645 APInt(CstEltSizeInBits, 0));
5646 for (unsigned i = 0; i != NumSubElts; ++i) {
5647 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
5648 UndefSubElts, i))
5649 return false;
5650 for (unsigned j = 1; j != NumSubVecs; ++j)
5651 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
5652 }
5653 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
5654 UndefSubElts);
5655 return CastBitData(UndefSubElts, SubEltBits);
5656 }
5657 }
5658
5659 // Extract a rematerialized scalar constant insertion.
5660 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5661 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5662 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5663 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5664 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5665
5666 APInt UndefSrcElts(NumSrcElts, 0);
5667 SmallVector<APInt, 64> SrcEltBits;
5668 const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
5669 SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
5670 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5671 return CastBitData(UndefSrcElts, SrcEltBits);
5672 }
5673
5674 // Insert constant bits from a base and sub vector sources.
5675 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
5676 // If bitcasts to larger elements we might lose track of undefs - don't
5677 // allow any to be safe.
5678 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5679 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
5680
5681 APInt UndefSrcElts, UndefSubElts;
5682 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
5683 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
5684 UndefSubElts, EltSubBits,
5685 AllowWholeUndefs && AllowUndefs,
5686 AllowPartialUndefs && AllowUndefs) &&
5687 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
5688 UndefSrcElts, EltSrcBits,
5689 AllowWholeUndefs && AllowUndefs,
5690 AllowPartialUndefs && AllowUndefs)) {
5691 unsigned BaseIdx = Op.getConstantOperandVal(2);
5692 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
5693 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
5694 EltSrcBits[BaseIdx + i] = EltSubBits[i];
5695 return CastBitData(UndefSrcElts, EltSrcBits);
5696 }
5697 }
5698
5699 // Extract constant bits from a subvector's source.
5700 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5701 getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits, UndefElts,
5702 EltBits, AllowWholeUndefs,
5703 AllowPartialUndefs)) {
5704 EVT SrcVT = Op.getOperand(0).getValueType();
5705 unsigned NumSrcElts = SrcVT.getSizeInBits() / EltSizeInBits;
5706 unsigned NumSubElts = VT.getSizeInBits() / EltSizeInBits;
5707 unsigned BaseOfs = Op.getConstantOperandVal(1) * VT.getScalarSizeInBits();
5708 unsigned BaseIdx = BaseOfs / EltSizeInBits;
5709 assert((SrcVT.getSizeInBits() % EltSizeInBits) == 0 &&
5710 (VT.getSizeInBits() % EltSizeInBits) == 0 &&
5711 (BaseOfs % EltSizeInBits) == 0 && "Bad subvector index");
5712
5713 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5714 if ((BaseIdx + NumSubElts) != NumSrcElts)
5715 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5716 if (BaseIdx != 0)
5717 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5718 return true;
5719 }
5720
5721 // Extract constant bits from shuffle node sources.
5722 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5723 // TODO - support shuffle through bitcasts.
5724 if (EltSizeInBits != VT.getScalarSizeInBits())
5725 return false;
5726
5727 ArrayRef<int> Mask = SVN->getMask();
5728 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5729 llvm::any_of(Mask, [](int M) { return M < 0; }))
5730 return false;
5731
5732 APInt UndefElts0, UndefElts1;
5733 SmallVector<APInt, 32> EltBits0, EltBits1;
5734 if (isAnyInRange(Mask, 0, NumElts) &&
5735 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5736 UndefElts0, EltBits0, AllowWholeUndefs,
5737 AllowPartialUndefs))
5738 return false;
5739 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5740 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5741 UndefElts1, EltBits1, AllowWholeUndefs,
5742 AllowPartialUndefs))
5743 return false;
5744
5745 UndefElts = APInt::getZero(NumElts);
5746 for (int i = 0; i != (int)NumElts; ++i) {
5747 int M = Mask[i];
5748 if (M < 0) {
5749 UndefElts.setBit(i);
5750 EltBits.push_back(APInt::getZero(EltSizeInBits));
5751 } else if (M < (int)NumElts) {
5752 if (UndefElts0[M])
5753 UndefElts.setBit(i);
5754 EltBits.push_back(EltBits0[M]);
5755 } else {
5756 if (UndefElts1[M - NumElts])
5757 UndefElts.setBit(i);
5758 EltBits.push_back(EltBits1[M - NumElts]);
5759 }
5760 }
5761 return true;
5762 }
5763
5764 return false;
5765}
5766
5767namespace llvm {
5768namespace X86 {
5769bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
5770 APInt UndefElts;
5771 SmallVector<APInt, 16> EltBits;
5773 Op, Op.getScalarValueSizeInBits(), UndefElts, EltBits,
5774 /*AllowWholeUndefs*/ true, AllowPartialUndefs)) {
5775 int SplatIndex = -1;
5776 for (int i = 0, e = EltBits.size(); i != e; ++i) {
5777 if (UndefElts[i])
5778 continue;
5779 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5780 SplatIndex = -1;
5781 break;
5782 }
5783 SplatIndex = i;
5784 }
5785 if (0 <= SplatIndex) {
5786 SplatVal = EltBits[SplatIndex];
5787 return true;
5788 }
5789 }
5790
5791 return false;
5792}
5793
5794int getRoundingModeX86(unsigned RM) {
5795 switch (static_cast<::llvm::RoundingMode>(RM)) {
5796 // clang-format off
5797 case ::llvm::RoundingMode::NearestTiesToEven: return X86::rmToNearest;
5798 case ::llvm::RoundingMode::TowardNegative: return X86::rmDownward;
5799 case ::llvm::RoundingMode::TowardPositive: return X86::rmUpward;
5800 case ::llvm::RoundingMode::TowardZero: return X86::rmTowardZero;
5801 default: return X86::rmInvalid;
5802 // clang-format on
5803 }
5804}
5805
5806} // namespace X86
5807} // namespace llvm
5808
5810 unsigned MaskEltSizeInBits,
5812 APInt &UndefElts) {
5813 // Extract the raw target constant bits.
5814 SmallVector<APInt, 64> EltBits;
5815 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5816 EltBits, /* AllowWholeUndefs */ true,
5817 /* AllowPartialUndefs */ false))
5818 return false;
5819
5820 // Insert the extracted elements into the mask.
5821 for (const APInt &Elt : EltBits)
5822 RawMask.push_back(Elt.getZExtValue());
5823
5824 return true;
5825}
5826
5827static bool isConstantPowerOf2(SDValue V, unsigned EltSizeInBIts,
5828 bool AllowUndefs) {
5829 APInt UndefElts;
5830 SmallVector<APInt, 64> EltBits;
5831 if (!getTargetConstantBitsFromNode(V, EltSizeInBIts, UndefElts, EltBits,
5832 /*AllowWholeUndefs*/ AllowUndefs,
5833 /*AllowPartialUndefs*/ false))
5834 return false;
5835
5836 bool IsPow2OrUndef = true;
5837 for (unsigned I = 0, E = EltBits.size(); I != E; ++I)
5838 IsPow2OrUndef &= UndefElts[I] || EltBits[I].isPowerOf2();
5839 return IsPow2OrUndef;
5840}
5841
5842// Helper to attempt to return a cheaper, bit-inverted version of \p V.
5844 // TODO: don't always ignore oneuse constraints.
5845 V = peekThroughBitcasts(V);
5846 EVT VT = V.getValueType();
5847
5848 // Match not(xor X, -1) -> X.
5849 if (V.getOpcode() == ISD::XOR &&
5850 (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
5851 isAllOnesConstant(V.getOperand(1))))
5852 return V.getOperand(0);
5853
5854 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
5855 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5856 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5857 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5858 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5859 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
5860 V.getOperand(1));
5861 }
5862 }
5863
5864 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
5865 if (V.getOpcode() == X86ISD::PCMPGT &&
5866 !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
5867 !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
5868 V.getOperand(0).hasOneUse()) {
5869 APInt UndefElts;
5870 SmallVector<APInt> EltBits;
5871 if (getTargetConstantBitsFromNode(V.getOperand(0),
5872 V.getScalarValueSizeInBits(), UndefElts,
5873 EltBits) &&
5874 !ISD::isBuildVectorOfConstantSDNodes(V.getOperand(1).getNode())) {
5875 // Don't fold min_signed_value -> (min_signed_value - 1)
5876 bool MinSigned = false;
5877 for (APInt &Elt : EltBits) {
5878 MinSigned |= Elt.isMinSignedValue();
5879 Elt -= 1;
5880 }
5881 if (!MinSigned) {
5882 SDLoc DL(V);
5883 MVT VT = V.getSimpleValueType();
5884 return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5885 getConstVector(EltBits, UndefElts, VT, DAG, DL));
5886 }
5887 }
5888 }
5889
5890 // Match not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
5892 if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5893 for (SDValue &CatOp : CatOps) {
5894 SDValue NotCat = IsNOT(CatOp, DAG);
5895 if (!NotCat)
5896 return SDValue();
5897 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5898 }
5899 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), VT, CatOps);
5900 }
5901
5902 // Match not(or(not(X),not(Y))) -> and(X, Y).
5903 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
5904 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
5905 // TODO: Handle cases with single NOT operand -> ANDNP
5906 if (SDValue Op1 = IsNOT(V.getOperand(1), DAG))
5907 if (SDValue Op0 = IsNOT(V.getOperand(0), DAG))
5908 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
5909 DAG.getBitcast(VT, Op1));
5910 }
5911
5912 return SDValue();
5913}
5914
5915/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5916/// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5917/// Note: This ignores saturation, so inputs must be checked first.
5919 bool Unary, unsigned NumStages = 1) {
5920 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5921 unsigned NumElts = VT.getVectorNumElements();
5922 unsigned NumLanes = VT.getSizeInBits() / 128;
5923 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5924 unsigned Offset = Unary ? 0 : NumElts;
5925 unsigned Repetitions = 1u << (NumStages - 1);
5926 unsigned Increment = 1u << NumStages;
5927 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5928
5929 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5930 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5931 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5932 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5933 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5934 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5935 }
5936 }
5937}
5938
5939// Split the demanded elts of a PACKSS/PACKUS node between its operands.
5940static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5941 APInt &DemandedLHS, APInt &DemandedRHS) {
5942 int NumLanes = VT.getSizeInBits() / 128;
5943 int NumElts = DemandedElts.getBitWidth();
5944 int NumInnerElts = NumElts / 2;
5945 int NumEltsPerLane = NumElts / NumLanes;
5946 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5947
5948 DemandedLHS = APInt::getZero(NumInnerElts);
5949 DemandedRHS = APInt::getZero(NumInnerElts);
5950
5951 // Map DemandedElts to the packed operands.
5952 for (int Lane = 0; Lane != NumLanes; ++Lane) {
5953 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5954 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
5955 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
5956 if (DemandedElts[OuterIdx])
5957 DemandedLHS.setBit(InnerIdx);
5958 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
5959 DemandedRHS.setBit(InnerIdx);
5960 }
5961 }
5962}
5963
5964// Split the demanded elts of a HADD/HSUB node between its operands.
5965static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
5966 APInt &DemandedLHS, APInt &DemandedRHS) {
5968 DemandedLHS, DemandedRHS);
5969 DemandedLHS |= DemandedLHS << 1;
5970 DemandedRHS |= DemandedRHS << 1;
5971}
5972
5973/// Calculates the shuffle mask corresponding to the target-specific opcode.
5974/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5975/// operands in \p Ops, and returns true.
5976/// Sets \p IsUnary to true if only one source is used. Note that this will set
5977/// IsUnary for shuffles which use a single input multiple times, and in those
5978/// cases it will adjust the mask to only have indices within that single input.
5979/// It is an error to call this with non-empty Mask/Ops vectors.
5980static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
5982 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5983 if (!isTargetShuffle(N.getOpcode()))
5984 return false;
5985
5986 MVT VT = N.getSimpleValueType();
5987 unsigned NumElems = VT.getVectorNumElements();
5988 unsigned MaskEltSize = VT.getScalarSizeInBits();
5990 APInt RawUndefs;
5991 uint64_t ImmN;
5992
5993 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
5994 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
5995
5996 IsUnary = false;
5997 bool IsFakeUnary = false;
5998 switch (N.getOpcode()) {
5999 case X86ISD::BLENDI:
6000 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6001 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6002 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6003 DecodeBLENDMask(NumElems, ImmN, Mask);
6004 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6005 break;
6006 case X86ISD::SHUFP:
6007 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6008 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6009 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6010 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6011 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6012 break;
6013 case X86ISD::INSERTPS:
6014 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6015 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6016 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6017 DecodeINSERTPSMask(ImmN, Mask, /*SrcIsMem=*/false);
6018 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6019 break;
6020 case X86ISD::EXTRQI:
6021 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6022 if (isa<ConstantSDNode>(N.getOperand(1)) &&
6023 isa<ConstantSDNode>(N.getOperand(2))) {
6024 int BitLen = N.getConstantOperandVal(1);
6025 int BitIdx = N.getConstantOperandVal(2);
6026 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6027 IsUnary = true;
6028 }
6029 break;
6030 case X86ISD::INSERTQI:
6031 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6032 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6033 if (isa<ConstantSDNode>(N.getOperand(2)) &&
6034 isa<ConstantSDNode>(N.getOperand(3))) {
6035 int BitLen = N.getConstantOperandVal(2);
6036 int BitIdx = N.getConstantOperandVal(3);
6037 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6038 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6039 }
6040 break;
6041 case X86ISD::UNPCKH:
6042 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6043 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6044 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6045 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6046 break;
6047 case X86ISD::UNPCKL:
6048 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6049 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6050 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6051 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6052 break;
6053 case X86ISD::MOVHLPS:
6054 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6055 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6056 DecodeMOVHLPSMask(NumElems, Mask);
6057 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6058 break;
6059 case X86ISD::MOVLHPS:
6060 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6061 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6062 DecodeMOVLHPSMask(NumElems, Mask);
6063 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6064 break;
6065 case X86ISD::VALIGN:
6066 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
6067 "Only 32-bit and 64-bit elements are supported!");
6068 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6069 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6070 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6071 DecodeVALIGNMask(NumElems, ImmN, Mask);
6072 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6073 Ops.push_back(N.getOperand(1));
6074 Ops.push_back(N.getOperand(0));
6075 break;
6076 case X86ISD::PALIGNR:
6077 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6078 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6079 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6080 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6081 DecodePALIGNRMask(NumElems, ImmN, Mask);
6082 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6083 Ops.push_back(N.getOperand(1));
6084 Ops.push_back(N.getOperand(0));
6085 break;
6086 case X86ISD::VSHLDQ:
6087 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6088 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6089 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6090 DecodePSLLDQMask(NumElems, ImmN, Mask);
6091 IsUnary = true;
6092 break;
6093 case X86ISD::VSRLDQ:
6094 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6095 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6096 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6097 DecodePSRLDQMask(NumElems, ImmN, Mask);
6098 IsUnary = true;
6099 break;
6100 case X86ISD::PSHUFD:
6101 case X86ISD::VPERMILPI:
6102 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6103 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6104 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
6105 IsUnary = true;
6106 break;
6107 case X86ISD::PSHUFHW:
6108 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6109 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6110 DecodePSHUFHWMask(NumElems, ImmN, Mask);
6111 IsUnary = true;
6112 break;
6113 case X86ISD::PSHUFLW:
6114 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6115 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6116 DecodePSHUFLWMask(NumElems, ImmN, Mask);
6117 IsUnary = true;
6118 break;
6119 case X86ISD::VZEXT_MOVL:
6120 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6121 DecodeZeroMoveLowMask(NumElems, Mask);
6122 IsUnary = true;
6123 break;
6124 case X86ISD::VBROADCAST:
6125 // We only decode broadcasts of same-sized vectors, peeking through to
6126 // extracted subvectors is likely to cause hasOneUse issues with
6127 // SimplifyDemandedBits etc.
6128 if (N.getOperand(0).getValueType() == VT) {
6129 DecodeVectorBroadcast(NumElems, Mask);
6130 IsUnary = true;
6131 break;
6132 }
6133 return false;
6134 case X86ISD::VPERMILPV: {
6135 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6136 IsUnary = true;
6137 SDValue MaskNode = N.getOperand(1);
6138 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6139 RawUndefs)) {
6140 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6141 break;
6142 }
6143 return false;
6144 }
6145 case X86ISD::PSHUFB: {
6146 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6147 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6148 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6149 IsUnary = true;
6150 SDValue MaskNode = N.getOperand(1);
6151 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6152 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6153 break;
6154 }
6155 return false;
6156 }
6157 case X86ISD::VPERMI:
6158 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6159 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6160 DecodeVPERMMask(NumElems, ImmN, Mask);
6161 IsUnary = true;
6162 break;
6163 case X86ISD::MOVSS:
6164 case X86ISD::MOVSD:
6165 case X86ISD::MOVSH:
6166 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6167 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6168 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6169 break;
6170 case X86ISD::VPERM2X128:
6171 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6172 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6173 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6174 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
6175 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6176 break;
6177 case X86ISD::SHUF128:
6178 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6179 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6180 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6181 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
6182 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6183 break;
6184 case X86ISD::MOVSLDUP:
6185 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6186 DecodeMOVSLDUPMask(NumElems, Mask);
6187 IsUnary = true;
6188 break;
6189 case X86ISD::MOVSHDUP:
6190 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6191 DecodeMOVSHDUPMask(NumElems, Mask);
6192 IsUnary = true;
6193 break;
6194 case X86ISD::MOVDDUP:
6195 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6196 DecodeMOVDDUPMask(NumElems, Mask);
6197 IsUnary = true;
6198 break;
6199 case X86ISD::VPERMIL2: {
6200 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6201 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6202 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6203 SDValue MaskNode = N.getOperand(2);
6204 SDValue CtrlNode = N.getOperand(3);
6205 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6206 unsigned CtrlImm = CtrlOp->getZExtValue();
6207 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6208 RawUndefs)) {
6209 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6210 Mask);
6211 break;
6212 }
6213 }
6214 return false;
6215 }
6216 case X86ISD::VPPERM: {
6217 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6218 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6219 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6220 SDValue MaskNode = N.getOperand(2);
6221 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6222 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6223 break;
6224 }
6225 return false;
6226 }
6227 case X86ISD::VPERMV: {
6228 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6229 IsUnary = true;
6230 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6231 Ops.push_back(N.getOperand(1));
6232 SDValue MaskNode = N.getOperand(0);
6233 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6234 RawUndefs)) {
6235 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6236 break;
6237 }
6238 return false;
6239 }
6240 case X86ISD::VPERMV3: {
6241 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6242 assert(N.getOperand(2).getValueType() == VT && "Unexpected value type");
6243 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(2);
6244 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6245 Ops.push_back(N.getOperand(0));
6246 Ops.push_back(N.getOperand(2));
6247 SDValue MaskNode = N.getOperand(1);
6248 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6249 RawUndefs)) {
6250 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6251 break;
6252 }
6253 return false;
6254 }
6255 case X86ISD::COMPRESS: {
6256 SDValue CmpVec = N.getOperand(0);
6257 SDValue PassThru = N.getOperand(1);
6258 SDValue CmpMask = N.getOperand(2);
6259 APInt UndefElts;
6260 SmallVector<APInt> EltBits;
6261 if (!getTargetConstantBitsFromNode(CmpMask, 1, UndefElts, EltBits))
6262 return false;
6263 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6264 "Illegal compression mask");
6265 for (unsigned I = 0; I != NumElems; ++I) {
6266 if (!EltBits[I].isZero())
6267 Mask.push_back(I);
6268 }
6269 while (Mask.size() != NumElems) {
6270 Mask.push_back(NumElems + Mask.size());
6271 }
6272 Ops.push_back(CmpVec);
6273 Ops.push_back(PassThru);
6274 return true;
6275 }
6276 case X86ISD::EXPAND: {
6277 SDValue ExpVec = N.getOperand(0);
6278 SDValue PassThru = N.getOperand(1);
6279 SDValue ExpMask = N.getOperand(2);
6280 APInt UndefElts;
6281 SmallVector<APInt> EltBits;
6282 if (!getTargetConstantBitsFromNode(ExpMask, 1, UndefElts, EltBits))
6283 return false;
6284 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6285 "Illegal expansion mask");
6286 unsigned ExpIndex = 0;
6287 for (unsigned I = 0; I != NumElems; ++I) {
6288 if (EltBits[I].isZero())
6289 Mask.push_back(I + NumElems);
6290 else
6291 Mask.push_back(ExpIndex++);
6292 }
6293 Ops.push_back(ExpVec);
6294 Ops.push_back(PassThru);
6295 return true;
6296 }
6297 default:
6298 llvm_unreachable("unknown target shuffle node");
6299 }
6300
6301 // Empty mask indicates the decode failed.
6302 if (Mask.empty())
6303 return false;
6304
6305 // Check if we're getting a shuffle mask with zero'd elements.
6306 if (!AllowSentinelZero && isAnyZero(Mask))
6307 return false;
6308
6309 // If we have a fake unary shuffle, the shuffle mask is spread across two
6310 // inputs that are actually the same node. Re-map the mask to always point
6311 // into the first input.
6312 if (IsFakeUnary)
6313 for (int &M : Mask)
6314 if (M >= (int)Mask.size())
6315 M -= Mask.size();
6316
6317 // If we didn't already add operands in the opcode-specific code, default to
6318 // adding 1 or 2 operands starting at 0.
6319 if (Ops.empty()) {
6320 Ops.push_back(N.getOperand(0));
6321 if (!IsUnary || IsFakeUnary)
6322 Ops.push_back(N.getOperand(1));
6323 }
6324
6325 return true;
6326}
6327
6328// Wrapper for getTargetShuffleMask with InUnary;
6329static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6331 SmallVectorImpl<int> &Mask) {
6332 bool IsUnary;
6333 return getTargetShuffleMask(N, AllowSentinelZero, Ops, Mask, IsUnary);
6334}
6335
6336/// Compute whether each element of a shuffle is zeroable.
6337///
6338/// A "zeroable" vector shuffle element is one which can be lowered to zero.
6339/// Either it is an undef element in the shuffle mask, the element of the input
6340/// referenced is undef, or the element of the input referenced is known to be
6341/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6342/// as many lanes with this technique as possible to simplify the remaining
6343/// shuffle.
6345 SDValue V1, SDValue V2,
6346 APInt &KnownUndef, APInt &KnownZero) {
6347 int Size = Mask.size();
6348 KnownUndef = KnownZero = APInt::getZero(Size);
6349
6351 V2 = peekThroughBitcasts(V2);
6352
6353 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6354 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6355
6356 int VectorSizeInBits = V1.getValueSizeInBits();
6357 int ScalarSizeInBits = VectorSizeInBits / Size;
6358 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
6359
6360 for (int i = 0; i < Size; ++i) {
6361 int M = Mask[i];
6362 // Handle the easy cases.
6363 if (M < 0) {
6364 KnownUndef.setBit(i);
6365 continue;
6366 }
6367 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6368 KnownZero.setBit(i);
6369 continue;
6370 }
6371
6372 // Determine shuffle input and normalize the mask.
6373 SDValue V = M < Size ? V1 : V2;
6374 M %= Size;
6375
6376 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
6377 if (V.getOpcode() != ISD::BUILD_VECTOR)
6378 continue;
6379
6380 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
6381 // the (larger) source element must be UNDEF/ZERO.
6382 if ((Size % V.getNumOperands()) == 0) {
6383 int Scale = Size / V->getNumOperands();
6384 SDValue Op = V.getOperand(M / Scale);
6385 if (Op.isUndef())
6386 KnownUndef.setBit(i);
6387 if (X86::isZeroNode(Op))
6388 KnownZero.setBit(i);
6389 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
6390 APInt Val = Cst->getAPIntValue();
6391 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6392 if (Val == 0)
6393 KnownZero.setBit(i);
6394 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6395 APInt Val = Cst->getValueAPF().bitcastToAPInt();
6396 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6397 if (Val == 0)
6398 KnownZero.setBit(i);
6399 }
6400 continue;
6401 }
6402
6403 // If the BUILD_VECTOR has more elements then all the (smaller) source
6404 // elements must be UNDEF or ZERO.
6405 if ((V.getNumOperands() % Size) == 0) {
6406 int Scale = V->getNumOperands() / Size;
6407 bool AllUndef = true;
6408 bool AllZero = true;
6409 for (int j = 0; j < Scale; ++j) {
6410 SDValue Op = V.getOperand((M * Scale) + j);
6411 AllUndef &= Op.isUndef();
6412 AllZero &= X86::isZeroNode(Op);
6413 }
6414 if (AllUndef)
6415 KnownUndef.setBit(i);
6416 if (AllZero)
6417 KnownZero.setBit(i);
6418 continue;
6419 }
6420 }
6421}
6422
6423/// Decode a target shuffle mask and inputs and see if any values are
6424/// known to be undef or zero from their inputs.
6425/// Returns true if the target shuffle mask was decoded.
6426/// FIXME: Merge this with computeZeroableShuffleElements?
6429 APInt &KnownUndef, APInt &KnownZero) {
6430 bool IsUnary;
6431 if (!isTargetShuffle(N.getOpcode()))
6432 return false;
6433
6434 MVT VT = N.getSimpleValueType();
6435 if (!getTargetShuffleMask(N, true, Ops, Mask, IsUnary))
6436 return false;
6437
6438 int Size = Mask.size();
6439 SDValue V1 = Ops[0];
6440 SDValue V2 = IsUnary ? V1 : Ops[1];
6441 KnownUndef = KnownZero = APInt::getZero(Size);
6442
6444 V2 = peekThroughBitcasts(V2);
6445
6446 assert((VT.getSizeInBits() % Size) == 0 &&
6447 "Illegal split of shuffle value type");
6448 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
6449
6450 // Extract known constant input data.
6451 APInt UndefSrcElts[2];
6452 SmallVector<APInt, 32> SrcEltBits[2];
6453 bool IsSrcConstant[2] = {
6454 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6455 SrcEltBits[0], /*AllowWholeUndefs*/ true,
6456 /*AllowPartialUndefs*/ false),
6457 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6458 SrcEltBits[1], /*AllowWholeUndefs*/ true,
6459 /*AllowPartialUndefs*/ false)};
6460
6461 for (int i = 0; i < Size; ++i) {
6462 int M = Mask[i];
6463
6464 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6465 if (M < 0) {
6466 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
6467 if (SM_SentinelUndef == M)
6468 KnownUndef.setBit(i);
6469 if (SM_SentinelZero == M)
6470 KnownZero.setBit(i);
6471 continue;
6472 }
6473
6474 // Determine shuffle input and normalize the mask.
6475 unsigned SrcIdx = M / Size;
6476 SDValue V = M < Size ? V1 : V2;
6477 M %= Size;
6478
6479 // We are referencing an UNDEF input.
6480 if (V.isUndef()) {
6481 KnownUndef.setBit(i);
6482 continue;
6483 }
6484
6485 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6486 // TODO: We currently only set UNDEF for integer types - floats use the same
6487 // registers as vectors and many of the scalar folded loads rely on the
6488 // SCALAR_TO_VECTOR pattern.
6489 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6490 (Size % V.getValueType().getVectorNumElements()) == 0) {
6491 int Scale = Size / V.getValueType().getVectorNumElements();
6492 int Idx = M / Scale;
6493 if (Idx != 0 && !VT.isFloatingPoint())
6494 KnownUndef.setBit(i);
6495 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6496 KnownZero.setBit(i);
6497 continue;
6498 }
6499
6500 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
6501 // base vectors.
6502 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
6503 SDValue Vec = V.getOperand(0);
6504 int NumVecElts = Vec.getValueType().getVectorNumElements();
6505 if (Vec.isUndef() && Size == NumVecElts) {
6506 int Idx = V.getConstantOperandVal(2);
6507 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
6508 if (M < Idx || (Idx + NumSubElts) <= M)
6509 KnownUndef.setBit(i);
6510 }
6511 continue;
6512 }
6513
6514 // Attempt to extract from the source's constant bits.
6515 if (IsSrcConstant[SrcIdx]) {
6516 if (UndefSrcElts[SrcIdx][M])
6517 KnownUndef.setBit(i);
6518 else if (SrcEltBits[SrcIdx][M] == 0)
6519 KnownZero.setBit(i);
6520 }
6521 }
6522
6523 assert(VT.getVectorNumElements() == (unsigned)Size &&
6524 "Different mask size from vector size!");
6525 return true;
6526}
6527
6528// Replace target shuffle mask elements with known undef/zero sentinels.
6530 const APInt &KnownUndef,
6531 const APInt &KnownZero,
6532 bool ResolveKnownZeros= true) {
6533 unsigned NumElts = Mask.size();
6534 assert(KnownUndef.getBitWidth() == NumElts &&
6535 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
6536
6537 for (unsigned i = 0; i != NumElts; ++i) {
6538 if (KnownUndef[i])
6539 Mask[i] = SM_SentinelUndef;
6540 else if (ResolveKnownZeros && KnownZero[i])
6541 Mask[i] = SM_SentinelZero;
6542 }
6543}
6544
6545// Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
6547 APInt &KnownUndef,
6548 APInt &KnownZero) {
6549 unsigned NumElts = Mask.size();
6550 KnownUndef = KnownZero = APInt::getZero(NumElts);
6551
6552 for (unsigned i = 0; i != NumElts; ++i) {
6553 int M = Mask[i];
6554 if (SM_SentinelUndef == M)
6555 KnownUndef.setBit(i);
6556 if (SM_SentinelZero == M)
6557 KnownZero.setBit(i);
6558 }
6559}
6560
6561// Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
6563 SDValue Cond, bool IsBLENDV = false) {
6564 EVT CondVT = Cond.getValueType();
6565 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
6566 unsigned NumElts = CondVT.getVectorNumElements();
6567
6568 APInt UndefElts;
6569 SmallVector<APInt, 32> EltBits;
6570 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
6571 /*AllowWholeUndefs*/ true,
6572 /*AllowPartialUndefs*/ false))
6573 return false;
6574
6575 Mask.resize(NumElts, SM_SentinelUndef);
6576
6577 for (int i = 0; i != (int)NumElts; ++i) {
6578 Mask[i] = i;
6579 // Arbitrarily choose from the 2nd operand if the select condition element
6580 // is undef.
6581 // TODO: Can we do better by matching patterns such as even/odd?
6582 if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
6583 (IsBLENDV && EltBits[i].isNonNegative()))
6584 Mask[i] += NumElts;
6585 }
6586
6587 return true;
6588}
6589
6590// Forward declaration (for getFauxShuffleMask recursive check).
6591static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6594 const SelectionDAG &DAG, unsigned Depth,
6595 bool ResolveKnownElts);
6596
6597// Attempt to decode ops that could be represented as a shuffle mask.
6598// The decoded shuffle mask may contain a different number of elements to the
6599// destination value type.
6600// TODO: Merge into getTargetShuffleInputs()
6601static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
6604 const SelectionDAG &DAG, unsigned Depth,
6605 bool ResolveKnownElts) {
6606 Mask.clear();
6607 Ops.clear();
6608
6609 MVT VT = N.getSimpleValueType();
6610 unsigned NumElts = VT.getVectorNumElements();
6611 unsigned NumSizeInBits = VT.getSizeInBits();
6612 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6613 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
6614 return false;
6615 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
6616 unsigned NumSizeInBytes = NumSizeInBits / 8;
6617 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6618
6619 unsigned Opcode = N.getOpcode();
6620 switch (Opcode) {
6621 case ISD::VECTOR_SHUFFLE: {
6622 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6623 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6624 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6625 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6626 Ops.push_back(N.getOperand(0));
6627 Ops.push_back(N.getOperand(1));
6628 return true;
6629 }
6630 return false;
6631 }
6632 case ISD::AND:
6633 case X86ISD::ANDNP: {
6634 // Attempt to decode as a per-byte mask.
6635 APInt UndefElts;
6636 SmallVector<APInt, 32> EltBits;
6637 SDValue N0 = N.getOperand(0);
6638 SDValue N1 = N.getOperand(1);
6639 bool IsAndN = (X86ISD::ANDNP == Opcode);
6640 uint64_t ZeroMask = IsAndN ? 255 : 0;
6641 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits,
6642 /*AllowWholeUndefs*/ false,
6643 /*AllowPartialUndefs*/ false))
6644 return false;
6645 // We can't assume an undef src element gives an undef dst - the other src
6646 // might be zero.
6647 assert(UndefElts.isZero() && "Unexpected UNDEF element in AND/ANDNP mask");
6648 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6649 const APInt &ByteBits = EltBits[i];
6650 if (ByteBits != 0 && ByteBits != 255)
6651 return false;
6652 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6653 }
6654 Ops.push_back(IsAndN ? N1 : N0);
6655 return true;
6656 }
6657 case ISD::OR: {
6658 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6659 // is a valid shuffle index.
6660 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
6661 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
6662 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6663 return false;
6664
6665 SmallVector<int, 64> SrcMask0, SrcMask1;
6666 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6669 if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
6670 Depth + 1, true) ||
6671 !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
6672 Depth + 1, true))
6673 return false;
6674
6675 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6676 SmallVector<int, 64> Mask0, Mask1;
6677 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6678 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6679 for (int i = 0; i != (int)MaskSize; ++i) {
6680 // NOTE: Don't handle demanded SM_SentinelUndef, as we can end up in
6681 // infinite loops converting between OR and BLEND shuffles due to
6682 // canWidenShuffleElements merging away undef elements, meaning we
6683 // fail to recognise the OR as the undef element isn't known zero.
6684 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6685 Mask.push_back(SM_SentinelZero);
6686 else if (Mask1[i] == SM_SentinelZero)
6687 Mask.push_back(i);
6688 else if (Mask0[i] == SM_SentinelZero)
6689 Mask.push_back(i + MaskSize);
6690 else if (MaskSize == NumElts && !DemandedElts[i])
6691 Mask.push_back(SM_SentinelUndef);
6692 else
6693 return false;
6694 }
6695 Ops.push_back(N.getOperand(0));
6696 Ops.push_back(N.getOperand(1));
6697 return true;
6698 }
6699 case ISD::CONCAT_VECTORS: {
6700 // Limit this to vXi64 vector cases to make the most of cross lane shuffles.
6701 unsigned NumSubElts = N.getOperand(0).getValueType().getVectorNumElements();
6702 if (NumBitsPerElt == 64) {
6703 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
6704 for (unsigned M = 0; M != NumSubElts; ++M)
6705 Mask.push_back((I * NumElts) + M);
6706 Ops.push_back(N.getOperand(I));
6707 }
6708 return true;
6709 }
6710 return false;
6711 }
6712 case ISD::INSERT_SUBVECTOR: {
6713 SDValue Src = N.getOperand(0);
6714 SDValue Sub = N.getOperand(1);
6715 EVT SubVT = Sub.getValueType();
6716 unsigned NumSubElts = SubVT.getVectorNumElements();
6717 uint64_t InsertIdx = N.getConstantOperandVal(2);
6718 // Subvector isn't demanded - just return the base vector.
6719 if (DemandedElts.extractBits(NumSubElts, InsertIdx) == 0) {
6720 Mask.resize(NumElts);
6721 std::iota(Mask.begin(), Mask.end(), 0);
6722 Ops.push_back(Src);
6723 return true;
6724 }
6725 // Handle CONCAT(SUB0, SUB1).
6726 // Limit to vXi64/splat cases to make the most of cross lane shuffles.
6727 if (Depth > 0 && InsertIdx == NumSubElts && NumElts == (2 * NumSubElts) &&
6728 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6729 Src.getOperand(0).isUndef() &&
6730 Src.getOperand(1).getValueType() == SubVT &&
6731 Src.getConstantOperandVal(2) == 0 &&
6732 (NumBitsPerElt == 64 || Src.getOperand(1) == Sub) &&
6733 SDNode::areOnlyUsersOf({N.getNode(), Src.getNode()}, Sub.getNode())) {
6734 Mask.resize(NumElts);
6735 std::iota(Mask.begin(), Mask.begin() + NumSubElts, 0);
6736 std::iota(Mask.begin() + NumSubElts, Mask.end(), NumElts);
6737 Ops.push_back(Src.getOperand(1));
6738 Ops.push_back(Sub);
6739 return true;
6740 }
6741 // Handle INSERT_SUBVECTOR(UNDEF, SUB, IDX) iff IDX != 0
6742 if (InsertIdx != 0 && Src.isUndef() &&
6744 Mask.assign(NumElts, SM_SentinelUndef);
6745 std::iota(Mask.begin() + InsertIdx, Mask.begin() + InsertIdx + NumSubElts,
6746 0);
6747 Ops.push_back(Sub);
6748 return true;
6749 }
6750 if (!N->isOnlyUserOf(Sub.getNode()))
6751 return false;
6752
6753 SmallVector<int, 64> SubMask;
6754 SmallVector<SDValue, 2> SubInputs;
6756 EVT SubSrcVT = SubSrc.getValueType();
6757 if (!SubSrcVT.isVector())
6758 return false;
6759
6760 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
6761 if (SubSrc.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6762 SubSrc.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6763 uint64_t ExtractIdx = SubSrc.getConstantOperandVal(1);
6764 SDValue SubSrcSrc = SubSrc.getOperand(0);
6765 unsigned NumSubSrcSrcElts =
6766 SubSrcSrc.getValueType().getVectorNumElements();
6767 unsigned MaxElts = std::max(NumElts, NumSubSrcSrcElts);
6768 assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcSrcElts) == 0 &&
6769 "Subvector valuetype mismatch");
6770 InsertIdx *= (MaxElts / NumElts);
6771 ExtractIdx *= (MaxElts / NumSubSrcSrcElts);
6772 NumSubElts *= (MaxElts / NumElts);
6773 bool SrcIsUndef = Src.isUndef();
6774 for (int i = 0; i != (int)MaxElts; ++i)
6775 Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
6776 for (int i = 0; i != (int)NumSubElts; ++i)
6777 Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
6778 if (!SrcIsUndef)
6779 Ops.push_back(Src);
6780 Ops.push_back(SubSrcSrc);
6781 return true;
6782 }
6783
6784 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6785 APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
6786 if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
6787 Depth + 1, ResolveKnownElts))
6788 return false;
6789
6790 // Subvector shuffle inputs must not be larger than the subvector.
6791 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
6792 return SubVT.getFixedSizeInBits() <
6793 SubInput.getValueSizeInBits().getFixedValue();
6794 }))
6795 return false;
6796
6797 if (SubMask.size() != NumSubElts) {
6798 assert(((SubMask.size() % NumSubElts) == 0 ||
6799 (NumSubElts % SubMask.size()) == 0) &&
6800 "Illegal submask scale");
6801 if ((NumSubElts % SubMask.size()) == 0) {
6802 int Scale = NumSubElts / SubMask.size();
6803 SmallVector<int, 64> ScaledSubMask;
6804 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
6805 SubMask = ScaledSubMask;
6806 } else {
6807 int Scale = SubMask.size() / NumSubElts;
6808 NumSubElts = SubMask.size();
6809 NumElts *= Scale;
6810 InsertIdx *= Scale;
6811 }
6812 }
6813 Ops.push_back(Src);
6814 Ops.append(SubInputs.begin(), SubInputs.end());
6815 if (ISD::isBuildVectorAllZeros(Src.getNode()))
6816 Mask.append(NumElts, SM_SentinelZero);
6817 else
6818 for (int i = 0; i != (int)NumElts; ++i)
6819 Mask.push_back(i);
6820 for (int i = 0; i != (int)NumSubElts; ++i) {
6821 int M = SubMask[i];
6822 if (0 <= M) {
6823 int InputIdx = M / NumSubElts;
6824 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6825 }
6826 Mask[i + InsertIdx] = M;
6827 }
6828 return true;
6829 }
6830 case X86ISD::PINSRB:
6831 case X86ISD::PINSRW:
6834 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
6835 // vector, for matching src/dst vector types.
6836 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
6837
6838 unsigned DstIdx = 0;
6839 if (Opcode != ISD::SCALAR_TO_VECTOR) {
6840 // Check we have an in-range constant insertion index.
6841 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6842 N.getConstantOperandAPInt(2).uge(NumElts))
6843 return false;
6844 DstIdx = N.getConstantOperandVal(2);
6845
6846 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
6847 if (X86::isZeroNode(Scl)) {
6848 Ops.push_back(N.getOperand(0));
6849 for (unsigned i = 0; i != NumElts; ++i)
6850 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
6851 return true;
6852 }
6853 }
6854
6855 // Peek through trunc/aext/zext/bitcast.
6856 // TODO: aext shouldn't require SM_SentinelZero padding.
6857 // TODO: handle shift of scalars.
6858 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
6859 while (Scl.getOpcode() == ISD::TRUNCATE ||
6860 Scl.getOpcode() == ISD::ANY_EXTEND ||
6861 Scl.getOpcode() == ISD::ZERO_EXTEND ||
6862 (Scl.getOpcode() == ISD::BITCAST &&
6865 Scl = Scl.getOperand(0);
6866 MinBitsPerElt =
6867 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
6868 }
6869 if ((MinBitsPerElt % 8) != 0)
6870 return false;
6871
6872 // Attempt to find the source vector the scalar was extracted from.
6873 SDValue SrcExtract;
6874 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
6875 Scl.getOpcode() == X86ISD::PEXTRW ||
6876 Scl.getOpcode() == X86ISD::PEXTRB) &&
6877 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6878 SrcExtract = Scl;
6879 }
6880 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6881 return false;
6882
6883 SDValue SrcVec = SrcExtract.getOperand(0);
6884 EVT SrcVT = SrcVec.getValueType();
6885 if (!SrcVT.getScalarType().isByteSized())
6886 return false;
6887 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6888 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
6889 unsigned DstByte = DstIdx * NumBytesPerElt;
6890 MinBitsPerElt =
6891 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
6892
6893 // Create 'identity' byte level shuffle mask and then add inserted bytes.
6894 if (Opcode == ISD::SCALAR_TO_VECTOR) {
6895 Ops.push_back(SrcVec);
6896 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6897 } else {
6898 Ops.push_back(SrcVec);
6899 Ops.push_back(N.getOperand(0));
6900 for (int i = 0; i != (int)NumSizeInBytes; ++i)
6901 Mask.push_back(NumSizeInBytes + i);
6902 }
6903
6904 unsigned MinBytesPerElts = MinBitsPerElt / 8;
6905 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
6906 for (unsigned i = 0; i != MinBytesPerElts; ++i)
6907 Mask[DstByte + i] = SrcByte + i;
6908 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
6909 Mask[DstByte + i] = SM_SentinelZero;
6910 return true;
6911 }
6912 case X86ISD::PACKSS:
6913 case X86ISD::PACKUS: {
6914 SDValue N0 = N.getOperand(0);
6915 SDValue N1 = N.getOperand(1);
6916 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6917 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6918 "Unexpected input value type");
6919
6920 APInt EltsLHS, EltsRHS;
6921 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
6922
6923 // If we know input saturation won't happen (or we don't care for particular
6924 // lanes), we can treat this as a truncation shuffle.
6925 bool Offset0 = false, Offset1 = false;
6926 if (Opcode == X86ISD::PACKSS) {
6927 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6928 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
6929 (!(N1.isUndef() || EltsRHS.isZero()) &&
6930 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
6931 return false;
6932 // We can't easily fold ASHR into a shuffle, but if it was feeding a
6933 // PACKSS then it was likely being used for sign-extension for a
6934 // truncation, so just peek through and adjust the mask accordingly.
6935 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
6936 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
6937 Offset0 = true;
6938 N0 = N0.getOperand(0);
6939 }
6940 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
6941 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
6942 Offset1 = true;
6943 N1 = N1.getOperand(0);
6944 }
6945 } else {
6946 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6947 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6948 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
6949 (!(N1.isUndef() || EltsRHS.isZero()) &&
6950 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
6951 return false;
6952 }
6953
6954 bool IsUnary = (N0 == N1);
6955
6956 Ops.push_back(N0);
6957 if (!IsUnary)
6958 Ops.push_back(N1);
6959
6960 createPackShuffleMask(VT, Mask, IsUnary);
6961
6962 if (Offset0 || Offset1) {
6963 for (int &M : Mask)
6964 if ((Offset0 && isInRange(M, 0, NumElts)) ||
6965 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
6966 ++M;
6967 }
6968 return true;
6969 }
6970 case ISD::VSELECT:
6971 case X86ISD::BLENDV: {
6972 SDValue Cond = N.getOperand(0);
6973 if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
6974 Ops.push_back(N.getOperand(1));
6975 Ops.push_back(N.getOperand(2));
6976 return true;
6977 }
6978 return false;
6979 }
6980 case X86ISD::VTRUNC: {
6981 SDValue Src = N.getOperand(0);
6982 EVT SrcVT = Src.getValueType();
6983 if (SrcVT.getSizeInBits() != NumSizeInBits)
6984 return false;
6985 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6986 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6987 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
6988 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
6989 for (unsigned i = 0; i != NumSrcElts; ++i)
6990 Mask.push_back(i * Scale);
6991 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
6992 Ops.push_back(Src);
6993 return true;
6994 }
6995 case ISD::SHL:
6996 case ISD::SRL: {
6997 APInt UndefElts;
6998 SmallVector<APInt, 32> EltBits;
6999 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7000 UndefElts, EltBits,
7001 /*AllowWholeUndefs*/ true,
7002 /*AllowPartialUndefs*/ false))
7003 return false;
7004
7005 // We can only decode 'whole byte' bit shifts as shuffles.
7006 for (unsigned I = 0; I != NumElts; ++I)
7007 if (DemandedElts[I] && !UndefElts[I] &&
7008 (EltBits[I].urem(8) != 0 || EltBits[I].uge(NumBitsPerElt)))
7009 return false;
7010
7011 Mask.append(NumSizeInBytes, SM_SentinelUndef);
7012 Ops.push_back(N.getOperand(0));
7013
7014 for (unsigned I = 0; I != NumElts; ++I) {
7015 if (!DemandedElts[I] || UndefElts[I])
7016 continue;
7017 unsigned ByteShift = EltBits[I].getZExtValue() / 8;
7018 unsigned Lo = I * NumBytesPerElt;
7019 unsigned Hi = Lo + NumBytesPerElt;
7020 // Clear mask to all zeros and insert the shifted byte indices.
7021 std::fill(Mask.begin() + Lo, Mask.begin() + Hi, SM_SentinelZero);
7022 if (ISD::SHL == Opcode)
7023 std::iota(Mask.begin() + Lo + ByteShift, Mask.begin() + Hi, Lo);
7024 else
7025 std::iota(Mask.begin() + Lo, Mask.begin() + Hi - ByteShift,
7026 Lo + ByteShift);
7027 }
7028 return true;
7029 }
7030 case X86ISD::VSHLI:
7031 case X86ISD::VSRLI: {
7032 uint64_t ShiftVal = N.getConstantOperandVal(1);
7033 // Out of range bit shifts are guaranteed to be zero.
7034 if (NumBitsPerElt <= ShiftVal) {
7035 Mask.append(NumElts, SM_SentinelZero);
7036 return true;
7037 }
7038
7039 // We can only decode 'whole byte' bit shifts as shuffles.
7040 if ((ShiftVal % 8) != 0)
7041 break;
7042
7043 uint64_t ByteShift = ShiftVal / 8;
7044 Ops.push_back(N.getOperand(0));
7045
7046 // Clear mask to all zeros and insert the shifted byte indices.
7047 Mask.append(NumSizeInBytes, SM_SentinelZero);
7048
7049 if (X86ISD::VSHLI == Opcode) {
7050 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7051 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7052 Mask[i + j] = i + j - ByteShift;
7053 } else {
7054 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7055 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7056 Mask[i + j - ByteShift] = i + j;
7057 }
7058 return true;
7059 }
7060 case ISD::ROTL:
7061 case ISD::ROTR: {
7062 APInt UndefElts;
7063 SmallVector<APInt, 32> EltBits;
7064 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7065 UndefElts, EltBits,
7066 /*AllowWholeUndefs*/ true,
7067 /*AllowPartialUndefs*/ false))
7068 return false;
7069
7070 // We can only decode 'whole byte' bit rotates as shuffles.
7071 for (unsigned I = 0; I != NumElts; ++I)
7072 if (DemandedElts[I] && !UndefElts[I] &&
7073 (EltBits[I].urem(NumBitsPerElt) % 8) != 0)
7074 return false;
7075
7076 Ops.push_back(N.getOperand(0));
7077 for (unsigned I = 0; I != NumElts; ++I) {
7078 if (!DemandedElts[I] || UndefElts[I]) {
7079 Mask.append(NumBytesPerElt, SM_SentinelUndef);
7080 continue;
7081 }
7082 int Offset = EltBits[I].urem(NumBitsPerElt) / 8;
7083 Offset = (ISD::ROTL == Opcode ? NumBytesPerElt - Offset : Offset);
7084 int BaseIdx = I * NumBytesPerElt;
7085 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7086 Mask.push_back(BaseIdx + ((Offset + J) % NumBytesPerElt));
7087 }
7088 }
7089 return true;
7090 }
7091 case X86ISD::VROTLI:
7092 case X86ISD::VROTRI: {
7093 // We can only decode 'whole byte' bit rotates as shuffles.
7094 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7095 if ((RotateVal % 8) != 0)
7096 return false;
7097 Ops.push_back(N.getOperand(0));
7098 int Offset = RotateVal / 8;
7099 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7100 for (int i = 0; i != (int)NumElts; ++i) {
7101 int BaseIdx = i * NumBytesPerElt;
7102 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7103 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7104 }
7105 }
7106 return true;
7107 }
7108 case X86ISD::VSHLD:
7109 case X86ISD::VSHRD: {
7110 // We can only decode 'whole byte' bit funnel shifts as shuffles.
7111 uint64_t ShiftVal = N.getConstantOperandAPInt(2).urem(NumBitsPerElt);
7112 int Offset = ShiftVal / 8;
7113 if ((ShiftVal % 8) != 0 || Offset == 0)
7114 return false;
7115 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 1 : 0));
7116 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 0 : 1));
7117 Offset = X86ISD::VSHRD == Opcode ? (NumBytesPerElt - Offset) : Offset;
7118 for (int I = 0; I != (int)NumElts; ++I) {
7119 int BaseIdx = (I * NumBytesPerElt) - Offset;
7120 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7121 int MaskIdx = BaseIdx + J;
7122 MaskIdx += J < Offset ? (NumSizeInBytes + NumBytesPerElt) : 0;
7123 Mask.push_back(MaskIdx);
7124 }
7125 }
7126 return true;
7127 }
7128 case X86ISD::VBROADCAST: {
7129 SDValue Src = N.getOperand(0);
7130 if (!Src.getSimpleValueType().isVector()) {
7131 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7132 !isNullConstant(Src.getOperand(1)) ||
7133 Src.getOperand(0).getValueType().getScalarType() !=
7134 VT.getScalarType())
7135 return false;
7136 Src = Src.getOperand(0);
7137 }
7138 Ops.push_back(Src);
7139 Mask.append(NumElts, 0);
7140 return true;
7141 }
7143 SDValue Src = N.getOperand(0);
7144 EVT SrcVT = Src.getValueType();
7145 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7146
7147 // Extended source must be a simple vector.
7148 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7149 (NumBitsPerSrcElt % 8) != 0)
7150 return false;
7151
7152 // We can only handle all-signbits extensions.
7153 APInt DemandedSrcElts =
7154 DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
7155 if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
7156 return false;
7157
7158 assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
7159 unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
7160 for (unsigned I = 0; I != NumElts; ++I)
7161 Mask.append(Scale, I);
7162 Ops.push_back(Src);
7163 return true;
7164 }
7165 case ISD::ZERO_EXTEND:
7166 case ISD::ANY_EXTEND:
7169 SDValue Src = N.getOperand(0);
7170 EVT SrcVT = Src.getValueType();
7171
7172 // Extended source must be a simple vector.
7173 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7174 (SrcVT.getScalarSizeInBits() % 8) != 0)
7175 return false;
7176
7177 bool IsAnyExtend =
7178 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7179 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7180 IsAnyExtend, Mask);
7181 Ops.push_back(Src);
7182 return true;
7183 }
7184 }
7185
7186 return false;
7187}
7188
7189/// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7191 SmallVectorImpl<int> &Mask) {
7192 int MaskWidth = Mask.size();
7193 SmallVector<SDValue, 16> UsedInputs;
7194 for (int i = 0, e = Inputs.size(); i < e; ++i) {
7195 int lo = UsedInputs.size() * MaskWidth;
7196 int hi = lo + MaskWidth;
7197
7198 // Strip UNDEF input usage.
7199 if (Inputs[i].isUndef())
7200 for (int &M : Mask)
7201 if ((lo <= M) && (M < hi))
7202 M = SM_SentinelUndef;
7203
7204 // Check for unused inputs.
7205 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7206 for (int &M : Mask)
7207 if (lo <= M)
7208 M -= MaskWidth;
7209 continue;
7210 }
7211
7212 // Check for repeated inputs.
7213 bool IsRepeat = false;
7214 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7215 if (peekThroughBitcasts(UsedInputs[j]) != peekThroughBitcasts(Inputs[i]))
7216 continue;
7217 for (int &M : Mask)
7218 if (lo <= M)
7219 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7220 IsRepeat = true;
7221 break;
7222 }
7223 if (IsRepeat)
7224 continue;
7225
7226 UsedInputs.push_back(Inputs[i]);
7227 }
7228 Inputs = std::move(UsedInputs);
7229}
7230
7231/// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7232/// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7233/// Returns true if the target shuffle mask was decoded.
7234static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7237 APInt &KnownUndef, APInt &KnownZero,
7238 const SelectionDAG &DAG, unsigned Depth,
7239 bool ResolveKnownElts) {
7241 return false; // Limit search depth.
7242
7243 EVT VT = Op.getValueType();
7244 if (!VT.isSimple() || !VT.isVector())
7245 return false;
7246
7247 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7248 if (ResolveKnownElts)
7249 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7250 return true;
7251 }
7252 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7253 ResolveKnownElts)) {
7254 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7255 return true;
7256 }
7257 return false;
7258}
7259
7260static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7263 const SelectionDAG &DAG, unsigned Depth,
7264 bool ResolveKnownElts) {
7265 APInt KnownUndef, KnownZero;
7266 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7267 KnownZero, DAG, Depth, ResolveKnownElts);
7268}
7269
7272 const SelectionDAG &DAG, unsigned Depth = 0,
7273 bool ResolveKnownElts = true) {
7274 EVT VT = Op.getValueType();
7275 if (!VT.isSimple() || !VT.isVector())
7276 return false;
7277
7278 unsigned NumElts = Op.getValueType().getVectorNumElements();
7279 APInt DemandedElts = APInt::getAllOnes(NumElts);
7280 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
7281 ResolveKnownElts);
7282}
7283
7284// Attempt to create a scalar/subvector broadcast from the base MemSDNode.
7285static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
7286 EVT MemVT, MemSDNode *Mem, unsigned Offset,
7287 SelectionDAG &DAG) {
7288 assert((Opcode == X86ISD::VBROADCAST_LOAD ||
7289 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
7290 "Unknown broadcast load type");
7291
7292 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
7293 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
7294 return SDValue();
7295
7296 SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
7298 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7299 SDValue Ops[] = {Mem->getChain(), Ptr};
7300 SDValue BcstLd = DAG.getMemIntrinsicNode(
7301 Opcode, DL, Tys, Ops, MemVT,
7303 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
7304 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
7305 return BcstLd;
7306}
7307
7308/// Returns the scalar element that will make up the i'th
7309/// element of the result of the vector shuffle.
7310static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7311 SelectionDAG &DAG, unsigned Depth) {
7313 return SDValue(); // Limit search depth.
7314
7315 EVT VT = Op.getValueType();
7316 unsigned Opcode = Op.getOpcode();
7317 unsigned NumElems = VT.getVectorNumElements();
7318
7319 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7320 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7321 int Elt = SV->getMaskElt(Index);
7322
7323 if (Elt < 0)
7324 return DAG.getUNDEF(VT.getVectorElementType());
7325
7326 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7327 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7328 }
7329
7330 // Recurse into target specific vector shuffles to find scalars.
7331 if (isTargetShuffle(Opcode)) {
7332 MVT ShufVT = VT.getSimpleVT();
7333 MVT ShufSVT = ShufVT.getVectorElementType();
7334 int NumElems = (int)ShufVT.getVectorNumElements();
7335 SmallVector<int, 16> ShuffleMask;
7337 if (!getTargetShuffleMask(Op, true, ShuffleOps, ShuffleMask))
7338 return SDValue();
7339
7340 int Elt = ShuffleMask[Index];
7341 if (Elt == SM_SentinelZero)
7342 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7343 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7344 if (Elt == SM_SentinelUndef)
7345 return DAG.getUNDEF(ShufSVT);
7346
7347 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7348 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7349 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7350 }
7351
7352 // Recurse into insert_subvector base/sub vector to find scalars.
7353 if (Opcode == ISD::INSERT_SUBVECTOR) {
7354 SDValue Vec = Op.getOperand(0);
7355 SDValue Sub = Op.getOperand(1);
7356 uint64_t SubIdx = Op.getConstantOperandVal(2);
7357 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7358
7359 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7360 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7361 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7362 }
7363
7364 // Recurse into concat_vectors sub vector to find scalars.
7365 if (Opcode == ISD::CONCAT_VECTORS) {
7366 EVT SubVT = Op.getOperand(0).getValueType();
7367 unsigned NumSubElts = SubVT.getVectorNumElements();
7368 uint64_t SubIdx = Index / NumSubElts;
7369 uint64_t SubElt = Index % NumSubElts;
7370 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
7371 }
7372
7373 // Recurse into extract_subvector src vector to find scalars.
7374 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
7375 SDValue Src = Op.getOperand(0);
7376 uint64_t SrcIdx = Op.getConstantOperandVal(1);
7377 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
7378 }
7379
7380 // We only peek through bitcasts of the same vector width.
7381 if (Opcode == ISD::BITCAST) {
7382 SDValue Src = Op.getOperand(0);
7383 EVT SrcVT = Src.getValueType();
7384 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
7385 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
7386 return SDValue();
7387 }
7388
7389 // Actual nodes that may contain scalar elements
7390
7391 // For insert_vector_elt - either return the index matching scalar or recurse
7392 // into the base vector.
7393 if (Opcode == ISD::INSERT_VECTOR_ELT &&
7394 isa<ConstantSDNode>(Op.getOperand(2))) {
7395 if (Op.getConstantOperandAPInt(2) == Index)
7396 return Op.getOperand(1);
7397 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
7398 }
7399
7400 if (Opcode == ISD::SCALAR_TO_VECTOR)
7401 return (Index == 0) ? Op.getOperand(0)
7402 : DAG.getUNDEF(VT.getVectorElementType());
7403
7404 if (Opcode == ISD::BUILD_VECTOR)
7405 return Op.getOperand(Index);
7406
7407 return SDValue();
7408}
7409
7410// Use PINSRB/PINSRW/PINSRD to create a build vector.
7412 const APInt &NonZeroMask,
7413 unsigned NumNonZero, unsigned NumZero,
7414 SelectionDAG &DAG,
7415 const X86Subtarget &Subtarget) {
7416 MVT VT = Op.getSimpleValueType();
7417 unsigned NumElts = VT.getVectorNumElements();
7418 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7419 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7420 "Illegal vector insertion");
7421
7422 SDValue V;
7423 bool First = true;
7424
7425 for (unsigned i = 0; i < NumElts; ++i) {
7426 bool IsNonZero = NonZeroMask[i];
7427 if (!IsNonZero)
7428 continue;
7429
7430 // If the build vector contains zeros or our first insertion is not the
7431 // first index then insert into zero vector to break any register
7432 // dependency else use SCALAR_TO_VECTOR.
7433 if (First) {
7434 First = false;
7435 if (NumZero || 0 != i)
7436 V = getZeroVector(VT, Subtarget, DAG, DL);
7437 else {
7438 assert(0 == i && "Expected insertion into zero-index");
7439 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7440 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7441 V = DAG.getBitcast(VT, V);
7442 continue;
7443 }
7444 }
7445 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, V, Op.getOperand(i),
7446 DAG.getVectorIdxConstant(i, DL));
7447 }
7448
7449 return V;
7450}
7451
7452/// Custom lower build_vector of v16i8.