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