LLVM 24.0.0git
X86ISelLowering.cpp
Go to the documentation of this file.
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that X86 uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86ISelLowering.h"
16#include "X86.h"
17#include "X86FrameLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86IntrinsicsInfo.h"
21#include "X86TargetMachine.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/Intrinsics.h"
54#include "llvm/MC/MCAsmInfo.h"
55#include "llvm/MC/MCContext.h"
56#include "llvm/MC/MCExpr.h"
57#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <bitset>
66#include <cctype>
67#include <numeric>
68using namespace llvm;
69
70#define DEBUG_TYPE "x86-isel"
71
73 "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
75 "Sets the preferable loop alignment for experiments (as log2 bytes) "
76 "for innermost loops only. If specified, this option overrides "
77 "alignment set by x86-experimental-pref-loop-alignment."),
79
81 "x86-br-merging-base-cost", cl::init(2),
83 "Sets the cost threshold for when multiple conditionals will be merged "
84 "into one branch versus be split in multiple branches. Merging "
85 "conditionals saves branches at the cost of additional instructions. "
86 "This value sets the instruction cost limit, below which conditionals "
87 "will be merged, and above which conditionals will be split. Set to -1 "
88 "to never merge branches."),
90
92 "x86-br-merging-ccmp-bias", cl::init(6),
93 cl::desc("Increases 'x86-br-merging-base-cost' in cases that the target "
94 "supports conditional compare instructions."),
96
97static cl::opt<bool>
98 WidenShift("x86-widen-shift", cl::init(true),
99 cl::desc("Replace narrow shifts with wider shifts."),
100 cl::Hidden);
101
103 "x86-br-merging-likely-bias", cl::init(0),
104 cl::desc("Increases 'x86-br-merging-base-cost' in cases that it is likely "
105 "that all conditionals will be executed. For example for merging "
106 "the conditionals (a == b && c > d), if its known that a == b is "
107 "likely, then it is likely that if the conditionals are split "
108 "both sides will be executed, so it may be desirable to increase "
109 "the instruction cost threshold. Set to -1 to never merge likely "
110 "branches."),
111 cl::Hidden);
112
114 "x86-br-merging-unlikely-bias", cl::init(-1),
115 cl::desc(
116 "Decreases 'x86-br-merging-base-cost' in cases that it is unlikely "
117 "that all conditionals will be executed. For example for merging "
118 "the conditionals (a == b && c > d), if its known that a == b is "
119 "unlikely, then it is unlikely that if the conditionals are split "
120 "both sides will be executed, so it may be desirable to decrease "
121 "the instruction cost threshold. Set to -1 to never merge unlikely "
122 "branches."),
123 cl::Hidden);
124
126 "mul-constant-optimization", cl::init(true),
127 cl::desc("Replace 'mul x, Const' with more effective instructions like "
128 "SHIFT, LEA, etc."),
129 cl::Hidden);
130
132 const X86Subtarget &STI)
133 : TargetLowering(TM, STI), Subtarget(STI) {
134 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
135 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
136
137 // Set up the TargetLowering object.
138
139 // X86 is weird. It always uses i8 for shift amounts and setcc results.
141 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
143
144 // X86 instruction cache is coherent with its data cache so we can use the
145 // default expansion to a no-op.
147
148 // For 64-bit, since we have so many registers, use the ILP scheduler.
149 // For 32-bit, use the register pressure specific scheduling.
150 // For Atom, always use ILP scheduling.
151 if (Subtarget.isAtom())
153 else if (Subtarget.is64Bit())
155 else
157 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
158 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
159
160 // Bypass expensive divides and use cheaper ones.
161 if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
162 if (Subtarget.hasSlowDivide32())
163 addBypassSlowDiv(32, 8);
164 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
165 addBypassSlowDiv(64, 32);
166 }
167
168 if (Subtarget.canUseCMPXCHG16B())
170 else if (Subtarget.canUseCMPXCHG8B())
172 else
174
175 setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
176
178
179 // Set up the register classes.
180 addRegisterClass(MVT::i8, &X86::GR8RegClass);
181 addRegisterClass(MVT::i16, &X86::GR16RegClass);
182 addRegisterClass(MVT::i32, &X86::GR32RegClass);
183 if (Subtarget.is64Bit())
184 addRegisterClass(MVT::i64, &X86::GR64RegClass);
185
186 for (MVT VT : MVT::integer_valuetypes())
188
189 // We don't accept any truncstore of integer registers.
190 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
191 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
192 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
193 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
194 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
195 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
196
197 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
198
199 // SETOEQ and SETUNE require checking two conditions.
200 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
203 }
204
205 // Integer absolute.
206 if (Subtarget.canUseCMOV()) {
207 setOperationAction(ISD::ABS , MVT::i16 , Custom);
208 setOperationAction(ISD::ABS , MVT::i32 , Custom);
209 if (Subtarget.is64Bit())
210 setOperationAction(ISD::ABS , MVT::i64 , Custom);
211 }
212
213 // Absolute difference.
214 for (auto Op : {ISD::ABDS, ISD::ABDU}) {
215 setOperationAction(Op , MVT::i8 , Custom);
216 setOperationAction(Op , MVT::i16 , Custom);
217 setOperationAction(Op , MVT::i32 , Custom);
218 if (Subtarget.is64Bit())
219 setOperationAction(Op , MVT::i64 , Custom);
220 }
221
222 // Signed saturation subtraction.
226 if (Subtarget.is64Bit())
228
229 // Funnel shifts.
230 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
231 // For slow shld targets we only lower for code size.
232 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
233
234 setOperationAction(ShiftOp , MVT::i8 , Custom);
235 setOperationAction(ShiftOp , MVT::i16 , Custom);
236 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
237 if (Subtarget.is64Bit())
238 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
239 }
240
241 if (!Subtarget.useSoftFloat()) {
242 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
243 // operation.
248 // We have an algorithm for SSE2, and we turn this into a 64-bit
249 // FILD or VCVTUSI2SS/SD for other targets.
252 // We have an algorithm for SSE2->double, and we turn this into a
253 // 64-bit FILD followed by conditional FADD for other targets.
256
257 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
258 // this operation.
261 // SSE has no i16 to fp conversion, only i32. We promote in the handler
262 // to allow f80 to use i16 and f64 to use i16 with sse1 only
265 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
268 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
269 // are Legal, f80 is custom lowered.
272
273 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
274 // this operation.
276 // FIXME: This doesn't generate invalid exception when it should. PR44019.
282 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
283 // are Legal, f80 is custom lowered.
286
287 // Handle FP_TO_UINT by promoting the destination to a larger signed
288 // conversion.
290 // FIXME: This doesn't generate invalid exception when it should. PR44019.
293 // FIXME: This doesn't generate invalid exception when it should. PR44019.
299
304
305 if (!Subtarget.is64Bit() && Subtarget.hasX87()) {
308 }
309 }
310
311 if (Subtarget.hasSSE2()) {
312 // Custom lowering for saturating float to int conversions.
313 // We handle promotion to larger result types manually.
314 for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
317 }
318 if (Subtarget.is64Bit()) {
321 }
322 }
323 if (Subtarget.hasAVX10_2()) {
324 for (MVT VT : {MVT::v8i8, MVT::v16i8, MVT::v32i8}) {
327 }
332 for (MVT VT : {MVT::i32, MVT::v4i32, MVT::v8i32, MVT::v16i32, MVT::v2i64,
333 MVT::v4i64}) {
336 }
337 if (Subtarget.is64Bit()) {
340 }
341 }
342
343 // Handle address space casts between mixed sized pointers.
346
347 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
348 if (!Subtarget.hasSSE2()) {
351 if (Subtarget.is64Bit()) {
353 // Without SSE, i64->f64 goes through memory.
355 }
356 } else if (!Subtarget.is64Bit())
358
359 // Scalar integer divide and remainder are lowered to use operations that
360 // produce two results, to match the available instructions. This exposes
361 // the two-result form to trivial CSE, which is able to combine x/y and x%y
362 // into a single instruction.
363 //
364 // Scalar integer multiply-high is also lowered to use two-result
365 // operations, to match the available instructions. However, plain multiply
366 // (low) operations are left as Legal, as there are single-result
367 // instructions for this in x86. Using the two-result multiply instructions
368 // when both high and low results are needed must be arranged by dagcombine.
369 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
376 }
377
378 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
380 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
381 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
384 }
385 if (Subtarget.is64Bit())
390
395
396 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
402 }
403
404 // Promote the i8 variants and force them on up to i32 which has a shorter
405 // encoding.
406 setOperationPromotedToType(ISD::CTTZ, MVT::i8, MVT::i32);
408 // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
409 // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
410 // promote that too.
411 setOperationPromotedToType(ISD::CTTZ, MVT::i16, MVT::i32);
413
414 if (!Subtarget.hasBMI()) {
417 if (Subtarget.is64Bit()) {
420 }
421 }
422
423 if (Subtarget.hasLZCNT()) {
424 // When promoting the i8 variants, force them to i32 for a shorter
425 // encoding.
426 setOperationPromotedToType(ISD::CTLZ, MVT::i8, MVT::i32);
428 } else {
429 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
430 if (VT == MVT::i64 && !Subtarget.is64Bit())
431 continue;
434 }
435 }
436
439 // Special handling for half-precision floating point conversions.
440 // If we don't have F16C support, then lower half float conversions
441 // into library calls.
443 Op, MVT::f32,
444 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
445 // There's never any support for operations beyond MVT::f32.
446 setOperationAction(Op, MVT::f64, Expand);
447 setOperationAction(Op, MVT::f80, Expand);
448 setOperationAction(Op, MVT::f128, Expand);
449 }
450
451 for (auto VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
454 }
455
456 for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
457 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
458 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
459 setTruncStoreAction(VT, MVT::f16, Expand);
460 setTruncStoreAction(VT, MVT::bf16, Expand);
461
464 }
465
469 if (Subtarget.is64Bit())
471 if (Subtarget.hasPOPCNT()) {
472 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
473 // popcntw is longer to encode than popcntl and also has a false dependency
474 // on the dest that popcntl hasn't had since Cannon Lake.
475 setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
476 } else {
481 }
482
483 if (Subtarget.hasBMI2()) {
487 if (Subtarget.is64Bit())
489 }
490
492
493 if (!Subtarget.hasMOVBE())
495
496 // X86 wants to expand cmov itself.
497 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
502 }
503 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
504 if (VT == MVT::i64 && !Subtarget.is64Bit())
505 continue;
508 }
509
511
512 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
515
517 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
518 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
522
523 // Darwin ABI issue.
524 for (auto VT : { MVT::i32, MVT::i64 }) {
525 if (VT == MVT::i64 && !Subtarget.is64Bit())
526 continue;
533 }
534
535 // 64-bit shl, sra, srl (iff 32-bit x86)
536 for (auto VT : { MVT::i32, MVT::i64 }) {
537 if (VT == MVT::i64 && !Subtarget.is64Bit())
538 continue;
542 }
543
544 if (Subtarget.hasSSEPrefetch())
546
548
549 // Expand certain atomics
550 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
558 }
559
560 if (!Subtarget.is64Bit())
562
563 if (Subtarget.is64Bit() && Subtarget.hasAVX()) {
564 // All CPUs supporting AVX will atomically load/store aligned 128-bit
565 // values, so we can emit [V]MOVAPS/[V]MOVDQA.
568 }
569
570 if (Subtarget.canUseCMPXCHG16B())
572
573 // FIXME - use subtarget debug flags
574 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
575 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
576 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
578 }
579
582
585
586 setOperationAction(ISD::TRAP, MVT::Other, Legal);
588 if (Subtarget.isTargetPS())
590 else
592
593 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
595 setOperationAction(ISD::VAEND , MVT::Other, Expand);
596 bool Is64Bit = Subtarget.is64Bit();
597 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
598 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
599
602
604
605 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
608
610
611 auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
612 setOperationAction(ISD::FABS, VT, Action);
613 setOperationAction(ISD::FNEG, VT, Action);
615 setOperationAction(ISD::FREM, VT, Action);
616 setOperationAction(ISD::FMA, VT, Action);
617 setOperationAction(ISD::FMINNUM, VT, Action);
618 setOperationAction(ISD::FMAXNUM, VT, Action);
623 setOperationAction(ISD::FSIN, VT, Action);
624 setOperationAction(ISD::FCOS, VT, Action);
625 setOperationAction(ISD::FSINCOS, VT, Action);
626 setOperationAction(ISD::FTAN, VT, Action);
627 setOperationAction(ISD::FSQRT, VT, Action);
628 setOperationAction(ISD::FPOW, VT, Action);
629 setOperationAction(ISD::FPOWI, VT, Action);
630 setOperationAction(ISD::FLOG, VT, Action);
631 setOperationAction(ISD::FLOG2, VT, Action);
632 setOperationAction(ISD::FLOG10, VT, Action);
633 setOperationAction(ISD::FEXP, VT, Action);
634 setOperationAction(ISD::FEXP2, VT, Action);
635 setOperationAction(ISD::FEXP10, VT, Action);
636 setOperationAction(ISD::FCEIL, VT, Action);
637 setOperationAction(ISD::FFLOOR, VT, Action);
639 setOperationAction(ISD::FRINT, VT, Action);
640 setOperationAction(ISD::BR_CC, VT, Action);
641 setOperationAction(ISD::SETCC, VT, Action);
644 setOperationAction(ISD::FROUND, VT, Action);
646 setOperationAction(ISD::FTRUNC, VT, Action);
647 setOperationAction(ISD::FLDEXP, VT, Action);
648 setOperationAction(ISD::FFREXP, VT, Action);
650 };
651
652 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
653 // f16, f32 and f64 use SSE.
654 // Set up the FP register classes.
655 addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
656 : &X86::FR16RegClass);
657 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
658 : &X86::FR32RegClass);
659 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
660 : &X86::FR64RegClass);
661
662 // Disable f32->f64 extload as we can only generate this in one instruction
663 // under optsize. So its easier to pattern match (fpext (load)) for that
664 // case instead of needing to emit 2 instructions for extload in the
665 // non-optsize case.
666 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
667
668 for (auto VT : { MVT::f32, MVT::f64 }) {
669 // Use ANDPD to simulate FABS.
671
672 // Use XORP to simulate FNEG.
674
675 // Use ANDPD and ORPD to simulate FCOPYSIGN.
677
678 // These might be better off as horizontal vector ops.
681
682 // We don't support sin/cos/fmod
686 }
687
688 // Half type will be promoted by default.
689 setF16Action(MVT::f16, Promote);
700
730
735
740
741 // Lower this to MOVMSK plus an AND.
744
745 } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
746 (UseX87 || Is64Bit)) {
747 // Use SSE for f32, x87 for f64.
748 // Set up the FP register classes.
749 addRegisterClass(MVT::f32, &X86::FR32RegClass);
750 if (UseX87)
751 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
752
753 // Use ANDPS to simulate FABS.
755
756 // Use XORP to simulate FNEG.
758
759 if (UseX87)
761
762 // Use ANDPS and ORPS to simulate FCOPYSIGN.
763 if (UseX87)
766
767 // We don't support sin/cos/fmod
771
772 if (UseX87) {
773 // Always expand sin/cos functions even though x87 has an instruction.
777 }
778 } else if (UseX87) {
779 // f32 and f64 in x87.
780 // Set up the FP register classes.
781 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
782 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
783
784 for (auto VT : { MVT::f32, MVT::f64 }) {
787
788 // Always expand sin/cos functions even though x87 has an instruction.
792 }
793 }
794
795 // Expand FP32 immediates into loads from the stack, save special cases.
796 if (isTypeLegal(MVT::f32)) {
797 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
798 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
799 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
800 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
801 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
802 } else // SSE immediates.
803 addLegalFPImmediate(APFloat(+0.0f)); // xorps
804 }
805 // Expand FP64 immediates into loads from the stack, save special cases.
806 if (isTypeLegal(MVT::f64)) {
807 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
808 addLegalFPImmediate(APFloat(+0.0)); // FLD0
809 addLegalFPImmediate(APFloat(+1.0)); // FLD1
810 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
811 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
812 } else // SSE immediates.
813 addLegalFPImmediate(APFloat(+0.0)); // xorpd
814 }
815 // Support fp16 0 immediate.
816 if (isTypeLegal(MVT::f16))
817 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
818
819 // Handle constrained floating-point operations of scalar.
832
833 // We don't support FMA.
836
837 // f80 always uses X87.
838 if (UseX87) {
839 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
842 {
844 addLegalFPImmediate(TmpFlt); // FLD0
845 TmpFlt.changeSign();
846 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
847
848 bool ignored;
849 APFloat TmpFlt2(+1.0);
851 &ignored);
852 addLegalFPImmediate(TmpFlt2); // FLD1
853 TmpFlt2.changeSign();
854 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
855 }
856
857 // Always expand sin/cos functions even though x87 has an instruction.
858 // clang-format off
870 // clang-format on
871
883
884 // Handle constrained floating-point operations of scalar.
891 if (isTypeLegal(MVT::f16)) {
894 } else {
896 }
897 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
898 // as Custom.
900 }
901
902 // f128 uses xmm registers, but most operations require libcalls.
903 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
904 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
905 : &X86::VR128RegClass);
906
907 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
908
919
923
924 // clang-format off
932 // clang-format on
933 // No STRICT_FSINCOS
936
939 // We need to custom handle any FP_ROUND with an f128 input, but
940 // LegalizeDAG uses the result type to know when to run a custom handler.
941 // So we have to list all legal floating point result types here.
942 if (isTypeLegal(MVT::f32)) {
945 }
946 if (isTypeLegal(MVT::f64)) {
949 }
950 if (isTypeLegal(MVT::f80)) {
954 }
955
957
958 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
959 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
960 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
961 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
962 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
963 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
964 }
965
966 // Always use a library call for pow.
967 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
968 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
969 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
970 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
971
980
981 // Some FP actions are always expanded for vector types.
982 for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
983 MVT::v4f32, MVT::v8f32, MVT::v16f32,
984 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
985 // clang-format off
999 // clang-format on
1000 }
1001
1002 // First set operation action for all vector types to either promote
1003 // (for widening) or expand (for scalarization). Then we will selectively
1004 // turn on ones that can be effectively codegen'd.
1044 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1045 setTruncStoreAction(InnerVT, VT, Expand);
1046
1047 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
1048 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
1049
1050 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
1051 // types, we have to deal with them whether we ask for Expansion or not.
1052 // Setting Expand causes its own optimisation problems though, so leave
1053 // them legal.
1054 if (VT.getVectorElementType() == MVT::i1)
1055 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1056
1057 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
1058 // split/scalarized right now.
1059 if (VT.getVectorElementType() == MVT::f16 ||
1060 VT.getVectorElementType() == MVT::bf16)
1061 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1062 }
1063 }
1064
1065 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
1066 // with -msoft-float, disable use of MMX as well.
1067 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
1068 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
1069 // No operations on x86mmx supported, everything uses intrinsics.
1070 }
1071
1072 auto SetFPMinMaxAction = [&](MVT VT) {
1081 };
1082
1083 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
1084 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1085 : &X86::VR128RegClass);
1086
1087 SetFPMinMaxAction(MVT::f32);
1088
1089 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
1090 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
1098
1099 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
1100 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
1102
1108 }
1109
1110 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1111 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1112 : &X86::VR128RegClass);
1113
1114 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1115 // registers cannot be used even for integer operations.
1116 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1117 : &X86::VR128RegClass);
1118 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1119 : &X86::VR128RegClass);
1120 addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1121 : &X86::VR128RegClass);
1122 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1123 : &X86::VR128RegClass);
1124 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1125 : &X86::VR128RegClass);
1126
1127 for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 })
1128 SetFPMinMaxAction(VT);
1129
1130 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
1131 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
1132 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
1133
1134 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1135 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1136 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1137 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
1138 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
1139 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
1140 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
1141 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
1142 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
1143 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1146
1147 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
1148 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
1149 setOperationAction(ISD::UMULO, MVT::v2i32, Custom);
1150
1151 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
1153 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
1155
1156 setOperationAction(ISD::LRINT, MVT::v4f32, Custom);
1157 setOperationAction(ISD::LRINT, MVT::v2i32, Custom);
1158
1159 setOperationAction(ISD::AND, MVT::i128, Custom);
1160 setOperationAction(ISD::OR, MVT::i128, Custom);
1161 setOperationAction(ISD::XOR, MVT::i128, Custom);
1163
1164 if (Subtarget.hasPCLMUL()) {
1165 for (auto VT : {MVT::i64, MVT::v4i32, MVT::v2i64}) {
1168 }
1172 }
1173
1174 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1175 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1176 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1177 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1178 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1182 }
1183
1184 // SSE2 can use basic vector unrolling.
1185 // SSE41 can use PHMINPOS to perform v16i8/v8i16 minmax reductions.
1186 // Fallback to ReplaceNodeResults for vXi64 reductions on 32-bit targets.
1187 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::i64}) {
1193 }
1194
1205
1210
1211 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1217
1218 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1219 // setcc all the way to isel and prefer SETGT in some isel patterns.
1222 }
1223
1224 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
1225 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
1230
1231 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1237 }
1238
1239 for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1243
1244 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1245 continue;
1246
1249 }
1250 setF16Action(MVT::v8f16, Expand);
1251 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1252 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1253 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1254 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1255 setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1256 setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1258
1259 // Custom lower v2i64 and v2f64 selects.
1266
1273
1274 // Custom legalize these to avoid over promotion or custom promotion.
1275 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1280 }
1281
1286
1289
1292
1293 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1298
1303
1304 // We want to legalize this to an f64 load rather than an i64 load on
1305 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1306 // store.
1307 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1308 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1309 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1310 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1311 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1313
1314 // Add 32-bit vector stores to help vectorization opportunities.
1315 setOperationAction(ISD::STORE, MVT::v2i16, Custom);
1317
1321 if (!Subtarget.hasAVX512())
1323
1327
1329
1346
1347 // In the customized shift lowering, the legal v4i32/v2i64 cases
1348 // in AVX2 will be recognized.
1349 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1353 if (VT == MVT::v2i64) continue;
1358 }
1359
1365 }
1366
1367 if (!Subtarget.useSoftFloat() && Subtarget.hasGFNI()) {
1372
1373 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1375 }
1376
1377 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1378 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
1379 }
1380
1381 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1382 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1383 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1384 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1385
1386 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1389 }
1391
1392 // These might be better off as horizontal vector ops.
1397 }
1398 if (Subtarget.hasNDD()) {
1399 // Enable custom lowering for scalar USUBSAT to optimize usub.sat(X,1)
1400 // with cmp+adc when NDD is available.
1405 }
1406 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1407 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1410 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1414 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1420
1422 }
1423
1424 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1425 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1426 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1427 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1428 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1429 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1430 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1431 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1432
1436
1437 // FIXME: Do we need to handle scalar-to-vector here?
1438 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1439 setOperationAction(ISD::SMULO, MVT::v2i32, Custom);
1440
1441 // We directly match byte blends in the backend as they match the VSELECT
1442 // condition form.
1444
1445 // SSE41 brings specific instructions for doing vector sign extend even in
1446 // cases where we don't have SRA.
1447 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1450 }
1451
1452 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1453 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1454 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1455 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1456 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1457 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1458 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1459 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1460 }
1461
1462 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1463 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1464 // do the pre and post work in the vector domain.
1467 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1468 // so that DAG combine doesn't try to turn it into uint_to_fp.
1471 }
1472 }
1473
1474 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1476 }
1477
1478 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1479 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1480 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1483 }
1484
1485 // XOP can efficiently perform BITREVERSE with VPPERM.
1486 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1488 }
1489
1490 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1491 bool HasInt256 = Subtarget.hasInt256();
1492
1493 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1494 : &X86::VR256RegClass);
1495 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1496 : &X86::VR256RegClass);
1497 addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1498 : &X86::VR256RegClass);
1499 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1500 : &X86::VR256RegClass);
1501 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1502 : &X86::VR256RegClass);
1503 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1504 : &X86::VR256RegClass);
1505 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1506 : &X86::VR256RegClass);
1507
1508 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1521
1523
1528 SetFPMinMaxAction(VT);
1529 }
1530
1531 setOperationAction(ISD::LRINT, MVT::v8f32, Custom);
1532 setOperationAction(ISD::LRINT, MVT::v4f64, Custom);
1533
1534 setOperationAction(ISD::AND, MVT::i256, Custom);
1535 setOperationAction(ISD::OR, MVT::i256, Custom);
1536 setOperationAction(ISD::XOR, MVT::i256, Custom);
1539
1540 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1541 // even though v8i16 is a legal type.
1542 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1543 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1544 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1545 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1549
1556
1568
1569 if (!Subtarget.hasAVX512())
1571
1572 // In the customized shift lowering, the legal v8i32/v4i64 cases
1573 // in AVX2 will be recognized.
1574 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1588 if (VT == MVT::v4i64) continue;
1593 }
1594
1595 // These types need custom splitting if their input is a 128-bit vector.
1600
1604 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1605 setOperationAction(ISD::SELECT, MVT::v16f16, Custom);
1608
1609 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1613 }
1614
1619
1620 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1625
1626 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1627 // setcc all the way to isel and prefer SETGT in some isel patterns.
1630 }
1631
1632 setOperationAction(ISD::SETCC, MVT::v4f64, Custom);
1633 setOperationAction(ISD::SETCC, MVT::v8f32, Custom);
1638
1639 if (Subtarget.hasAnyFMA()) {
1640 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1641 MVT::v2f64, MVT::v4f64 }) {
1644 }
1645 }
1646
1647 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1648 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1649 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1650 }
1651
1652 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1653 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1654 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1655 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1656
1657 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1658 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1659 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1660 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1661 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1662 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1663 setOperationAction(ISD::AVGCEILU, MVT::v16i16, HasInt256 ? Legal : Custom);
1664 setOperationAction(ISD::AVGCEILU, MVT::v32i8, HasInt256 ? Legal : Custom);
1665
1666 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1667 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1668
1669 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1670 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1671 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1672 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1673 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1674
1675 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1676 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1677 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1678 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1679 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1680 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1681 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1682 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1687
1688 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1689 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1690 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1691 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1692 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1693 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1694 }
1695
1696 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1699 }
1700
1701 if (HasInt256) {
1702 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1703 // when we have a 256bit-wide blend with immediate.
1706
1707 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1708 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1709 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1710 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1711 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1712 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1713 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1714 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1715 }
1716 }
1717
1718 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1719 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1720 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1722 }
1723
1724 // Extract subvector is special because the value type
1725 // (result) is 128-bit but the source is 256-bit wide.
1726 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1727 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1729 }
1730
1731 // Custom lower several nodes for 256-bit types.
1732 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1733 MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1743 }
1744 setF16Action(MVT::v16f16, Expand);
1745 setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1746 setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1748 setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1749 setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1750 setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1751 setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1752
1753 // Only PCLMUL required as we always unroll clmul vectors.
1754 if (Subtarget.hasPCLMUL()) {
1755 for (auto VT : {MVT::v8i32, MVT::v4i64}) {
1758 }
1759 }
1760
1761 if (HasInt256) {
1762 setOperationAction(ISD::MULHU, MVT::v4i64, Custom);
1763 // Custom so the combiner keeps full products as [SU]MUL_LOHI, not
1764 // MULH[SU].
1768
1769 // Custom legalize 2x32 to get a little better code.
1772
1773 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1774 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1776 }
1777
1778 if (Subtarget.hasGFNI()) {
1779 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1780 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1781 }
1782 }
1783
1784 if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1785 Subtarget.hasF16C()) {
1786 for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1789 }
1790 for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1793 }
1794 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1795 setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1796 setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1797 }
1798 setOperationAction(ISD::SETCC, MVT::v8f16, Custom);
1799 setOperationAction(ISD::SETCC, MVT::v16f16, Custom);
1800 }
1801
1802 // This block controls legalization of the mask vector sizes that are
1803 // available with AVX512. 512-bit vectors are in a separate block controlled
1804 // by useAVX512Regs.
1805 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1806 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1807 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1808 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1809 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1810 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1811
1815
1816 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1817 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1818 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1819 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1820 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1821 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1822 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1823 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1831
1832 // There is no byte sized k-register load or store without AVX512DQ.
1833 if (!Subtarget.hasDQI()) {
1834 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1835 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1836 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1837 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1838
1843 }
1844
1845 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1846 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1850 }
1851
1852 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1854
1855 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1859
1866 }
1867
1868 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1870 }
1871 if (Subtarget.hasDQI() && Subtarget.hasVLX()) {
1872 for (MVT VT : {MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1875 }
1876 }
1877
1878 // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1879 // elements. 512-bits can be disabled based on prefer-vector-width and
1880 // required-vector-width function attributes.
1881 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1882 bool HasBWI = Subtarget.hasBWI();
1883
1884 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1885 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1886 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1887 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1888 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1889 addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1890 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1891
1892 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1893 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1894 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1895 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1896 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1897 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1898 if (HasBWI)
1899 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1900 }
1901
1902 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1903 SetFPMinMaxAction(VT);
1911 }
1912 setOperationAction(ISD::LRINT, MVT::v16f32,
1913 Subtarget.hasDQI() ? Legal : Custom);
1914 setOperationAction(ISD::LRINT, MVT::v8f64,
1915 Subtarget.hasDQI() ? Legal : Custom);
1916 if (Subtarget.hasDQI())
1917 setOperationAction(ISD::LLRINT, MVT::v8f64, Legal);
1918
1919 setOperationAction(ISD::AND, MVT::i512, Custom);
1920 setOperationAction(ISD::OR, MVT::i512, Custom);
1921 setOperationAction(ISD::XOR, MVT::i512, Custom);
1922 setOperationAction(ISD::ADD, MVT::i512, Custom);
1923 setOperationAction(ISD::SUB, MVT::i512, Custom);
1924 setOperationAction(ISD::SRL, MVT::i512, Custom);
1925 setOperationAction(ISD::SHL, MVT::i512, Custom);
1926 setOperationAction(ISD::SRA, MVT::i512, Custom);
1927 setOperationAction(ISD::FSHR, MVT::i512, Custom);
1928 setOperationAction(ISD::FSHL, MVT::i512, Custom);
1929 setOperationAction(ISD::FSHR, MVT::i256, Custom);
1930 setOperationAction(ISD::FSHL, MVT::i256, Custom);
1933
1934 for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1939 }
1940
1941 for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1946 }
1947
1954
1966
1967 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1968 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1969 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1970 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1971 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1972 if (HasBWI)
1973 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1974
1975 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1976 // to 512-bit rather than use the AVX2 instructions so that we can use
1977 // k-masks.
1978 if (!Subtarget.hasVLX()) {
1979 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1980 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1983 }
1984 }
1985
1987 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1988 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
1998
1999 if (HasBWI) {
2000 // Extends from v64i1 masks to 512-bit vectors.
2004 }
2005
2006 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
2019
2021 }
2022
2023 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2026 }
2027
2028 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
2029 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
2030 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
2031 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
2032
2033 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
2034 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
2035 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
2036 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
2037
2038 setOperationAction(ISD::MULHU, MVT::v8i64, Custom);
2041 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
2042 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
2043 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
2044 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
2045 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
2046 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
2047 setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
2048 setOperationAction(ISD::AVGCEILU, MVT::v64i8, HasBWI ? Legal : Custom);
2049
2050 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
2051 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
2052
2053 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
2071
2072 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
2073 // setcc all the way to isel and prefer SETGT in some isel patterns.
2076 }
2077
2078 setOperationAction(ISD::SETCC, MVT::v8f64, Custom);
2079 setOperationAction(ISD::SETCC, MVT::v16f32, Custom);
2084
2085 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
2094 }
2095
2096 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2097 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
2098 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
2100 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
2101 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
2102 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
2103 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
2108 }
2109
2110 setOperationAction(ISD::FSHL, MVT::v64i8, Custom);
2111 setOperationAction(ISD::FSHR, MVT::v64i8, Custom);
2112 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
2113 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
2114 setOperationAction(ISD::FSHL, MVT::v16i32, Custom);
2115 setOperationAction(ISD::FSHR, MVT::v16i32, Custom);
2116
2117 if (Subtarget.hasDQI() || Subtarget.hasFP16())
2121 setOperationAction(Opc, MVT::v8i64, Custom);
2122
2123 if (Subtarget.hasDQI()) {
2124 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
2125
2126 // MULHS needs vpmullq (AVX512DQ) for its low multiply to be a win.
2127 setOperationAction(ISD::MULHS, MVT::v8i64, Custom);
2128 }
2129
2130 if (Subtarget.hasCDI()) {
2131 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
2132 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
2134 }
2135 } // Subtarget.hasCDI()
2136
2137 if (Subtarget.hasVPOPCNTDQ()) {
2138 for (auto VT : { MVT::v16i32, MVT::v8i64 })
2141 }
2142
2143 // Extract subvector is special because the value type
2144 // (result) is 256-bit but the source is 512-bit wide.
2145 // 128-bit was made Legal under AVX1.
2146 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
2147 MVT::v16f16, MVT::v8f32, MVT::v4f64 })
2149
2150 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
2151 MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
2161 }
2162 setF16Action(MVT::v32f16, Expand);
2167 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2168 setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
2169 setOperationAction(ISD::SETCC, MVT::v32f16, Custom);
2170
2171 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
2176 }
2177 if (HasBWI) {
2178 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
2181 }
2182 } else {
2183 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
2184 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
2185 }
2186
2187 if (Subtarget.hasVBMI2()) {
2188 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
2191 }
2192
2193 setOperationAction(ISD::ROTL, MVT::v32i16, Legal);
2194 setOperationAction(ISD::ROTR, MVT::v32i16, Legal);
2195 }
2196
2197 // Only PCLMUL required as we always unroll clmul vectors.
2198 if (Subtarget.hasPCLMUL()) {
2199 for (auto VT : {MVT::v16i32, MVT::v8i64}) {
2202 }
2203 }
2204
2205 setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2206 setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2208 setOperationAction(ISD::FLDEXP, MVT::v32f16, Custom);
2209
2210 if (Subtarget.hasGFNI()) {
2211 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
2212 setOperationAction(ISD::CTTZ, MVT::v64i8, Custom);
2213 }
2214 }// useAVX512Regs
2215
2216 if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
2217 for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
2218 MVT::v4i64}) {
2221 }
2222
2223 setOperationAction(ISD::ROTL, MVT::v16i16, Legal);
2224 setOperationAction(ISD::ROTR, MVT::v16i16, Legal);
2225 setOperationAction(ISD::ROTL, MVT::v8i16, Legal);
2226 setOperationAction(ISD::ROTR, MVT::v8i16, Legal);
2227 }
2228
2229 // This block controls legalization for operations that don't have
2230 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
2231 // narrower widths.
2232 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
2233 for (MVT VT : {MVT::f16, MVT::f32, MVT::f64, MVT::v8f16, MVT::v4f32,
2234 MVT::v2f64, MVT::v16f16, MVT::v8f32, MVT::v4f64})
2236
2237 // These operations are handled on non-VLX by artificially widening in
2238 // isel patterns.
2242
2243 if (Subtarget.hasDQI()) {
2244 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
2245 // v2f32 UINT_TO_FP is already custom under SSE2.
2248 "Unexpected operation action!");
2249 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2254 }
2255
2256 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2262 }
2263
2264 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2267 }
2268
2269 // Custom legalize 2x32 to get a little better code.
2272
2273 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2274 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2276
2277 if (Subtarget.hasDQI()) {
2281 setOperationAction(Opc, MVT::v2i64, Custom);
2282 setOperationAction(Opc, MVT::v4i64, Custom);
2283 }
2284 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2285 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2286
2287 // MULHS is only a win when the low multiply can use vpmullq; non-VLX
2288 // targets handle VPMULLQ by implicit widening.
2289 setOperationAction(ISD::MULHS, MVT::v4i64, Custom);
2290 }
2291
2292 if (Subtarget.hasCDI()) {
2293 for (auto VT : {MVT::i256, MVT::i512}) {
2294 if (VT == MVT::i512 && !Subtarget.useAVX512Regs())
2295 continue;
2300 }
2301 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2303 }
2304 } // Subtarget.hasCDI()
2305
2306 if (Subtarget.hasVPOPCNTDQ()) {
2307 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64})
2310 }
2311
2312 // We can try to convert vectors to different sizes to leverage legal
2313 // `vpcompress` cases. So we mark these supported vector sizes as Custom and
2314 // then specialize to Legal below.
2315 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2316 MVT::v4f64, MVT::v2i64, MVT::v2f64, MVT::v16i8, MVT::v8i16,
2317 MVT::v16i16, MVT::v8i8})
2319
2320 // Legal vpcompress depends on various AVX512 extensions.
2321 // Legal in AVX512F
2322 for (MVT VT : {MVT::v16i32, MVT::v16f32, MVT::v8i64, MVT::v8f64})
2324
2325 // Legal in AVX512F + AVX512VL
2326 if (Subtarget.hasVLX())
2327 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v4i32, MVT::v4f32, MVT::v4i64,
2328 MVT::v4f64, MVT::v2i64, MVT::v2f64})
2330
2331 // Legal in AVX512F + AVX512VBMI2
2332 if (Subtarget.hasVBMI2())
2333 for (MVT VT : {MVT::v32i16, MVT::v64i8})
2335
2336 // Legal in AVX512F + AVX512VL + AVX512VBMI2
2337 if (Subtarget.hasVBMI2() && Subtarget.hasVLX())
2338 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v32i8, MVT::v16i16})
2340 }
2341
2342 // This block control legalization of v32i1/v64i1 which are available with
2343 // AVX512BW..
2344 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2345 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
2346 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
2347
2348 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2359 }
2360
2361 for (auto VT : { MVT::v16i1, MVT::v32i1 })
2363
2364 // Extends from v32i1 masks to 256-bit vectors.
2368
2369 for (auto VT : {MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16,
2370 MVT::v16f16, MVT::v8f16}) {
2371 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
2372 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2373 }
2374
2375 // These operations are handled on non-VLX by artificially widening in
2376 // isel patterns.
2377 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2378
2379 if (Subtarget.hasBITALG()) {
2380 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2382 }
2383
2384 if (Subtarget.hasBMM()) {
2389
2390 for (auto VT : {MVT::v16i8, MVT::v32i8, MVT::v64i8})
2392 }
2393 }
2394
2395 if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2396 auto setGroup = [&] (MVT VT) {
2407
2420
2422
2425
2431
2437
2441 };
2442
2443 // AVX512_FP16 scalar operations
2444 setGroup(MVT::f16);
2445 SetFPMinMaxAction(MVT::f16);
2459
2462
2463 if (Subtarget.useAVX512Regs()) {
2464 setGroup(MVT::v32f16);
2470 setOperationAction(ISD::FP_ROUND, MVT::v16f16, Legal);
2477
2482 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i8, MVT::v32i16);
2484 MVT::v32i16);
2485 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i8, MVT::v32i16);
2487 MVT::v32i16);
2488 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v32i1, MVT::v32i16);
2490 MVT::v32i16);
2491 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v32i1, MVT::v32i16);
2493 MVT::v32i16);
2494
2498
2499 setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Legal);
2500 setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2501
2502 SetFPMinMaxAction(MVT::v32f16);
2503 setOperationAction(ISD::LRINT, MVT::v32f16, Legal);
2504 setOperationAction(ISD::LLRINT, MVT::v8f16, Legal);
2505 }
2506
2511
2512 if (Subtarget.hasVLX()) {
2513 setGroup(MVT::v8f16);
2514 setGroup(MVT::v16f16);
2515
2526
2533
2534 // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2537
2541
2542 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2543 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2544 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2545 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2546
2547 // Need to custom widen these to prevent scalarization.
2548 setOperationAction(ISD::LOAD, MVT::v4f16, Custom);
2549 setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2550
2551 SetFPMinMaxAction(MVT::v8f16);
2552 SetFPMinMaxAction(MVT::v16f16);
2553
2554 setOperationAction(ISD::LRINT, MVT::v8f16, Legal);
2555 setOperationAction(ISD::LRINT, MVT::v16f16, Legal);
2556 }
2557 }
2558
2559 if (!Subtarget.useSoftFloat() &&
2560 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2561 addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2562 : &X86::VR128RegClass);
2563 addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2564 : &X86::VR256RegClass);
2565 // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2566 // provide the method to promote BUILD_VECTOR and INSERT_VECTOR_ELT.
2567 // Set the operation action Custom to do the customization later.
2570 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2571 setF16Action(VT, Expand);
2572 if (!Subtarget.hasBF16())
2578 }
2579 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
2580 setOperationPromotedToType(Opc, MVT::v8bf16, MVT::v8f32);
2581 setOperationPromotedToType(Opc, MVT::v16bf16, MVT::v16f32);
2582 }
2583 setOperationAction(ISD::SETCC, MVT::v8bf16, Custom);
2584 setOperationAction(ISD::SETCC, MVT::v16bf16, Custom);
2586 addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2587 }
2588
2589 if (!Subtarget.useSoftFloat() && Subtarget.hasBF16() &&
2590 Subtarget.useAVX512Regs()) {
2591 addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2592 setF16Action(MVT::v32bf16, Expand);
2593 for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV})
2594 setOperationPromotedToType(Opc, MVT::v32bf16, MVT::v32f32);
2595 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2597 setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2601 }
2602
2603 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX10_2()) {
2604 setOperationAction(ISD::FADD, MVT::v32bf16, Legal);
2605 setOperationAction(ISD::FSUB, MVT::v32bf16, Legal);
2606 setOperationAction(ISD::FMUL, MVT::v32bf16, Legal);
2607 setOperationAction(ISD::FDIV, MVT::v32bf16, Legal);
2608 setOperationAction(ISD::FSQRT, MVT::v32bf16, Legal);
2609 setOperationAction(ISD::FMA, MVT::v32bf16, Legal);
2610 setOperationAction(ISD::SETCC, MVT::v32bf16, Custom);
2611 SetFPMinMaxAction(MVT::v32bf16);
2612 for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2620 SetFPMinMaxAction(VT);
2621 }
2622 for (auto VT : {MVT::f16, MVT::f32, MVT::f64}) {
2625 }
2626 }
2627
2628 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2629 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
2630 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2631 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2632 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
2633 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2634
2635 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
2636 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2637 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2638 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
2639 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2640
2641 if (Subtarget.hasBWI()) {
2642 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
2643 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
2644 }
2645
2646 if (Subtarget.hasFP16()) {
2647 // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2656 // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2665 // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2670 // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2675 }
2676 }
2677
2678 if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2679 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2680 }
2681
2682 // We want to custom lower some of our intrinsics.
2686 if (!Subtarget.is64Bit()) {
2688 }
2689
2690 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2691 // handle type legalization for these operations here.
2692 //
2693 // FIXME: We really should do custom legalization for addition and
2694 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
2695 // than generic legalization for 64-bit multiplication-with-overflow, though.
2696 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2697 if (VT == MVT::i64 && !Subtarget.is64Bit())
2698 continue;
2699 // Add/Sub/Mul with overflow operations are custom lowered.
2706
2707 // Support carry in as value rather than glue.
2713 }
2714
2715 // Combine sin / cos into _sincos_stret if it is available.
2718
2719 if (Subtarget.isTargetWin64()) {
2720 setOperationAction(ISD::SDIV, MVT::i128, Custom);
2721 setOperationAction(ISD::UDIV, MVT::i128, Custom);
2722 setOperationAction(ISD::SREM, MVT::i128, Custom);
2723 setOperationAction(ISD::UREM, MVT::i128, Custom);
2732 }
2733
2734 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2735 // is. We should promote the value to 64-bits to solve this.
2736 // This is what the CRT headers do - `fmodf` is an inline header
2737 // function casting to f64 and calling `fmod`.
2738 if (Subtarget.is32Bit() &&
2739 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2740 // clang-format off
2741 for (ISD::NodeType Op :
2759 // TODO: Add ISD:::STRICT_FMODF too once implemented.
2760 ISD::FMODF})
2761 if (isOperationExpandOrLibCall(Op, MVT::f32))
2762 setOperationAction(Op, MVT::f32, Promote);
2763 // clang-format on
2764
2765 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
2766 // it, but it's just a wrapper around ldexp.
2767 if (Subtarget.isOSWindows()) {
2769 if (isOperationExpand(Op, MVT::f32))
2770 setOperationAction(Op, MVT::f32, Promote);
2771 }
2772
2773 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f16, MVT::i16);
2774 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f32, MVT::i32);
2775 setOperationPromotedToType(ISD::ATOMIC_LOAD, MVT::f64, MVT::i64);
2776
2777 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f16, MVT::i16);
2778 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f32, MVT::i32);
2779 setOperationPromotedToType(ISD::ATOMIC_STORE, MVT::f64, MVT::i64);
2780
2781 // We have target-specific dag combine patterns for the following nodes:
2792 ISD::SHL,
2793 ISD::SRA,
2794 ISD::SRL,
2795 ISD::OR,
2796 ISD::AND,
2802 ISD::ADD,
2805 ISD::FADD,
2806 ISD::FSUB,
2807 ISD::FNEG,
2808 ISD::FMA,
2814 ISD::SUB,
2816 ISD::LOAD,
2817 ISD::LRINT,
2819 ISD::MLOAD,
2820 ISD::STORE,
2838 ISD::SETCC,
2839 ISD::MUL,
2840 ISD::XOR,
2848 ISD::ROTL,
2849 ISD::ROTR,
2850 ISD::FSHL,
2851 ISD::FSHR,
2855
2856 computeRegisterProperties(Subtarget.getRegisterInfo());
2857
2858 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2860 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2862 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2864
2865 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2866 // that needs to benchmarked and balanced with the potential use of vector
2867 // load/store types (PR33329, PR33914).
2870
2871 // Default loop alignment, which can be overridden by -align-loops.
2873
2874 // An out-of-order CPU can speculatively execute past a predictable branch,
2875 // but a conditional move could be stalled by an expensive earlier operation.
2876 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2877 EnableExtLdPromotion = true;
2879
2881
2882 // Default to having -disable-strictnode-mutation on
2883 IsStrictFPEnabled = true;
2884}
2885
2886// This has so far only been implemented for 64-bit MachO.
2888 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2889}
2890
2892 // Currently only MSVC CRTs mix the frame pointer into the stack guard value.
2893 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2894}
2895
2897 const SDLoc &DL) const {
2898 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2899 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2900 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2901 return SDValue(Node, 0);
2902}
2903
2906 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2907 !Subtarget.hasBWI())
2908 return TypeSplitVector;
2909
2910 // Since v8f16 is legal, widen anything over v4f16.
2911 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2912 VT.getVectorNumElements() <= 4 && !Subtarget.hasF16C() &&
2913 VT.getVectorElementType() == MVT::f16)
2914 return TypeSplitVector;
2915
2916 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2917 VT.getVectorElementType() != MVT::i1)
2918 return TypeWidenVector;
2919
2921}
2922
2924 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
2925 const LibcallLoweringInfo *libcallLowering) const {
2926 return X86::createFastISel(funcInfo, libInfo, libcallLowering);
2927}
2928
2929//===----------------------------------------------------------------------===//
2930// Other Lowering Hooks
2931//===----------------------------------------------------------------------===//
2932
2934 bool AssumeSingleUse, bool IgnoreAlignment) {
2935 if (!AssumeSingleUse && !Op.hasOneUse())
2936 return false;
2937 if (!ISD::isNormalLoad(Op.getNode()))
2938 return false;
2939
2940 // If this is an unaligned vector, make sure the target supports folding it.
2941 auto *Ld = cast<LoadSDNode>(Op.getNode());
2942 if (!IgnoreAlignment && !Subtarget.hasAVX() &&
2943 !Subtarget.hasSSEUnalignedMem() && Ld->getValueSizeInBits(0) == 128 &&
2944 Ld->getAlign() < Align(16))
2945 return false;
2946
2947 // TODO: If this is a non-temporal load and the target has an instruction
2948 // for it, it should not be folded. See "useNonTemporalLoad()".
2949
2950 return true;
2951}
2952
2954 const X86Subtarget &Subtarget,
2955 bool AssumeSingleUse) {
2956 assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2957 if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2958 return false;
2959
2960 // We can not replace a wide volatile load with a broadcast-from-memory,
2961 // because that would narrow the load, which isn't legal for volatiles.
2962 auto *Ld = cast<LoadSDNode>(Op.getNode());
2963 return !Ld->isVolatile() ||
2964 Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
2965}
2966
2968 if (!Op.hasOneUse())
2969 return false;
2970 // Peek through (oneuse) bitcast users
2971 SDNode *User = *Op->user_begin();
2972 while (User->getOpcode() == ISD::BITCAST) {
2973 if (!User->hasOneUse())
2974 return false;
2975 User = *User->user_begin();
2976 }
2977 return ISD::isNormalStore(User) || User->getOpcode() == ISD::ATOMIC_STORE;
2978}
2979
2981 if (Op.hasOneUse()) {
2982 unsigned Opcode = Op.getNode()->user_begin()->getOpcode();
2983 return (ISD::ZERO_EXTEND == Opcode);
2984 }
2985 return false;
2986}
2987
2988// Return true if its cheap to bitcast this to a vector type.
2990 const X86Subtarget &Subtarget) {
2991 if (peekThroughBitcasts(Op).getValueType().isVector())
2992 return true;
2994 return true;
2995
2996 EVT VT = Op.getValueType();
2997 unsigned Opcode = Op.getOpcode();
2998 if ((VT == MVT::i128 || VT == MVT::i256 || VT == MVT::i512) &&
2999 DAG.getTargetLoweringInfo().getOperationAction(Opcode, VT) ==
3001 // Check for larger than legal scalar integer ops that might have been
3002 // custom lowered to vector instruction.
3003 switch (Opcode) {
3004 case ISD::BITREVERSE:
3005 return true;
3006 case ISD::SHL:
3007 case ISD::SRL:
3008 case ISD::SRA:
3009 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget);
3010 case ISD::AND:
3011 case ISD::OR:
3012 case ISD::XOR:
3013 case ISD::ADD:
3014 case ISD::SUB:
3015 case ISD::FSHL:
3016 case ISD::FSHR:
3017 return mayFoldIntoVector(Op.getOperand(0), DAG, Subtarget) &&
3018 mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget);
3019 case ISD::SELECT:
3020 return mayFoldIntoVector(Op.getOperand(1), DAG, Subtarget) &&
3021 mayFoldIntoVector(Op.getOperand(2), DAG, Subtarget);
3022 }
3023 }
3024 return X86::mayFoldLoad(Op, Subtarget, /*AssumeSingleUse=*/true,
3025 /*IgnoreAlignment=*/true);
3026}
3027
3028static bool isLogicOp(unsigned Opcode) {
3029 // TODO: Add support for X86ISD::FAND/FOR/FXOR/FANDN with test coverage.
3030 return ISD::isBitwiseLogicOp(Opcode) || X86ISD::ANDNP == Opcode;
3031}
3032
3033static bool isTargetShuffle(unsigned Opcode) {
3034 switch(Opcode) {
3035 default: return false;
3036 case X86ISD::BLENDI:
3037 case X86ISD::PSHUFB:
3038 case X86ISD::PSHUFD:
3039 case X86ISD::PSHUFHW:
3040 case X86ISD::PSHUFLW:
3041 case X86ISD::SHUFP:
3042 case X86ISD::INSERTPS:
3043 case X86ISD::EXTRQI:
3044 case X86ISD::INSERTQI:
3045 case X86ISD::VALIGN:
3046 case X86ISD::PALIGNR:
3047 case X86ISD::VSHLDQ:
3048 case X86ISD::VSRLDQ:
3049 case X86ISD::MOVLHPS:
3050 case X86ISD::MOVHLPS:
3051 case X86ISD::MOVSHDUP:
3052 case X86ISD::MOVSLDUP:
3053 case X86ISD::MOVDDUP:
3054 case X86ISD::MOVSS:
3055 case X86ISD::MOVSD:
3056 case X86ISD::MOVSH:
3057 case X86ISD::UNPCKL:
3058 case X86ISD::UNPCKH:
3059 case X86ISD::VBROADCAST:
3060 case X86ISD::VPERMILPI:
3061 case X86ISD::VPERMILPV:
3062 case X86ISD::VPERM2X128:
3063 case X86ISD::SHUF128:
3064 case X86ISD::VPERMIL2:
3065 case X86ISD::VPERMI:
3066 case X86ISD::VPPERM:
3067 case X86ISD::VPERMV:
3068 case X86ISD::VPERMV3:
3069 case X86ISD::VZEXT_MOVL:
3070 case X86ISD::COMPRESS:
3071 case X86ISD::EXPAND:
3072 return true;
3073 }
3074}
3075
3076static bool isTargetShuffleVariableMask(unsigned Opcode) {
3077 switch (Opcode) {
3078 default: return false;
3079 // Target Shuffles.
3080 case X86ISD::PSHUFB:
3081 case X86ISD::VPERMILPV:
3082 case X86ISD::VPERMIL2:
3083 case X86ISD::VPPERM:
3084 case X86ISD::VPERMV:
3085 case X86ISD::VPERMV3:
3086 return true;
3087 // 'Faux' Target Shuffles.
3088 case ISD::OR:
3089 case ISD::AND:
3090 case X86ISD::ANDNP:
3091 return true;
3092 }
3093}
3094
3097 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3099 int ReturnAddrIndex = FuncInfo->getRAIndex();
3100
3101 if (ReturnAddrIndex == 0) {
3102 // Set up a frame object for the return address.
3103 unsigned SlotSize = RegInfo->getSlotSize();
3104 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
3105 -(int64_t)SlotSize,
3106 false);
3107 FuncInfo->setRAIndex(ReturnAddrIndex);
3108 }
3109
3110 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3111}
3112
3114 bool HasSymbolicDisplacement) {
3115 // Offset should fit into 32 bit immediate field.
3116 if (!isInt<32>(Offset))
3117 return false;
3118
3119 // If we don't have a symbolic displacement - we don't have any extra
3120 // restrictions.
3121 if (!HasSymbolicDisplacement)
3122 return true;
3123
3124 // We can fold large offsets in the large code model because we always use
3125 // 64-bit offsets.
3126 if (CM == CodeModel::Large)
3127 return true;
3128
3129 // For kernel code model we know that all object resist in the negative half
3130 // of 32bits address space. We may not accept negative offsets, since they may
3131 // be just off and we may accept pretty large positive ones.
3132 if (CM == CodeModel::Kernel)
3133 return Offset >= 0;
3134
3135 // For other non-large code models we assume that latest small object is 16MB
3136 // before end of 31 bits boundary. We may also accept pretty large negative
3137 // constants knowing that all objects are in the positive half of address
3138 // space.
3139 return Offset < 16 * 1024 * 1024;
3140}
3141
3142/// Return true if the condition is an signed comparison operation.
3143static bool isX86CCSigned(X86::CondCode X86CC) {
3144 switch (X86CC) {
3145 default:
3146 llvm_unreachable("Invalid integer condition!");
3147 case X86::COND_E:
3148 case X86::COND_NE:
3149 case X86::COND_B:
3150 case X86::COND_A:
3151 case X86::COND_BE:
3152 case X86::COND_AE:
3153 return false;
3154 case X86::COND_G:
3155 case X86::COND_GE:
3156 case X86::COND_L:
3157 case X86::COND_LE:
3158 return true;
3159 }
3160}
3161
3163 switch (SetCCOpcode) {
3164 // clang-format off
3165 default: llvm_unreachable("Invalid integer condition!");
3166 case ISD::SETEQ: return X86::COND_E;
3167 case ISD::SETGT: return X86::COND_G;
3168 case ISD::SETGE: return X86::COND_GE;
3169 case ISD::SETLT: return X86::COND_L;
3170 case ISD::SETLE: return X86::COND_LE;
3171 case ISD::SETNE: return X86::COND_NE;
3172 case ISD::SETULT: return X86::COND_B;
3173 case ISD::SETUGT: return X86::COND_A;
3174 case ISD::SETULE: return X86::COND_BE;
3175 case ISD::SETUGE: return X86::COND_AE;
3176 // clang-format on
3177 }
3178}
3179
3180/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3181/// condition code, returning the condition code and the LHS/RHS of the
3182/// comparison to make.
3184 bool isFP, SDValue &LHS, SDValue &RHS,
3185 SelectionDAG &DAG) {
3186 if (!isFP) {
3188 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
3189 // X > -1 -> X == 0, jump !sign.
3190 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3191 return X86::COND_NS;
3192 }
3193 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
3194 // X < 0 -> X == 0, jump on sign.
3195 return X86::COND_S;
3196 }
3197 if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
3198 // X >= 0 -> X == 0, jump on !sign.
3199 return X86::COND_NS;
3200 }
3201 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
3202 // X < 1 -> X <= 0
3203 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3204 return X86::COND_LE;
3205 }
3206 }
3207
3208 return TranslateIntegerX86CC(SetCCOpcode);
3209 }
3210
3211 // First determine if it is required or is profitable to flip the operands.
3212
3213 // If LHS is a foldable load, but RHS is not, flip the condition.
3214 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3215 !ISD::isNON_EXTLoad(RHS.getNode())) {
3216 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3217 std::swap(LHS, RHS);
3218 }
3219
3220 switch (SetCCOpcode) {
3221 default: break;
3222 case ISD::SETOLT:
3223 case ISD::SETOLE:
3224 case ISD::SETUGT:
3225 case ISD::SETUGE:
3226 std::swap(LHS, RHS);
3227 break;
3228 }
3229
3230 // On a floating point condition, the flags are set as follows:
3231 // ZF PF CF op
3232 // 0 | 0 | 0 | X > Y
3233 // 0 | 0 | 1 | X < Y
3234 // 1 | 0 | 0 | X == Y
3235 // 1 | 1 | 1 | unordered
3236 switch (SetCCOpcode) {
3237 // clang-format off
3238 default: llvm_unreachable("Condcode should be pre-legalized away");
3239 case ISD::SETUEQ:
3240 case ISD::SETEQ: return X86::COND_E;
3241 case ISD::SETOLT: // flipped
3242 case ISD::SETOGT:
3243 case ISD::SETGT: return X86::COND_A;
3244 case ISD::SETOLE: // flipped
3245 case ISD::SETOGE:
3246 case ISD::SETGE: return X86::COND_AE;
3247 case ISD::SETUGT: // flipped
3248 case ISD::SETULT:
3249 case ISD::SETLT: return X86::COND_B;
3250 case ISD::SETUGE: // flipped
3251 case ISD::SETULE:
3252 case ISD::SETLE: return X86::COND_BE;
3253 case ISD::SETONE:
3254 case ISD::SETNE: return X86::COND_NE;
3255 case ISD::SETUO: return X86::COND_P;
3256 case ISD::SETO: return X86::COND_NP;
3257 case ISD::SETOEQ:
3258 case ISD::SETUNE: return X86::COND_INVALID;
3259 // clang-format on
3260 }
3261}
3262
3263/// Is there a floating point cmov for the specific X86 condition code?
3264/// Current x86 isa includes the following FP cmov instructions:
3265/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3266static bool hasFPCMov(unsigned X86CC) {
3267 switch (X86CC) {
3268 default:
3269 return false;
3270 case X86::COND_B:
3271 case X86::COND_BE:
3272 case X86::COND_E:
3273 case X86::COND_P:
3274 case X86::COND_A:
3275 case X86::COND_AE:
3276 case X86::COND_NE:
3277 case X86::COND_NP:
3278 return true;
3279 }
3280}
3281
3282static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
3283 return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
3284 VT.is512BitVector();
3285}
3286
3289 MachineFunction &MF, unsigned Intrinsic) const {
3290 IntrinsicInfo Info;
3292 Info.offset = 0;
3293
3295 if (!IntrData) {
3296 switch (Intrinsic) {
3297 case Intrinsic::x86_aesenc128kl:
3298 case Intrinsic::x86_aesdec128kl:
3299 Info.opc = ISD::INTRINSIC_W_CHAIN;
3300 Info.ptrVal = I.getArgOperand(1);
3301 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3302 Info.align = Align(1);
3303 Info.flags |= MachineMemOperand::MOLoad;
3304 Infos.push_back(Info);
3305 return;
3306 case Intrinsic::x86_aesenc256kl:
3307 case Intrinsic::x86_aesdec256kl:
3308 Info.opc = ISD::INTRINSIC_W_CHAIN;
3309 Info.ptrVal = I.getArgOperand(1);
3310 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3311 Info.align = Align(1);
3312 Info.flags |= MachineMemOperand::MOLoad;
3313 Infos.push_back(Info);
3314 return;
3315 case Intrinsic::x86_aesencwide128kl:
3316 case Intrinsic::x86_aesdecwide128kl:
3317 Info.opc = ISD::INTRINSIC_W_CHAIN;
3318 Info.ptrVal = I.getArgOperand(0);
3319 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
3320 Info.align = Align(1);
3321 Info.flags |= MachineMemOperand::MOLoad;
3322 Infos.push_back(Info);
3323 return;
3324 case Intrinsic::x86_aesencwide256kl:
3325 case Intrinsic::x86_aesdecwide256kl:
3326 Info.opc = ISD::INTRINSIC_W_CHAIN;
3327 Info.ptrVal = I.getArgOperand(0);
3328 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
3329 Info.align = Align(1);
3330 Info.flags |= MachineMemOperand::MOLoad;
3331 Infos.push_back(Info);
3332 return;
3333 case Intrinsic::x86_cmpccxadd32:
3334 case Intrinsic::x86_cmpccxadd64:
3335 case Intrinsic::x86_atomic_bts:
3336 case Intrinsic::x86_atomic_btc:
3337 case Intrinsic::x86_atomic_btr: {
3338 Info.opc = ISD::INTRINSIC_W_CHAIN;
3339 Info.ptrVal = I.getArgOperand(0);
3340 unsigned Size = I.getType()->getScalarSizeInBits();
3341 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3342 Info.align = Align(Size);
3345 Infos.push_back(Info);
3346 return;
3347 }
3348 case Intrinsic::x86_atomic_bts_rm:
3349 case Intrinsic::x86_atomic_btc_rm:
3350 case Intrinsic::x86_atomic_btr_rm: {
3351 Info.opc = ISD::INTRINSIC_W_CHAIN;
3352 Info.ptrVal = I.getArgOperand(0);
3353 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3354 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3355 Info.align = Align(Size);
3358 Infos.push_back(Info);
3359 return;
3360 }
3361 case Intrinsic::x86_aadd32:
3362 case Intrinsic::x86_aadd64:
3363 case Intrinsic::x86_aand32:
3364 case Intrinsic::x86_aand64:
3365 case Intrinsic::x86_aor32:
3366 case Intrinsic::x86_aor64:
3367 case Intrinsic::x86_axor32:
3368 case Intrinsic::x86_axor64:
3369 case Intrinsic::x86_atomic_add_cc:
3370 case Intrinsic::x86_atomic_sub_cc:
3371 case Intrinsic::x86_atomic_or_cc:
3372 case Intrinsic::x86_atomic_and_cc:
3373 case Intrinsic::x86_atomic_xor_cc: {
3374 Info.opc = ISD::INTRINSIC_W_CHAIN;
3375 Info.ptrVal = I.getArgOperand(0);
3376 unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
3377 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
3378 Info.align = Align(Size);
3381 Infos.push_back(Info);
3382 return;
3383 }
3384 }
3385 return;
3386 }
3387
3388 switch (IntrData->Type) {
3391 case TRUNCATE_TO_MEM_VI32: {
3392 Info.opc = ISD::INTRINSIC_VOID;
3393 Info.ptrVal = I.getArgOperand(0);
3394 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
3396 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
3397 ScalarVT = MVT::i8;
3398 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
3399 ScalarVT = MVT::i16;
3400 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
3401 ScalarVT = MVT::i32;
3402
3403 Info.memVT = VT.changeElementType(ScalarVT);
3404 Info.align = Align(1);
3405 Info.flags |= MachineMemOperand::MOStore;
3406 Infos.push_back(Info);
3407 return;
3408 }
3409 case GATHER:
3410 case GATHER_AVX2: {
3411 Info.opc = ISD::INTRINSIC_W_CHAIN;
3412 Info.ptrVal = nullptr;
3413 MVT DataVT = MVT::getVT(I.getType());
3414 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3415 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3416 IndexVT.getVectorNumElements());
3417 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3418 Info.align = Align(1);
3419 Info.flags |= MachineMemOperand::MOLoad;
3420 Infos.push_back(Info);
3421 return;
3422 }
3423 case SCATTER: {
3424 Info.opc = ISD::INTRINSIC_VOID;
3425 Info.ptrVal = nullptr;
3426 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
3427 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
3428 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
3429 IndexVT.getVectorNumElements());
3430 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
3431 Info.align = Align(1);
3432 Info.flags |= MachineMemOperand::MOStore;
3433 Infos.push_back(Info);
3434 return;
3435 }
3436 default:
3437 return;
3438 }
3439}
3440
3441/// Returns true if the target can instruction select the
3442/// specified FP immediate natively. If false, the legalizer will
3443/// materialize the FP immediate as a load from a constant pool.
3445 bool ForCodeSize) const {
3446 for (const APFloat &FPImm : LegalFPImmediates)
3447 if (Imm.bitwiseIsEqual(FPImm))
3448 return true;
3449 return false;
3450}
3451
3453 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
3454 std::optional<unsigned> ByteOffset) const {
3455 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3456
3457 auto PeekThroughOneUserBitcasts = [](const SDNode *N) {
3458 while (N->getOpcode() == ISD::BITCAST && N->hasOneUse())
3459 N = *N->user_begin();
3460 return N;
3461 };
3462
3463 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3464 // relocation target a movq or addq instruction: don't let the load shrink.
3465 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3466 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3467 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3468 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3469
3470 // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
3471 // those uses are extracted directly into a store, then the extract + store
3472 // can be store-folded, or (4) any use will be used by legal full width
3473 // instruction. Then, it's probably not worth splitting the load.
3474 EVT VT = Load->getValueType(0);
3475 if ((VT.is256BitVector() || VT.is512BitVector()) &&
3476 !SDValue(Load, 0).hasOneUse()) {
3477 bool FullWidthUse = false;
3478 bool AllExtractStores = true;
3479 for (SDUse &Use : Load->uses()) {
3480 // Skip uses of the chain value. Result 0 of the node is the load value.
3481 if (Use.getResNo() != 0)
3482 continue;
3483
3484 const SDNode *User = PeekThroughOneUserBitcasts(Use.getUser());
3485
3486 // If this use is an extract + store, it's probably not worth splitting.
3487 if (User->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
3488 all_of(User->uses(), [&](const SDUse &U) {
3489 const SDNode *Inner = PeekThroughOneUserBitcasts(U.getUser());
3490 return Inner->getOpcode() == ISD::STORE;
3491 }))
3492 continue;
3493
3494 AllExtractStores = false;
3495
3496 // If any use is a full width legal/target bin op, then assume its legal
3497 // and won't split.
3498 if (isBinOp(User->getOpcode()) &&
3499 (isOperationLegal(User->getOpcode(), User->getValueType(0)) ||
3500 User->getOpcode() > ISD::BUILTIN_OP_END))
3501 FullWidthUse = true;
3502 }
3503
3504 if (AllExtractStores)
3505 return false;
3506
3507 // If we have an user that uses the full vector width, then this use is
3508 // only worth splitting if the offset isn't 0 (to avoid an
3509 // EXTRACT_SUBVECTOR) or we're loading a scalar integer.
3510 if (FullWidthUse)
3511 return (ByteOffset.value_or(0) > 0) || NewVT.isScalarInteger();
3512 }
3513
3514 return true;
3515}
3516
3517/// Returns true if it is beneficial to convert a load of a constant
3518/// to just the constant itself.
3520 Type *Ty) const {
3521 assert(Ty->isIntegerTy());
3522
3523 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3524 if (BitSize == 0 || BitSize > 64)
3525 return false;
3526 return true;
3527}
3528
3530 // If we are using XMM registers in the ABI and the condition of the select is
3531 // a floating-point compare and we have blendv or conditional move, then it is
3532 // cheaper to select instead of doing a cross-register move and creating a
3533 // load that depends on the compare result.
3534 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3535 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3536}
3537
3539 // TODO: It might be a win to ease or lift this restriction, but the generic
3540 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3541 if (VT.isVector() && Subtarget.hasAVX512())
3542 return false;
3543
3544 return true;
3545}
3546
3548 EVT) const {
3549 // With CCMP, keep and/or(setcc, setcc) trees intact so LowerSELECT can
3550 // emit them as CCMP chains rather than splitting into chained selects.
3551 return !(Subtarget.hasCCMP() && VT.isScalarInteger());
3552}
3553
3555 SDValue C) const {
3556 // TODO: We handle scalars using custom code, but generic combining could make
3557 // that unnecessary.
3558 APInt MulC;
3559 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3560 return false;
3561
3562 if (VT.isVector() && VT.getScalarSizeInBits() == 8) {
3563 // Check whether a vXi8 multiply can be decomposed into two shifts
3564 // (decomposing 2^m ± 2^n as 2^(a+b) ± 2^b). Similar to
3565 // DAGCombiner::visitMUL, consider the constant `2` decomposable as
3566 // (2^0 + 1).
3567 APInt ShiftedMulC = MulC.abs();
3568 unsigned TZeros = ShiftedMulC == 2 ? 0 : ShiftedMulC.countr_zero();
3569 ShiftedMulC.lshrInPlace(TZeros);
3570 if ((ShiftedMulC - 1).isPowerOf2() || (ShiftedMulC + 1).isPowerOf2())
3571 return true;
3572 }
3573
3574 // Find the type this will be legalized too. Otherwise we might prematurely
3575 // convert this to shl+add/sub and then still have to type legalize those ops.
3576 // Another choice would be to defer the decision for illegal types until
3577 // after type legalization. But constant splat vectors of i64 can't make it
3578 // through type legalization on 32-bit targets so we would need to special
3579 // case vXi64.
3580 while (getTypeAction(Context, VT) != TypeLegal)
3581 VT = getTypeToTransformTo(Context, VT);
3582
3583 // If vector multiply is legal, assume that's faster than shl + add/sub.
3584 // Multiply is a complex op with higher latency and lower throughput in
3585 // most implementations, sub-vXi32 vector multiplies are always fast,
3586 // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3587 // is always going to be slow.
3588 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3589 if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3590 (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3591 return false;
3592
3593 // shl+add, shl+sub, shl+add+neg
3594 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3595 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3596}
3597
3599 unsigned Index) const {
3601 return false;
3602
3603 // Mask vectors support all subregister combinations and operations that
3604 // extract half of vector.
3605 if (ResVT.getVectorElementType() == MVT::i1)
3606 return Index == 0 ||
3607 ((ResVT.getSizeInBits() * 2 == SrcVT.getSizeInBits()) &&
3608 (Index == ResVT.getVectorNumElements()));
3609
3610 return (Index % ResVT.getVectorNumElements()) == 0;
3611}
3612
3614 unsigned Opc = VecOp.getOpcode();
3615
3616 // Assume target opcodes can't be scalarized.
3617 // TODO - do we have any exceptions?
3618 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
3619 return false;
3620
3621 // If the vector op is not supported, try to convert to scalar.
3622 EVT VecVT = VecOp.getValueType();
3624 return true;
3625
3626 // If the vector op is supported, but the scalar op is not, the transform may
3627 // not be worthwhile.
3628 EVT ScalarVT = VecVT.getScalarType();
3629 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3630}
3631
3633 bool) const {
3634 // TODO: Allow vectors?
3635 if (VT.isVector())
3636 return false;
3637 return VT.isSimple() || !isOperationExpand(Opcode, VT);
3638}
3639
3641 // Speculate cttz only if we can directly use TZCNT/CMOV, can promote to
3642 // i32/i64 or can rely on BSF passthrough value.
3643 return Subtarget.hasBMI() || Subtarget.canUseCMOV() ||
3644 Subtarget.hasBitScanPassThrough() ||
3645 (!Ty->isVectorTy() &&
3646 Ty->getScalarSizeInBits() < (Subtarget.is64Bit() ? 64u : 32u));
3647}
3648
3650 // Speculate ctlz only if we can directly use LZCNT/CMOV, or can rely on BSR
3651 // passthrough value.
3652 return Subtarget.hasLZCNT() || Subtarget.canUseCMOV() ||
3653 Subtarget.hasBitScanPassThrough();
3654}
3655
3657 // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3658 // expensive than a straight movsd. On the other hand, it's important to
3659 // shrink long double fp constant since fldt is very slow.
3660 return !Subtarget.hasSSE2() || VT == MVT::f80;
3661}
3662
3664 return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3665 (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3666}
3667
3669 const SelectionDAG &DAG,
3670 const MachineMemOperand &MMO) const {
3671 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3672 BitcastVT.getVectorElementType() == MVT::i1)
3673 return false;
3674
3675 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3676 return false;
3677
3678 if (LoadVT.isVector() && BitcastVT.isVector()) {
3679 // If both types are legal vectors, it's always ok to convert them.
3680 // Don't convert to an illegal type.
3681 if (isTypeLegal(LoadVT))
3682 return isTypeLegal(BitcastVT);
3683 }
3684
3685 // If we have a large vector type (even if illegal), don't bitcast to large
3686 // (illegal) scalar types. Better to load fewer vectors and extract.
3687 if (LoadVT.isVector() && !BitcastVT.isVector() && LoadVT.isInteger() &&
3688 BitcastVT.isInteger() && (LoadVT.getSizeInBits() % 128) == 0)
3689 return false;
3690
3691 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3692}
3693
3695 const MachineFunction &MF) const {
3696 // Do not merge to float value size (128 bytes) if no implicit
3697 // float attribute is set.
3698 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3699
3700 if (NoFloat) {
3701 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3702 return (MemVT.getSizeInBits() <= MaxIntSize);
3703 }
3704 // Make sure we don't merge greater than our preferred vector
3705 // width.
3706 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3707 return false;
3708
3709 return true;
3710}
3711
3713 return Subtarget.hasFastLZCNT();
3714}
3715
3717 const Instruction &AndI) const {
3718 return true;
3719}
3720
3722 // Scalar integer and-not compares are efficiently handled by NOT+TEST (or
3723 // BMI ANDN).
3724 return Y.getValueType().isScalarInteger();
3725}
3726
3728 EVT VT = Y.getValueType();
3729
3730 if (!VT.isVector()) {
3731 if (!Subtarget.hasBMI())
3732 return false;
3733
3734 // There are only 32-bit and 64-bit forms for 'andn'.
3735 if (VT != MVT::i32 && VT != MVT::i64)
3736 return false;
3737 return !isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque();
3738 }
3739
3740 // Vector.
3741 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3742 return false;
3743
3744 if (VT == MVT::v4i32)
3745 return true;
3746
3747 return Subtarget.hasSSE2();
3748}
3749
3751 return X.getValueType().isScalarInteger(); // 'bt'
3752}
3753
3757 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3758 SelectionDAG &DAG) const {
3759 // Does baseline recommend not to perform the fold by default?
3761 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3762 return false;
3763 // For scalars this transform is always beneficial.
3764 if (X.getValueType().isScalarInteger())
3765 return true;
3766 // If all the shift amounts are identical, then transform is beneficial even
3767 // with rudimentary SSE2 shifts.
3768 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3769 return true;
3770 // If we have AVX2 with it's powerful shift operations, then it's also good.
3771 if (Subtarget.hasAVX2())
3772 return true;
3773 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3774 return NewShiftOpcode == ISD::SHL;
3775}
3776
3778 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3779 const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3780 if (!VT.isInteger())
3781 return ShiftOpc;
3782
3783 bool PreferRotate = false;
3784 if (VT.isVector()) {
3785 // For vectors, if we have rotate instruction support, then its definetly
3786 // best. Otherwise its not clear what the best so just don't make changed.
3787 PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3788 VT.getScalarType() == MVT::i64);
3789 } else {
3790 // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3791 // rotate unless we have a zext mask+shr.
3792 PreferRotate = Subtarget.hasBMI2();
3793 if (!PreferRotate) {
3794 unsigned MaskBits =
3795 VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3796 PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3797 }
3798 }
3799
3800 if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3801 assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3802
3803 if (PreferRotate && MayTransformRotate)
3804 return ISD::ROTL;
3805
3806 // If vector we don't really get much benefit swapping around constants.
3807 // Maybe we could check if the DAG has the flipped node already in the
3808 // future.
3809 if (VT.isVector())
3810 return ShiftOpc;
3811
3812 // See if the beneficial to swap shift type.
3813 if (ShiftOpc == ISD::SHL) {
3814 // If the current setup has imm64 mask, then inverse will have
3815 // at least imm32 mask (or be zext i32 -> i64).
3816 if (VT == MVT::i64)
3817 return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3818 : ShiftOpc;
3819
3820 // We can only benefit if req at least 7-bit for the mask. We
3821 // don't want to replace shl of 1,2,3 as they can be implemented
3822 // with lea/add.
3823 return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3824 }
3825
3826 if (VT == MVT::i64)
3827 // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3828 // extremely efficient.
3829 return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3830
3831 // Keep small shifts as shl so we can generate add/lea.
3832 return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3833 }
3834
3835 // We prefer rotate for vectors of if we won't get a zext mask with SRL
3836 // (PreferRotate will be set in the latter case).
3837 if (PreferRotate || !MayTransformRotate || VT.isVector())
3838 return ShiftOpc;
3839
3840 // Non-vector type and we have a zext mask with SRL.
3841 return ISD::SRL;
3842}
3843
3846 const Value *Lhs,
3847 const Value *Rhs,
3848 const Function *) const {
3849 using namespace llvm::PatternMatch;
3850 int BaseCost = BrMergingBaseCostThresh.getValue();
3851 // With CCMP, branches can be merged in a more efficient way.
3852 if (BaseCost >= 0 && Subtarget.hasCCMP())
3853 BaseCost += BrMergingCcmpBias;
3854 // a == b && a == c is a fast pattern on x86.
3855 if (BaseCost >= 0 && Opc == Instruction::And &&
3858 BaseCost += 1;
3859
3860 // For OR conditions with EQ comparisons, prefer splitting into branches
3861 // (unless CCMP is available). OR+EQ cannot be optimized via bitwise ops,
3862 // unlike OR+NE which becomes (P|Q)!=0. Similarly, don't split signed
3863 // comparisons (SLT, SGT) that can be optimized.
3864 if (BaseCost >= 0 && !Subtarget.hasCCMP() && Opc == Instruction::Or &&
3867 return {-1, -1, -1};
3868
3869 return {BaseCost, BrMergingLikelyBias.getValue(),
3870 BrMergingUnlikelyBias.getValue()};
3871}
3872
3874 return N->getOpcode() != ISD::FP_EXTEND;
3875}
3876
3878 const SDNode *N) const {
3879 assert(((N->getOpcode() == ISD::SHL &&
3880 N->getOperand(0).getOpcode() == ISD::SRL) ||
3881 (N->getOpcode() == ISD::SRL &&
3882 N->getOperand(0).getOpcode() == ISD::SHL)) &&
3883 "Expected shift-shift mask");
3884 // TODO: Should we always create i64 masks? Or only folded immediates?
3885 EVT VT = N->getValueType(0);
3886 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3887 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3888 // Only fold if the shift values are equal - so it folds to AND.
3889 // TODO - we should fold if either is a non-uniform vector but we don't do
3890 // the fold for non-splats yet.
3891 return N->getOperand(1) == N->getOperand(0).getOperand(1);
3892 }
3894}
3895
3897 EVT VT = Y.getValueType();
3898
3899 // For vectors, we don't have a preference, but we probably want a mask.
3900 if (VT.isVector())
3901 return false;
3902
3903 unsigned MaxWidth = Subtarget.is64Bit() ? 64 : 32;
3904 return VT.getScalarSizeInBits() <= MaxWidth;
3905}
3906
3909 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3911 !Subtarget.isOSWindows())
3914 ExpansionFactor);
3915}
3916
3918 // Any legal vector type can be splatted more efficiently than
3919 // loading/spilling from memory.
3920 return isTypeLegal(VT);
3921}
3922
3924 MVT VT = MVT::getIntegerVT(NumBits);
3925 if (isTypeLegal(VT))
3926 return VT;
3927
3928 // PMOVMSKB can handle this.
3929 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
3930 return MVT::v16i8;
3931
3932 // VPMOVMSKB can handle this.
3933 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
3934 return MVT::v32i8;
3935
3936 // TODO: Allow 64-bit type for 32-bit target.
3937 // TODO: 512-bit types should be allowed, but make sure that those
3938 // cases are handled in combineVectorSizedSetCCEquality().
3939
3941}
3942
3943/// Val is the undef sentinel value or equal to the specified value.
3944static bool isUndefOrEqual(int Val, int CmpVal) {
3945 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
3946}
3947
3948/// Return true if every element in Mask is the undef sentinel value or equal to
3949/// the specified value.
3950static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
3951 return llvm::all_of(Mask, [CmpVal](int M) {
3952 return (M == SM_SentinelUndef) || (M == CmpVal);
3953 });
3954}
3955
3956/// Return true if every element in Mask, beginning from position Pos and ending
3957/// in Pos+Size is the undef sentinel value or equal to the specified value.
3958static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
3959 unsigned Size) {
3960 return llvm::all_of(Mask.slice(Pos, Size),
3961 [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
3962}
3963
3964/// Val is either the undef or zero sentinel value.
3965static bool isUndefOrZero(int Val) {
3966 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
3967}
3968
3969/// Return true if every element in Mask, beginning from position Pos and ending
3970/// in Pos+Size is the undef sentinel value.
3971static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3972 return llvm::all_of(Mask.slice(Pos, Size), equal_to(SM_SentinelUndef));
3973}
3974
3975/// Return true if the mask creates a vector whose lower half is undefined.
3977 unsigned NumElts = Mask.size();
3978 return isUndefInRange(Mask, 0, NumElts / 2);
3979}
3980
3981/// Return true if the mask creates a vector whose upper half is undefined.
3983 unsigned NumElts = Mask.size();
3984 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
3985}
3986
3987/// Return true if Val falls within the specified range (L, H].
3988static bool isInRange(int Val, int Low, int Hi) {
3989 return (Val >= Low && Val < Hi);
3990}
3991
3992/// Return true if the value of any element in Mask falls within the specified
3993/// range (L, H].
3994static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
3995 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
3996}
3997
3998/// Return true if the value of any element in Mask is the zero sentinel value.
3999static bool isAnyZero(ArrayRef<int> Mask) {
4000 return llvm::any_of(Mask, equal_to(SM_SentinelZero));
4001}
4002
4003/// Return true if Val is undef or if its value falls within the
4004/// specified range (L, H].
4005static bool isUndefOrInRange(int Val, int Low, int Hi) {
4006 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
4007}
4008
4009/// Return true if every element in Mask is undef or if its value
4010/// falls within the specified range (L, H].
4011static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4012 return llvm::all_of(
4013 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
4014}
4015
4016/// Return true if Val is undef, zero or if its value falls within the
4017/// specified range (L, H].
4018static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4019 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
4020}
4021
4022/// Return true if every element in Mask is undef, zero or if its value
4023/// falls within the specified range (L, H].
4024static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4025 return llvm::all_of(
4026 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
4027}
4028
4029/// Return true if every element in Mask, is an in-place blend/select mask or is
4030/// undef.
4031[[maybe_unused]] static bool isBlendOrUndef(ArrayRef<int> Mask) {
4032 unsigned NumElts = Mask.size();
4033 for (auto [I, M] : enumerate(Mask))
4034 if (!isUndefOrEqual(M, I) && !isUndefOrEqual(M, I + NumElts))
4035 return false;
4036 return true;
4037}
4038
4039/// Return true if every element in Mask, beginning
4040/// from position Pos and ending in Pos + Size, falls within the specified
4041/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
4042static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
4043 unsigned Size, int Low, int Step = 1) {
4044 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4045 if (!isUndefOrEqual(Mask[i], Low))
4046 return false;
4047 return true;
4048}
4049
4050/// Return true if every element in Mask, beginning
4051/// from position Pos and ending in Pos+Size, falls within the specified
4052/// sequential range (Low, Low+Size], or is undef or is zero.
4054 unsigned Size, int Low,
4055 int Step = 1) {
4056 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4057 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4058 return false;
4059 return true;
4060}
4061
4062/// Return true if every element in Mask, beginning
4063/// from position Pos and ending in Pos+Size is undef or is zero.
4064static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4065 unsigned Size) {
4066 return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
4067}
4068
4069/// Return true if every element of a single input is referenced by the shuffle
4070/// mask. i.e. it just permutes them all.
4072 unsigned NumElts = Mask.size();
4073 APInt DemandedElts = APInt::getZero(NumElts);
4074 for (int M : Mask)
4075 if (isInRange(M, 0, NumElts))
4076 DemandedElts.setBit(M);
4077 return DemandedElts.isAllOnes();
4078}
4079
4080/// Helper function to test whether a shuffle mask could be
4081/// simplified by widening the elements being shuffled.
4082///
4083/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4084/// leaves it in an unspecified state.
4085///
4086/// NOTE: This must handle normal vector shuffle masks and *target* vector
4087/// shuffle masks. The latter have the special property of a '-2' representing
4088/// a zero-ed lane of a vector.
4090 SmallVectorImpl<int> &WidenedMask) {
4091 WidenedMask.assign(Mask.size() / 2, 0);
4092 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4093 int M0 = Mask[i];
4094 int M1 = Mask[i + 1];
4095
4096 // If both elements are undef, its trivial.
4097 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4098 WidenedMask[i / 2] = SM_SentinelUndef;
4099 continue;
4100 }
4101
4102 // Check for an undef mask and a mask value properly aligned to fit with
4103 // a pair of values. If we find such a case, use the non-undef mask's value.
4104 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4105 WidenedMask[i / 2] = M1 / 2;
4106 continue;
4107 }
4108 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4109 WidenedMask[i / 2] = M0 / 2;
4110 continue;
4111 }
4112
4113 // When zeroing, we need to spread the zeroing across both lanes to widen.
4114 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4115 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4117 WidenedMask[i / 2] = SM_SentinelZero;
4118 continue;
4119 }
4120 return false;
4121 }
4122
4123 // Finally check if the two mask values are adjacent and aligned with
4124 // a pair.
4125 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4126 WidenedMask[i / 2] = M0 / 2;
4127 continue;
4128 }
4129
4130 // Otherwise we can't safely widen the elements used in this shuffle.
4131 return false;
4132 }
4133 assert(WidenedMask.size() == Mask.size() / 2 &&
4134 "Incorrect size of mask after widening the elements!");
4135
4136 return true;
4137}
4138
4140 const APInt &Zeroable,
4141 bool V2IsZero,
4142 SmallVectorImpl<int> &WidenedMask) {
4143 // Create an alternative mask with info about zeroable elements.
4144 // Here we do not set undef elements as zeroable.
4145 SmallVector<int, 64> ZeroableMask(Mask);
4146 if (V2IsZero) {
4147 assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
4148 for (int i = 0, Size = Mask.size(); i != Size; ++i)
4149 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
4150 ZeroableMask[i] = SM_SentinelZero;
4151 }
4152 return canWidenShuffleElements(ZeroableMask, WidenedMask);
4153}
4154
4156 SmallVector<int, 32> WidenedMask;
4157 return canWidenShuffleElements(Mask, WidenedMask);
4158}
4159
4160// Attempt to narrow/widen shuffle mask until it matches the target number of
4161// elements.
4162static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
4163 SmallVectorImpl<int> &ScaledMask) {
4164 unsigned NumSrcElts = Mask.size();
4165 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
4166 "Illegal shuffle scale factor");
4167
4168 // Narrowing is guaranteed to work.
4169 if (NumDstElts >= NumSrcElts) {
4170 int Scale = NumDstElts / NumSrcElts;
4171 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
4172 return true;
4173 }
4174
4175 // We have to repeat the widening until we reach the target size, but we can
4176 // split out the first widening as it sets up ScaledMask for us.
4177 if (canWidenShuffleElements(Mask, ScaledMask)) {
4178 while (ScaledMask.size() > NumDstElts) {
4179 SmallVector<int, 16> WidenedMask;
4180 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
4181 return false;
4182 ScaledMask = std::move(WidenedMask);
4183 }
4184 return true;
4185 }
4186
4187 return false;
4188}
4189
4190static bool canScaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts) {
4191 SmallVector<int, 32> ScaledMask;
4192 return scaleShuffleElements(Mask, NumDstElts, ScaledMask);
4193}
4194
4195// Helper to grow the shuffle mask for a larger value type.
4196// NOTE: This is different to scaleShuffleElements which is a same size type.
4197static void growShuffleMask(ArrayRef<int> SrcMask,
4198 SmallVectorImpl<int> &DstMask,
4199 unsigned SrcSizeInBits, unsigned DstSizeInBits) {
4200 assert(DstMask.empty() && "Expected an empty shuffle mas");
4201 assert((DstSizeInBits % SrcSizeInBits) == 0 && "Illegal shuffle scale");
4202 unsigned Scale = DstSizeInBits / SrcSizeInBits;
4203 unsigned NumSrcElts = SrcMask.size();
4204 DstMask.assign(SrcMask.begin(), SrcMask.end());
4205 for (int &M : DstMask) {
4206 if (M < 0)
4207 continue;
4208 M = (M % NumSrcElts) + ((M / NumSrcElts) * Scale * NumSrcElts);
4209 }
4210 DstMask.append((Scale - 1) * NumSrcElts, SM_SentinelUndef);
4211}
4212
4213/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4215 return isNullConstant(Elt) || isNullFPConstant(Elt);
4216}
4217
4218// Build a vector of constants.
4219// Use an UNDEF node if MaskElt == -1.
4220// Split 64-bit constants in the 32-bit mode.
4222 const SDLoc &dl, bool IsMask = false) {
4223
4225 bool Split = false;
4226
4227 MVT ConstVecVT = VT;
4228 unsigned NumElts = VT.getVectorNumElements();
4229 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4230 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4231 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4232 Split = true;
4233 }
4234
4235 MVT EltVT = ConstVecVT.getVectorElementType();
4236 for (unsigned i = 0; i < NumElts; ++i) {
4237 bool IsUndef = Values[i] < 0 && IsMask;
4238 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4239 DAG.getConstant(Values[i], dl, EltVT);
4240 Ops.push_back(OpNode);
4241 if (Split)
4242 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4243 DAG.getConstant(0, dl, EltVT));
4244 }
4245 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4246 if (Split)
4247 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4248 return ConstsNode;
4249}
4250
4251static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
4252 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4253 assert(Bits.size() == Undefs.getBitWidth() &&
4254 "Unequal constant and undef arrays");
4256 bool Split = false;
4257
4258 MVT ConstVecVT = VT;
4259 unsigned NumElts = VT.getVectorNumElements();
4260 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4261 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4262 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4263 Split = true;
4264 }
4265
4266 MVT EltVT = ConstVecVT.getVectorElementType();
4267 MVT EltIntVT = EltVT.changeTypeToInteger();
4268 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
4269 if (Undefs[i]) {
4270 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
4271 continue;
4272 }
4273 const APInt &V = Bits[i];
4274 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
4275 if (Split) {
4276 Ops.push_back(DAG.getConstant(V.extractBits(32, 0), dl, EltVT));
4277 Ops.push_back(DAG.getConstant(V.extractBits(32, 32), dl, EltVT));
4278 } else {
4279 Ops.push_back(DAG.getBitcast(EltVT, DAG.getConstant(V, dl, EltIntVT)));
4280 }
4281 }
4282
4283 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4284 return DAG.getBitcast(VT, ConstsNode);
4285}
4286
4288 SelectionDAG &DAG, const SDLoc &dl) {
4289 APInt Undefs = APInt::getZero(Bits.size());
4290 return getConstVector(Bits, Undefs, VT, DAG, dl);
4291}
4292
4293/// Returns a vector of specified type with all zero elements.
4294static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
4295 SelectionDAG &DAG, const SDLoc &dl) {
4296 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
4297 VT.getVectorElementType() == MVT::i1) &&
4298 "Unexpected vector type");
4299
4300 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4301 // type. This ensures they get CSE'd. But if the integer type is not
4302 // available, use a floating-point +0.0 instead.
4303 SDValue Vec;
4304 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4305 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4306 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4307 } else if (VT.isFloatingPoint() &&
4309 Vec = DAG.getConstantFP(+0.0, dl, VT);
4310 } else if (VT.getVectorElementType() == MVT::i1) {
4311 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
4312 "Unexpected vector type");
4313 Vec = DAG.getConstant(0, dl, VT);
4314 } else {
4315 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4316 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4317 }
4318 return DAG.getBitcast(VT, Vec);
4319}
4320
4321// Helper to determine if the ops are all the extracted subvectors come from a
4322// single source. If we allow commute they don't have to be in order (Lo/Hi).
4323static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
4324 if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4325 RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4326 LHS.getValueType() != RHS.getValueType() ||
4327 LHS.getOperand(0) != RHS.getOperand(0))
4328 return SDValue();
4329
4330 SDValue Src = LHS.getOperand(0);
4331 if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
4332 return SDValue();
4333
4334 unsigned NumElts = LHS.getValueType().getVectorNumElements();
4335 if ((LHS.getConstantOperandAPInt(1) == 0 &&
4336 RHS.getConstantOperandAPInt(1) == NumElts) ||
4337 (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
4338 LHS.getConstantOperandAPInt(1) == NumElts))
4339 return Src;
4340
4341 return SDValue();
4342}
4343
4344static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4345 const SDLoc &dl, unsigned vectorWidth) {
4346 EVT VT = Vec.getValueType();
4347 EVT ElVT = VT.getVectorElementType();
4348 unsigned ResultNumElts =
4349 (VT.getVectorNumElements() * vectorWidth) / VT.getSizeInBits();
4350 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, ResultNumElts);
4351
4352 assert(ResultVT.getSizeInBits() == vectorWidth &&
4353 "Illegal subvector extraction");
4354
4355 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4356 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4357 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4358
4359 // This is the index of the first element of the vectorWidth-bit chunk
4360 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4361 IdxVal &= ~(ElemsPerChunk - 1);
4362
4363 // If the input is a buildvector just emit a smaller one.
4364 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4365 return DAG.getBuildVector(ResultVT, dl,
4366 Vec->ops().slice(IdxVal, ElemsPerChunk));
4367
4368 // Check if we're extracting the upper undef of a widening pattern.
4369 if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
4370 Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
4371 isNullConstant(Vec.getOperand(2)))
4372 return DAG.getUNDEF(ResultVT);
4373
4374 return DAG.getExtractSubvector(dl, ResultVT, Vec, IdxVal);
4375}
4376
4377/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4378/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4379/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4380/// instructions or a simple subregister reference. Idx is an index in the
4381/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4382/// lowering EXTRACT_VECTOR_ELT operations easier.
4383static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4384 SelectionDAG &DAG, const SDLoc &dl) {
4386 Vec.getValueType().is512BitVector()) &&
4387 "Unexpected vector size!");
4388 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4389}
4390
4391/// Generate a DAG to grab 256-bits from a 512-bit vector.
4392static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4393 SelectionDAG &DAG, const SDLoc &dl) {
4394 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4395 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4396}
4397
4398static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4399 SelectionDAG &DAG, const SDLoc &dl,
4400 unsigned vectorWidth) {
4401 assert((vectorWidth == 128 || vectorWidth == 256) &&
4402 "Unsupported vector width");
4403 // Inserting UNDEF is Result
4404 if (Vec.isUndef())
4405 return Result;
4406
4407 // Insert the relevant vectorWidth bits.
4408 EVT VT = Vec.getValueType();
4409 unsigned ElemsPerChunk = vectorWidth / VT.getScalarSizeInBits();
4410 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4411
4412 // This is the index of the first element of the vectorWidth-bit chunk
4413 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4414 IdxVal &= ~(ElemsPerChunk - 1);
4415 return DAG.getInsertSubvector(dl, Result, Vec, IdxVal);
4416}
4417
4418/// Generate a DAG to put 128-bits into a vector > 128 bits. This
4419/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4420/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4421/// simple superregister reference. Idx is an index in the 128 bits
4422/// we want. It need not be aligned to a 128-bit boundary. That makes
4423/// lowering INSERT_VECTOR_ELT operations easier.
4424static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4425 SelectionDAG &DAG, const SDLoc &dl) {
4426 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4427 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4428}
4429
4430/// Widen a vector to a larger size with the same scalar type, with the new
4431/// elements either zero or undef.
4432static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
4433 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4434 const SDLoc &dl) {
4435 EVT VecVT = Vec.getValueType();
4437 VecVT.getScalarType() == VT.getScalarType() &&
4438 "Unsupported vector widening type");
4439 // If the upper 128-bits of a build vector are already undef/zero, then try to
4440 // widen from the lower 128-bits.
4441 if (Vec.getOpcode() == ISD::BUILD_VECTOR && VecVT.is256BitVector()) {
4442 unsigned NumSrcElts = VecVT.getVectorNumElements();
4443 ArrayRef<SDUse> Hi = Vec->ops().drop_front(NumSrcElts / 2);
4444 if (all_of(Hi, [&](SDValue V) {
4445 return V.isUndef() || (ZeroNewElements && X86::isZeroNode(V));
4446 }))
4447 Vec = extract128BitVector(Vec, 0, DAG, dl);
4448 }
4449 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
4450 : DAG.getUNDEF(VT);
4451 return DAG.getInsertSubvector(dl, Res, Vec, 0);
4452}
4453
4454/// Widen a vector to a larger size with the same scalar type, with the new
4455/// elements either zero or undef.
4456static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
4457 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4458 const SDLoc &dl, unsigned WideSizeInBits) {
4459 assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
4460 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
4461 "Unsupported vector widening type");
4462 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
4463 MVT SVT = Vec.getSimpleValueType().getScalarType();
4464 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
4465 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4466}
4467
4468/// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
4469/// and bitcast with integer types.
4470static MVT widenMaskVectorType(MVT VT, const X86Subtarget &Subtarget) {
4471 assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
4472 unsigned NumElts = VT.getVectorNumElements();
4473 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
4474 return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4475 return VT;
4476}
4477
4478/// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
4479/// bitcast with integer types.
4480static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
4481 const X86Subtarget &Subtarget, SelectionDAG &DAG,
4482 const SDLoc &dl) {
4483 MVT VT = widenMaskVectorType(Vec.getSimpleValueType(), Subtarget);
4484 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
4485}
4486
4487// Helper function to collect subvector ops that are concatenated together,
4488// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
4489// The subvectors in Ops are guaranteed to be the same type.
4491 SelectionDAG &DAG) {
4492 assert(Ops.empty() && "Expected an empty ops vector");
4493
4494 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
4495 Ops.append(N->op_begin(), N->op_end());
4496 return true;
4497 }
4498
4499 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
4500 SDValue Src = N->getOperand(0);
4501 SDValue Sub = N->getOperand(1);
4502 const APInt &Idx = N->getConstantOperandAPInt(2);
4503 EVT VT = Src.getValueType();
4504 EVT SubVT = Sub.getValueType();
4505
4506 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
4507 // insert_subvector(undef, x, lo)
4508 if (Idx == 0 && Src.isUndef()) {
4509 Ops.push_back(Sub);
4510 Ops.push_back(DAG.getUNDEF(SubVT));
4511 return true;
4512 }
4513 if (Idx == (VT.getVectorNumElements() / 2)) {
4514 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
4515 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
4516 Src.getOperand(1).getValueType() == SubVT &&
4517 isNullConstant(Src.getOperand(2))) {
4518 // Attempt to recurse into inner (matching) concats.
4519 SDValue Lo = Src.getOperand(1);
4520 SDValue Hi = Sub;
4521 SmallVector<SDValue, 2> LoOps, HiOps;
4522 if (collectConcatOps(Lo.getNode(), LoOps, DAG) &&
4523 collectConcatOps(Hi.getNode(), HiOps, DAG) &&
4524 LoOps.size() == HiOps.size()) {
4525 Ops.append(LoOps);
4526 Ops.append(HiOps);
4527 return true;
4528 }
4529 Ops.push_back(Lo);
4530 Ops.push_back(Hi);
4531 return true;
4532 }
4533 // insert_subvector(x, extract_subvector(x, lo), hi)
4534 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4535 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
4536 Ops.append(2, Sub);
4537 return true;
4538 }
4539 // insert_subvector(undef, x, hi)
4540 if (Src.isUndef()) {
4541 Ops.push_back(DAG.getUNDEF(SubVT));
4542 Ops.push_back(Sub);
4543 return true;
4544 }
4545 }
4546 }
4547 }
4548
4549 if (N->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4550 EVT VT = N->getValueType(0);
4551 SDValue Src = N->getOperand(0);
4552 uint64_t Idx = N->getConstantOperandVal(1);
4553
4554 // Collect all the subvectors from the source vector and slice off the
4555 // extraction.
4557 if (collectConcatOps(Src.getNode(), SrcOps, DAG) &&
4558 VT.getSizeInBits() > SrcOps[0].getValueSizeInBits() &&
4559 (VT.getSizeInBits() % SrcOps[0].getValueSizeInBits()) == 0 &&
4560 (Idx % SrcOps[0].getValueType().getVectorNumElements()) == 0) {
4561 unsigned SubIdx = Idx / SrcOps[0].getValueType().getVectorNumElements();
4562 unsigned NumSubs = VT.getSizeInBits() / SrcOps[0].getValueSizeInBits();
4563 Ops.append(SrcOps.begin() + SubIdx, SrcOps.begin() + SubIdx + NumSubs);
4564 return true;
4565 }
4566 }
4567
4568 assert(Ops.empty() && "Expected an empty ops vector");
4569 return false;
4570}
4571
4572// Helper to check if \p V can be split into subvectors and the upper subvectors
4573// are all undef. In which case return the lower subvector.
4575 SelectionDAG &DAG) {
4576 SmallVector<SDValue> SubOps;
4577 if (!collectConcatOps(V.getNode(), SubOps, DAG))
4578 return SDValue();
4579
4580 unsigned NumSubOps = SubOps.size();
4581 unsigned HalfNumSubOps = NumSubOps / 2;
4582 assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
4583
4584 ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
4585 if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
4586 return SDValue();
4587
4588 EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
4589 ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
4590 return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
4591}
4592
4593// Helper to check if we can access all the constituent subvectors without any
4594// extract ops.
4597 return collectConcatOps(V.getNode(), Ops, DAG);
4598}
4599
4600static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4601 const SDLoc &dl) {
4602 EVT VT = Op.getValueType();
4603 unsigned NumElems = VT.getVectorNumElements();
4604 unsigned SizeInBits = VT.getSizeInBits();
4605 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4606 "Can't split odd sized vector");
4607
4609 if (collectConcatOps(Op.getNode(), SubOps, DAG)) {
4610 assert((SubOps.size() % 2) == 0 && "Can't split odd sized vector concat");
4611 unsigned HalfOps = SubOps.size() / 2;
4612 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
4613 SmallVector<SDValue, 2> LoOps(SubOps.begin(), SubOps.begin() + HalfOps);
4614 SmallVector<SDValue, 2> HiOps(SubOps.begin() + HalfOps, SubOps.end());
4615 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, LoOps);
4616 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, HiOps);
4617 return std::make_pair(Lo, Hi);
4618 }
4619
4620 // If this is a splat value (with no-undefs) then use the lower subvector,
4621 // which should be a free extraction.
4622 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4623 if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4624 return std::make_pair(Lo, Lo);
4625
4626 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4627 return std::make_pair(Lo, Hi);
4628}
4629
4630/// Break an operation into 2 half sized ops and then concatenate the results.
4632 unsigned NumOps = Op.getNumOperands();
4633 EVT VT = Op.getValueType();
4634
4635 // Extract the LHS Lo/Hi vectors
4638 for (unsigned I = 0; I != NumOps; ++I) {
4639 SDValue SrcOp = Op.getOperand(I);
4640 if (!SrcOp.getValueType().isVector()) {
4641 LoOps[I] = HiOps[I] = SrcOp;
4642 continue;
4643 }
4644 std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4645 }
4646
4647 EVT LoVT, HiVT;
4648 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4649 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4650 DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4651 DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4652}
4653
4654/// Break an unary integer operation into 2 half sized ops and then
4655/// concatenate the result back.
4657 const SDLoc &dl) {
4658 // Make sure we only try to split 256/512-bit types to avoid creating
4659 // narrow vectors.
4660 [[maybe_unused]] EVT VT = Op.getValueType();
4661 assert((Op.getOperand(0).getValueType().is256BitVector() ||
4662 Op.getOperand(0).getValueType().is512BitVector()) &&
4663 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4664 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4665 VT.getVectorNumElements() &&
4666 "Unexpected VTs!");
4667 return splitVectorOp(Op, DAG, dl);
4668}
4669
4670/// Break a binary integer operation into 2 half sized ops and then
4671/// concatenate the result back.
4673 const SDLoc &dl) {
4674 // Assert that all the types match.
4675 [[maybe_unused]] EVT VT = Op.getValueType();
4676 assert(Op.getOperand(0).getValueType() == VT &&
4677 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4678 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4679 return splitVectorOp(Op, DAG, dl);
4680}
4681
4682// Helper for splitting operands of an operation to legal target size and
4683// apply a function on each part.
4684// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4685// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4686// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4687// The argument Builder is a function that will be applied on each split part:
4688// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4689template <typename F>
4691 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4692 F Builder, bool CheckBWI = true,
4693 bool AllowAVX512 = true) {
4694 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4695 unsigned NumSubs = 1;
4696 if (AllowAVX512 && ((CheckBWI && Subtarget.useBWIRegs()) ||
4697 (!CheckBWI && Subtarget.useAVX512Regs()))) {
4698 if (VT.getSizeInBits() > 512) {
4699 NumSubs = VT.getSizeInBits() / 512;
4700 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4701 }
4702 } else if (Subtarget.hasAVX2()) {
4703 if (VT.getSizeInBits() > 256) {
4704 NumSubs = VT.getSizeInBits() / 256;
4705 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4706 }
4707 } else {
4708 if (VT.getSizeInBits() > 128) {
4709 NumSubs = VT.getSizeInBits() / 128;
4710 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4711 }
4712 }
4713
4714 if (NumSubs == 1)
4715 return Builder(DAG, DL, Ops);
4716
4718 for (unsigned i = 0; i != NumSubs; ++i) {
4720 for (SDValue Op : Ops) {
4721 EVT OpVT = Op.getValueType();
4722 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4723 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4724 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4725 }
4726 Subs.push_back(Builder(DAG, DL, SubOps));
4727 }
4728 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4729}
4730
4731// Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4732// targets.
4733static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4735 const X86Subtarget &Subtarget) {
4736 assert(Subtarget.hasAVX512() && "AVX512 target expected");
4737 MVT SVT = VT.getScalarType();
4738
4739 // If we have a 32/64 splatted constant, splat it to DstTy to
4740 // encourage a foldable broadcast'd operand.
4741 auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4742 unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4743 // AVX512 broadcasts 32/64-bit operands.
4744 // TODO: Support float once getAVX512Node is used by fp-ops.
4745 if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4747 return SDValue();
4748 // If we're not widening, don't bother if we're not bitcasting.
4749 if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4750 return SDValue();
4752 APInt SplatValue, SplatUndef;
4753 unsigned SplatBitSize;
4754 bool HasAnyUndefs;
4755 if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4756 HasAnyUndefs, OpEltSizeInBits) &&
4757 !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4758 return DAG.getConstant(SplatValue, DL, DstVT);
4759 }
4760 return SDValue();
4761 };
4762
4763 bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4764
4765 MVT DstVT = VT;
4766 if (Widen)
4767 DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4768
4769 // Canonicalize src operands.
4770 SmallVector<SDValue> SrcOps(Ops);
4771 for (SDValue &Op : SrcOps) {
4772 MVT OpVT = Op.getSimpleValueType();
4773 // Just pass through scalar operands.
4774 if (!OpVT.isVector())
4775 continue;
4776 assert(OpVT == VT && "Vector type mismatch");
4777
4778 if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4779 Op = BroadcastOp;
4780 continue;
4781 }
4782
4783 // Just widen the subvector by inserting into an undef wide vector.
4784 if (Widen)
4785 Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4786 }
4787
4788 SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4789
4790 // Perform the 512-bit op then extract the bottom subvector.
4791 if (Widen)
4792 Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4793 return Res;
4794}
4795
4796/// Insert i1-subvector to i1-vector.
4798 const X86Subtarget &Subtarget) {
4799
4800 SDLoc dl(Op);
4801 SDValue Vec = Op.getOperand(0);
4802 SDValue SubVec = Op.getOperand(1);
4803 SDValue Idx = Op.getOperand(2);
4804 unsigned IdxVal = Op.getConstantOperandVal(2);
4805
4806 // Inserting undef is a nop. We can just return the original vector.
4807 if (SubVec.isUndef())
4808 return Vec;
4809
4810 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4811 return Op;
4812
4813 MVT OpVT = Op.getSimpleValueType();
4814 unsigned NumElems = OpVT.getVectorNumElements();
4815 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, dl);
4816
4817 // Extend to natively supported kshift.
4818 MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4819
4820 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4821 // if necessary.
4822 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4823 // May need to promote to a legal type.
4824 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4825 DAG.getConstant(0, dl, WideOpVT),
4826 SubVec, Idx);
4827 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4828 }
4829
4830 MVT SubVecVT = SubVec.getSimpleValueType();
4831 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4832 assert(IdxVal + SubVecNumElems <= NumElems &&
4833 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4834 "Unexpected index value in INSERT_SUBVECTOR");
4835
4836 SDValue Undef = DAG.getUNDEF(WideOpVT);
4837
4838 if (IdxVal == 0) {
4839 // Zero lower bits of the Vec
4840 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4841 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4842 ZeroIdx);
4843 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4844 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4845 // Merge them together, SubVec should be zero extended.
4846 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4847 DAG.getConstant(0, dl, WideOpVT),
4848 SubVec, ZeroIdx);
4849 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4850 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4851 }
4852
4853 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4854 Undef, SubVec, ZeroIdx);
4855
4856 if (Vec.isUndef()) {
4857 assert(IdxVal != 0 && "Unexpected index");
4858 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4859 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4860 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4861 }
4862
4864 assert(IdxVal != 0 && "Unexpected index");
4865 // If upper elements of Vec are known undef, then just shift into place.
4866 if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4867 [](SDValue V) { return V.isUndef(); })) {
4868 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4869 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4870 } else {
4871 NumElems = WideOpVT.getVectorNumElements();
4872 unsigned ShiftLeft = NumElems - SubVecNumElems;
4873 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4874 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4875 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4876 if (ShiftRight != 0)
4877 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4878 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4879 }
4880 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4881 }
4882
4883 // Simple case when we put subvector in the upper part
4884 if (IdxVal + SubVecNumElems == NumElems) {
4885 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4886 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4887 if (SubVecNumElems * 2 == NumElems) {
4888 // Special case, use legal zero extending insert_subvector. This allows
4889 // isel to optimize when bits are known zero.
4890 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4891 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4892 DAG.getConstant(0, dl, WideOpVT),
4893 Vec, ZeroIdx);
4894 } else {
4895 // Otherwise use explicit shifts to zero the bits.
4896 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4897 Undef, Vec, ZeroIdx);
4898 NumElems = WideOpVT.getVectorNumElements();
4899 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4900 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4901 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4902 }
4903 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4904 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4905 }
4906
4907 // Inserting into the middle is more complicated.
4908
4909 NumElems = WideOpVT.getVectorNumElements();
4910
4911 // Widen the vector if needed.
4912 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4913
4914 unsigned ShiftLeft = NumElems - SubVecNumElems;
4915 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4916
4917 // Do an optimization for the most frequently used types.
4918 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4919 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4920 Mask0.flipAllBits();
4921 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4922 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4923 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4924 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4925 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4926 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4927 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4928 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4929
4930 // Reduce to original width if needed.
4931 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4932 }
4933
4934 // Clear the upper bits of the subvector and move it to its insert position.
4935 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4936 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4937 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4938 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4939
4940 // Isolate the bits below the insertion point.
4941 unsigned LowShift = NumElems - IdxVal;
4942 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
4943 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4944 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
4945 DAG.getTargetConstant(LowShift, dl, MVT::i8));
4946
4947 // Isolate the bits after the last inserted bit.
4948 unsigned HighShift = IdxVal + SubVecNumElems;
4949 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
4950 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4951 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
4952 DAG.getTargetConstant(HighShift, dl, MVT::i8));
4953
4954 // Now OR all 3 pieces together.
4955 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
4956 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
4957
4958 // Reduce to original width if needed.
4959 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4960}
4961
4963 const SDLoc &dl) {
4964 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
4965 EVT SubVT = V1.getValueType();
4966 EVT SubSVT = SubVT.getScalarType();
4967 unsigned SubNumElts = SubVT.getVectorNumElements();
4968 unsigned SubVectorWidth = SubVT.getSizeInBits();
4969 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
4970 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
4971 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
4972}
4973
4974/// Returns a vector of specified type with all bits set.
4975/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
4976/// Then bitcast to their original type, ensuring they get CSE'd.
4977static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4978 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4979 "Expected a 128/256/512-bit vector type");
4980 unsigned NumElts = VT.getSizeInBits() / 32;
4981 SDValue Vec = DAG.getAllOnesConstant(dl, MVT::getVectorVT(MVT::i32, NumElts));
4982 return DAG.getBitcast(VT, Vec);
4983}
4984
4985// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
4986static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
4987 switch (Opc) {
4988 case ISD::SHL:
4989 case X86ISD::VSHL:
4990 case X86ISD::VSHLI:
4991 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
4992 case ISD::SRL:
4993 case X86ISD::VSRL:
4994 case X86ISD::VSRLI:
4995 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
4996 case ISD::SRA:
4997 case X86ISD::VSRA:
4998 case X86ISD::VSRAI:
4999 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
5000 }
5001 llvm_unreachable("Unknown target vector shift node");
5002}
5003
5004/// Handle vector element shifts where the shift amount is a constant.
5005/// Takes immediate version of shift as input.
5006static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
5007 SDValue SrcOp, uint64_t ShiftAmt,
5008 SelectionDAG &DAG) {
5009 assert(
5010 (Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) &&
5011 "Unknown target vector shift-by-constant node");
5012
5013 // Bitcast the source vector to the output type, this is mainly necessary for
5014 // vXi8/vXi64 shifts.
5015 SrcOp = DAG.getBitcast(VT, SrcOp);
5016
5017 // Fold this packed shift into its first operand if ShiftAmt is 0.
5018 if (ShiftAmt == 0)
5019 return SrcOp;
5020
5021 // Check for ShiftAmt >= element width
5022 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5023 if (ShiftAmt >= EltSizeInBits) {
5024 if (Opc == X86ISD::VSRAI)
5025 ShiftAmt = EltSizeInBits - 1;
5026 else
5027 return DAG.getConstant(0, dl, VT);
5028 }
5029
5030 // Fold this packed vector shift into a build vector if SrcOp is a
5031 // vector of Constants or UNDEFs.
5033 unsigned ShiftOpc;
5034 switch (Opc) {
5035 default:
5036 llvm_unreachable("Unknown opcode!");
5037 case X86ISD::VSHLI:
5038 ShiftOpc = ISD::SHL;
5039 break;
5040 case X86ISD::VSRLI:
5041 ShiftOpc = ISD::SRL;
5042 break;
5043 case X86ISD::VSRAI:
5044 ShiftOpc = ISD::SRA;
5045 break;
5046 }
5047
5048 SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
5049 if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
5050 return C;
5051 }
5052
5053 return DAG.getNode(Opc, dl, VT, SrcOp,
5054 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
5055}
5056
5057/// Handle vector element shifts by a splat shift amount
5058static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
5059 SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
5060 const X86Subtarget &Subtarget,
5061 SelectionDAG &DAG) {
5062 MVT AmtVT = ShAmt.getSimpleValueType();
5063 assert(AmtVT.isVector() && "Vector shift type mismatch");
5064 assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
5065 "Illegal vector splat index");
5066
5067 // Move the splat element to the bottom element.
5068 if (ShAmtIdx != 0) {
5069 SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
5070 Mask[0] = ShAmtIdx;
5071 ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
5072 }
5073
5074 // Peek through any zext node if we can get back to a 128-bit source.
5075 if (AmtVT.getScalarSizeInBits() == 64 &&
5076 (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
5078 ShAmt.getOperand(0).getValueType().isSimple() &&
5079 ShAmt.getOperand(0).getValueType().is128BitVector()) {
5080 ShAmt = ShAmt.getOperand(0);
5081 AmtVT = ShAmt.getSimpleValueType();
5082 }
5083
5084 // See if we can mask off the upper elements using the existing source node.
5085 // The shift uses the entire lower 64-bits of the amount vector, so no need to
5086 // do this for vXi64 types.
5087 bool IsMasked = false;
5088 if (AmtVT.getScalarSizeInBits() < 64) {
5089 if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
5090 ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5091 // If the shift amount has come from a scalar, then zero-extend the scalar
5092 // before moving to the vector.
5093 ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
5094 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
5095 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
5096 AmtVT = MVT::v4i32;
5097 IsMasked = true;
5098 } else if (ShAmt.getOpcode() == ISD::AND) {
5099 // See if the shift amount is already masked (e.g. for rotation modulo),
5100 // then we can zero-extend it by setting all the other mask elements to
5101 // zero.
5102 SmallVector<SDValue> MaskElts(
5103 AmtVT.getVectorNumElements(),
5104 DAG.getConstant(0, dl, AmtVT.getScalarType()));
5105 MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
5106 SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
5107 if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
5108 {ShAmt.getOperand(1), Mask}))) {
5109 ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
5110 IsMasked = true;
5111 }
5112 }
5113 }
5114
5115 // Extract if the shift amount vector is larger than 128-bits.
5116 if (AmtVT.getSizeInBits() > 128) {
5117 ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
5118 AmtVT = ShAmt.getSimpleValueType();
5119 }
5120
5121 // Zero-extend bottom element to v2i64 vector type, either by extension or
5122 // shuffle masking.
5123 if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
5124 if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
5125 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
5126 ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
5127 } else if (Subtarget.hasSSE41()) {
5128 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
5129 MVT::v2i64, ShAmt);
5130 } else {
5131 SDValue ByteShift = DAG.getTargetConstant(
5132 (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
5133 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
5134 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5135 ByteShift);
5136 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
5137 ByteShift);
5138 }
5139 }
5140
5141 // Change opcode to non-immediate version.
5143
5144 // The return type has to be a 128-bit type with the same element
5145 // type as the input type.
5146 MVT EltVT = VT.getVectorElementType();
5147 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
5148
5149 ShAmt = DAG.getBitcast(ShVT, ShAmt);
5150 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
5151}
5152
5153static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
5154 SDValue In, SelectionDAG &DAG) {
5155 EVT InVT = In.getValueType();
5156 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
5157
5158 // Canonicalize Opcode to general extension version.
5159 switch (Opcode) {
5160 case ISD::ANY_EXTEND:
5162 Opcode = ISD::ANY_EXTEND;
5163 break;
5164 case ISD::SIGN_EXTEND:
5166 Opcode = ISD::SIGN_EXTEND;
5167 break;
5168 case ISD::ZERO_EXTEND:
5170 Opcode = ISD::ZERO_EXTEND;
5171 break;
5172 default:
5173 llvm_unreachable("Unknown extension opcode");
5174 }
5175
5176 // For 256-bit vectors, we only need the lower (128-bit) input half.
5177 // For 512-bit vectors, we only need the lower input half or quarter.
5178 if (InVT.getSizeInBits() > 128) {
5179 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
5180 "Expected VTs to be the same size!");
5181 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5182 In = extractSubVector(In, 0, DAG, DL,
5183 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
5184 InVT = In.getValueType();
5185 }
5186
5187 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
5188 Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
5189
5190 return DAG.getNode(Opcode, DL, VT, In);
5191}
5192
5193// Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
5195 SDValue Mask, SelectionDAG &DAG) {
5196 LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
5197 RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
5198 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5199}
5200
5202 bool Lo, bool Unary) {
5203 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
5204 "Illegal vector type to unpack");
5205 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5206 int NumElts = VT.getVectorNumElements();
5207 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
5208 for (int i = 0; i < NumElts; ++i) {
5209 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
5210 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
5211 Pos += (Unary ? 0 : NumElts * (i % 2));
5212 Pos += (Lo ? 0 : NumEltsInLane / 2);
5213 Mask.push_back(Pos);
5214 }
5215}
5216
5217/// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
5218/// imposed by AVX and specific to the unary pattern. Example:
5219/// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
5220/// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
5222 bool Lo) {
5223 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5224 int NumElts = VT.getVectorNumElements();
5225 for (int i = 0; i < NumElts; ++i) {
5226 int Pos = i / 2;
5227 Pos += (Lo ? 0 : NumElts / 2);
5228 Mask.push_back(Pos);
5229 }
5230}
5231
5232// Attempt to constant fold, else just create a VECTOR_SHUFFLE.
5233static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
5234 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
5235 if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
5237 SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
5238 for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
5239 int M = Mask[I];
5240 if (M < 0)
5241 continue;
5242 SDValue V = (M < NumElts) ? V1 : V2;
5243 if (V.isUndef())
5244 continue;
5245 Ops[I] = V.getOperand(M % NumElts);
5246 }
5247 return DAG.getBuildVector(VT, dl, Ops);
5248 }
5249
5250 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5251}
5252
5253/// Returns a vector_shuffle node for an unpackl operation.
5254static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5255 SDValue V1, SDValue V2) {
5257 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5258 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5259}
5260
5261/// Returns a vector_shuffle node for an unpackh operation.
5262static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
5263 SDValue V1, SDValue V2) {
5265 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5266 return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
5267}
5268
5269/// Returns a node that packs the LHS + RHS nodes together at half width.
5270/// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
5271/// TODO: Add subvector splitting if/when we have a need for it.
5272static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5273 const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
5274 bool PackHiHalf = false) {
5275 MVT OpVT = LHS.getSimpleValueType();
5276 unsigned EltSizeInBits = VT.getScalarSizeInBits();
5277 bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
5278 assert(OpVT == RHS.getSimpleValueType() &&
5279 VT.getSizeInBits() == OpVT.getSizeInBits() &&
5280 (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
5281 "Unexpected PACK operand types");
5282 assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
5283 "Unexpected PACK result type");
5284
5285 // Rely on vector shuffles for vXi64 -> vXi32 packing.
5286 if (EltSizeInBits == 32) {
5287 SmallVector<int> PackMask;
5288 int Offset = PackHiHalf ? 1 : 0;
5289 int NumElts = VT.getVectorNumElements();
5290 for (int I = 0; I != NumElts; I += 4) {
5291 PackMask.push_back(I + Offset);
5292 PackMask.push_back(I + Offset + 2);
5293 PackMask.push_back(I + Offset + NumElts);
5294 PackMask.push_back(I + Offset + NumElts + 2);
5295 }
5296 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
5297 DAG.getBitcast(VT, RHS), PackMask);
5298 }
5299
5300 // See if we already have sufficient leading bits for PACKSS/PACKUS.
5301 if (!PackHiHalf) {
5302 if (UsePackUS &&
5303 DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
5304 DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
5305 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5306
5307 if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
5308 DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
5309 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5310 }
5311
5312 // Fallback to sign/zero extending the requested half and pack.
5313 SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
5314 if (UsePackUS) {
5315 if (PackHiHalf) {
5316 LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
5317 RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
5318 } else {
5319 SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
5320 LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
5321 RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
5322 };
5323 return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
5324 };
5325
5326 if (!PackHiHalf) {
5327 LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
5328 RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
5329 }
5330 LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
5331 RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
5332 return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
5333}
5334
5335/// Return a vector_shuffle of the specified vector of zero or undef vector.
5336/// This produces a shuffle where the low element of V2 is swizzled into the
5337/// zero/undef vector, landing at element Idx.
5338/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5340 bool IsZero,
5341 const X86Subtarget &Subtarget,
5342 SelectionDAG &DAG) {
5343 MVT VT = V2.getSimpleValueType();
5344 SDValue V1 = IsZero
5345 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5346 int NumElems = VT.getVectorNumElements();
5347 SmallVector<int, 16> MaskVec(NumElems);
5348 for (int i = 0; i != NumElems; ++i)
5349 // If this is the insertion idx, put the low elt of V2 here.
5350 MaskVec[i] = (i == Idx) ? NumElems : i;
5351 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5352}
5353
5355 if (Ptr.getOpcode() == X86ISD::Wrapper ||
5356 Ptr.getOpcode() == X86ISD::WrapperRIP)
5357 Ptr = Ptr.getOperand(0);
5358 return dyn_cast<ConstantPoolSDNode>(Ptr);
5359}
5360
5361// TODO: Add support for non-zero offsets.
5364 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5365 return nullptr;
5366 return CNode->getConstVal();
5367}
5368
5370 if (!Load || !ISD::isNormalLoad(Load))
5371 return nullptr;
5372 return getTargetConstantFromBasePtr(Load->getBasePtr());
5373}
5374
5379
5380const Constant *
5382 assert(LD && "Unexpected null LoadSDNode");
5383 return getTargetConstantFromNode(LD);
5384}
5385
5387 // Do not fold (vselect not(C), X, 0s) to (vselect C, Os, X)
5388 SDValue Cond = N->getOperand(0);
5389 SDValue RHS = N->getOperand(2);
5390 EVT CondVT = Cond.getValueType();
5391 return N->getOpcode() == ISD::VSELECT && Subtarget.hasAVX512() &&
5392 CondVT.getVectorElementType() == MVT::i1 &&
5393 ISD::isBuildVectorAllZeros(RHS.getNode());
5394}
5395
5396// Extract raw constant bits from constant pools.
5397static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5398 APInt &UndefElts,
5399 SmallVectorImpl<APInt> &EltBits,
5400 bool AllowWholeUndefs = true,
5401 bool AllowPartialUndefs = false) {
5402 assert(EltBits.empty() && "Expected an empty EltBits vector");
5403
5405
5406 EVT VT = Op.getValueType();
5407 unsigned SizeInBits = VT.getSizeInBits();
5408 unsigned NumElts = SizeInBits / EltSizeInBits;
5409
5410 // Can't split constant.
5411 if ((SizeInBits % EltSizeInBits) != 0)
5412 return false;
5413
5414 // Bitcast a source array of element bits to the target size.
5415 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5416 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5417 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5418 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
5419 "Constant bit sizes don't match");
5420
5421 // Don't split if we don't allow undef bits.
5422 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5423 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5424 return false;
5425
5426 // If we're already the right size, don't bother bitcasting.
5427 if (NumSrcElts == NumElts) {
5428 UndefElts = UndefSrcElts;
5429 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5430 return true;
5431 }
5432
5433 // Extract all the undef/constant element data and pack into single bitsets.
5434 APInt UndefBits(SizeInBits, 0);
5435 APInt MaskBits(SizeInBits, 0);
5436
5437 for (unsigned i = 0; i != NumSrcElts; ++i) {
5438 unsigned BitOffset = i * SrcEltSizeInBits;
5439 if (UndefSrcElts[i])
5440 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5441 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5442 }
5443
5444 // Split the undef/constant single bitset data into the target elements.
5445 UndefElts = APInt(NumElts, 0);
5446 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5447
5448 for (unsigned i = 0; i != NumElts; ++i) {
5449 unsigned BitOffset = i * EltSizeInBits;
5450 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5451
5452 // Only treat an element as UNDEF if all bits are UNDEF.
5453 if (UndefEltBits.isAllOnes()) {
5454 if (!AllowWholeUndefs)
5455 return false;
5456 UndefElts.setBit(i);
5457 continue;
5458 }
5459
5460 // If only some bits are UNDEF then treat them as zero (or bail if not
5461 // supported).
5462 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5463 return false;
5464
5465 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
5466 }
5467 return true;
5468 };
5469
5470 // Collect constant bits and insert into mask/undef bit masks.
5471 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5472 unsigned UndefBitIndex) {
5473 if (!Cst)
5474 return false;
5475 if (isa<UndefValue>(Cst)) {
5476 Undefs.setBit(UndefBitIndex);
5477 return true;
5478 }
5479 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5480 Mask = APInt::getSplat(CInt->getType()->getPrimitiveSizeInBits(),
5481 CInt->getValue());
5482 return true;
5483 }
5484 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5485 Mask = APInt::getSplat(CFP->getType()->getPrimitiveSizeInBits(),
5486 CFP->getValueAPF().bitcastToAPInt());
5487 return true;
5488 }
5489 if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
5490 Type *Ty = CDS->getType();
5491 Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
5492 Type *EltTy = CDS->getElementType();
5493 bool IsInteger = EltTy->isIntegerTy();
5494 bool IsFP =
5495 EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
5496 if (!IsInteger && !IsFP)
5497 return false;
5498 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
5499 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
5500 if (IsInteger)
5501 Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
5502 else
5503 Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
5504 I * EltBits);
5505 return true;
5506 }
5507 return false;
5508 };
5509
5510 // Handle UNDEFs.
5511 if (Op.isUndef()) {
5512 APInt UndefSrcElts = APInt::getAllOnes(NumElts);
5513 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5514 return CastBitData(UndefSrcElts, SrcEltBits);
5515 }
5516
5517 // Extract scalar constant bits.
5518 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5519 APInt UndefSrcElts = APInt::getZero(1);
5520 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5521 return CastBitData(UndefSrcElts, SrcEltBits);
5522 }
5523 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5524 APInt UndefSrcElts = APInt::getZero(1);
5525 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5526 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5527 return CastBitData(UndefSrcElts, SrcEltBits);
5528 }
5529
5530 // Extract constant bits from build vector.
5531 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5532 BitVector Undefs;
5533 SmallVector<APInt> SrcEltBits;
5534 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5535 if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
5536 APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
5537 for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
5538 if (Undefs[I])
5539 UndefSrcElts.setBit(I);
5540 return CastBitData(UndefSrcElts, SrcEltBits);
5541 }
5542 }
5543
5544 // Extract constant bits from constant pool vector.
5545 if (auto *Cst = getTargetConstantFromNode(Op)) {
5546 Type *CstTy = Cst->getType();
5547 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5548 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5549 return false;
5550
5551 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5552 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5553 if ((SizeInBits % SrcEltSizeInBits) != 0)
5554 return false;
5555
5556 APInt UndefSrcElts(NumSrcElts, 0);
5557 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5558 for (unsigned i = 0; i != NumSrcElts; ++i)
5559 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5560 UndefSrcElts, i))
5561 return false;
5562
5563 return CastBitData(UndefSrcElts, SrcEltBits);
5564 }
5565
5566 // Extract constant bits from a broadcasted constant pool scalar.
5567 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
5568 EltSizeInBits <= VT.getScalarSizeInBits()) {
5569 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5570 if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
5571 return false;
5572
5573 SDValue Ptr = MemIntr->getBasePtr();
5574 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
5575 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5576 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5577
5578 APInt UndefSrcElts(NumSrcElts, 0);
5579 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5580 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
5581 if (UndefSrcElts[0])
5582 UndefSrcElts.setBits(0, NumSrcElts);
5583 if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
5584 SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
5585 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5586 return CastBitData(UndefSrcElts, SrcEltBits);
5587 }
5588 }
5589 }
5590
5591 // Extract constant bits from a subvector broadcast.
5592 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
5593 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
5594 SDValue Ptr = MemIntr->getBasePtr();
5595 // The source constant may be larger than the subvector broadcast,
5596 // ensure we extract the correct subvector constants.
5597 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
5598 Type *CstTy = Cst->getType();
5599 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5600 unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
5601 if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
5602 (SizeInBits % SubVecSizeInBits) != 0)
5603 return false;
5604 unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
5605 unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
5606 unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
5607 APInt UndefSubElts(NumSubElts, 0);
5608 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
5609 APInt(CstEltSizeInBits, 0));
5610 for (unsigned i = 0; i != NumSubElts; ++i) {
5611 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
5612 UndefSubElts, i))
5613 return false;
5614 for (unsigned j = 1; j != NumSubVecs; ++j)
5615 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
5616 }
5617 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
5618 UndefSubElts);
5619 return CastBitData(UndefSubElts, SubEltBits);
5620 }
5621 }
5622
5623 // Extract a rematerialized scalar constant insertion.
5624 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5625 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5626 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5627 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5628 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5629
5630 APInt UndefSrcElts(NumSrcElts, 0);
5631 SmallVector<APInt, 64> SrcEltBits;
5632 const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
5633 SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
5634 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5635 return CastBitData(UndefSrcElts, SrcEltBits);
5636 }
5637
5638 // Insert constant bits from a base and sub vector sources.
5639 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
5640 // If bitcasts to larger elements we might lose track of undefs - don't
5641 // allow any to be safe.
5642 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5643 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
5644
5645 APInt UndefSrcElts, UndefSubElts;
5646 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
5647 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
5648 UndefSubElts, EltSubBits,
5649 AllowWholeUndefs && AllowUndefs,
5650 AllowPartialUndefs && AllowUndefs) &&
5651 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
5652 UndefSrcElts, EltSrcBits,
5653 AllowWholeUndefs && AllowUndefs,
5654 AllowPartialUndefs && AllowUndefs)) {
5655 unsigned BaseIdx = Op.getConstantOperandVal(2);
5656 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
5657 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
5658 EltSrcBits[BaseIdx + i] = EltSubBits[i];
5659 return CastBitData(UndefSrcElts, EltSrcBits);
5660 }
5661 }
5662
5663 // Extract constant bits from a subvector's source.
5664 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5665 getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits, UndefElts,
5666 EltBits, AllowWholeUndefs,
5667 AllowPartialUndefs)) {
5668 EVT SrcVT = Op.getOperand(0).getValueType();
5669 unsigned NumSrcElts = SrcVT.getSizeInBits() / EltSizeInBits;
5670 unsigned NumSubElts = VT.getSizeInBits() / EltSizeInBits;
5671 unsigned BaseOfs = Op.getConstantOperandVal(1) * VT.getScalarSizeInBits();
5672 unsigned BaseIdx = BaseOfs / EltSizeInBits;
5673 assert((SrcVT.getSizeInBits() % EltSizeInBits) == 0 &&
5674 (VT.getSizeInBits() % EltSizeInBits) == 0 &&
5675 (BaseOfs % EltSizeInBits) == 0 && "Bad subvector index");
5676
5677 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5678 if ((BaseIdx + NumSubElts) != NumSrcElts)
5679 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5680 if (BaseIdx != 0)
5681 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5682 return true;
5683 }
5684
5685 // Extract constant bits from shuffle node sources.
5686 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5687 // TODO - support shuffle through bitcasts.
5688 if (EltSizeInBits != VT.getScalarSizeInBits())
5689 return false;
5690
5691 ArrayRef<int> Mask = SVN->getMask();
5692 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5693 llvm::any_of(Mask, [](int M) { return M < 0; }))
5694 return false;
5695
5696 APInt UndefElts0, UndefElts1;
5697 SmallVector<APInt, 32> EltBits0, EltBits1;
5698 if (isAnyInRange(Mask, 0, NumElts) &&
5699 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5700 UndefElts0, EltBits0, AllowWholeUndefs,
5701 AllowPartialUndefs))
5702 return false;
5703 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
5704 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
5705 UndefElts1, EltBits1, AllowWholeUndefs,
5706 AllowPartialUndefs))
5707 return false;
5708
5709 UndefElts = APInt::getZero(NumElts);
5710 for (int i = 0; i != (int)NumElts; ++i) {
5711 int M = Mask[i];
5712 if (M < 0) {
5713 UndefElts.setBit(i);
5714 EltBits.push_back(APInt::getZero(EltSizeInBits));
5715 } else if (M < (int)NumElts) {
5716 if (UndefElts0[M])
5717 UndefElts.setBit(i);
5718 EltBits.push_back(EltBits0[M]);
5719 } else {
5720 if (UndefElts1[M - NumElts])
5721 UndefElts.setBit(i);
5722 EltBits.push_back(EltBits1[M - NumElts]);
5723 }
5724 }
5725 return true;
5726 }
5727
5728 return false;
5729}
5730
5731namespace llvm {
5732namespace X86 {
5733bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
5734 APInt UndefElts;
5735 SmallVector<APInt, 16> EltBits;
5737 Op, Op.getScalarValueSizeInBits(), UndefElts, EltBits,
5738 /*AllowWholeUndefs*/ true, AllowPartialUndefs)) {
5739 int SplatIndex = -1;
5740 for (int i = 0, e = EltBits.size(); i != e; ++i) {
5741 if (UndefElts[i])
5742 continue;
5743 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
5744 SplatIndex = -1;
5745 break;
5746 }
5747 SplatIndex = i;
5748 }
5749 if (0 <= SplatIndex) {
5750 SplatVal = EltBits[SplatIndex];
5751 return true;
5752 }
5753 }
5754
5755 return false;
5756}
5757
5758int getRoundingModeX86(unsigned RM) {
5759 switch (static_cast<::llvm::RoundingMode>(RM)) {
5760 // clang-format off
5761 case ::llvm::RoundingMode::NearestTiesToEven: return X86::rmToNearest;
5762 case ::llvm::RoundingMode::TowardNegative: return X86::rmDownward;
5763 case ::llvm::RoundingMode::TowardPositive: return X86::rmUpward;
5764 case ::llvm::RoundingMode::TowardZero: return X86::rmTowardZero;
5765 default: return X86::rmInvalid;
5766 // clang-format on
5767 }
5768}
5769
5770} // namespace X86
5771} // namespace llvm
5772
5774 unsigned MaskEltSizeInBits,
5776 APInt &UndefElts) {
5777 // Extract the raw target constant bits.
5778 SmallVector<APInt, 64> EltBits;
5779 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5780 EltBits, /* AllowWholeUndefs */ true,
5781 /* AllowPartialUndefs */ false))
5782 return false;
5783
5784 // Insert the extracted elements into the mask.
5785 for (const APInt &Elt : EltBits)
5786 RawMask.push_back(Elt.getZExtValue());
5787
5788 return true;
5789}
5790
5791static bool isConstantPowerOf2(SDValue V, unsigned EltSizeInBIts,
5792 bool AllowUndefs) {
5793 APInt UndefElts;
5794 SmallVector<APInt, 64> EltBits;
5795 if (!getTargetConstantBitsFromNode(V, EltSizeInBIts, UndefElts, EltBits,
5796 /*AllowWholeUndefs*/ AllowUndefs,
5797 /*AllowPartialUndefs*/ false))
5798 return false;
5799
5800 bool IsPow2OrUndef = true;
5801 for (unsigned I = 0, E = EltBits.size(); I != E; ++I)
5802 IsPow2OrUndef &= UndefElts[I] || EltBits[I].isPowerOf2();
5803 return IsPow2OrUndef;
5804}
5805
5806// Helper to attempt to return a cheaper, bit-inverted version of \p V.
5808 // TODO: don't always ignore oneuse constraints.
5809 V = peekThroughBitcasts(V);
5810 EVT VT = V.getValueType();
5811
5812 // Match not(xor X, -1) -> X.
5813 if (V.getOpcode() == ISD::XOR &&
5814 (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
5815 isAllOnesConstant(V.getOperand(1))))
5816 return V.getOperand(0);
5817
5818 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
5819 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5820 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5821 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5822 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5823 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
5824 V.getOperand(1));
5825 }
5826 }
5827
5828 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
5829 if (V.getOpcode() == X86ISD::PCMPGT &&
5830 !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
5831 !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
5832 V.getOperand(0).hasOneUse()) {
5833 APInt UndefElts;
5834 SmallVector<APInt> EltBits;
5835 if (getTargetConstantBitsFromNode(V.getOperand(0),
5836 V.getScalarValueSizeInBits(), UndefElts,
5837 EltBits) &&
5838 !ISD::isBuildVectorOfConstantSDNodes(V.getOperand(1).getNode())) {
5839 // Don't fold min_signed_value -> (min_signed_value - 1)
5840 bool MinSigned = false;
5841 for (APInt &Elt : EltBits) {
5842 MinSigned |= Elt.isMinSignedValue();
5843 Elt -= 1;
5844 }
5845 if (!MinSigned) {
5846 SDLoc DL(V);
5847 MVT VT = V.getSimpleValueType();
5848 return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5849 getConstVector(EltBits, UndefElts, VT, DAG, DL));
5850 }
5851 }
5852 }
5853
5854 // Match not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
5856 if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5857 for (SDValue &CatOp : CatOps) {
5858 SDValue NotCat = IsNOT(CatOp, DAG);
5859 if (!NotCat)
5860 return SDValue();
5861 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5862 }
5863 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), VT, CatOps);
5864 }
5865
5866 // Match not(or(not(X),not(Y))) -> and(X, Y).
5867 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
5868 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
5869 // TODO: Handle cases with single NOT operand -> ANDNP
5870 if (SDValue Op1 = IsNOT(V.getOperand(1), DAG))
5871 if (SDValue Op0 = IsNOT(V.getOperand(0), DAG))
5872 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
5873 DAG.getBitcast(VT, Op1));
5874 }
5875
5876 return SDValue();
5877}
5878
5879/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5880/// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5881/// Note: This ignores saturation, so inputs must be checked first.
5883 bool Unary, unsigned NumStages = 1) {
5884 assert(Mask.empty() && "Expected an empty shuffle mask vector");
5885 unsigned NumElts = VT.getVectorNumElements();
5886 unsigned NumLanes = VT.getSizeInBits() / 128;
5887 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5888 unsigned Offset = Unary ? 0 : NumElts;
5889 unsigned Repetitions = 1u << (NumStages - 1);
5890 unsigned Increment = 1u << NumStages;
5891 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5892
5893 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5894 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5895 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5896 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5897 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5898 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5899 }
5900 }
5901}
5902
5903// Split the demanded elts of a PACKSS/PACKUS node between its operands.
5904static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5905 APInt &DemandedLHS, APInt &DemandedRHS) {
5906 int NumLanes = VT.getSizeInBits() / 128;
5907 int NumElts = DemandedElts.getBitWidth();
5908 int NumInnerElts = NumElts / 2;
5909 int NumEltsPerLane = NumElts / NumLanes;
5910 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5911
5912 DemandedLHS = APInt::getZero(NumInnerElts);
5913 DemandedRHS = APInt::getZero(NumInnerElts);
5914
5915 // Map DemandedElts to the packed operands.
5916 for (int Lane = 0; Lane != NumLanes; ++Lane) {
5917 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5918 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
5919 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
5920 if (DemandedElts[OuterIdx])
5921 DemandedLHS.setBit(InnerIdx);
5922 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
5923 DemandedRHS.setBit(InnerIdx);
5924 }
5925 }
5926}
5927
5928// Split the demanded elts of a HADD/HSUB node between its operands.
5929static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
5930 APInt &DemandedLHS, APInt &DemandedRHS) {
5932 DemandedLHS, DemandedRHS);
5933 DemandedLHS |= DemandedLHS << 1;
5934 DemandedRHS |= DemandedRHS << 1;
5935}
5936
5937/// Calculates the shuffle mask corresponding to the target-specific opcode.
5938/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5939/// operands in \p Ops, and returns true.
5940/// Sets \p IsUnary to true if only one source is used. Note that this will set
5941/// IsUnary for shuffles which use a single input multiple times, and in those
5942/// cases it will adjust the mask to only have indices within that single input.
5943/// It is an error to call this with non-empty Mask/Ops vectors.
5944static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
5946 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5947 if (!isTargetShuffle(N.getOpcode()))
5948 return false;
5949
5950 MVT VT = N.getSimpleValueType();
5951 unsigned NumElems = VT.getVectorNumElements();
5952 unsigned MaskEltSize = VT.getScalarSizeInBits();
5954 APInt RawUndefs;
5955 uint64_t ImmN;
5956
5957 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
5958 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
5959
5960 IsUnary = false;
5961 bool IsFakeUnary = false;
5962 switch (N.getOpcode()) {
5963 case X86ISD::BLENDI:
5964 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5965 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5966 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5967 DecodeBLENDMask(NumElems, ImmN, Mask);
5968 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5969 break;
5970 case X86ISD::SHUFP:
5971 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5972 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5973 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5974 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
5975 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5976 break;
5977 case X86ISD::INSERTPS:
5978 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5979 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5980 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
5981 DecodeINSERTPSMask(ImmN, Mask, /*SrcIsMem=*/false);
5982 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
5983 break;
5984 case X86ISD::EXTRQI:
5985 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5986 if (isa<ConstantSDNode>(N.getOperand(1)) &&
5987 isa<ConstantSDNode>(N.getOperand(2))) {
5988 int BitLen = N.getConstantOperandVal(1);
5989 int BitIdx = N.getConstantOperandVal(2);
5990 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
5991 IsUnary = true;
5992 }
5993 break;
5994 case X86ISD::INSERTQI:
5995 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
5996 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
5997 if (isa<ConstantSDNode>(N.getOperand(2)) &&
5998 isa<ConstantSDNode>(N.getOperand(3))) {
5999 int BitLen = N.getConstantOperandVal(2);
6000 int BitIdx = N.getConstantOperandVal(3);
6001 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6002 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6003 }
6004 break;
6005 case X86ISD::UNPCKH:
6006 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6007 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6008 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6009 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6010 break;
6011 case X86ISD::UNPCKL:
6012 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6013 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6014 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6015 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6016 break;
6017 case X86ISD::MOVHLPS:
6018 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6019 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6020 DecodeMOVHLPSMask(NumElems, Mask);
6021 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6022 break;
6023 case X86ISD::MOVLHPS:
6024 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6025 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6026 DecodeMOVLHPSMask(NumElems, Mask);
6027 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6028 break;
6029 case X86ISD::VALIGN:
6030 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
6031 "Only 32-bit and 64-bit elements are supported!");
6032 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6033 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6034 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6035 DecodeVALIGNMask(NumElems, ImmN, Mask);
6036 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6037 Ops.push_back(N.getOperand(1));
6038 Ops.push_back(N.getOperand(0));
6039 break;
6040 case X86ISD::PALIGNR:
6041 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6042 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6043 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6044 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6045 DecodePALIGNRMask(NumElems, ImmN, Mask);
6046 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6047 Ops.push_back(N.getOperand(1));
6048 Ops.push_back(N.getOperand(0));
6049 break;
6050 case X86ISD::VSHLDQ:
6051 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6052 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6053 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6054 DecodePSLLDQMask(NumElems, ImmN, Mask);
6055 IsUnary = true;
6056 break;
6057 case X86ISD::VSRLDQ:
6058 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6059 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6060 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6061 DecodePSRLDQMask(NumElems, ImmN, Mask);
6062 IsUnary = true;
6063 break;
6064 case X86ISD::PSHUFD:
6065 case X86ISD::VPERMILPI:
6066 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6067 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6068 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
6069 IsUnary = true;
6070 break;
6071 case X86ISD::PSHUFHW:
6072 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6073 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6074 DecodePSHUFHWMask(NumElems, ImmN, Mask);
6075 IsUnary = true;
6076 break;
6077 case X86ISD::PSHUFLW:
6078 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6079 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6080 DecodePSHUFLWMask(NumElems, ImmN, Mask);
6081 IsUnary = true;
6082 break;
6083 case X86ISD::VZEXT_MOVL:
6084 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6085 DecodeZeroMoveLowMask(NumElems, Mask);
6086 IsUnary = true;
6087 break;
6088 case X86ISD::VBROADCAST:
6089 // We only decode broadcasts of same-sized vectors, peeking through to
6090 // extracted subvectors is likely to cause hasOneUse issues with
6091 // SimplifyDemandedBits etc.
6092 if (N.getOperand(0).getValueType() == VT) {
6093 DecodeVectorBroadcast(NumElems, Mask);
6094 IsUnary = true;
6095 break;
6096 }
6097 return false;
6098 case X86ISD::VPERMILPV: {
6099 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6100 IsUnary = true;
6101 SDValue MaskNode = N.getOperand(1);
6102 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6103 RawUndefs)) {
6104 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6105 break;
6106 }
6107 return false;
6108 }
6109 case X86ISD::PSHUFB: {
6110 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6111 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6112 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6113 IsUnary = true;
6114 SDValue MaskNode = N.getOperand(1);
6115 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6116 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6117 break;
6118 }
6119 return false;
6120 }
6121 case X86ISD::VPERMI:
6122 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6123 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6124 DecodeVPERMMask(NumElems, ImmN, Mask);
6125 IsUnary = true;
6126 break;
6127 case X86ISD::MOVSS:
6128 case X86ISD::MOVSD:
6129 case X86ISD::MOVSH:
6130 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6131 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6132 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6133 break;
6134 case X86ISD::VPERM2X128:
6135 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6136 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6137 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6138 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
6139 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6140 break;
6141 case X86ISD::SHUF128:
6142 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6143 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6144 ImmN = N.getConstantOperandVal(N.getNumOperands() - 1);
6145 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
6146 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6147 break;
6148 case X86ISD::MOVSLDUP:
6149 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6150 DecodeMOVSLDUPMask(NumElems, Mask);
6151 IsUnary = true;
6152 break;
6153 case X86ISD::MOVSHDUP:
6154 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6155 DecodeMOVSHDUPMask(NumElems, Mask);
6156 IsUnary = true;
6157 break;
6158 case X86ISD::MOVDDUP:
6159 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6160 DecodeMOVDDUPMask(NumElems, Mask);
6161 IsUnary = true;
6162 break;
6163 case X86ISD::VPERMIL2: {
6164 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6165 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6166 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6167 SDValue MaskNode = N.getOperand(2);
6168 SDValue CtrlNode = N.getOperand(3);
6169 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6170 unsigned CtrlImm = CtrlOp->getZExtValue();
6171 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6172 RawUndefs)) {
6173 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6174 Mask);
6175 break;
6176 }
6177 }
6178 return false;
6179 }
6180 case X86ISD::VPPERM: {
6181 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6182 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6183 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(1);
6184 SDValue MaskNode = N.getOperand(2);
6185 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6186 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6187 break;
6188 }
6189 return false;
6190 }
6191 case X86ISD::VPERMV: {
6192 assert(N.getOperand(1).getValueType() == VT && "Unexpected value type");
6193 IsUnary = true;
6194 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6195 Ops.push_back(N.getOperand(1));
6196 SDValue MaskNode = N.getOperand(0);
6197 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6198 RawUndefs)) {
6199 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6200 break;
6201 }
6202 return false;
6203 }
6204 case X86ISD::VPERMV3: {
6205 assert(N.getOperand(0).getValueType() == VT && "Unexpected value type");
6206 assert(N.getOperand(2).getValueType() == VT && "Unexpected value type");
6207 IsUnary = IsFakeUnary = N.getOperand(0) == N.getOperand(2);
6208 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6209 Ops.push_back(N.getOperand(0));
6210 Ops.push_back(N.getOperand(2));
6211 SDValue MaskNode = N.getOperand(1);
6212 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6213 RawUndefs)) {
6214 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6215 break;
6216 }
6217 return false;
6218 }
6219 case X86ISD::COMPRESS: {
6220 SDValue CmpVec = N.getOperand(0);
6221 SDValue PassThru = N.getOperand(1);
6222 SDValue CmpMask = N.getOperand(2);
6223 APInt UndefElts;
6224 SmallVector<APInt> EltBits;
6225 if (!getTargetConstantBitsFromNode(CmpMask, 1, UndefElts, EltBits))
6226 return false;
6227 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6228 "Illegal compression mask");
6229 for (unsigned I = 0; I != NumElems; ++I) {
6230 if (!EltBits[I].isZero())
6231 Mask.push_back(I);
6232 }
6233 while (Mask.size() != NumElems) {
6234 Mask.push_back(NumElems + Mask.size());
6235 }
6236 Ops.push_back(CmpVec);
6237 Ops.push_back(PassThru);
6238 return true;
6239 }
6240 case X86ISD::EXPAND: {
6241 SDValue ExpVec = N.getOperand(0);
6242 SDValue PassThru = N.getOperand(1);
6243 SDValue ExpMask = N.getOperand(2);
6244 APInt UndefElts;
6245 SmallVector<APInt> EltBits;
6246 if (!getTargetConstantBitsFromNode(ExpMask, 1, UndefElts, EltBits))
6247 return false;
6248 assert(UndefElts.getBitWidth() == NumElems && EltBits.size() == NumElems &&
6249 "Illegal expansion mask");
6250 unsigned ExpIndex = 0;
6251 for (unsigned I = 0; I != NumElems; ++I) {
6252 if (EltBits[I].isZero())
6253 Mask.push_back(I + NumElems);
6254 else
6255 Mask.push_back(ExpIndex++);
6256 }
6257 Ops.push_back(ExpVec);
6258 Ops.push_back(PassThru);
6259 return true;
6260 }
6261 default:
6262 llvm_unreachable("unknown target shuffle node");
6263 }
6264
6265 // Empty mask indicates the decode failed.
6266 if (Mask.empty())
6267 return false;
6268
6269 // Check if we're getting a shuffle mask with zero'd elements.
6270 if (!AllowSentinelZero && isAnyZero(Mask))
6271 return false;
6272
6273 // If we have a fake unary shuffle, the shuffle mask is spread across two
6274 // inputs that are actually the same node. Re-map the mask to always point
6275 // into the first input.
6276 if (IsFakeUnary)
6277 for (int &M : Mask)
6278 if (M >= (int)Mask.size())
6279 M -= Mask.size();
6280
6281 // If we didn't already add operands in the opcode-specific code, default to
6282 // adding 1 or 2 operands starting at 0.
6283 if (Ops.empty()) {
6284 Ops.push_back(N.getOperand(0));
6285 if (!IsUnary || IsFakeUnary)
6286 Ops.push_back(N.getOperand(1));
6287 }
6288
6289 return true;
6290}
6291
6292// Wrapper for getTargetShuffleMask with InUnary;
6293static bool getTargetShuffleMask(SDValue N, bool AllowSentinelZero,
6295 SmallVectorImpl<int> &Mask) {
6296 bool IsUnary;
6297 return getTargetShuffleMask(N, AllowSentinelZero, Ops, Mask, IsUnary);
6298}
6299
6300/// Compute whether each element of a shuffle is zeroable.
6301///
6302/// A "zeroable" vector shuffle element is one which can be lowered to zero.
6303/// Either it is an undef element in the shuffle mask, the element of the input
6304/// referenced is undef, or the element of the input referenced is known to be
6305/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6306/// as many lanes with this technique as possible to simplify the remaining
6307/// shuffle.
6309 SDValue V1, SDValue V2,
6310 APInt &KnownUndef, APInt &KnownZero) {
6311 int Size = Mask.size();
6312 KnownUndef = KnownZero = APInt::getZero(Size);
6313
6315 V2 = peekThroughBitcasts(V2);
6316
6317 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6318 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6319
6320 int VectorSizeInBits = V1.getValueSizeInBits();
6321 int ScalarSizeInBits = VectorSizeInBits / Size;
6322 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
6323
6324 for (int i = 0; i < Size; ++i) {
6325 int M = Mask[i];
6326 // Handle the easy cases.
6327 if (M < 0) {
6328 KnownUndef.setBit(i);
6329 continue;
6330 }
6331 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6332 KnownZero.setBit(i);
6333 continue;
6334 }
6335
6336 // Determine shuffle input and normalize the mask.
6337 SDValue V = M < Size ? V1 : V2;
6338 M %= Size;
6339
6340 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
6341 if (V.getOpcode() != ISD::BUILD_VECTOR)
6342 continue;
6343
6344 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
6345 // the (larger) source element must be UNDEF/ZERO.
6346 if ((Size % V.getNumOperands()) == 0) {
6347 int Scale = Size / V->getNumOperands();
6348 SDValue Op = V.getOperand(M / Scale);
6349 if (Op.isUndef())
6350 KnownUndef.setBit(i);
6351 if (X86::isZeroNode(Op))
6352 KnownZero.setBit(i);
6353 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
6354 APInt Val = Cst->getAPIntValue();
6355 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6356 if (Val == 0)
6357 KnownZero.setBit(i);
6358 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6359 APInt Val = Cst->getValueAPF().bitcastToAPInt();
6360 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
6361 if (Val == 0)
6362 KnownZero.setBit(i);
6363 }
6364 continue;
6365 }
6366
6367 // If the BUILD_VECTOR has more elements then all the (smaller) source
6368 // elements must be UNDEF or ZERO.
6369 if ((V.getNumOperands() % Size) == 0) {
6370 int Scale = V->getNumOperands() / Size;
6371 bool AllUndef = true;
6372 bool AllZero = true;
6373 for (int j = 0; j < Scale; ++j) {
6374 SDValue Op = V.getOperand((M * Scale) + j);
6375 AllUndef &= Op.isUndef();
6376 AllZero &= X86::isZeroNode(Op);
6377 }
6378 if (AllUndef)
6379 KnownUndef.setBit(i);
6380 if (AllZero)
6381 KnownZero.setBit(i);
6382 continue;
6383 }
6384 }
6385}
6386
6387/// Decode a target shuffle mask and inputs and see if any values are
6388/// known to be undef or zero from their inputs.
6389/// Returns true if the target shuffle mask was decoded.
6390/// FIXME: Merge this with computeZeroableShuffleElements?
6393 APInt &KnownUndef, APInt &KnownZero) {
6394 bool IsUnary;
6395 if (!isTargetShuffle(N.getOpcode()))
6396 return false;
6397
6398 MVT VT = N.getSimpleValueType();
6399 if (!getTargetShuffleMask(N, true, Ops, Mask, IsUnary))
6400 return false;
6401
6402 int Size = Mask.size();
6403 SDValue V1 = Ops[0];
6404 SDValue V2 = IsUnary ? V1 : Ops[1];
6405 KnownUndef = KnownZero = APInt::getZero(Size);
6406
6408 V2 = peekThroughBitcasts(V2);
6409
6410 assert((VT.getSizeInBits() % Size) == 0 &&
6411 "Illegal split of shuffle value type");
6412 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
6413
6414 // Extract known constant input data.
6415 APInt UndefSrcElts[2];
6416 SmallVector<APInt, 32> SrcEltBits[2];
6417 bool IsSrcConstant[2] = {
6418 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6419 SrcEltBits[0], /*AllowWholeUndefs*/ true,
6420 /*AllowPartialUndefs*/ false),
6421 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6422 SrcEltBits[1], /*AllowWholeUndefs*/ true,
6423 /*AllowPartialUndefs*/ false)};
6424
6425 for (int i = 0; i < Size; ++i) {
6426 int M = Mask[i];
6427
6428 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6429 if (M < 0) {
6430 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
6431 if (SM_SentinelUndef == M)
6432 KnownUndef.setBit(i);
6433 if (SM_SentinelZero == M)
6434 KnownZero.setBit(i);
6435 continue;
6436 }
6437
6438 // Determine shuffle input and normalize the mask.
6439 unsigned SrcIdx = M / Size;
6440 SDValue V = M < Size ? V1 : V2;
6441 M %= Size;
6442
6443 // We are referencing an UNDEF input.
6444 if (V.isUndef()) {
6445 KnownUndef.setBit(i);
6446 continue;
6447 }
6448
6449 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6450 // TODO: We currently only set UNDEF for integer types - floats use the same
6451 // registers as vectors and many of the scalar folded loads rely on the
6452 // SCALAR_TO_VECTOR pattern.
6453 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6454 (Size % V.getValueType().getVectorNumElements()) == 0) {
6455 int Scale = Size / V.getValueType().getVectorNumElements();
6456 int Idx = M / Scale;
6457 if (Idx != 0 && !VT.isFloatingPoint())
6458 KnownUndef.setBit(i);
6459 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6460 KnownZero.setBit(i);
6461 continue;
6462 }
6463
6464 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
6465 // base vectors.
6466 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
6467 SDValue Vec = V.getOperand(0);
6468 int NumVecElts = Vec.getValueType().getVectorNumElements();
6469 if (Vec.isUndef() && Size == NumVecElts) {
6470 int Idx = V.getConstantOperandVal(2);
6471 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
6472 if (M < Idx || (Idx + NumSubElts) <= M)
6473 KnownUndef.setBit(i);
6474 }
6475 continue;
6476 }
6477
6478 // Attempt to extract from the source's constant bits.
6479 if (IsSrcConstant[SrcIdx]) {
6480 if (UndefSrcElts[SrcIdx][M])
6481 KnownUndef.setBit(i);
6482 else if (SrcEltBits[SrcIdx][M] == 0)
6483 KnownZero.setBit(i);
6484 }
6485 }
6486
6487 assert(VT.getVectorNumElements() == (unsigned)Size &&
6488 "Different mask size from vector size!");
6489 return true;
6490}
6491
6492// Replace target shuffle mask elements with known undef/zero sentinels.
6494 const APInt &KnownUndef,
6495 const APInt &KnownZero,
6496 bool ResolveKnownZeros= true) {
6497 unsigned NumElts = Mask.size();
6498 assert(KnownUndef.getBitWidth() == NumElts &&
6499 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
6500
6501 for (unsigned i = 0; i != NumElts; ++i) {
6502 if (KnownUndef[i])
6503 Mask[i] = SM_SentinelUndef;
6504 else if (ResolveKnownZeros && KnownZero[i])
6505 Mask[i] = SM_SentinelZero;
6506 }
6507}
6508
6509// Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
6511 APInt &KnownUndef,
6512 APInt &KnownZero) {
6513 unsigned NumElts = Mask.size();
6514 KnownUndef = KnownZero = APInt::getZero(NumElts);
6515
6516 for (unsigned i = 0; i != NumElts; ++i) {
6517 int M = Mask[i];
6518 if (SM_SentinelUndef == M)
6519 KnownUndef.setBit(i);
6520 if (SM_SentinelZero == M)
6521 KnownZero.setBit(i);
6522 }
6523}
6524
6525// Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
6527 SDValue Cond, bool IsBLENDV = false) {
6528 EVT CondVT = Cond.getValueType();
6529 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
6530 unsigned NumElts = CondVT.getVectorNumElements();
6531
6532 APInt UndefElts;
6533 SmallVector<APInt, 32> EltBits;
6534 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
6535 /*AllowWholeUndefs*/ true,
6536 /*AllowPartialUndefs*/ false))
6537 return false;
6538
6539 Mask.resize(NumElts, SM_SentinelUndef);
6540
6541 for (int i = 0; i != (int)NumElts; ++i) {
6542 Mask[i] = i;
6543 // Arbitrarily choose from the 2nd operand if the select condition element
6544 // is undef.
6545 // TODO: Can we do better by matching patterns such as even/odd?
6546 if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
6547 (IsBLENDV && EltBits[i].isNonNegative()))
6548 Mask[i] += NumElts;
6549 }
6550
6551 return true;
6552}
6553
6554// Forward declaration (for getFauxShuffleMask recursive check).
6555static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6558 const SelectionDAG &DAG, unsigned Depth,
6559 bool ResolveKnownElts);
6560
6561// Attempt to decode ops that could be represented as a shuffle mask.
6562// The decoded shuffle mask may contain a different number of elements to the
6563// destination value type.
6564// TODO: Merge into getTargetShuffleInputs()
6565static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
6568 const SelectionDAG &DAG, unsigned Depth,
6569 bool ResolveKnownElts) {
6570 Mask.clear();
6571 Ops.clear();
6572
6573 MVT VT = N.getSimpleValueType();
6574 unsigned NumElts = VT.getVectorNumElements();
6575 unsigned NumSizeInBits = VT.getSizeInBits();
6576 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6577 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
6578 return false;
6579 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
6580 unsigned NumSizeInBytes = NumSizeInBits / 8;
6581 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6582
6583 unsigned Opcode = N.getOpcode();
6584 switch (Opcode) {
6585 case ISD::VECTOR_SHUFFLE: {
6586 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6587 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6588 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6589 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6590 Ops.push_back(N.getOperand(0));
6591 Ops.push_back(N.getOperand(1));
6592 return true;
6593 }
6594 return false;
6595 }
6596 case ISD::AND:
6597 case X86ISD::ANDNP: {
6598 // Attempt to decode as a per-byte mask.
6599 APInt UndefElts;
6600 SmallVector<APInt, 32> EltBits;
6601 SDValue N0 = N.getOperand(0);
6602 SDValue N1 = N.getOperand(1);
6603 bool IsAndN = (X86ISD::ANDNP == Opcode);
6604 uint64_t ZeroMask = IsAndN ? 255 : 0;
6605 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits,
6606 /*AllowWholeUndefs*/ false,
6607 /*AllowPartialUndefs*/ false))
6608 return false;
6609 // We can't assume an undef src element gives an undef dst - the other src
6610 // might be zero.
6611 assert(UndefElts.isZero() && "Unexpected UNDEF element in AND/ANDNP mask");
6612 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6613 const APInt &ByteBits = EltBits[i];
6614 if (ByteBits != 0 && ByteBits != 255)
6615 return false;
6616 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6617 }
6618 Ops.push_back(IsAndN ? N1 : N0);
6619 return true;
6620 }
6621 case ISD::OR: {
6622 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6623 // is a valid shuffle index.
6624 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
6625 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
6626 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6627 return false;
6628
6629 SmallVector<int, 64> SrcMask0, SrcMask1;
6630 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6633 if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
6634 Depth + 1, true) ||
6635 !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
6636 Depth + 1, true))
6637 return false;
6638
6639 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6640 SmallVector<int, 64> Mask0, Mask1;
6641 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6642 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6643 for (int i = 0; i != (int)MaskSize; ++i) {
6644 // NOTE: Don't handle demanded SM_SentinelUndef, as we can end up in
6645 // infinite loops converting between OR and BLEND shuffles due to
6646 // canWidenShuffleElements merging away undef elements, meaning we
6647 // fail to recognise the OR as the undef element isn't known zero.
6648 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6649 Mask.push_back(SM_SentinelZero);
6650 else if (Mask1[i] == SM_SentinelZero)
6651 Mask.push_back(i);
6652 else if (Mask0[i] == SM_SentinelZero)
6653 Mask.push_back(i + MaskSize);
6654 else if (MaskSize == NumElts && !DemandedElts[i])
6655 Mask.push_back(SM_SentinelUndef);
6656 else
6657 return false;
6658 }
6659 Ops.push_back(N.getOperand(0));
6660 Ops.push_back(N.getOperand(1));
6661 return true;
6662 }
6663 case ISD::CONCAT_VECTORS: {
6664 // Limit this to vXi64 vector cases to make the most of cross lane shuffles.
6665 unsigned NumSubElts = N.getOperand(0).getValueType().getVectorNumElements();
6666 if (NumBitsPerElt == 64) {
6667 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
6668 for (unsigned M = 0; M != NumSubElts; ++M)
6669 Mask.push_back((I * NumElts) + M);
6670 Ops.push_back(N.getOperand(I));
6671 }
6672 return true;
6673 }
6674 return false;
6675 }
6676 case ISD::INSERT_SUBVECTOR: {
6677 SDValue Src = N.getOperand(0);
6678 SDValue Sub = N.getOperand(1);
6679 EVT SubVT = Sub.getValueType();
6680 unsigned NumSubElts = SubVT.getVectorNumElements();
6681 uint64_t InsertIdx = N.getConstantOperandVal(2);
6682 // Subvector isn't demanded - just return the base vector.
6683 if (DemandedElts.extractBits(NumSubElts, InsertIdx) == 0) {
6684 Mask.resize(NumElts);
6685 std::iota(Mask.begin(), Mask.end(), 0);
6686 Ops.push_back(Src);
6687 return true;
6688 }
6689 // Handle CONCAT(SUB0, SUB1).
6690 // Limit to vXi64/splat cases to make the most of cross lane shuffles.
6691 if (Depth > 0 && InsertIdx == NumSubElts && NumElts == (2 * NumSubElts) &&
6692 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6693 Src.getOperand(0).isUndef() &&
6694 Src.getOperand(1).getValueType() == SubVT &&
6695 Src.getConstantOperandVal(2) == 0 &&
6696 (NumBitsPerElt == 64 || Src.getOperand(1) == Sub) &&
6697 SDNode::areOnlyUsersOf({N.getNode(), Src.getNode()}, Sub.getNode())) {
6698 Mask.resize(NumElts);
6699 std::iota(Mask.begin(), Mask.begin() + NumSubElts, 0);
6700 std::iota(Mask.begin() + NumSubElts, Mask.end(), NumElts);
6701 Ops.push_back(Src.getOperand(1));
6702 Ops.push_back(Sub);
6703 return true;
6704 }
6705 // Handle INSERT_SUBVECTOR(UNDEF, SUB, IDX) iff IDX != 0
6706 if (InsertIdx != 0 && Src.isUndef() &&
6708 Mask.assign(NumElts, SM_SentinelUndef);
6709 std::iota(Mask.begin() + InsertIdx, Mask.begin() + InsertIdx + NumSubElts,
6710 0);
6711 Ops.push_back(Sub);
6712 return true;
6713 }
6714 if (!N->isOnlyUserOf(Sub.getNode()))
6715 return false;
6716
6717 SmallVector<int, 64> SubMask;
6718 SmallVector<SDValue, 2> SubInputs;
6720 EVT SubSrcVT = SubSrc.getValueType();
6721 if (!SubSrcVT.isVector())
6722 return false;
6723
6724 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
6725 if (SubSrc.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6726 SubSrc.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6727 uint64_t ExtractIdx = SubSrc.getConstantOperandVal(1);
6728 SDValue SubSrcSrc = SubSrc.getOperand(0);
6729 unsigned NumSubSrcSrcElts =
6730 SubSrcSrc.getValueType().getVectorNumElements();
6731 unsigned MaxElts = std::max(NumElts, NumSubSrcSrcElts);
6732 assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcSrcElts) == 0 &&
6733 "Subvector valuetype mismatch");
6734 InsertIdx *= (MaxElts / NumElts);
6735 ExtractIdx *= (MaxElts / NumSubSrcSrcElts);
6736 NumSubElts *= (MaxElts / NumElts);
6737 bool SrcIsUndef = Src.isUndef();
6738 for (int i = 0; i != (int)MaxElts; ++i)
6739 Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
6740 for (int i = 0; i != (int)NumSubElts; ++i)
6741 Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
6742 if (!SrcIsUndef)
6743 Ops.push_back(Src);
6744 Ops.push_back(SubSrcSrc);
6745 return true;
6746 }
6747
6748 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6749 APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
6750 if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
6751 Depth + 1, ResolveKnownElts))
6752 return false;
6753
6754 // Subvector shuffle inputs must not be larger than the subvector.
6755 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
6756 return SubVT.getFixedSizeInBits() <
6757 SubInput.getValueSizeInBits().getFixedValue();
6758 }))
6759 return false;
6760
6761 if (SubMask.size() != NumSubElts) {
6762 assert(((SubMask.size() % NumSubElts) == 0 ||
6763 (NumSubElts % SubMask.size()) == 0) &&
6764 "Illegal submask scale");
6765 if ((NumSubElts % SubMask.size()) == 0) {
6766 int Scale = NumSubElts / SubMask.size();
6767 SmallVector<int, 64> ScaledSubMask;
6768 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
6769 SubMask = ScaledSubMask;
6770 } else {
6771 int Scale = SubMask.size() / NumSubElts;
6772 NumSubElts = SubMask.size();
6773 NumElts *= Scale;
6774 InsertIdx *= Scale;
6775 }
6776 }
6777 Ops.push_back(Src);
6778 Ops.append(SubInputs.begin(), SubInputs.end());
6779 if (ISD::isBuildVectorAllZeros(Src.getNode()))
6780 Mask.append(NumElts, SM_SentinelZero);
6781 else
6782 for (int i = 0; i != (int)NumElts; ++i)
6783 Mask.push_back(i);
6784 for (int i = 0; i != (int)NumSubElts; ++i) {
6785 int M = SubMask[i];
6786 if (0 <= M) {
6787 int InputIdx = M / NumSubElts;
6788 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6789 }
6790 Mask[i + InsertIdx] = M;
6791 }
6792 return true;
6793 }
6794 case X86ISD::PINSRB:
6795 case X86ISD::PINSRW:
6798 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
6799 // vector, for matching src/dst vector types.
6800 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
6801
6802 unsigned DstIdx = 0;
6803 if (Opcode != ISD::SCALAR_TO_VECTOR) {
6804 // Check we have an in-range constant insertion index.
6805 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6806 N.getConstantOperandAPInt(2).uge(NumElts))
6807 return false;
6808 DstIdx = N.getConstantOperandVal(2);
6809
6810 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
6811 if (X86::isZeroNode(Scl)) {
6812 Ops.push_back(N.getOperand(0));
6813 for (unsigned i = 0; i != NumElts; ++i)
6814 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
6815 return true;
6816 }
6817 }
6818
6819 // Peek through trunc/aext/zext/bitcast.
6820 // TODO: aext shouldn't require SM_SentinelZero padding.
6821 // TODO: handle shift of scalars.
6822 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
6823 while (Scl.getOpcode() == ISD::TRUNCATE ||
6824 Scl.getOpcode() == ISD::ANY_EXTEND ||
6825 Scl.getOpcode() == ISD::ZERO_EXTEND ||
6826 (Scl.getOpcode() == ISD::BITCAST &&
6829 Scl = Scl.getOperand(0);
6830 MinBitsPerElt =
6831 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
6832 }
6833 if ((MinBitsPerElt % 8) != 0)
6834 return false;
6835
6836 // Attempt to find the source vector the scalar was extracted from.
6837 SDValue SrcExtract;
6838 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
6839 Scl.getOpcode() == X86ISD::PEXTRW ||
6840 Scl.getOpcode() == X86ISD::PEXTRB) &&
6841 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
6842 SrcExtract = Scl;
6843 }
6844 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6845 return false;
6846
6847 SDValue SrcVec = SrcExtract.getOperand(0);
6848 EVT SrcVT = SrcVec.getValueType();
6849 if (!SrcVT.getScalarType().isByteSized())
6850 return false;
6851 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6852 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
6853 unsigned DstByte = DstIdx * NumBytesPerElt;
6854 MinBitsPerElt =
6855 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
6856
6857 // Create 'identity' byte level shuffle mask and then add inserted bytes.
6858 if (Opcode == ISD::SCALAR_TO_VECTOR) {
6859 Ops.push_back(SrcVec);
6860 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6861 } else {
6862 Ops.push_back(SrcVec);
6863 Ops.push_back(N.getOperand(0));
6864 for (int i = 0; i != (int)NumSizeInBytes; ++i)
6865 Mask.push_back(NumSizeInBytes + i);
6866 }
6867
6868 unsigned MinBytesPerElts = MinBitsPerElt / 8;
6869 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
6870 for (unsigned i = 0; i != MinBytesPerElts; ++i)
6871 Mask[DstByte + i] = SrcByte + i;
6872 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
6873 Mask[DstByte + i] = SM_SentinelZero;
6874 return true;
6875 }
6876 case X86ISD::PACKSS:
6877 case X86ISD::PACKUS: {
6878 SDValue N0 = N.getOperand(0);
6879 SDValue N1 = N.getOperand(1);
6880 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
6881 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
6882 "Unexpected input value type");
6883
6884 APInt EltsLHS, EltsRHS;
6885 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
6886
6887 // If we know input saturation won't happen (or we don't care for particular
6888 // lanes), we can treat this as a truncation shuffle.
6889 bool Offset0 = false, Offset1 = false;
6890 if (Opcode == X86ISD::PACKSS) {
6891 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6892 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
6893 (!(N1.isUndef() || EltsRHS.isZero()) &&
6894 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
6895 return false;
6896 // We can't easily fold ASHR into a shuffle, but if it was feeding a
6897 // PACKSS then it was likely being used for sign-extension for a
6898 // truncation, so just peek through and adjust the mask accordingly.
6899 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
6900 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
6901 Offset0 = true;
6902 N0 = N0.getOperand(0);
6903 }
6904 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
6905 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
6906 Offset1 = true;
6907 N1 = N1.getOperand(0);
6908 }
6909 } else {
6910 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6911 if ((!(N0.isUndef() || EltsLHS.isZero()) &&
6912 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
6913 (!(N1.isUndef() || EltsRHS.isZero()) &&
6914 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
6915 return false;
6916 }
6917
6918 bool IsUnary = (N0 == N1);
6919
6920 Ops.push_back(N0);
6921 if (!IsUnary)
6922 Ops.push_back(N1);
6923
6924 createPackShuffleMask(VT, Mask, IsUnary);
6925
6926 if (Offset0 || Offset1) {
6927 for (int &M : Mask)
6928 if ((Offset0 && isInRange(M, 0, NumElts)) ||
6929 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
6930 ++M;
6931 }
6932 return true;
6933 }
6934 case ISD::VSELECT:
6935 case X86ISD::BLENDV: {
6936 SDValue Cond = N.getOperand(0);
6937 if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
6938 Ops.push_back(N.getOperand(1));
6939 Ops.push_back(N.getOperand(2));
6940 return true;
6941 }
6942 return false;
6943 }
6944 case X86ISD::VTRUNC: {
6945 SDValue Src = N.getOperand(0);
6946 EVT SrcVT = Src.getValueType();
6947 if (SrcVT.getSizeInBits() != NumSizeInBits)
6948 return false;
6949 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6950 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6951 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
6952 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
6953 for (unsigned i = 0; i != NumSrcElts; ++i)
6954 Mask.push_back(i * Scale);
6955 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
6956 Ops.push_back(Src);
6957 return true;
6958 }
6959 case ISD::SHL:
6960 case ISD::SRL: {
6961 APInt UndefElts;
6962 SmallVector<APInt, 32> EltBits;
6963 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
6964 UndefElts, EltBits,
6965 /*AllowWholeUndefs*/ true,
6966 /*AllowPartialUndefs*/ false))
6967 return false;
6968
6969 // We can only decode 'whole byte' bit shifts as shuffles.
6970 for (unsigned I = 0; I != NumElts; ++I)
6971 if (DemandedElts[I] && !UndefElts[I] &&
6972 (EltBits[I].urem(8) != 0 || EltBits[I].uge(NumBitsPerElt)))
6973 return false;
6974
6975 Mask.append(NumSizeInBytes, SM_SentinelUndef);
6976 Ops.push_back(N.getOperand(0));
6977
6978 for (unsigned I = 0; I != NumElts; ++I) {
6979 if (!DemandedElts[I] || UndefElts[I])
6980 continue;
6981 unsigned ByteShift = EltBits[I].getZExtValue() / 8;
6982 unsigned Lo = I * NumBytesPerElt;
6983 unsigned Hi = Lo + NumBytesPerElt;
6984 // Clear mask to all zeros and insert the shifted byte indices.
6985 std::fill(Mask.begin() + Lo, Mask.begin() + Hi, SM_SentinelZero);
6986 if (ISD::SHL == Opcode)
6987 std::iota(Mask.begin() + Lo + ByteShift, Mask.begin() + Hi, Lo);
6988 else
6989 std::iota(Mask.begin() + Lo, Mask.begin() + Hi - ByteShift,
6990 Lo + ByteShift);
6991 }
6992 return true;
6993 }
6994 case X86ISD::VSHLI:
6995 case X86ISD::VSRLI: {
6996 uint64_t ShiftVal = N.getConstantOperandVal(1);
6997 // Out of range bit shifts are guaranteed to be zero.
6998 if (NumBitsPerElt <= ShiftVal) {
6999 Mask.append(NumElts, SM_SentinelZero);
7000 return true;
7001 }
7002
7003 // We can only decode 'whole byte' bit shifts as shuffles.
7004 if ((ShiftVal % 8) != 0)
7005 break;
7006
7007 uint64_t ByteShift = ShiftVal / 8;
7008 Ops.push_back(N.getOperand(0));
7009
7010 // Clear mask to all zeros and insert the shifted byte indices.
7011 Mask.append(NumSizeInBytes, SM_SentinelZero);
7012
7013 if (X86ISD::VSHLI == Opcode) {
7014 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7015 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7016 Mask[i + j] = i + j - ByteShift;
7017 } else {
7018 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7019 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7020 Mask[i + j - ByteShift] = i + j;
7021 }
7022 return true;
7023 }
7024 case ISD::ROTL:
7025 case ISD::ROTR: {
7026 APInt UndefElts;
7027 SmallVector<APInt, 32> EltBits;
7028 if (!getTargetConstantBitsFromNode(N.getOperand(1), NumBitsPerElt,
7029 UndefElts, EltBits,
7030 /*AllowWholeUndefs*/ true,
7031 /*AllowPartialUndefs*/ false))
7032 return false;
7033
7034 // We can only decode 'whole byte' bit rotates as shuffles.
7035 for (unsigned I = 0; I != NumElts; ++I)
7036 if (DemandedElts[I] && !UndefElts[I] &&
7037 (EltBits[I].urem(NumBitsPerElt) % 8) != 0)
7038 return false;
7039
7040 Ops.push_back(N.getOperand(0));
7041 for (unsigned I = 0; I != NumElts; ++I) {
7042 if (!DemandedElts[I] || UndefElts[I]) {
7043 Mask.append(NumBytesPerElt, SM_SentinelUndef);
7044 continue;
7045 }
7046 int Offset = EltBits[I].urem(NumBitsPerElt) / 8;
7047 Offset = (ISD::ROTL == Opcode ? NumBytesPerElt - Offset : Offset);
7048 int BaseIdx = I * NumBytesPerElt;
7049 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7050 Mask.push_back(BaseIdx + ((Offset + J) % NumBytesPerElt));
7051 }
7052 }
7053 return true;
7054 }
7055 case X86ISD::VROTLI:
7056 case X86ISD::VROTRI: {
7057 // We can only decode 'whole byte' bit rotates as shuffles.
7058 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7059 if ((RotateVal % 8) != 0)
7060 return false;
7061 Ops.push_back(N.getOperand(0));
7062 int Offset = RotateVal / 8;
7063 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7064 for (int i = 0; i != (int)NumElts; ++i) {
7065 int BaseIdx = i * NumBytesPerElt;
7066 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7067 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7068 }
7069 }
7070 return true;
7071 }
7072 case X86ISD::VSHLD:
7073 case X86ISD::VSHRD: {
7074 // We can only decode 'whole byte' bit funnel shifts as shuffles.
7075 uint64_t ShiftVal = N.getConstantOperandAPInt(2).urem(NumBitsPerElt);
7076 int Offset = ShiftVal / 8;
7077 if ((ShiftVal % 8) != 0 || Offset == 0)
7078 return false;
7079 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 1 : 0));
7080 Ops.push_back(N.getOperand(X86ISD::VSHRD == Opcode ? 0 : 1));
7081 Offset = X86ISD::VSHRD == Opcode ? (NumBytesPerElt - Offset) : Offset;
7082 for (int I = 0; I != (int)NumElts; ++I) {
7083 int BaseIdx = (I * NumBytesPerElt) - Offset;
7084 for (int J = 0; J != (int)NumBytesPerElt; ++J) {
7085 int MaskIdx = BaseIdx + J;
7086 MaskIdx += J < Offset ? (NumSizeInBytes + NumBytesPerElt) : 0;
7087 Mask.push_back(MaskIdx);
7088 }
7089 }
7090 return true;
7091 }
7092 case X86ISD::VBROADCAST: {
7093 SDValue Src = N.getOperand(0);
7094 if (!Src.getSimpleValueType().isVector()) {
7095 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7096 !isNullConstant(Src.getOperand(1)) ||
7097 Src.getOperand(0).getValueType().getScalarType() !=
7098 VT.getScalarType())
7099 return false;
7100 Src = Src.getOperand(0);
7101 }
7102 Ops.push_back(Src);
7103 Mask.append(NumElts, 0);
7104 return true;
7105 }
7107 SDValue Src = N.getOperand(0);
7108 EVT SrcVT = Src.getValueType();
7109 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7110
7111 // Extended source must be a simple vector.
7112 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7113 (NumBitsPerSrcElt % 8) != 0)
7114 return false;
7115
7116 // We can only handle all-signbits extensions.
7117 APInt DemandedSrcElts =
7118 DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
7119 if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
7120 return false;
7121
7122 assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
7123 unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
7124 for (unsigned I = 0; I != NumElts; ++I)
7125 Mask.append(Scale, I);
7126 Ops.push_back(Src);
7127 return true;
7128 }
7129 case ISD::ZERO_EXTEND:
7130 case ISD::ANY_EXTEND:
7133 SDValue Src = N.getOperand(0);
7134 EVT SrcVT = Src.getValueType();
7135
7136 // Extended source must be a simple vector.
7137 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7138 (SrcVT.getScalarSizeInBits() % 8) != 0)
7139 return false;
7140
7141 bool IsAnyExtend =
7142 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7143 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7144 IsAnyExtend, Mask);
7145 Ops.push_back(Src);
7146 return true;
7147 }
7148 }
7149
7150 return false;
7151}
7152
7153/// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7155 SmallVectorImpl<int> &Mask) {
7156 int MaskWidth = Mask.size();
7157 SmallVector<SDValue, 16> UsedInputs;
7158 for (int i = 0, e = Inputs.size(); i < e; ++i) {
7159 int lo = UsedInputs.size() * MaskWidth;
7160 int hi = lo + MaskWidth;
7161
7162 // Strip UNDEF input usage.
7163 if (Inputs[i].isUndef())
7164 for (int &M : Mask)
7165 if ((lo <= M) && (M < hi))
7166 M = SM_SentinelUndef;
7167
7168 // Check for unused inputs.
7169 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7170 for (int &M : Mask)
7171 if (lo <= M)
7172 M -= MaskWidth;
7173 continue;
7174 }
7175
7176 // Check for repeated inputs.
7177 bool IsRepeat = false;
7178 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7179 if (peekThroughBitcasts(UsedInputs[j]) != peekThroughBitcasts(Inputs[i]))
7180 continue;
7181 for (int &M : Mask)
7182 if (lo <= M)
7183 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7184 IsRepeat = true;
7185 break;
7186 }
7187 if (IsRepeat)
7188 continue;
7189
7190 UsedInputs.push_back(Inputs[i]);
7191 }
7192 Inputs = std::move(UsedInputs);
7193}
7194
7195/// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7196/// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7197/// Returns true if the target shuffle mask was decoded.
7198static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7201 APInt &KnownUndef, APInt &KnownZero,
7202 const SelectionDAG &DAG, unsigned Depth,
7203 bool ResolveKnownElts) {
7205 return false; // Limit search depth.
7206
7207 EVT VT = Op.getValueType();
7208 if (!VT.isSimple() || !VT.isVector())
7209 return false;
7210
7211 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7212 if (ResolveKnownElts)
7213 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7214 return true;
7215 }
7216 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7217 ResolveKnownElts)) {
7218 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7219 return true;
7220 }
7221 return false;
7222}
7223
7224static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7227 const SelectionDAG &DAG, unsigned Depth,
7228 bool ResolveKnownElts) {
7229 APInt KnownUndef, KnownZero;
7230 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7231 KnownZero, DAG, Depth, ResolveKnownElts);
7232}
7233
7236 const SelectionDAG &DAG, unsigned Depth = 0,
7237 bool ResolveKnownElts = true) {
7238 EVT VT = Op.getValueType();
7239 if (!VT.isSimple() || !VT.isVector())
7240 return false;
7241
7242 unsigned NumElts = Op.getValueType().getVectorNumElements();
7243 APInt DemandedElts = APInt::getAllOnes(NumElts);
7244 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
7245 ResolveKnownElts);
7246}
7247
7248// Attempt to create a scalar/subvector broadcast from the base MemSDNode.
7249static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
7250 EVT MemVT, MemSDNode *Mem, unsigned Offset,
7251 SelectionDAG &DAG) {
7252 assert((Opcode == X86ISD::VBROADCAST_LOAD ||
7253 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
7254 "Unknown broadcast load type");
7255
7256 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
7257 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
7258 return SDValue();
7259
7260 SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
7262 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7263 SDValue Ops[] = {Mem->getChain(), Ptr};
7264 SDValue BcstLd = DAG.getMemIntrinsicNode(
7265 Opcode, DL, Tys, Ops, MemVT,
7267 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
7268 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
7269 return BcstLd;
7270}
7271
7272/// Returns the scalar element that will make up the i'th
7273/// element of the result of the vector shuffle.
7274static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7275 SelectionDAG &DAG, unsigned Depth) {
7277 return SDValue(); // Limit search depth.
7278
7279 EVT VT = Op.getValueType();
7280 unsigned Opcode = Op.getOpcode();
7281 unsigned NumElems = VT.getVectorNumElements();
7282
7283 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7284 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7285 int Elt = SV->getMaskElt(Index);
7286
7287 if (Elt < 0)
7288 return DAG.getUNDEF(VT.getVectorElementType());
7289
7290 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7291 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7292 }
7293
7294 // Recurse into target specific vector shuffles to find scalars.
7295 if (isTargetShuffle(Opcode)) {
7296 MVT ShufVT = VT.getSimpleVT();
7297 MVT ShufSVT = ShufVT.getVectorElementType();
7298 int NumElems = (int)ShufVT.getVectorNumElements();
7299 SmallVector<int, 16> ShuffleMask;
7301 if (!getTargetShuffleMask(Op, true, ShuffleOps, ShuffleMask))
7302 return SDValue();
7303
7304 int Elt = ShuffleMask[Index];
7305 if (Elt == SM_SentinelZero)
7306 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7307 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7308 if (Elt == SM_SentinelUndef)
7309 return DAG.getUNDEF(ShufSVT);
7310
7311 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7312 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7313 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7314 }
7315
7316 // Recurse into insert_subvector base/sub vector to find scalars.
7317 if (Opcode == ISD::INSERT_SUBVECTOR) {
7318 SDValue Vec = Op.getOperand(0);
7319 SDValue Sub = Op.getOperand(1);
7320 uint64_t SubIdx = Op.getConstantOperandVal(2);
7321 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7322
7323 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7324 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7325 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7326 }
7327
7328 // Recurse into concat_vectors sub vector to find scalars.
7329 if (Opcode == ISD::CONCAT_VECTORS) {
7330 EVT SubVT = Op.getOperand(0).getValueType();
7331 unsigned NumSubElts = SubVT.getVectorNumElements();
7332 uint64_t SubIdx = Index / NumSubElts;
7333 uint64_t SubElt = Index % NumSubElts;
7334 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
7335 }
7336
7337 // Recurse into extract_subvector src vector to find scalars.
7338 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
7339 SDValue Src = Op.getOperand(0);
7340 uint64_t SrcIdx = Op.getConstantOperandVal(1);
7341 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
7342 }
7343
7344 // We only peek through bitcasts of the same vector width.
7345 if (Opcode == ISD::BITCAST) {
7346 SDValue Src = Op.getOperand(0);
7347 EVT SrcVT = Src.getValueType();
7348 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
7349 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
7350 return SDValue();
7351 }
7352
7353 // Actual nodes that may contain scalar elements
7354
7355 // For insert_vector_elt - either return the index matching scalar or recurse
7356 // into the base vector.
7357 if (Opcode == ISD::INSERT_VECTOR_ELT &&
7358 isa<ConstantSDNode>(Op.getOperand(2))) {
7359 if (Op.getConstantOperandAPInt(2) == Index)
7360 return Op.getOperand(1);
7361 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
7362 }
7363
7364 if (Opcode == ISD::SCALAR_TO_VECTOR)
7365 return (Index == 0) ? Op.getOperand(0)
7366 : DAG.getUNDEF(VT.getVectorElementType());
7367
7368 if (Opcode == ISD::BUILD_VECTOR)
7369 return Op.getOperand(Index);
7370
7371 return SDValue();
7372}
7373
7374// Use PINSRB/PINSRW/PINSRD to create a build vector.
7376 const APInt &NonZeroMask,
7377 unsigned NumNonZero, unsigned NumZero,
7378 SelectionDAG &DAG,
7379 const X86Subtarget &Subtarget) {
7380 MVT VT = Op.getSimpleValueType();
7381 unsigned NumElts = VT.getVectorNumElements();
7382 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7383 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7384 "Illegal vector insertion");
7385
7386 SDValue V;
7387 bool First = true;
7388
7389 for (unsigned i = 0; i < NumElts; ++i) {
7390 bool IsNonZero = NonZeroMask[i];
7391 if (!IsNonZero)
7392 continue;
7393
7394 // If the build vector contains zeros or our first insertion is not the
7395 // first index then insert into zero vector to break any register
7396 // dependency else use SCALAR_TO_VECTOR.
7397 if (First) {
7398 First = false;
7399 if (NumZero || 0 != i)
7400 V = getZeroVector(VT, Subtarget, DAG, DL);
7401 else {
7402 assert(0 == i && "Expected insertion into zero-index");
7403 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7404 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7405 V = DAG.getBitcast(VT, V);
7406 continue;
7407 }
7408 }
7409 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, V, Op.getOperand(i),
7410 DAG.getVectorIdxConstant(i, DL));
7411 }
7412
7413 return V;
7414}
7415
7416/// Custom lower build_vector of v16i8.
7418 const APInt &NonZeroMask,
7419 unsigned NumNonZero, unsigned NumZero,
7420 SelectionDAG &DAG,
7421 const X86Subtarget &Subtarget) {
7422 if (NumNonZero > 8 && !Subtarget.hasSSE41())
7423 return SDValue();
7424
7425 // SSE4.1 - use PINSRB to insert each byte directly.
7426 if (Subtarget.hasSSE41())
7427 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero,
7428 DAG, Subtarget);
7429
7430 SDValue V;
7431
7432 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7433 // If both the lowest 16-bits are non-zero, then convert to MOVD.
7434 if (!NonZeroMask.extractBits(2, 0).isZero() &&
7435 !NonZeroMask.extractBits(2, 2).isZero()) {
7436 for (unsigned I = 0; I != 4; ++I) {
7437 if (!NonZeroMask[I])
7438 continue;
7439 SDValue Elt = DAG.getZExtOrTrunc(Op.getOperand(I), DL, MVT::i32);
7440 if (I != 0)
7441 Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt,
7442 DAG.getConstant(I * 8, DL, MVT::i8));
7443 V = V ? DAG.getNode(ISD::OR, DL, MVT::i32, V, Elt) : Elt;
7444 }
7445 assert(V && "Failed to fold v16i8 vector to zero");
7446 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, V);
7447 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32, V);
7448 V = DAG.getBitcast(MVT::v8i16, V);
7449 }
7450 for (unsigned i = V ? 4 : 0; i < 16; i += 2) {
7451 bool ThisIsNonZero = NonZeroMask[i];
7452 bool NextIsNonZero = NonZeroMask[i + 1];
7453 if (!ThisIsNonZero && !NextIsNonZero)
7454 continue;
7455
7456 SDValue Elt;
7457 if (ThisIsNonZero) {
7458 if (NumZero || NextIsNonZero)
7459 Elt = DAG.getZExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7460 else
7461 Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), DL, MVT::i32);
7462 }
7463
7464 if (NextIsNonZero) {
7465 SDValue NextElt = Op.getOperand(i + 1);
7466 if (i == 0 && NumZero)
7467 NextElt = DAG.getZExtOrTrunc(NextElt, DL, MVT::i32);
7468 else
7469 NextElt = DAG.getAnyExtOrTrunc(NextElt, DL, MVT::i32);
7470 NextElt = DAG.getNode(ISD::SHL, DL, MVT::i32, NextElt,
7471 DAG.getConstant(8, DL, MVT::i8));
7472 if (ThisIsNonZero)
7473 Elt = DAG.getNode(ISD::OR, DL, MVT::i32, NextElt, Elt);
7474 else
7475 Elt = NextElt;
7476 }
7477
7478 // If our first insertion is not the first index or zeros are needed, then
7479 // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
7480 // elements undefined).
7481 if (!V) {
7482 if (i != 0 || NumZero)
7483 V = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7484 else {
7485 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32, Elt);
7486 V = DAG.getBitcast(MVT::v8i16, V);
7487 continue;
7488 }
7489 }
7490 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
7491 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16, V, Elt,
7492 DAG.getVectorIdxConstant(i / 2, DL));
7493 }
7494
7495 return DAG.getBitcast(MVT::v16i8, V);
7496}
7497
7498/// Custom lower build_vector of v8i16.
7500 const APInt &NonZeroMask,
7501 unsigned NumNonZero, unsigned NumZero,
7502 SelectionDAG &DAG,
7503 const X86Subtarget &Subtarget) {
7504 if (NumNonZero > 4 && !Subtarget.hasSSE41())
7505 return SDValue();
7506
7507 // Use PINSRW to insert each byte directly.
7508 return LowerBuildVectorAsInsert(Op, DL, NonZeroMask, NumNonZero, NumZero, DAG,
7509 Subtarget);
7510}
7511
7512/// Custom lower build_vector of v4i32 or v4f32.
7514 SelectionDAG &DAG,
7515 const X86Subtarget &Subtarget) {
7516 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
7517 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
7518 // Because we're creating a less complicated build vector here, we may enable
7519 // further folding of the MOVDDUP via shuffle transforms.
7520 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
7521 Op.getOperand(0) == Op.getOperand(2) &&
7522 Op.getOperand(1) == Op.getOperand(3) &&
7523 Op.getOperand(0) != Op.getOperand(1)) {
7524 MVT VT = Op.getSimpleValueType();
7525 MVT EltVT = VT.getVectorElementType();
7526 // Create a new build vector with the first 2 elements followed by undef
7527 // padding, bitcast to v2f64, duplicate, and bitcast back.
7528 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
7529 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
7530 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7531 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7532 return DAG.getBitcast(VT, Dup);
7533 }
7534
7535 // Find all zeroable elements.
7536 std::bitset<4> Zeroable, Undefs;
7537 for (int i = 0; i < 4; ++i) {
7538 SDValue Elt = Op.getOperand(i);
7539 Undefs[i] = Elt.isUndef();
7540 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7541 }
7542 assert(Zeroable.size() - Zeroable.count() > 1 &&
7543 "We expect at least two non-zero elements!");
7544
7545 // We only know how to deal with build_vector nodes where elements are either
7546 // zeroable or extract_vector_elt with constant index.
7547 SDValue FirstNonZero;
7548 unsigned FirstNonZeroIdx;
7549 for (unsigned i = 0; i < 4; ++i) {
7550 if (Zeroable[i])
7551 continue;
7552 SDValue Elt = Op.getOperand(i);
7553 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7555 return SDValue();
7556 // Make sure that this node is extracting from a 128-bit vector.
7557 MVT VT = Elt.getOperand(0).getSimpleValueType();
7558 if (!VT.is128BitVector())
7559 return SDValue();
7560 if (!FirstNonZero.getNode()) {
7561 FirstNonZero = Elt;
7562 FirstNonZeroIdx = i;
7563 }
7564 }
7565
7566 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
7567 SDValue V1 = FirstNonZero.getOperand(0);
7568 MVT VT = V1.getSimpleValueType();
7569
7570 // See if this build_vector can be lowered as a blend with zero.
7571 SDValue Elt;
7572 unsigned EltMaskIdx, EltIdx;
7573 int Mask[4];
7574 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7575 if (Zeroable[EltIdx]) {
7576 // The zero vector will be on the right hand side.
7577 Mask[EltIdx] = EltIdx+4;
7578 continue;
7579 }
7580
7581 Elt = Op->getOperand(EltIdx);
7582 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7583 EltMaskIdx = Elt.getConstantOperandVal(1);
7584 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7585 break;
7586 Mask[EltIdx] = EltIdx;
7587 }
7588
7589 if (EltIdx == 4) {
7590 // Let the shuffle legalizer deal with blend operations.
7591 SDValue VZeroOrUndef = (Zeroable == Undefs)
7592 ? DAG.getUNDEF(VT)
7593 : getZeroVector(VT, Subtarget, DAG, DL);
7594 if (V1.getSimpleValueType() != VT)
7595 V1 = DAG.getBitcast(VT, V1);
7596 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
7597 }
7598
7599 // See if we can lower this build_vector to a INSERTPS.
7600 if (!Subtarget.hasSSE41())
7601 return SDValue();
7602
7603 SDValue V2 = Elt.getOperand(0);
7604 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7605 V1 = SDValue();
7606
7607 bool CanFold = true;
7608 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7609 if (Zeroable[i])
7610 continue;
7611
7612 SDValue Current = Op->getOperand(i);
7613 SDValue SrcVector = Current->getOperand(0);
7614 if (!V1.getNode())
7615 V1 = SrcVector;
7616 CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
7617 }
7618
7619 if (!CanFold)
7620 return SDValue();
7621
7622 assert(V1.getNode() && "Expected at least two non-zero elements!");
7623 if (V1.getSimpleValueType() != MVT::v4f32)
7624 V1 = DAG.getBitcast(MVT::v4f32, V1);
7625 if (V2.getSimpleValueType() != MVT::v4f32)
7626 V2 = DAG.getBitcast(MVT::v4f32, V2);
7627
7628 // Ok, we can emit an INSERTPS instruction.
7629 unsigned ZMask = Zeroable.to_ulong();
7630
7631 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7632 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7633 SDValue Result =
7634 DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7635 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
7636 return DAG.getBitcast(VT, Result);
7637}
7638
7639/// Return a vector logical shift node.
7640static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7641 SelectionDAG &DAG, const TargetLowering &TLI,
7642 const SDLoc &dl) {
7643 assert(VT.is128BitVector() && "Unknown type for VShift");
7644 MVT ShVT = MVT::v16i8;
7645 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7646 SrcOp = DAG.getBitcast(ShVT, SrcOp);
7647 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
7648 SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
7649 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7650}
7651
7653 SelectionDAG &DAG) {
7654
7655 // Check if the scalar load can be widened into a vector load. And if
7656 // the address is "base + cst" see if the cst can be "absorbed" into
7657 // the shuffle mask.
7659 SDValue Ptr = LD->getBasePtr();
7660 if (!ISD::isNormalLoad(LD) || !LD->isSimple())
7661 return SDValue();
7662 EVT PVT = LD->getValueType(0);
7663 if (PVT != MVT::i32 && PVT != MVT::f32)
7664 return SDValue();
7665
7666 int FI = -1;
7667 int64_t Offset = 0;
7668 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7669 FI = FINode->getIndex();
7670 Offset = 0;
7671 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7673 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7675 Ptr = Ptr.getOperand(0);
7676 } else {
7677 return SDValue();
7678 }
7679
7680 // FIXME: 256-bit vector instructions don't require a strict alignment,
7681 // improve this code to support it better.
7682 Align RequiredAlign(VT.getSizeInBits() / 8);
7683 SDValue Chain = LD->getChain();
7684 // Make sure the stack object alignment is at least 16 or 32.
7686 MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
7687 if (!InferredAlign || *InferredAlign < RequiredAlign) {
7688 if (MFI.isFixedObjectIndex(FI)) {
7689 // Can't change the alignment. FIXME: It's possible to compute
7690 // the exact stack offset and reference FI + adjust offset instead.
7691 // If someone *really* cares about this. That's the way to implement it.
7692 return SDValue();
7693 } else {
7694 MFI.setObjectAlignment(FI, RequiredAlign);
7695 }
7696 }
7697
7698 // (Offset % 16 or 32) must be multiple of 4. Then address is then
7699 // Ptr + (Offset & ~15).
7700 if (Offset < 0)
7701 return SDValue();
7702 if ((Offset % RequiredAlign.value()) & 3)
7703 return SDValue();
7704 int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
7705 if (StartOffset) {
7706 SDLoc DL(Ptr);
7707 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7708 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7709 }
7710
7711 int EltNo = (Offset - StartOffset) >> 2;
7712 unsigned NumElems = VT.getVectorNumElements();
7713
7714 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
7715 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
7716 LD->getPointerInfo().getWithOffset(StartOffset));
7717
7718 SmallVector<int, 8> Mask(NumElems, EltNo);
7719
7720 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
7721 }
7722
7723 return SDValue();
7724}
7725
7726// Recurse to find a LoadSDNode source and the accumulated ByteOffest.
7727static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
7728 if (ISD::isNON_EXTLoad(Elt.getNode())) {
7729 auto *BaseLd = cast<LoadSDNode>(Elt);
7730 if (!BaseLd->isSimple())
7731 return false;
7732 Ld = BaseLd;
7733 ByteOffset = 0;
7734 return true;
7735 }
7736
7737 switch (Elt.getOpcode()) {
7738 case ISD::BITCAST:
7739 case ISD::TRUNCATE:
7741 return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
7742 case ISD::SRL:
7743 if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7744 uint64_t Amt = AmtC->getZExtValue();
7745 if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
7746 ByteOffset += Amt / 8;
7747 return true;
7748 }
7749 }
7750 break;
7752 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
7753 SDValue Src = Elt.getOperand(0);
7754 unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
7755 unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
7756 if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
7757 findEltLoadSrc(Src, Ld, ByteOffset)) {
7758 uint64_t Idx = IdxC->getZExtValue();
7759 ByteOffset += Idx * (SrcSizeInBits / 8);
7760 return true;
7761 }
7762 }
7763 break;
7764 }
7765
7766 return false;
7767}
7768
7769/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7770/// elements can be replaced by a single large load which has the same value as
7771/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7772///
7773/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
7775 const SDLoc &DL, SelectionDAG &DAG,
7776 const X86Subtarget &Subtarget,
7777 bool IsAfterLegalize,
7778 unsigned Depth = 0) {
7780 return SDValue(); // Limit search depth.
7781 if ((VT.getScalarSizeInBits() % 8) != 0)
7782 return SDValue();
7783
7784 // If all of these are oneuse frozen loads, then attempt to create a frozen
7785 // consecutive load.
7786 if (all_of(Elts, [](SDValue Elt) {
7787 return Elt.getOpcode() == ISD::FREEZE &&
7789 Elt.hasOneUse();
7790 })) {
7792 for (SDValue Elt : Elts)
7793 SrcElts.push_back(peekThroughFreeze(Elt));
7794 if (SDValue LD = EltsFromConsecutiveLoads(VT, SrcElts, DL, DAG, Subtarget,
7795 IsAfterLegalize, Depth + 1))
7796 return DAG.getFreeze(LD);
7797 return SDValue();
7798 }
7799
7800 unsigned NumElems = Elts.size();
7801
7802 int LastLoadedElt = -1;
7803 APInt LoadMask = APInt::getZero(NumElems);
7804 APInt ZeroMask = APInt::getZero(NumElems);
7805 APInt UndefMask = APInt::getZero(NumElems);
7806
7807 SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
7808 SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
7809
7810 // For each element in the initializer, see if we've found a load, zero or an
7811 // undef.
7812 for (unsigned i = 0; i < NumElems; ++i) {
7813 SDValue Elt = peekThroughBitcasts(Elts[i]);
7814 if (!Elt.getNode())
7815 return SDValue();
7816 if (Elt.isUndef()) {
7817 UndefMask.setBit(i);
7818 continue;
7819 }
7821 ZeroMask.setBit(i);
7822 continue;
7823 }
7824
7825 // Each loaded element must be the correct fractional portion of the
7826 // requested vector load.
7827 unsigned EltSizeInBits = Elt.getValueSizeInBits();
7828 if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
7829 return SDValue();
7830
7831 if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
7832 return SDValue();
7833 unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
7834 if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
7835 return SDValue();
7836
7837 LoadMask.setBit(i);
7838 LastLoadedElt = i;
7839 }
7840 assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
7841 NumElems &&
7842 "Incomplete element masks");
7843
7844 // Handle Special Cases - all undef or undef/zero.
7845 if (UndefMask.popcount() == NumElems)
7846 return DAG.getUNDEF(VT);
7847 if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
7848 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7849 : DAG.getConstantFP(0.0, DL, VT);
7850
7851 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7852 int FirstLoadedElt = LoadMask.countr_zero();
7853 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7854 EVT EltBaseVT = EltBase.getValueType();
7855 assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
7856 "Register/Memory size mismatch");
7857 LoadSDNode *LDBase = Loads[FirstLoadedElt];
7858 assert(LDBase && "Did not find base load for merging consecutive loads");
7859 unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
7860 unsigned BaseSizeInBytes = BaseSizeInBits / 8;
7861 int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
7862 int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
7863 assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
7864
7865 // TODO: Support offsetting the base load.
7866 if (ByteOffsets[FirstLoadedElt] != 0)
7867 return SDValue();
7868
7869 // Check to see if the element's load is consecutive to the base load
7870 // or offset from a previous (already checked) load.
7871 auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
7872 LoadSDNode *Ld = Loads[EltIdx];
7873 int64_t ByteOffset = ByteOffsets[EltIdx];
7874 if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
7875 int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
7876 return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
7877 Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
7878 }
7879 int Stride = EltIdx - FirstLoadedElt;
7880 if (DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes, Stride))
7881 return true;
7882 // Try again using the memory load size (we might have broken a large load
7883 // into smaller elements), ensure the stride is the full memory load size
7884 // apart and a whole number of elements fit in each memory load.
7885 unsigned BaseMemSizeInBits = Base->getMemoryVT().getSizeInBits();
7886 if (((Stride * BaseSizeInBits) % BaseMemSizeInBits) == 0 &&
7887 (BaseMemSizeInBits % BaseSizeInBits) == 0) {
7888 unsigned Scale = BaseMemSizeInBits / BaseSizeInBits;
7889 return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseMemSizeInBits / 8,
7890 Stride / Scale);
7891 }
7892 return false;
7893 };
7894
7895 // Consecutive loads can contain UNDEFS but not ZERO elements.
7896 // Consecutive loads with UNDEFs and ZEROs elements require a
7897 // an additional shuffle stage to clear the ZERO elements.
7898 bool IsConsecutiveLoad = true;
7899 bool IsConsecutiveLoadWithZeros = true;
7900 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7901 if (LoadMask[i]) {
7902 if (!CheckConsecutiveLoad(LDBase, i)) {
7903 IsConsecutiveLoad = false;
7904 IsConsecutiveLoadWithZeros = false;
7905 break;
7906 }
7907 } else if (ZeroMask[i]) {
7908 IsConsecutiveLoad = false;
7909 }
7910 }
7911
7912 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7913 auto MMOFlags = LDBase->getMemOperand()->getFlags();
7914 assert(LDBase->isSimple() &&
7915 "Cannot merge volatile or atomic loads.");
7916 SDValue NewLd =
7917 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7918 LDBase->getPointerInfo(), LDBase->getBaseAlign(), MMOFlags);
7919 for (auto *LD : Loads)
7920 if (LD)
7921 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
7922 return NewLd;
7923 };
7924
7925 // Check if the base load is entirely dereferenceable.
7926 bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
7927 VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
7928
7929 // LOAD - all consecutive load/undefs (must start/end with a load or be
7930 // entirely dereferenceable). If we have found an entire vector of loads and
7931 // undefs, then return a large load of the entire vector width starting at the
7932 // base pointer. If the vector contains zeros, then attempt to shuffle those
7933 // elements.
7934 if (FirstLoadedElt == 0 &&
7935 (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
7936 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
7937 if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
7938 return SDValue();
7939
7940 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
7941 // will lower to regular temporal loads and use the cache.
7942 if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
7943 VT.is256BitVector() && !Subtarget.hasInt256())
7944 return SDValue();
7945
7946 if (NumElems == 1)
7947 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
7948
7949 if (!ZeroMask)
7950 return CreateLoad(VT, LDBase);
7951
7952 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
7953 // vector and a zero vector to clear out the zero elements.
7954 if (!IsAfterLegalize && VT.isVector()) {
7955 unsigned NumMaskElts = VT.getVectorNumElements();
7956 if ((NumMaskElts % NumElems) == 0) {
7957 unsigned Scale = NumMaskElts / NumElems;
7958 SmallVector<int, 4> ClearMask(NumMaskElts, -1);
7959 for (unsigned i = 0; i < NumElems; ++i) {
7960 if (UndefMask[i])
7961 continue;
7962 int Offset = ZeroMask[i] ? NumMaskElts : 0;
7963 for (unsigned j = 0; j != Scale; ++j)
7964 ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
7965 }
7966 SDValue V = CreateLoad(VT, LDBase);
7967 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
7968 : DAG.getConstantFP(0.0, DL, VT);
7969 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
7970 }
7971 }
7972 }
7973
7974 // If the upper half of a ymm/zmm load is undef then just load the lower half.
7975 if (VT.is256BitVector() || VT.is512BitVector()) {
7976 unsigned HalfNumElems = NumElems / 2;
7977 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
7978 EVT HalfVT =
7979 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
7980 SDValue HalfLD =
7981 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
7982 DAG, Subtarget, IsAfterLegalize, Depth + 1);
7983 if (HalfLD)
7984 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
7985 HalfLD, DAG.getVectorIdxConstant(0, DL));
7986 }
7987 }
7988
7989 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
7990 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
7991 ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
7992 LoadSizeInBits == 64) &&
7993 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
7994 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
7995 : MVT::getIntegerVT(LoadSizeInBits);
7996 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
7997 // Allow v4f32 on SSE1 only targets.
7998 // FIXME: Add more isel patterns so we can just use VT directly.
7999 if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8000 VecVT = MVT::v4f32;
8001 if (TLI.isTypeLegal(VecVT)) {
8002 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8003 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8004 SDValue ResNode = DAG.getMemIntrinsicNode(
8005 X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8007 for (auto *LD : Loads)
8008 if (LD)
8009 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8010 return DAG.getBitcast(VT, ResNode);
8011 }
8012 }
8013
8014 // BROADCAST - match the smallest possible repetition pattern, load that
8015 // scalar/subvector element and then broadcast to the entire vector.
8016 if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8017 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8018 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8019 unsigned RepeatSize = SubElems * BaseSizeInBits;
8020 unsigned ScalarSize = std::min(RepeatSize, 64u);
8021 if (!Subtarget.hasAVX2() && ScalarSize < 32)
8022 continue;
8023
8024 // Don't attempt a 1:N subvector broadcast - it should be caught by
8025 // combineConcatVectorOps, else will cause infinite loops.
8026 if (RepeatSize > ScalarSize && SubElems == 1)
8027 continue;
8028
8029 bool Match = true;
8030 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8031 for (unsigned i = 0; i != NumElems && Match; ++i) {
8032 if (!LoadMask[i])
8033 continue;
8034 SDValue Elt = peekThroughBitcasts(Elts[i]);
8035 if (RepeatedLoads[i % SubElems].isUndef())
8036 RepeatedLoads[i % SubElems] = Elt;
8037 else
8038 Match &= (RepeatedLoads[i % SubElems] == Elt);
8039 }
8040
8041 // We must have loads at both ends of the repetition.
8042 Match &= !RepeatedLoads.front().isUndef();
8043 Match &= !RepeatedLoads.back().isUndef();
8044 if (!Match)
8045 continue;
8046
8047 EVT RepeatVT =
8048 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8049 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8050 : EVT::getFloatingPointVT(ScalarSize);
8051 if (RepeatSize > ScalarSize)
8052 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8053 RepeatSize / ScalarSize);
8054 EVT BroadcastVT =
8055 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8056 VT.getSizeInBits() / ScalarSize);
8057 if (TLI.isTypeLegal(BroadcastVT)) {
8058 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8059 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize,
8060 Depth + 1)) {
8061 SDValue Broadcast = RepeatLoad;
8062 if (RepeatSize > ScalarSize) {
8063 while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
8064 Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
8065 } else {
8066 if (!Subtarget.hasAVX2() &&
8068 RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
8069 Subtarget,
8070 /*AssumeSingleUse=*/true))
8071 return SDValue();
8072 Broadcast =
8073 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
8074 }
8075 return DAG.getBitcast(VT, Broadcast);
8076 }
8077 }
8078 }
8079 }
8080
8081 // REVERSE - attempt to match the loads in reverse and then shuffle back.
8082 // TODO: Do this for any permute or mismatching element counts.
8083 if (Depth == 0 && ZeroMask.isZero() && UndefMask.isZero() &&
8084 TLI.isTypeLegal(VT) && VT.isVector() &&
8085 NumElems == VT.getVectorNumElements()) {
8086 SmallVector<SDValue, 16> ReverseElts(Elts.rbegin(), Elts.rend());
8088 VT, ReverseElts, DL, DAG, Subtarget, IsAfterLegalize, Depth + 1)) {
8089 SmallVector<int, 16> ReverseMask(NumElems);
8090 std::iota(ReverseMask.rbegin(), ReverseMask.rend(), 0);
8091 return DAG.getVectorShuffle(VT, DL, RevLd, DAG.getUNDEF(VT), ReverseMask);
8092 }
8093 }
8094
8095 return SDValue();
8096}
8097
8098// Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8099// load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8100// are consecutive, non-overlapping, and in the right order.
8102 SelectionDAG &DAG,
8103 const X86Subtarget &Subtarget,
8104 bool IsAfterLegalize) {
8106 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8107 if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8108 Elts.push_back(Elt);
8109 continue;
8110 }
8111 return SDValue();
8112 }
8113 assert(Elts.size() == VT.getVectorNumElements());
8114 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8115 IsAfterLegalize);
8116}
8117
8119 const APInt &Undefs, LLVMContext &C) {
8120 unsigned ScalarSize = VT.getScalarSizeInBits();
8121 Type *Ty = EVT(VT.getScalarType()).getTypeForEVT(C);
8122
8123 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8124 if (VT.isFloatingPoint()) {
8125 if (ScalarSize == 16)
8126 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8127 if (ScalarSize == 32)
8128 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8129 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8130 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8131 }
8132 return Constant::getIntegerValue(Ty, Val);
8133 };
8134
8135 SmallVector<Constant *, 32> ConstantVec;
8136 for (unsigned I = 0, E = Bits.size(); I != E; ++I)
8137 ConstantVec.push_back(Undefs[I] ? UndefValue::get(Ty)
8138 : getConstantScalar(Bits[I]));
8139
8140 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8141}
8142
8143static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8144 unsigned SplatBitSize, LLVMContext &C) {
8145 unsigned ScalarSize = VT.getScalarSizeInBits();
8146
8147 auto getConstantScalar = [&](const APInt &Val) -> Constant * {
8148 if (VT.isFloatingPoint()) {
8149 if (ScalarSize == 16)
8150 return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
8151 if (ScalarSize == 32)
8152 return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8153 assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8154 return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8155 }
8156 return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8157 };
8158
8159 if (ScalarSize == SplatBitSize)
8160 return getConstantScalar(SplatValue);
8161
8162 unsigned NumElm = SplatBitSize / ScalarSize;
8163 SmallVector<Constant *, 32> ConstantVec;
8164 for (unsigned I = 0; I != NumElm; ++I) {
8165 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
8166 ConstantVec.push_back(getConstantScalar(Val));
8167 }
8168 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8169}
8170
8172 for (auto *U : N->users()) {
8173 unsigned Opc = U->getOpcode();
8174 // VPERMV/VPERMV3 shuffles can never fold their index operands.
8175 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8176 return false;
8177 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8178 return false;
8179 if (isTargetShuffle(Opc))
8180 return true;
8181 if (Opc == ISD::BITCAST) // Ignore bitcasts
8182 return isFoldableUseOfShuffle(U);
8183 if (N->hasOneUse()) {
8184 // TODO, there may be some general way to know if a SDNode can
8185 // be folded. We now only know whether an MI is foldable.
8186 if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
8187 return false;
8188 return true;
8189 }
8190 }
8191 return false;
8192}
8193
8195 while (V.getOpcode() == ISD::BITCAST ||
8196 V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8197 V = V.getOperand(0);
8198 return isTargetShuffle(V.getOpcode());
8199}
8200
8201// If the node has a single use by a VSELECT then AVX512 targets may be able to
8202// fold as a predicated instruction.
8203static bool isMaskableNode(SDValue V, const X86Subtarget &Subtarget) {
8204 unsigned SizeInBits = V.getValueSizeInBits();
8205 if ((SizeInBits == 512 && Subtarget.hasAVX512()) ||
8206 (SizeInBits >= 128 && Subtarget.hasVLX())) {
8207 if (V.hasOneUse() && V->user_begin()->getOpcode() == ISD::VSELECT &&
8208 V->user_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
8209 return true;
8210 }
8211 }
8212 return false;
8213}
8214
8215/// Attempt to use the vbroadcast instruction to generate a splat value
8216/// from a splat BUILD_VECTOR which uses:
8217/// a. A single scalar load, or a constant.
8218/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8219///
8220/// The VBROADCAST node is returned when a pattern is found,
8221/// or SDValue() otherwise.
8223 const SDLoc &dl,
8224 const X86Subtarget &Subtarget,
8225 SelectionDAG &DAG) {
8226 // VBROADCAST requires AVX.
8227 // TODO: Splats could be generated for non-AVX CPUs using SSE
8228 // instructions, but there's less potential gain for only 128-bit vectors.
8229 if (!Subtarget.hasAVX())
8230 return SDValue();
8231
8232 MVT VT = BVOp->getSimpleValueType(0);
8233 unsigned NumElts = VT.getVectorNumElements();
8234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8235 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8236 "Unsupported vector type for broadcast.");
8237
8238 // See if the build vector is a repeating sequence of scalars (inc. splat).
8239 SDValue Ld;
8240 BitVector UndefElements;
8241 SmallVector<SDValue, 16> Sequence;
8242 if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
8243 assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
8244 if (Sequence.size() == 1)
8245 Ld = Sequence[0];
8246 }
8247
8248 // Attempt to use VBROADCASTM
8249 // From this pattern:
8250 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8251 // b. t1 = (build_vector t0 t0)
8252 //
8253 // Create (VBROADCASTM v2i1 X)
8254 if (!Sequence.empty() && Subtarget.hasCDI()) {
8255 // If not a splat, are the upper sequence values zeroable?
8256 unsigned SeqLen = Sequence.size();
8257 bool UpperZeroOrUndef =
8258 SeqLen == 1 ||
8259 llvm::all_of(ArrayRef(Sequence).drop_front(),
8260 [](SDValue V) { return !V || isNullConstantOrUndef(V); });
8261 SDValue Op0 = Sequence[0];
8262 if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
8263 (Op0.getOpcode() == ISD::ZERO_EXTEND &&
8264 Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
8265 SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
8266 ? Op0.getOperand(0)
8267 : Op0.getOperand(0).getOperand(0);
8268 MVT MaskVT = BOperand.getSimpleValueType();
8269 MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
8270 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8271 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8272 MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
8273 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
8274 unsigned Scale = 512 / VT.getSizeInBits();
8275 BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
8276 }
8277 SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
8278 if (BcstVT.getSizeInBits() != VT.getSizeInBits())
8279 Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
8280 return DAG.getBitcast(VT, Bcst);
8281 }
8282 }
8283 }
8284
8285 unsigned NumUndefElts = UndefElements.count();
8286 if (!Ld || (NumElts - NumUndefElts) <= 1) {
8287 APInt SplatValue, Undef;
8288 unsigned SplatBitSize;
8289 bool HasUndef;
8290 // Check if this is a repeated constant pattern suitable for broadcasting.
8291 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8292 SplatBitSize > VT.getScalarSizeInBits() &&
8293 SplatBitSize < VT.getSizeInBits()) {
8294 // Avoid replacing with broadcast when it's a use of a shuffle
8295 // instruction to preserve the present custom lowering of shuffles.
8296 if (isFoldableUseOfShuffle(BVOp))
8297 return SDValue();
8298 // replace BUILD_VECTOR with broadcast of the repeated constants.
8299 LLVMContext *Ctx = DAG.getContext();
8300 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8301 if (SplatBitSize == 32 || SplatBitSize == 64 ||
8302 (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8303 // Load the constant scalar/subvector and broadcast it.
8304 MVT CVT = MVT::getIntegerVT(SplatBitSize);
8305 Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8306 SDValue CP = DAG.getConstantPool(C, PVT);
8307 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8308
8309 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8310 SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8311 SDValue Ops[] = {DAG.getEntryNode(), CP};
8312 MachinePointerInfo MPI =
8314 SDValue Brdcst =
8315 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8316 MPI, Alignment, MachineMemOperand::MOLoad);
8317 return DAG.getBitcast(VT, Brdcst);
8318 }
8319 if (SplatBitSize > 64) {
8320 // Load the vector of constants and broadcast it.
8321 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
8322 SDValue VCP = DAG.getConstantPool(VecC, PVT);
8323 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8324 MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
8325 Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8326 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8327 SDValue Ops[] = {DAG.getEntryNode(), VCP};
8328 MachinePointerInfo MPI =
8330 return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
8331 Ops, VVT, MPI, Alignment,
8333 }
8334 }
8335
8336 // If we are moving a scalar into a vector (Ld must be set and all elements
8337 // but 1 are undef) and that operation is not obviously supported by
8338 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8339 // That's better than general shuffling and may eliminate a load to GPR and
8340 // move from scalar to vector register.
8341 if (!Ld || NumElts - NumUndefElts != 1)
8342 return SDValue();
8343 unsigned ScalarSize = Ld.getValueSizeInBits();
8344 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8345 return SDValue();
8346 }
8347
8348 bool ConstSplatVal =
8349 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8350 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8351
8352 // TODO: Handle broadcasts of non-constant sequences.
8353
8354 // Make sure that all of the users of a non-constant load are from the
8355 // BUILD_VECTOR node.
8356 // FIXME: Is the use count needed for non-constant, non-load case?
8357 if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8358 return SDValue();
8359
8360 unsigned ScalarSize = Ld.getValueSizeInBits();
8361 bool IsGE256 = (VT.getSizeInBits() >= 256);
8362
8363 // When optimizing for size, generate up to 5 extra bytes for a broadcast
8364 // instruction to save 8 or more bytes of constant pool data.
8365 // TODO: If multiple splats are generated to load the same constant,
8366 // it may be detrimental to overall size. There needs to be a way to detect
8367 // that condition to know if this is truly a size win.
8368 bool OptForSize = DAG.shouldOptForSize();
8369
8370 // Handle broadcasting a single constant scalar from the constant pool
8371 // into a vector.
8372 // On Sandybridge (no AVX2), it is still better to load a constant vector
8373 // from the constant pool and not to broadcast it from a scalar.
8374 // But override that restriction when optimizing for size.
8375 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8376 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8377 EVT CVT = Ld.getValueType();
8378 assert(!CVT.isVector() && "Must not broadcast a vector type");
8379
8380 // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
8381 // For size optimization, also splat v2f64 and v2i64, and for size opt
8382 // with AVX2, also splat i8 and i16.
8383 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8384 if (ScalarSize == 32 ||
8385 (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
8386 (CVT == MVT::f16 && Subtarget.hasAVX2()) ||
8387 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8388 const Constant *C = nullptr;
8390 C = CI->getConstantIntValue();
8392 C = CF->getConstantFPValue();
8393
8394 assert(C && "Invalid constant type");
8395
8396 SDValue CP =
8398 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8399
8400 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8401 SDValue Ops[] = {DAG.getEntryNode(), CP};
8402 MachinePointerInfo MPI =
8404 return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8405 MPI, Alignment, MachineMemOperand::MOLoad);
8406 }
8407 }
8408
8409 // Handle AVX2 in-register broadcasts.
8410 if (!IsLoad && Subtarget.hasInt256() &&
8411 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8412 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8413
8414 // The scalar source must be a normal load.
8415 if (!IsLoad)
8416 return SDValue();
8417
8418 // Make sure the non-chain result is only used by this build vector.
8419 if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
8420 return SDValue();
8421
8422 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8423 (Subtarget.hasVLX() && ScalarSize == 64)) {
8424 auto *LN = cast<LoadSDNode>(Ld);
8425 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8426 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8427 SDValue BCast =
8428 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8429 LN->getMemoryVT(), LN->getMemOperand());
8430 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8431 return BCast;
8432 }
8433
8434 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8435 // double since there is no vbroadcastsd xmm
8436 if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
8437 (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
8438 auto *LN = cast<LoadSDNode>(Ld);
8439 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8440 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8441 SDValue BCast =
8442 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8443 LN->getMemoryVT(), LN->getMemOperand());
8444 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8445 return BCast;
8446 }
8447
8448 if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
8449 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8450
8451 // Unsupported broadcast.
8452 return SDValue();
8453}
8454
8455/// For an EXTRACT_VECTOR_ELT with a constant index return the real
8456/// underlying vector and index.
8457///
8458/// Modifies \p ExtractedFromVec to the real vector and returns the real
8459/// index.
8460static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
8461 SDValue ExtIdx) {
8462 int Idx = ExtIdx->getAsZExtVal();
8463 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
8464 return Idx;
8465
8466 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
8467 // lowered this:
8468 // (extract_vector_elt (v8f32 %1), Constant<6>)
8469 // to:
8470 // (extract_vector_elt (vector_shuffle<2,u,u,u>
8471 // (extract_subvector (v8f32 %0), Constant<4>),
8472 // undef)
8473 // Constant<0>)
8474 // In this case the vector is the extract_subvector expression and the index
8475 // is 2, as specified by the shuffle.
8476 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
8477 SDValue ShuffleVec = SVOp->getOperand(0);
8478 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
8479 assert(ShuffleVecVT.getVectorElementType() ==
8480 ExtractedFromVec.getSimpleValueType().getVectorElementType());
8481
8482 int ShuffleIdx = SVOp->getMaskElt(Idx);
8483 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
8484 ExtractedFromVec = ShuffleVec;
8485 return ShuffleIdx;
8486 }
8487 return Idx;
8488}
8489
8491 SelectionDAG &DAG) {
8492 MVT VT = Op.getSimpleValueType();
8493
8494 // Skip if insert_vec_elt is not supported.
8495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8497 return SDValue();
8498
8499 unsigned NumElems = Op.getNumOperands();
8500 SDValue VecIn1;
8501 SDValue VecIn2;
8502 SmallVector<unsigned, 4> InsertIndices;
8503 SmallVector<int, 8> Mask(NumElems, -1);
8504
8505 for (unsigned i = 0; i != NumElems; ++i) {
8506 unsigned Opc = Op.getOperand(i).getOpcode();
8507
8508 if (Opc == ISD::POISON || Opc == ISD::UNDEF)
8509 continue;
8510
8512 // Quit if more than 1 elements need inserting.
8513 if (InsertIndices.size() > 1)
8514 return SDValue();
8515
8516 InsertIndices.push_back(i);
8517 continue;
8518 }
8519
8520 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
8521 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
8522
8523 // Quit if non-constant index.
8524 if (!isa<ConstantSDNode>(ExtIdx))
8525 return SDValue();
8526 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
8527
8528 // Quit if extracted from vector of different type.
8529 if (ExtractedFromVec.getValueType() != VT)
8530 return SDValue();
8531
8532 if (!VecIn1.getNode())
8533 VecIn1 = ExtractedFromVec;
8534 else if (VecIn1 != ExtractedFromVec) {
8535 if (!VecIn2.getNode())
8536 VecIn2 = ExtractedFromVec;
8537 else if (VecIn2 != ExtractedFromVec)
8538 // Quit if more than 2 vectors to shuffle
8539 return SDValue();
8540 }
8541
8542 if (ExtractedFromVec == VecIn1)
8543 Mask[i] = Idx;
8544 else if (ExtractedFromVec == VecIn2)
8545 Mask[i] = Idx + NumElems;
8546 }
8547
8548 if (!VecIn1.getNode())
8549 return SDValue();
8550
8551 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getPOISON(VT);
8552 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
8553
8554 for (unsigned Idx : InsertIndices)
8555 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8556 DAG.getVectorIdxConstant(Idx, DL));
8557
8558 return NV;
8559}
8560
8561// Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
8563 const X86Subtarget &Subtarget) {
8564 MVT VT = Op.getSimpleValueType();
8565 MVT SVT = Subtarget.hasFP16() ? MVT::f16 : MVT::i16;
8566 MVT IVT = VT.changeVectorElementType(SVT);
8568 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
8569 NewOps.push_back(DAG.getBitcast(SVT, Op.getOperand(I)));
8570 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
8571 return DAG.getBitcast(VT, Res);
8572}
8573
8574// Lower BUILD_VECTOR operation for vXi1 types.
8576 SelectionDAG &DAG,
8577 const X86Subtarget &Subtarget) {
8578
8579 MVT VT = Op.getSimpleValueType();
8580 assert((VT.getVectorElementType() == MVT::i1) &&
8581 "Unexpected type in LowerBUILD_VECTORvXi1!");
8582 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
8583 ISD::isBuildVectorAllOnes(Op.getNode()))
8584 return Op;
8585
8586 uint64_t Undefs = 0;
8587 uint64_t Immediate = 0;
8588 uint64_t NonConstMask = 0;
8589 SmallSet<SDValue, 16> NonConstElts;
8590 bool HasConstElts = false;
8591 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8592 SDValue In = Op.getOperand(idx);
8593 if (In.isUndef()) {
8594 Undefs |= 1ULL << idx;
8595 continue;
8596 }
8597 if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
8598 Immediate |= (InC->getZExtValue() & 0x1) << idx;
8599 HasConstElts = true;
8600 } else {
8601 NonConstMask |= 1ULL << idx;
8602 NonConstElts.insert(In);
8603 }
8604 }
8605
8606 // for single non-const use " (select i1 elt, imm | elt_mask, imm)"
8607 if (NonConstElts.size() == 1) {
8608 // The build_vector allows the scalar element to be larger than the vector
8609 // element type. We need to mask it to use as a condition unless we know
8610 // the upper bits are zero.
8611 // FIXME: Use computeKnownBits instead of checking specific opcode?
8612 SDValue Cond = *NonConstElts.begin();
8613 assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
8614 if (Cond.getOpcode() != ISD::SETCC)
8615 Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
8616 DAG.getConstant(1, dl, MVT::i8));
8617
8618 uint64_t TrueImm = NonConstMask | Immediate;
8619 uint64_t FalseImm = Immediate;
8620
8621 // Perform the select in the scalar domain so we can use cmov.
8622 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8623 uint64_t TrueLo = (unsigned)TrueImm;
8624 uint64_t TrueHi = TrueImm >> 32;
8625 uint64_t FalseLo = (unsigned)FalseImm;
8626 uint64_t FalseHi = FalseImm >> 32;
8627 SDValue Lo = DAG.getSelect(dl, MVT::i32, Cond,
8628 DAG.getConstant(TrueLo, dl, MVT::i32),
8629 DAG.getConstant(FalseLo, dl, MVT::i32));
8630 SDValue Hi = DAG.getSelect(dl, MVT::i32, Cond,
8631 DAG.getConstant(TrueHi, dl, MVT::i32),
8632 DAG.getConstant(FalseHi, dl, MVT::i32));
8633 Lo = DAG.getBitcast(MVT::v32i1, Lo);
8634 Hi = DAG.getBitcast(MVT::v32i1, Hi);
8635 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
8636 } else {
8637 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8638 // Adjust extended value to -1 as it will improve folding.
8639 if ((TrueImm | Undefs) == (~0ULL >> (64 - VT.getSizeInBits())))
8640 TrueImm = ~0ULL >> (64 - ImmVT.getSizeInBits());
8641 SDValue Select =
8642 DAG.getSelect(dl, ImmVT, Cond, DAG.getConstant(TrueImm, dl, ImmVT),
8643 DAG.getConstant(FalseImm, dl, ImmVT));
8644 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8645 Select = DAG.getBitcast(VecVT, Select);
8646 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
8647 DAG.getVectorIdxConstant(0, dl));
8648 }
8649 }
8650
8651 // See if we can cheaply generate a vXi8 vector and convert to vXi1.
8652 MVT OpVT = Op.getOperand(0).getSimpleValueType();
8653 if (OpVT == MVT::i8 && NonConstMask != 0) {
8654 // On pre-BWI targets, we must extend to vXi32 instead.
8655 MVT ByteVT = VT.changeVectorElementType(MVT::i8);
8656 MVT WideSVT = Subtarget.hasBWI() ? MVT::i8 : MVT::i32;
8657 if (ByteVT.getSizeInBits() < 128) {
8658 WideSVT = ByteVT == MVT::v4i8 ? MVT::i32 : MVT::i64;
8659 ByteVT = MVT::v16i8;
8660 }
8661 MVT WideVT = VT.changeVectorElementType(WideSVT);
8662 if (DAG.getTargetLoweringInfo().isTypeLegal(ByteVT) &&
8663 DAG.getTargetLoweringInfo().isTypeLegal(WideVT)) {
8664 SmallVector<SDValue, 16> Elts(Op->op_values());
8665 Elts.append(ByteVT.getVectorNumElements() - Elts.size(),
8666 DAG.getPOISON(OpVT));
8667 SDValue ByteBV = DAG.getBuildVector(ByteVT, dl, Elts);
8668 SDValue WideBV =
8669 getEXTEND_VECTOR_INREG(ISD::ANY_EXTEND, dl, WideVT, ByteBV, DAG);
8670 WideBV = DAG.getNode(ISD::AND, dl, WideVT, WideBV,
8671 DAG.getConstant(1, dl, WideVT));
8672 return DAG.getSetCC(dl, VT, WideBV, DAG.getConstant(0, dl, WideVT),
8673 ISD::SETNE);
8674 }
8675 }
8676
8677 // insert elements one by one
8678 SDValue DstVec;
8679 if (HasConstElts) {
8680 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8681 SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
8682 SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
8683 ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
8684 ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
8685 DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
8686 } else {
8687 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
8688 SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
8689 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
8690 DstVec = DAG.getBitcast(VecVT, Imm);
8691 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
8692 DAG.getVectorIdxConstant(0, dl));
8693 }
8694 } else
8695 DstVec = DAG.getUNDEF(VT);
8696
8697 for (unsigned Idx = 0, E = Op.getNumOperands(); Idx != E; ++Idx)
8698 if (NonConstMask & (1ULL << Idx))
8699 DstVec = DAG.getInsertVectorElt(dl, DstVec, Op.getOperand(Idx), Idx);
8700
8701 return DstVec;
8702}
8703
8704[[maybe_unused]] static bool isHorizOp(unsigned Opcode) {
8705 switch (Opcode) {
8706 case X86ISD::PACKSS:
8707 case X86ISD::PACKUS:
8708 case X86ISD::FHADD:
8709 case X86ISD::FHSUB:
8710 case X86ISD::HADD:
8711 case X86ISD::HSUB:
8712 case X86ISD::HADDS:
8713 case X86ISD::HSUBS:
8714 return true;
8715 }
8716 return false;
8717}
8718
8719/// Returns true iff \p BV builds a vector with the result equivalent to
8720/// the result of ADDSUB/SUBADD operation.
8721/// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
8722/// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
8723/// \p Opnd0 and \p Opnd1.
8725 const X86Subtarget &Subtarget, SelectionDAG &DAG,
8726 SDValue &Opnd0, SDValue &Opnd1,
8727 unsigned &NumExtracts, bool &IsSubAdd,
8728 bool &HasAllowContract) {
8729 using namespace SDPatternMatch;
8730
8731 MVT VT = BV->getSimpleValueType(0);
8732 if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
8733 return false;
8734
8735 unsigned NumElts = VT.getVectorNumElements();
8736 SDValue InVec0 = DAG.getUNDEF(VT);
8737 SDValue InVec1 = DAG.getUNDEF(VT);
8738
8739 NumExtracts = 0;
8740 HasAllowContract = NumElts != 0;
8741
8742 // Odd-numbered elements in the input build vector are obtained from
8743 // adding/subtracting two integer/float elements.
8744 // Even-numbered elements in the input build vector are obtained from
8745 // subtracting/adding two integer/float elements.
8746 unsigned Opc[2] = {0, 0};
8747 for (unsigned i = 0, e = NumElts; i != e; ++i) {
8748 SDValue Op = BV->getOperand(i);
8749
8750 // Skip 'undef' values.
8751 unsigned Opcode = Op.getOpcode();
8752 if (Opcode == ISD::UNDEF)
8753 continue;
8754
8755 // Early exit if we found an unexpected opcode.
8756 if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
8757 return false;
8758
8759 SDValue Op0 = Op.getOperand(0);
8760 SDValue Op1 = Op.getOperand(1);
8761
8762 // Try to match the following pattern:
8763 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
8764 // Early exit if we cannot match that sequence.
8765 if (!sd_match(Op0, m_ExtractElt(m_SpecificVT(VT), m_SpecificInt(i))) ||
8766 !sd_match(Op1, m_ExtractElt(m_SpecificVT(VT), m_SpecificInt(i))))
8767 return false;
8768
8769 // We found a valid add/sub node, make sure its the same opcode as previous
8770 // elements for this parity.
8771 if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
8772 return false;
8773 Opc[i % 2] = Opcode;
8774
8775 // Update InVec0 and InVec1.
8776 if (InVec0.isUndef())
8777 InVec0 = Op0.getOperand(0);
8778 if (InVec1.isUndef())
8779 InVec1 = Op1.getOperand(0);
8780
8781 // Make sure that operands in input to each add/sub node always
8782 // come from a same pair of vectors.
8783 if (InVec0 != Op0.getOperand(0)) {
8784 if (Opcode == ISD::FSUB)
8785 return false;
8786
8787 // FADD is commutable. Try to commute the operands
8788 // and then test again.
8789 std::swap(Op0, Op1);
8790 if (InVec0 != Op0.getOperand(0))
8791 return false;
8792 }
8793
8794 if (InVec1 != Op1.getOperand(0))
8795 return false;
8796
8797 // Increment the number of extractions done.
8798 ++NumExtracts;
8799 HasAllowContract &= Op->getFlags().hasAllowContract();
8800 }
8801
8802 // Ensure we have found an opcode for both parities and that they are
8803 // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
8804 // inputs are undef.
8805 if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
8806 InVec0.isUndef() || InVec1.isUndef())
8807 return false;
8808
8809 IsSubAdd = Opc[0] == ISD::FADD;
8810
8811 Opnd0 = InVec0;
8812 Opnd1 = InVec1;
8813 return true;
8814}
8815
8816/// Returns true if is possible to fold MUL and an idiom that has already been
8817/// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8818/// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8819/// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8820///
8821/// Prior to calling this function it should be known that there is some
8822/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8823/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8824/// before replacement of such SDNode with ADDSUB operation. Thus the number
8825/// of \p Opnd0 uses is expected to be equal to 2.
8826/// For example, this function may be called for the following IR:
8827/// %AB = fmul fast <2 x double> %A, %B
8828/// %Sub = fsub fast <2 x double> %AB, %C
8829/// %Add = fadd fast <2 x double> %AB, %C
8830/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8831/// <2 x i32> <i32 0, i32 3>
8832/// There is a def for %Addsub here, which potentially can be replaced by
8833/// X86ISD::ADDSUB operation:
8834/// %Addsub = X86ISD::ADDSUB %AB, %C
8835/// and such ADDSUB can further be replaced with FMADDSUB:
8836/// %Addsub = FMADDSUB %A, %B, %C.
8837///
8838/// The main reason why this method is called before the replacement of the
8839/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8840/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8841/// FMADDSUB is.
8842static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
8843 SelectionDAG &DAG, SDValue &Opnd0,
8844 SDValue &Opnd1, SDValue &Opnd2,
8845 unsigned ExpectedUses,
8846 bool AllowSubAddOrAddSubContract) {
8847 if (Opnd0.getOpcode() != ISD::FMUL ||
8848 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8849 return false;
8850
8851 // FIXME: These checks must match the similar ones in
8852 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8853 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8854 // or MUL + ADDSUB to FMADDSUB.
8855 bool AllowFusion =
8856 (AllowSubAddOrAddSubContract && Opnd0->getFlags().hasAllowContract());
8857 if (!AllowFusion)
8858 return false;
8859
8860 Opnd2 = Opnd1;
8861 Opnd1 = Opnd0.getOperand(1);
8862 Opnd0 = Opnd0.getOperand(0);
8863
8864 return true;
8865}
8866
8867/// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
8868/// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
8869/// X86ISD::FMSUBADD node.
8871 const SDLoc &DL,
8872 const X86Subtarget &Subtarget,
8873 SelectionDAG &DAG) {
8874 SDValue Opnd0, Opnd1;
8875 unsigned NumExtracts;
8876 bool IsSubAdd;
8877 bool HasAllowContract;
8878 if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts, IsSubAdd,
8879 HasAllowContract))
8880 return SDValue();
8881
8882 MVT VT = BV->getSimpleValueType(0);
8883
8884 // Try to generate X86ISD::FMADDSUB node here.
8885 SDValue Opnd2;
8886 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts,
8887 HasAllowContract)) {
8888 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
8889 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
8890 }
8891
8892 // We only support ADDSUB.
8893 if (IsSubAdd)
8894 return SDValue();
8895
8896 // There are no known X86 targets with 512-bit ADDSUB instructions!
8897 // Convert to blend(fsub,fadd).
8898 if (VT.is512BitVector()) {
8899 SmallVector<int> Mask;
8900 for (int I = 0, E = VT.getVectorNumElements(); I != E; I += 2) {
8901 Mask.push_back(I);
8902 Mask.push_back(I + E + 1);
8903 }
8904 SDValue Sub = DAG.getNode(ISD::FSUB, DL, VT, Opnd0, Opnd1);
8905 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, Opnd0, Opnd1);
8906 return DAG.getVectorShuffle(VT, DL, Sub, Add, Mask);
8907 }
8908
8909 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
8910}
8911
8912static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
8913 SelectionDAG &DAG);
8914
8915/// If a BUILD_VECTOR's source elements all apply the same bit operation and
8916/// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8917/// just apply the bit to the vectors.
8918/// NOTE: Its not in our interest to start make a general purpose vectorizer
8919/// from this, but enough scalar bit operations are created from the later
8920/// legalization + scalarization stages to need basic support.
8922 const X86Subtarget &Subtarget,
8923 SelectionDAG &DAG) {
8924 MVT VT = Op->getSimpleValueType(0);
8925 unsigned NumElems = VT.getVectorNumElements();
8926 unsigned ElemSize = VT.getScalarSizeInBits();
8927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8928
8929 // Check that all elements have the same opcode.
8930 // TODO: Should we allow UNDEFS and if so how many?
8931 unsigned Opcode = Op->getOperand(0).getOpcode();
8932 for (unsigned i = 1; i < NumElems; ++i)
8933 if (Opcode != Op->getOperand(i).getOpcode())
8934 return SDValue();
8935
8936 // TODO: We may be able to add support for other Ops (e.g. ADD/SUB).
8937 bool IsShift = false;
8938 switch (Opcode) {
8939 default:
8940 return SDValue();
8941 case ISD::SHL:
8942 case ISD::SRL:
8943 case ISD::SRA:
8944 IsShift = true;
8945 break;
8946 case ISD::AND:
8947 case ISD::XOR:
8948 case ISD::OR:
8949 // Don't do this if the buildvector is a splat - we'd replace one
8950 // constant with an entire vector.
8951 if (Op->getSplatValue())
8952 return SDValue();
8953 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8954 return SDValue();
8955 break;
8956 }
8957
8958 // Collect elements.
8959 bool RHSAllConst = true;
8960 SmallVector<SDValue, 4> LHSElts, RHSElts;
8961 for (SDValue Elt : Op->ops()) {
8962 SDValue LHS = Elt.getOperand(0);
8963 SDValue RHS = Elt.getOperand(1);
8964 RHSAllConst &= isa<ConstantSDNode>(RHS);
8965 LHSElts.push_back(LHS);
8966 RHSElts.push_back(RHS);
8967 }
8968
8969 // Canonicalize shift amounts.
8970 if (IsShift) {
8971 // We expect the canonicalized RHS operand to be the constant.
8972 // TODO: Permit non-constant XOP/AVX2 cases?
8973 if (!RHSAllConst)
8974 return SDValue();
8975
8976 // Extend shift amounts.
8977 for (SDValue &Op1 : RHSElts)
8978 if (Op1.getValueSizeInBits() != ElemSize)
8979 Op1 = DAG.getZExtOrTrunc(Op1, DL, VT.getScalarType());
8980
8981 // Limit to shifts by uniform immediates.
8982 // TODO: Only accept vXi8/vXi64 special cases?
8983 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
8984 if (any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
8985 return SDValue();
8986 }
8987 assert(all_of(llvm::concat<SDValue>(LHSElts, RHSElts),
8988 [ElemSize](SDValue V) {
8989 return V.getValueSizeInBits() == ElemSize;
8990 }) &&
8991 "Element size mismatch");
8992
8993 // To avoid an increase in GPR->FPU instructions, LHS/RHS must be foldable as
8994 // a load or RHS must be constant.
8995 SDValue LHS = EltsFromConsecutiveLoads(VT, LHSElts, DL, DAG, Subtarget,
8996 /*IsAfterLegalize=*/true);
8997 SDValue RHS = EltsFromConsecutiveLoads(VT, RHSElts, DL, DAG, Subtarget,
8998 /*IsAfterLegalize=*/true);
8999 if (!LHS && !RHS && !RHSAllConst)
9000 return SDValue();
9001
9002 if (!LHS)
9003 LHS = DAG.getBuildVector(VT, DL, LHSElts);
9004 if (!RHS)
9005 RHS = DAG.getBuildVector(VT, DL, RHSElts);
9006 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9007
9008 if (!IsShift)
9009 return Res;
9010
9011 // Immediately lower the shift to ensure the constant build vector doesn't
9012 // get converted to a constant pool before the shift is lowered.
9013 return LowerShift(Res, Subtarget, DAG);
9014}
9015
9016static bool isShuffleFoldableLoad(SDValue);
9017
9018/// Attempt to lower a BUILD_VECTOR of scalar values to a shuffle of splats
9019/// representing a blend.
9021 X86Subtarget const &Subtarget,
9022 SelectionDAG &DAG) {
9023 MVT VT = BVOp->getSimpleValueType(0u);
9024
9025 if (VT != MVT::v4f64)
9026 return SDValue();
9027
9028 // Collect unique operands.
9029 auto UniqueOps = SmallSet<SDValue, 16u>();
9030 for (SDValue Op : BVOp->ops()) {
9031 if (isIntOrFPConstant(Op) || Op.isUndef())
9032 return SDValue();
9033 UniqueOps.insert(Op);
9034 }
9035
9036 // Candidate BUILD_VECTOR must have 2 unique operands.
9037 if (UniqueOps.size() != 2u)
9038 return SDValue();
9039
9040 SDValue Op0 = BVOp->getOperand(0u);
9041 UniqueOps.erase(Op0);
9042 SDValue Op1 = *UniqueOps.begin();
9043
9044 if (Subtarget.hasAVX2() || isShuffleFoldableLoad(Op0) ||
9045 isShuffleFoldableLoad(Op1)) {
9046 // Create shuffle mask.
9047 auto const NumElems = VT.getVectorNumElements();
9048 SmallVector<int, 16u> Mask(NumElems);
9049 for (auto I = 0u; I < NumElems; ++I) {
9050 SDValue Op = BVOp->getOperand(I);
9051 Mask[I] = Op == Op0 ? I : I + NumElems;
9052 }
9053 // Create shuffle of splats.
9054 SDValue NewOp0 = DAG.getSplatBuildVector(VT, DL, Op0);
9055 SDValue NewOp1 = DAG.getSplatBuildVector(VT, DL, Op1);
9056 return DAG.getVectorShuffle(VT, DL, NewOp0, NewOp1, Mask);
9057 }
9058
9059 return SDValue();
9060}
9061
9062/// Widen a BUILD_VECTOR if the scalar operands are freely mergeable.
9064 X86Subtarget const &Subtarget,
9065 SelectionDAG &DAG) {
9066 using namespace SDPatternMatch;
9067 MVT VT = BVOp->getSimpleValueType(0);
9068 MVT SVT = VT.getScalarType();
9069 unsigned NumElts = VT.getVectorNumElements();
9070 unsigned EltBits = SVT.getSizeInBits();
9071
9072 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
9073 return SDValue();
9074
9075 unsigned WideBits = 2 * EltBits;
9076 MVT WideSVT = MVT::getIntegerVT(WideBits);
9077 MVT WideVT = MVT::getVectorVT(WideSVT, NumElts / 2);
9078 if (!DAG.getTargetLoweringInfo().isTypeLegal(WideSVT))
9079 return SDValue();
9080
9082 for (unsigned I = 0; I != NumElts; I += 2) {
9083 SDValue Op0 = BVOp->getOperand(I + 0);
9084 SDValue Op1 = BVOp->getOperand(I + 1);
9085
9086 if (Op0.isUndef() && Op1.isUndef()) {
9087 WideOps.push_back(DAG.getUNDEF(WideSVT));
9088 continue;
9089 }
9090
9091 // TODO: Constant repacking?
9092
9093 // Merge scalars that have been split from the same source.
9094 SDValue X, Y;
9095 if (sd_match(Op0, m_Trunc(m_Value(X))) &&
9096 sd_match(Op1, m_Trunc(m_Srl(m_Value(Y), m_SpecificInt(EltBits)))) &&
9098 X.getValueType().bitsGE(WideSVT)) {
9099 if (X.getValueType().bitsGT(WideSVT))
9100 X = DAG.getNode(ISD::TRUNCATE, DL, WideSVT, X);
9101 WideOps.push_back(X);
9102 continue;
9103 }
9104
9105 return SDValue();
9106 }
9107
9108 assert(WideOps.size() == (NumElts / 2) && "Failed to widen build vector");
9109 return DAG.getBitcast(VT, DAG.getBuildVector(WideVT, DL, WideOps));
9110}
9111
9112/// Create a vector constant without a load. SSE/AVX provide the bare minimum
9113/// functionality to do this, so it's all zeros, all ones, or some derivation
9114/// that is cheap to calculate.
9116 SelectionDAG &DAG,
9117 const X86Subtarget &Subtarget) {
9118 MVT VT = Op.getSimpleValueType();
9119
9120 // Vectors containing all zeros can be matched by pxor and xorps.
9121 if (ISD::isBuildVectorAllZeros(Op.getNode()))
9122 return Op;
9123
9124 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9125 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9126 // vpcmpeqd on 256-bit vectors.
9127 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9128 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9129 return Op;
9130
9131 return getOnesVector(VT, DAG, DL);
9132 }
9133
9134 return SDValue();
9135}
9136
9137/// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9138/// from a vector of source values and a vector of extraction indices.
9139/// The vectors might be manipulated to match the type of the permute op.
9140static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9141 const SDLoc &DL, SelectionDAG &DAG,
9142 const X86Subtarget &Subtarget) {
9143 MVT ShuffleVT = VT;
9144 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9145 unsigned NumElts = VT.getVectorNumElements();
9146 unsigned SizeInBits = VT.getSizeInBits();
9147
9148 // Adjust IndicesVec to match VT size.
9149 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9150 "Illegal variable permute mask size");
9151 if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
9152 // Narrow/widen the indices vector to the correct size.
9153 if (IndicesVec.getValueSizeInBits() > SizeInBits)
9154 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9155 NumElts * VT.getScalarSizeInBits());
9156 else if (IndicesVec.getValueSizeInBits() < SizeInBits)
9157 IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
9158 SDLoc(IndicesVec), SizeInBits);
9159 // Zero-extend the index elements within the vector.
9160 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9161 IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
9162 IndicesVT, IndicesVec);
9163 }
9164 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9165
9166 // Handle SrcVec that don't match VT type.
9167 if (SrcVec.getValueSizeInBits() != SizeInBits) {
9168 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9169 // Handle larger SrcVec by treating it as a larger permute.
9170 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9171 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9172 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9173 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9174 Subtarget, DAG, SDLoc(IndicesVec));
9175 SDValue NewSrcVec =
9176 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9177 if (NewSrcVec)
9178 return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
9179 return SDValue();
9180 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9181 // Widen smaller SrcVec to match VT.
9182 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9183 } else
9184 return SDValue();
9185 }
9186
9187 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9188 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9189 EVT SrcVT = Idx.getValueType();
9190 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9191 uint64_t IndexScale = 0;
9192 uint64_t IndexOffset = 0;
9193
9194 // If we're scaling a smaller permute op, then we need to repeat the
9195 // indices, scaling and offsetting them as well.
9196 // e.g. v4i32 -> v16i8 (Scale = 4)
9197 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9198 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9199 for (uint64_t i = 0; i != Scale; ++i) {
9200 IndexScale |= Scale << (i * NumDstBits);
9201 IndexOffset |= i << (i * NumDstBits);
9202 }
9203
9204 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9205 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9206 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9207 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9208 return Idx;
9209 };
9210
9211 unsigned Opcode = 0;
9212 switch (VT.SimpleTy) {
9213 default:
9214 break;
9215 case MVT::v16i8:
9216 if (Subtarget.hasSSSE3())
9217 Opcode = X86ISD::PSHUFB;
9218 break;
9219 case MVT::v8i16:
9220 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9221 Opcode = X86ISD::VPERMV;
9222 else if (Subtarget.hasSSSE3()) {
9223 Opcode = X86ISD::PSHUFB;
9224 ShuffleVT = MVT::v16i8;
9225 }
9226 break;
9227 case MVT::v4f32:
9228 case MVT::v4i32:
9229 if (Subtarget.hasAVX()) {
9230 Opcode = X86ISD::VPERMILPV;
9231 ShuffleVT = MVT::v4f32;
9232 } else if (Subtarget.hasSSSE3()) {
9233 Opcode = X86ISD::PSHUFB;
9234 ShuffleVT = MVT::v16i8;
9235 }
9236 break;
9237 case MVT::v2f64:
9238 case MVT::v2i64:
9239 if (Subtarget.hasAVX()) {
9240 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
9241 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9242 Opcode = X86ISD::VPERMILPV;
9243 ShuffleVT = MVT::v2f64;
9244 } else if (Subtarget.hasSSE41()) {
9245 // SSE41 can compare v2i64 - select between indices 0 and 1.
9246 return DAG.getSelectCC(
9247 DL, IndicesVec,
9248 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
9249 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
9250 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
9252 }
9253 break;
9254 case MVT::v32i8:
9255 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
9256 Opcode = X86ISD::VPERMV;
9257 else if (Subtarget.hasXOP()) {
9258 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
9259 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
9260 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
9261 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
9262 return DAG.getNode(
9264 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
9265 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
9266 } else if (Subtarget.hasAVX()) {
9267 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
9268 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
9269 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
9270 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
9271 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
9273 // Permute Lo and Hi and then select based on index range.
9274 // This works as SHUFB uses bits[3:0] to permute elements and we don't
9275 // care about the bit[7] as its just an index vector.
9276 SDValue Idx = Ops[2];
9277 EVT VT = Idx.getValueType();
9278 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
9279 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
9280 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
9282 };
9283 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
9284 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
9285 PSHUFBBuilder);
9286 }
9287 break;
9288 case MVT::v16i16:
9289 if (Subtarget.hasVLX() && Subtarget.hasBWI())
9290 Opcode = X86ISD::VPERMV;
9291 else if (Subtarget.hasAVX()) {
9292 // Scale to v32i8 and perform as v32i8.
9293 IndicesVec = ScaleIndices(IndicesVec, 2);
9294 return DAG.getBitcast(
9296 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
9297 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
9298 }
9299 break;
9300 case MVT::v8f32:
9301 case MVT::v8i32:
9302 if (Subtarget.hasAVX2())
9303 Opcode = X86ISD::VPERMV;
9304 else if (Subtarget.hasAVX()) {
9305 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
9306 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9307 {0, 1, 2, 3, 0, 1, 2, 3});
9308 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9309 {4, 5, 6, 7, 4, 5, 6, 7});
9310 if (Subtarget.hasXOP())
9311 return DAG.getBitcast(
9312 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
9313 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9314 // Permute Lo and Hi and then select based on index range.
9315 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
9316 SDValue Res = DAG.getSelectCC(
9317 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
9318 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
9319 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
9321 return DAG.getBitcast(VT, Res);
9322 }
9323 break;
9324 case MVT::v4i64:
9325 case MVT::v4f64:
9326 if (Subtarget.hasAVX512()) {
9327 if (!Subtarget.hasVLX()) {
9328 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9329 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9330 SDLoc(SrcVec));
9331 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9332 DAG, SDLoc(IndicesVec));
9333 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9334 DAG, Subtarget);
9335 return extract256BitVector(Res, 0, DAG, DL);
9336 }
9337 Opcode = X86ISD::VPERMV;
9338 } else if (Subtarget.hasAVX()) {
9339 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9340 SDValue LoLo =
9341 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9342 SDValue HiHi =
9343 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9344 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
9345 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9346 if (Subtarget.hasXOP())
9347 return DAG.getBitcast(
9348 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
9349 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9350 // Permute Lo and Hi and then select based on index range.
9351 // This works as VPERMILPD only uses index bit[1] to permute elements.
9352 SDValue Res = DAG.getSelectCC(
9353 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
9354 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
9355 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
9357 return DAG.getBitcast(VT, Res);
9358 }
9359 break;
9360 case MVT::v64i8:
9361 if (Subtarget.hasVBMI())
9362 Opcode = X86ISD::VPERMV;
9363 break;
9364 case MVT::v32i16:
9365 if (Subtarget.hasBWI())
9366 Opcode = X86ISD::VPERMV;
9367 break;
9368 case MVT::v16f32:
9369 case MVT::v16i32:
9370 case MVT::v8f64:
9371 case MVT::v8i64:
9372 if (Subtarget.hasAVX512())
9373 Opcode = X86ISD::VPERMV;
9374 break;
9375 }
9376 if (!Opcode)
9377 return SDValue();
9378
9379 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
9380 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
9381 "Illegal variable permute shuffle type");
9382
9383 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
9384 if (Scale > 1)
9385 IndicesVec = ScaleIndices(IndicesVec, Scale);
9386
9387 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
9388 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
9389
9390 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
9391 SDValue Res = Opcode == X86ISD::VPERMV
9392 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
9393 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
9394 return DAG.getBitcast(VT, Res);
9395}
9396
9397// Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
9398// reasoned to be a permutation of a vector by indices in a non-constant vector.
9399// (build_vector (extract_elt V, (extract_elt I, 0)),
9400// (extract_elt V, (extract_elt I, 1)),
9401// ...
9402// ->
9403// (vpermv I, V)
9404//
9405// TODO: Handle undefs
9406// TODO: Utilize pshufb and zero mask blending to support more efficient
9407// construction of vectors with constant-0 elements.
9408static SDValue
9410 SelectionDAG &DAG,
9411 const X86Subtarget &Subtarget) {
9412 SDValue SrcVec, IndicesVec;
9413
9414 // Check for a match of the permute source vector and permute index elements.
9415 // This is done by checking that the i-th build_vector operand is of the form:
9416 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
9417 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
9418 SDValue Op = peekThroughOneUseFreeze(V.getOperand(Idx));
9419 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9420 return SDValue();
9421
9422 // If this is the first extract encountered in V, set the source vector,
9423 // otherwise verify the extract is from the previously defined source
9424 // vector.
9425 if (!SrcVec)
9426 SrcVec = Op.getOperand(0);
9427 else if (SrcVec != Op.getOperand(0))
9428 return SDValue();
9429 SDValue ExtractedIndex = Op->getOperand(1);
9430 // Peek through extends.
9431 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
9432 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
9433 ExtractedIndex = ExtractedIndex.getOperand(0);
9434 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9435 return SDValue();
9436
9437 // If this is the first extract from the index vector candidate, set the
9438 // indices vector, otherwise verify the extract is from the previously
9439 // defined indices vector.
9440 if (!IndicesVec)
9441 IndicesVec = ExtractedIndex.getOperand(0);
9442 else if (IndicesVec != ExtractedIndex.getOperand(0))
9443 return SDValue();
9444
9445 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
9446 if (!PermIdx || PermIdx->getAPIntValue() != Idx)
9447 return SDValue();
9448 }
9449
9450 MVT VT = V.getSimpleValueType();
9451 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9452}
9453
9454SDValue
9455X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
9456 SDLoc dl(Op);
9457
9458 MVT VT = Op.getSimpleValueType();
9459 MVT EltVT = VT.getVectorElementType();
9460 MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
9461 unsigned NumElems = Op.getNumOperands();
9462
9463 // Generate vectors for predicate vectors.
9464 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
9465 return LowerBUILD_VECTORvXi1(Op, dl, DAG, Subtarget);
9466
9467 if (VT.getVectorElementType() == MVT::bf16 &&
9468 (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16()))
9469 return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
9470
9471 if (SDValue VectorCst = materializeVectorConstant(Op, dl, DAG, Subtarget))
9472 return VectorCst;
9473
9474 unsigned EVTBits = EltVT.getSizeInBits();
9475 APInt UndefMask = APInt::getZero(NumElems);
9476 APInt FrozenUndefMask = APInt::getZero(NumElems);
9477 APInt ZeroMask = APInt::getZero(NumElems);
9478 APInt NonZeroMask = APInt::getZero(NumElems);
9479 bool IsAllConstants = true;
9480 bool OneUseFrozenUndefs = true;
9481 SmallSet<SDValue, 8> Values;
9482 unsigned NumConstants = NumElems;
9483 for (unsigned i = 0; i < NumElems; ++i) {
9484 SDValue Elt = Op.getOperand(i);
9485 if (Elt.isUndef()) {
9486 UndefMask.setBit(i);
9487 continue;
9488 }
9489 if (ISD::isFreezeUndef(Elt.getNode())) {
9490 OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
9491 FrozenUndefMask.setBit(i);
9492 continue;
9493 }
9494 Values.insert(Elt);
9495 if (!isIntOrFPConstant(Elt)) {
9496 IsAllConstants = false;
9497 NumConstants--;
9498 }
9499 if (X86::isZeroNode(Elt)) {
9500 ZeroMask.setBit(i);
9501 } else {
9502 NonZeroMask.setBit(i);
9503 }
9504 }
9505
9506 // All undef vector. Return an UNDEF.
9507 if (UndefMask.isAllOnes())
9508 return DAG.getUNDEF(VT);
9509
9510 // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
9511 if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
9512 return DAG.getFreeze(DAG.getUNDEF(VT));
9513
9514 // All undef/freeze(undef)/zero vector. Return a zero vector.
9515 if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
9516 return getZeroVector(VT, Subtarget, DAG, dl);
9517
9518 // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
9519 // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
9520 // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
9521 // and blend the FREEZE-UNDEF operands back in.
9522 // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
9523 if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
9524 NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
9525 SmallVector<int, 16> BlendMask(NumElems, -1);
9526 SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
9527 for (unsigned i = 0; i < NumElems; ++i) {
9528 if (UndefMask[i]) {
9529 BlendMask[i] = -1;
9530 continue;
9531 }
9532 BlendMask[i] = i;
9533 if (!FrozenUndefMask[i])
9534 Elts[i] = Op.getOperand(i);
9535 else
9536 BlendMask[i] += NumElems;
9537 }
9538 SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
9539 SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
9540 SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
9541 return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
9542 }
9543
9544 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9545
9546 // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
9547 // be better off lowering to a smaller build vector and padding with
9548 // undef/zero.
9549 if ((VT.is256BitVector() || VT.is512BitVector()) &&
9551 unsigned UpperElems = NumElems / 2;
9552 APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
9553 unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
9554 if (NumUpperUndefsOrZeros >= UpperElems) {
9555 if (VT.is512BitVector() &&
9556 NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
9557 UpperElems = NumElems - (NumElems / 4);
9558 // If freeze(undef) is in any upper elements, force to zero.
9559 bool UndefUpper = UndefMask.countl_one() >= UpperElems;
9560 MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
9561 SDValue NewBV =
9562 DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
9563 return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
9564 }
9565 }
9566
9567 if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, dl, Subtarget, DAG))
9568 return AddSub;
9569 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, dl, Subtarget, DAG))
9570 return Broadcast;
9571 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, dl, Subtarget, DAG))
9572 return BitOp;
9573 if (SDValue Blend = lowerBuildVectorAsBlend(BV, dl, Subtarget, DAG))
9574 return Blend;
9575 if (SDValue WideBV = widenBuildVector(BV, dl, Subtarget, DAG))
9576 return WideBV;
9577
9578 unsigned NumZero = ZeroMask.popcount();
9579 unsigned NumNonZero = NonZeroMask.popcount();
9580
9581 // If we are inserting one variable into a vector of non-zero constants, try
9582 // to avoid loading each constant element as a scalar. Load the constants as a
9583 // vector and then insert the variable scalar element. If insertion is not
9584 // supported, fall back to a shuffle to get the scalar blended with the
9585 // constants. Insertion into a zero vector is handled as a special-case
9586 // somewhere below here.
9587 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9588 FrozenUndefMask.isZero() &&
9591 // Create an all-constant vector. The variable element in the old
9592 // build vector is replaced by undef in the constant vector. Save the
9593 // variable scalar element and its index for use in the insertelement.
9594 LLVMContext &Context = *DAG.getContext();
9595 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9596 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9597 SDValue VarElt;
9598 SDValue InsIndex;
9599 for (unsigned i = 0; i != NumElems; ++i) {
9600 SDValue Elt = Op.getOperand(i);
9601 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9602 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9603 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9604 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9605 else if (!Elt.isUndef()) {
9606 assert(!VarElt.getNode() && !InsIndex.getNode() &&
9607 "Expected one variable element in this vector");
9608 VarElt = Elt;
9609 InsIndex = DAG.getVectorIdxConstant(i, dl);
9610 }
9611 }
9612 Constant *CV = ConstantVector::get(ConstVecOps);
9613 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9614
9615 // The constants we just created may not be legal (eg, floating point). We
9616 // must lower the vector right here because we can not guarantee that we'll
9617 // legalize it before loading it. This is also why we could not just create
9618 // a new build vector here. If the build vector contains illegal constants,
9619 // it could get split back up into a series of insert elements.
9620 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9621 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9622 MachineFunction &MF = DAG.getMachineFunction();
9623 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9624 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9625 unsigned InsertC = InsIndex->getAsZExtVal();
9626 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9627 if (InsertC < NumEltsInLow128Bits)
9628 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9629
9630 // There's no good way to insert into the high elements of a >128-bit
9631 // vector, so use shuffles to avoid an extract/insert sequence.
9632 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
9633 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
9634 SmallVector<int, 8> ShuffleMask;
9635 unsigned NumElts = VT.getVectorNumElements();
9636 for (unsigned i = 0; i != NumElts; ++i)
9637 ShuffleMask.push_back(i == InsertC ? NumElts : i);
9638 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9639 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9640 }
9641
9642 // Special case for single non-zero, non-undef, element.
9643 if (NumNonZero == 1) {
9644 unsigned Idx = NonZeroMask.countr_zero();
9645 SDValue Item = Op.getOperand(Idx);
9646
9647 // If we have a constant or non-constant insertion into the low element of
9648 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9649 // the rest of the elements. This will be matched as movd/movq/movss/movsd
9650 // depending on what the source datatype is.
9651 if (Idx == 0) {
9652 if (NumZero == 0)
9653 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9654
9655 if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
9656 EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
9657 (EltVT == MVT::i16 && Subtarget.hasFP16())) {
9658 assert((VT.is128BitVector() || VT.is256BitVector() ||
9659 VT.is512BitVector()) &&
9660 "Expected an SSE value type!");
9661 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9662 // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
9663 // zero vector.
9664 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9665 }
9666
9667 // We can't directly insert an i8 or i16 into a vector, so zero extend
9668 // it to i32 first.
9669 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9670 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9671 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
9672 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9673 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9674 return DAG.getBitcast(VT, Item);
9675 }
9676 }
9677
9678 // Is it a vector logical left shift?
9679 if (NumElems == 2 && Idx == 1 &&
9680 X86::isZeroNode(Op.getOperand(0)) &&
9681 !X86::isZeroNode(Op.getOperand(1))) {
9682 unsigned NumBits = VT.getSizeInBits();
9683 return getVShift(true, VT,
9685 VT, Op.getOperand(1)),
9686 NumBits/2, DAG, *this, dl);
9687 }
9688
9689 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9690 return SDValue();
9691
9692 // Otherwise, if this is a vector with i32 or f32 elements, and the element
9693 // is a non-constant being inserted into an element other than the low one,
9694 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
9695 // movd/movss) to move this into the low element, then shuffle it into
9696 // place.
9697 if (EVTBits == 32) {
9698 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9699 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9700 }
9701 }
9702
9703 // Splat is obviously ok. Let legalizer expand it to a shuffle.
9704 if (Values.size() == 1) {
9705 if (EVTBits == 32) {
9706 // Instead of a shuffle like this:
9707 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9708 // Check if it's possible to issue this instead.
9709 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9710 unsigned Idx = NonZeroMask.countr_zero();
9711 SDValue Item = Op.getOperand(Idx);
9712 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9713 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9714 }
9715 return SDValue();
9716 }
9717
9718 // A vector full of immediates; various special cases are already
9719 // handled, so this is best done with a single constant-pool load.
9720 if (IsAllConstants)
9721 return SDValue();
9722
9723 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, dl, DAG, Subtarget))
9724 return V;
9725
9726 // See if we can use a vector load to get all of the elements.
9727 {
9728 SmallVector<SDValue, 64> Ops(Op->ops().take_front(NumElems));
9729 if (SDValue LD =
9730 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9731 return LD;
9732 }
9733
9734 // If this is a splat of pairs of 32-bit elements, we can use a narrower
9735 // build_vector and broadcast it.
9736 // TODO: We could probably generalize this more.
9737 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9738 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9739 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9740 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9741 // Make sure all the even/odd operands match.
9742 for (unsigned i = 2; i != NumElems; ++i)
9743 if (Ops[i % 2] != Op.getOperand(i))
9744 return false;
9745 return true;
9746 };
9747 if (CanSplat(Op, NumElems, Ops)) {
9748 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9749 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9750 // Create a new build vector and cast to v2i64/v2f64.
9751 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9752 DAG.getBuildVector(NarrowVT, dl, Ops));
9753 // Broadcast from v2i64/v2f64 and cast to final VT.
9754 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
9755 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9756 NewBV));
9757 }
9758 }
9759
9760 // For AVX-length vectors, build the individual 128-bit pieces and use
9761 // shuffles to put them in place.
9762 if (VT.getSizeInBits() > 128) {
9763 MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
9764
9765 // Build both the lower and upper subvector.
9766 SDValue Lower =
9767 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9769 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9770
9771 // Recreate the wider vector with the lower and upper part.
9772 return concatSubVectors(Lower, Upper, DAG, dl);
9773 }
9774
9775 // Let legalizer expand 2-wide build_vectors.
9776 if (EVTBits == 64) {
9777 if (NumNonZero == 1) {
9778 // One half is zero or undef.
9779 unsigned Idx = NonZeroMask.countr_zero();
9780 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9781 Op.getOperand(Idx));
9782 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9783 }
9784 return SDValue();
9785 }
9786
9787 // If element VT is < 32 bits, convert it to inserts into a zero vector.
9788 if (EVTBits == 8 && NumElems == 16)
9789 if (SDValue V = LowerBuildVectorv16i8(Op, dl, NonZeroMask, NumNonZero,
9790 NumZero, DAG, Subtarget))
9791 return V;
9792
9793 if (EltVT == MVT::i16 && NumElems == 8)
9794 if (SDValue V = LowerBuildVectorv8i16(Op, dl, NonZeroMask, NumNonZero,
9795 NumZero, DAG, Subtarget))
9796 return V;
9797
9798 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9799 if (EVTBits == 32 && NumElems == 4)
9800 if (SDValue V = LowerBuildVectorv4x32(Op, dl, DAG, Subtarget))
9801 return V;
9802
9803 // If element VT is == 32 bits, turn it into a number of shuffles.
9804 if (NumElems == 4 && NumZero > 0) {
9805 SmallVector<SDValue, 8> Ops(NumElems);
9806 for (unsigned i = 0; i < 4; ++i) {
9807 bool isZero = !NonZeroMask[i];
9808 if (isZero)
9809 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9810 else
9811 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9812 }
9813
9814 for (unsigned i = 0; i < 2; ++i) {
9815 switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
9816 default: llvm_unreachable("Unexpected NonZero count");
9817 case 0:
9818 Ops[i] = Ops[i*2]; // Must be a zero vector.
9819 break;
9820 case 1:
9821 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9822 break;
9823 case 2:
9824 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9825 break;
9826 case 3:
9827 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9828 break;
9829 }
9830 }
9831
9832 bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
9833 bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
9834 int MaskVec[] = {
9835 Reverse1 ? 1 : 0,
9836 Reverse1 ? 0 : 1,
9837 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9838 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
9839 };
9840 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9841 }
9842
9843 assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9844
9845 // Check for a build vector from mostly shuffle plus few inserting.
9846 if (SDValue Sh = buildFromShuffleMostly(Op, dl, DAG))
9847 return Sh;
9848
9849 // For SSE 4.1, use insertps to put the high elements into the low element.
9850 if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
9852 if (!Op.getOperand(0).isUndef())
9853 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9854 else
9855 Result = DAG.getUNDEF(VT);
9856
9857 for (unsigned i = 1; i < NumElems; ++i) {
9858 if (Op.getOperand(i).isUndef()) continue;
9859 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9860 Op.getOperand(i), DAG.getVectorIdxConstant(i, dl));
9861 }
9862 return Result;
9863 }
9864
9865 // Otherwise, expand into a number of unpckl*, start by extending each of
9866 // our (non-undef) elements to the full vector width with the element in the
9867 // bottom slot of the vector (which generates no code for SSE).
9868 SmallVector<SDValue, 8> Ops(NumElems);
9869 for (unsigned i = 0; i < NumElems; ++i) {
9870 if (!Op.getOperand(i).isUndef())
9871 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9872 else
9873 Ops[i] = DAG.getUNDEF(VT);
9874 }
9875
9876 // Next, we iteratively mix elements, e.g. for v4f32:
9877 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9878 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9879 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
9880 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9881 // Generate scaled UNPCKL shuffle mask.
9882 SmallVector<int, 16> Mask;
9883 for(unsigned i = 0; i != Scale; ++i)
9884 Mask.push_back(i);
9885 for (unsigned i = 0; i != Scale; ++i)
9886 Mask.push_back(NumElems+i);
9887 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9888
9889 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9890 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9891 }
9892 return Ops[0];
9893}
9894
9895// 256-bit AVX can use the vinsertf128 instruction
9896// to create 256-bit vectors from two other 128-bit ones.
9897// TODO: Detect subvector broadcast here instead of DAG combine?
9899 SelectionDAG &DAG,
9900 const X86Subtarget &Subtarget) {
9901 MVT ResVT = Op.getSimpleValueType();
9902 assert((ResVT.is256BitVector() || ResVT.is512BitVector()) &&
9903 "Value type must be 256-/512-bit wide");
9904
9905 unsigned NumOperands = Op.getNumOperands();
9906 unsigned NumFreezeUndef = 0;
9907 unsigned NumZero = 0;
9908 unsigned NumNonZero = 0;
9909 unsigned NonZeros = 0;
9910 SmallSet<SDValue, 4> Undefs;
9911 for (unsigned i = 0; i != NumOperands; ++i) {
9912 SDValue SubVec = Op.getOperand(i);
9913 if (SubVec.isUndef())
9914 continue;
9915 if (ISD::isFreezeUndef(SubVec.getNode())) {
9916 // If the freeze(undef) has multiple uses then we must fold to zero.
9917 if (SubVec.hasOneUse()) {
9918 ++NumFreezeUndef;
9919 } else {
9920 ++NumZero;
9921 Undefs.insert(SubVec);
9922 }
9923 }
9924 else if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9925 ++NumZero;
9926 else {
9927 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9928 NonZeros |= 1 << i;
9929 ++NumNonZero;
9930 }
9931 }
9932
9933 // If we have more than 2 non-zeros, build each half separately.
9934 if (NumNonZero > 2) {
9935 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9936 ArrayRef<SDUse> Ops = Op->ops();
9937 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9938 Ops.slice(0, NumOperands/2));
9939 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9940 Ops.slice(NumOperands/2));
9941 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9942 }
9943
9944 // Otherwise, build it up through insert_subvectors.
9945 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9946 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
9947 : DAG.getUNDEF(ResVT));
9948
9949 // Replace Undef operands with ZeroVector.
9950 for (SDValue U : Undefs)
9952 U, getZeroVector(U.getSimpleValueType(), Subtarget, DAG, dl));
9953
9954 MVT SubVT = Op.getOperand(0).getSimpleValueType();
9955 unsigned NumSubElems = SubVT.getVectorNumElements();
9956 for (unsigned i = 0; i != NumOperands; ++i) {
9957 if ((NonZeros & (1 << i)) == 0)
9958 continue;
9959
9960 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(i),
9961 DAG.getVectorIdxConstant(i * NumSubElems, dl));
9962 }
9963
9964 return Vec;
9965}
9966
9967// Returns true if the given node is a type promotion (by concatenating i1
9968// zeros) of the result of a node that already zeros all upper bits of
9969// k-register.
9970// TODO: Merge this with LowerAVXCONCAT_VECTORS?
9972 const X86Subtarget &Subtarget,
9973 SelectionDAG & DAG) {
9974 MVT ResVT = Op.getSimpleValueType();
9975 unsigned NumOperands = Op.getNumOperands();
9976 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9977 "Unexpected number of operands in CONCAT_VECTORS");
9978
9979 uint64_t Zeros = 0;
9980 uint64_t NonZeros = 0;
9981 for (unsigned i = 0; i != NumOperands; ++i) {
9982 SDValue SubVec = Op.getOperand(i);
9983 if (SubVec.isUndef())
9984 continue;
9985 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9986 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9987 Zeros |= (uint64_t)1 << i;
9988 else
9989 NonZeros |= (uint64_t)1 << i;
9990 }
9991
9992 unsigned NumElems = ResVT.getVectorNumElements();
9993
9994 // If we are inserting non-zero vector and there are zeros in LSBs and undef
9995 // in the MSBs we need to emit a KSHIFTL. The generic lowering to
9996 // insert_subvector will give us two kshifts.
9997 if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
9998 Log2_64(NonZeros) != NumOperands - 1) {
9999 unsigned Idx = Log2_64(NonZeros);
10000 SDValue SubVec = Op.getOperand(Idx);
10001 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10002 MVT ShiftVT = widenMaskVectorType(ResVT, Subtarget);
10003 Op = widenSubVector(ShiftVT, SubVec, false, Subtarget, DAG, dl);
10004 Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, Op,
10005 DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10006 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10007 DAG.getVectorIdxConstant(0, dl));
10008 }
10009
10010 // If there are zero or one non-zeros we can handle this very simply.
10011 if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10012 SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10013 if (!NonZeros)
10014 return Vec;
10015 unsigned Idx = Log2_64(NonZeros);
10016 SDValue SubVec = Op.getOperand(Idx);
10017 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10018 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10019 DAG.getVectorIdxConstant(Idx * SubVecNumElts, dl));
10020 }
10021
10022 if (NumOperands > 2) {
10023 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10024 ArrayRef<SDUse> Ops = Op->ops();
10025 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10026 Ops.slice(0, NumOperands / 2));
10027 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10028 Ops.slice(NumOperands / 2));
10029 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10030 }
10031
10032 assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
10033
10034 if (ResVT.getVectorNumElements() >= 16)
10035 return Op; // The operation is legal with KUNPCK
10036
10037 SDValue Vec =
10038 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, DAG.getUNDEF(ResVT),
10039 Op.getOperand(0), DAG.getVectorIdxConstant(0, dl));
10040 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10041 DAG.getVectorIdxConstant(NumElems / 2, dl));
10042}
10043
10045 const X86Subtarget &Subtarget,
10046 SelectionDAG &DAG) {
10047 SDLoc DL(Op);
10048 MVT VT = Op.getSimpleValueType();
10049 if (VT.getVectorElementType() == MVT::i1)
10050 return LowerCONCAT_VECTORSvXi1(Op, DL, Subtarget, DAG);
10051
10052 // AVX can use the vinsertf128 instruction to create 256-bit vectors
10053 // from two other 128-bit ones.
10054 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10055 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10056 (VT.is512BitVector() &&
10057 (Op.getNumOperands() == 2 || Op.getNumOperands() == 4)));
10058 return LowerAVXCONCAT_VECTORS(Op, DL, DAG, Subtarget);
10059}
10060
10061//===----------------------------------------------------------------------===//
10062// Vector shuffle lowering
10063//
10064// This is an experimental code path for lowering vector shuffles on x86. It is
10065// designed to handle arbitrary vector shuffles and blends, gracefully
10066// degrading performance as necessary. It works hard to recognize idiomatic
10067// shuffles and lower them to optimal instruction patterns without leaving
10068// a framework that allows reasonably efficient handling of all vector shuffle
10069// patterns.
10070//===----------------------------------------------------------------------===//
10071
10072/// Checks whether the vector elements referenced by two shuffle masks are
10073/// equivalent.
10074static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
10075 int Idx, int ExpectedIdx) {
10076 assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
10077 ExpectedIdx < MaskSize && "Out of range element index");
10078 if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
10079 return false;
10080
10081 EVT VT = Op.getValueType();
10082 EVT ExpectedVT = ExpectedOp.getValueType();
10083
10084 // Sources must be vectors and match the mask's element count.
10085 if (!VT.isVector() || !ExpectedVT.isVector() ||
10086 (int)VT.getVectorNumElements() != MaskSize ||
10087 (int)ExpectedVT.getVectorNumElements() != MaskSize)
10088 return false;
10089
10090 // Exact match.
10091 if (Idx == ExpectedIdx && Op == ExpectedOp)
10092 return true;
10093
10094 switch (Op.getOpcode()) {
10095 case ISD::BUILD_VECTOR:
10096 // If the values are build vectors, we can look through them to find
10097 // equivalent inputs that make the shuffles equivalent.
10098 return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
10099 case ISD::BITCAST: {
10101 EVT SrcVT = Src.getValueType();
10102 if (Op == ExpectedOp && SrcVT.isVector()) {
10103 if ((SrcVT.getScalarSizeInBits() % VT.getScalarSizeInBits()) == 0) {
10104 unsigned Scale = SrcVT.getScalarSizeInBits() / VT.getScalarSizeInBits();
10105 return (Idx % Scale) == (ExpectedIdx % Scale) &&
10106 IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10107 Idx / Scale, ExpectedIdx / Scale);
10108 }
10109 if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0) {
10110 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
10111 for (unsigned I = 0; I != Scale; ++I)
10112 if (!IsElementEquivalent(SrcVT.getVectorNumElements(), Src, Src,
10113 (Idx * Scale) + I,
10114 (ExpectedIdx * Scale) + I))
10115 return false;
10116 return true;
10117 }
10118 }
10119 break;
10120 }
10121 case ISD::VECTOR_SHUFFLE: {
10122 auto *SVN = cast<ShuffleVectorSDNode>(Op);
10123 return Op == ExpectedOp &&
10124 SVN->getMaskElt(Idx) == SVN->getMaskElt(ExpectedIdx);
10125 }
10126 case X86ISD::VBROADCAST:
10127 case X86ISD::VBROADCAST_LOAD:
10128 return Op == ExpectedOp;
10129 case X86ISD::SUBV_BROADCAST_LOAD:
10130 if (Op == ExpectedOp) {
10131 auto *MemOp = cast<MemSDNode>(Op);
10132 unsigned NumMemElts = MemOp->getMemoryVT().getVectorNumElements();
10133 return (Idx % NumMemElts) == (ExpectedIdx % NumMemElts);
10134 }
10135 break;
10136 case X86ISD::VPERMI: {
10137 if (Op == ExpectedOp) {
10139 DecodeVPERMMask(MaskSize, Op.getConstantOperandVal(1), Mask);
10140 SDValue Src = Op.getOperand(0);
10141 return IsElementEquivalent(MaskSize, Src, Src, Mask[Idx],
10142 Mask[ExpectedIdx]);
10143 }
10144 break;
10145 }
10146 case X86ISD::HADD:
10147 case X86ISD::HSUB:
10148 case X86ISD::FHADD:
10149 case X86ISD::FHSUB:
10150 case X86ISD::PACKSS:
10151 case X86ISD::PACKUS:
10152 // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
10153 // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
10154 if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
10155 int NumElts = VT.getVectorNumElements();
10156 int NumLanes = VT.getSizeInBits() / 128;
10157 int NumEltsPerLane = NumElts / NumLanes;
10158 int NumHalfEltsPerLane = NumEltsPerLane / 2;
10159 bool SameLane = (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
10160 bool SameElt =
10161 (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
10162 return SameLane && SameElt;
10163 }
10164 break;
10165 }
10166
10167 return false;
10168}
10169
10170/// Tiny helper function to identify a no-op mask.
10171///
10172/// This is a somewhat boring predicate function. It checks whether the mask
10173/// array input, which is assumed to be a single-input shuffle mask of the kind
10174/// used by the X86 shuffle instructions (not a fully general
10175/// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10176/// in-place shuffle are 'no-op's.
10178 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10179 assert(Mask[i] >= -1 && "Out of bound mask element!");
10180 if (Mask[i] >= 0 && Mask[i] != i)
10181 return false;
10182 }
10183 return true;
10184}
10185
10186/// Test whether there are elements crossing LaneSizeInBits lanes in this
10187/// shuffle mask.
10188///
10189/// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10190/// and we routinely test for these.
10191static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10192 unsigned ScalarSizeInBits,
10193 ArrayRef<int> Mask) {
10194 assert(LaneSizeInBits && ScalarSizeInBits &&
10195 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10196 "Illegal shuffle lane size");
10197 int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10198 int Size = Mask.size();
10199 for (int i = 0; i < Size; ++i)
10200 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10201 return true;
10202 return false;
10203}
10204
10205/// Test whether there are elements crossing 128-bit lanes in this
10206/// shuffle mask.
10208 return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10209}
10210
10211/// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
10212/// from multiple lanes - this is different to isLaneCrossingShuffleMask to
10213/// better support 'repeated mask + lane permute' style shuffles.
10214static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
10215 unsigned ScalarSizeInBits,
10216 ArrayRef<int> Mask) {
10217 assert(LaneSizeInBits && ScalarSizeInBits &&
10218 (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10219 "Illegal shuffle lane size");
10220 int NumElts = Mask.size();
10221 int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
10222 int NumLanes = NumElts / NumEltsPerLane;
10223 if (NumLanes > 1) {
10224 for (int i = 0; i != NumLanes; ++i) {
10225 int SrcLane = -1;
10226 for (int j = 0; j != NumEltsPerLane; ++j) {
10227 int M = Mask[(i * NumEltsPerLane) + j];
10228 if (M < 0)
10229 continue;
10230 int Lane = (M % NumElts) / NumEltsPerLane;
10231 if (SrcLane >= 0 && SrcLane != Lane)
10232 return true;
10233 SrcLane = Lane;
10234 }
10235 }
10236 }
10237 return false;
10238}
10239
10240/// Test whether a shuffle mask is equivalent within each sub-lane.
10241///
10242/// This checks a shuffle mask to see if it is performing the same
10243/// lane-relative shuffle in each sub-lane. This trivially implies
10244/// that it is also not lane-crossing. It may however involve a blend from the
10245/// same lane of a second vector.
10246///
10247/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10248/// non-trivial to compute in the face of undef lanes. The representation is
10249/// suitable for use with existing 128-bit shuffles as entries from the second
10250/// vector have been remapped to [LaneSize, 2*LaneSize).
10251static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10252 ArrayRef<int> Mask,
10253 SmallVectorImpl<int> &RepeatedMask) {
10254 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10255 RepeatedMask.assign(LaneSize, -1);
10256 int Size = Mask.size();
10257 for (int i = 0; i < Size; ++i) {
10258 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10259 if (Mask[i] < 0)
10260 continue;
10261 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10262 // This entry crosses lanes, so there is no way to model this shuffle.
10263 return false;
10264
10265 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10266 // Adjust second vector indices to start at LaneSize instead of Size.
10267 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10268 : Mask[i] % LaneSize + LaneSize;
10269 if (RepeatedMask[i % LaneSize] < 0)
10270 // This is the first non-undef entry in this slot of a 128-bit lane.
10271 RepeatedMask[i % LaneSize] = LocalM;
10272 else if (RepeatedMask[i % LaneSize] != LocalM)
10273 // Found a mismatch with the repeated mask.
10274 return false;
10275 }
10276 return true;
10277}
10278
10279/// Test whether a shuffle mask is equivalent within each 128-bit lane.
10280static bool
10282 SmallVectorImpl<int> &RepeatedMask) {
10283 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10284}
10285
10286static bool
10288 SmallVector<int, 32> RepeatedMask;
10289 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10290}
10291
10292/// Test whether a shuffle mask is equivalent within each 256-bit lane.
10293static bool
10295 SmallVectorImpl<int> &RepeatedMask) {
10296 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10297}
10298
10299/// Test whether a target shuffle mask is equivalent within each sub-lane.
10300/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10301static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
10302 unsigned EltSizeInBits,
10303 ArrayRef<int> Mask,
10304 SmallVectorImpl<int> &RepeatedMask) {
10305 int LaneSize = LaneSizeInBits / EltSizeInBits;
10306 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10307 int Size = Mask.size();
10308 for (int i = 0; i < Size; ++i) {
10309 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10310 if (Mask[i] == SM_SentinelUndef)
10311 continue;
10312 if (Mask[i] == SM_SentinelZero) {
10313 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10314 return false;
10315 RepeatedMask[i % LaneSize] = SM_SentinelZero;
10316 continue;
10317 }
10318 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10319 // This entry crosses lanes, so there is no way to model this shuffle.
10320 return false;
10321
10322 // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
10323 // later vector indices to start at multiples of LaneSize instead of Size.
10324 int LaneM = Mask[i] / Size;
10325 int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
10326 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10327 // This is the first non-undef entry in this slot of a 128-bit lane.
10328 RepeatedMask[i % LaneSize] = LocalM;
10329 else if (RepeatedMask[i % LaneSize] != LocalM)
10330 // Found a mismatch with the repeated mask.
10331 return false;
10332 }
10333 return true;
10334}
10335
10336/// Test whether a target shuffle mask is equivalent within each sub-lane.
10337/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10338static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10339 ArrayRef<int> Mask,
10340 SmallVectorImpl<int> &RepeatedMask) {
10341 return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
10342 Mask, RepeatedMask);
10343}
10344
10345/// Checks whether a shuffle mask is equivalent to an explicit list of
10346/// arguments.
10347///
10348/// This is a fast way to test a shuffle mask against a fixed pattern:
10349///
10350/// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
10351///
10352/// It returns true if the mask is exactly as wide as the argument list, and
10353/// each element of the mask is either -1 (signifying undef) or the value given
10354/// in the argument.
10355static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
10356 SDValue V1 = SDValue(),
10357 SDValue V2 = SDValue()) {
10358 int Size = Mask.size();
10359 if (Size != (int)ExpectedMask.size())
10360 return false;
10361
10362 for (int i = 0; i < Size; ++i) {
10363 assert(Mask[i] >= -1 && "Out of bound mask element!");
10364 int MaskIdx = Mask[i];
10365 int ExpectedIdx = ExpectedMask[i];
10366 if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
10367 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10368 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10369 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10370 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10371 if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10372 return false;
10373 }
10374 }
10375 return true;
10376}
10377
10378/// Checks whether a target shuffle mask is equivalent to an explicit pattern.
10379///
10380/// The masks must be exactly the same width.
10381///
10382/// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
10383/// value in ExpectedMask is always accepted. Otherwise the indices must match.
10384///
10385/// SM_SentinelZero is accepted as a valid negative index but must match in
10386/// both, or via a known bits test.
10388 ArrayRef<int> ExpectedMask,
10389 const SelectionDAG &DAG,
10390 SDValue V1 = SDValue(),
10391 SDValue V2 = SDValue()) {
10392 int Size = Mask.size();
10393 if (Size != (int)ExpectedMask.size())
10394 return false;
10395 assert(llvm::all_of(ExpectedMask,
10396 [Size](int M) {
10397 return M == SM_SentinelZero ||
10398 isInRange(M, 0, 2 * Size);
10399 }) &&
10400 "Illegal target shuffle mask");
10401
10402 // Check for out-of-range target shuffle mask indices.
10403 if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
10404 return false;
10405
10406 // Don't use V1/V2 if they're not the same size as the shuffle mask type.
10407 if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
10408 !V1.getValueType().isVector()))
10409 V1 = SDValue();
10410 if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
10411 !V2.getValueType().isVector()))
10412 V2 = SDValue();
10413
10414 APInt ZeroV1 = APInt::getZero(Size);
10415 APInt ZeroV2 = APInt::getZero(Size);
10416
10417 for (int i = 0; i < Size; ++i) {
10418 int MaskIdx = Mask[i];
10419 int ExpectedIdx = ExpectedMask[i];
10420 if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
10421 continue;
10422 // If we failed to match an expected SM_SentinelZero then early out.
10423 if (ExpectedIdx < 0)
10424 return false;
10425 if (MaskIdx == SM_SentinelZero) {
10426 // If we need this expected index to be a zero element, then update the
10427 // relevant zero mask and perform the known bits at the end to minimize
10428 // repeated computes.
10429 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10430 if (ExpectedV &&
10431 Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
10432 int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10433 APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
10434 ZeroMask.setBit(BitIdx);
10435 continue;
10436 }
10437 }
10438 if (MaskIdx >= 0) {
10439 SDValue MaskV = MaskIdx < Size ? V1 : V2;
10440 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
10441 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
10442 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
10443 if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
10444 continue;
10445 }
10446 return false;
10447 }
10448 return (ZeroV1.isZero() || DAG.MaskedVectorIsZero(V1, ZeroV1)) &&
10449 (ZeroV2.isZero() || DAG.MaskedVectorIsZero(V2, ZeroV2));
10450}
10451
10452// Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
10453// instructions.
10455 const SelectionDAG &DAG) {
10456 if (VT != MVT::v8i32 && VT != MVT::v8f32)
10457 return false;
10458
10459 SmallVector<int, 8> Unpcklwd;
10460 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
10461 /* Unary = */ false);
10462 SmallVector<int, 8> Unpckhwd;
10463 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
10464 /* Unary = */ false);
10465 bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
10466 isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
10467 return IsUnpackwdMask;
10468}
10469
10471 const SelectionDAG &DAG) {
10472 // Create 128-bit vector type based on mask size.
10473 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
10474 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
10475
10476 // We can't assume a canonical shuffle mask, so try the commuted version too.
10477 SmallVector<int, 4> CommutedMask(Mask);
10479
10480 // Match any of unary/binary or low/high.
10481 for (unsigned i = 0; i != 4; ++i) {
10482 SmallVector<int, 16> UnpackMask;
10483 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
10484 if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
10485 isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
10486 return true;
10487 }
10488 return false;
10489}
10490
10491/// Return true if a shuffle mask chooses elements identically in its top and
10492/// bottom halves. For example, any splat mask has the same top and bottom
10493/// halves. If an element is undefined in only one half of the mask, the halves
10494/// are not considered identical.
10496 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
10497 unsigned HalfSize = Mask.size() / 2;
10498 for (unsigned i = 0; i != HalfSize; ++i) {
10499 if (Mask[i] != Mask[i + HalfSize])
10500 return false;
10501 }
10502 return true;
10503}
10504
10505/// Get a 4-lane 8-bit shuffle immediate for a mask.
10506///
10507/// This helper function produces an 8-bit shuffle immediate corresponding to
10508/// the ubiquitous shuffle encoding scheme used in x86 instructions for
10509/// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10510/// example.
10511///
10512/// NB: We rely heavily on "undef" masks preserving the input lane.
10513static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10514 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
10515 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
10516 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
10517 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
10518 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
10519
10520 // If the mask only uses one non-undef element, then fully 'splat' it to
10521 // improve later broadcast matching.
10522 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10523 assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
10524
10525 int FirstElt = Mask[FirstIndex];
10526 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
10527 return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
10528
10529 unsigned Imm = 0;
10530 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10531 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10532 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10533 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10534 return Imm;
10535}
10536
10538 SelectionDAG &DAG) {
10539 return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10540}
10541
10542// Canonicalize SHUFPD mask to improve chances of further folding.
10543// Mask elements are assumed to be -1, 0 or 1 to match the SHUFPD lo/hi pattern.
10544static unsigned getSHUFPDImm(ArrayRef<int> Mask) {
10545 assert((Mask.size() == 2 || Mask.size() == 4 || Mask.size() == 8) &&
10546 "Unexpected SHUFPD mask size");
10547 assert(all_of(Mask, [](int M) { return -1 <= M && M <= 1; }) &&
10548 "Unexpected SHUFPD mask elements");
10549
10550 // If the mask only uses one non-undef element, then fully 'splat' it to
10551 // improve later broadcast matching.
10552 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
10553 assert(0 <= FirstIndex && FirstIndex < (int)Mask.size() &&
10554 "All undef shuffle mask");
10555
10556 int FirstElt = Mask[FirstIndex];
10557 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }) &&
10558 count_if(Mask, [FirstElt](int M) { return M == FirstElt; }) > 1) {
10559 unsigned Imm = 0;
10560 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10561 Imm |= FirstElt << I;
10562 return Imm;
10563 }
10564
10565 // Attempt to keep any undef elements in place to improve chances of the
10566 // shuffle becoming a (commutative) blend.
10567 unsigned Imm = 0;
10568 for (unsigned I = 0, E = Mask.size(); I != E; ++I)
10569 Imm |= (Mask[I] < 0 ? (I & 1) : Mask[I]) << I;
10570
10571 return Imm;
10572}
10573
10575 SelectionDAG &DAG) {
10576 return DAG.getTargetConstant(getSHUFPDImm(Mask), DL, MVT::i8);
10577}
10578
10579// The Shuffle result is as follow:
10580// 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10581// Each Zeroable's element correspond to a particular Mask's element.
10582// As described in computeZeroableShuffleElements function.
10583//
10584// The function looks for a sub-mask that the nonzero elements are in
10585// increasing order. If such sub-mask exist. The function returns true.
10586static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10587 ArrayRef<int> Mask, const EVT &VectorType,
10588 bool &IsZeroSideLeft) {
10589 int NextElement = -1;
10590 // Check if the Mask's nonzero elements are in increasing order.
10591 for (int i = 0, e = Mask.size(); i < e; i++) {
10592 // Checks if the mask's zeros elements are built from only zeros.
10593 assert(Mask[i] >= -1 && "Out of bound mask element!");
10594 if (Mask[i] < 0)
10595 return false;
10596 if (Zeroable[i])
10597 continue;
10598 // Find the lowest non zero element
10599 if (NextElement < 0) {
10600 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10601 IsZeroSideLeft = NextElement != 0;
10602 }
10603 // Exit if the mask's non zero elements are not in increasing order.
10604 if (NextElement != Mask[i])
10605 return false;
10606 NextElement++;
10607 }
10608 return true;
10609}
10610
10611static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
10613 const X86Subtarget &Subtarget,
10614 unsigned Depth = 0);
10615
10616/// Try to lower a shuffle with a single PSHUFB of V1 or V2.
10618 ArrayRef<int> Mask, SDValue V1,
10619 SDValue V2, const APInt &Zeroable,
10620 const X86Subtarget &Subtarget,
10621 SelectionDAG &DAG) {
10622 int Size = Mask.size();
10623 int LaneSize = 128 / VT.getScalarSizeInBits();
10624 const int NumBytes = VT.getSizeInBits() / 8;
10625 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10626
10627 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
10628 (Subtarget.hasAVX2() && VT.is256BitVector()) ||
10629 (Subtarget.hasBWI() && VT.is512BitVector()));
10630
10631 SmallVector<int, 64> PSHUFBMask(NumBytes, -1);
10632 SDValue V;
10633 for (int i = 0; i < NumBytes; ++i) {
10634 int M = Mask[i / NumEltBytes];
10635 if (M < 0)
10636 continue;
10637
10638 if (Zeroable[i / NumEltBytes]) {
10639 // Sign bit set in i8 mask means zero element.
10640 PSHUFBMask[i] = 0x80;
10641 continue;
10642 }
10643
10644 // We can only use a single input of V1 or V2.
10645 SDValue SrcV = (M >= Size ? V2 : V1);
10646 if (V && V != SrcV)
10647 return SDValue();
10648 V = SrcV;
10649 M %= Size;
10650
10651 // PSHUFB can't cross lanes, ensure this doesn't happen.
10652 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10653 return SDValue();
10654
10655 M = M % LaneSize;
10656 M = M * NumEltBytes + (i % NumEltBytes);
10657 PSHUFBMask[i] = M;
10658 }
10659 assert(V && "Failed to find a source input");
10660
10661 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10662 SDValue R = getConstVector(PSHUFBMask, I8VT, DAG, DL, /*IsMask=*/true);
10663 R = DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V), R);
10664 return DAG.getBitcast(VT, R);
10665}
10666
10667/// Return Mask with the necessary casting or extending
10668/// for \p Mask according to \p MaskVT when lowering masking intrinsics
10669static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10670 const X86Subtarget &Subtarget, SelectionDAG &DAG,
10671 const SDLoc &dl) {
10672 MVT SrcVT = Mask.getSimpleValueType();
10673 assert(SrcVT.isScalarInteger() && "Expected scalar integer mask source!");
10674 assert(MaskVT.bitsLE(SrcVT) && "Unexpected mask size!");
10675 assert(MaskVT.getVectorElementType() == MVT::i1 && "Bool vector expected!");
10676
10677 if (isAllOnesConstant(Mask))
10678 return DAG.getConstant(1, dl, MaskVT);
10679 if (X86::isZeroNode(Mask))
10680 return DAG.getConstant(0, dl, MaskVT);
10681
10682 // Attempt to pre-truncate the mask source (to a minimum of i8).
10683 if (SrcVT.getSizeInBits() > MaskVT.getVectorNumElements()) {
10684 SrcVT = MVT::getIntegerVT(std::max((int)MaskVT.getVectorNumElements(), 8));
10685 Mask = DAG.getNode(ISD::TRUNCATE, dl, SrcVT, Mask);
10686 }
10687
10688 if (SrcVT == MVT::i64 && Subtarget.is32Bit()) {
10689 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
10690 assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
10691 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
10692 SDValue Lo, Hi;
10693 std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
10694 Lo = DAG.getBitcast(MVT::v32i1, Lo);
10695 Hi = DAG.getBitcast(MVT::v32i1, Hi);
10696 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
10697 }
10698
10699 MVT BitcastVT = MVT::getVectorVT(MVT::i1, SrcVT.getSizeInBits());
10700 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
10701 // are extracted by EXTRACT_SUBVECTOR.
10702 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
10703 DAG.getBitcast(BitcastVT, Mask),
10704 DAG.getVectorIdxConstant(0, dl));
10705}
10706
10707// X86 has dedicated shuffle that can be lowered to VEXPAND
10709 SDValue V2, ArrayRef<int> Mask,
10710 const APInt &Zeroable,
10711 const X86Subtarget &Subtarget,
10712 SelectionDAG &DAG) {
10713 bool IsLeftZeroSide = true;
10714 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10715 IsLeftZeroSide))
10716 return SDValue();
10717 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10719 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10720 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10721 unsigned NumElts = VT.getVectorNumElements();
10722 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
10723 "Unexpected number of vector elements");
10724 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10725 Subtarget, DAG, DL);
10726 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10727 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10728 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10729}
10730
10732 unsigned &UnpackOpcode, bool IsUnary,
10733 ArrayRef<int> TargetMask, const SDLoc &DL,
10734 SelectionDAG &DAG,
10735 const X86Subtarget &Subtarget) {
10736 int NumElts = VT.getVectorNumElements();
10737
10738 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10739 for (int i = 0; i != NumElts; i += 2) {
10740 int M1 = TargetMask[i + 0];
10741 int M2 = TargetMask[i + 1];
10742 Undef1 &= (SM_SentinelUndef == M1);
10743 Undef2 &= (SM_SentinelUndef == M2);
10744 Zero1 &= isUndefOrZero(M1);
10745 Zero2 &= isUndefOrZero(M2);
10746 }
10747 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
10748 "Zeroable shuffle detected");
10749
10750 // Attempt to match the target mask against the unpack lo/hi mask patterns.
10751 SmallVector<int, 64> Unpckl, Unpckh;
10752 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10753 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
10754 (IsUnary ? V1 : V2))) {
10755 UnpackOpcode = X86ISD::UNPCKL;
10756 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10757 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10758 return true;
10759 }
10760
10761 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10762 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
10763 (IsUnary ? V1 : V2))) {
10764 UnpackOpcode = X86ISD::UNPCKH;
10765 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10766 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10767 return true;
10768 }
10769
10770 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10771 if (IsUnary && (Zero1 || Zero2)) {
10772 // Don't bother if we can blend instead.
10773 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10774 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10775 return false;
10776
10777 bool MatchLo = true, MatchHi = true;
10778 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10779 int M = TargetMask[i];
10780
10781 // Ignore if the input is known to be zero or the index is undef.
10782 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10783 (M == SM_SentinelUndef))
10784 continue;
10785
10786 MatchLo &= (M == Unpckl[i]);
10787 MatchHi &= (M == Unpckh[i]);
10788 }
10789
10790 if (MatchLo || MatchHi) {
10791 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10792 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10793 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10794 return true;
10795 }
10796 }
10797
10798 // If a binary shuffle, commute and try again.
10799 if (!IsUnary) {
10801 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
10802 UnpackOpcode = X86ISD::UNPCKL;
10803 std::swap(V1, V2);
10804 return true;
10805 }
10806
10808 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
10809 UnpackOpcode = X86ISD::UNPCKH;
10810 std::swap(V1, V2);
10811 return true;
10812 }
10813 }
10814
10815 return false;
10816}
10817
10818// X86 has dedicated unpack instructions that can handle specific blend
10819// operations: UNPCKH and UNPCKL.
10821 SDValue V2, ArrayRef<int> Mask,
10822 SelectionDAG &DAG) {
10823 SmallVector<int, 8> Unpckl;
10824 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10825 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10826 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10827
10828 SmallVector<int, 8> Unpckh;
10829 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10830 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10831 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10832
10833 // Commute and try again.
10835 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10836 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10837
10839 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10840 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10841
10842 return SDValue();
10843}
10844
10845/// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
10846/// followed by unpack 256-bit.
10848 SDValue V2, ArrayRef<int> Mask,
10849 SelectionDAG &DAG) {
10850 SmallVector<int, 32> Unpckl, Unpckh;
10851 createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
10852 createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
10853
10854 unsigned UnpackOpcode;
10855 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
10856 UnpackOpcode = X86ISD::UNPCKL;
10857 else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
10858 UnpackOpcode = X86ISD::UNPCKH;
10859 else
10860 return SDValue();
10861
10862 // This is a "natural" unpack operation (rather than the 128-bit sectored
10863 // operation implemented by AVX). We need to rearrange 64-bit chunks of the
10864 // input in order to use the x86 instruction.
10865 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
10866 DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
10867 V1 = DAG.getBitcast(VT, V1);
10868 return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
10869}
10870
10871// Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
10872// source into the lower elements and zeroing the upper elements.
10873static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
10874 ArrayRef<int> Mask, const APInt &Zeroable,
10875 const X86Subtarget &Subtarget) {
10876 if (!VT.is512BitVector() && !Subtarget.hasVLX())
10877 return false;
10878
10879 unsigned NumElts = Mask.size();
10880 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10881 unsigned MaxScale = 64 / EltSizeInBits;
10882
10883 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10884 unsigned SrcEltBits = EltSizeInBits * Scale;
10885 if (SrcEltBits < 32 && !Subtarget.hasBWI())
10886 continue;
10887 unsigned NumSrcElts = NumElts / Scale;
10888 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
10889 continue;
10890 unsigned UpperElts = NumElts - NumSrcElts;
10891 if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10892 continue;
10893 SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
10894 SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
10895 DstVT = MVT::getIntegerVT(EltSizeInBits);
10896 if ((NumSrcElts * EltSizeInBits) >= 128) {
10897 // ISD::TRUNCATE
10898 DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
10899 } else {
10900 // X86ISD::VTRUNC
10901 DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
10902 }
10903 return true;
10904 }
10905
10906 return false;
10907}
10908
10909// Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
10910// element padding to the final DstVT.
10911static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
10912 const X86Subtarget &Subtarget,
10913 SelectionDAG &DAG, bool ZeroUppers) {
10914 MVT SrcVT = Src.getSimpleValueType();
10915 MVT DstSVT = DstVT.getScalarType();
10916 unsigned NumDstElts = DstVT.getVectorNumElements();
10917 unsigned NumSrcElts = SrcVT.getVectorNumElements();
10918 unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
10919
10920 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
10921 return SDValue();
10922
10923 // Perform a direct ISD::TRUNCATE if possible.
10924 if (NumSrcElts == NumDstElts)
10925 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
10926
10927 if (NumSrcElts > NumDstElts) {
10928 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10929 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10930 return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
10931 }
10932
10933 if ((NumSrcElts * DstEltSizeInBits) >= 128) {
10934 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
10935 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
10936 return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10937 DstVT.getSizeInBits());
10938 }
10939
10940 // Non-VLX targets must truncate from a 512-bit type, so we need to
10941 // widen, truncate and then possibly extract the original subvector.
10942 if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
10943 SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
10944 return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
10945 }
10946
10947 // Fallback to a X86ISD::VTRUNC, padding if necessary.
10948 MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
10949 SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
10950 if (DstVT != TruncVT)
10951 Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
10952 DstVT.getSizeInBits());
10953 return Trunc;
10954}
10955
10956// Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10957//
10958// An example is the following:
10959//
10960// t0: ch = EntryToken
10961// t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10962// t25: v4i32 = truncate t2
10963// t41: v8i16 = bitcast t25
10964// t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10965// Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10966// t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10967// t18: v2i64 = bitcast t51
10968//
10969// One can just use a single vpmovdw instruction, without avx512vl we need to
10970// use the zmm variant and extract the lower subvector, padding with zeroes.
10971// TODO: Merge with lowerShuffleAsVTRUNC.
10973 SDValue V2, ArrayRef<int> Mask,
10974 const APInt &Zeroable,
10975 const X86Subtarget &Subtarget,
10976 SelectionDAG &DAG) {
10977 assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
10978 if (!Subtarget.hasAVX512())
10979 return SDValue();
10980
10981 unsigned NumElts = VT.getVectorNumElements();
10982 unsigned EltSizeInBits = VT.getScalarSizeInBits();
10983 unsigned MaxScale = 64 / EltSizeInBits;
10984 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10985 unsigned SrcEltBits = EltSizeInBits * Scale;
10986 unsigned NumSrcElts = NumElts / Scale;
10987 unsigned UpperElts = NumElts - NumSrcElts;
10988 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
10989 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10990 continue;
10991
10992 // Attempt to find a matching source truncation, but as a fall back VLX
10993 // cases can use the VPMOV directly.
10995 if (Src.getOpcode() == ISD::TRUNCATE &&
10996 Src.getScalarValueSizeInBits() == SrcEltBits) {
10997 Src = Src.getOperand(0);
10998 } else if (Subtarget.hasVLX()) {
10999 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11000 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11001 Src = DAG.getBitcast(SrcVT, Src);
11002 // Don't do this if PACKSS/PACKUS could perform it cheaper.
11003 if (Scale == 2 &&
11004 ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
11005 (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
11006 return SDValue();
11007 } else
11008 return SDValue();
11009
11010 // VPMOVWB is only available with avx512bw.
11011 if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
11012 return SDValue();
11013
11014 bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
11015 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11016 }
11017
11018 return SDValue();
11019}
11020
11021// Attempt to match binary shuffle patterns as a truncate.
11023 SDValue V2, ArrayRef<int> Mask,
11024 const APInt &Zeroable,
11025 const X86Subtarget &Subtarget,
11026 SelectionDAG &DAG) {
11027 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11028 "Unexpected VTRUNC type");
11029 if (!Subtarget.hasAVX512() ||
11030 (VT.is256BitVector() && !Subtarget.useAVX512Regs()))
11031 return SDValue();
11032
11033 unsigned NumElts = VT.getVectorNumElements();
11034 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11035 unsigned MaxScale = 64 / EltSizeInBits;
11036 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11037 // TODO: Support non-BWI VPMOVWB truncations?
11038 unsigned SrcEltBits = EltSizeInBits * Scale;
11039 if (SrcEltBits < 32 && !Subtarget.hasBWI())
11040 continue;
11041
11042 // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
11043 // Bail if the V2 elements are undef.
11044 unsigned NumHalfSrcElts = NumElts / Scale;
11045 unsigned NumSrcElts = 2 * NumHalfSrcElts;
11046 for (unsigned Offset = 0; Offset != Scale; ++Offset) {
11047 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
11048 isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
11049 continue;
11050
11051 // The elements beyond the truncation must be undef/zero.
11052 unsigned UpperElts = NumElts - NumSrcElts;
11053 if (UpperElts > 0 &&
11054 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
11055 continue;
11056 bool UndefUppers =
11057 UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
11058
11059 // As we're using both sources then we need to concat them together
11060 // and truncate from the double-sized src.
11061 MVT ConcatVT = VT.getDoubleNumVectorElementsVT();
11062
11063 // For offset truncations, ensure that the concat is cheap.
11064 SDValue Src =
11065 combineConcatVectorOps(DL, ConcatVT, {V1, V2}, DAG, Subtarget);
11066 if (!Src) {
11067 if (Offset)
11068 continue;
11069 Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
11070 }
11071
11072 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11073 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11074 Src = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, SrcVT, Src,
11075 Offset * EltSizeInBits, DAG);
11076 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11077 }
11078 }
11079
11080 return SDValue();
11081}
11082
11083/// Check whether a compaction lowering can be done by dropping even/odd
11084/// elements and compute how many times even/odd elements must be dropped.
11085///
11086/// This handles shuffles which take every Nth element where N is a power of
11087/// two. Example shuffle masks:
11088///
11089/// (even)
11090/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
11091/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11092/// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
11093/// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
11094/// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
11095/// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
11096///
11097/// (odd)
11098/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 14
11099/// N = 1: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
11100///
11101/// Any of these lanes can of course be undef.
11102///
11103/// This routine only supports N <= 3.
11104/// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11105/// for larger N.
11106///
11107/// \returns N above, or the number of times even/odd elements must be dropped
11108/// if there is such a number. Otherwise returns zero.
11109static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
11110 bool IsSingleInput) {
11111 // The modulus for the shuffle vector entries is based on whether this is
11112 // a single input or not.
11113 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11114 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
11115 "We should only be called with masks with a power-of-2 size!");
11116
11117 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11118 int Offset = MatchEven ? 0 : 1;
11119
11120 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11121 // and 2^3 simultaneously. This is because we may have ambiguity with
11122 // partially undef inputs.
11123 bool ViableForN[3] = {true, true, true};
11124
11125 for (int i = 0, e = Mask.size(); i < e; ++i) {
11126 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11127 // want.
11128 if (Mask[i] < 0)
11129 continue;
11130
11131 bool IsAnyViable = false;
11132 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11133 if (ViableForN[j]) {
11134 uint64_t N = j + 1;
11135
11136 // The shuffle mask must be equal to (i * 2^N) % M.
11137 if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
11138 IsAnyViable = true;
11139 else
11140 ViableForN[j] = false;
11141 }
11142 // Early exit if we exhaust the possible powers of two.
11143 if (!IsAnyViable)
11144 break;
11145 }
11146
11147 for (unsigned j = 0; j != std::size(ViableForN); ++j)
11148 if (ViableForN[j])
11149 return j + 1;
11150
11151 // Return 0 as there is no viable power of two.
11152 return 0;
11153}
11154
11155// X86 has dedicated pack instructions that can handle specific truncation
11156// operations: PACKSS and PACKUS.
11157// Checks for compaction shuffle masks if MaxStages > 1.
11158// TODO: Add support for matching multiple PACKSS/PACKUS stages.
11159static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11160 unsigned &PackOpcode, ArrayRef<int> TargetMask,
11161 const SelectionDAG &DAG,
11162 const X86Subtarget &Subtarget,
11163 unsigned MaxStages = 1) {
11164 unsigned NumElts = VT.getVectorNumElements();
11165 unsigned BitSize = VT.getScalarSizeInBits();
11166 assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
11167 "Illegal maximum compaction");
11168
11169 auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11170 unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11171 unsigned NumPackedBits = NumSrcBits - BitSize;
11172 N1 = peekThroughBitcasts(N1);
11173 N2 = peekThroughBitcasts(N2);
11174 unsigned NumBits1 = N1.getScalarValueSizeInBits();
11175 unsigned NumBits2 = N2.getScalarValueSizeInBits();
11176 bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
11177 bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
11178 if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
11179 (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
11180 return false;
11181 if (Subtarget.hasSSE41() || BitSize == 8) {
11182 APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11183 if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
11184 (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
11185 V1 = N1;
11186 V2 = N2;
11187 SrcVT = PackVT;
11188 PackOpcode = X86ISD::PACKUS;
11189 return true;
11190 }
11191 }
11192 bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
11193 bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
11194 if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
11195 DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
11196 (N2.isUndef() || IsZero2 || IsAllOnes2 ||
11197 DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
11198 V1 = N1;
11199 V2 = N2;
11200 SrcVT = PackVT;
11201 PackOpcode = X86ISD::PACKSS;
11202 return true;
11203 }
11204 return false;
11205 };
11206
11207 // Attempt to match against wider and wider compaction patterns.
11208 for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11209 MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11210 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11211
11212 // Try binary shuffle.
11213 SmallVector<int, 32> BinaryMask;
11214 createPackShuffleMask(VT, BinaryMask, false, NumStages);
11215 if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
11216 if (MatchPACK(V1, V2, PackVT))
11217 return true;
11218
11219 // Try unary shuffle.
11220 SmallVector<int, 32> UnaryMask;
11221 createPackShuffleMask(VT, UnaryMask, true, NumStages);
11222 if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
11223 if (MatchPACK(V1, V1, PackVT))
11224 return true;
11225 }
11226
11227 return false;
11228}
11229
11231 SDValue V2, ArrayRef<int> Mask,
11232 const X86Subtarget &Subtarget,
11233 SelectionDAG &DAG) {
11234 MVT PackVT;
11235 unsigned PackOpcode;
11236 unsigned SizeBits = VT.getSizeInBits();
11237 unsigned EltBits = VT.getScalarSizeInBits();
11238 unsigned MaxStages = Log2_32(64 / EltBits);
11239 if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11240 Subtarget, MaxStages))
11241 return SDValue();
11242
11243 unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11244 unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11245
11246 // Don't lower multi-stage packs on AVX512, truncation is better.
11247 if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11248 return SDValue();
11249
11250 // Pack to the largest type possible:
11251 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11252 unsigned MaxPackBits = 16;
11253 if (CurrentEltBits > 16 &&
11254 (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11255 MaxPackBits = 32;
11256
11257 // Repeatedly pack down to the target size.
11258 SDValue Res;
11259 for (unsigned i = 0; i != NumStages; ++i) {
11260 unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11261 unsigned NumSrcElts = SizeBits / SrcEltBits;
11262 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11263 MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11264 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11265 MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11266 Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11267 DAG.getBitcast(SrcVT, V2));
11268 V1 = V2 = Res;
11269 CurrentEltBits /= 2;
11270 }
11271 assert(Res && Res.getValueType() == VT &&
11272 "Failed to lower compaction shuffle");
11273 return Res;
11274}
11275
11276/// Try to emit a bitmask instruction for a shuffle.
11277///
11278/// This handles cases where we can model a blend exactly as a bitmask due to
11279/// one of the inputs being zeroable.
11281 SDValue V2, ArrayRef<int> Mask,
11282 const APInt &Zeroable, SelectionDAG &DAG) {
11283 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11284 APInt Zero = APInt::getZero(EltSizeInBIts);
11285 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11286
11287 SmallVector<APInt, 16> VMaskOps(Mask.size(), Zero);
11288 SDValue V;
11289 for (int I = 0, Size = Mask.size(); I != Size; ++I) {
11290 if (Zeroable[I])
11291 continue;
11292 if (Mask[I] % Size != I)
11293 return SDValue(); // Not a blend.
11294 if (!V)
11295 V = Mask[I] < Size ? V1 : V2;
11296 else if (V != (Mask[I] < Size ? V1 : V2))
11297 return SDValue(); // Can only let one input through the mask.
11298
11299 VMaskOps[I] = AllOnes;
11300 }
11301 if (!V)
11302 return SDValue(); // No non-zeroable elements!
11303
11304 MVT LogicVT = VT.changeTypeToInteger();
11305 SDValue VMask = getConstVector(VMaskOps, LogicVT, DAG, DL);
11306 V = DAG.getBitcast(LogicVT, V);
11307 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11308 return DAG.getBitcast(VT, And);
11309}
11310
11311/// Try to emit a blend instruction for a shuffle using bit math.
11312///
11313/// This is used as a fallback approach when first class blend instructions are
11314/// unavailable. Currently it is only suitable for integer vectors, but could
11315/// be generalized for floating point vectors if desirable.
11317 SDValue V2, ArrayRef<int> Mask,
11318 SelectionDAG &DAG) {
11319 assert(VT.isInteger() && "Only supports integer vector types!");
11320 unsigned EltSizeInBIts = VT.getScalarSizeInBits();
11321 APInt Zero = APInt::getZero(EltSizeInBIts);
11322 APInt AllOnes = APInt::getAllOnes(EltSizeInBIts);
11323 SmallVector<APInt, 16> MaskOps;
11324 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11325 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11326 return SDValue(); // Shuffled input!
11327 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11328 }
11329 SDValue V1Mask = getConstVector(MaskOps, VT, DAG, DL);
11330 return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
11331}
11332
11334 SDValue PreservedSrc,
11335 const X86Subtarget &Subtarget,
11336 SelectionDAG &DAG);
11337
11340 const APInt &Zeroable, bool &ForceV1Zero,
11341 bool &ForceV2Zero, uint64_t &BlendMask) {
11342 bool V1IsZeroOrUndef =
11343 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11344 bool V2IsZeroOrUndef =
11346
11347 BlendMask = 0;
11348 ForceV1Zero = false, ForceV2Zero = false;
11349 assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11350
11351 int NumElts = Mask.size();
11352 int NumLanes = VT.getSizeInBits() / 128;
11353 int NumEltsPerLane = NumElts / NumLanes;
11354 assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
11355
11356 // For 32/64-bit elements, if we only reference one input (plus any undefs),
11357 // then ensure the blend mask part for that lane just references that input.
11358 bool ForceWholeLaneMasks =
11359 VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
11360
11361 // Attempt to generate the binary blend mask. If an input is zero then
11362 // we can use any lane.
11363 for (int Lane = 0; Lane != NumLanes; ++Lane) {
11364 // Keep track of the inputs used per lane.
11365 bool LaneV1InUse = false;
11366 bool LaneV2InUse = false;
11367 uint64_t LaneBlendMask = 0;
11368 for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
11369 int Elt = (Lane * NumEltsPerLane) + LaneElt;
11370 int M = Mask[Elt];
11371 if (M == SM_SentinelUndef)
11372 continue;
11373 if (M == Elt || (0 <= M && M < NumElts &&
11374 IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
11375 Mask[Elt] = Elt;
11376 LaneV1InUse = true;
11377 continue;
11378 }
11379 if (M == (Elt + NumElts) ||
11380 (NumElts <= M &&
11381 IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
11382 LaneBlendMask |= 1ull << LaneElt;
11383 Mask[Elt] = Elt + NumElts;
11384 LaneV2InUse = true;
11385 continue;
11386 }
11387 if (Zeroable[Elt]) {
11388 if (V1IsZeroOrUndef) {
11389 ForceV1Zero = true;
11390 Mask[Elt] = Elt;
11391 LaneV1InUse = true;
11392 continue;
11393 }
11394 if (V2IsZeroOrUndef) {
11395 ForceV2Zero = true;
11396 LaneBlendMask |= 1ull << LaneElt;
11397 Mask[Elt] = Elt + NumElts;
11398 LaneV2InUse = true;
11399 continue;
11400 }
11401 }
11402 return false;
11403 }
11404
11405 // If we only used V2 then splat the lane blend mask to avoid any demanded
11406 // elts from V1 in this lane (the V1 equivalent is implicit with a zero
11407 // blend mask bit).
11408 if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
11409 LaneBlendMask = (1ull << NumEltsPerLane) - 1;
11410
11411 BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
11412 }
11413 return true;
11414}
11415
11416/// Try to emit a blend instruction for a shuffle.
11417///
11418/// This doesn't do any checks for the availability of instructions for blending
11419/// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11420/// be matched in the backend with the type given. What it does check for is
11421/// that the shuffle mask is a blend, or convertible into a blend with zero.
11423 SDValue V2, ArrayRef<int> Original,
11424 const APInt &Zeroable,
11425 const X86Subtarget &Subtarget,
11426 SelectionDAG &DAG) {
11427 uint64_t BlendMask = 0;
11428 bool ForceV1Zero = false, ForceV2Zero = false;
11429 SmallVector<int, 64> Mask(Original);
11430 if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11431 BlendMask))
11432 return SDValue();
11433
11434 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11435 if (ForceV1Zero)
11436 V1 = getZeroVector(VT, Subtarget, DAG, DL);
11437 if (ForceV2Zero)
11438 V2 = getZeroVector(VT, Subtarget, DAG, DL);
11439
11440 unsigned NumElts = VT.getVectorNumElements();
11441
11442 switch (VT.SimpleTy) {
11443 case MVT::v4i64:
11444 case MVT::v8i32:
11445 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11446 [[fallthrough]];
11447 case MVT::v4f64:
11448 case MVT::v8f32:
11449 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11450 [[fallthrough]];
11451 case MVT::v2f64:
11452 case MVT::v2i64:
11453 case MVT::v4f32:
11454 case MVT::v4i32:
11455 case MVT::v8i16:
11456 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
11457 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
11458 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11459 case MVT::v16i16: {
11460 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
11461 SmallVector<int, 8> RepeatedMask;
11462 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11463 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
11464 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
11465 BlendMask = 0;
11466 for (int i = 0; i < 8; ++i)
11467 if (RepeatedMask[i] >= 8)
11468 BlendMask |= 1ull << i;
11469 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11470 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11471 }
11472 // Use PBLENDW for lower/upper lanes and then blend lanes.
11473 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
11474 // merge to VSELECT where useful.
11475 uint64_t LoMask = BlendMask & 0xFF;
11476 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
11477 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
11478 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11479 DAG.getTargetConstant(LoMask, DL, MVT::i8));
11480 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11481 DAG.getTargetConstant(HiMask, DL, MVT::i8));
11482 return DAG.getVectorShuffle(
11483 MVT::v16i16, DL, Lo, Hi,
11484 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
11485 }
11486 [[fallthrough]];
11487 }
11488 case MVT::v32i8:
11489 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
11490 [[fallthrough]];
11491 case MVT::v16i8: {
11492 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
11493
11494 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
11495 if (SDValue Masked =
11496 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11497 return Masked;
11498
11499 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
11500 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11501 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11502 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11503 }
11504
11505 // If we have VPTERNLOG, we can use that as a bit blend.
11506 if (Subtarget.hasVLX())
11507 if (SDValue BitBlend =
11508 lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
11509 return BitBlend;
11510
11511 // Scale the blend by the number of bytes per element.
11512 int Scale = VT.getScalarSizeInBits() / 8;
11513
11514 // This form of blend is always done on bytes. Compute the byte vector
11515 // type.
11516 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11517
11518 // x86 allows load folding with blendvb from the 2nd source operand. But
11519 // we are still using LLVM select here (see comment below), so that's V1.
11520 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
11521 // allow that load-folding possibility.
11522 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
11524 std::swap(V1, V2);
11525 }
11526
11527 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
11528 // mix of LLVM's code generator and the x86 backend. We tell the code
11529 // generator that boolean values in the elements of an x86 vector register
11530 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
11531 // mapping a select to operand #1, and 'false' mapping to operand #2. The
11532 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
11533 // of the element (the remaining are ignored) and 0 in that high bit would
11534 // mean operand #1 while 1 in the high bit would mean operand #2. So while
11535 // the LLVM model for boolean values in vector elements gets the relevant
11536 // bit set, it is set backwards and over constrained relative to x86's
11537 // actual model.
11538 SmallVector<SDValue, 32> VSELECTMask;
11539 for (int i = 0, Size = Mask.size(); i < Size; ++i)
11540 for (int j = 0; j < Scale; ++j)
11541 VSELECTMask.push_back(
11542 Mask[i] < 0
11543 ? DAG.getUNDEF(MVT::i8)
11544 : DAG.getSignedConstant(Mask[i] < Size ? -1 : 0, DL, MVT::i8));
11545
11546 V1 = DAG.getBitcast(BlendVT, V1);
11547 V2 = DAG.getBitcast(BlendVT, V2);
11548 return DAG.getBitcast(
11549 VT,
11550 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
11551 V1, V2));
11552 }
11553 case MVT::v16f32:
11554 case MVT::v8f64:
11555 case MVT::v8i64:
11556 case MVT::v16i32:
11557 case MVT::v32i16:
11558 case MVT::v64i8: {
11559 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
11560 bool OptForSize = DAG.shouldOptForSize();
11561 if (!OptForSize) {
11562 if (SDValue Masked =
11563 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
11564 return Masked;
11565 }
11566
11567 // Otherwise load an immediate into a GPR, cast to k-register, and use a
11568 // masked move.
11569 MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
11570 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11571 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11572 }
11573 default:
11574 llvm_unreachable("Not a supported integer vector type!");
11575 }
11576}
11577
11578/// Try to lower as a blend of elements from two inputs followed by
11579/// a single-input permutation.
11580///
11581/// This matches the pattern where we can blend elements from two inputs and
11582/// then reduce the shuffle to a single-input permutation.
11584 SDValue V1, SDValue V2,
11585 ArrayRef<int> Mask,
11586 SelectionDAG &DAG,
11587 bool ImmBlends = false) {
11588 // We build up the blend mask while checking whether a blend is a viable way
11589 // to reduce the shuffle.
11590 SmallVector<int, 32> BlendMask(Mask.size(), -1);
11591 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
11592
11593 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11594 if (Mask[i] < 0)
11595 continue;
11596
11597 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
11598
11599 if (BlendMask[Mask[i] % Size] < 0)
11600 BlendMask[Mask[i] % Size] = Mask[i];
11601 else if (BlendMask[Mask[i] % Size] != Mask[i])
11602 return SDValue(); // Can't blend in the needed input!
11603
11604 PermuteMask[i] = Mask[i] % Size;
11605 }
11606
11607 // If only immediate blends, then bail if the blend mask can't be widened to
11608 // i16.
11609 unsigned EltSize = VT.getScalarSizeInBits();
11610 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11611 return SDValue();
11612
11613 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11614 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11615}
11616
11617/// Try to lower as an unpack of elements from two inputs followed by
11618/// a single-input permutation.
11619///
11620/// This matches the pattern where we can unpack elements from two inputs and
11621/// then reduce the shuffle to a single-input (wider) permutation.
11623 SDValue V1, SDValue V2,
11624 ArrayRef<int> Mask,
11625 SelectionDAG &DAG) {
11626 int NumElts = Mask.size();
11627 int NumLanes = VT.getSizeInBits() / 128;
11628 int NumLaneElts = NumElts / NumLanes;
11629 int NumHalfLaneElts = NumLaneElts / 2;
11630
11631 bool MatchLo = true, MatchHi = true;
11632 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11633
11634 // Determine UNPCKL/UNPCKH type and operand order.
11635 for (int Elt = 0; Elt != NumElts; ++Elt) {
11636 int M = Mask[Elt];
11637 if (M < 0)
11638 continue;
11639
11640 // Normalize the mask value depending on whether it's V1 or V2.
11641 int NormM = M;
11642 SDValue &Op = Ops[Elt & 1];
11643 if (M < NumElts && (Op.isUndef() || Op == V1))
11644 Op = V1;
11645 else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
11646 Op = V2;
11647 NormM -= NumElts;
11648 } else
11649 return SDValue();
11650
11651 bool MatchLoAnyLane = false, MatchHiAnyLane = false;
11652 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11653 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11654 MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
11655 MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
11656 if (MatchLoAnyLane || MatchHiAnyLane) {
11657 assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
11658 "Failed to match UNPCKLO/UNPCKHI");
11659 break;
11660 }
11661 }
11662 MatchLo &= MatchLoAnyLane;
11663 MatchHi &= MatchHiAnyLane;
11664 if (!MatchLo && !MatchHi)
11665 return SDValue();
11666 }
11667 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11668
11669 // Element indices have changed after unpacking. Calculate permute mask
11670 // so that they will be put back to the position as dictated by the
11671 // original shuffle mask indices.
11672 SmallVector<int, 32> PermuteMask(NumElts, -1);
11673 for (int Elt = 0; Elt != NumElts; ++Elt) {
11674 int M = Mask[Elt];
11675 if (M < 0)
11676 continue;
11677 int NormM = M;
11678 if (NumElts <= M)
11679 NormM -= NumElts;
11680 bool IsFirstOp = M < NumElts;
11681 int BaseMaskElt =
11682 NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
11683 if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
11684 PermuteMask[Elt] = BaseMaskElt;
11685 else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
11686 PermuteMask[Elt] = BaseMaskElt + 1;
11687 assert(PermuteMask[Elt] != -1 &&
11688 "Input mask element is defined but failed to assign permute mask");
11689 }
11690
11691 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11692 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11693 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11694}
11695
11696/// Try to lower a shuffle as a permute of the inputs followed by an
11697/// UNPCK instruction.
11698///
11699/// This specifically targets cases where we end up with alternating between
11700/// the two inputs, and so can permute them into something that feeds a single
11701/// UNPCK instruction. Note that this routine only targets integer vectors
11702/// because for floating point vectors we have a generalized SHUFPS lowering
11703/// strategy that handles everything that doesn't *exactly* match an unpack,
11704/// making this clever lowering unnecessary.
11706 SDValue V1, SDValue V2,
11707 ArrayRef<int> Mask,
11708 const X86Subtarget &Subtarget,
11709 SelectionDAG &DAG) {
11710 int Size = Mask.size();
11711 assert(Mask.size() >= 2 && "Single element masks are invalid.");
11712
11713 // This routine only supports 128-bit integer dual input vectors.
11714 if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
11715 return SDValue();
11716
11717 int NumLoInputs =
11718 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
11719 int NumHiInputs =
11720 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
11721
11722 bool UnpackLo = NumLoInputs >= NumHiInputs;
11723
11724 auto TryUnpack = [&](int ScalarSize, int Scale) {
11725 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
11726 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
11727
11728 for (int i = 0; i < Size; ++i) {
11729 if (Mask[i] < 0)
11730 continue;
11731
11732 // Each element of the unpack contains Scale elements from this mask.
11733 int UnpackIdx = i / Scale;
11734
11735 // We only handle the case where V1 feeds the first slots of the unpack.
11736 // We rely on canonicalization to ensure this is the case.
11737 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
11738 return SDValue();
11739
11740 // Setup the mask for this input. The indexing is tricky as we have to
11741 // handle the unpack stride.
11742 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
11743 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
11744 Mask[i] % Size;
11745 }
11746
11747 // If we will have to shuffle both inputs to use the unpack, check whether
11748 // we can just unpack first and shuffle the result. If so, skip this unpack.
11749 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
11750 !isNoopShuffleMask(V2Mask))
11751 return SDValue();
11752
11753 // Shuffle the inputs into place.
11754 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11755 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11756
11757 // Cast the inputs to the type we will use to unpack them.
11758 MVT UnpackVT =
11759 MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
11760 V1 = DAG.getBitcast(UnpackVT, V1);
11761 V2 = DAG.getBitcast(UnpackVT, V2);
11762
11763 // Unpack the inputs and cast the result back to the desired type.
11764 return DAG.getBitcast(
11765 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
11766 UnpackVT, V1, V2));
11767 };
11768
11769 // We try each unpack from the largest to the smallest to try and find one
11770 // that fits this mask.
11771 int OrigScalarSize = VT.getScalarSizeInBits();
11772 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
11773 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
11774 return Unpack;
11775
11776 // If we're shuffling with a zero vector then we're better off not doing
11777 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
11778 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
11780 return SDValue();
11781
11782 // If none of the unpack-rooted lowerings worked (or were profitable) try an
11783 // initial unpack.
11784 if (NumLoInputs == 0 || NumHiInputs == 0) {
11785 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
11786 "We have to have *some* inputs!");
11787 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
11788
11789 // FIXME: We could consider the total complexity of the permute of each
11790 // possible unpacking. Or at the least we should consider how many
11791 // half-crossings are created.
11792 // FIXME: We could consider commuting the unpacks.
11793
11794 SmallVector<int, 32> PermMask((unsigned)Size, -1);
11795 for (int i = 0; i < Size; ++i) {
11796 if (Mask[i] < 0)
11797 continue;
11798
11799 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
11800
11801 PermMask[i] =
11802 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
11803 }
11804 return DAG.getVectorShuffle(
11805 VT, DL,
11806 DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
11807 V1, V2),
11808 DAG.getUNDEF(VT), PermMask);
11809 }
11810
11811 return SDValue();
11812}
11813
11814/// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11815/// permuting the elements of the result in place.
11817 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11818 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11819 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11820 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11821 (VT.is512BitVector() && !Subtarget.hasBWI()))
11822 return SDValue();
11823
11824 // We don't currently support lane crossing permutes.
11825 if (is128BitLaneCrossingShuffleMask(VT, Mask))
11826 return SDValue();
11827
11828 int Scale = VT.getScalarSizeInBits() / 8;
11829 int NumLanes = VT.getSizeInBits() / 128;
11830 int NumElts = VT.getVectorNumElements();
11831 int NumEltsPerLane = NumElts / NumLanes;
11832
11833 // Determine range of mask elts.
11834 bool Blend1 = true;
11835 bool Blend2 = true;
11836 std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11837 std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11838 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11839 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11840 int M = Mask[Lane + Elt];
11841 if (M < 0)
11842 continue;
11843 if (M < NumElts) {
11844 Blend1 &= (M == (Lane + Elt));
11845 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11846 M = M % NumEltsPerLane;
11847 Range1.first = std::min(Range1.first, M);
11848 Range1.second = std::max(Range1.second, M);
11849 } else {
11850 M -= NumElts;
11851 Blend2 &= (M == (Lane + Elt));
11852 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11853 M = M % NumEltsPerLane;
11854 Range2.first = std::min(Range2.first, M);
11855 Range2.second = std::max(Range2.second, M);
11856 }
11857 }
11858 }
11859
11860 // Bail if we don't need both elements.
11861 // TODO - it might be worth doing this for unary shuffles if the permute
11862 // can be widened.
11863 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11864 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11865 return SDValue();
11866
11867 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11868 return SDValue();
11869
11870 // Rotate the 2 ops so we can access both ranges, then permute the result.
11871 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11872 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11873 SDValue Rotate = DAG.getBitcast(
11874 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11875 DAG.getBitcast(ByteVT, Lo),
11876 DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11877 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11878 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11879 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11880 int M = Mask[Lane + Elt];
11881 if (M < 0)
11882 continue;
11883 if (M < NumElts)
11884 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11885 else
11886 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
11887 }
11888 }
11889 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
11890 };
11891
11892 // Check if the ranges are small enough to rotate from either direction.
11893 if (Range2.second < Range1.first)
11894 return RotateAndPermute(V1, V2, Range1.first, 0);
11895 if (Range1.second < Range2.first)
11896 return RotateAndPermute(V2, V1, Range2.first, NumElts);
11897 return SDValue();
11898}
11899
11901 return isUndefOrEqual(Mask, 0);
11902}
11903
11905 return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
11906}
11907
11908/// Check if the Mask consists of the same element repeated multiple times.
11910 size_t NumUndefs = 0;
11911 std::optional<int> UniqueElt;
11912 for (int Elt : Mask) {
11913 if (Elt == SM_SentinelUndef) {
11914 NumUndefs++;
11915 continue;
11916 }
11917 if (UniqueElt.has_value() && UniqueElt.value() != Elt)
11918 return false;
11919 UniqueElt = Elt;
11920 }
11921 // Make sure the element is repeated enough times by checking the number of
11922 // undefs is small.
11923 return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
11924}
11925
11926/// Generic routine to decompose a shuffle and blend into independent
11927/// blends and permutes.
11928///
11929/// This matches the extremely common pattern for handling combined
11930/// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11931/// operations. It will try to pick the best arrangement of shuffles and
11932/// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
11934 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11935 const APInt &Zeroable, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11936 int NumElts = Mask.size();
11937 int NumLanes = VT.getSizeInBits() / 128;
11938 int NumEltsPerLane = NumElts / NumLanes;
11939 int EltSizeInBits = VT.getScalarSizeInBits();
11940
11941 // Shuffle the input elements into the desired positions in V1 and V2 and
11942 // unpack/blend them together.
11943 bool IsAlternating = true;
11944 bool V1Zero = true, V2Zero = true;
11945 SmallVector<int, 32> V1Mask(NumElts, -1);
11946 SmallVector<int, 32> V2Mask(NumElts, -1);
11947 SmallVector<int, 32> FinalMask(NumElts, -1);
11948 for (int i = 0; i < NumElts; ++i) {
11949 int M = Mask[i];
11950 if (M >= 0 && M < NumElts) {
11951 V1Mask[i] = M;
11952 FinalMask[i] = i;
11953 V1Zero &= Zeroable[i];
11954 IsAlternating &= (i & 1) == 0;
11955 } else if (M >= NumElts) {
11956 V2Mask[i] = M - NumElts;
11957 FinalMask[i] = i + NumElts;
11958 V2Zero &= Zeroable[i];
11959 IsAlternating &= (i & 1) == 1;
11960 }
11961 }
11962
11963 // If we effectively only demand the 0'th element of \p Input, and not only
11964 // as 0'th element, then broadcast said input,
11965 // and change \p InputMask to be a no-op (identity) mask.
11966 auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
11967 &DAG](SDValue &Input,
11968 MutableArrayRef<int> InputMask) {
11969 unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
11970 if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
11971 !X86::mayFoldLoad(Input, Subtarget)))
11972 return;
11973 if (isNoopShuffleMask(InputMask))
11974 return;
11975 assert(isBroadcastShuffleMask(InputMask) &&
11976 "Expected to demand only the 0'th element.");
11977 Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
11978 for (auto I : enumerate(InputMask)) {
11979 int &InputMaskElt = I.value();
11980 if (InputMaskElt >= 0)
11981 InputMaskElt = I.index();
11982 }
11983 };
11984
11985 // Currently, we may need to produce one shuffle per input, and blend results.
11986 // It is possible that the shuffle for one of the inputs is already a no-op.
11987 // See if we can simplify non-no-op shuffles into broadcasts,
11988 // which we consider to be strictly better than an arbitrary shuffle.
11989 if (isNoopOrBroadcastShuffleMask(V1Mask) &&
11991 canonicalizeBroadcastableInput(V1, V1Mask);
11992 canonicalizeBroadcastableInput(V2, V2Mask);
11993 }
11994
11995 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
11996 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
11997 // the shuffle may be able to fold with a load or other benefit. However, when
11998 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
11999 // pre-shuffle first is a better strategy.
12000 bool V1Noop = isNoopShuffleMask(V1Mask);
12001 bool V2Noop = isNoopShuffleMask(V2Mask);
12002 if (!V1Noop && !V2Noop) {
12003 // If we don't have blends, see if we can create a cheap unpack.
12004 if (!Subtarget.hasSSE41() && VT.is128BitVector() &&
12005 (is128BitUnpackShuffleMask(V1Mask, DAG) ||
12006 is128BitUnpackShuffleMask(V2Mask, DAG)))
12007 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12008 DL, VT, V1, V2, Mask, Subtarget, DAG))
12009 return PermUnpack;
12010
12011 // Only prefer immediate blends to unpack/rotate.
12012 if (SDValue BlendPerm =
12013 lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG, true))
12014 return BlendPerm;
12015
12016 // If either input vector provides only a single element which is repeated
12017 // multiple times, unpacking from both input vectors would generate worse
12018 // code. e.g. for
12019 // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
12020 // it is better to process t4 first to create a vector of t4[0], then unpack
12021 // that vector with t2.
12022 if (!V1Zero && !V2Zero && !isSingleElementRepeatedMask(V1Mask) &&
12024 if (SDValue UnpackPerm =
12025 lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
12026 return UnpackPerm;
12027
12029 DL, VT, V1, V2, Mask, Subtarget, DAG))
12030 return RotatePerm;
12031
12032 // Unpack/rotate failed - try again with variable blends.
12033 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12034 DAG))
12035 return BlendPerm;
12036
12037 if (EltSizeInBits >= 32)
12038 if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
12039 DL, VT, V1, V2, Mask, Subtarget, DAG))
12040 return PermUnpack;
12041 }
12042
12043 // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12044 // UNPCKL(SHUFFLE, SHUFFLE) pattern unless BLENDI is cheap.
12045 // TODO: It doesn't have to be alternating - but each lane mustn't have more
12046 // than half the elements coming from each source.
12047 bool PreferBlend = EltSizeInBits == 16 && (V1Noop || V2Noop) &&
12048 Subtarget.hasSSE41() &&
12049 is128BitLaneRepeatedShuffleMask(VT, FinalMask);
12050 if (!PreferBlend && IsAlternating && EltSizeInBits < 32) {
12051 V1Mask.assign(NumElts, -1);
12052 V2Mask.assign(NumElts, -1);
12053 FinalMask.assign(NumElts, -1);
12054 for (int i = 0; i != NumElts; i += NumEltsPerLane)
12055 for (int j = 0; j != NumEltsPerLane; ++j) {
12056 int M = Mask[i + j];
12057 if (M >= 0 && M < NumElts) {
12058 V1Mask[i + (j / 2)] = M;
12059 FinalMask[i + j] = i + (j / 2);
12060 } else if (M >= NumElts) {
12061 V2Mask[i + (j / 2)] = M - NumElts;
12062 FinalMask[i + j] = i + (j / 2) + NumElts;
12063 }
12064 }
12065 }
12066
12067 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12068 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12069 return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12070}
12071
12072static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12073 const X86Subtarget &Subtarget,
12074 ArrayRef<int> Mask) {
12075 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12076 assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12077
12078 // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12079 int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12080 int MaxSubElts = 64 / EltSizeInBits;
12081 unsigned RotateAmt, NumSubElts;
12082 if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, MinSubElts,
12083 MaxSubElts, NumSubElts, RotateAmt))
12084 return -1;
12085 unsigned NumElts = Mask.size();
12086 MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12087 RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12088 return RotateAmt;
12089}
12090
12091/// Lower shuffle using X86ISD::VROTLI rotations.
12093 ArrayRef<int> Mask,
12094 const X86Subtarget &Subtarget,
12095 SelectionDAG &DAG) {
12096 // Only XOP + AVX512 targets have bit rotation instructions.
12097 // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12098 bool IsLegal =
12099 (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12100 if (!IsLegal && Subtarget.hasSSE3())
12101 return SDValue();
12102
12103 MVT RotateVT;
12104 int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12105 Subtarget, Mask);
12106 if (RotateAmt < 0)
12107 return SDValue();
12108
12109 // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12110 // expanded to OR(SRL,SHL), will be more efficient, but if they can
12111 // widen to vXi16 or more then existing lowering should will be better.
12112 if (!IsLegal) {
12113 if ((RotateAmt % 16) == 0)
12114 return SDValue();
12115 unsigned ShlAmt = RotateAmt;
12116 unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12117 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, RotateVT, V1,
12118 ShlAmt, DAG);
12119 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, RotateVT, V1,
12120 SrlAmt, DAG);
12121 SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12122 return DAG.getBitcast(VT, Rot);
12123 }
12124
12125 SDValue Rot =
12126 DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12127 DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12128 return DAG.getBitcast(VT, Rot);
12129}
12130
12131/// Try to match a vector shuffle as an element rotation.
12132///
12133/// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
12135 ArrayRef<int> Mask) {
12136 int NumElts = Mask.size();
12137
12138 // We need to detect various ways of spelling a rotation:
12139 // [11, 12, 13, 14, 15, 0, 1, 2]
12140 // [-1, 12, 13, 14, -1, -1, 1, -1]
12141 // [-1, -1, -1, -1, -1, -1, 1, 2]
12142 // [ 3, 4, 5, 6, 7, 8, 9, 10]
12143 // [-1, 4, 5, 6, -1, -1, 9, -1]
12144 // [-1, 4, 5, 6, -1, -1, -1, -1]
12145 int Rotation = 0;
12146 SDValue Lo, Hi;
12147 for (int i = 0; i < NumElts; ++i) {
12148 int M = Mask[i];
12149 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
12150 "Unexpected mask index.");
12151 if (M < 0)
12152 continue;
12153
12154 // Determine where a rotated vector would have started.
12155 int StartIdx = i - (M % NumElts);
12156 if (StartIdx == 0)
12157 // The identity rotation isn't interesting, stop.
12158 return -1;
12159
12160 // If we found the tail of a vector the rotation must be the missing
12161 // front. If we found the head of a vector, it must be how much of the
12162 // head.
12163 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12164
12165 if (Rotation == 0)
12166 Rotation = CandidateRotation;
12167 else if (Rotation != CandidateRotation)
12168 // The rotations don't match, so we can't match this mask.
12169 return -1;
12170
12171 // Compute which value this mask is pointing at.
12172 SDValue MaskV = M < NumElts ? V1 : V2;
12173
12174 // Compute which of the two target values this index should be assigned
12175 // to. This reflects whether the high elements are remaining or the low
12176 // elements are remaining.
12177 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12178
12179 // Either set up this value if we've not encountered it before, or check
12180 // that it remains consistent.
12181 if (!TargetV)
12182 TargetV = MaskV;
12183 else if (TargetV != MaskV)
12184 // This may be a rotation, but it pulls from the inputs in some
12185 // unsupported interleaving.
12186 return -1;
12187 }
12188
12189 // Check that we successfully analyzed the mask, and normalize the results.
12190 assert(Rotation != 0 && "Failed to locate a viable rotation!");
12191 assert((Lo || Hi) && "Failed to find a rotated input vector!");
12192 if (!Lo)
12193 Lo = Hi;
12194 else if (!Hi)
12195 Hi = Lo;
12196
12197 V1 = Lo;
12198 V2 = Hi;
12199
12200 return Rotation;
12201}
12202
12203/// Try to lower a vector shuffle as a byte rotation.
12204///
12205/// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12206/// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12207/// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12208/// try to generically lower a vector shuffle through such an pattern. It
12209/// does not check for the profitability of lowering either as PALIGNR or
12210/// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12211/// This matches shuffle vectors that look like:
12212///
12213/// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12214///
12215/// Essentially it concatenates V1 and V2, shifts right by some number of
12216/// elements, and takes the low elements as the result. Note that while this is
12217/// specified as a *right shift* because x86 is little-endian, it is a *left
12218/// rotate* of the vector lanes.
12220 ArrayRef<int> Mask) {
12221 // Don't accept any shuffles with zero elements.
12222 if (isAnyZero(Mask))
12223 return -1;
12224
12225 // PALIGNR works on 128-bit lanes.
12226 SmallVector<int, 16> RepeatedMask;
12227 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12228 return -1;
12229
12230 int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12231 if (Rotation <= 0)
12232 return -1;
12233
12234 // PALIGNR rotates bytes, so we need to scale the
12235 // rotation based on how many bytes are in the vector lane.
12236 int NumElts = RepeatedMask.size();
12237 int Scale = 16 / NumElts;
12238 return Rotation * Scale;
12239}
12240
12242 SDValue V2, ArrayRef<int> Mask,
12243 const X86Subtarget &Subtarget,
12244 SelectionDAG &DAG) {
12245 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12246
12247 SDValue Lo = V1, Hi = V2;
12248 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12249 if (ByteRotation <= 0)
12250 return SDValue();
12251
12252 // Cast the inputs to i8 vector of correct length to match PALIGNR or
12253 // PSLLDQ/PSRLDQ.
12254 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12255 Lo = DAG.getBitcast(ByteVT, Lo);
12256 Hi = DAG.getBitcast(ByteVT, Hi);
12257
12258 // SSSE3 targets can use the palignr instruction.
12259 if (Subtarget.hasSSSE3()) {
12260 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
12261 "512-bit PALIGNR requires BWI instructions");
12262 return DAG.getBitcast(
12263 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12264 DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12265 }
12266
12267 assert(VT.is128BitVector() &&
12268 "Rotate-based lowering only supports 128-bit lowering!");
12269 assert(Mask.size() <= 16 &&
12270 "Can shuffle at most 16 bytes in a 128-bit vector!");
12271 assert(ByteVT == MVT::v16i8 &&
12272 "SSE2 rotate lowering only needed for v16i8!");
12273
12274 // Default SSE2 implementation
12275 int LoByteShift = 16 - ByteRotation;
12276 int HiByteShift = ByteRotation;
12277
12278 SDValue LoShift =
12279 DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12280 DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12281 SDValue HiShift =
12282 DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12283 DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12284 return DAG.getBitcast(VT,
12285 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12286}
12287
12288/// Try to lower a vector shuffle as a dword/qword rotation.
12289///
12290/// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12291/// rotation of the concatenation of two vectors; This routine will
12292/// try to generically lower a vector shuffle through such an pattern.
12293///
12294/// Essentially it concatenates V1 and V2, shifts right by some number of
12295/// elements, and takes the low elements as the result. Note that while this is
12296/// specified as a *right shift* because x86 is little-endian, it is a *left
12297/// rotate* of the vector lanes.
12299 SDValue V2, ArrayRef<int> Mask,
12300 const APInt &Zeroable,
12301 const X86Subtarget &Subtarget,
12302 SelectionDAG &DAG) {
12303 unsigned EltBits = VT.getScalarSizeInBits();
12304 if (EltBits != 32 && EltBits != 64)
12305 return SDValue();
12306
12308
12309 // 128/256-bit vectors are only supported with VLX.
12310 assert((Subtarget.hasVLX() ||
12311 (!AlignVT.is128BitVector() && !AlignVT.is256BitVector())) &&
12312 "VLX required for 128/256-bit vectors");
12313
12314 auto emitVALIGN = [&](SDValue Lo, SDValue Hi, unsigned Imm) -> SDValue {
12315 SDValue AlignLo = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Lo) : Lo;
12316 SDValue AlignHi = VT.isFloatingPoint() ? DAG.getBitcast(AlignVT, Hi) : Hi;
12317 SDValue Res = DAG.getNode(X86ISD::VALIGN, DL, AlignVT, AlignLo, AlignHi,
12318 DAG.getTargetConstant(Imm, DL, MVT::i8));
12319 return VT.isFloatingPoint() ? DAG.getBitcast(VT, Res) : Res;
12320 };
12321
12322 SDValue Lo = V1, Hi = V2;
12323 int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12324 if (0 < Rotation)
12325 return emitVALIGN(Lo, Hi, Rotation);
12326
12327 // See if we can use VALIGN as a cross-lane version of VSHLDQ/VSRLDQ.
12328 // TODO: Pull this out as a matchShuffleAsElementShift helper?
12329 // TODO: We can probably make this more aggressive and use shift-pairs like
12330 // lowerShuffleAsByteShiftMask.
12331 unsigned NumElts = Mask.size();
12332 unsigned ZeroLo = Zeroable.countr_one();
12333 unsigned ZeroHi = Zeroable.countl_one();
12334 assert((ZeroLo + ZeroHi) < NumElts && "Zeroable shuffle detected");
12335 if (!ZeroLo && !ZeroHi)
12336 return SDValue();
12337
12338 if (ZeroLo) {
12339 SDValue Src = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12340 int Low = Mask[ZeroLo] < (int)NumElts ? 0 : NumElts;
12341 if (isSequentialOrUndefInRange(Mask, ZeroLo, NumElts - ZeroLo, Low))
12342 return emitVALIGN(Src, getZeroVector(AlignVT, Subtarget, DAG, DL),
12343 NumElts - ZeroLo);
12344 }
12345
12346 if (ZeroHi) {
12347 SDValue Src = Mask[0] < (int)NumElts ? V1 : V2;
12348 int Low = Mask[0] < (int)NumElts ? 0 : NumElts;
12349 if (isSequentialOrUndefInRange(Mask, 0, NumElts - ZeroHi, Low + ZeroHi))
12350 return emitVALIGN(getZeroVector(AlignVT, Subtarget, DAG, DL), Src,
12351 ZeroHi);
12352 }
12353
12354 return SDValue();
12355}
12356
12357/// Try to lower a vector shuffle as a byte shift sequence.
12359 SDValue V2, ArrayRef<int> Mask,
12360 const APInt &Zeroable,
12361 const X86Subtarget &Subtarget,
12362 SelectionDAG &DAG) {
12363 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12364 assert(VT.is128BitVector() && "Only 128-bit vectors supported");
12365
12366 // We need a shuffle that has zeros at one/both ends and a sequential
12367 // shuffle from one source within.
12368 unsigned ZeroLo = Zeroable.countr_one();
12369 unsigned ZeroHi = Zeroable.countl_one();
12370 if (!ZeroLo && !ZeroHi)
12371 return SDValue();
12372
12373 unsigned NumElts = Mask.size();
12374 unsigned Len = NumElts - (ZeroLo + ZeroHi);
12375 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12376 return SDValue();
12377
12378 unsigned Scale = VT.getScalarSizeInBits() / 8;
12379 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12380 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12381 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12382 return SDValue();
12383
12384 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12385 Res = DAG.getBitcast(MVT::v16i8, Res);
12386
12387 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12388 // inner sequential set of elements, possibly offset:
12389 // 01234567 --> zzzzzz01 --> 1zzzzzzz
12390 // 01234567 --> 4567zzzz --> zzzzz456
12391 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12392 if (ZeroLo == 0) {
12393 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12394 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12395 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12396 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12397 DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12398 } else if (ZeroHi == 0) {
12399 unsigned Shift = Mask[ZeroLo] % NumElts;
12400 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12401 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12402 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12403 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12404 } else if (!Subtarget.hasSSSE3()) {
12405 // If we don't have PSHUFB then its worth avoiding an AND constant mask
12406 // by performing 3 byte shifts. Shuffle combining can kick in above that.
12407 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12408 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12409 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12410 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12411 Shift += Mask[ZeroLo] % NumElts;
12412 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12413 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12414 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12415 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12416 } else
12417 return SDValue();
12418
12419 return DAG.getBitcast(VT, Res);
12420}
12421
12422/// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12423///
12424/// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12425/// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12426/// matches elements from one of the input vectors shuffled to the left or
12427/// right with zeroable elements 'shifted in'. It handles both the strictly
12428/// bit-wise element shifts and the byte shift across an entire 128-bit double
12429/// quad word lane.
12430///
12431/// PSHL : (little-endian) left bit shift.
12432/// [ zz, 0, zz, 2 ]
12433/// [ -1, 4, zz, -1 ]
12434/// PSRL : (little-endian) right bit shift.
12435/// [ 1, zz, 3, zz]
12436/// [ -1, -1, 7, zz]
12437/// PSLLDQ : (little-endian) left byte shift
12438/// [ zz, 0, 1, 2, 3, 4, 5, 6]
12439/// [ zz, zz, -1, -1, 2, 3, 4, -1]
12440/// [ zz, zz, zz, zz, zz, zz, -1, 1]
12441/// PSRLDQ : (little-endian) right byte shift
12442/// [ 5, 6, 7, zz, zz, zz, zz, zz]
12443/// [ -1, 5, 6, 7, zz, zz, zz, zz]
12444/// [ 1, 2, -1, -1, -1, -1, zz, zz]
12445static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12446 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12447 int MaskOffset, const APInt &Zeroable,
12448 const X86Subtarget &Subtarget) {
12449 int Size = Mask.size();
12450 unsigned SizeInBits = Size * ScalarSizeInBits;
12451
12452 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12453 for (int i = 0; i < Size; i += Scale)
12454 for (int j = 0; j < Shift; ++j)
12455 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12456 return false;
12457
12458 return true;
12459 };
12460
12461 auto MatchShift = [&](int Shift, int Scale, bool Left) {
12462 for (int i = 0; i != Size; i += Scale) {
12463 unsigned Pos = Left ? i + Shift : i;
12464 unsigned Low = Left ? i : i + Shift;
12465 unsigned Len = Scale - Shift;
12466 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12467 return -1;
12468 }
12469
12470 int ShiftEltBits = ScalarSizeInBits * Scale;
12471 bool ByteShift = ShiftEltBits > 64;
12472 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12473 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12474 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12475
12476 // Normalize the scale for byte shifts to still produce an i64 element
12477 // type.
12478 Scale = ByteShift ? Scale / 2 : Scale;
12479
12480 // We need to round trip through the appropriate type for the shift.
12481 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12482 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12483 : MVT::getVectorVT(ShiftSVT, Size / Scale);
12484 return ShiftAmt;
12485 };
12486
12487 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12488 // keep doubling the size of the integer elements up to that. We can
12489 // then shift the elements of the integer vector by whole multiples of
12490 // their width within the elements of the larger integer vector. Test each
12491 // multiple to see if we can find a match with the moved element indices
12492 // and that the shifted in elements are all zeroable.
12493 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12494 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12495 for (int Shift = 1; Shift != Scale; ++Shift)
12496 for (bool Left : {true, false})
12497 if (CheckZeros(Shift, Scale, Left)) {
12498 int ShiftAmt = MatchShift(Shift, Scale, Left);
12499 if (0 < ShiftAmt)
12500 return ShiftAmt;
12501 }
12502
12503 // no match
12504 return -1;
12505}
12506
12508 SDValue V2, ArrayRef<int> Mask,
12509 const APInt &Zeroable,
12510 const X86Subtarget &Subtarget,
12511 SelectionDAG &DAG, bool BitwiseOnly) {
12512 int Size = Mask.size();
12513 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12514
12515 MVT ShiftVT;
12516 SDValue V = V1;
12517 unsigned Opcode;
12518
12519 // Try to match shuffle against V1 shift.
12520 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12521 Mask, 0, Zeroable, Subtarget);
12522
12523 // If V1 failed, try to match shuffle against V2 shift.
12524 if (ShiftAmt < 0) {
12525 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12526 Mask, Size, Zeroable, Subtarget);
12527 V = V2;
12528 }
12529
12530 if (ShiftAmt < 0)
12531 return SDValue();
12532
12533 if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
12534 return SDValue();
12535
12536 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
12537 "Illegal integer vector type");
12538 V = DAG.getBitcast(ShiftVT, V);
12539 V = DAG.getNode(Opcode, DL, ShiftVT, V,
12540 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12541 return DAG.getBitcast(VT, V);
12542}
12543
12544/// Try to match a vector shuffle as a X86ISD::VSHLD funnel shift.
12545static int matchShuffleAsVSHLD(MVT &ShiftVT, SDValue &V1, SDValue &V2,
12546 unsigned ScalarSizeInBits, ArrayRef<int> Mask) {
12547 assert(isPowerOf2_32(ScalarSizeInBits) && ScalarSizeInBits >= 8 &&
12548 "Unexpected element size");
12549 int Size = Mask.size();
12551 return -1;
12552
12553 SmallVector<int, 32> FunnelMask(Size);
12554 for (int Scale = 2; (Scale * ScalarSizeInBits) <= 64; Scale *= 2) {
12555 for (int Shift = 1; Shift != Scale; ++Shift) {
12556 for (int Elt = 0; Elt != Size; Elt += Scale) {
12557 std::iota(FunnelMask.begin() + Elt, FunnelMask.begin() + Elt + Shift,
12558 Elt + Size + (Scale - Shift));
12559 std::iota(FunnelMask.begin() + Elt + Shift,
12560 FunnelMask.begin() + Elt + Scale, Elt);
12561 }
12562 if (isShuffleEquivalent(Mask, FunnelMask)) {
12563 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12564 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12565 return Shift * ScalarSizeInBits;
12566 }
12568 if (isShuffleEquivalent(Mask, FunnelMask)) {
12569 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12570 ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
12571 std::swap(V1, V2);
12572 return Shift * ScalarSizeInBits;
12573 }
12574 }
12575 }
12576
12577 return -1;
12578}
12579
12580// EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12581// Remainder of lower half result is zero and upper half is all undef.
12583 ArrayRef<int> Mask, uint64_t &BitLen,
12584 uint64_t &BitIdx, const APInt &Zeroable) {
12585 int Size = Mask.size();
12586 int HalfSize = Size / 2;
12587 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12588 assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
12589
12590 // Upper half must be undefined.
12591 if (!isUndefUpperHalf(Mask))
12592 return false;
12593
12594 // Determine the extraction length from the part of the
12595 // lower half that isn't zeroable.
12596 int Len = HalfSize;
12597 for (; Len > 0; --Len)
12598 if (!Zeroable[Len - 1])
12599 break;
12600 assert(Len > 0 && "Zeroable shuffle mask");
12601
12602 // Attempt to match first Len sequential elements from the lower half.
12603 SDValue Src;
12604 int Idx = -1;
12605 for (int i = 0; i != Len; ++i) {
12606 int M = Mask[i];
12607 if (M == SM_SentinelUndef)
12608 continue;
12609 SDValue &V = (M < Size ? V1 : V2);
12610 M = M % Size;
12611
12612 // The extracted elements must start at a valid index and all mask
12613 // elements must be in the lower half.
12614 if (i > M || M >= HalfSize)
12615 return false;
12616
12617 if (Idx < 0 || (Src == V && Idx == (M - i))) {
12618 Src = V;
12619 Idx = M - i;
12620 continue;
12621 }
12622 return false;
12623 }
12624
12625 if (!Src || Idx < 0)
12626 return false;
12627
12628 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12629 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12630 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12631 V1 = Src;
12632 return true;
12633}
12634
12635// INSERTQ: Extract lowest Len elements from lower half of second source and
12636// insert over first source, starting at Idx.
12637// { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
12639 ArrayRef<int> Mask, uint64_t &BitLen,
12640 uint64_t &BitIdx) {
12641 int Size = Mask.size();
12642 int HalfSize = Size / 2;
12643 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12644
12645 // Upper half must be undefined.
12646 if (!isUndefUpperHalf(Mask))
12647 return false;
12648
12649 for (int Idx = 0; Idx != HalfSize; ++Idx) {
12650 SDValue Base;
12651
12652 // Attempt to match first source from mask before insertion point.
12653 if (isUndefInRange(Mask, 0, Idx)) {
12654 /* EMPTY */
12655 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12656 Base = V1;
12657 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12658 Base = V2;
12659 } else {
12660 continue;
12661 }
12662
12663 // Extend the extraction length looking to match both the insertion of
12664 // the second source and the remaining elements of the first.
12665 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12666 SDValue Insert;
12667 int Len = Hi - Idx;
12668
12669 // Match insertion.
12670 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12671 Insert = V1;
12672 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12673 Insert = V2;
12674 } else {
12675 continue;
12676 }
12677
12678 // Match the remaining elements of the lower half.
12679 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12680 /* EMPTY */
12681 } else if ((!Base || (Base == V1)) &&
12682 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12683 Base = V1;
12684 } else if ((!Base || (Base == V2)) &&
12685 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12686 Size + Hi)) {
12687 Base = V2;
12688 } else {
12689 continue;
12690 }
12691
12692 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12693 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12694 V1 = Base;
12695 V2 = Insert;
12696 return true;
12697 }
12698 }
12699
12700 return false;
12701}
12702
12703/// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
12705 SDValue V2, ArrayRef<int> Mask,
12706 const APInt &Zeroable, SelectionDAG &DAG) {
12707 uint64_t BitLen, BitIdx;
12708 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12709 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12710 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12711 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12712
12713 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12714 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12715 V2 ? V2 : DAG.getUNDEF(VT),
12716 DAG.getTargetConstant(BitLen, DL, MVT::i8),
12717 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12718
12719 return SDValue();
12720}
12721
12722/// Lower a vector shuffle as an any/signed/zero extension.
12723///
12724/// Given a specific number of elements, element bit width, and extension
12725/// stride, produce either an extension based on the available
12726/// features of the subtarget. The extended elements are consecutive and
12727/// begin and can start from an offsetted element index in the input; to
12728/// avoid excess shuffling the offset must either being in the bottom lane
12729/// or at the start of a higher lane. All extended elements must be from
12730/// the same lane.
12732 int Scale, int Offset,
12733 unsigned ExtOpc, SDValue InputV,
12734 ArrayRef<int> Mask,
12735 const X86Subtarget &Subtarget,
12736 SelectionDAG &DAG) {
12737 assert(Scale > 1 && "Need a scale to extend.");
12738 assert(ISD::isExtOpcode(ExtOpc) && "Unsupported extension");
12739 int EltBits = VT.getScalarSizeInBits();
12740 int NumElements = VT.getVectorNumElements();
12741 int NumEltsPerLane = 128 / EltBits;
12742 int OffsetLane = Offset / NumEltsPerLane;
12743 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12744 "Only 8, 16, and 32 bit elements can be extended.");
12745 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12746 assert(0 <= Offset && "Extension offset must be positive.");
12747 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12748 "Extension offset must be in the first lane or start an upper lane.");
12749
12750 // Check that an index is in same lane as the base offset.
12751 auto SafeOffset = [&](int Idx) {
12752 return OffsetLane == (Idx / NumEltsPerLane);
12753 };
12754
12755 // Shift along an input so that the offset base moves to the first element.
12756 auto ShuffleOffset = [&](SDValue V) {
12757 if (!Offset)
12758 return V;
12759
12760 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12761 for (int i = 0; i * Scale < NumElements; ++i) {
12762 int SrcIdx = i + Offset;
12763 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12764 }
12765 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12766 };
12767
12768 // Found a valid a/zext mask! Try various lowering strategies based on the
12769 // input type and available ISA extensions.
12770 if (Subtarget.hasSSE41()) {
12771 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12772 // PUNPCK will catch this in a later shuffle match.
12773 if (Offset && Scale == 2 && VT.is128BitVector())
12774 return SDValue();
12775 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12776 NumElements / Scale);
12777 InputV = DAG.getBitcast(VT, InputV);
12778 InputV = ShuffleOffset(InputV);
12779 InputV = getEXTEND_VECTOR_INREG(ExtOpc, DL, ExtVT, InputV, DAG);
12780 return DAG.getBitcast(VT, InputV);
12781 }
12782
12783 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12784 InputV = DAG.getBitcast(VT, InputV);
12785 bool AnyExt = ExtOpc == ISD::ANY_EXTEND;
12786
12787 // TODO: Add pre-SSE41 SIGN_EXTEND_VECTOR_INREG handling.
12788 if (ExtOpc == ISD::SIGN_EXTEND)
12789 return SDValue();
12790
12791 // For any extends we can cheat for larger element sizes and use shuffle
12792 // instructions that can fold with a load and/or copy.
12793 if (AnyExt && EltBits == 32) {
12794 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12795 -1};
12796 return DAG.getBitcast(
12797 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12798 DAG.getBitcast(MVT::v4i32, InputV),
12799 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12800 }
12801 if (AnyExt && EltBits == 16 && Scale > 2) {
12802 int PSHUFDMask[4] = {Offset / 2, -1,
12803 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12804 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12805 DAG.getBitcast(MVT::v4i32, InputV),
12806 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12807 int PSHUFWMask[4] = {1, -1, -1, -1};
12808 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12809 return DAG.getBitcast(
12810 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12811 DAG.getBitcast(MVT::v8i16, InputV),
12812 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12813 }
12814
12815 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12816 // to 64-bits.
12817 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12818 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12819 assert(VT.is128BitVector() && "Unexpected vector width!");
12820
12821 int LoIdx = Offset * EltBits;
12822 SDValue Lo = DAG.getBitcast(
12823 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12824 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12825 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12826
12827 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12828 return DAG.getBitcast(VT, Lo);
12829
12830 int HiIdx = (Offset + 1) * EltBits;
12831 SDValue Hi = DAG.getBitcast(
12832 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12833 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12834 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12835 return DAG.getBitcast(VT,
12836 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12837 }
12838
12839 // If this would require more than 2 unpack instructions to expand, use
12840 // pshufb when available. We can only use more than 2 unpack instructions
12841 // when zero extending i8 elements which also makes it easier to use pshufb.
12842 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12843 assert(NumElements == 16 && "Unexpected byte vector width!");
12844 SDValue PSHUFBMask[16];
12845 for (int i = 0; i < 16; ++i) {
12846 int Idx = Offset + (i / Scale);
12847 if ((i % Scale == 0 && SafeOffset(Idx))) {
12848 PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12849 continue;
12850 }
12851 PSHUFBMask[i] =
12852 AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12853 }
12854 InputV = DAG.getBitcast(MVT::v16i8, InputV);
12855 return DAG.getBitcast(
12856 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12857 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12858 }
12859
12860 // If we are extending from an offset, ensure we start on a boundary that
12861 // we can unpack from.
12862 int AlignToUnpack = Offset % (NumElements / Scale);
12863 if (AlignToUnpack) {
12864 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12865 for (int i = AlignToUnpack; i < NumElements; ++i)
12866 ShMask[i - AlignToUnpack] = i;
12867 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12868 Offset -= AlignToUnpack;
12869 }
12870
12871 // Otherwise emit a sequence of unpacks.
12872 do {
12873 unsigned UnpackLoHi = X86ISD::UNPCKL;
12874 if (Offset >= (NumElements / 2)) {
12875 UnpackLoHi = X86ISD::UNPCKH;
12876 Offset -= (NumElements / 2);
12877 }
12878
12879 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12880 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12881 : getZeroVector(InputVT, Subtarget, DAG, DL);
12882 InputV = DAG.getBitcast(InputVT, InputV);
12883 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12884 Scale /= 2;
12885 EltBits *= 2;
12886 NumElements /= 2;
12887 } while (Scale > 1);
12888 return DAG.getBitcast(VT, InputV);
12889}
12890
12891/// Try to lower a vector shuffle as a zero extension on any microarch.
12892///
12893/// This routine will try to do everything in its power to cleverly lower
12894/// a shuffle which happens to match the pattern of a zero extend. It doesn't
12895/// check for the profitability of this lowering, it tries to aggressively
12896/// match this pattern. It will use all of the micro-architectural details it
12897/// can to emit an efficient lowering. It handles both blends with all-zero
12898/// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12899/// masking out later).
12900///
12901/// The reason we have dedicated lowering for zext-style shuffles is that they
12902/// are both incredibly common and often quite performance sensitive.
12904 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12905 const APInt &Zeroable, const X86Subtarget &Subtarget,
12906 SelectionDAG &DAG) {
12907 int Bits = VT.getSizeInBits();
12908 int NumLanes = Bits / 128;
12909 int NumElements = VT.getVectorNumElements();
12910 int NumEltsPerLane = NumElements / NumLanes;
12911 assert(VT.getScalarSizeInBits() <= 32 &&
12912 "Exceeds 32-bit integer zero extension limit");
12913 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12914
12915 // Define a helper function to check a particular ext-scale and lower to it if
12916 // valid.
12917 auto Lower = [&](int Scale) -> SDValue {
12918 SDValue InputV;
12919 bool AnyExt = true;
12920 int Offset = 0;
12921 int Matches = 0;
12922 for (int i = 0; i < NumElements; ++i) {
12923 int M = Mask[i];
12924 if (M < 0)
12925 continue; // Valid anywhere but doesn't tell us anything.
12926 if (i % Scale != 0) {
12927 // Each of the extended elements need to be zeroable.
12928 if (!Zeroable[i])
12929 return SDValue();
12930
12931 // We no longer are in the anyext case.
12932 AnyExt = false;
12933 continue;
12934 }
12935
12936 // Each of the base elements needs to be consecutive indices into the
12937 // same input vector.
12938 SDValue V = M < NumElements ? V1 : V2;
12939 M = M % NumElements;
12940 if (!InputV) {
12941 InputV = V;
12942 Offset = M - (i / Scale);
12943 } else if (InputV != V)
12944 return SDValue(); // Flip-flopping inputs.
12945
12946 // Offset must start in the lowest 128-bit lane or at the start of an
12947 // upper lane.
12948 // FIXME: Is it ever worth allowing a negative base offset?
12949 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12950 (Offset % NumEltsPerLane) == 0))
12951 return SDValue();
12952
12953 // If we are offsetting, all referenced entries must come from the same
12954 // lane.
12955 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12956 return SDValue();
12957
12958 if ((M % NumElements) != (Offset + (i / Scale)))
12959 return SDValue(); // Non-consecutive strided elements.
12960 Matches++;
12961 }
12962
12963 // If we fail to find an input, we have a zero-shuffle which should always
12964 // have already been handled.
12965 // FIXME: Maybe handle this here in case during blending we end up with one?
12966 if (!InputV)
12967 return SDValue();
12968
12969 // If we are offsetting, don't extend if we only match a single input, we
12970 // can always do better by using a basic PSHUF or PUNPCK.
12971 if (Offset != 0 && Matches < 2)
12972 return SDValue();
12973
12974 unsigned ExtOpc = AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND;
12975 return lowerShuffleAsSpecificExtension(DL, VT, Scale, Offset, ExtOpc,
12976 InputV, Mask, Subtarget, DAG);
12977 };
12978
12979 // Match against a foldable v4i32 VZEXT_MOVL zero-extending instruction.
12980 // TODO: Add v8i16 (with FP16) support when we have test coverage.
12981 if (VT == MVT::v4i32 &&
12982 (V1.getOpcode() == ISD::SCALAR_TO_VECTOR || isa<MemSDNode>(V1)) &&
12983 Mask[0] == 0 && (NumElements - 1) == (int)Zeroable.countLeadingOnes())
12984 return DAG.getNode(X86ISD::VZEXT_MOVL, DL, VT, V1);
12985
12986 // The widest scale possible for extending is to a 64-bit integer.
12987 assert(Bits % 64 == 0 &&
12988 "The number of bits in a vector must be divisible by 64 on x86!");
12989 int NumExtElements = Bits / 64;
12990
12991 // Each iteration, try extending the elements half as much, but into twice as
12992 // many elements.
12993 for (; NumExtElements < NumElements; NumExtElements *= 2) {
12994 assert(NumElements % NumExtElements == 0 &&
12995 "The input vector size must be divisible by the extended size.");
12996 if (SDValue V = Lower(NumElements / NumExtElements))
12997 return V;
12998 }
12999
13000 // General extends failed, but 128-bit vectors may be able to use MOVQ.
13001 if (Bits != 128)
13002 return SDValue();
13003
13004 // Returns one of the source operands if the shuffle can be reduced to a
13005 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13006 auto CanZExtLowHalf = [&]() {
13007 for (int i = NumElements / 2; i != NumElements; ++i)
13008 if (!Zeroable[i])
13009 return SDValue();
13010 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13011 return V1;
13012 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13013 return V2;
13014 return SDValue();
13015 };
13016
13017 if (SDValue V = CanZExtLowHalf()) {
13018 V = DAG.getBitcast(MVT::v2i64, V);
13019 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13020 return DAG.getBitcast(VT, V);
13021 }
13022
13023 // No viable ext lowering found.
13024 return SDValue();
13025}
13026
13027/// Try to get a scalar value for a specific element of a vector.
13028///
13029/// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13031 SelectionDAG &DAG) {
13032 MVT VT = V.getSimpleValueType();
13033 MVT EltVT = VT.getVectorElementType();
13034 V = peekThroughBitcasts(V);
13035
13036 // If the bitcasts shift the element size, we can't extract an equivalent
13037 // element from it.
13038 MVT NewVT = V.getSimpleValueType();
13039 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13040 return SDValue();
13041
13042 if (V.getOpcode() == ISD::BUILD_VECTOR ||
13043 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13044 // Ensure the scalar operand is the same size as the destination.
13045 // FIXME: Add support for scalar truncation where possible.
13046 SDValue S = V.getOperand(Idx);
13047 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13048 return DAG.getBitcast(EltVT, S);
13049 }
13050
13051 return SDValue();
13052}
13053
13054/// Helper to test for a load that can be folded with x86 shuffles.
13055///
13056/// This is particularly important because the set of instructions varies
13057/// significantly based on whether the operand is a load or not.
13059 return V.hasOneUse() &&
13061}
13062
13063template<typename T>
13064static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
13065 T EltVT = VT.getScalarType();
13066 return (EltVT == MVT::bf16 && !Subtarget.hasAVX10_2()) ||
13067 (EltVT == MVT::f16 && !Subtarget.hasFP16());
13068}
13069
13070template<typename T>
13071static bool isBF16orSoftF16(T VT, const X86Subtarget &Subtarget) {
13072 T EltVT = VT.getScalarType();
13073 return EltVT == MVT::bf16 || (EltVT == MVT::f16 && !Subtarget.hasFP16());
13074}
13075
13076/// Try to lower insertion of a single element into a zero vector.
13077///
13078/// This is a common pattern that we have especially efficient patterns to lower
13079/// across all subtarget feature sets.
13081 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13082 const APInt &Zeroable, const X86Subtarget &Subtarget,
13083 SelectionDAG &DAG) {
13084 MVT ExtVT = VT;
13085 MVT EltVT = VT.getVectorElementType();
13086 unsigned NumElts = VT.getVectorNumElements();
13087 unsigned EltBits = VT.getScalarSizeInBits();
13088
13089 if (isSoftF16(EltVT, Subtarget))
13090 return SDValue();
13091
13092 int V2Index =
13093 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13094 Mask.begin();
13095 bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
13096 bool IsV1Zeroable = true;
13097 for (int i = 0, Size = Mask.size(); i < Size; ++i)
13098 if (i != V2Index && !Zeroable[i]) {
13099 IsV1Zeroable = false;
13100 break;
13101 }
13102
13103 // Bail if a non-zero V1 isn't used in place.
13104 if (!IsV1Zeroable) {
13105 SmallVector<int, 8> V1Mask(Mask);
13106 V1Mask[V2Index] = -1;
13107 if (!isNoopShuffleMask(V1Mask))
13108 return SDValue();
13109 }
13110
13111 // Check for a single input from a SCALAR_TO_VECTOR node.
13112 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13113 // all the smarts here sunk into that routine. However, the current
13114 // lowering of BUILD_VECTOR makes that nearly impossible until the old
13115 // vector shuffle lowering is dead.
13116 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13117 DAG);
13118 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13119 // We need to zext the scalar if it is smaller than an i32.
13120 V2S = DAG.getBitcast(EltVT, V2S);
13121 if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
13122 // Using zext to expand a narrow element won't work for non-zero
13123 // insertions. But we can use a masked constant vector if we're
13124 // inserting V2 into the bottom of V1.
13125 if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
13126 return SDValue();
13127
13128 // Zero-extend directly to i32.
13129 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13130 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13131
13132 // If we're inserting into a constant, mask off the inserted index
13133 // and OR with the zero-extended scalar.
13134 if (!IsV1Zeroable) {
13135 SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
13136 Bits[V2Index] = APInt::getZero(EltBits);
13137 SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
13138 V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
13139 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13140 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
13141 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
13142 }
13143 }
13144 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13145 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13146 (EltVT == MVT::i16 && !Subtarget.hasAVX10_2())) {
13147 // Either not inserting from the low element of the input or the input
13148 // element size is too small to use VZEXT_MOVL to clear the high bits.
13149 return SDValue();
13150 }
13151
13152 if (!IsV1Zeroable) {
13153 // If V1 can't be treated as a zero vector we have fewer options to lower
13154 // this. We can't support integer vectors or non-zero targets cheaply.
13155 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13156 if (!VT.isFloatingPoint() || V2Index != 0)
13157 return SDValue();
13158 if (!VT.is128BitVector())
13159 return SDValue();
13160
13161 // Otherwise, use MOVSD, MOVSS or MOVSH.
13162 unsigned MovOpc = 0;
13163 if (EltVT == MVT::f16)
13164 MovOpc = X86ISD::MOVSH;
13165 else if (EltVT == MVT::f32)
13166 MovOpc = X86ISD::MOVSS;
13167 else if (EltVT == MVT::f64)
13168 MovOpc = X86ISD::MOVSD;
13169 else
13170 llvm_unreachable("Unsupported floating point element type to handle!");
13171 return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
13172 }
13173
13174 // This lowering only works for the low element with floating point vectors.
13175 if (VT.isFloatingPoint() && V2Index != 0)
13176 return SDValue();
13177
13178 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13179 if (ExtVT != VT)
13180 V2 = DAG.getBitcast(VT, V2);
13181
13182 if (V2Index != 0) {
13183 // If we have 4 or fewer lanes we can cheaply shuffle the element into
13184 // the desired position. Otherwise it is more efficient to do a vector
13185 // shift left. We know that we can do a vector shift left because all
13186 // the inputs are zero.
13187 if (VT.isFloatingPoint() || NumElts <= 4) {
13188 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13189 V2Shuffle[V2Index] = 0;
13190 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13191 } else {
13192 V2 = DAG.getBitcast(MVT::v16i8, V2);
13193 V2 = DAG.getNode(
13194 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13195 DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
13196 V2 = DAG.getBitcast(VT, V2);
13197 }
13198 }
13199 return V2;
13200}
13201
13202/// Try to lower broadcast of a single - truncated - integer element,
13203/// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13204///
13205/// This assumes we have AVX2.
13207 int BroadcastIdx,
13208 const X86Subtarget &Subtarget,
13209 SelectionDAG &DAG) {
13210 assert(Subtarget.hasAVX2() &&
13211 "We can only lower integer broadcasts with AVX2!");
13212
13213 MVT EltVT = VT.getVectorElementType();
13214 MVT V0VT = V0.getSimpleValueType();
13215
13216 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
13217 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
13218
13219 MVT V0EltVT = V0VT.getVectorElementType();
13220 if (!V0EltVT.isInteger())
13221 return SDValue();
13222
13223 const unsigned EltSize = EltVT.getSizeInBits();
13224 const unsigned V0EltSize = V0EltVT.getSizeInBits();
13225
13226 // This is only a truncation if the original element type is larger.
13227 if (V0EltSize <= EltSize)
13228 return SDValue();
13229
13230 assert(((V0EltSize % EltSize) == 0) &&
13231 "Scalar type sizes must all be powers of 2 on x86!");
13232
13233 const unsigned V0Opc = V0.getOpcode();
13234 const unsigned Scale = V0EltSize / EltSize;
13235 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13236
13237 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13238 V0Opc != ISD::BUILD_VECTOR)
13239 return SDValue();
13240
13241 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13242
13243 // If we're extracting non-least-significant bits, shift so we can truncate.
13244 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13245 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13246 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13247 if (const int OffsetIdx = BroadcastIdx % Scale)
13248 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13249 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13250
13251 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13252 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13253}
13254
13255/// Test whether this can be lowered with a single SHUFPS instruction.
13256///
13257/// This is used to disable more specialized lowerings when the shufps lowering
13258/// will happen to be efficient.
13260 // This routine only handles 128-bit shufps.
13261 assert(Mask.size() == 4 && "Unsupported mask size!");
13262 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
13263 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
13264 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
13265 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
13266
13267 // To lower with a single SHUFPS we need to have the low half and high half
13268 // each requiring a single input.
13269 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13270 return false;
13271 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13272 return false;
13273
13274 return true;
13275}
13276
13277/// Test whether the specified input (0 or 1) is in-place blended by the
13278/// given mask.
13279///
13280/// This returns true if the elements from a particular input are already in the
13281/// slot required by the given mask and require no permutation.
13283 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
13284 int Size = Mask.size();
13285 for (int i = 0; i < Size; ++i)
13286 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
13287 return false;
13288
13289 return true;
13290}
13291
13292/// Test whether the specified input (0 or 1) is a broadcast/splat blended by
13293/// the given mask.
13294///
13296 int BroadcastableElement = 0) {
13297 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
13298 int Size = Mask.size();
13299 for (int i = 0; i < Size; ++i)
13300 if (Mask[i] >= 0 && Mask[i] / Size == Input &&
13301 Mask[i] % Size != BroadcastableElement)
13302 return false;
13303 return true;
13304}
13305
13306/// If we are extracting two 128-bit halves of a vector and shuffling the
13307/// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13308/// multi-shuffle lowering.
13310 SDValue N1, ArrayRef<int> Mask,
13311 SelectionDAG &DAG) {
13312 MVT VT = N0.getSimpleValueType();
13313 assert((VT.is128BitVector() &&
13314 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
13315 "VPERM* family of shuffles requires 32-bit or 64-bit elements");
13316
13317 // Check that both sources are extracts of the same source vector.
13318 if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13320 N0.getOperand(0) != N1.getOperand(0) ||
13321 !N0.hasOneUse() || !N1.hasOneUse())
13322 return SDValue();
13323
13324 SDValue WideVec = N0.getOperand(0);
13325 MVT WideVT = WideVec.getSimpleValueType();
13326 if (!WideVT.is256BitVector())
13327 return SDValue();
13328
13329 // Match extracts of each half of the wide source vector. Commute the shuffle
13330 // if the extract of the low half is N1.
13331 unsigned NumElts = VT.getVectorNumElements();
13332 SmallVector<int, 4> NewMask(Mask);
13333 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13334 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13335 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13337 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13338 return SDValue();
13339
13340 // Final bailout: if the mask is simple, we are better off using an extract
13341 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13342 // because that avoids a constant load from memory.
13343 if (NumElts == 4 &&
13344 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
13345 return SDValue();
13346
13347 // Extend the shuffle mask with undef elements.
13348 NewMask.append(NumElts, -1);
13349
13350 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13351 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13352 NewMask);
13353 // This is free: ymm -> xmm.
13354 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13355 DAG.getVectorIdxConstant(0, DL));
13356}
13357
13358/// Try to lower broadcast of a single element.
13359///
13360/// For convenience, this code also bundles all of the subtarget feature set
13361/// filtering. While a little annoying to re-dispatch on type here, there isn't
13362/// a convenient way to factor it out.
13364 SDValue V2, ArrayRef<int> Mask,
13365 const X86Subtarget &Subtarget,
13366 SelectionDAG &DAG) {
13367 MVT EltVT = VT.getVectorElementType();
13368 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13369 (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
13370 (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
13371 return SDValue();
13372
13373 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13374 // we can only broadcast from a register with AVX2.
13375 unsigned NumEltBits = VT.getScalarSizeInBits();
13376 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13377 ? X86ISD::MOVDDUP
13378 : X86ISD::VBROADCAST;
13379 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13380
13381 // Check that the mask is a broadcast.
13382 int BroadcastIdx = getSplatIndex(Mask);
13383 if (BroadcastIdx < 0) {
13384 // Check for hidden broadcast.
13385 SmallVector<int, 16> BroadcastMask(VT.getVectorNumElements(), 0);
13386 if (!isShuffleEquivalent(Mask, BroadcastMask, V1, V2))
13387 return SDValue();
13388 BroadcastIdx = 0;
13389 }
13390 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
13391 "a sorted mask where the broadcast "
13392 "comes from V1.");
13393 int NumActiveElts = count_if(Mask, [](int M) { return M >= 0; });
13394
13395 // Go up the chain of (vector) values to find a scalar load that we can
13396 // combine with the broadcast.
13397 // TODO: Combine this logic with findEltLoadSrc() used by
13398 // EltsFromConsecutiveLoads().
13399 int BitOffset = BroadcastIdx * NumEltBits;
13400 SDValue V = V1;
13401 for (;;) {
13402 switch (V.getOpcode()) {
13403 case ISD::BITCAST: {
13404 V = V.getOperand(0);
13405 continue;
13406 }
13407 case ISD::CONCAT_VECTORS: {
13408 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13409 int OpIdx = BitOffset / OpBitWidth;
13410 V = V.getOperand(OpIdx);
13411 BitOffset %= OpBitWidth;
13412 continue;
13413 }
13415 // The extraction index adds to the existing offset.
13416 unsigned EltBitWidth = V.getScalarValueSizeInBits();
13417 unsigned Idx = V.getConstantOperandVal(1);
13418 unsigned BeginOffset = Idx * EltBitWidth;
13419 BitOffset += BeginOffset;
13420 V = V.getOperand(0);
13421 continue;
13422 }
13423 case ISD::INSERT_SUBVECTOR: {
13424 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13425 int EltBitWidth = VOuter.getScalarValueSizeInBits();
13426 int Idx = (int)V.getConstantOperandVal(2);
13427 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13428 int BeginOffset = Idx * EltBitWidth;
13429 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13430 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13431 BitOffset -= BeginOffset;
13432 V = VInner;
13433 } else {
13434 V = VOuter;
13435 }
13436 continue;
13437 }
13438 }
13439 break;
13440 }
13441 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
13442 BroadcastIdx = BitOffset / NumEltBits;
13443
13444 // Do we need to bitcast the source to retrieve the original broadcast index?
13445 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13446
13447 // Check if this is a broadcast of a scalar. We special case lowering
13448 // for scalars so that we can more effectively fold with loads.
13449 // If the original value has a larger element type than the shuffle, the
13450 // broadcast element is in essence truncated. Make that explicit to ease
13451 // folding.
13452 if (BitCastSrc && VT.isInteger())
13453 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13454 DL, VT, V, BroadcastIdx, Subtarget, DAG))
13455 return TruncBroadcast;
13456
13457 // Also check the simpler case, where we can directly reuse the scalar.
13458 if (!BitCastSrc &&
13459 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13460 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13461 V = V.getOperand(BroadcastIdx);
13462
13463 // If we can't broadcast from a register, check that the input is a load.
13464 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13465 return SDValue();
13466 } else if (ISD::isNormalLoad(V.getNode()) &&
13467 cast<LoadSDNode>(V)->isSimple()) {
13468 // We do not check for one-use of the vector load because a broadcast load
13469 // is expected to be a win for code size, register pressure, and possibly
13470 // uops even if the original vector load is not eliminated.
13471
13472 // Reduce the vector load and shuffle to a broadcasted scalar load.
13473 auto *Ld = cast<LoadSDNode>(V);
13474 SDValue BaseAddr = Ld->getBasePtr();
13475 MVT SVT = VT.getScalarType();
13476 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13477 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
13478 SDValue NewAddr =
13480
13481 // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13482 // than MOVDDUP.
13483 // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13484 if (Opcode == X86ISD::VBROADCAST) {
13485 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13486 SDValue Ops[] = {Ld->getChain(), NewAddr};
13487 V = DAG.getMemIntrinsicNode(
13488 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13490 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13492 return DAG.getBitcast(VT, V);
13493 }
13494 assert(SVT == MVT::f64 && "Unexpected VT!");
13495 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13497 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13499 } else if (!BroadcastFromReg) {
13500 // We can't broadcast from a vector register.
13501 return SDValue();
13502 } else if (BitOffset != 0) {
13503 // We can only broadcast from the zero-element of a vector register,
13504 // but it can be advantageous to broadcast from the zero-element of a
13505 // subvector.
13506 if (!VT.is256BitVector() && !VT.is512BitVector())
13507 return SDValue();
13508
13509 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13510 if (VT == MVT::v4f64 || VT == MVT::v4i64)
13511 return SDValue();
13512
13513 // If we are broadcasting an element from the lowest 128-bit subvector, try
13514 // to move the element in position.
13515 if (BitOffset < 128 && NumActiveElts > 1 &&
13516 V.getScalarValueSizeInBits() == NumEltBits) {
13517 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13518 "Unexpected bit-offset");
13519 SmallVector<int, 16> ExtractMask(128 / NumEltBits, SM_SentinelUndef);
13520 ExtractMask[0] = BitOffset / V.getScalarValueSizeInBits();
13521 V = extractSubVector(V, 0, DAG, DL, 128);
13522 V = DAG.getVectorShuffle(V.getValueType(), DL, V, V, ExtractMask);
13523 } else {
13524 // Only broadcast the zero-element of a 128-bit subvector.
13525 if ((BitOffset % 128) != 0)
13526 return SDValue();
13527
13528 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13529 "Unexpected bit-offset");
13530 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
13531 "Unexpected vector size");
13532 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13533 V = extract128BitVector(V, ExtractIdx, DAG, DL);
13534 }
13535 }
13536
13537 // On AVX we can use VBROADCAST directly for scalar sources.
13538 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
13539 V = DAG.getBitcast(MVT::f64, V);
13540 if (Subtarget.hasAVX()) {
13541 V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
13542 return DAG.getBitcast(VT, V);
13543 }
13544 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
13545 }
13546
13547 // If this is a scalar, do the broadcast on this type and bitcast.
13548 if (!V.getValueType().isVector()) {
13549 assert(V.getScalarValueSizeInBits() == NumEltBits &&
13550 "Unexpected scalar size");
13551 MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13553 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13554 }
13555
13556 // We only support broadcasting from 128-bit vectors to minimize the
13557 // number of patterns we need to deal with in isel. So extract down to
13558 // 128-bits, removing as many bitcasts as possible.
13559 if (V.getValueSizeInBits() > 128)
13561
13562 // Otherwise cast V to a vector with the same element type as VT, but
13563 // possibly narrower than VT. Then perform the broadcast.
13564 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13565 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13566 return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13567}
13568
13569// Check for whether we can use INSERTPS to perform the shuffle. We only use
13570// INSERTPS when the V1 elements are already in the correct locations
13571// because otherwise we can just always use two SHUFPS instructions which
13572// are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13573// perform INSERTPS if a single V1 element is out of place and all V2
13574// elements are zeroable.
13576 unsigned &InsertPSMask,
13577 const APInt &Zeroable,
13578 ArrayRef<int> Mask, SelectionDAG &DAG) {
13579 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
13580 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
13581 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13582
13583 // Attempt to match INSERTPS with one element from VA or VB being
13584 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13585 // are updated.
13586 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13587 ArrayRef<int> CandidateMask) {
13588 unsigned ZMask = 0;
13589 int VADstIndex = -1;
13590 int VBDstIndex = -1;
13591 bool VAUsedInPlace = false;
13592
13593 for (int i = 0; i < 4; ++i) {
13594 // Synthesize a zero mask from the zeroable elements (includes undefs).
13595 if (Zeroable[i]) {
13596 ZMask |= 1 << i;
13597 continue;
13598 }
13599
13600 // Flag if we use any VA inputs in place.
13601 if (i == CandidateMask[i]) {
13602 VAUsedInPlace = true;
13603 continue;
13604 }
13605
13606 // We can only insert a single non-zeroable element.
13607 if (VADstIndex >= 0 || VBDstIndex >= 0)
13608 return false;
13609
13610 if (CandidateMask[i] < 4) {
13611 // VA input out of place for insertion.
13612 VADstIndex = i;
13613 } else {
13614 // VB input for insertion.
13615 VBDstIndex = i;
13616 }
13617 }
13618
13619 // Don't bother if we have no (non-zeroable) element for insertion.
13620 if (VADstIndex < 0 && VBDstIndex < 0)
13621 return false;
13622
13623 // Determine element insertion src/dst indices. The src index is from the
13624 // start of the inserted vector, not the start of the concatenated vector.
13625 unsigned VBSrcIndex = 0;
13626 if (VADstIndex >= 0) {
13627 // If we have a VA input out of place, we use VA as the V2 element
13628 // insertion and don't use the original V2 at all.
13629 VBSrcIndex = CandidateMask[VADstIndex];
13630 VBDstIndex = VADstIndex;
13631 VB = VA;
13632 } else {
13633 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13634 }
13635
13636 // If no V1 inputs are used in place, then the result is created only from
13637 // the zero mask and the V2 insertion - so remove V1 dependency.
13638 if (!VAUsedInPlace)
13639 VA = DAG.getUNDEF(MVT::v4f32);
13640
13641 // Update V1, V2 and InsertPSMask accordingly.
13642 V1 = VA;
13643 V2 = VB;
13644
13645 // Insert the V2 element into the desired position.
13646 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13647 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
13648 return true;
13649 };
13650
13651 if (matchAsInsertPS(V1, V2, Mask))
13652 return true;
13653
13654 // Commute and try again.
13655 SmallVector<int, 4> CommutedMask(Mask);
13657 if (matchAsInsertPS(V2, V1, CommutedMask))
13658 return true;
13659
13660 return false;
13661}
13662
13664 ArrayRef<int> Mask, const APInt &Zeroable,
13665 SelectionDAG &DAG) {
13666 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13667 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13668
13669 // Attempt to match the insertps pattern.
13670 unsigned InsertPSMask = 0;
13671 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13672 return SDValue();
13673
13674 // Insert the V2 element into the desired position.
13675 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13676 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13677}
13678
13679/// Handle lowering of 2-lane 64-bit floating point shuffles.
13680///
13681/// This is the basis function for the 2-lane 64-bit shuffles as we have full
13682/// support for floating point shuffles but not integer shuffles. These
13683/// instructions will incur a domain crossing penalty on some chips though so
13684/// it is better to avoid lowering through this for integer vectors where
13685/// possible.
13687 const APInt &Zeroable, SDValue V1, SDValue V2,
13688 const X86Subtarget &Subtarget,
13689 SelectionDAG &DAG) {
13690 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13691 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13692 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13693
13694 if (V2.isUndef()) {
13695 // Check for being able to broadcast a single element.
13696 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13697 Mask, Subtarget, DAG))
13698 return Broadcast;
13699
13700 // Straight shuffle of a single input vector. Simulate this by using the
13701 // single input as both of the "inputs" to this instruction..
13702 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13703
13704 if (Subtarget.hasAVX()) {
13705 // If we have AVX, we can use VPERMILPS which will allow folding a load
13706 // into the shuffle.
13707 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13708 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13709 }
13710
13711 return DAG.getNode(
13712 X86ISD::SHUFP, DL, MVT::v2f64,
13713 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13714 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13715 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13716 }
13717 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13718 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13719 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13720 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13721
13722 if (Subtarget.hasAVX2())
13723 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13724 return Extract;
13725
13726 // When loading a scalar and then shuffling it into a vector we can often do
13727 // the insertion cheaply.
13729 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13730 return Insertion;
13731 // Try inverting the insertion since for v2 masks it is easy to do and we
13732 // can't reliably sort the mask one way or the other.
13733 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13734 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13736 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13737 return Insertion;
13738
13739 // Try to use one of the special instruction patterns to handle two common
13740 // blend patterns if a zero-blend above didn't work.
13741 if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
13742 isShuffleEquivalent(Mask, {1, 3}, V1, V2))
13743 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13744 // We can either use a special instruction to load over the low double or
13745 // to move just the low double.
13746 return DAG.getNode(
13747 X86ISD::MOVSD, DL, MVT::v2f64, V2,
13748 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13749
13750 if (Subtarget.hasSSE41())
13751 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13752 Zeroable, Subtarget, DAG))
13753 return Blend;
13754
13755 // Use dedicated unpack instructions for masks that match their pattern.
13756 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, V1, V2, Mask, DAG))
13757 return V;
13758
13759 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13760 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13761 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13762}
13763
13764/// Handle lowering of 2-lane 64-bit integer shuffles.
13765///
13766/// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13767/// the integer unit to minimize domain crossing penalties. However, for blends
13768/// it falls back to the floating point shuffle operation with appropriate bit
13769/// casting.
13771 const APInt &Zeroable, SDValue V1, SDValue V2,
13772 const X86Subtarget &Subtarget,
13773 SelectionDAG &DAG) {
13774 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13775 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13776 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13777
13778 if (V2.isUndef()) {
13779 // Check for being able to broadcast a single element.
13780 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13781 Mask, Subtarget, DAG))
13782 return Broadcast;
13783
13784 // Straight shuffle of a single input vector. For everything from SSE2
13785 // onward this has a single fast instruction with no scary immediates.
13786 // We have to map the mask as it is actually a v4i32 shuffle instruction.
13787 V1 = DAG.getBitcast(MVT::v4i32, V1);
13788 int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
13789 Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
13790 Mask[1] < 0 ? -1 : (Mask[1] * 2),
13791 Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
13792 return DAG.getBitcast(
13793 MVT::v2i64,
13794 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13795 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13796 }
13797 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13798 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13799 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13800 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13801
13802 if (Subtarget.hasAVX2())
13803 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13804 return Extract;
13805
13806 // Try to use shift instructions.
13807 if (SDValue Shift =
13808 lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
13809 DAG, /*BitwiseOnly*/ false))
13810 return Shift;
13811
13812 // When loading a scalar and then shuffling it into a vector we can often do
13813 // the insertion cheaply.
13815 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13816 return Insertion;
13817 // Try inverting the insertion since for v2 masks it is easy to do and we
13818 // can't reliably sort the mask one way or the other.
13819 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13821 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13822 return Insertion;
13823
13824 // We have different paths for blend lowering, but they all must use the
13825 // *exact* same predicate.
13826 bool IsBlendSupported = Subtarget.hasSSE41();
13827 if (IsBlendSupported)
13828 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13829 Zeroable, Subtarget, DAG))
13830 return Blend;
13831
13832 // Use dedicated unpack instructions for masks that match their pattern.
13833 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, V1, V2, Mask, DAG))
13834 return V;
13835
13836 // Try to use byte rotation instructions.
13837 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13838 if (Subtarget.hasSSSE3()) {
13839 if (Subtarget.hasVLX())
13840 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
13841 Zeroable, Subtarget, DAG))
13842 return Rotate;
13843
13844 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13845 Subtarget, DAG))
13846 return Rotate;
13847 }
13848
13849 // If we have direct support for blends, we should lower by decomposing into
13850 // a permute. That will be faster than the domain cross.
13851 if (IsBlendSupported)
13852 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
13853 Zeroable, Subtarget, DAG);
13854
13855 // We implement this with SHUFPD which is pretty lame because it will likely
13856 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13857 // However, all the alternatives are still more cycles and newer chips don't
13858 // have this problem. It would be really nice if x86 had better shuffles here.
13859 V1 = DAG.getBitcast(MVT::v2f64, V1);
13860 V2 = DAG.getBitcast(MVT::v2f64, V2);
13861 return DAG.getBitcast(MVT::v2i64,
13862 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13863}
13864
13865/// Lower a vector shuffle using the SHUFPS instruction.
13866///
13867/// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13868/// It makes no assumptions about whether this is the *best* lowering, it simply
13869/// uses it.
13871 ArrayRef<int> Mask, SDValue V1,
13872 SDValue V2, SelectionDAG &DAG) {
13873 SDValue LowV = V1, HighV = V2;
13874 SmallVector<int, 4> NewMask(Mask);
13875 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13876
13877 if (NumV2Elements == 1) {
13878 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13879
13880 // Compute the index adjacent to V2Index and in the same half by toggling
13881 // the low bit.
13882 int V2AdjIndex = V2Index ^ 1;
13883
13884 if (Mask[V2AdjIndex] < 0) {
13885 // Handles all the cases where we have a single V2 element and an undef.
13886 // This will only ever happen in the high lanes because we commute the
13887 // vector otherwise.
13888 if (V2Index < 2)
13889 std::swap(LowV, HighV);
13890 NewMask[V2Index] -= 4;
13891 } else {
13892 // Handle the case where the V2 element ends up adjacent to a V1 element.
13893 // To make this work, blend them together as the first step.
13894 int V1Index = V2AdjIndex;
13895 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13896 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13897 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13898
13899 // Now proceed to reconstruct the final blend as we have the necessary
13900 // high or low half formed.
13901 if (V2Index < 2) {
13902 LowV = V2;
13903 HighV = V1;
13904 } else {
13905 HighV = V2;
13906 }
13907 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13908 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13909 }
13910 } else if (NumV2Elements == 2) {
13911 if (Mask[0] < 4 && Mask[1] < 4) {
13912 // Handle the easy case where we have V1 in the low lanes and V2 in the
13913 // high lanes.
13914 NewMask[2] -= 4;
13915 NewMask[3] -= 4;
13916 } else if (Mask[2] < 4 && Mask[3] < 4) {
13917 // We also handle the reversed case because this utility may get called
13918 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13919 // arrange things in the right direction.
13920 NewMask[0] -= 4;
13921 NewMask[1] -= 4;
13922 HighV = V1;
13923 LowV = V2;
13924 } else {
13925 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13926 // trying to place elements directly, just blend them and set up the final
13927 // shuffle to place them.
13928
13929 // The first two blend mask elements are for V1, the second two are for
13930 // V2.
13931 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13932 Mask[2] < 4 ? Mask[2] : Mask[3],
13933 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13934 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13935 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13936 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13937
13938 // Now we do a normal shuffle of V1 by giving V1 as both operands to
13939 // a blend.
13940 LowV = HighV = V1;
13941 NewMask[0] = Mask[0] < 4 ? 0 : 2;
13942 NewMask[1] = Mask[0] < 4 ? 2 : 0;
13943 NewMask[2] = Mask[2] < 4 ? 1 : 3;
13944 NewMask[3] = Mask[2] < 4 ? 3 : 1;
13945 }
13946 } else if (NumV2Elements == 3) {
13947 // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
13948 // we can get here due to other paths (e.g repeated mask matching) that we
13949 // don't want to do another round of lowerVECTOR_SHUFFLE.
13951 return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
13952 }
13953 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13954 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13955}
13956
13957/// Lower 4-lane 32-bit floating point shuffles.
13958///
13959/// Uses instructions exclusively from the floating point unit to minimize
13960/// domain crossing penalties, as these are sufficient to implement all v4f32
13961/// shuffles.
13963 const APInt &Zeroable, SDValue V1, SDValue V2,
13964 const X86Subtarget &Subtarget,
13965 SelectionDAG &DAG) {
13966 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13967 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13968 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13969
13970 if (Subtarget.hasSSE41())
13971 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13972 Zeroable, Subtarget, DAG))
13973 return Blend;
13974
13975 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13976
13977 if (NumV2Elements == 0) {
13978 // Check for being able to broadcast a single element.
13979 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
13980 Mask, Subtarget, DAG))
13981 return Broadcast;
13982
13983 // Use even/odd duplicate instructions for masks that match their pattern.
13984 if (Subtarget.hasSSE3()) {
13985 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
13986 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
13987 if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
13988 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
13989 }
13990
13991 if (Subtarget.hasAVX()) {
13992 // If we have AVX, we can use VPERMILPS which will allow folding a load
13993 // into the shuffle.
13994 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
13995 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13996 }
13997
13998 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
13999 // in SSE1 because otherwise they are widened to v2f64 and never get here.
14000 if (!Subtarget.hasSSE2()) {
14001 if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14002 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14003 if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14004 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14005 }
14006
14007 // Otherwise, use a straight shuffle of a single input vector. We pass the
14008 // input vector to both operands to simulate this with a SHUFPS.
14009 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14010 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14011 }
14012
14013 if (Subtarget.hasSSE2())
14015 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
14016 ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
14017 return ZExt;
14018 }
14019
14020 if (Subtarget.hasAVX2())
14021 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14022 return Extract;
14023
14024 // There are special ways we can lower some single-element blends. However, we
14025 // have custom ways we can lower more complex single-element blends below that
14026 // we defer to if both this and BLENDPS fail to match, so restrict this to
14027 // when the V2 input is targeting element 0 of the mask -- that is the fast
14028 // case here.
14029 if (NumV2Elements == 1 && Mask[0] >= 4)
14030 if (SDValue V = lowerShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2, Mask,
14031 Zeroable, Subtarget, DAG))
14032 return V;
14033
14034 if (Subtarget.hasSSE41()) {
14035 bool MatchesShufPS = isSingleSHUFPSMask(Mask);
14036
14037 // Use INSERTPS if we can complete the shuffle efficiently.
14038 if (!MatchesShufPS || Zeroable == 0x3 || Zeroable == 0xC)
14039 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14040 return V;
14041
14042 if (!MatchesShufPS)
14043 if (SDValue BlendPerm =
14044 lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1, V2, Mask, DAG))
14045 return BlendPerm;
14046 }
14047
14048 // Use low/high mov instructions. These are only valid in SSE1 because
14049 // otherwise they are widened to v2f64 and never get here.
14050 if (!Subtarget.hasSSE2()) {
14051 if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14052 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14053 if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14054 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14055 }
14056
14057 // Use dedicated unpack instructions for masks that match their pattern.
14058 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, V1, V2, Mask, DAG))
14059 return V;
14060
14061 // Otherwise fall back to a SHUFPS lowering strategy.
14062 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14063}
14064
14065/// Lower 4-lane i32 vector shuffles.
14066///
14067/// We try to handle these with integer-domain shuffles where we can, but for
14068/// blends we use the floating point domain blend instructions.
14070 const APInt &Zeroable, SDValue V1, SDValue V2,
14071 const X86Subtarget &Subtarget,
14072 SelectionDAG &DAG) {
14073 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14074 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14075 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14076
14077 // Whenever we can lower this as a zext, that instruction is strictly faster
14078 // than any alternative. It also allows us to fold memory operands into the
14079 // shuffle in many cases.
14080 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14081 Zeroable, Subtarget, DAG))
14082 return ZExt;
14083
14084 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14085
14086 // Try to use shift instructions if fast.
14087 if (Subtarget.preferLowerShuffleAsShift()) {
14088 if (SDValue Shift =
14089 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
14090 Subtarget, DAG, /*BitwiseOnly*/ true))
14091 return Shift;
14092 if (NumV2Elements == 0)
14093 if (SDValue Rotate =
14094 lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
14095 return Rotate;
14096 }
14097
14098 if (NumV2Elements == 0) {
14099 // Try to use broadcast unless the mask only has one non-undef element.
14100 if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14101 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14102 Mask, Subtarget, DAG))
14103 return Broadcast;
14104 }
14105
14106 // Straight shuffle of a single input vector. For everything from SSE2
14107 // onward this has a single fast instruction with no scary immediates.
14108 // We coerce the shuffle pattern to be compatible with UNPCK instructions
14109 // but we aren't actually going to use the UNPCK instruction because doing
14110 // so prevents folding a load into this instruction or making a copy.
14111 const int UnpackLoMask[] = {0, 0, 1, 1};
14112 const int UnpackHiMask[] = {2, 2, 3, 3};
14113 if (!isSingleElementRepeatedMask(Mask)) {
14114 if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14115 Mask = UnpackLoMask;
14116 else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14117 Mask = UnpackHiMask;
14118 }
14119
14120 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14121 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14122 }
14123
14124 if (Subtarget.hasAVX2())
14125 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14126 return Extract;
14127
14128 // Try to use shift instructions.
14129 if (SDValue Shift =
14130 lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
14131 DAG, /*BitwiseOnly*/ false))
14132 return Shift;
14133
14134 // There are special ways we can lower some single-element blends.
14135 if (NumV2Elements == 1)
14137 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14138 return V;
14139
14140 // We have different paths for blend lowering, but they all must use the
14141 // *exact* same predicate.
14142 bool IsBlendSupported = Subtarget.hasSSE41();
14143 if (IsBlendSupported)
14144 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14145 Zeroable, Subtarget, DAG))
14146 return Blend;
14147
14148 if (SDValue Masked =
14149 lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, Zeroable, DAG))
14150 return Masked;
14151
14152 // Use dedicated unpack instructions for masks that match their pattern.
14153 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, V1, V2, Mask, DAG))
14154 return V;
14155
14156 // Try to use byte rotation instructions.
14157 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14158 if (Subtarget.hasSSSE3()) {
14159 if (Subtarget.hasVLX())
14160 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14161 Zeroable, Subtarget, DAG))
14162 return Rotate;
14163
14164 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14165 Subtarget, DAG))
14166 return Rotate;
14167 }
14168
14169 // Assume that a single SHUFPS is faster than an alternative sequence of
14170 // multiple instructions (even if the CPU has a domain penalty).
14171 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14172 if (!isSingleSHUFPSMask(Mask)) {
14173 // If we have direct support for blends, we should lower by decomposing into
14174 // a permute. That will be faster than the domain cross.
14175 if (IsBlendSupported)
14176 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
14177 Zeroable, Subtarget, DAG);
14178
14179 // Try to lower by permuting the inputs into an unpack instruction.
14180 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14181 Mask, Subtarget, DAG))
14182 return Unpack;
14183 }
14184
14185 // We implement this with SHUFPS because it can blend from two vectors.
14186 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14187 // up the inputs, bypassing domain shift penalties that we would incur if we
14188 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14189 // relevant.
14190 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14191 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14192 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14193 return DAG.getBitcast(MVT::v4i32, ShufPS);
14194}
14195
14196/// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14197/// shuffle lowering, and the most complex part.
14198///
14199/// The lowering strategy is to try to form pairs of input lanes which are
14200/// targeted at the same half of the final vector, and then use a dword shuffle
14201/// to place them onto the right half, and finally unpack the paired lanes into
14202/// their final position.
14203///
14204/// The exact breakdown of how to form these dword pairs and align them on the
14205/// correct sides is really tricky. See the comments within the function for
14206/// more of the details.
14207///
14208/// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14209/// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14210/// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14211/// vector, form the analogous 128-bit 8-element Mask.
14213 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14214 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14215 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
14216 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14217
14218 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
14219 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14220 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14221
14222 // Attempt to directly match PSHUFLW or PSHUFHW.
14223 if (isUndefOrInRange(LoMask, 0, 4) &&
14224 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14225 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14226 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14227 }
14228 if (isUndefOrInRange(HiMask, 4, 8) &&
14229 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14230 for (int i = 0; i != 4; ++i)
14231 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14232 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14233 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14234 }
14235
14236 SmallVector<int, 4> LoInputs;
14237 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14238 array_pod_sort(LoInputs.begin(), LoInputs.end());
14239 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
14240 SmallVector<int, 4> HiInputs;
14241 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14242 array_pod_sort(HiInputs.begin(), HiInputs.end());
14243 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
14244 int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14245 int NumHToL = LoInputs.size() - NumLToL;
14246 int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14247 int NumHToH = HiInputs.size() - NumLToH;
14248 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14249 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14250 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14251 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14252
14253 // If we are shuffling values from one half - check how many different DWORD
14254 // pairs we need to create. If only 1 or 2 then we can perform this as a
14255 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14256 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14257 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14258 V = DAG.getNode(ShufWOp, DL, VT, V,
14259 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14260 V = DAG.getBitcast(PSHUFDVT, V);
14261 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14262 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14263 return DAG.getBitcast(VT, V);
14264 };
14265
14266 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14267 int PSHUFDMask[4] = { -1, -1, -1, -1 };
14268 SmallVector<std::pair<int, int>, 4> DWordPairs;
14269 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14270
14271 // Collect the different DWORD pairs.
14272 for (int DWord = 0; DWord != 4; ++DWord) {
14273 int M0 = Mask[2 * DWord + 0];
14274 int M1 = Mask[2 * DWord + 1];
14275 M0 = (M0 >= 0 ? M0 % 4 : M0);
14276 M1 = (M1 >= 0 ? M1 % 4 : M1);
14277 if (M0 < 0 && M1 < 0)
14278 continue;
14279
14280 bool Match = false;
14281 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14282 auto &DWordPair = DWordPairs[j];
14283 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14284 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14285 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14286 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14287 PSHUFDMask[DWord] = DOffset + j;
14288 Match = true;
14289 break;
14290 }
14291 }
14292 if (!Match) {
14293 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14294 DWordPairs.push_back(std::make_pair(M0, M1));
14295 }
14296 }
14297
14298 if (DWordPairs.size() <= 2) {
14299 DWordPairs.resize(2, std::make_pair(-1, -1));
14300 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14301 DWordPairs[1].first, DWordPairs[1].second};
14302 // For splat, ensure we widen the PSHUFDMask to allow vXi64 folds.
14303 if (ShuffleVectorSDNode::isSplatMask(PSHUFDMask) &&
14304 ShuffleVectorSDNode::isSplatMask(PSHUFHalfMask)) {
14305 int SplatIdx = ShuffleVectorSDNode::getSplatMaskIndex(PSHUFHalfMask);
14306 std::fill(PSHUFHalfMask, PSHUFHalfMask + 4, SplatIdx);
14307 PSHUFDMask[0] = PSHUFDMask[2] = DOffset + 0;
14308 PSHUFDMask[1] = PSHUFDMask[3] = DOffset + 1;
14309 }
14310 if ((NumHToL + NumHToH) == 0)
14311 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14312 if ((NumLToL + NumLToH) == 0)
14313 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14314 }
14315 }
14316
14317 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14318 // such inputs we can swap two of the dwords across the half mark and end up
14319 // with <=2 inputs to each half in each half. Once there, we can fall through
14320 // to the generic code below. For example:
14321 //
14322 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14323 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14324 //
14325 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14326 // and an existing 2-into-2 on the other half. In this case we may have to
14327 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14328 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14329 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14330 // because any other situation (including a 3-into-1 or 1-into-3 in the other
14331 // half than the one we target for fixing) will be fixed when we re-enter this
14332 // path. We will also combine away any sequence of PSHUFD instructions that
14333 // result into a single instruction. Here is an example of the tricky case:
14334 //
14335 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14336 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14337 //
14338 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14339 //
14340 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14341 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14342 //
14343 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14344 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14345 //
14346 // The result is fine to be handled by the generic logic.
14347 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14348 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14349 int AOffset, int BOffset) {
14350 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
14351 "Must call this with A having 3 or 1 inputs from the A half.");
14352 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
14353 "Must call this with B having 1 or 3 inputs from the B half.");
14354 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
14355 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
14356
14357 bool ThreeAInputs = AToAInputs.size() == 3;
14358
14359 // Compute the index of dword with only one word among the three inputs in
14360 // a half by taking the sum of the half with three inputs and subtracting
14361 // the sum of the actual three inputs. The difference is the remaining
14362 // slot.
14363 int ADWord = 0, BDWord = 0;
14364 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14365 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14366 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14367 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14368 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14369 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14370 int TripleNonInputIdx =
14371 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14372 TripleDWord = TripleNonInputIdx / 2;
14373
14374 // We use xor with one to compute the adjacent DWord to whichever one the
14375 // OneInput is in.
14376 OneInputDWord = (OneInput / 2) ^ 1;
14377
14378 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14379 // and BToA inputs. If there is also such a problem with the BToB and AToB
14380 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14381 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14382 // is essential that we don't *create* a 3<-1 as then we might oscillate.
14383 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14384 // Compute how many inputs will be flipped by swapping these DWords. We
14385 // need
14386 // to balance this to ensure we don't form a 3-1 shuffle in the other
14387 // half.
14388 int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
14389 llvm::count(AToBInputs, 2 * ADWord + 1);
14390 int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
14391 llvm::count(BToBInputs, 2 * BDWord + 1);
14392 if ((NumFlippedAToBInputs == 1 &&
14393 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14394 (NumFlippedBToBInputs == 1 &&
14395 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14396 // We choose whether to fix the A half or B half based on whether that
14397 // half has zero flipped inputs. At zero, we may not be able to fix it
14398 // with that half. We also bias towards fixing the B half because that
14399 // will more commonly be the high half, and we have to bias one way.
14400 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14401 ArrayRef<int> Inputs) {
14402 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14403 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14404 // Determine whether the free index is in the flipped dword or the
14405 // unflipped dword based on where the pinned index is. We use this bit
14406 // in an xor to conditionally select the adjacent dword.
14407 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14408 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14409 if (IsFixIdxInput == IsFixFreeIdxInput)
14410 FixFreeIdx += 1;
14411 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14412 assert(IsFixIdxInput != IsFixFreeIdxInput &&
14413 "We need to be changing the number of flipped inputs!");
14414 int PSHUFHalfMask[] = {0, 1, 2, 3};
14415 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14416 V = DAG.getNode(
14417 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14418 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14419 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14420
14421 for (int &M : Mask)
14422 if (M >= 0 && M == FixIdx)
14423 M = FixFreeIdx;
14424 else if (M >= 0 && M == FixFreeIdx)
14425 M = FixIdx;
14426 };
14427 if (NumFlippedBToBInputs != 0) {
14428 int BPinnedIdx =
14429 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14430 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14431 } else {
14432 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
14433 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14434 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14435 }
14436 }
14437 }
14438
14439 int PSHUFDMask[] = {0, 1, 2, 3};
14440 PSHUFDMask[ADWord] = BDWord;
14441 PSHUFDMask[BDWord] = ADWord;
14442 V = DAG.getBitcast(
14443 VT,
14444 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14445 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14446
14447 // Adjust the mask to match the new locations of A and B.
14448 for (int &M : Mask)
14449 if (M >= 0 && M/2 == ADWord)
14450 M = 2 * BDWord + M % 2;
14451 else if (M >= 0 && M/2 == BDWord)
14452 M = 2 * ADWord + M % 2;
14453
14454 // Recurse back into this routine to re-compute state now that this isn't
14455 // a 3 and 1 problem.
14456 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14457 };
14458 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14459 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14460 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14461 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14462
14463 // At this point there are at most two inputs to the low and high halves from
14464 // each half. That means the inputs can always be grouped into dwords and
14465 // those dwords can then be moved to the correct half with a dword shuffle.
14466 // We use at most one low and one high word shuffle to collect these paired
14467 // inputs into dwords, and finally a dword shuffle to place them.
14468 int PSHUFLMask[4] = {-1, -1, -1, -1};
14469 int PSHUFHMask[4] = {-1, -1, -1, -1};
14470 int PSHUFDMask[4] = {-1, -1, -1, -1};
14471
14472 // First fix the masks for all the inputs that are staying in their
14473 // original halves. This will then dictate the targets of the cross-half
14474 // shuffles.
14475 auto fixInPlaceInputs =
14476 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14477 MutableArrayRef<int> SourceHalfMask,
14478 MutableArrayRef<int> HalfMask, int HalfOffset) {
14479 if (InPlaceInputs.empty())
14480 return;
14481 if (InPlaceInputs.size() == 1) {
14482 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14483 InPlaceInputs[0] - HalfOffset;
14484 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14485 return;
14486 }
14487 if (IncomingInputs.empty()) {
14488 // Just fix all of the in place inputs.
14489 for (int Input : InPlaceInputs) {
14490 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14491 PSHUFDMask[Input / 2] = Input / 2;
14492 }
14493 return;
14494 }
14495
14496 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
14497 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14498 InPlaceInputs[0] - HalfOffset;
14499 // Put the second input next to the first so that they are packed into
14500 // a dword. We find the adjacent index by toggling the low bit.
14501 int AdjIndex = InPlaceInputs[0] ^ 1;
14502 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14503 llvm::replace(HalfMask, InPlaceInputs[1], AdjIndex);
14504 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14505 };
14506 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14507 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14508
14509 // Now gather the cross-half inputs and place them into a free dword of
14510 // their target half.
14511 // FIXME: This operation could almost certainly be simplified dramatically to
14512 // look more like the 3-1 fixing operation.
14513 auto moveInputsToRightHalf = [&PSHUFDMask](
14514 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14515 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14516 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14517 int DestOffset) {
14518 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14519 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14520 };
14521 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14522 int Word) {
14523 int LowWord = Word & ~1;
14524 int HighWord = Word | 1;
14525 return isWordClobbered(SourceHalfMask, LowWord) ||
14526 isWordClobbered(SourceHalfMask, HighWord);
14527 };
14528
14529 if (IncomingInputs.empty())
14530 return;
14531
14532 if (ExistingInputs.empty()) {
14533 // Map any dwords with inputs from them into the right half.
14534 for (int Input : IncomingInputs) {
14535 // If the source half mask maps over the inputs, turn those into
14536 // swaps and use the swapped lane.
14537 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14538 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14539 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14540 Input - SourceOffset;
14541 // We have to swap the uses in our half mask in one sweep.
14542 for (int &M : HalfMask)
14543 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14544 M = Input;
14545 else if (M == Input)
14546 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14547 } else {
14548 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
14549 Input - SourceOffset &&
14550 "Previous placement doesn't match!");
14551 }
14552 // Note that this correctly re-maps both when we do a swap and when
14553 // we observe the other side of the swap above. We rely on that to
14554 // avoid swapping the members of the input list directly.
14555 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14556 }
14557
14558 // Map the input's dword into the correct half.
14559 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14560 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14561 else
14562 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
14563 Input / 2 &&
14564 "Previous placement doesn't match!");
14565 }
14566
14567 // And just directly shift any other-half mask elements to be same-half
14568 // as we will have mirrored the dword containing the element into the
14569 // same position within that half.
14570 for (int &M : HalfMask)
14571 if (M >= SourceOffset && M < SourceOffset + 4) {
14572 M = M - SourceOffset + DestOffset;
14573 assert(M >= 0 && "This should never wrap below zero!");
14574 }
14575 return;
14576 }
14577
14578 // Ensure we have the input in a viable dword of its current half. This
14579 // is particularly tricky because the original position may be clobbered
14580 // by inputs being moved and *staying* in that half.
14581 if (IncomingInputs.size() == 1) {
14582 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14583 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14584 SourceOffset;
14585 SourceHalfMask[InputFixed - SourceOffset] =
14586 IncomingInputs[0] - SourceOffset;
14587 llvm::replace(HalfMask, IncomingInputs[0], InputFixed);
14588 IncomingInputs[0] = InputFixed;
14589 }
14590 } else if (IncomingInputs.size() == 2) {
14591 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14592 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14593 // We have two non-adjacent or clobbered inputs we need to extract from
14594 // the source half. To do this, we need to map them into some adjacent
14595 // dword slot in the source mask.
14596 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14597 IncomingInputs[1] - SourceOffset};
14598
14599 // If there is a free slot in the source half mask adjacent to one of
14600 // the inputs, place the other input in it. We use (Index XOR 1) to
14601 // compute an adjacent index.
14602 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14603 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14604 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14605 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14606 InputsFixed[1] = InputsFixed[0] ^ 1;
14607 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14608 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14609 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14610 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14611 InputsFixed[0] = InputsFixed[1] ^ 1;
14612 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14613 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14614 // The two inputs are in the same DWord but it is clobbered and the
14615 // adjacent DWord isn't used at all. Move both inputs to the free
14616 // slot.
14617 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14618 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14619 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14620 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14621 } else {
14622 // The only way we hit this point is if there is no clobbering
14623 // (because there are no off-half inputs to this half) and there is no
14624 // free slot adjacent to one of the inputs. In this case, we have to
14625 // swap an input with a non-input.
14626 for (int i = 0; i < 4; ++i)
14627 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14628 "We can't handle any clobbers here!");
14629 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14630 "Cannot have adjacent inputs here!");
14631
14632 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14633 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14634
14635 // We also have to update the final source mask in this case because
14636 // it may need to undo the above swap.
14637 for (int &M : FinalSourceHalfMask)
14638 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14639 M = InputsFixed[1] + SourceOffset;
14640 else if (M == InputsFixed[1] + SourceOffset)
14641 M = (InputsFixed[0] ^ 1) + SourceOffset;
14642
14643 InputsFixed[1] = InputsFixed[0] ^ 1;
14644 }
14645
14646 // Point everything at the fixed inputs.
14647 for (int &M : HalfMask)
14648 if (M == IncomingInputs[0])
14649 M = InputsFixed[0] + SourceOffset;
14650 else if (M == IncomingInputs[1])
14651 M = InputsFixed[1] + SourceOffset;
14652
14653 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14654 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14655 }
14656 } else {
14657 llvm_unreachable("Unhandled input size!");
14658 }
14659
14660 // Now hoist the DWord down to the right half.
14661 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14662 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14663 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14664 for (int &M : HalfMask)
14665 for (int Input : IncomingInputs)
14666 if (M == Input)
14667 M = FreeDWord * 2 + Input % 2;
14668 };
14669 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14670 /*SourceOffset*/ 4, /*DestOffset*/ 0);
14671 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14672 /*SourceOffset*/ 0, /*DestOffset*/ 4);
14673
14674 // Now enact all the shuffles we've computed to move the inputs into their
14675 // target half.
14676 if (!isNoopShuffleMask(PSHUFLMask))
14677 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14678 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14679 if (!isNoopShuffleMask(PSHUFHMask))
14680 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14681 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14682 if (!isNoopShuffleMask(PSHUFDMask))
14683 V = DAG.getBitcast(
14684 VT,
14685 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14686 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14687
14688 // At this point, each half should contain all its inputs, and we can then
14689 // just shuffle them into their final position.
14690 assert(none_of(LoMask, [](int M) { return M >= 4; }) &&
14691 "Failed to lift all the high half inputs to the low mask!");
14692 assert(none_of(HiMask, [](int M) { return M >= 0 && M < 4; }) &&
14693 "Failed to lift all the low half inputs to the high mask!");
14694
14695 // Do a half shuffle for the low mask.
14696 if (!isNoopShuffleMask(LoMask))
14697 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14698 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14699
14700 // Do a half shuffle with the high mask after shifting its values down.
14701 for (int &M : HiMask)
14702 if (M >= 0)
14703 M -= 4;
14704 if (!isNoopShuffleMask(HiMask))
14705 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14706 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14707
14708 return V;
14709}
14710
14711/// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14712/// blend if only one input is used.
14714 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14715 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14717 "Lane crossing shuffle masks not supported");
14718
14719 int NumBytes = VT.getSizeInBits() / 8;
14720 int Size = Mask.size();
14721 int Scale = NumBytes / Size;
14722
14723 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14724 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14725 V1InUse = false;
14726 V2InUse = false;
14727
14728 for (int i = 0; i < NumBytes; ++i) {
14729 int M = Mask[i / Scale];
14730 if (M < 0)
14731 continue;
14732
14733 const int ZeroMask = 0x80;
14734 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14735 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14736 if (Zeroable[i / Scale])
14737 V1Idx = V2Idx = ZeroMask;
14738
14739 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14740 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14741 V1InUse |= (ZeroMask != V1Idx);
14742 V2InUse |= (ZeroMask != V2Idx);
14743 }
14744
14745 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14746 if (V1InUse)
14747 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14748 DAG.getBuildVector(ShufVT, DL, V1Mask));
14749 if (V2InUse)
14750 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14751 DAG.getBuildVector(ShufVT, DL, V2Mask));
14752
14753 // If we need shuffled inputs from both, blend the two.
14754 SDValue V;
14755 if (V1InUse && V2InUse)
14756 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14757 else
14758 V = V1InUse ? V1 : V2;
14759
14760 // Cast the result back to the correct type.
14761 return DAG.getBitcast(VT, V);
14762}
14763
14764/// Generic lowering of 8-lane i16 shuffles.
14765///
14766/// This handles both single-input shuffles and combined shuffle/blends with
14767/// two inputs. The single input shuffles are immediately delegated to
14768/// a dedicated lowering routine.
14769///
14770/// The blends are lowered in one of three fundamental ways. If there are few
14771/// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14772/// of the input is significantly cheaper when lowered as an interleaving of
14773/// the two inputs, try to interleave them. Otherwise, blend the low and high
14774/// halves of the inputs separately (making them have relatively few inputs)
14775/// and then concatenate them.
14777 const APInt &Zeroable, SDValue V1, SDValue V2,
14778 const X86Subtarget &Subtarget,
14779 SelectionDAG &DAG) {
14780 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14781 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14782 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14783
14784 // Whenever we can lower this as a zext, that instruction is strictly faster
14785 // than any alternative.
14786 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14787 Zeroable, Subtarget, DAG))
14788 return ZExt;
14789
14790 // Try to use lower using a truncation.
14791 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14792 Subtarget, DAG))
14793 return V;
14794
14795 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14796
14797 if (NumV2Inputs == 0) {
14798 // Try to use shift instructions.
14799 if (SDValue Shift =
14800 lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
14801 Subtarget, DAG, /*BitwiseOnly*/ false))
14802 return Shift;
14803
14804 // Check for being able to broadcast a single element.
14805 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14806 Mask, Subtarget, DAG))
14807 return Broadcast;
14808
14809 // Try to use bit rotation instructions.
14810 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
14811 Subtarget, DAG))
14812 return Rotate;
14813
14814 // Use dedicated unpack instructions for masks that match their pattern.
14815 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14816 return V;
14817
14818 // Use dedicated pack instructions for masks that match their pattern.
14819 if (SDValue V =
14820 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14821 return V;
14822
14823 // Try to use byte rotation instructions.
14824 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14825 Subtarget, DAG))
14826 return Rotate;
14827
14828 // Make a copy of the mask so it can be modified.
14829 SmallVector<int, 8> MutableMask(Mask);
14830 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14831 Subtarget, DAG);
14832 }
14833
14834 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14835 "All single-input shuffles should be canonicalized to be V1-input "
14836 "shuffles.");
14837
14838 // Try to use shift instructions.
14839 if (SDValue Shift =
14840 lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
14841 DAG, /*BitwiseOnly*/ false))
14842 return Shift;
14843
14844 // See if we can use SSE4A Extraction / Insertion.
14845 if (Subtarget.hasSSE4A())
14846 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14847 Zeroable, DAG))
14848 return V;
14849
14850 // There are special ways we can lower some single-element blends.
14851 if (NumV2Inputs == 1)
14853 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14854 return V;
14855
14856 // We have different paths for blend lowering, but they all must use the
14857 // *exact* same predicate.
14858 bool IsBlendSupported = Subtarget.hasSSE41();
14859 if (IsBlendSupported)
14860 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14861 Zeroable, Subtarget, DAG))
14862 return Blend;
14863
14864 if (SDValue Masked =
14865 lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, Zeroable, DAG))
14866 return Masked;
14867
14868 // Use dedicated unpack instructions for masks that match their pattern.
14869 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, V1, V2, Mask, DAG))
14870 return V;
14871
14872 // Use dedicated pack instructions for masks that match their pattern.
14873 if (SDValue V =
14874 lowerShuffleWithPACK(DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
14875 return V;
14876
14877 // Try to use lower using a truncation.
14878 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
14879 Subtarget, DAG))
14880 return V;
14881
14882 // Try to use byte rotation instructions.
14883 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14884 Subtarget, DAG))
14885 return Rotate;
14886
14887 if (SDValue BitBlend =
14888 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14889 return BitBlend;
14890
14891 // Try to use byte shift instructions to mask.
14892 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14893 Zeroable, Subtarget, DAG))
14894 return V;
14895
14896 // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
14897 int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
14898 if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
14899 !Subtarget.hasVLX()) {
14900 // Check if this is part of a 256-bit vector truncation.
14901 unsigned PackOpc = 0;
14902 if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
14904 peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
14905 SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
14906 V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
14907 getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
14908 DAG.getTargetConstant(0xEE, DL, MVT::i8));
14909 V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
14910 V1 = extract128BitVector(V1V2, 0, DAG, DL);
14911 V2 = extract128BitVector(V1V2, 4, DAG, DL);
14912 PackOpc = X86ISD::PACKUS;
14913 } else if (Subtarget.hasSSE41()) {
14914 SmallVector<SDValue, 4> DWordClearOps(4,
14915 DAG.getConstant(0, DL, MVT::i32));
14916 for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
14917 DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
14918 SDValue DWordClearMask =
14919 DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
14920 V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
14921 DWordClearMask);
14922 V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
14923 DWordClearMask);
14924 PackOpc = X86ISD::PACKUS;
14925 } else if (!Subtarget.hasSSSE3()) {
14926 SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
14927 V1 = DAG.getBitcast(MVT::v4i32, V1);
14928 V2 = DAG.getBitcast(MVT::v4i32, V2);
14929 V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
14930 V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
14931 V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
14932 V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
14933 PackOpc = X86ISD::PACKSS;
14934 }
14935 if (PackOpc) {
14936 // Now pack things back together.
14937 SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
14938 if (NumEvenDrops == 2) {
14939 Result = DAG.getBitcast(MVT::v4i32, Result);
14940 Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
14941 }
14942 return Result;
14943 }
14944 }
14945
14946 // When compacting odd (upper) elements, use PACKSS pre-SSE41.
14947 int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
14948 if (NumOddDrops == 1) {
14949 bool HasSSE41 = Subtarget.hasSSE41();
14950 V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14951 DAG.getBitcast(MVT::v4i32, V1),
14952 DAG.getTargetConstant(16, DL, MVT::i8));
14953 V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
14954 DAG.getBitcast(MVT::v4i32, V2),
14955 DAG.getTargetConstant(16, DL, MVT::i8));
14956 return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
14957 MVT::v8i16, V1, V2);
14958 }
14959
14960 // Try to lower by permuting the inputs into an unpack instruction.
14961 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14962 Mask, Subtarget, DAG))
14963 return Unpack;
14964
14965 // If we can't directly blend but can use PSHUFB, that will be better as it
14966 // can both shuffle and set up the inefficient blend.
14967 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14968 bool V1InUse, V2InUse;
14969 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14970 Zeroable, DAG, V1InUse, V2InUse);
14971 }
14972
14973 // We can always bit-blend if we have to so the fallback strategy is to
14974 // decompose into single-input permutes and blends/unpacks.
14975 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2, Mask,
14976 Zeroable, Subtarget, DAG);
14977}
14978
14979/// Lower 8-lane 16-bit floating point shuffles.
14981 const APInt &Zeroable, SDValue V1, SDValue V2,
14982 const X86Subtarget &Subtarget,
14983 SelectionDAG &DAG) {
14984 assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14985 assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
14986 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14987 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
14988
14989 if (Subtarget.hasFP16()) {
14990 if (NumV2Elements == 0) {
14991 // Check for being able to broadcast a single element.
14992 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
14993 Mask, Subtarget, DAG))
14994 return Broadcast;
14995 }
14996 if (NumV2Elements == 1 && Mask[0] >= 8)
14998 DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14999 return V;
15000 }
15001
15002 V1 = DAG.getBitcast(MVT::v8i16, V1);
15003 V2 = DAG.getBitcast(MVT::v8i16, V2);
15004 return DAG.getBitcast(MVT::v8f16,
15005 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15006}
15007
15008// Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15009// sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15010// the active subvector is extracted.
15012 ArrayRef<int> OriginalMask, SDValue V1,
15013 SDValue V2, const X86Subtarget &Subtarget,
15014 SelectionDAG &DAG) {
15015 // Commute binary inputs so V2 is a load to simplify VPERMI2/T2 folds.
15016 SmallVector<int, 32> Mask(OriginalMask);
15017 if (!V2.isUndef() && isShuffleFoldableLoad(V1) &&
15018 !isShuffleFoldableLoad(V2)) {
15020 std::swap(V1, V2);
15021 }
15022
15023 MVT MaskVT = VT.changeTypeToInteger();
15024 SDValue MaskNode;
15025 MVT ShuffleVT = VT;
15026 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15027 V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15028 V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15029 ShuffleVT = V1.getSimpleValueType();
15030
15031 // Adjust mask to correct indices for the second input.
15032 int NumElts = VT.getVectorNumElements();
15033 unsigned Scale = 512 / VT.getSizeInBits();
15034 SmallVector<int, 32> AdjustedMask(Mask);
15035 for (int &M : AdjustedMask)
15036 if (NumElts <= M)
15037 M += (Scale - 1) * NumElts;
15038 MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15039 MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15040 } else {
15041 MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15042 }
15043
15044 SDValue Result;
15045 if (V2.isUndef())
15046 Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15047 else
15048 Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15049
15050 if (VT != ShuffleVT)
15051 Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15052
15053 return Result;
15054}
15055
15056/// Generic lowering of v16i8 shuffles.
15057///
15058/// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15059/// detect any complexity reducing interleaving. If that doesn't help, it uses
15060/// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15061/// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15062/// back together.
15064 const APInt &Zeroable, SDValue V1, SDValue V2,
15065 const X86Subtarget &Subtarget,
15066 SelectionDAG &DAG) {
15067 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15068 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15069 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15070
15071 // Try to use shift instructions.
15072 if (SDValue Shift =
15073 lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
15074 DAG, /*BitwiseOnly*/ false))
15075 return Shift;
15076
15077 // Try to use byte rotation instructions.
15078 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15079 Subtarget, DAG))
15080 return Rotate;
15081
15082 // Use dedicated pack instructions for masks that match their pattern.
15083 if (SDValue V =
15084 lowerShuffleWithPACK(DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15085 return V;
15086
15087 // Try to use a zext lowering.
15088 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15089 Zeroable, Subtarget, DAG))
15090 return ZExt;
15091
15092 // Try to use lower using a truncation.
15093 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15094 Subtarget, DAG))
15095 return V;
15096
15097 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15098 Subtarget, DAG))
15099 return V;
15100
15101 // See if we can use SSE4A Extraction / Insertion.
15102 if (Subtarget.hasSSE4A())
15103 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15104 Zeroable, DAG))
15105 return V;
15106
15107 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15108
15109 // For single-input shuffles, there are some nicer lowering tricks we can use.
15110 if (NumV2Elements == 0) {
15111 // Check for being able to broadcast a single element.
15112 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15113 Mask, Subtarget, DAG))
15114 return Broadcast;
15115
15116 // Try to use bit rotation instructions.
15117 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15118 Subtarget, DAG))
15119 return Rotate;
15120
15121 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15122 return V;
15123
15124 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15125 // Notably, this handles splat and partial-splat shuffles more efficiently.
15126 // However, it only makes sense if the pre-duplication shuffle simplifies
15127 // things significantly. Currently, this means we need to be able to
15128 // express the pre-duplication shuffle as an i16 shuffle.
15129 //
15130 // FIXME: We should check for other patterns which can be widened into an
15131 // i16 shuffle as well.
15132 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15133 for (int i = 0; i < 16; i += 2)
15134 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15135 return false;
15136
15137 return true;
15138 };
15139 auto tryToWidenViaDuplication = [&]() -> SDValue {
15140 if (!canWidenViaDuplication(Mask))
15141 return SDValue();
15142 SmallVector<int, 4> LoInputs;
15143 copy_if(Mask, std::back_inserter(LoInputs),
15144 [](int M) { return M >= 0 && M < 8; });
15145 array_pod_sort(LoInputs.begin(), LoInputs.end());
15146 LoInputs.erase(llvm::unique(LoInputs), LoInputs.end());
15147 SmallVector<int, 4> HiInputs;
15148 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15149 array_pod_sort(HiInputs.begin(), HiInputs.end());
15150 HiInputs.erase(llvm::unique(HiInputs), HiInputs.end());
15151
15152 bool TargetLo = LoInputs.size() >= HiInputs.size();
15153 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15154 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15155
15156 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15158 for (int I : InPlaceInputs) {
15159 PreDupI16Shuffle[I/2] = I/2;
15160 LaneMap[I] = I;
15161 }
15162 int j = TargetLo ? 0 : 4, je = j + 4;
15163 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15164 // Check if j is already a shuffle of this input. This happens when
15165 // there are two adjacent bytes after we move the low one.
15166 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15167 // If we haven't yet mapped the input, search for a slot into which
15168 // we can map it.
15169 while (j < je && PreDupI16Shuffle[j] >= 0)
15170 ++j;
15171
15172 if (j == je)
15173 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15174 return SDValue();
15175
15176 // Map this input with the i16 shuffle.
15177 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15178 }
15179
15180 // Update the lane map based on the mapping we ended up with.
15181 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15182 }
15183 V1 = DAG.getBitcast(
15184 MVT::v16i8,
15185 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15186 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15187
15188 // Unpack the bytes to form the i16s that will be shuffled into place.
15189 bool EvenInUse = false, OddInUse = false;
15190 for (int i = 0; i < 16; i += 2) {
15191 EvenInUse |= (Mask[i + 0] >= 0);
15192 OddInUse |= (Mask[i + 1] >= 0);
15193 if (EvenInUse && OddInUse)
15194 break;
15195 }
15196 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15197 MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15198 OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15199
15200 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15201 for (int i = 0; i < 16; ++i)
15202 if (Mask[i] >= 0) {
15203 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15204 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
15205 if (PostDupI16Shuffle[i / 2] < 0)
15206 PostDupI16Shuffle[i / 2] = MappedMask;
15207 else
15208 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
15209 "Conflicting entries in the original shuffle!");
15210 }
15211 return DAG.getBitcast(
15212 MVT::v16i8,
15213 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15214 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
15215 };
15216 if (SDValue V = tryToWidenViaDuplication())
15217 return V;
15218 }
15219
15220 if (SDValue Masked =
15221 lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG))
15222 return Masked;
15223
15224 // Use dedicated unpack instructions for masks that match their pattern.
15225 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, V1, V2, Mask, DAG))
15226 return V;
15227
15228 // Try to use byte shift instructions to mask.
15229 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15230 Zeroable, Subtarget, DAG))
15231 return V;
15232
15233 // Check for compaction patterns.
15234 bool IsSingleInput = V2.isUndef();
15235 int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
15236
15237 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15238 // with PSHUFB. It is important to do this before we attempt to generate any
15239 // blends but after all of the single-input lowerings. If the single input
15240 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15241 // want to preserve that and we can DAG combine any longer sequences into
15242 // a PSHUFB in the end. But once we start blending from multiple inputs,
15243 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15244 // and there are *very* few patterns that would actually be faster than the
15245 // PSHUFB approach because of its ability to zero lanes.
15246 //
15247 // If the mask is a binary compaction, we can more efficiently perform this
15248 // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15249 //
15250 // FIXME: The only exceptions to the above are blends which are exact
15251 // interleavings with direct instructions supporting them. We currently don't
15252 // handle those well here.
15253 if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15254 bool V1InUse = false;
15255 bool V2InUse = false;
15256
15258 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15259
15260 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15261 // do so. This avoids using them to handle blends-with-zero which is
15262 // important as a single pshufb is significantly faster for that.
15263 if (V1InUse && V2InUse) {
15264 if (Subtarget.hasSSE41())
15265 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15266 Zeroable, Subtarget, DAG))
15267 return Blend;
15268
15269 // We can use an unpack to do the blending rather than an or in some
15270 // cases. Even though the or may be (very minorly) more efficient, we
15271 // preference this lowering because there are common cases where part of
15272 // the complexity of the shuffles goes away when we do the final blend as
15273 // an unpack.
15274 // FIXME: It might be worth trying to detect if the unpack-feeding
15275 // shuffles will both be pshufb, in which case we shouldn't bother with
15276 // this.
15278 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15279 return Unpack;
15280
15281 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
15282 if (Subtarget.hasVBMI())
15283 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
15284 DAG);
15285
15286 // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
15287 if (Subtarget.hasXOP()) {
15288 SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
15289 return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
15290 }
15291
15292 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15293 // PALIGNR will be cheaper than the second PSHUFB+OR.
15295 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15296 return V;
15297 }
15298
15299 return PSHUFB;
15300 }
15301
15302 // There are special ways we can lower some single-element blends.
15303 if (NumV2Elements == 1)
15305 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15306 return V;
15307
15308 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15309 return Blend;
15310
15311 // Check whether a compaction lowering can be done. This handles shuffles
15312 // which take every Nth element for some even N. See the helper function for
15313 // details.
15314 //
15315 // We special case these as they can be particularly efficiently handled with
15316 // the PACKUSB instruction on x86 and they show up in common patterns of
15317 // rearranging bytes to truncate wide elements.
15318 if (NumEvenDrops) {
15319 // NumEvenDrops is the power of two stride of the elements. Another way of
15320 // thinking about it is that we need to drop the even elements this many
15321 // times to get the original input.
15322
15323 // First we need to zero all the dropped bytes.
15324 assert(NumEvenDrops <= 3 &&
15325 "No support for dropping even elements more than 3 times.");
15326 SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15327 for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15328 WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15329 SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15330 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15331 WordClearMask);
15332 if (!IsSingleInput)
15333 V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15334 WordClearMask);
15335
15336 // Now pack things back together.
15337 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15338 IsSingleInput ? V1 : V2);
15339 for (int i = 1; i < NumEvenDrops; ++i) {
15340 Result = DAG.getBitcast(MVT::v8i16, Result);
15341 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15342 }
15343 return Result;
15344 }
15345
15346 int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
15347 if (NumOddDrops == 1) {
15348 V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15349 DAG.getBitcast(MVT::v8i16, V1),
15350 DAG.getTargetConstant(8, DL, MVT::i8));
15351 if (!IsSingleInput)
15352 V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
15353 DAG.getBitcast(MVT::v8i16, V2),
15354 DAG.getTargetConstant(8, DL, MVT::i8));
15355 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15356 IsSingleInput ? V1 : V2);
15357 }
15358
15359 // Handle multi-input cases by blending/unpacking single-input shuffles.
15360 if (NumV2Elements > 0)
15361 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
15362 Zeroable, Subtarget, DAG);
15363
15364 // The fallback path for single-input shuffles widens this into two v8i16
15365 // vectors with unpacks, shuffles those, and then pulls them back together
15366 // with a pack.
15367 SDValue V = V1;
15368
15369 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15370 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15371 for (int i = 0; i < 16; ++i)
15372 if (Mask[i] >= 0)
15373 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15374
15375 SDValue VLoHalf, VHiHalf;
15376 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15377 // them out and avoid using UNPCK{L,H} to extract the elements of V as
15378 // i16s.
15379 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15380 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15381 // Use a mask to drop the high bytes.
15382 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15383 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15384 DAG.getConstant(0x00FF, DL, MVT::v8i16));
15385
15386 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15387 VHiHalf = DAG.getUNDEF(MVT::v8i16);
15388
15389 // Squash the masks to point directly into VLoHalf.
15390 for (int &M : LoBlendMask)
15391 if (M >= 0)
15392 M /= 2;
15393 for (int &M : HiBlendMask)
15394 if (M >= 0)
15395 M /= 2;
15396 } else {
15397 // Otherwise just unpack the low half of V into VLoHalf and the high half into
15398 // VHiHalf so that we can blend them as i16s.
15399 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15400
15401 VLoHalf = DAG.getBitcast(
15402 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15403 VHiHalf = DAG.getBitcast(
15404 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15405 }
15406
15407 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15408 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15409
15410 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15411}
15412
15413/// Dispatching routine to lower various 128-bit x86 vector shuffles.
15414///
15415/// This routine breaks down the specific type of 128-bit shuffle and
15416/// dispatches to the lowering routines accordingly.
15418 MVT VT, SDValue V1, SDValue V2,
15419 const APInt &Zeroable,
15420 const X86Subtarget &Subtarget,
15421 SelectionDAG &DAG) {
15422 if (VT == MVT::v8bf16) {
15423 V1 = DAG.getBitcast(MVT::v8i16, V1);
15424 V2 = DAG.getBitcast(MVT::v8i16, V2);
15425 return DAG.getBitcast(VT,
15426 DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
15427 }
15428
15429 switch (VT.SimpleTy) {
15430 case MVT::v2i64:
15431 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15432 case MVT::v2f64:
15433 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15434 case MVT::v4i32:
15435 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15436 case MVT::v4f32:
15437 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15438 case MVT::v8i16:
15439 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15440 case MVT::v8f16:
15441 return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15442 case MVT::v16i8:
15443 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15444
15445 default:
15446 llvm_unreachable("Unimplemented!");
15447 }
15448}
15449
15450/// Generic routine to split vector shuffle into half-sized shuffles.
15451///
15452/// This routine just extracts two subvectors, shuffles them independently, and
15453/// then concatenates them back together. This should work effectively with all
15454/// AVX vector shuffle types.
15456 SDValue V2, ArrayRef<int> Mask,
15457 SelectionDAG &DAG, bool SimpleOnly) {
15458 assert(VT.getSizeInBits() >= 256 &&
15459 "Only for 256-bit or wider vector shuffles!");
15460 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
15461 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
15462
15463 // If this came from the AVX1 v8i32 -> v8f32 bitcast, split using v4i32.
15464 if (VT == MVT::v8f32) {
15466 SDValue BC2 = peekThroughBitcasts(V2);
15467 if (BC1.getValueType() == MVT::v8i32 && BC2.getValueType() == MVT::v8i32) {
15468 if (SDValue Split = splitAndLowerShuffle(DL, MVT::v8i32, BC1, BC2, Mask,
15469 DAG, SimpleOnly))
15470 return DAG.getBitcast(VT, Split);
15471 }
15472 }
15473
15474 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15475 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15476
15477 int NumElements = VT.getVectorNumElements();
15478 int SplitNumElements = NumElements / 2;
15479 MVT ScalarVT = VT.getVectorElementType();
15480 MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15481
15482 // Use splitVector/extractSubVector so that split build-vectors just build two
15483 // narrower build vectors. This helps shuffling with splats and zeros.
15484 auto SplitVector = [&](SDValue V) {
15485 SDValue LoV, HiV;
15486 std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15487 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15488 DAG.getBitcast(SplitVT, HiV));
15489 };
15490
15491 SDValue LoV1, HiV1, LoV2, HiV2;
15492 std::tie(LoV1, HiV1) = SplitVector(V1);
15493 std::tie(LoV2, HiV2) = SplitVector(V2);
15494
15495 // Now create two 4-way blends of these half-width vectors.
15496 auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
15497 bool &UseHiV1, bool &UseLoV2,
15498 bool &UseHiV2) {
15499 UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
15500 for (int i = 0; i < SplitNumElements; ++i) {
15501 int M = HalfMask[i];
15502 if (M >= NumElements) {
15503 if (M >= NumElements + SplitNumElements)
15504 UseHiV2 = true;
15505 else
15506 UseLoV2 = true;
15507 } else if (M >= 0) {
15508 if (M >= SplitNumElements)
15509 UseHiV1 = true;
15510 else
15511 UseLoV1 = true;
15512 }
15513 }
15514 };
15515
15516 auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
15517 if (!SimpleOnly)
15518 return true;
15519
15520 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15521 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15522
15523 return !(UseHiV1 || UseHiV2);
15524 };
15525
15526 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15527 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15528 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15529 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15530 for (int i = 0; i < SplitNumElements; ++i) {
15531 int M = HalfMask[i];
15532 if (M >= NumElements) {
15533 V2BlendMask[i] = M - NumElements;
15534 BlendMask[i] = SplitNumElements + i;
15535 } else if (M >= 0) {
15536 V1BlendMask[i] = M;
15537 BlendMask[i] = i;
15538 }
15539 }
15540
15541 bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
15542 GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
15543
15544 // Because the lowering happens after all combining takes place, we need to
15545 // manually combine these blend masks as much as possible so that we create
15546 // a minimal number of high-level vector shuffle nodes.
15547 assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
15548
15549 // First try just blending the halves of V1 or V2.
15550 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15551 return DAG.getUNDEF(SplitVT);
15552 if (!UseLoV2 && !UseHiV2)
15553 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15554 if (!UseLoV1 && !UseHiV1)
15555 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15556
15557 SDValue V1Blend, V2Blend;
15558 if (UseLoV1 && UseHiV1) {
15559 V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15560 } else {
15561 // We only use half of V1 so map the usage down into the final blend mask.
15562 V1Blend = UseLoV1 ? LoV1 : HiV1;
15563 for (int i = 0; i < SplitNumElements; ++i)
15564 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15565 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15566 }
15567 if (UseLoV2 && UseHiV2) {
15568 V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15569 } else {
15570 // We only use half of V2 so map the usage down into the final blend mask.
15571 V2Blend = UseLoV2 ? LoV2 : HiV2;
15572 for (int i = 0; i < SplitNumElements; ++i)
15573 if (BlendMask[i] >= SplitNumElements)
15574 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15575 }
15576 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15577 };
15578
15579 if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
15580 return SDValue();
15581
15582 SDValue Lo = HalfBlend(LoMask);
15583 SDValue Hi = HalfBlend(HiMask);
15584 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15585}
15586
15587/// Either split a vector in halves or decompose the shuffles and the
15588/// blend/unpack.
15589///
15590/// This is provided as a good fallback for many lowerings of non-single-input
15591/// shuffles with more than one 128-bit lane. In those cases, we want to select
15592/// between splitting the shuffle into 128-bit components and stitching those
15593/// back together vs. extracting the single-input shuffles and blending those
15594/// results.
15596 SDValue V2, ArrayRef<int> Mask,
15597 const APInt &Zeroable,
15598 const X86Subtarget &Subtarget,
15599 SelectionDAG &DAG) {
15600 assert(!V2.isUndef() && "This routine must not be used to lower single-input "
15601 "shuffles as it could then recurse on itself.");
15602 int Size = Mask.size();
15603
15604 // If this can be modeled as a broadcast of two elements followed by a blend,
15605 // prefer that lowering. This is especially important because broadcasts can
15606 // often fold with memory operands.
15607 auto DoBothBroadcast = [&] {
15608 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15609 for (int M : Mask)
15610 if (M >= Size) {
15611 if (V2BroadcastIdx < 0)
15612 V2BroadcastIdx = M - Size;
15613 else if ((M - Size) != V2BroadcastIdx &&
15614 !IsElementEquivalent(Size, V2, V2, M - Size, V2BroadcastIdx))
15615 return false;
15616 } else if (M >= 0) {
15617 if (V1BroadcastIdx < 0)
15618 V1BroadcastIdx = M;
15619 else if (M != V1BroadcastIdx &&
15620 !IsElementEquivalent(Size, V1, V1, M, V1BroadcastIdx))
15621 return false;
15622 }
15623 return true;
15624 };
15625 if (DoBothBroadcast())
15626 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15627 Subtarget, DAG);
15628
15629 // If the inputs all stem from a single 128-bit lane of each input, then we
15630 // split them rather than blending because the split will decompose to
15631 // unusually few instructions.
15632 int LaneCount = VT.getSizeInBits() / 128;
15633 int LaneSize = Size / LaneCount;
15634 SmallBitVector LaneInputs[2];
15635 LaneInputs[0].resize(LaneCount, false);
15636 LaneInputs[1].resize(LaneCount, false);
15637 for (int i = 0; i < Size; ++i)
15638 if (Mask[i] >= 0)
15639 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15640 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15641 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15642 /*SimpleOnly*/ false);
15643
15644 // Without AVX2, if we can freely split the subvectors then we're better off
15645 // performing half width shuffles.
15646 if (!Subtarget.hasAVX2()) {
15648 SDValue BC2 = peekThroughBitcasts(V2);
15649 bool SplatOrSplitV1 = isFreeToSplitVector(BC1, DAG) ||
15650 DAG.isSplatValue(BC1, /*AllowUndefs=*/true);
15651 bool SplatOrSplitV2 = isFreeToSplitVector(BC2, DAG) ||
15652 DAG.isSplatValue(BC2, /*AllowUndefs=*/true);
15653 if (SplatOrSplitV1 && SplatOrSplitV2)
15654 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15655 /*SimpleOnly*/ false);
15656 }
15657
15658 // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
15659 // requires that the decomposed single-input shuffles don't end up here.
15660 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Zeroable,
15661 Subtarget, DAG);
15662}
15663
15664// Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15665// TODO: Extend to support v8f32 (+ 512-bit shuffles).
15667 SDValue V1, SDValue V2,
15668 ArrayRef<int> Mask,
15669 SelectionDAG &DAG) {
15670 assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
15671
15672 int LHSMask[4] = {-1, -1, -1, -1};
15673 int RHSMask[4] = {-1, -1, -1, -1};
15674 int SHUFPDMask[4] = {-1, -1, -1, -1};
15675
15676 // As SHUFPD uses a single LHS/RHS element per lane, we can always
15677 // perform the shuffle once the lanes have been shuffled in place.
15678 for (int i = 0; i != 4; ++i) {
15679 int M = Mask[i];
15680 if (M < 0)
15681 continue;
15682 int LaneBase = i & ~1;
15683 auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15684 LaneMask[LaneBase + (M & 1)] = M;
15685 SHUFPDMask[i] = M & 1;
15686 }
15687
15688 SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15689 SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15690 return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15691 getSHUFPDImmForMask(SHUFPDMask, DL, DAG));
15692}
15693
15694/// Lower a vector shuffle crossing multiple 128-bit lanes as
15695/// a lane permutation followed by a per-lane permutation.
15696///
15697/// This is mainly for cases where we can have non-repeating permutes
15698/// in each lane.
15699///
15700/// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15701/// we should investigate merging them.
15703 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15704 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15705 int NumElts = VT.getVectorNumElements();
15706 int NumLanes = VT.getSizeInBits() / 128;
15707 int NumEltsPerLane = NumElts / NumLanes;
15708 bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
15709
15710 /// Attempts to find a sublane permute with the given size
15711 /// that gets all elements into their target lanes.
15712 ///
15713 /// If successful, fills CrossLaneMask and InLaneMask and returns true.
15714 /// If unsuccessful, returns false and may overwrite InLaneMask.
15715 auto getSublanePermute = [&](int NumSublanes) -> SDValue {
15716 int NumSublanesPerLane = NumSublanes / NumLanes;
15717 int NumEltsPerSublane = NumElts / NumSublanes;
15718
15719 SmallVector<int, 16> CrossLaneMask;
15720 SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
15721 // CrossLaneMask but one entry == one sublane.
15722 SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
15723 APInt DemandedCrossLane = APInt::getZero(NumElts);
15724
15725 for (int i = 0; i != NumElts; ++i) {
15726 int M = Mask[i];
15727 if (M < 0)
15728 continue;
15729
15730 int SrcSublane = M / NumEltsPerSublane;
15731 int DstLane = i / NumEltsPerLane;
15732
15733 // We only need to get the elements into the right lane, not sublane.
15734 // So search all sublanes that make up the destination lane.
15735 bool Found = false;
15736 int DstSubStart = DstLane * NumSublanesPerLane;
15737 int DstSubEnd = DstSubStart + NumSublanesPerLane;
15738 for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
15739 if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
15740 continue;
15741
15742 Found = true;
15743 CrossLaneMaskLarge[DstSublane] = SrcSublane;
15744 int DstSublaneOffset = DstSublane * NumEltsPerSublane;
15745 InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
15746 DemandedCrossLane.setBit(InLaneMask[i]);
15747 break;
15748 }
15749 if (!Found)
15750 return SDValue();
15751 }
15752
15753 // Fill CrossLaneMask using CrossLaneMaskLarge.
15754 narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15755
15756 if (!CanUseSublanes) {
15757 // If we're only shuffling a single lowest lane and the rest are identity
15758 // then don't bother.
15759 // TODO - isShuffleMaskInputInPlace could be extended to something like
15760 // this.
15761 int NumIdentityLanes = 0;
15762 bool OnlyShuffleLowestLane = true;
15763 for (int i = 0; i != NumLanes; ++i) {
15764 int LaneOffset = i * NumEltsPerLane;
15765 if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15766 i * NumEltsPerLane))
15767 NumIdentityLanes++;
15768 else if (CrossLaneMask[LaneOffset] != 0)
15769 OnlyShuffleLowestLane = false;
15770 }
15771 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15772 return SDValue();
15773 }
15774
15775 // Simplify CrossLaneMask based on the actual demanded elements.
15776 if (V1.hasOneUse())
15777 for (int i = 0; i != NumElts; ++i)
15778 if (!DemandedCrossLane[i])
15779 CrossLaneMask[i] = SM_SentinelUndef;
15780
15781 // Avoid returning the same shuffle operation. For example,
15782 // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
15783 // undef:v16i16
15784 if (CrossLaneMask == Mask || InLaneMask == Mask)
15785 return SDValue();
15786
15787 SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15788 return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15789 InLaneMask);
15790 };
15791
15792 // First attempt a solution with full lanes.
15793 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
15794 return V;
15795
15796 // The rest of the solutions use sublanes.
15797 if (!CanUseSublanes)
15798 return SDValue();
15799
15800 // Then attempt a solution with 64-bit sublanes (vpermq).
15801 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
15802 return V;
15803
15804 // If that doesn't work and we have fast variable cross-lane shuffle,
15805 // attempt 32-bit sublanes (vpermd).
15806 if (!Subtarget.hasFastVariableCrossLaneShuffle())
15807 return SDValue();
15808
15809 return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
15810}
15811
15812/// Helper to get compute inlane shuffle mask for a complete shuffle mask.
15813static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
15814 SmallVector<int> &InLaneMask) {
15815 int Size = Mask.size();
15816 InLaneMask.assign(Mask.begin(), Mask.end());
15817 for (int i = 0; i < Size; ++i) {
15818 int &M = InLaneMask[i];
15819 if (M < 0)
15820 continue;
15821 if (((M % Size) / LaneSize) != (i / LaneSize))
15822 M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15823 }
15824}
15825
15826/// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15827/// source with a lane permutation.
15828///
15829/// This lowering strategy results in four instructions in the worst case for a
15830/// single-input cross lane shuffle which is lower than any other fully general
15831/// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15832/// shuffle pattern should be handled prior to trying this lowering.
15834 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15835 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15836 // FIXME: This should probably be generalized for 512-bit vectors as well.
15837 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15838 int Size = Mask.size();
15839 int LaneSize = Size / 2;
15840
15841 // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15842 // Only do this if the elements aren't all from the lower lane,
15843 // otherwise we're (probably) better off doing a split.
15844 if (VT == MVT::v4f64 &&
15845 !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15846 return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
15847
15848 // If there are only inputs from one 128-bit lane, splitting will in fact be
15849 // less expensive. The flags track whether the given lane contains an element
15850 // that crosses to another lane.
15851 bool AllLanes;
15852 if (!Subtarget.hasAVX2()) {
15853 bool LaneCrossing[2] = {false, false};
15854 for (int i = 0; i < Size; ++i)
15855 if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15856 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15857 AllLanes = LaneCrossing[0] && LaneCrossing[1];
15858 } else {
15859 bool LaneUsed[2] = {false, false};
15860 for (int i = 0; i < Size; ++i)
15861 if (Mask[i] >= 0)
15862 LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15863 AllLanes = LaneUsed[0] && LaneUsed[1];
15864 }
15865
15866 // TODO - we could support shuffling V2 in the Flipped input.
15867 assert(V2.isUndef() &&
15868 "This last part of this routine only works on single input shuffles");
15869
15870 SmallVector<int> InLaneMask;
15871 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
15872
15873 assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15874 "In-lane shuffle mask expected");
15875
15876 // If we're not using both lanes in each lane and the inlane mask is not
15877 // repeating, then we're better off splitting.
15878 if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
15879 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
15880 /*SimpleOnly*/ false);
15881
15882 // Flip the lanes, and shuffle the results which should now be in-lane.
15883 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15884 SDValue Flipped = DAG.getBitcast(PVT, V1);
15885 Flipped =
15886 DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15887 Flipped = DAG.getBitcast(VT, Flipped);
15888 return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15889}
15890
15891/// Handle lowering 2-lane 128-bit shuffles.
15893 SDValue V2, ArrayRef<int> Mask,
15894 const APInt &Zeroable,
15895 const X86Subtarget &Subtarget,
15896 SelectionDAG &DAG) {
15897 if (V2.isUndef()) {
15898 // Attempt to match VBROADCAST*128 subvector broadcast load.
15899 bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
15900 bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
15901 if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
15903 MVT MemVT = VT.getHalfNumVectorElementsVT();
15904 unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
15906 if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
15907 VT, MemVT, Ld, Ofs, DAG))
15908 return BcstLd;
15909 }
15910
15911 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15912 if (Subtarget.hasAVX2())
15913 return SDValue();
15914 }
15915
15916 bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15917
15918 SmallVector<int, 4> WidenedMask;
15919 if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15920 return SDValue();
15921
15922 bool IsLowZero = (Zeroable & 0x3) == 0x3;
15923 bool IsHighZero = (Zeroable & 0xc) == 0xc;
15924
15925 // Try to use an insert into a zero vector.
15926 if (WidenedMask[0] == 0 && IsHighZero) {
15927 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15928 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15929 DAG.getVectorIdxConstant(0, DL));
15930 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15931 getZeroVector(VT, Subtarget, DAG, DL), LoV,
15932 DAG.getVectorIdxConstant(0, DL));
15933 }
15934
15935 // TODO: If minimizing size and one of the inputs is a zero vector and the
15936 // the zero vector has only one use, we could use a VPERM2X128 to save the
15937 // instruction bytes needed to explicitly generate the zero vector.
15938
15939 // Blends are faster and handle all the non-lane-crossing cases.
15940 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15941 Subtarget, DAG))
15942 return Blend;
15943
15944 // If either input operand is a zero vector, use VPERM2X128 because its mask
15945 // allows us to replace the zero input with an implicit zero.
15946 if (!IsLowZero && !IsHighZero) {
15947 // Check for patterns which can be matched with a single insert of a 128-bit
15948 // subvector.
15949 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
15950 if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
15951
15952 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15953 // this will likely become vinsertf128 which can't fold a 256-bit memop.
15955 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15956 SDValue SubVec =
15957 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
15958 DAG.getVectorIdxConstant(0, DL));
15959 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15960 DAG.getVectorIdxConstant(2, DL));
15961 }
15962 }
15963
15964 // Try to use SHUF128 if possible.
15965 if (Subtarget.hasVLX()) {
15966 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15967 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15968 ((WidenedMask[1] % 2) << 1);
15969 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
15970 DAG.getTargetConstant(PermMask, DL, MVT::i8));
15971 }
15972 }
15973 }
15974
15975 // Otherwise form a 128-bit permutation. After accounting for undefs,
15976 // convert the 64-bit shuffle mask selection values into 128-bit
15977 // selection bits by dividing the indexes by 2 and shifting into positions
15978 // defined by a vperm2*128 instruction's immediate control byte.
15979
15980 // The immediate permute control byte looks like this:
15981 // [1:0] - select 128 bits from sources for low half of destination
15982 // [2] - ignore
15983 // [3] - zero low half of destination
15984 // [5:4] - select 128 bits from sources for high half of destination
15985 // [6] - ignore
15986 // [7] - zero high half of destination
15987
15988 assert((WidenedMask[0] >= 0 || IsLowZero) &&
15989 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
15990
15991 unsigned PermMask = 0;
15992 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
15993 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
15994
15995 // Check the immediate mask and replace unused sources with undef.
15996 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
15997 V1 = DAG.getUNDEF(VT);
15998 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
15999 V2 = DAG.getUNDEF(VT);
16000
16001 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16002 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16003}
16004
16005/// Lower a vector shuffle by first fixing the 128-bit lanes and then
16006/// shuffling each lane.
16007///
16008/// This attempts to create a repeated lane shuffle where each lane uses one
16009/// or two of the lanes of the inputs. The lanes of the input vectors are
16010/// shuffled in one or two independent shuffles to get the lanes into the
16011/// position needed by the final shuffle.
16013 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16014 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16015 // This is only useful for binary shuffle with a non-repeating mask.
16016 if (V2.isUndef() || is128BitLaneRepeatedShuffleMask(VT, Mask))
16017 return SDValue();
16018
16019 int NumElts = Mask.size();
16020 int NumLanes = VT.getSizeInBits() / 128;
16021 int NumLaneElts = 128 / VT.getScalarSizeInBits();
16022 SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16023 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16024
16025 // First pass will try to fill in the RepeatMask from lanes that need two
16026 // sources.
16027 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16028 int Srcs[2] = {-1, -1};
16029 SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16030 for (int i = 0; i != NumLaneElts; ++i) {
16031 int M = Mask[(Lane * NumLaneElts) + i];
16032 if (M < 0)
16033 continue;
16034 // Determine which of the possible input lanes (NumLanes from each source)
16035 // this element comes from. Assign that as one of the sources for this
16036 // lane. We can assign up to 2 sources for this lane. If we run out
16037 // sources we can't do anything.
16038 int LaneSrc = M / NumLaneElts;
16039 int Src;
16040 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16041 Src = 0;
16042 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16043 Src = 1;
16044 else
16045 return SDValue();
16046
16047 Srcs[Src] = LaneSrc;
16048 InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16049 }
16050
16051 // If this lane has two sources, see if it fits with the repeat mask so far.
16052 if (Srcs[1] < 0)
16053 continue;
16054
16055 LaneSrcs[Lane][0] = Srcs[0];
16056 LaneSrcs[Lane][1] = Srcs[1];
16057
16058 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16059 assert(M1.size() == M2.size() && "Unexpected mask size");
16060 for (int i = 0, e = M1.size(); i != e; ++i)
16061 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16062 return false;
16063 return true;
16064 };
16065
16066 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16067 assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
16068 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16069 int M = Mask[i];
16070 if (M < 0)
16071 continue;
16072 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
16073 "Unexpected mask element");
16074 MergedMask[i] = M;
16075 }
16076 };
16077
16078 if (MatchMasks(InLaneMask, RepeatMask)) {
16079 // Merge this lane mask into the final repeat mask.
16080 MergeMasks(InLaneMask, RepeatMask);
16081 continue;
16082 }
16083
16084 // Didn't find a match. Swap the operands and try again.
16085 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16087
16088 if (MatchMasks(InLaneMask, RepeatMask)) {
16089 // Merge this lane mask into the final repeat mask.
16090 MergeMasks(InLaneMask, RepeatMask);
16091 continue;
16092 }
16093
16094 // Couldn't find a match with the operands in either order.
16095 return SDValue();
16096 }
16097
16098 // Now handle any lanes with only one source.
16099 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16100 // If this lane has already been processed, skip it.
16101 if (LaneSrcs[Lane][0] >= 0)
16102 continue;
16103
16104 for (int i = 0; i != NumLaneElts; ++i) {
16105 int M = Mask[(Lane * NumLaneElts) + i];
16106 if (M < 0)
16107 continue;
16108
16109 // If RepeatMask isn't defined yet we can define it ourself.
16110 if (RepeatMask[i] < 0)
16111 RepeatMask[i] = M % NumLaneElts;
16112
16113 if (RepeatMask[i] < NumElts) {
16114 if (RepeatMask[i] != M % NumLaneElts)
16115 return SDValue();
16116 LaneSrcs[Lane][0] = M / NumLaneElts;
16117 } else {
16118 if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16119 return SDValue();
16120 LaneSrcs[Lane][1] = M / NumLaneElts;
16121 }
16122 }
16123
16124 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16125 return SDValue();
16126 }
16127
16128 SmallVector<int, 16> NewMask(NumElts, -1);
16129 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16130 int Src = LaneSrcs[Lane][0];
16131 for (int i = 0; i != NumLaneElts; ++i) {
16132 int M = -1;
16133 if (Src >= 0)
16134 M = Src * NumLaneElts + i;
16135 NewMask[Lane * NumLaneElts + i] = M;
16136 }
16137 }
16138 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16139 // Ensure we didn't get back the shuffle we started with.
16140 // FIXME: This is a hack to make up for some splat handling code in
16141 // getVectorShuffle.
16142 if (isa<ShuffleVectorSDNode>(NewV1) &&
16143 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16144 return SDValue();
16145
16146 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16147 int Src = LaneSrcs[Lane][1];
16148 for (int i = 0; i != NumLaneElts; ++i) {
16149 int M = -1;
16150 if (Src >= 0)
16151 M = Src * NumLaneElts + i;
16152 NewMask[Lane * NumLaneElts + i] = M;
16153 }
16154 }
16155 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16156 // Ensure we didn't get back the shuffle we started with.
16157 // FIXME: This is a hack to make up for some splat handling code in
16158 // getVectorShuffle.
16159 if (isa<ShuffleVectorSDNode>(NewV2) &&
16160 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16161 return SDValue();
16162
16163 for (int i = 0; i != NumElts; ++i) {
16164 if (Mask[i] < 0) {
16165 NewMask[i] = -1;
16166 continue;
16167 }
16168 NewMask[i] = RepeatMask[i % NumLaneElts];
16169 if (NewMask[i] < 0)
16170 continue;
16171
16172 NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16173 }
16174 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16175}
16176
16177/// If the input shuffle mask results in a vector that is undefined in all upper
16178/// or lower half elements and that mask accesses only 2 halves of the
16179/// shuffle's operands, return true. A mask of half the width with mask indexes
16180/// adjusted to access the extracted halves of the original shuffle operands is
16181/// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16182/// lower half of each input operand is accessed.
16183static bool
16185 int &HalfIdx1, int &HalfIdx2) {
16186 assert((Mask.size() == HalfMask.size() * 2) &&
16187 "Expected input mask to be twice as long as output");
16188
16189 // Exactly one half of the result must be undef to allow narrowing.
16190 bool UndefLower = isUndefLowerHalf(Mask);
16191 bool UndefUpper = isUndefUpperHalf(Mask);
16192 if (UndefLower == UndefUpper)
16193 return false;
16194
16195 unsigned HalfNumElts = HalfMask.size();
16196 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16197 HalfIdx1 = -1;
16198 HalfIdx2 = -1;
16199 for (unsigned i = 0; i != HalfNumElts; ++i) {
16200 int M = Mask[i + MaskIndexOffset];
16201 if (M < 0) {
16202 HalfMask[i] = M;
16203 continue;
16204 }
16205
16206 // Determine which of the 4 half vectors this element is from.
16207 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16208 int HalfIdx = M / HalfNumElts;
16209
16210 // Determine the element index into its half vector source.
16211 int HalfElt = M % HalfNumElts;
16212
16213 // We can shuffle with up to 2 half vectors, set the new 'half'
16214 // shuffle mask accordingly.
16215 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16216 HalfMask[i] = HalfElt;
16217 HalfIdx1 = HalfIdx;
16218 continue;
16219 }
16220 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16221 HalfMask[i] = HalfElt + HalfNumElts;
16222 HalfIdx2 = HalfIdx;
16223 continue;
16224 }
16225
16226 // Too many half vectors referenced.
16227 return false;
16228 }
16229
16230 return true;
16231}
16232
16233/// Given the output values from getHalfShuffleMask(), create a half width
16234/// shuffle of extracted vectors followed by an insert back to full width.
16236 ArrayRef<int> HalfMask, int HalfIdx1,
16237 int HalfIdx2, bool UndefLower,
16238 SelectionDAG &DAG, bool UseConcat = false) {
16239 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
16240 assert(V1.getValueType().isSimple() && "Expecting only simple types");
16241
16242 MVT VT = V1.getSimpleValueType();
16243 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16244 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16245
16246 auto getHalfVector = [&](int HalfIdx) {
16247 if (HalfIdx < 0)
16248 return DAG.getUNDEF(HalfVT);
16249 SDValue V = (HalfIdx < 2 ? V1 : V2);
16250 HalfIdx = (HalfIdx % 2) * HalfNumElts;
16251 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16252 DAG.getVectorIdxConstant(HalfIdx, DL));
16253 };
16254
16255 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16256 SDValue Half1 = getHalfVector(HalfIdx1);
16257 SDValue Half2 = getHalfVector(HalfIdx2);
16258 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16259 if (UseConcat) {
16260 SDValue Op0 = V;
16261 SDValue Op1 = DAG.getUNDEF(HalfVT);
16262 if (UndefLower)
16263 std::swap(Op0, Op1);
16264 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16265 }
16266
16267 unsigned Offset = UndefLower ? HalfNumElts : 0;
16268 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16270}
16271
16272/// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16273/// This allows for fast cases such as subvector extraction/insertion
16274/// or shuffling smaller vector types which can lower more efficiently.
16276 SDValue V2, ArrayRef<int> Mask,
16277 const X86Subtarget &Subtarget,
16278 SelectionDAG &DAG) {
16279 assert((VT.is256BitVector() || VT.is512BitVector()) &&
16280 "Expected 256-bit or 512-bit vector");
16281
16282 bool UndefLower = isUndefLowerHalf(Mask);
16283 if (!UndefLower && !isUndefUpperHalf(Mask))
16284 return SDValue();
16285
16286 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
16287 "Completely undef shuffle mask should have been simplified already");
16288
16289 // Upper half is undef and lower half is whole upper subvector.
16290 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16291 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16292 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16293 if (!UndefLower &&
16294 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16295 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16296 DAG.getVectorIdxConstant(HalfNumElts, DL));
16297 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16298 DAG.getVectorIdxConstant(0, DL));
16299 }
16300
16301 // Lower half is undef and upper half is whole lower subvector.
16302 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16303 if (UndefLower &&
16304 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16305 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16306 DAG.getVectorIdxConstant(0, DL));
16307 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16308 DAG.getVectorIdxConstant(HalfNumElts, DL));
16309 }
16310
16311 int HalfIdx1, HalfIdx2;
16312 SmallVector<int, 8> HalfMask(HalfNumElts);
16313 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
16314 return SDValue();
16315
16316 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
16317
16318 // Only shuffle the halves of the inputs when useful.
16319 unsigned NumLowerHalves =
16320 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
16321 unsigned NumUpperHalves =
16322 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
16323 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
16324
16325 // Determine the larger pattern of undef/halves, then decide if it's worth
16326 // splitting the shuffle based on subtarget capabilities and types.
16327 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
16328 if (!UndefLower) {
16329 // XXXXuuuu: no insert is needed.
16330 // Always extract lowers when setting lower - these are all free subreg ops.
16331 if (NumUpperHalves == 0)
16332 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16333 UndefLower, DAG);
16334
16335 if (NumUpperHalves == 1) {
16336 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
16337 if (Subtarget.hasAVX2()) {
16338 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
16339 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
16340 !is128BitUnpackShuffleMask(HalfMask, DAG) &&
16341 (!isSingleSHUFPSMask(HalfMask) ||
16342 Subtarget.hasFastVariableCrossLaneShuffle()))
16343 return SDValue();
16344 // If this is an unary shuffle (assume that the 2nd operand is
16345 // canonicalized to undef), then we can use vpermpd. Otherwise, we
16346 // are better off extracting the upper half of 1 operand and using a
16347 // narrow shuffle.
16348 if (EltWidth == 64 && V2.isUndef())
16349 return SDValue();
16350 // If this is an unary vXi8 shuffle with inplace halves, then perform as
16351 // full width pshufb, and then merge.
16352 if (EltWidth == 8 && HalfIdx1 == 0 && HalfIdx2 == 1)
16353 return SDValue();
16354 }
16355 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16356 if (Subtarget.hasAVX512() && VT.is512BitVector())
16357 return SDValue();
16358 // Extract + narrow shuffle is better than the wide alternative.
16359 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16360 UndefLower, DAG);
16361 }
16362
16363 // Don't extract both uppers, instead shuffle and then extract.
16364 assert(NumUpperHalves == 2 && "Half vector count went wrong");
16365 return SDValue();
16366 }
16367
16368 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
16369 if (NumUpperHalves == 0) {
16370 // AVX2 has efficient 64-bit element cross-lane shuffles.
16371 // TODO: Refine to account for unary shuffle, splat, and other masks?
16372 if (Subtarget.hasAVX2() && EltWidth == 64)
16373 return SDValue();
16374 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16375 if (Subtarget.hasAVX512() && VT.is512BitVector())
16376 return SDValue();
16377 // Narrow shuffle + insert is better than the wide alternative.
16378 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16379 UndefLower, DAG);
16380 }
16381
16382 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
16383 return SDValue();
16384}
16385
16386/// Handle case where shuffle sources are coming from the same 128-bit lane and
16387/// every lane can be represented as the same repeating mask - allowing us to
16388/// shuffle the sources with the repeating shuffle and then permute the result
16389/// to the destination lanes.
16391 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16392 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16393 int NumElts = VT.getVectorNumElements();
16394 int NumLanes = VT.getSizeInBits() / 128;
16395 int NumLaneElts = NumElts / NumLanes;
16396
16397 // On AVX2 we may be able to just shuffle the lowest elements and then
16398 // broadcast the result.
16399 if (Subtarget.hasAVX2()) {
16400 for (unsigned BroadcastSize : {16, 32, 64}) {
16401 if (BroadcastSize <= VT.getScalarSizeInBits())
16402 continue;
16403 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16404
16405 // Attempt to match a repeating pattern every NumBroadcastElts,
16406 // accounting for UNDEFs but only references the lowest 128-bit
16407 // lane of the inputs.
16408 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16409 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16410 for (int j = 0; j != NumBroadcastElts; ++j) {
16411 int M = Mask[i + j];
16412 if (M < 0)
16413 continue;
16414 int &R = RepeatMask[j];
16415 if (0 != ((M % NumElts) / NumLaneElts))
16416 return false;
16417 if (0 <= R && R != M)
16418 return false;
16419 R = M;
16420 }
16421 return true;
16422 };
16423
16424 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16425 if (!FindRepeatingBroadcastMask(RepeatMask))
16426 continue;
16427
16428 // Shuffle the (lowest) repeated elements in place for broadcast.
16429 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16430
16431 // Shuffle the actual broadcast.
16432 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16433 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16434 for (int j = 0; j != NumBroadcastElts; ++j)
16435 BroadcastMask[i + j] = j;
16436
16437 // Avoid returning the same shuffle operation. For example,
16438 // v8i32 = vector_shuffle<0,1,0,1,0,1,0,1> t5, undef:v8i32
16439 if (BroadcastMask == Mask)
16440 return SDValue();
16441
16442 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16443 BroadcastMask);
16444 }
16445 }
16446
16447 // Bail if the shuffle mask doesn't cross 128-bit lanes.
16448 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16449 return SDValue();
16450
16451 // Bail if we already have a repeated lane shuffle mask.
16452 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16453 return SDValue();
16454
16455 // Helper to look for repeated mask in each split sublane, and that those
16456 // sublanes can then be permuted into place.
16457 auto ShuffleSubLanes = [&](int SubLaneScale) {
16458 int NumSubLanes = NumLanes * SubLaneScale;
16459 int NumSubLaneElts = NumLaneElts / SubLaneScale;
16460
16461 // Check that all the sources are coming from the same lane and see if we
16462 // can form a repeating shuffle mask (local to each sub-lane). At the same
16463 // time, determine the source sub-lane for each destination sub-lane.
16464 int TopSrcSubLane = -1;
16465 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16466 SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
16467 SubLaneScale,
16468 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
16469
16470 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16471 // Extract the sub-lane mask, check that it all comes from the same lane
16472 // and normalize the mask entries to come from the first lane.
16473 int SrcLane = -1;
16474 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16475 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16476 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16477 if (M < 0)
16478 continue;
16479 int Lane = (M % NumElts) / NumLaneElts;
16480 if ((0 <= SrcLane) && (SrcLane != Lane))
16481 return SDValue();
16482 SrcLane = Lane;
16483 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16484 SubLaneMask[Elt] = LocalM;
16485 }
16486
16487 // Whole sub-lane is UNDEF.
16488 if (SrcLane < 0)
16489 continue;
16490
16491 // Attempt to match against the candidate repeated sub-lane masks.
16492 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16493 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16494 for (int i = 0; i != NumSubLaneElts; ++i) {
16495 if (M1[i] < 0 || M2[i] < 0)
16496 continue;
16497 if (M1[i] != M2[i])
16498 return false;
16499 }
16500 return true;
16501 };
16502
16503 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16504 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16505 continue;
16506
16507 // Merge the sub-lane mask into the matching repeated sub-lane mask.
16508 for (int i = 0; i != NumSubLaneElts; ++i) {
16509 int M = SubLaneMask[i];
16510 if (M < 0)
16511 continue;
16512 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
16513 "Unexpected mask element");
16514 RepeatedSubLaneMask[i] = M;
16515 }
16516
16517 // Track the top most source sub-lane - by setting the remaining to
16518 // UNDEF we can greatly simplify shuffle matching.
16519 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16520 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16521 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16522 break;
16523 }
16524
16525 // Bail if we failed to find a matching repeated sub-lane mask.
16526 if (Dst2SrcSubLanes[DstSubLane] < 0)
16527 return SDValue();
16528 }
16529 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
16530 "Unexpected source lane");
16531
16532 // Create a repeating shuffle mask for the entire vector.
16533 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16534 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16535 int Lane = SubLane / SubLaneScale;
16536 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16537 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16538 int M = RepeatedSubLaneMask[Elt];
16539 if (M < 0)
16540 continue;
16541 int Idx = (SubLane * NumSubLaneElts) + Elt;
16542 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16543 }
16544 }
16545
16546 // Shuffle each source sub-lane to its destination.
16547 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16548 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16549 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16550 if (SrcSubLane < 0)
16551 continue;
16552 for (int j = 0; j != NumSubLaneElts; ++j)
16553 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16554 }
16555
16556 // Avoid returning the same shuffle operation.
16557 // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
16558 if (RepeatedMask == Mask || SubLaneMask == Mask)
16559 return SDValue();
16560
16561 SDValue RepeatedShuffle =
16562 DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16563
16564 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16565 SubLaneMask);
16566 };
16567
16568 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16569 // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
16570 // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
16571 // Otherwise we can only permute whole 128-bit lanes.
16572 int MinSubLaneScale = 1, MaxSubLaneScale = 1;
16573 if (Subtarget.hasAVX2() && VT.is256BitVector()) {
16574 bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
16575 MinSubLaneScale = 2;
16576 MaxSubLaneScale =
16577 (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
16578 }
16579 if (Subtarget.hasBWI() && VT == MVT::v64i8)
16580 MinSubLaneScale = MaxSubLaneScale = 4;
16581
16582 for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
16583 if (SDValue Shuffle = ShuffleSubLanes(Scale))
16584 return Shuffle;
16585
16586 return SDValue();
16587}
16588
16590 bool &ForceV1Zero, bool &ForceV2Zero,
16591 unsigned &ShuffleImm, ArrayRef<int> Mask,
16592 const APInt &Zeroable) {
16593 int NumElts = VT.getVectorNumElements();
16594 assert(VT.getScalarSizeInBits() == 64 &&
16595 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
16596 "Unexpected data type for VSHUFPD");
16597 assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
16598 "Illegal shuffle mask");
16599
16600 bool ZeroLane[2] = { true, true };
16601 for (int i = 0; i < NumElts; ++i)
16602 ZeroLane[i & 1] &= Zeroable[i];
16603
16604 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
16605 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
16606 bool IsSHUFPD = true;
16607 bool IsCommutable = true;
16608 SmallVector<int, 8> SHUFPDMask(NumElts, -1);
16609 for (int i = 0; i < NumElts; ++i) {
16610 if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16611 continue;
16612 if (Mask[i] < 0)
16613 return false;
16614 int Val = (i & 6) + NumElts * (i & 1);
16615 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16616 if (Mask[i] < Val || Mask[i] > Val + 1)
16617 IsSHUFPD = false;
16618 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16619 IsCommutable = false;
16620 SHUFPDMask[i] = Mask[i] % 2;
16621 }
16622
16623 if (!IsSHUFPD && !IsCommutable)
16624 return false;
16625
16626 if (!IsSHUFPD && IsCommutable)
16627 std::swap(V1, V2);
16628
16629 ForceV1Zero = ZeroLane[0];
16630 ForceV2Zero = ZeroLane[1];
16631 ShuffleImm = getSHUFPDImm(SHUFPDMask);
16632 return true;
16633}
16634
16636 SDValue V2, ArrayRef<int> Mask,
16637 const APInt &Zeroable,
16638 const X86Subtarget &Subtarget,
16639 SelectionDAG &DAG) {
16640 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
16641 "Unexpected data type for VSHUFPD");
16642
16643 unsigned Immediate = 0;
16644 bool ForceV1Zero = false, ForceV2Zero = false;
16645 if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16646 Mask, Zeroable))
16647 return SDValue();
16648
16649 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16650 if (ForceV1Zero)
16651 V1 = getZeroVector(VT, Subtarget, DAG, DL);
16652 if (ForceV2Zero)
16653 V2 = getZeroVector(VT, Subtarget, DAG, DL);
16654
16655 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16656 DAG.getTargetConstant(Immediate, DL, MVT::i8));
16657}
16658
16659// Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16660// by zeroable elements in the remaining 24 elements. Turn this into two
16661// vmovqb instructions shuffled together.
16663 SDValue V1, SDValue V2,
16664 ArrayRef<int> Mask,
16665 const APInt &Zeroable,
16666 SelectionDAG &DAG) {
16667 assert(VT == MVT::v32i8 && "Unexpected type!");
16668
16669 // The first 8 indices should be every 8th element.
16670 if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16671 return SDValue();
16672
16673 // Remaining elements need to be zeroable.
16674 if (Zeroable.countl_one() < (Mask.size() - 8))
16675 return SDValue();
16676
16677 V1 = DAG.getBitcast(MVT::v4i64, V1);
16678 V2 = DAG.getBitcast(MVT::v4i64, V2);
16679
16680 V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16681 V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16682
16683 // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16684 // the upper bits of the result using an unpckldq.
16685 SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16686 { 0, 1, 2, 3, 16, 17, 18, 19,
16687 4, 5, 6, 7, 20, 21, 22, 23 });
16688 // Insert the unpckldq into a zero vector to widen to v32i8.
16689 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16690 DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16691 DAG.getVectorIdxConstant(0, DL));
16692}
16693
16694// a = shuffle v1, v2, mask1 ; interleaving lower lanes of v1 and v2
16695// b = shuffle v1, v2, mask2 ; interleaving higher lanes of v1 and v2
16696// =>
16697// ul = unpckl v1, v2
16698// uh = unpckh v1, v2
16699// a = vperm ul, uh
16700// b = vperm ul, uh
16701//
16702// Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
16703// and permute. We cannot directly match v3 because it is split into two
16704// 256-bit vectors in earlier isel stages. Therefore, this function matches a
16705// pair of 256-bit shuffles and makes sure the masks are consecutive.
16706//
16707// Once unpck and permute nodes are created, the permute corresponding to this
16708// shuffle is returned, while the other permute replaces the other half of the
16709// shuffle in the selection dag.
16711 SDValue V1, SDValue V2,
16712 ArrayRef<int> Mask,
16713 SelectionDAG &DAG) {
16714 if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
16715 VT != MVT::v32i8)
16716 return SDValue();
16717 // <B0, B1, B0+1, B1+1, ..., >
16718 auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
16719 unsigned Begin1) {
16720 size_t Size = Mask.size();
16721 assert(Size % 2 == 0 && "Expected even mask size");
16722 for (unsigned I = 0; I < Size; I += 2) {
16723 if (Mask[I] != (int)(Begin0 + I / 2) ||
16724 Mask[I + 1] != (int)(Begin1 + I / 2))
16725 return false;
16726 }
16727 return true;
16728 };
16729 // Check which half is this shuffle node
16730 int NumElts = VT.getVectorNumElements();
16731 size_t FirstQtr = NumElts / 2;
16732 size_t ThirdQtr = NumElts + NumElts / 2;
16733 bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
16734 bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
16735 if (!IsFirstHalf && !IsSecondHalf)
16736 return SDValue();
16737
16738 // Find the intersection between shuffle users of V1 and V2.
16739 SmallVector<SDNode *, 2> Shuffles;
16740 for (SDNode *User : V1->users())
16741 if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
16742 User->getOperand(1) == V2)
16743 Shuffles.push_back(User);
16744 // Limit user size to two for now.
16745 if (Shuffles.size() != 2)
16746 return SDValue();
16747 // Find out which half of the 512-bit shuffles is each smaller shuffle
16748 auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
16749 auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
16750 SDNode *FirstHalf;
16751 SDNode *SecondHalf;
16752 if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
16753 IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
16754 FirstHalf = Shuffles[0];
16755 SecondHalf = Shuffles[1];
16756 } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
16757 IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
16758 FirstHalf = Shuffles[1];
16759 SecondHalf = Shuffles[0];
16760 } else {
16761 return SDValue();
16762 }
16763 // Lower into unpck and perm. Return the perm of this shuffle and replace
16764 // the other.
16765 SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
16766 SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
16767 SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16768 DAG.getTargetConstant(0x20, DL, MVT::i8));
16769 SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
16770 DAG.getTargetConstant(0x31, DL, MVT::i8));
16771 if (IsFirstHalf) {
16772 DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
16773 return Perm1;
16774 }
16775 DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
16776 return Perm2;
16777}
16778
16779/// Handle lowering of 4-lane 64-bit floating point shuffles.
16780///
16781/// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16782/// isn't available.
16784 const APInt &Zeroable, SDValue V1, SDValue V2,
16785 const X86Subtarget &Subtarget,
16786 SelectionDAG &DAG) {
16787 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16788 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16789 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16790
16791 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16792 Subtarget, DAG))
16793 return V;
16794
16795 if (V2.isUndef()) {
16796 // Check for being able to broadcast a single element.
16797 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16798 Mask, Subtarget, DAG))
16799 return Broadcast;
16800
16801 // Use low duplicate instructions for masks that match their pattern.
16802 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16803 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16804
16805 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16806 // Non-half-crossing single input shuffles can be lowered with an
16807 // interleaved permutation.
16808 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16809 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16810 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16811 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16812 }
16813
16814 // With AVX2 we have direct support for this permutation.
16815 if (Subtarget.hasAVX2())
16816 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16817 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16818
16819 // Try to create an in-lane repeating shuffle mask and then shuffle the
16820 // results into the target lanes.
16822 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16823 return V;
16824
16825 // Try to permute the lanes and then use a per-lane permute.
16826 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16827 Mask, DAG, Subtarget))
16828 return V;
16829
16830 // Otherwise, fall back.
16831 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16832 DAG, Subtarget);
16833 }
16834
16835 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16836 Zeroable, Subtarget, DAG))
16837 return Blend;
16838
16839 // Use dedicated unpack instructions for masks that match their pattern.
16840 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, V1, V2, Mask, DAG))
16841 return V;
16842
16843 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16844 Zeroable, Subtarget, DAG))
16845 return Op;
16846
16847 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16848 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16849 bool V1IsSplat = isShuffleMaskInputBroadcastable(0, Mask);
16850 bool V2IsSplat = isShuffleMaskInputBroadcastable(1, Mask);
16851
16852 // If we have lane crossing shuffles AND they don't all come from the lower
16853 // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16854 // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16855 // canonicalize to a blend of splat which isn't necessary for this combine.
16856 if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16857 !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16858 (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16859 (V2.getOpcode() != ISD::BUILD_VECTOR) &&
16860 (!Subtarget.hasAVX2() ||
16861 !((V1IsInPlace || V1IsSplat) && (V2IsInPlace || V2IsSplat))))
16862 return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
16863
16864 // If we have one input in place, then we can permute the other input and
16865 // blend the result.
16866 if (V1IsInPlace || V2IsInPlace)
16867 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16868 Zeroable, Subtarget, DAG);
16869
16870 // Try to create an in-lane repeating shuffle mask and then shuffle the
16871 // results into the target lanes.
16873 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16874 return V;
16875
16876 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16877 // shuffle. However, if we have AVX2 and either inputs are already in place,
16878 // we will be able to shuffle even across lanes the other input in a single
16879 // instruction so skip this pattern.
16880 if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
16882 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16883 return V;
16884
16885 // If we have VLX support, we can use VEXPAND.
16886 if (Subtarget.hasVLX())
16887 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4f64, V1, V2, Mask,
16888 Zeroable, Subtarget, DAG))
16889 return V;
16890
16891 // If we have AVX2 then we always want to lower with a blend because an v4 we
16892 // can fully permute the elements.
16893 if (Subtarget.hasAVX2())
16894 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16895 Zeroable, Subtarget, DAG);
16896
16897 // Otherwise fall back on generic lowering.
16898 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16899 Subtarget, DAG);
16900}
16901
16902/// Handle lowering of 4-lane 64-bit integer shuffles.
16903///
16904/// This routine is only called when we have AVX2 and thus a reasonable
16905/// instruction set for v4i64 shuffling..
16907 const APInt &Zeroable, SDValue V1, SDValue V2,
16908 const X86Subtarget &Subtarget,
16909 SelectionDAG &DAG) {
16910 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16911 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16912 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16913 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16914
16915 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16916 Subtarget, DAG))
16917 return V;
16918
16919 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16920 Zeroable, Subtarget, DAG))
16921 return Blend;
16922
16923 // Check for being able to broadcast a single element.
16924 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16925 Subtarget, DAG))
16926 return Broadcast;
16927
16928 // Try to use shift instructions if fast.
16929 if (Subtarget.preferLowerShuffleAsShift())
16930 if (SDValue Shift =
16931 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16932 Subtarget, DAG, /*BitwiseOnly*/ true))
16933 return Shift;
16934
16935 if (V2.isUndef()) {
16936 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16937 // can use lower latency instructions that will operate on both lanes.
16938 SmallVector<int, 2> RepeatedMask;
16939 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16940 SmallVector<int, 4> PSHUFDMask;
16941 narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16942 return DAG.getBitcast(
16943 MVT::v4i64,
16944 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16945 DAG.getBitcast(MVT::v8i32, V1),
16946 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16947 }
16948
16949 // AVX2 provides a direct instruction for permuting a single input across
16950 // lanes.
16951 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16952 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16953 }
16954
16955 // Try to use shift instructions.
16956 if (SDValue Shift =
16957 lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
16958 DAG, /*BitwiseOnly*/ false))
16959 return Shift;
16960
16961 // If we have VLX support, we can use VALIGN or VEXPAND.
16962 if (Subtarget.hasVLX()) {
16963 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16964 Zeroable, Subtarget, DAG))
16965 return Rotate;
16966
16967 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v4i64, V1, V2, Mask,
16968 Zeroable, Subtarget, DAG))
16969 return V;
16970 }
16971
16972 // Try to use PALIGNR.
16973 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16974 Subtarget, DAG))
16975 return Rotate;
16976
16977 // Use dedicated unpack instructions for masks that match their pattern.
16978 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, V1, V2, Mask, DAG))
16979 return V;
16980
16981 bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
16982 bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
16983
16984 // If we have one input in place, then we can permute the other input and
16985 // blend the result.
16986 if (V1IsInPlace || V2IsInPlace)
16987 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
16988 Zeroable, Subtarget, DAG);
16989
16990 // Try to create an in-lane repeating shuffle mask and then shuffle the
16991 // results into the target lanes.
16993 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16994 return V;
16995
16996 // Try to lower to PERMQ(BLENDD(V1,V2)).
16997 if (SDValue V =
16998 lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
16999 return V;
17000
17001 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17002 // shuffle. However, if we have AVX2 and either inputs are already in place,
17003 // we will be able to shuffle even across lanes the other input in a single
17004 // instruction so skip this pattern.
17005 if (!V1IsInPlace && !V2IsInPlace)
17007 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17008 return Result;
17009
17010 // Otherwise fall back on generic blend lowering.
17011 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17012 Zeroable, Subtarget, DAG);
17013}
17014
17015/// Handle lowering of 8-lane 32-bit floating point shuffles.
17016///
17017/// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17018/// isn't available.
17020 const APInt &Zeroable, SDValue V1, SDValue V2,
17021 const X86Subtarget &Subtarget,
17022 SelectionDAG &DAG) {
17023 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17024 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
17025 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17026
17027 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17028 Zeroable, Subtarget, DAG))
17029 return Blend;
17030
17031 // Check for being able to broadcast a single element.
17032 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17033 Subtarget, DAG))
17034 return Broadcast;
17035
17036 if (!Subtarget.hasAVX2()) {
17037 SmallVector<int> InLaneMask;
17038 computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
17039
17040 if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
17041 if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
17042 /*SimpleOnly*/ true))
17043 return R;
17044 }
17045 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17046 Zeroable, Subtarget, DAG))
17047 return DAG.getBitcast(MVT::v8f32, ZExt);
17048
17049 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17050 // options to efficiently lower the shuffle.
17051 SmallVector<int, 4> RepeatedMask;
17052 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17053 assert(RepeatedMask.size() == 4 &&
17054 "Repeated masks must be half the mask width!");
17055
17056 // Use even/odd duplicate instructions for masks that match their pattern.
17057 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17058 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17059 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17060 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17061
17062 if (V2.isUndef())
17063 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17064 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17065
17066 // Use dedicated unpack instructions for masks that match their pattern.
17067 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, V1, V2, Mask, DAG))
17068 return V;
17069
17070 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
17071 // have already handled any direct blends.
17072 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
17073 }
17074
17075 // Try to create an in-lane repeating shuffle mask and then shuffle the
17076 // results into the target lanes.
17078 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17079 return V;
17080
17081 // If we have a single input shuffle with different shuffle patterns in the
17082 // two 128-bit lanes use the variable mask to VPERMILPS.
17083 if (V2.isUndef()) {
17084 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
17085 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17086 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
17087 }
17088 if (Subtarget.hasAVX2()) {
17089 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17090 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17091 }
17092 // Otherwise, fall back.
17093 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17094 DAG, Subtarget);
17095 }
17096
17097 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17098 // shuffle.
17100 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17101 return Result;
17102
17103 // If we have VLX support, we can use VEXPAND.
17104 if (Subtarget.hasVLX())
17105 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f32, V1, V2, Mask,
17106 Zeroable, Subtarget, DAG))
17107 return V;
17108
17109 // Try to match an interleave of two v8f32s and lower them as unpck and
17110 // permutes using ymms. This needs to go before we try to split the vectors.
17111 // Don't attempt on AVX1 if we're likely to split vectors anyway.
17112 if ((Subtarget.hasAVX2() ||
17115 !Subtarget.hasAVX512())
17116 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
17117 Mask, DAG))
17118 return V;
17119
17120 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17121 // since after split we get a more efficient code using vpunpcklwd and
17122 // vpunpckhwd instrs than vblend.
17123 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
17124 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17125 Subtarget, DAG);
17126
17127 // If we have AVX2 then we always want to lower with a blend because at v8 we
17128 // can fully permute the elements.
17129 if (Subtarget.hasAVX2())
17130 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17131 Zeroable, Subtarget, DAG);
17132
17133 // Otherwise fall back on generic lowering.
17134 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Zeroable,
17135 Subtarget, DAG);
17136}
17137
17138/// Handle lowering of 8-lane 32-bit integer shuffles.
17139///
17140/// This routine is only called when we have AVX2 and thus a reasonable
17141/// instruction set for v8i32 shuffling..
17143 const APInt &Zeroable, SDValue V1, SDValue V2,
17144 const X86Subtarget &Subtarget,
17145 SelectionDAG &DAG) {
17146 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17147 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17148 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17149 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
17150
17151 int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
17152
17153 // Whenever we can lower this as a zext, that instruction is strictly faster
17154 // than any alternative. It also allows us to fold memory operands into the
17155 // shuffle in many cases.
17156 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17157 Zeroable, Subtarget, DAG))
17158 return ZExt;
17159
17160 // Try to match an interleave of two v8i32s and lower them as unpck and
17161 // permutes using ymms. This needs to go before we try to split the vectors.
17162 if (!Subtarget.hasAVX512())
17163 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
17164 Mask, DAG))
17165 return V;
17166
17167 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17168 // since after split we get a more efficient code than vblend by using
17169 // vpunpcklwd and vpunpckhwd instrs.
17170 if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
17171 !Subtarget.hasAVX512())
17172 return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17173 Subtarget, DAG);
17174
17175 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17176 Zeroable, Subtarget, DAG))
17177 return Blend;
17178
17179 // Check for being able to broadcast a single element.
17180 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17181 Subtarget, DAG))
17182 return Broadcast;
17183
17184 // Try to use shift instructions if fast.
17185 if (Subtarget.preferLowerShuffleAsShift()) {
17186 if (SDValue Shift =
17187 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
17188 Subtarget, DAG, /*BitwiseOnly*/ true))
17189 return Shift;
17190 if (NumV2Elements == 0)
17191 if (SDValue Rotate =
17192 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17193 return Rotate;
17194 }
17195
17196 // If the shuffle mask is repeated in each 128-bit lane we can use more
17197 // efficient instructions that mirror the shuffles across the two 128-bit
17198 // lanes.
17199 SmallVector<int, 4> RepeatedMask;
17200 bool Is128BitLaneRepeatedShuffle =
17201 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17202 if (Is128BitLaneRepeatedShuffle) {
17203 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17204 if (V2.isUndef())
17205 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17206 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17207
17208 // Use dedicated unpack instructions for masks that match their pattern.
17209 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, V1, V2, Mask, DAG))
17210 return V;
17211 }
17212
17213 // Try to use shift instructions.
17214 if (SDValue Shift =
17215 lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
17216 DAG, /*BitwiseOnly*/ false))
17217 return Shift;
17218
17219 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
17220 if (SDValue Rotate =
17221 lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
17222 return Rotate;
17223
17224 // If we have VLX support, we can use VALIGN or EXPAND.
17225 if (Subtarget.hasVLX()) {
17226 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17227 Zeroable, Subtarget, DAG))
17228 return Rotate;
17229
17230 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i32, V1, V2, Mask,
17231 Zeroable, Subtarget, DAG))
17232 return V;
17233 }
17234
17235 // Try to use byte rotation instructions.
17236 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17237 Subtarget, DAG))
17238 return Rotate;
17239
17240 // Try to create an in-lane repeating shuffle mask and then shuffle the
17241 // results into the target lanes.
17243 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17244 return V;
17245
17246 if (V2.isUndef()) {
17247 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17248 // because that should be faster than the variable permute alternatives.
17249 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, V1, V2, Mask, DAG))
17250 return V;
17251
17252 // If the shuffle patterns aren't repeated but it's a single input, directly
17253 // generate a cross-lane VPERMD instruction.
17254 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17255 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17256 }
17257
17258 // Assume that a single SHUFPS is faster than an alternative sequence of
17259 // multiple instructions (even if the CPU has a domain penalty).
17260 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17261 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17262 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17263 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17264 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17265 CastV1, CastV2, DAG);
17266 return DAG.getBitcast(MVT::v8i32, ShufPS);
17267 }
17268
17269 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17270 // shuffle.
17272 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17273 return Result;
17274
17275 // Otherwise fall back on generic blend lowering.
17276 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17277 Zeroable, Subtarget, DAG);
17278}
17279
17280/// Handle lowering of 16-lane 16-bit integer shuffles.
17281///
17282/// This routine is only called when we have AVX2 and thus a reasonable
17283/// instruction set for v16i16 shuffling..
17285 const APInt &Zeroable, SDValue V1, SDValue V2,
17286 const X86Subtarget &Subtarget,
17287 SelectionDAG &DAG) {
17288 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17289 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17290 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17291 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
17292
17293 // Whenever we can lower this as a zext, that instruction is strictly faster
17294 // than any alternative. It also allows us to fold memory operands into the
17295 // shuffle in many cases.
17297 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17298 return ZExt;
17299
17300 // Check for being able to broadcast a single element.
17301 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17302 Subtarget, DAG))
17303 return Broadcast;
17304
17305 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17306 Zeroable, Subtarget, DAG))
17307 return Blend;
17308
17309 // Use dedicated unpack instructions for masks that match their pattern.
17310 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, V1, V2, Mask, DAG))
17311 return V;
17312
17313 // Use dedicated pack instructions for masks that match their pattern.
17314 if (SDValue V =
17315 lowerShuffleWithPACK(DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17316 return V;
17317
17318 // Try to use lower using a truncation.
17319 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17320 Subtarget, DAG))
17321 return V;
17322
17323 // Try to use shift instructions.
17324 if (SDValue Shift =
17325 lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17326 Subtarget, DAG, /*BitwiseOnly*/ false))
17327 return Shift;
17328
17329 // Try to use byte rotation instructions.
17330 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17331 Subtarget, DAG))
17332 return Rotate;
17333
17334 // Try to create an in-lane repeating shuffle mask and then shuffle the
17335 // results into the target lanes.
17337 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17338 return V;
17339
17340 if (V2.isUndef()) {
17341 // Try to use bit rotation instructions.
17342 if (SDValue Rotate =
17343 lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17344 return Rotate;
17345
17346 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17347 // because that should be faster than the variable permute alternatives.
17348 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, V1, V2, Mask, DAG))
17349 return V;
17350
17351 // There are no generalized cross-lane shuffle operations available on i16
17352 // element types.
17353 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17355 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17356 return V;
17357
17358 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17359 DAG, Subtarget);
17360 }
17361
17362 SmallVector<int, 8> RepeatedMask;
17363 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17364 // As this is a single-input shuffle, the repeated mask should be
17365 // a strictly valid v8i16 mask that we can pass through to the v8i16
17366 // lowering to handle even the v16 case.
17368 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17369 }
17370 }
17371
17372 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17373 Zeroable, Subtarget, DAG))
17374 return PSHUFB;
17375
17376 // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17377 if (Subtarget.hasBWI())
17378 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17379
17380 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17381 // shuffle.
17383 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17384 return Result;
17385
17386 // Try to permute the lanes and then use a per-lane permute.
17388 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17389 return V;
17390
17391 // Try to match an interleave of two v16i16s and lower them as unpck and
17392 // permutes using ymms.
17393 if (!Subtarget.hasAVX512())
17394 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
17395 Mask, DAG))
17396 return V;
17397
17398 // Otherwise fall back on generic lowering.
17399 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17400 Subtarget, DAG);
17401}
17402
17403/// Handle lowering of 32-lane 8-bit integer shuffles.
17404///
17405/// This routine is only called when we have AVX2 and thus a reasonable
17406/// instruction set for v32i8 shuffling..
17408 const APInt &Zeroable, SDValue V1, SDValue V2,
17409 const X86Subtarget &Subtarget,
17410 SelectionDAG &DAG) {
17411 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17412 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17413 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17414 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
17415
17416 // Whenever we can lower this as a zext, that instruction is strictly faster
17417 // than any alternative. It also allows us to fold memory operands into the
17418 // shuffle in many cases.
17419 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17420 Zeroable, Subtarget, DAG))
17421 return ZExt;
17422
17423 // Check for being able to broadcast a single element.
17424 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17425 Subtarget, DAG))
17426 return Broadcast;
17427
17428 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17429 Zeroable, Subtarget, DAG))
17430 return Blend;
17431
17432 // Use dedicated unpack instructions for masks that match their pattern.
17433 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, V1, V2, Mask, DAG))
17434 return V;
17435
17436 // Use dedicated pack instructions for masks that match their pattern.
17437 if (SDValue V =
17438 lowerShuffleWithPACK(DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17439 return V;
17440
17441 // Try to use lower using a truncation.
17442 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17443 Subtarget, DAG))
17444 return V;
17445
17446 // Try to use shift instructions.
17447 if (SDValue Shift =
17448 lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
17449 DAG, /*BitwiseOnly*/ false))
17450 return Shift;
17451
17452 // Try to use byte rotation instructions.
17453 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17454 Subtarget, DAG))
17455 return Rotate;
17456
17457 // Try to use bit rotation instructions.
17458 if (V2.isUndef())
17459 if (SDValue Rotate =
17460 lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17461 return Rotate;
17462
17463 // Try to create an in-lane repeating shuffle mask and then shuffle the
17464 // results into the target lanes.
17466 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17467 return V;
17468
17469 // There are no generalized cross-lane shuffle operations available on i8
17470 // element types.
17471 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17472 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17473 // because that should be faster than the variable permute alternatives.
17474 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, V1, V2, Mask, DAG))
17475 return V;
17476
17478 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17479 return V;
17480
17481 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17482 DAG, Subtarget);
17483 }
17484
17485 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17486 Zeroable, Subtarget, DAG))
17487 return PSHUFB;
17488
17489 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17490 if (Subtarget.hasVBMI())
17491 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17492
17493 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17494 // shuffle.
17496 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17497 return Result;
17498
17499 // Try to permute the lanes and then use a per-lane permute.
17501 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17502 return V;
17503
17504 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17505 // by zeroable elements in the remaining 24 elements. Turn this into two
17506 // vmovqb instructions shuffled together.
17507 if (Subtarget.hasVLX())
17508 if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
17509 Mask, Zeroable, DAG))
17510 return V;
17511
17512 // Try to match an interleave of two v32i8s and lower them as unpck and
17513 // permutes using ymms.
17514 if (!Subtarget.hasAVX512())
17515 if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
17516 Mask, DAG))
17517 return V;
17518
17519 // Otherwise fall back on generic lowering.
17520 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17521 Subtarget, DAG);
17522}
17523
17524/// High-level routine to lower various 256-bit x86 vector shuffles.
17525///
17526/// This routine either breaks down the specific type of a 256-bit x86 vector
17527/// shuffle or splits it into two 128-bit shuffles and fuses the results back
17528/// together based on the available instructions.
17530 SDValue V1, SDValue V2, const APInt &Zeroable,
17531 const X86Subtarget &Subtarget,
17532 SelectionDAG &DAG) {
17533 // If we have a single input to the zero element, insert that into V1 if we
17534 // can do so cheaply.
17535 int NumElts = VT.getVectorNumElements();
17536 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17537
17538 if (NumV2Elements == 1 && Mask[0] >= NumElts)
17540 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17541 return Insertion;
17542
17543 // Handle special cases where the lower or upper half is UNDEF.
17544 if (SDValue V =
17545 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17546 return V;
17547
17548 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
17549 // can check for those subtargets here and avoid much of the subtarget
17550 // querying in the per-vector-type lowering routines. With AVX1 we have
17551 // essentially *zero* ability to manipulate a 256-bit vector with integer
17552 // types. Since we'll use floating point types there eventually, just
17553 // immediately cast everything to a float and operate entirely in that domain.
17554 if (VT.isInteger() && !Subtarget.hasAVX2()) {
17555 int ElementBits = VT.getScalarSizeInBits();
17556 if (ElementBits < 32) {
17557 // No floating point type available, if we can't use the bit operations
17558 // for masking/blending then decompose into 128-bit vectors.
17559 if (SDValue V =
17560 lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
17561 return V;
17562 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17563 return V;
17564 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17565 }
17566
17567 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
17569 V1 = DAG.getBitcast(FpVT, V1);
17570 V2 = DAG.getBitcast(FpVT, V2);
17571 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
17572 }
17573
17574 if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
17575 V1 = DAG.getBitcast(MVT::v16i16, V1);
17576 V2 = DAG.getBitcast(MVT::v16i16, V2);
17577 return DAG.getBitcast(VT,
17578 DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
17579 }
17580
17581 switch (VT.SimpleTy) {
17582 case MVT::v4f64:
17583 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17584 case MVT::v4i64:
17585 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17586 case MVT::v8f32:
17587 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17588 case MVT::v8i32:
17589 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17590 case MVT::v16i16:
17591 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17592 case MVT::v32i8:
17593 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17594
17595 default:
17596 llvm_unreachable("Not a valid 256-bit x86 vector type!");
17597 }
17598}
17599
17600/// Try to lower a vector shuffle as a 128-bit shuffles.
17602 const APInt &Zeroable, SDValue V1, SDValue V2,
17603 const X86Subtarget &Subtarget,
17604 SelectionDAG &DAG) {
17605 assert(VT.getScalarSizeInBits() == 64 &&
17606 "Unexpected element type size for 128bit shuffle.");
17607
17608 // To handle 256 bit vector requires VLX and most probably
17609 // function lowerV2X128VectorShuffle() is better solution.
17610 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
17611
17612 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17613 SmallVector<int, 4> Widened128Mask;
17614 if (!canWidenShuffleElements(Mask, Widened128Mask))
17615 return SDValue();
17616 assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
17617
17618 // Try to use an insert into a zero vector.
17619 if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17620 (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17621 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17622 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17623 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17624 DAG.getVectorIdxConstant(0, DL));
17625 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17626 getZeroVector(VT, Subtarget, DAG, DL), LoV,
17627 DAG.getVectorIdxConstant(0, DL));
17628 }
17629
17630 // Check for patterns which can be matched with a single insert of a 256-bit
17631 // subvector.
17632 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
17633 if (OnlyUsesV1 ||
17634 isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
17635 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17636 SDValue SubVec =
17637 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17638 DAG.getVectorIdxConstant(0, DL));
17639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17640 DAG.getVectorIdxConstant(4, DL));
17641 }
17642
17643 // See if this is an insertion of the lower 128-bits of V2 into V1.
17644 bool IsInsert = true;
17645 int V2Index = -1;
17646 for (int i = 0; i < 4; ++i) {
17647 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17648 if (Widened128Mask[i] < 0)
17649 continue;
17650
17651 // Make sure all V1 subvectors are in place.
17652 if (Widened128Mask[i] < 4) {
17653 if (Widened128Mask[i] != i) {
17654 IsInsert = false;
17655 break;
17656 }
17657 } else {
17658 // Make sure we only have a single V2 index and its the lowest 128-bits.
17659 if (V2Index >= 0 || Widened128Mask[i] != 4) {
17660 IsInsert = false;
17661 break;
17662 }
17663 V2Index = i;
17664 }
17665 }
17666 if (IsInsert && V2Index >= 0) {
17667 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17668 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17669 DAG.getVectorIdxConstant(0, DL));
17670 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17671 }
17672
17673 // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17674 // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17675 // possible we at least ensure the lanes stay sequential to help later
17676 // combines.
17677 SmallVector<int, 2> Widened256Mask;
17678 if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17679 Widened128Mask.clear();
17680 narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17681 }
17682
17683 // Try to lower to vshuf64x2/vshuf32x4.
17684 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17685 int PermMask[4] = {-1, -1, -1, -1};
17686 // Ensure elements came from the same Op.
17687 for (int i = 0; i < 4; ++i) {
17688 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17689 if (Widened128Mask[i] < 0)
17690 continue;
17691
17692 SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17693 unsigned OpIndex = i / 2;
17694 if (Ops[OpIndex].isUndef())
17695 Ops[OpIndex] = Op;
17696 else if (Ops[OpIndex] != Op)
17697 return SDValue();
17698
17699 PermMask[i] = Widened128Mask[i] % 4;
17700 }
17701
17702 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17703 getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
17704}
17705
17706/// Handle lowering of 8-lane 64-bit floating point shuffles.
17708 const APInt &Zeroable, SDValue V1, SDValue V2,
17709 const X86Subtarget &Subtarget,
17710 SelectionDAG &DAG) {
17711 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17712 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17713 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17714
17715 if (V2.isUndef()) {
17716 // Use low duplicate instructions for masks that match their pattern.
17717 if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
17718 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17719
17720 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17721 // Non-half-crossing single input shuffles can be lowered with an
17722 // interleaved permutation.
17723 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17724 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17725 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17726 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17727 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17728 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17729 }
17730
17731 SmallVector<int, 4> RepeatedMask;
17732 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17733 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17734 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17735 }
17736
17737 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17738 V2, Subtarget, DAG))
17739 return Shuf128;
17740
17741 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, V1, V2, Mask, DAG))
17742 return Unpck;
17743
17744 // Check if the blend happens to exactly fit that of SHUFPD.
17745 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17746 Zeroable, Subtarget, DAG))
17747 return Op;
17748
17749 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8f64, V1, V2, Mask, Zeroable,
17750 Subtarget, DAG))
17751 return V;
17752
17753 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17754 Zeroable, Subtarget, DAG))
17755 return Blend;
17756
17757 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPD which
17758 // requires an extra register for the index vector; VALIGNQ uses an immediate.
17759 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8f64, V1, V2, Mask,
17760 Zeroable, Subtarget, DAG))
17761 return Rotate;
17762
17763 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17764}
17765
17766/// Handle lowering of 16-lane 32-bit floating point shuffles.
17768 const APInt &Zeroable, SDValue V1, SDValue V2,
17769 const X86Subtarget &Subtarget,
17770 SelectionDAG &DAG) {
17771 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17772 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17773 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17774
17775 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17776 // options to efficiently lower the shuffle.
17777 SmallVector<int, 4> RepeatedMask;
17778 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17779 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17780
17781 // Use even/odd duplicate instructions for masks that match their pattern.
17782 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17783 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17784 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17785 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17786
17787 if (V2.isUndef())
17788 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17789 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17790
17791 // Use dedicated unpack instructions for masks that match their pattern.
17792 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, V1, V2, Mask, DAG))
17793 return V;
17794
17795 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17796 Zeroable, Subtarget, DAG))
17797 return Blend;
17798
17799 // Otherwise, fall back to a SHUFPS sequence.
17800 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17801 }
17802
17803 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17804 Zeroable, Subtarget, DAG))
17805 return Blend;
17806
17808 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17809 return DAG.getBitcast(MVT::v16f32, ZExt);
17810
17811 // Try to create an in-lane repeating shuffle mask and then shuffle the
17812 // results into the target lanes.
17814 DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17815 return V;
17816
17817 // If we have a single input shuffle with different shuffle patterns in the
17818 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17819 if (V2.isUndef() &&
17820 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17821 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17822 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17823 }
17824
17825 // If we have AVX512F support, we can use VEXPAND.
17826 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16f32, V1, V2, Mask,
17827 Zeroable, Subtarget, DAG))
17828 return V;
17829
17830 // Try to use VALIGN via integer domain bitcast. Avoids VPERMPS which
17831 // requires an extra register for the index vector; VALIGND uses an immediate.
17832 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16f32, V1, V2, Mask,
17833 Zeroable, Subtarget, DAG))
17834 return Rotate;
17835
17836 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17837}
17838
17839/// Handle lowering of 8-lane 64-bit integer shuffles.
17841 const APInt &Zeroable, SDValue V1, SDValue V2,
17842 const X86Subtarget &Subtarget,
17843 SelectionDAG &DAG) {
17844 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17845 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17846 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17847
17848 // Try to use shift instructions if fast.
17849 if (Subtarget.preferLowerShuffleAsShift())
17850 if (SDValue Shift =
17851 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17852 Subtarget, DAG, /*BitwiseOnly*/ true))
17853 return Shift;
17854
17855 if (V2.isUndef()) {
17856 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17857 // can use lower latency instructions that will operate on all four
17858 // 128-bit lanes.
17859 SmallVector<int, 2> Repeated128Mask;
17860 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17861 SmallVector<int, 4> PSHUFDMask;
17862 narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17863 return DAG.getBitcast(
17864 MVT::v8i64,
17865 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17866 DAG.getBitcast(MVT::v16i32, V1),
17867 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17868 }
17869
17870 SmallVector<int, 4> Repeated256Mask;
17871 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17872 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17873 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17874 }
17875
17876 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17877 V2, Subtarget, DAG))
17878 return Shuf128;
17879
17880 // Try to use shift instructions.
17881 if (SDValue Shift =
17882 lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
17883 DAG, /*BitwiseOnly*/ false))
17884 return Shift;
17885
17886 // Try to use VALIGN.
17887 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17888 Zeroable, Subtarget, DAG))
17889 return Rotate;
17890
17891 // Try to use PALIGNR.
17892 if (Subtarget.hasBWI())
17893 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17894 Subtarget, DAG))
17895 return Rotate;
17896
17897 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, V1, V2, Mask, DAG))
17898 return Unpck;
17899
17900 // If we have AVX512F support, we can use VEXPAND.
17901 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
17902 Subtarget, DAG))
17903 return V;
17904
17905 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17906 Zeroable, Subtarget, DAG))
17907 return Blend;
17908
17909 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17910}
17911
17912/// Handle lowering of 16-lane 32-bit integer shuffles.
17914 const APInt &Zeroable, SDValue V1, SDValue V2,
17915 const X86Subtarget &Subtarget,
17916 SelectionDAG &DAG) {
17917 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17918 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17919 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17920
17921 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
17922
17923 // Whenever we can lower this as a zext, that instruction is strictly faster
17924 // than any alternative. It also allows us to fold memory operands into the
17925 // shuffle in many cases.
17927 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17928 return ZExt;
17929
17930 // Try to use shift instructions if fast.
17931 if (Subtarget.preferLowerShuffleAsShift()) {
17932 if (SDValue Shift =
17933 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17934 Subtarget, DAG, /*BitwiseOnly*/ true))
17935 return Shift;
17936 if (NumV2Elements == 0)
17937 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
17938 Subtarget, DAG))
17939 return Rotate;
17940 }
17941
17942 // If the shuffle mask is repeated in each 128-bit lane we can use more
17943 // efficient instructions that mirror the shuffles across the four 128-bit
17944 // lanes.
17945 SmallVector<int, 4> RepeatedMask;
17946 bool Is128BitLaneRepeatedShuffle =
17947 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17948 if (Is128BitLaneRepeatedShuffle) {
17949 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17950 if (V2.isUndef())
17951 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17952 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17953
17954 // Use dedicated unpack instructions for masks that match their pattern.
17955 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, V1, V2, Mask, DAG))
17956 return V;
17957 }
17958
17959 // Try to use shift instructions.
17960 if (SDValue Shift =
17961 lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
17962 Subtarget, DAG, /*BitwiseOnly*/ false))
17963 return Shift;
17964
17965 if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
17966 if (SDValue Rotate =
17967 lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
17968 return Rotate;
17969
17970 // Try to use VALIGN.
17971 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17972 Zeroable, Subtarget, DAG))
17973 return Rotate;
17974
17975 // Try to use byte rotation instructions.
17976 if (Subtarget.hasBWI())
17977 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17978 Subtarget, DAG))
17979 return Rotate;
17980
17981 // Assume that a single SHUFPS is faster than using a permv shuffle.
17982 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17983 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17984 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
17985 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
17986 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
17987 CastV1, CastV2, DAG);
17988 return DAG.getBitcast(MVT::v16i32, ShufPS);
17989 }
17990
17991 // Try to create an in-lane repeating shuffle mask and then shuffle the
17992 // results into the target lanes.
17994 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
17995 return V;
17996
17997 // If we have AVX512F support, we can use VEXPAND.
17998 if (SDValue V = lowerShuffleWithEXPAND(DL, MVT::v16i32, V1, V2, Mask,
17999 Zeroable, Subtarget, DAG))
18000 return V;
18001
18002 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
18003 Zeroable, Subtarget, DAG))
18004 return Blend;
18005
18006 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
18007}
18008
18009/// Handle lowering of 32-lane 16-bit integer shuffles.
18011 const APInt &Zeroable, SDValue V1, SDValue V2,
18012 const X86Subtarget &Subtarget,
18013 SelectionDAG &DAG) {
18014 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18015 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
18016 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
18017 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
18018
18019 // Whenever we can lower this as a zext, that instruction is strictly faster
18020 // than any alternative. It also allows us to fold memory operands into the
18021 // shuffle in many cases.
18023 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
18024 return ZExt;
18025
18026 // Use dedicated unpack instructions for masks that match their pattern.
18027 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, V1, V2, Mask, DAG))
18028 return V;
18029
18030 // Use dedicated pack instructions for masks that match their pattern.
18031 if (SDValue V =
18032 lowerShuffleWithPACK(DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18033 return V;
18034
18035 // Try to use shift instructions.
18036 if (SDValue Shift =
18037 lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
18038 Subtarget, DAG, /*BitwiseOnly*/ false))
18039 return Shift;
18040
18041 // Try to use byte rotation instructions.
18042 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
18043 Subtarget, DAG))
18044 return Rotate;
18045
18046 if (V2.isUndef()) {
18047 // Try to use bit rotation instructions.
18048 if (SDValue Rotate =
18049 lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
18050 return Rotate;
18051
18052 SmallVector<int, 8> RepeatedMask;
18053 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
18054 // As this is a single-input shuffle, the repeated mask should be
18055 // a strictly valid v8i16 mask that we can pass through to the v8i16
18056 // lowering to handle even the v32 case.
18057 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
18058 RepeatedMask, Subtarget, DAG);
18059 }
18060 }
18061
18062 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
18063 Zeroable, Subtarget, DAG))
18064 return Blend;
18065
18066 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18067 Zeroable, Subtarget, DAG))
18068 return PSHUFB;
18069
18070 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18071 // shuffle.
18073 DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
18074 return Result;
18075
18076 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18077}
18078
18079/// Handle lowering of 64-lane 8-bit integer shuffles.
18081 const APInt &Zeroable, SDValue V1, SDValue V2,
18082 const X86Subtarget &Subtarget,
18083 SelectionDAG &DAG) {
18084 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18085 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
18086 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
18087 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
18088
18089 // Whenever we can lower this as a zext, that instruction is strictly faster
18090 // than any alternative. It also allows us to fold memory operands into the
18091 // shuffle in many cases.
18093 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18094 return ZExt;
18095
18096 // Use dedicated unpack instructions for masks that match their pattern.
18097 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, V1, V2, Mask, DAG))
18098 return V;
18099
18100 // Use dedicated pack instructions for masks that match their pattern.
18101 if (SDValue V =
18102 lowerShuffleWithPACK(DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18103 return V;
18104
18105 // Try to use shift instructions.
18106 if (SDValue Shift =
18107 lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
18108 DAG, /*BitwiseOnly*/ false))
18109 return Shift;
18110
18111 // Try to use byte rotation instructions.
18112 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18113 Subtarget, DAG))
18114 return Rotate;
18115
18116 // Try to use bit rotation instructions.
18117 if (V2.isUndef())
18118 if (SDValue Rotate =
18119 lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18120 return Rotate;
18121
18122 // Lower as AND if possible.
18123 if (SDValue Masked =
18124 lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask, Zeroable, DAG))
18125 return Masked;
18126
18127 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18128 Zeroable, Subtarget, DAG))
18129 return PSHUFB;
18130
18131 // Try to create an in-lane repeating shuffle mask and then shuffle the
18132 // results into the target lanes.
18133 // FIXME: Avoid on VBMI targets as the post lane permute often interferes
18134 // with shuffle combining (should be fixed by topological DAG sorting).
18135 if (!Subtarget.hasVBMI())
18137 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18138 return V;
18139
18141 DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
18142 return Result;
18143
18144 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18145 Zeroable, Subtarget, DAG))
18146 return Blend;
18147
18148 if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
18149 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
18150 // PALIGNR will be cheaper than the second PSHUFB+OR.
18151 if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
18152 Mask, Subtarget, DAG))
18153 return V;
18154
18155 // VBMI can use VPERMV/VPERMV3 byte shuffles more efficiently than
18156 // OR(PSHUFB,PSHUFB).
18157 if (Subtarget.hasVBMI())
18158 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget,
18159 DAG);
18160
18161 // If we can't directly blend but can use PSHUFB, that will be better as it
18162 // can both shuffle and set up the inefficient blend.
18163 bool V1InUse, V2InUse;
18164 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
18165 DAG, V1InUse, V2InUse);
18166 }
18167
18168 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18169 // shuffle.
18171 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18172 return Result;
18173
18174 // VBMI can use VPERMV/VPERMV3 byte shuffles.
18175 if (Subtarget.hasVBMI())
18176 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18177
18178 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG,
18179 /*SimpleOnly*/ false);
18180}
18181
18182/// High-level routine to lower various 512-bit x86 vector shuffles.
18183///
18184/// This routine either breaks down the specific type of a 512-bit x86 vector
18185/// shuffle or splits it into two 256-bit shuffles and fuses the results back
18186/// together based on the available instructions.
18188 MVT VT, SDValue V1, SDValue V2,
18189 const APInt &Zeroable,
18190 const X86Subtarget &Subtarget,
18191 SelectionDAG &DAG) {
18192 assert(Subtarget.hasAVX512() &&
18193 "Cannot lower 512-bit vectors w/ basic ISA!");
18194
18195 // If we have a single input to the zero element, insert that into V1 if we
18196 // can do so cheaply.
18197 int NumElts = Mask.size();
18198 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18199
18200 if (NumV2Elements == 1 && Mask[0] >= NumElts)
18202 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18203 return Insertion;
18204
18205 // Handle special cases where the lower or upper half is UNDEF.
18206 if (SDValue V =
18207 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18208 return V;
18209
18210 // Check for being able to broadcast a single element.
18211 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
18212 Subtarget, DAG))
18213 return Broadcast;
18214
18215 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
18216 // Try using bit ops for masking and blending before falling back to
18217 // splitting.
18218 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable, DAG))
18219 return V;
18220 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18221 return V;
18222
18223 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
18224 }
18225
18226 if (VT == MVT::v32f16 || VT == MVT::v32bf16) {
18227 if (!Subtarget.hasBWI())
18228 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
18229 /*SimpleOnly*/ false);
18230
18231 V1 = DAG.getBitcast(MVT::v32i16, V1);
18232 V2 = DAG.getBitcast(MVT::v32i16, V2);
18233 return DAG.getBitcast(VT,
18234 DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
18235 }
18236
18237 // Dispatch to each element type for lowering. If we don't have support for
18238 // specific element type shuffles at 512 bits, immediately split them and
18239 // lower them. Each lowering routine of a given type is allowed to assume that
18240 // the requisite ISA extensions for that element type are available.
18241 switch (VT.SimpleTy) {
18242 case MVT::v8f64:
18243 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18244 case MVT::v16f32:
18245 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18246 case MVT::v8i64:
18247 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18248 case MVT::v16i32:
18249 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18250 case MVT::v32i16:
18251 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18252 case MVT::v64i8:
18253 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18254
18255 default:
18256 llvm_unreachable("Not a valid 512-bit x86 vector type!");
18257 }
18258}
18259
18261 MVT VT, SDValue V1, SDValue V2,
18262 const X86Subtarget &Subtarget,
18263 SelectionDAG &DAG) {
18264 // Shuffle should be unary.
18265 if (!V2.isUndef())
18266 return SDValue();
18267
18268 int ShiftAmt = -1;
18269 int NumElts = Mask.size();
18270 for (int i = 0; i != NumElts; ++i) {
18271 int M = Mask[i];
18272 assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
18273 "Unexpected mask index.");
18274 if (M < 0)
18275 continue;
18276
18277 // The first non-undef element determines our shift amount.
18278 if (ShiftAmt < 0) {
18279 ShiftAmt = M - i;
18280 // Need to be shifting right.
18281 if (ShiftAmt <= 0)
18282 return SDValue();
18283 }
18284 // All non-undef elements must shift by the same amount.
18285 if (ShiftAmt != M - i)
18286 return SDValue();
18287 }
18288 assert(ShiftAmt >= 0 && "All undef?");
18289
18290 // Great we found a shift right.
18291 SDValue Res = widenMaskVector(V1, false, Subtarget, DAG, DL);
18292 Res = DAG.getNode(X86ISD::KSHIFTR, DL, Res.getValueType(), Res,
18293 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18294 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18295 DAG.getVectorIdxConstant(0, DL));
18296}
18297
18298// Determine if this shuffle can be implemented with a KSHIFT instruction.
18299// Returns the shift amount if possible or -1 if not. This is a simplified
18300// version of matchShuffleAsShift.
18301static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18302 int MaskOffset, const APInt &Zeroable) {
18303 int Size = Mask.size();
18304
18305 auto CheckZeros = [&](int Shift, bool Left) {
18306 for (int j = 0; j < Shift; ++j)
18307 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18308 return false;
18309
18310 return true;
18311 };
18312
18313 auto MatchShift = [&](int Shift, bool Left) {
18314 unsigned Pos = Left ? Shift : 0;
18315 unsigned Low = Left ? 0 : Shift;
18316 unsigned Len = Size - Shift;
18317 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18318 };
18319
18320 for (int Shift = 1; Shift != Size; ++Shift)
18321 for (bool Left : {true, false})
18322 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18323 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18324 return Shift;
18325 }
18326
18327 return -1;
18328}
18329
18330
18331// Lower vXi1 vector shuffles.
18332// There is no a dedicated instruction on AVX-512 that shuffles the masks.
18333// The only way to shuffle bits is to sign-extend the mask vector to SIMD
18334// vector, shuffle and then truncate it back.
18336 MVT VT, SDValue V1, SDValue V2,
18337 const APInt &Zeroable,
18338 const X86Subtarget &Subtarget,
18339 SelectionDAG &DAG) {
18340 assert(Subtarget.hasAVX512() &&
18341 "Cannot lower 512-bit vectors w/o basic ISA!");
18342
18343 int NumElts = Mask.size();
18344 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18345
18346 // Try to recognize shuffles that are just padding a subvector with zeros.
18347 int SubvecElts = 0;
18348 int Src = -1;
18349 for (int i = 0; i != NumElts; ++i) {
18350 if (Mask[i] >= 0) {
18351 // Grab the source from the first valid mask. All subsequent elements need
18352 // to use this same source.
18353 if (Src < 0)
18354 Src = Mask[i] / NumElts;
18355 if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18356 break;
18357 }
18358
18359 ++SubvecElts;
18360 }
18361 assert(SubvecElts != NumElts && "Identity shuffle?");
18362
18363 // Clip to a power 2.
18364 SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
18365
18366 // Make sure the number of zeroable bits in the top at least covers the bits
18367 // not covered by the subvector.
18368 if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
18369 assert(Src >= 0 && "Expected a source!");
18370 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18371 SDValue Extract =
18372 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, Src == 0 ? V1 : V2,
18373 DAG.getVectorIdxConstant(0, DL));
18374 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18375 DAG.getConstant(0, DL, VT), Extract,
18376 DAG.getVectorIdxConstant(0, DL));
18377 }
18378
18379 // Try a simple shift right with undef elements. Later we'll try with zeros.
18380 if (SDValue Shift =
18381 lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget, DAG))
18382 return Shift;
18383
18384 // Try to match KSHIFTs.
18385 unsigned Offset = 0;
18386 for (SDValue V : {V1, V2}) {
18387 unsigned Opcode;
18388 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18389 if (ShiftAmt >= 0) {
18390 SDValue Res = widenMaskVector(V, false, Subtarget, DAG, DL);
18391 MVT WideVT = Res.getSimpleValueType();
18392 // Widened right shifts need two shifts to ensure we shift in zeroes.
18393 if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18394 int WideElts = WideVT.getVectorNumElements();
18395 // Shift left to put the original vector in the MSBs of the new size.
18396 Res =
18397 DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18398 DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18399 // Increase the shift amount to account for the left shift.
18400 ShiftAmt += WideElts - NumElts;
18401 }
18402
18403 Res = DAG.getNode(Opcode, DL, WideVT, Res,
18404 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18405 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18406 DAG.getVectorIdxConstant(0, DL));
18407 }
18408 Offset += NumElts; // Increment for next iteration.
18409 }
18410
18411 // If we're performing an unary shuffle on a SETCC result, try to shuffle the
18412 // ops instead.
18413 // TODO: What other unary shuffles would benefit from this?
18414 if (NumV2Elements == 0 && V1.getOpcode() == ISD::SETCC && V1->hasOneUse()) {
18415 SDValue Op0 = V1.getOperand(0);
18416 SDValue Op1 = V1.getOperand(1);
18417 ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
18418 EVT OpVT = Op0.getValueType();
18419 if (OpVT.getScalarSizeInBits() >= 32 || isBroadcastShuffleMask(Mask))
18420 return DAG.getSetCC(
18421 DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
18422 DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
18423 }
18424
18425 // If this is a sequential shuffle with zero'd elements - then lower to AND.
18426 bool IsBlendWithZero = all_of(enumerate(Mask), [&Zeroable](auto M) {
18427 return Zeroable[M.index()] || (M.value() == (int)M.index());
18428 });
18429 if (IsBlendWithZero) {
18430 const unsigned Width = std::max<unsigned>(NumElts, 8u);
18431 MVT IntVT = MVT::getIntegerVT(Width);
18432
18433 APInt MaskValue = (~Zeroable).zextOrTrunc(Width);
18434 SDValue MaskNode = DAG.getConstant(MaskValue, DL, IntVT);
18435
18436 MVT MaskVecVT = MVT::getVectorVT(MVT::i1, Width);
18437 SDValue MaskVecNode = DAG.getBitcast(MaskVecVT, MaskNode);
18438
18439 SDValue MaskVec = DAG.getExtractSubvector(DL, VT, MaskVecNode, 0);
18440 return DAG.getNode(ISD::AND, DL, VT, V1, MaskVec);
18441 }
18442
18443 MVT ExtVT;
18444 switch (VT.SimpleTy) {
18445 default:
18446 llvm_unreachable("Expected a vector of i1 elements");
18447 case MVT::v2i1:
18448 ExtVT = MVT::v2i64;
18449 break;
18450 case MVT::v4i1:
18451 ExtVT = MVT::v4i32;
18452 break;
18453 case MVT::v8i1:
18454 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18455 // shuffle.
18456 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18457 break;
18458 case MVT::v16i1:
18459 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18460 // 256-bit operation available.
18461 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18462 break;
18463 case MVT::v32i1:
18464 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18465 // 256-bit operation available.
18466 assert(Subtarget.hasBWI() && "Expected AVX512BW support");
18467 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18468 break;
18469 case MVT::v64i1:
18470 // Fall back to scalarization. FIXME: We can do better if the shuffle
18471 // can be partitioned cleanly.
18472 if (!Subtarget.useBWIRegs())
18473 return SDValue();
18474 ExtVT = MVT::v64i8;
18475 break;
18476 }
18477
18478 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18479 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18480
18481 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18482 // i1 was sign extended we can use X86ISD::CVT2MASK.
18483 int NumElems = VT.getVectorNumElements();
18484 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18485 (Subtarget.hasDQI() && (NumElems < 32)))
18486 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18487 Shuffle, ISD::SETGT);
18488
18489 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18490}
18491
18492/// Helper function that returns true if the shuffle mask should be
18493/// commuted to improve canonicalization.
18495 int NumElements = Mask.size();
18496
18497 int NumV1Elements = 0, NumV2Elements = 0;
18498 for (int M : Mask)
18499 if (M < 0)
18500 continue;
18501 else if (M < NumElements)
18502 ++NumV1Elements;
18503 else
18504 ++NumV2Elements;
18505
18506 // Commute the shuffle as needed such that more elements come from V1 than
18507 // V2. This allows us to match the shuffle pattern strictly on how many
18508 // elements come from V1 without handling the symmetric cases.
18509 if (NumV2Elements > NumV1Elements)
18510 return true;
18511
18512 assert(NumV1Elements > 0 && "No V1 indices");
18513
18514 if (NumV2Elements == 0)
18515 return false;
18516
18517 // When the number of V1 and V2 elements are the same, try to minimize the
18518 // number of uses of V2 in the low half of the vector. When that is tied,
18519 // ensure that the sum of indices for V1 is equal to or lower than the sum
18520 // indices for V2. When those are equal, try to ensure that the number of odd
18521 // indices for V1 is lower than the number of odd indices for V2.
18522 if (NumV1Elements == NumV2Elements) {
18523 int LowV1Elements = 0, LowV2Elements = 0;
18524 for (int M : Mask.slice(0, NumElements / 2))
18525 if (M >= NumElements)
18526 ++LowV2Elements;
18527 else if (M >= 0)
18528 ++LowV1Elements;
18529 if (LowV2Elements > LowV1Elements)
18530 return true;
18531 if (LowV2Elements == LowV1Elements) {
18532 int SumV1Indices = 0, SumV2Indices = 0;
18533 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18534 if (Mask[i] >= NumElements)
18535 SumV2Indices += i;
18536 else if (Mask[i] >= 0)
18537 SumV1Indices += i;
18538 if (SumV2Indices < SumV1Indices)
18539 return true;
18540 if (SumV2Indices == SumV1Indices) {
18541 int NumV1OddIndices = 0, NumV2OddIndices = 0;
18542 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18543 if (Mask[i] >= NumElements)
18544 NumV2OddIndices += i % 2;
18545 else if (Mask[i] >= 0)
18546 NumV1OddIndices += i % 2;
18547 if (NumV2OddIndices < NumV1OddIndices)
18548 return true;
18549 }
18550 }
18551 }
18552
18553 return false;
18554}
18555
18557 const X86Subtarget &Subtarget) {
18558 if (!Subtarget.hasAVX512())
18559 return false;
18560
18561 if (!V.getValueType().isSimple())
18562 return false;
18563
18564 MVT VT = V.getSimpleValueType().getScalarType();
18565 if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
18566 return false;
18567
18568 // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
18569 // are preferable to blendw/blendvb/masked-mov.
18570 if ((VT == MVT::i16 || VT == MVT::i8) &&
18571 V.getSimpleValueType().getSizeInBits() < 512)
18572 return false;
18573
18574 auto HasMaskOperation = [&](SDValue V) {
18575 // TODO: Currently we only check limited opcode. We probably extend
18576 // it to all binary operation by checking TLI.isBinOp().
18577 switch (V->getOpcode()) {
18578 default:
18579 return false;
18580 case ISD::ADD:
18581 case ISD::SUB:
18582 case ISD::AND:
18583 case ISD::XOR:
18584 case ISD::OR:
18585 case ISD::SMAX:
18586 case ISD::SMIN:
18587 case ISD::UMAX:
18588 case ISD::UMIN:
18589 case ISD::ABS:
18590 case ISD::SHL:
18591 case ISD::SRL:
18592 case ISD::SRA:
18593 case ISD::MUL:
18594 break;
18595 }
18596 if (!V->hasOneUse())
18597 return false;
18598
18599 return true;
18600 };
18601
18602 if (HasMaskOperation(V))
18603 return true;
18604
18605 return false;
18606}
18607
18608// Forward declaration.
18611 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
18612 const X86Subtarget &Subtarget);
18613
18614 /// Top-level lowering for x86 vector shuffles.
18615///
18616/// This handles decomposition, canonicalization, and lowering of all x86
18617/// vector shuffles. Most of the specific lowering strategies are encapsulated
18618/// above in helper routines. The canonicalization attempts to widen shuffles
18619/// to involve fewer lanes of wider elements, consolidate symmetric patterns
18620/// s.t. only one of the two inputs needs to be tested, etc.
18622 SelectionDAG &DAG) {
18624 ArrayRef<int> OrigMask = SVOp->getMask();
18625 SDValue V1 = Op.getOperand(0);
18626 SDValue V2 = Op.getOperand(1);
18627 MVT VT = Op.getSimpleValueType();
18628 int NumElements = VT.getVectorNumElements();
18629 SDLoc DL(Op);
18630 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18631
18632 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
18633 "Can't lower MMX shuffles");
18634
18635 bool V1IsUndef = V1.isUndef();
18636 bool V2IsUndef = V2.isUndef();
18637 if (V1IsUndef && V2IsUndef)
18638 return DAG.getUNDEF(VT);
18639
18640 // When we create a shuffle node we put the UNDEF node to second operand,
18641 // but in some cases the first operand may be transformed to UNDEF.
18642 // In this case we should just commute the node.
18643 if (V1IsUndef)
18644 return DAG.getCommutedVectorShuffle(*SVOp);
18645
18646 // Check for non-undef masks pointing at an undef vector and make the masks
18647 // undef as well. This makes it easier to match the shuffle based solely on
18648 // the mask.
18649 if (V2IsUndef &&
18650 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18651 SmallVector<int, 8> NewMask(OrigMask);
18652 for (int &M : NewMask)
18653 if (M >= NumElements)
18654 M = -1;
18655 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18656 }
18657
18658 // Check for illegal shuffle mask element index values.
18659 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18660 (void)MaskUpperLimit;
18661 assert(llvm::all_of(OrigMask,
18662 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
18663 "Out of bounds shuffle index");
18664
18665 // We actually see shuffles that are entirely re-arrangements of a set of
18666 // zero inputs. This mostly happens while decomposing complex shuffles into
18667 // simple ones. Directly lower these as a buildvector of zeros.
18668 APInt KnownUndef, KnownZero;
18669 computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
18670
18671 APInt Zeroable = KnownUndef | KnownZero;
18672 if (Zeroable.isAllOnes())
18673 return getZeroVector(VT, Subtarget, DAG, DL);
18674
18675 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
18676
18677 // Try to collapse shuffles into using a vector type with fewer elements but
18678 // wider element types. We cap this to not form integers or floating point
18679 // elements wider than 64 bits. It does not seem beneficial to form i128
18680 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
18681 SmallVector<int, 16> WidenedMask;
18682 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
18683 !canCombineAsMaskOperation(V1, Subtarget) &&
18684 !canCombineAsMaskOperation(V2, Subtarget) &&
18685 canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
18686 // Shuffle mask widening should not interfere with a broadcast opportunity
18687 // by obfuscating the operands with bitcasts.
18688 // TODO: Avoid lowering directly from this top-level function: make this
18689 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
18690 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
18691 Subtarget, DAG))
18692 return Broadcast;
18693
18694 MVT NewEltVT = VT.isFloatingPoint()
18697 int NewNumElts = NumElements / 2;
18698 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
18699 // Make sure that the new vector type is legal. For example, v2f64 isn't
18700 // legal on SSE1.
18701 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
18702 if (V2IsZero) {
18703 // Modify the new Mask to take all zeros from the all-zero vector.
18704 // Choose indices that are blend-friendly.
18705 bool UsedZeroVector = false;
18706 assert(is_contained(WidenedMask, SM_SentinelZero) &&
18707 "V2's non-undef elements are used?!");
18708 for (int i = 0; i != NewNumElts; ++i)
18709 if (WidenedMask[i] == SM_SentinelZero) {
18710 WidenedMask[i] = i + NewNumElts;
18711 UsedZeroVector = true;
18712 }
18713 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
18714 // some elements to be undef.
18715 if (UsedZeroVector)
18716 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
18717 }
18718 V1 = DAG.getBitcast(NewVT, V1);
18719 V2 = DAG.getBitcast(NewVT, V2);
18720 return DAG.getBitcast(
18721 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
18722 }
18723 }
18724
18725 SmallVector<SDValue> Ops = {V1, V2};
18726 SmallVector<int> Mask(OrigMask);
18727
18728 // Canonicalize the shuffle with any horizontal ops inputs.
18729 // Don't attempt this if the shuffle can still be widened as we may lose
18730 // whole lane shuffle patterns.
18731 // NOTE: This may update Ops and Mask.
18732 if (!canWidenShuffleElements(Mask)) {
18734 Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
18735 return DAG.getBitcast(VT, HOp);
18736
18737 V1 = DAG.getBitcast(VT, Ops[0]);
18738 V2 = DAG.getBitcast(VT, Ops[1]);
18739 assert(NumElements == (int)Mask.size() &&
18740 "canonicalizeShuffleMaskWithHorizOp "
18741 "shouldn't alter the shuffle mask size");
18742 }
18743
18744 // Canonicalize zeros/ones/fp splat constants to ensure no undefs.
18745 // These will be materialized uniformly anyway, so make splat matching easier.
18746 // TODO: Allow all int constants?
18747 auto CanonicalizeConstant = [VT, &DL, &DAG](SDValue V) {
18748 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
18749 BitVector Undefs;
18750 if (SDValue Splat = BV->getSplatValue(&Undefs)) {
18751 if (Undefs.any() &&
18754 V = DAG.getBitcast(VT, DAG.getSplat(BV->getValueType(0), DL, Splat));
18755 }
18756 }
18757 }
18758 return V;
18759 };
18760 V1 = CanonicalizeConstant(V1);
18761 V2 = CanonicalizeConstant(V2);
18762
18763 // Commute the shuffle if it will improve canonicalization.
18766 std::swap(V1, V2);
18767 }
18768
18769 // For each vector width, delegate to a specialized lowering routine.
18770 if (VT.is128BitVector())
18771 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18772
18773 if (VT.is256BitVector())
18774 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18775
18776 if (VT.is512BitVector())
18777 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18778
18779 if (Is1BitVector)
18780 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18781
18782 llvm_unreachable("Unimplemented!");
18783}
18784
18785// As legal vpcompress instructions depend on various AVX512 extensions, try to
18786// convert illegal vector sizes to legal ones to avoid expansion.
18788 SelectionDAG &DAG) {
18789 assert(Subtarget.hasAVX512() &&
18790 "Need AVX512 for custom VECTOR_COMPRESS lowering.");
18791
18792 SDLoc DL(Op);
18793 SDValue Vec = Op.getOperand(0);
18794 SDValue Mask = Op.getOperand(1);
18795 SDValue Passthru = Op.getOperand(2);
18796
18797 EVT VecVT = Vec.getValueType();
18798 EVT ElementVT = VecVT.getVectorElementType();
18799 unsigned NumElements = VecVT.getVectorNumElements();
18800 unsigned NumVecBits = VecVT.getFixedSizeInBits();
18801 unsigned NumElementBits = ElementVT.getFixedSizeInBits();
18802
18803 // 128- and 256-bit vectors with <= 16 elements can be converted to and
18804 // compressed as 512-bit vectors in AVX512F.
18805 if (NumVecBits != 128 && NumVecBits != 256)
18806 return SDValue();
18807
18808 if (NumElementBits == 32 || NumElementBits == 64) {
18809 unsigned NumLargeElements = 512 / NumElementBits;
18810 MVT LargeVecVT =
18811 MVT::getVectorVT(ElementVT.getSimpleVT(), NumLargeElements);
18812 MVT LargeMaskVT = MVT::getVectorVT(MVT::i1, NumLargeElements);
18813
18814 Vec = widenSubVector(LargeVecVT, Vec, /*ZeroNewElements=*/false, Subtarget,
18815 DAG, DL);
18816 Mask = widenSubVector(LargeMaskVT, Mask, /*ZeroNewElements=*/true,
18817 Subtarget, DAG, DL);
18818 Passthru = Passthru.isUndef() ? DAG.getUNDEF(LargeVecVT)
18819 : widenSubVector(LargeVecVT, Passthru,
18820 /*ZeroNewElements=*/false,
18821 Subtarget, DAG, DL);
18822
18823 SDValue Compressed =
18824 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18825 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VecVT, Compressed,
18826 DAG.getConstant(0, DL, MVT::i64));
18827 }
18828
18829 if (VecVT == MVT::v8i16 || VecVT == MVT::v8i8 || VecVT == MVT::v16i8 ||
18830 VecVT == MVT::v16i16) {
18831 MVT LageElementVT = MVT::getIntegerVT(512 / NumElements);
18832 EVT LargeVecVT = MVT::getVectorVT(LageElementVT, NumElements);
18833
18834 Vec = DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Vec);
18835 Passthru = Passthru.isUndef()
18836 ? DAG.getUNDEF(LargeVecVT)
18837 : DAG.getNode(ISD::ANY_EXTEND, DL, LargeVecVT, Passthru);
18838
18839 SDValue Compressed =
18840 DAG.getNode(ISD::VECTOR_COMPRESS, DL, LargeVecVT, Vec, Mask, Passthru);
18841 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Compressed);
18842 }
18843
18844 return SDValue();
18845}
18846
18847/// Try to lower a VSELECT instruction to a vector shuffle.
18849 const X86Subtarget &Subtarget,
18850 SelectionDAG &DAG) {
18851 SDValue Cond = Op.getOperand(0);
18852 SDValue LHS = Op.getOperand(1);
18853 SDValue RHS = Op.getOperand(2);
18854 MVT VT = Op.getSimpleValueType();
18855
18856 // Only non-legal VSELECTs reach this lowering, convert those into generic
18857 // shuffles and re-use the shuffle lowering path for blends.
18861 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18862 }
18863
18864 return SDValue();
18865}
18866
18867SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18868 SDValue Cond = Op.getOperand(0);
18869 SDValue LHS = Op.getOperand(1);
18870 SDValue RHS = Op.getOperand(2);
18871
18872 SDLoc dl(Op);
18873 MVT VT = Op.getSimpleValueType();
18874 if (isSoftF16(VT, Subtarget)) {
18875 MVT NVT = VT.changeVectorElementTypeToInteger();
18876 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
18877 DAG.getBitcast(NVT, LHS),
18878 DAG.getBitcast(NVT, RHS)));
18879 }
18880
18881 // A vselect where all conditions and data are constants can be optimized into
18882 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18886 return SDValue();
18887
18888 // Try to lower this to a blend-style vector shuffle. This can handle all
18889 // constant condition cases.
18890 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18891 return BlendOp;
18892
18893 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18894 // with patterns on the mask registers on AVX-512.
18895 MVT CondVT = Cond.getSimpleValueType();
18896 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18897 if (CondEltSize == 1)
18898 return Op;
18899
18900 // Variable blends are only legal from SSE4.1 onward.
18901 if (!Subtarget.hasSSE41())
18902 return SDValue();
18903
18904 unsigned EltSize = VT.getScalarSizeInBits();
18905 unsigned NumElts = VT.getVectorNumElements();
18906
18907 // Expand v32i16/v64i8 without BWI.
18908 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18909 return SDValue();
18910
18911 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18912 // into an i1 condition so that we can use the mask-based 512-bit blend
18913 // instructions.
18914 if (VT.getSizeInBits() == 512) {
18915 // Build a mask by testing the condition against zero.
18916 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18917 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18918 DAG.getConstant(0, dl, CondVT),
18919 ISD::SETNE);
18920 // Now return a new VSELECT using the mask.
18921 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18922 }
18923
18924 // SEXT/TRUNC cases where the mask doesn't match the destination size.
18925 if (CondEltSize != EltSize) {
18926 // If we don't have a sign splat, rely on the expansion.
18927 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18928 return SDValue();
18929
18930 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18931 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18932 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18933 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18934 }
18935
18936 // v16i16/v32i8 selects without AVX2, if the condition and another operand
18937 // are free to split, then better to split before expanding the
18938 // select. Don't bother with XOP as it has the fast VPCMOV instruction.
18939 // TODO: This is very similar to narrowVectorSelect.
18940 // TODO: Add Load splitting to isFreeToSplitVector ?
18941 if (EltSize < 32 && VT.is256BitVector() && !Subtarget.hasAVX2() &&
18942 !Subtarget.hasXOP()) {
18943 bool FreeCond = isFreeToSplitVector(Cond, DAG);
18944 bool FreeLHS = isFreeToSplitVector(LHS, DAG) ||
18945 (ISD::isNormalLoad(LHS.getNode()) && LHS.hasOneUse());
18946 bool FreeRHS = isFreeToSplitVector(RHS, DAG) ||
18947 (ISD::isNormalLoad(RHS.getNode()) && RHS.hasOneUse());
18948 if (FreeCond && (FreeLHS || FreeRHS))
18949 return splitVectorOp(Op, DAG, dl);
18950 }
18951
18952 // Only some types will be legal on some subtargets. If we can emit a legal
18953 // VSELECT-matching blend, return Op, and but if we need to expand, return
18954 // a null value.
18955 switch (VT.SimpleTy) {
18956 default:
18957 // Most of the vector types have blends past SSE4.1.
18958 return Op;
18959
18960 case MVT::v32i8:
18961 // The byte blends for AVX vectors were introduced only in AVX2.
18962 if (Subtarget.hasAVX2())
18963 return Op;
18964
18965 return SDValue();
18966
18967 case MVT::v8i16:
18968 case MVT::v16i16:
18969 case MVT::v8f16:
18970 case MVT::v16f16: {
18971 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18972 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18973 Cond = DAG.getBitcast(CastVT, Cond);
18974 LHS = DAG.getBitcast(CastVT, LHS);
18975 RHS = DAG.getBitcast(CastVT, RHS);
18976 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18977 return DAG.getBitcast(VT, Select);
18978 }
18979 }
18980}
18981
18983 MVT VT = Op.getSimpleValueType();
18984 SDValue Vec = Op.getOperand(0);
18985 SDValue Idx = Op.getOperand(1);
18986 assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
18987 SDLoc dl(Op);
18988
18990 return SDValue();
18991
18992 if (VT.getSizeInBits() == 8) {
18993 // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
18994 // we're going to zero extend the register or fold the store.
18997 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
18998 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18999 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19000
19001 unsigned IdxVal = Idx->getAsZExtVal();
19002 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
19003 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19004 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19005 }
19006
19007 if (VT == MVT::f32) {
19008 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
19009 // the result back to FR32 register. It's only worth matching if the
19010 // result has a single use which is a store or a bitcast to i32. And in
19011 // the case of a store, it's not worth it if the index is a constant 0,
19012 // because a MOVSSmr can be used instead, which is smaller and faster.
19013 if (!Op.hasOneUse())
19014 return SDValue();
19015 SDNode *User = *Op.getNode()->user_begin();
19016 if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
19017 (User->getOpcode() != ISD::BITCAST ||
19018 User->getValueType(0) != MVT::i32))
19019 return SDValue();
19020 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19021 DAG.getBitcast(MVT::v4i32, Vec), Idx);
19022 return DAG.getBitcast(MVT::f32, Extract);
19023 }
19024
19025 if (VT == MVT::i32 || VT == MVT::i64)
19026 return Op;
19027
19028 return SDValue();
19029}
19030
19031/// Extract one bit from mask vector, like v16i1 or v8i1.
19032/// AVX-512 feature.
19034 const X86Subtarget &Subtarget) {
19035 SDValue Vec = Op.getOperand(0);
19036 SDLoc dl(Vec);
19037 MVT VecVT = Vec.getSimpleValueType();
19038 SDValue Idx = Op.getOperand(1);
19039 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19040 MVT EltVT = Op.getSimpleValueType();
19041
19042 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
19043 "Unexpected vector type in ExtractBitFromMaskVector");
19044
19045 // variable index can't be handled in mask registers,
19046 // extend vector to VR512/128
19047 if (!IdxC) {
19048 unsigned NumElts = VecVT.getVectorNumElements();
19049 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
19050 // than extending to 128/256bit.
19051 if (NumElts == 1) {
19052 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19054 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, DAG.getBitcast(IntVT, Vec));
19055 }
19056 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19057 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19058 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
19059 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
19060 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
19061 }
19062
19063 unsigned IdxVal = IdxC->getZExtValue();
19064 if (IdxVal == 0) // the operation is legal
19065 return Op;
19066
19067 // Extend to natively supported kshift.
19068 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19069
19070 // Use kshiftr instruction to move to the lower element.
19071 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19072 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19073
19074 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19075 DAG.getVectorIdxConstant(0, dl));
19076}
19077
19078// Helper to find all the extracted elements from a vector.
19080 MVT VT = N->getSimpleValueType(0);
19081 unsigned NumElts = VT.getVectorNumElements();
19082 APInt DemandedElts = APInt::getZero(NumElts);
19083 for (SDNode *User : N->users()) {
19084 switch (User->getOpcode()) {
19085 case X86ISD::PEXTRB:
19086 case X86ISD::PEXTRW:
19089 DemandedElts.setAllBits();
19090 return DemandedElts;
19091 }
19092 DemandedElts.setBit(User->getConstantOperandVal(1));
19093 break;
19094 case ISD::BITCAST: {
19095 if (!User->getValueType(0).isSimple() ||
19096 !User->getValueType(0).isVector()) {
19097 DemandedElts.setAllBits();
19098 return DemandedElts;
19099 }
19100 APInt DemandedSrcElts = getExtractedDemandedElts(User);
19101 DemandedElts |= APIntOps::ScaleBitMask(DemandedSrcElts, NumElts);
19102 break;
19103 }
19104 default:
19105 DemandedElts.setAllBits();
19106 return DemandedElts;
19107 }
19108 }
19109 return DemandedElts;
19110}
19111
19112SDValue
19113X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
19114 SelectionDAG &DAG) const {
19115 SDLoc dl(Op);
19116 SDValue Vec = Op.getOperand(0);
19117 MVT VecVT = Vec.getSimpleValueType();
19118 SDValue Idx = Op.getOperand(1);
19119 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
19120
19121 if (VecVT.getVectorElementType() == MVT::i1)
19122 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
19123
19124 if (!IdxC) {
19125 // Its more profitable to go through memory (1 cycles throughput)
19126 // than using VMOVD + VPERMV/PSHUFB sequence (2/3 cycles throughput)
19127 // IACA tool was used to get performance estimation
19128 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
19129 //
19130 // example : extractelement <16 x i8> %a, i32 %i
19131 //
19132 // Block Throughput: 3.00 Cycles
19133 // Throughput Bottleneck: Port5
19134 //
19135 // | Num Of | Ports pressure in cycles | |
19136 // | Uops | 0 - DV | 5 | 6 | 7 | |
19137 // ---------------------------------------------
19138 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
19139 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
19140 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
19141 // Total Num Of Uops: 4
19142 //
19143 //
19144 // Block Throughput: 1.00 Cycles
19145 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
19146 //
19147 // | | Ports pressure in cycles | |
19148 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
19149 // ---------------------------------------------------------
19150 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
19151 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
19152 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
19153 // Total Num Of Uops: 4
19154
19155 return SDValue();
19156 }
19157
19158 unsigned IdxVal = IdxC->getZExtValue();
19159
19160 // If this is a 256-bit vector result, first extract the 128-bit vector and
19161 // then extract the element from the 128-bit vector.
19162 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
19163 // Get the 128-bit vector.
19164 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
19165 MVT EltVT = VecVT.getVectorElementType();
19166
19167 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
19168 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
19169
19170 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
19171 // this can be done with a mask.
19172 IdxVal &= ElemsPerChunk - 1;
19173 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
19174 DAG.getVectorIdxConstant(IdxVal, dl));
19175 }
19176
19177 assert(VecVT.is128BitVector() && "Unexpected vector length");
19178
19179 MVT VT = Op.getSimpleValueType();
19180
19181 if (VT == MVT::i16) {
19182 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
19183 // we're going to zero extend the register or fold the store (SSE41 only).
19184 if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
19185 !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
19186 if (Subtarget.hasFP16())
19187 return Op;
19188
19189 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
19190 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19191 DAG.getBitcast(MVT::v4i32, Vec), Idx));
19192 }
19193
19194 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
19195 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19196 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
19197 }
19198
19199 if (Subtarget.hasSSE41())
19200 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
19201 return Res;
19202
19203 // Only extract a single element from a v16i8 source - determine the common
19204 // DWORD/WORD that all extractions share, and extract the sub-byte.
19205 // TODO: Add QWORD MOVQ extraction?
19206 if (VT == MVT::i8) {
19207 APInt DemandedElts = getExtractedDemandedElts(Vec.getNode());
19208 assert(DemandedElts.getBitWidth() == 16 && "Vector width mismatch");
19209
19210 // Extract either the lowest i32 or any i16, and extract the sub-byte.
19211 int DWordIdx = IdxVal / 4;
19212 if (DWordIdx == 0 && DemandedElts == (DemandedElts & 15)) {
19213 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
19214 DAG.getBitcast(MVT::v4i32, Vec),
19215 DAG.getVectorIdxConstant(DWordIdx, dl));
19216 int ShiftVal = (IdxVal % 4) * 8;
19217 if (ShiftVal != 0)
19218 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
19219 DAG.getConstant(ShiftVal, dl, MVT::i8));
19220 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19221 }
19222
19223 int WordIdx = IdxVal / 2;
19224 if (DemandedElts == (DemandedElts & (3 << (WordIdx * 2)))) {
19225 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
19226 DAG.getBitcast(MVT::v8i16, Vec),
19227 DAG.getVectorIdxConstant(WordIdx, dl));
19228 int ShiftVal = (IdxVal % 2) * 8;
19229 if (ShiftVal != 0)
19230 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
19231 DAG.getConstant(ShiftVal, dl, MVT::i8));
19232 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
19233 }
19234 }
19235
19236 if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
19237 if (IdxVal == 0)
19238 return Op;
19239
19240 // Shuffle the element to the lowest element, then movss or movsh.
19241 SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
19242 Mask[0] = static_cast<int>(IdxVal);
19243 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19244 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19245 DAG.getVectorIdxConstant(0, dl));
19246 }
19247
19248 if (VT.getSizeInBits() == 64) {
19249 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
19250 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
19251 // to match extract_elt for f64.
19252 if (IdxVal == 0)
19253 return Op;
19254
19255 // UNPCKHPD the element to the lowest double word, then movsd.
19256 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
19257 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
19258 int Mask[2] = { 1, -1 };
19259 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
19260 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
19261 DAG.getVectorIdxConstant(0, dl));
19262 }
19263
19264 return SDValue();
19265}
19266
19267/// Insert one bit to mask vector, like v16i1 or v8i1.
19268/// AVX-512 feature.
19270 const X86Subtarget &Subtarget) {
19271 SDLoc dl(Op);
19272 SDValue Vec = Op.getOperand(0);
19273 SDValue Elt = Op.getOperand(1);
19274 SDValue Idx = Op.getOperand(2);
19275 MVT VecVT = Vec.getSimpleValueType();
19276
19277 if (!isa<ConstantSDNode>(Idx)) {
19278 // Non constant index. Extend source and destination,
19279 // insert element and then truncate the result.
19280 unsigned NumElts = VecVT.getVectorNumElements();
19281 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
19282 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
19283 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
19284 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
19285 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
19286 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
19287 }
19288
19289 // Copy into a k-register, extract to v1i1 and insert_subvector.
19290 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
19291 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
19292}
19293
19294SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
19295 SelectionDAG &DAG) const {
19296 MVT VT = Op.getSimpleValueType();
19297 MVT EltVT = VT.getVectorElementType();
19298 unsigned NumElts = VT.getVectorNumElements();
19299 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
19300
19301 if (EltVT == MVT::i1)
19302 return InsertBitToMaskVector(Op, DAG, Subtarget);
19303
19304 SDLoc dl(Op);
19305 SDValue N0 = Op.getOperand(0);
19306 SDValue N1 = Op.getOperand(1);
19307 SDValue N2 = Op.getOperand(2);
19308 auto *N2C = dyn_cast<ConstantSDNode>(N2);
19309
19310 if (EltVT == MVT::bf16) {
19311 MVT IVT = VT.changeVectorElementTypeToInteger();
19312 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVT,
19313 DAG.getBitcast(IVT, N0),
19314 DAG.getBitcast(MVT::i16, N1), N2);
19315 return DAG.getBitcast(VT, Res);
19316 }
19317
19318 if (!N2C) {
19319 // Variable insertion indices, usually we're better off spilling to stack,
19320 // but AVX512 can use a variable compare+select by comparing against all
19321 // possible vector indices, and FP insertion has less gpr->simd traffic.
19322 if (!(Subtarget.hasBWI() ||
19323 (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
19324 (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
19325 return SDValue();
19326
19327 MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
19328 MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
19329 if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
19330 return SDValue();
19331
19332 SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
19333 SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
19334 SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
19335
19336 SmallVector<SDValue, 16> RawIndices;
19337 for (unsigned I = 0; I != NumElts; ++I)
19338 RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
19339 SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
19340
19341 // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
19342 return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
19344 }
19345
19346 if (N2C->getAPIntValue().uge(NumElts))
19347 return SDValue();
19348 uint64_t IdxVal = N2C->getZExtValue();
19349
19350 bool IsZeroElt = X86::isZeroNode(N1);
19351 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
19352
19353 if (IsZeroElt || IsAllOnesElt) {
19354 // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
19355 // We don't deal with i8 0 since it appears to be handled elsewhere.
19356 if (IsAllOnesElt &&
19357 ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
19358 ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
19359 SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
19360 SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
19361 SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
19362 CstVectorElts[IdxVal] = OnesCst;
19363 SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
19364 return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
19365 }
19366 // See if we can do this more efficiently with a blend shuffle with a
19367 // rematerializable vector.
19368 if (Subtarget.hasSSE41() &&
19369 (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
19370 SmallVector<int, 8> BlendMask;
19371 for (unsigned i = 0; i != NumElts; ++i)
19372 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19373 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
19374 : getOnesVector(VT, DAG, dl);
19375 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
19376 }
19377 }
19378
19379 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
19380 // into that, and then insert the subvector back into the result.
19381 if (VT.is256BitVector() || VT.is512BitVector()) {
19382 // With a 256-bit vector, we can insert into the zero element efficiently
19383 // using a blend if we have AVX or AVX2 and the right data type.
19384 if (VT.is256BitVector() && IdxVal == 0) {
19385 // TODO: It is worthwhile to cast integer to floating point and back
19386 // and incur a domain crossing penalty if that's what we'll end up
19387 // doing anyway after extracting to a 128-bit vector.
19388 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19389 (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
19390 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19391 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19392 DAG.getTargetConstant(1, dl, MVT::i8));
19393 }
19394 }
19395
19396 unsigned NumEltsIn128 = 128 / EltSizeInBits;
19397 assert(isPowerOf2_32(NumEltsIn128) &&
19398 "Vectors will always have power-of-two number of elements.");
19399
19400 // If we are not inserting into the low 128-bit vector chunk,
19401 // then prefer the broadcast+blend sequence.
19402 // FIXME: relax the profitability check iff all N1 uses are insertions.
19403 if (IdxVal >= NumEltsIn128 &&
19404 ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
19405 (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
19406 X86::mayFoldLoad(N1, Subtarget)))) {
19407 SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
19408 SmallVector<int, 8> BlendMask;
19409 for (unsigned i = 0; i != NumElts; ++i)
19410 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
19411 return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
19412 }
19413
19414 // Get the desired 128-bit vector chunk.
19415 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
19416
19417 // Insert the element into the desired chunk.
19418 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
19419 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
19420
19421 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
19422 DAG.getVectorIdxConstant(IdxIn128, dl));
19423
19424 // Insert the changed part back into the bigger vector
19425 return insert128BitVector(N0, V, IdxVal, DAG, dl);
19426 }
19427 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
19428
19429 // This will be just movw/movd/movq/movsh/movss/movsd.
19430 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
19431 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
19432 EltVT == MVT::f16 || EltVT == MVT::i64) {
19433 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19434 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19435 }
19436
19437 // We can't directly insert an i8 or i16 into a vector, so zero extend
19438 // it to i32 first.
19439 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
19440 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
19441 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
19442 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
19443 N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19444 return DAG.getBitcast(VT, N1);
19445 }
19446 }
19447
19448 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
19449 // argument. SSE41 required for pinsrb.
19450 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
19451 unsigned Opc;
19452 if (VT == MVT::v8i16) {
19453 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
19454 Opc = X86ISD::PINSRW;
19455 } else {
19456 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
19457 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
19458 Opc = X86ISD::PINSRB;
19459 }
19460
19461 assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
19462 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
19463 N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
19464 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
19465 }
19466
19467 if (Subtarget.hasSSE41()) {
19468 if (EltVT == MVT::f32) {
19469 // Bits [7:6] of the constant are the source select. This will always be
19470 // zero here. The DAG Combiner may combine an extract_elt index into
19471 // these bits. For example (insert (extract, 3), 2) could be matched by
19472 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
19473 // Bits [5:4] of the constant are the destination select. This is the
19474 // value of the incoming immediate.
19475 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
19476 // combine either bitwise AND or insert of float 0.0 to set these bits.
19477
19478 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
19479 if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
19480 // If this is an insertion of 32-bits into the low 32-bits of
19481 // a vector, we prefer to generate a blend with immediate rather
19482 // than an insertps. Blends are simpler operations in hardware and so
19483 // will always have equal or better performance than insertps.
19484 // But if optimizing for size and there's a load folding opportunity,
19485 // generate insertps because blendps does not have a 32-bit memory
19486 // operand form.
19487 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19488 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
19489 DAG.getTargetConstant(1, dl, MVT::i8));
19490 }
19491 // Create this as a scalar to vector..
19492 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19493 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
19494 DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
19495 }
19496
19497 // PINSR* works with constant index.
19498 if (EltVT == MVT::i32 || EltVT == MVT::i64)
19499 return Op;
19500 }
19501
19502 return SDValue();
19503}
19504
19505static SDValue LowerFLDEXP(SDValue Op, const X86Subtarget &Subtarget,
19506 SelectionDAG &DAG) {
19507 SDLoc DL(Op);
19508 SDValue X = Op.getOperand(0);
19509 MVT XTy = X.getSimpleValueType();
19510 SDValue Exp = Op.getOperand(1);
19511
19512 switch (XTy.SimpleTy) {
19513 default:
19514 return SDValue();
19515 case MVT::f16:
19516 if (!Subtarget.hasFP16())
19517 X = DAG.getFPExtendOrRound(X, DL, MVT::f32);
19518 [[fallthrough]];
19519 case MVT::f32:
19520 case MVT::f64: {
19521 MVT VT = MVT::getVectorVT(X.getSimpleValueType(),
19522 128 / X.getSimpleValueType().getSizeInBits());
19523 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, X.getValueType(), Exp);
19524 SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, X);
19525 SDValue VExp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Exp);
19526 SDValue Scalefs = DAG.getNode(X86ISD::SCALEFS, DL, VT, VX, VExp);
19527 SDValue Final = DAG.getExtractVectorElt(DL, X.getValueType(), Scalefs, 0);
19528 return DAG.getFPExtendOrRound(Final, DL, XTy);
19529 }
19530 case MVT::v4f32:
19531 case MVT::v2f64:
19532 case MVT::v8f32:
19533 case MVT::v4f64:
19534 case MVT::v16f32:
19535 case MVT::v8f64:
19536 if (XTy.getSizeInBits() == 512 || Subtarget.hasVLX()) {
19537 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19538 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19539 }
19540 break;
19541 case MVT::v8f16:
19542 case MVT::v16f16:
19543 if (Subtarget.hasFP16()) {
19544 if (Subtarget.hasVLX()) {
19545 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19546 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19547 }
19548 break;
19549 }
19550 X = DAG.getFPExtendOrRound(X, DL, XTy.changeVectorElementType(MVT::f32));
19551 Exp = DAG.getSExtOrTrunc(Exp, DL,
19552 X.getSimpleValueType().changeTypeToInteger());
19553 break;
19554 case MVT::v32f16:
19555 if (Subtarget.hasFP16()) {
19556 Exp = DAG.getNode(ISD::SINT_TO_FP, DL, XTy, Exp);
19557 return DAG.getNode(X86ISD::SCALEF, DL, XTy, X, Exp);
19558 }
19559 return splitVectorOp(Op, DAG, DL);
19560 }
19561 SDValue WideX = widenSubVector(X, true, Subtarget, DAG, DL, 512);
19562 // Widen Exp to the same *lane count* as WideX (not necessarily 512 bits) so
19563 // SINT_TO_FP has matching vector lengths. For wide f64 the int exponent
19564 // vector is narrower than 512 bits (e.g. v2i32 -> v8i32 to match v8f64).
19565 MVT WideExpVT =
19566 MVT::getVectorVT(Exp.getSimpleValueType().getVectorElementType(),
19568 SDValue WideExp = widenSubVector(WideExpVT, Exp, /*ZeroNewElements=*/true,
19569 Subtarget, DAG, DL);
19570 SDValue WideExpFp =
19571 DAG.getNode(ISD::SINT_TO_FP, DL, WideX.getValueType(), WideExp);
19572 SDValue Scalef =
19573 DAG.getNode(X86ISD::SCALEF, DL, WideX.getValueType(), WideX, WideExpFp);
19574 SDValue Final =
19575 DAG.getExtractSubvector(DL, X.getSimpleValueType(), Scalef, 0);
19576 return DAG.getFPExtendOrRound(Final, DL, XTy);
19577}
19578
19580 SelectionDAG &DAG) {
19581 SDLoc dl(Op);
19582 MVT OpVT = Op.getSimpleValueType();
19583
19584 // It's always cheaper to replace a xor+movd with xorps and simplifies further
19585 // combines.
19586 if (X86::isZeroNode(Op.getOperand(0)))
19587 return getZeroVector(OpVT, Subtarget, DAG, dl);
19588
19589 // If this is a 256-bit vector result, first insert into a 128-bit
19590 // vector and then insert into the 256-bit vector.
19591 if (!OpVT.is128BitVector()) {
19592 // Insert into a 128-bit vector.
19593 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
19595 OpVT.getVectorNumElements() / SizeFactor);
19596
19597 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
19598
19599 // Insert the 128-bit vector.
19600 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
19601 }
19602 assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
19603 "Expected an SSE type!");
19604
19605 // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
19606 // tblgen.
19607 if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
19608 return Op;
19609
19610 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
19611 return DAG.getBitcast(
19612 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
19613}
19614
19615// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
19616// simple superregister reference or explicit instructions to insert
19617// the upper bits of a vector.
19619 SelectionDAG &DAG) {
19620 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
19621
19622 return insert1BitVector(Op, DAG, Subtarget);
19623}
19624
19626 SelectionDAG &DAG) {
19627 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
19628 "Only vXi1 extract_subvectors need custom lowering");
19629
19630 SDLoc dl(Op);
19631 SDValue Vec = Op.getOperand(0);
19632 uint64_t IdxVal = Op.getConstantOperandVal(1);
19633
19634 if (IdxVal == 0) // the operation is legal
19635 return Op;
19636
19637 // Extend to natively supported kshift.
19638 Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
19639
19640 // Shift to the LSB.
19641 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
19642 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19643
19644 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19645 DAG.getVectorIdxConstant(0, dl));
19646}
19647
19648// Returns the appropriate wrapper opcode for a global reference.
19649unsigned X86TargetLowering::getGlobalWrapperKind(
19650 const GlobalValue *GV, const unsigned char OpFlags) const {
19651 // References to absolute symbols are never PC-relative.
19652 if (GV && GV->isAbsoluteSymbolRef())
19653 return X86ISD::Wrapper;
19654
19655 // The following OpFlags under RIP-rel PIC use RIP.
19656 if (Subtarget.isPICStyleRIPRel() &&
19657 (OpFlags == X86II::MO_NO_FLAG || OpFlags == X86II::MO_COFFSTUB ||
19658 OpFlags == X86II::MO_DLLIMPORT))
19659 return X86ISD::WrapperRIP;
19660
19661 // GOTPCREL references must always use RIP.
19662 if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
19663 return X86ISD::WrapperRIP;
19664
19665 return X86ISD::Wrapper;
19666}
19667
19668// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19669// their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19670// one of the above mentioned nodes. It has to be wrapped because otherwise
19671// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19672// be used to form addressing mode. These wrapped nodes will be selected
19673// into MOV32ri.
19674SDValue
19675X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19676 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19677
19678 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19679 // global base reg.
19680 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19681
19682 auto PtrVT = getPointerTy(DAG.getDataLayout());
19684 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19685 SDLoc DL(CP);
19686 Result =
19687 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19688 // With PIC, the address is actually $g + Offset.
19689 if (OpFlag) {
19690 Result =
19691 DAG.getNode(ISD::ADD, DL, PtrVT,
19692 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19693 }
19694
19695 return Result;
19696}
19697
19698SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19699 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19700
19701 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19702 // global base reg.
19703 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19704
19705 EVT PtrVT = Op.getValueType();
19706 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19707 SDLoc DL(JT);
19708 Result =
19709 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
19710
19711 // With PIC, the address is actually $g + Offset.
19712 if (OpFlag)
19713 Result =
19714 DAG.getNode(ISD::ADD, DL, PtrVT,
19715 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19716
19717 return Result;
19718}
19719
19720SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19721 SelectionDAG &DAG) const {
19722 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19723}
19724
19725SDValue
19726X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19727 // Create the TargetBlockAddressAddress node.
19728 unsigned char OpFlags =
19729 Subtarget.classifyBlockAddressReference();
19730 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19731 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19732 SDLoc dl(Op);
19733 EVT PtrVT = Op.getValueType();
19734 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19735 Result =
19736 DAG.getNode(getGlobalWrapperKind(nullptr, OpFlags), dl, PtrVT, Result);
19737
19738 // With PIC, the address is actually $g + Offset.
19739 if (isGlobalRelativeToPICBase(OpFlags)) {
19740 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19741 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19742 }
19743
19744 return Result;
19745}
19746
19747/// Creates target global address or external symbol nodes for calls or
19748/// other uses.
19749SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19750 bool ForCall,
19751 bool *IsImpCall) const {
19752 // Unpack the global address or external symbol.
19753 SDLoc dl(Op);
19754 const GlobalValue *GV = nullptr;
19755 int64_t Offset = 0;
19756 const char *ExternalSym = nullptr;
19757 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19758 GV = G->getGlobal();
19759 Offset = G->getOffset();
19760 } else {
19761 const auto *ES = cast<ExternalSymbolSDNode>(Op);
19762 ExternalSym = ES->getSymbol();
19763 }
19764
19765 // Calculate some flags for address lowering.
19767 unsigned char OpFlags;
19768 if (ForCall)
19769 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19770 else
19771 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19772 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19773 bool NeedsLoad = isGlobalStubReference(OpFlags);
19774
19776 EVT PtrVT = Op.getValueType();
19778
19779 if (GV) {
19780 // Create a target global address if this is a global. If possible, fold the
19781 // offset into the global address reference. Otherwise, ADD it on later.
19782 // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19783 // allowed because if the address of foo is 0, the ELF R_X86_64_32
19784 // relocation will compute to a negative value, which is invalid.
19785 int64_t GlobalOffset = 0;
19786 if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19788 std::swap(GlobalOffset, Offset);
19789 }
19790 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19791 } else {
19792 // If this is not a global address, this must be an external symbol.
19793 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19794 }
19795
19796 // If this is a direct call, avoid the wrapper if we don't need to do any
19797 // loads or adds. This allows SDAG ISel to match direct calls.
19798 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19799 return Result;
19800
19801 // If Import Call Optimization is enabled and this is an imported function
19802 // then make a note of it and return the global address without wrapping.
19803 if (IsImpCall && (OpFlags == X86II::MO_DLLIMPORT) &&
19804 Mod.getModuleFlag("import-call-optimization")) {
19805 assert(ForCall && "Should only enable import call optimization if we are "
19806 "lowering a call");
19807 *IsImpCall = true;
19808 return Result;
19809 }
19810
19811 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19812
19813 // With PIC, the address is actually $g + Offset.
19814 if (HasPICReg) {
19815 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19816 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19817 }
19818
19819 // For globals that require a load from a stub to get the address, emit the
19820 // load.
19821 if (NeedsLoad)
19822 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19824
19825 // If there was a non-zero offset that we didn't fold, create an explicit
19826 // addition for it.
19827 if (Offset != 0)
19828 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19829 DAG.getSignedConstant(Offset, dl, PtrVT));
19830
19831 return Result;
19832}
19833
19834SDValue
19835X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19836 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false, nullptr);
19837}
19838
19840 const EVT PtrVT, unsigned ReturnReg,
19841 unsigned char OperandFlags,
19842 bool LoadGlobalBaseReg = false,
19843 bool LocalDynamic = false) {
19845 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19846 SDLoc dl(GA);
19847 SDValue TGA;
19848 bool UseTLSDESC = DAG.getTarget().useTLSDESC();
19849 SDValue Chain = DAG.getEntryNode();
19850 SDValue Ret;
19851 if (LocalDynamic && UseTLSDESC) {
19852 TGA = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, OperandFlags);
19853 // Reuse existing GetTLSADDR node if we can find it.
19854 if (TGA->hasOneUse()) {
19855 // TLSDESC uses TGA.
19856 SDNode *TLSDescOp = *TGA->user_begin();
19857 assert(TLSDescOp->getOpcode() == X86ISD::TLSDESC &&
19858 "Unexpected TLSDESC DAG");
19859 // CALLSEQ_END uses TGA via a chain and glue.
19860 auto *CallSeqEndOp = TLSDescOp->getGluedUser();
19861 assert(CallSeqEndOp && CallSeqEndOp->getOpcode() == ISD::CALLSEQ_END &&
19862 "Unexpected TLSDESC DAG");
19863 // CopyFromReg uses CALLSEQ_END via a chain and glue.
19864 auto *CopyFromRegOp = CallSeqEndOp->getGluedUser();
19865 assert(CopyFromRegOp && CopyFromRegOp->getOpcode() == ISD::CopyFromReg &&
19866 "Unexpected TLSDESC DAG");
19867 Ret = SDValue(CopyFromRegOp, 0);
19868 }
19869 } else {
19870 TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19871 GA->getOffset(), OperandFlags);
19872 }
19873
19874 if (!Ret) {
19875 unsigned CallType = UseTLSDESC ? X86ISD::TLSDESC
19876 : LocalDynamic ? X86ISD::TLSBASEADDR
19877 : X86ISD::TLSADDR;
19878
19879 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
19880 if (LoadGlobalBaseReg) {
19881 SDValue InGlue;
19882 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
19883 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT),
19884 InGlue);
19885 InGlue = Chain.getValue(1);
19886 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA, InGlue});
19887 } else {
19888 Chain = DAG.getNode(CallType, dl, NodeTys, {Chain, TGA});
19889 }
19890 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), dl);
19891
19892 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19893 MFI.setHasCalls(true);
19894
19895 SDValue Glue = Chain.getValue(1);
19896 Ret = DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
19897 }
19898
19899 if (!UseTLSDESC)
19900 return Ret;
19901
19902 const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
19903 unsigned Seg = Subtarget.is64Bit() ? X86AS::FS : X86AS::GS;
19904
19906 SDValue Offset =
19907 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19908 MachinePointerInfo(Ptr));
19909 return DAG.getNode(ISD::ADD, dl, PtrVT, Ret, Offset);
19910}
19911
19912// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19913static SDValue
19915 const EVT PtrVT) {
19916 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD,
19917 /*LoadGlobalBaseReg=*/true);
19918}
19919
19920// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19921static SDValue
19923 const EVT PtrVT) {
19924 return GetTLSADDR(DAG, GA, PtrVT, X86::RAX, X86II::MO_TLSGD);
19925}
19926
19927// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19928static SDValue
19930 const EVT PtrVT) {
19931 return GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSGD);
19932}
19933
19935 SelectionDAG &DAG, const EVT PtrVT,
19936 bool Is64Bit, bool Is64BitLP64) {
19937 SDLoc dl(GA);
19938
19939 // Get the start address of the TLS block for this module.
19943
19944 SDValue Base;
19945 if (Is64Bit) {
19946 unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19947 Base = GetTLSADDR(DAG, GA, PtrVT, ReturnReg, X86II::MO_TLSLD,
19948 /*LoadGlobalBaseReg=*/false,
19949 /*LocalDynamic=*/true);
19950 } else {
19951 Base = GetTLSADDR(DAG, GA, PtrVT, X86::EAX, X86II::MO_TLSLDM,
19952 /*LoadGlobalBaseReg=*/true,
19953 /*LocalDynamic=*/true);
19954 }
19955
19956 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19957 // of Base.
19958
19959 // Build x@dtpoff.
19960 unsigned char OperandFlags = X86II::MO_DTPOFF;
19961 unsigned WrapperKind = X86ISD::Wrapper;
19962 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19963 GA->getValueType(0),
19964 GA->getOffset(), OperandFlags);
19965 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19966
19967 // Add x@dtpoff with the base.
19968 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19969}
19970
19971// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19973 const EVT PtrVT, TLSModel::Model model,
19974 bool is64Bit, bool isPIC) {
19975 SDLoc dl(GA);
19976
19977 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
19980
19981 SDValue ThreadPointer =
19982 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19983 MachinePointerInfo(Ptr));
19984
19985 unsigned char OperandFlags = 0;
19986 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
19987 // initialexec.
19988 unsigned WrapperKind = X86ISD::Wrapper;
19989 if (model == TLSModel::LocalExec) {
19990 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
19991 } else if (model == TLSModel::InitialExec) {
19992 if (is64Bit) {
19993 OperandFlags = X86II::MO_GOTTPOFF;
19994 WrapperKind = X86ISD::WrapperRIP;
19995 } else {
19996 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
19997 }
19998 } else {
19999 llvm_unreachable("Unexpected model");
20000 }
20001
20002 // emit "addl x@ntpoff,%eax" (local exec)
20003 // or "addl x@indntpoff,%eax" (initial exec)
20004 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
20005 SDValue TGA =
20006 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
20007 GA->getOffset(), OperandFlags);
20008 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
20009
20010 if (model == TLSModel::InitialExec) {
20011 if (isPIC && !is64Bit) {
20012 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
20013 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20014 Offset);
20015 }
20016
20017 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
20019 }
20020
20021 // The address of the thread local variable is the add of the thread
20022 // pointer with the offset of the variable.
20023 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
20024}
20025
20026SDValue
20027X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
20028
20029 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
20030
20031 if (DAG.getTarget().useEmulatedTLS())
20032 return LowerToTLSEmulatedModel(GA, DAG);
20033
20034 const GlobalValue *GV = GA->getGlobal();
20035 EVT PtrVT = Op.getValueType();
20036 bool PositionIndependent = isPositionIndependent();
20037
20038 if (Subtarget.isTargetELF()) {
20039 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
20040 // LFI does not support dlopen, so all TLS can be statically resolved. We
20041 // automatically upgrade dynamic models to InitialExec because the dynamic
20042 // TLS sequences are slower than necessary and interact poorly with LFI
20043 // rewriting combined with rewrites from linker relaxation.
20044 if (Subtarget.isLFI())
20045 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic)
20046 model = TLSModel::InitialExec;
20047 switch (model) {
20049 if (Subtarget.is64Bit()) {
20050 if (Subtarget.isTarget64BitLP64())
20051 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
20052 return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
20053 }
20054 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
20056 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
20057 Subtarget.isTarget64BitLP64());
20060 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
20061 PositionIndependent);
20062 }
20063 llvm_unreachable("Unknown TLS model.");
20064 }
20065
20066 if (Subtarget.isTargetDarwin()) {
20067 // Darwin only has one model of TLS. Lower to that.
20068 unsigned char OpFlag = 0;
20069 unsigned WrapperKind = 0;
20070
20071 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
20072 // global base reg.
20073 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
20074 if (PIC32) {
20075 OpFlag = X86II::MO_TLVP_PIC_BASE;
20076 WrapperKind = X86ISD::Wrapper;
20077 } else {
20078 OpFlag = X86II::MO_TLVP;
20079 WrapperKind = X86ISD::WrapperRIP;
20080 }
20081 SDLoc DL(Op);
20083 GA->getValueType(0),
20084 GA->getOffset(), OpFlag);
20085 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
20086
20087 // With PIC32, the address is actually $g + Offset.
20088 if (PIC32)
20089 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
20090 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
20091 Offset);
20092
20093 // Lowering the machine isd will make sure everything is in the right
20094 // location.
20095 SDValue Chain = DAG.getEntryNode();
20096 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20097 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
20098 SDValue Args[] = { Chain, Offset };
20099 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
20100 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
20101
20102 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
20103 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
20104 MFI.setAdjustsStack(true);
20105
20106 // And our return value (tls address) is in the standard call return value
20107 // location.
20108 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
20109 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
20110 }
20111
20112 if (Subtarget.isOSWindows()) {
20113 // Just use the implicit TLS architecture
20114 // Need to generate something similar to:
20115 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
20116 // ; from TEB
20117 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
20118 // mov rcx, qword [rdx+rcx*8]
20119 // mov eax, .tls$:tlsvar
20120 // [rax+rcx] contains the address
20121 // Windows 64bit: gs:0x58
20122 // Windows 32bit: fs:__tls_array
20123
20124 SDLoc dl(GA);
20125 SDValue Chain = DAG.getEntryNode();
20126
20127 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
20128 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
20129 // use its literal value of 0x2C.
20131 Subtarget.is64Bit() ? PointerType::get(*DAG.getContext(), X86AS::GS)
20133
20134 SDValue TlsArray = Subtarget.is64Bit()
20135 ? DAG.getIntPtrConstant(0x58, dl)
20136 : (Subtarget.isTargetWindowsGNU()
20137 ? DAG.getIntPtrConstant(0x2C, dl)
20138 : DAG.getExternalSymbol("_tls_array", PtrVT));
20139
20140 SDValue ThreadPointer =
20141 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
20142
20143 SDValue res;
20145 res = ThreadPointer;
20146 } else {
20147 // Load the _tls_index variable
20148 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
20149 if (Subtarget.is64Bit())
20150 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
20151 MachinePointerInfo(), MVT::i32);
20152 else
20153 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
20154
20155 const DataLayout &DL = DAG.getDataLayout();
20156 SDValue Scale =
20157 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
20158 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
20159
20160 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
20161 }
20162
20163 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
20164
20165 // Get the offset of start of .tls section
20166 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
20167 GA->getValueType(0),
20169 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
20170
20171 // The address of the thread local variable is the add of the thread
20172 // pointer with the offset of the variable.
20173 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
20174 }
20175
20176 llvm_unreachable("TLS not implemented for this target.");
20177}
20178
20180 if (Subtarget.is64Bit() && Subtarget.isTargetELF()) {
20181 const TargetMachine &TM = getTargetMachine();
20182 TLSModel::Model Model = TM.getTLSModel(&GV);
20183 switch (Model) {
20186 // We can include the %fs segment register in addressing modes.
20187 return true;
20190 // These models do not result in %fs relative addresses unless
20191 // TLS descriptior are used.
20192 //
20193 // Even in the case of TLS descriptors we currently have no way to model
20194 // the difference between %fs access and the computations needed for the
20195 // offset and returning `true` for TLS-desc currently duplicates both
20196 // which is detrimental :-/
20197 return false;
20198 }
20199 }
20200 return false;
20201}
20202
20203/// Lower SRA_PARTS and friends, which return two i32 values
20204/// and take a 2 x i32 value to shift plus a shift amount.
20205/// TODO: Can this be moved to general expansion code?
20207 SDValue Lo, Hi;
20208 DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
20209 return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
20210}
20211
20212// Try to use a packed vector operation to handle i64 on 32-bit targets when
20213// AVX512DQ is enabled.
20215 SelectionDAG &DAG,
20216 const X86Subtarget &Subtarget) {
20217 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20218 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20219 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20220 Op.getOpcode() == ISD::UINT_TO_FP) &&
20221 "Unexpected opcode!");
20222 bool IsStrict = Op->isStrictFPOpcode();
20223 unsigned OpNo = IsStrict ? 1 : 0;
20224 SDValue Src = Op.getOperand(OpNo);
20225 MVT SrcVT = Src.getSimpleValueType();
20226 MVT VT = Op.getSimpleValueType();
20227
20228 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
20229 (VT != MVT::f32 && VT != MVT::f64))
20230 return SDValue();
20231
20232 // Pack the i64 into a vector, do the operation and extract.
20233
20234 // Using 256-bit to ensure result is 128-bits for f32 case.
20235 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
20236 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
20237 MVT VecVT = MVT::getVectorVT(VT, NumElts);
20238
20239 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
20240 if (IsStrict) {
20241 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
20242 {Op.getOperand(0), InVec});
20243 SDValue Chain = CvtVec.getValue(1);
20244 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20245 DAG.getVectorIdxConstant(0, dl));
20246 return DAG.getMergeValues({Value, Chain}, dl);
20247 }
20248
20249 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
20250
20251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20252 DAG.getVectorIdxConstant(0, dl));
20253}
20254
20255// Try to use a packed vector operation to handle i64 on 32-bit targets.
20257 const X86Subtarget &Subtarget) {
20258 assert((Op.getOpcode() == ISD::SINT_TO_FP ||
20259 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
20260 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
20261 Op.getOpcode() == ISD::UINT_TO_FP) &&
20262 "Unexpected opcode!");
20263 bool IsStrict = Op->isStrictFPOpcode();
20264 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20265 MVT SrcVT = Src.getSimpleValueType();
20266 MVT VT = Op.getSimpleValueType();
20267
20268 if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
20269 return SDValue();
20270
20271 // Pack the i64 into a vector, do the operation and extract.
20272
20273 assert(Subtarget.hasFP16() && "Expected FP16");
20274
20275 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
20276 if (IsStrict) {
20277 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
20278 {Op.getOperand(0), InVec});
20279 SDValue Chain = CvtVec.getValue(1);
20280 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20281 DAG.getVectorIdxConstant(0, dl));
20282 return DAG.getMergeValues({Value, Chain}, dl);
20283 }
20284
20285 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
20286
20287 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
20288 DAG.getVectorIdxConstant(0, dl));
20289}
20290
20291static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
20292 const X86Subtarget &Subtarget) {
20293 switch (Opcode) {
20294 case ISD::SINT_TO_FP:
20295 // TODO: Handle wider types with AVX/AVX512.
20296 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
20297 return false;
20298 // CVTDQ2PS or (V)CVTDQ2PD
20299 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
20300
20301 case ISD::UINT_TO_FP:
20302 // TODO: Handle wider types and i64 elements.
20303 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
20304 return false;
20305 // VCVTUDQ2PS or VCVTUDQ2PD
20306 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
20307
20308 default:
20309 return false;
20310 }
20311}
20312
20313/// Given a scalar cast operation that is extracted from a vector, try to
20314/// vectorize the cast op followed by extraction. This will avoid an expensive
20315/// round-trip between XMM and GPR.
20317 SelectionDAG &DAG,
20318 const X86Subtarget &Subtarget) {
20319 // TODO: This could be enhanced to handle smaller integer types by peeking
20320 // through an extend.
20321 SDValue Extract = Cast.getOperand(0);
20322 MVT DestVT = Cast.getSimpleValueType();
20323 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
20324 !isa<ConstantSDNode>(Extract.getOperand(1)))
20325 return SDValue();
20326
20327 // See if we have a 128-bit vector cast op for this type of cast.
20328 SDValue VecOp = Extract.getOperand(0);
20329 EVT FromVT = VecOp.getValueType();
20330 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
20331 MVT Vec128VT =
20332 MVT::getVectorVT(FromVT.getScalarType().getSimpleVT(), NumEltsInXMM);
20333 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
20334 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
20335 return SDValue();
20336
20337 // If we are extracting from a non-zero element, first shuffle the source
20338 // vector to allow extracting from element zero.
20339 if (!isNullConstant(Extract.getOperand(1))) {
20340 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
20341 Mask[0] = Extract.getConstantOperandVal(1);
20342 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
20343 }
20344 // If the source vector is wider than 128-bits, extract the low part. Do not
20345 // create an unnecessarily wide vector cast op.
20346 if (FromVT != Vec128VT)
20347 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
20348
20349 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
20350 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
20351 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
20352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
20353 DAG.getVectorIdxConstant(0, DL));
20354}
20355
20356/// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
20357/// try to vectorize the cast ops. This will avoid an expensive round-trip
20358/// between XMM and GPR.
20359static SDValue lowerFPToIntToFP(SDValue CastToFP, const SDLoc &DL,
20360 SelectionDAG &DAG,
20361 const X86Subtarget &Subtarget) {
20362 SDValue CastToInt = CastToFP.getOperand(0);
20363 MVT VT = CastToFP.getSimpleValueType();
20364 if ((CastToInt.getOpcode() != ISD::FP_TO_SINT &&
20365 CastToInt.getOpcode() != ISD::FP_TO_UINT) ||
20366 VT.isVector())
20367 return SDValue();
20368
20369 MVT IntVT = CastToInt.getSimpleValueType();
20370 SDValue X = CastToInt.getOperand(0);
20371 MVT SrcVT = X.getSimpleValueType();
20372 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
20373 return SDValue();
20374
20375 // See if we have 128-bit vector cast instructions for this type of cast.
20376 // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
20377 if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
20378 (IntVT != MVT::i32 && IntVT != MVT::i64))
20379 return SDValue();
20380
20381 unsigned SrcSize = SrcVT.getSizeInBits();
20382 unsigned IntSize = IntVT.getSizeInBits();
20383 unsigned VTSize = VT.getSizeInBits();
20384 bool IsUnsigned = CastToInt.getOpcode() == ISD::FP_TO_UINT;
20385 unsigned ToIntOpcode =
20386 SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
20387 unsigned ToFPOpcode =
20388 IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
20389 unsigned Width = 128;
20390
20391 if (Subtarget.hasVLX() && Subtarget.hasDQI()) {
20392 // AVX512DQ+VLX
20393 if (IsUnsigned) {
20394 ToIntOpcode =
20395 SrcSize != IntSize ? X86ISD::CVTTP2UI : (unsigned)ISD::FP_TO_UINT;
20396 ToFPOpcode =
20397 IntSize != VTSize ? X86ISD::CVTUI2P : (unsigned)ISD::UINT_TO_FP;
20398 }
20399 } else {
20400 if (IsUnsigned || IntVT == MVT::i64) {
20401 // SSE2 can only perform f64/f32 <-> i32 signed.
20402 if (!Subtarget.useAVX512Regs() || !Subtarget.hasDQI())
20403 return SDValue();
20404
20405 // Need to extend width for AVX512DQ without AVX512VL.
20406 Width = 512;
20407 ToIntOpcode = CastToInt.getOpcode();
20408 ToFPOpcode = IsUnsigned ? ISD::UINT_TO_FP : ISD::SINT_TO_FP;
20409 }
20410 }
20411
20412 MVT VecSrcVT, VecIntVT, VecVT;
20413 unsigned NumElts;
20414 unsigned SrcElts, VTElts;
20415 // Some conversions are only legal with uniform vector sizes on AVX512DQ.
20416 if (Width == 512) {
20417 NumElts = std::min(Width / IntSize, Width / SrcSize);
20418 SrcElts = NumElts;
20419 VTElts = NumElts;
20420 } else {
20421 NumElts = Width / IntSize;
20422 SrcElts = Width / SrcSize;
20423 VTElts = Width / VTSize;
20424 }
20425 VecIntVT = MVT::getVectorVT(IntVT, NumElts);
20426 VecSrcVT = MVT::getVectorVT(SrcVT, SrcElts);
20427 VecVT = MVT::getVectorVT(VT, VTElts);
20428 // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
20429 //
20430 // We are not defining the high elements (for example, zero them) because
20431 // that could nullify any performance advantage that we hoped to gain from
20432 // this vector op hack. We do not expect any adverse effects (like denorm
20433 // penalties) with cast ops.
20434 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
20435 SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
20436 SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
20437 SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
20438 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
20439}
20440
20442 SelectionDAG &DAG,
20443 const X86Subtarget &Subtarget) {
20444 bool IsStrict = Op->isStrictFPOpcode();
20445 MVT VT = Op->getSimpleValueType(0);
20446 SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
20447
20448 if (Subtarget.hasDQI()) {
20449 assert(!Subtarget.hasVLX() && "Unexpected features");
20450
20451 assert((Src.getSimpleValueType() == MVT::v2i64 ||
20452 Src.getSimpleValueType() == MVT::v4i64) &&
20453 "Unsupported custom type");
20454
20455 // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
20456 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
20457 "Unexpected VT!");
20458 MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20459
20460 // Need to concat with zero vector for strict fp to avoid spurious
20461 // exceptions.
20462 SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
20463 : DAG.getUNDEF(MVT::v8i64);
20464 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
20465 DAG.getVectorIdxConstant(0, DL));
20466 SDValue Res, Chain;
20467 if (IsStrict) {
20468 Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
20469 {Op->getOperand(0), Src});
20470 Chain = Res.getValue(1);
20471 } else {
20472 Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
20473 }
20474
20475 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20476 DAG.getVectorIdxConstant(0, DL));
20477
20478 if (IsStrict)
20479 return DAG.getMergeValues({Res, Chain}, DL);
20480 return Res;
20481 }
20482
20483 bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
20484 Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
20485 if (VT != MVT::v4f32 || IsSigned)
20486 return SDValue();
20487
20488 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
20489 SDValue One = DAG.getConstant(1, DL, MVT::v4i64);
20490 SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
20491 DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
20492 DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
20493 SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
20494 SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
20495 SmallVector<SDValue, 4> SignCvts(4);
20496 SmallVector<SDValue, 4> Chains(4);
20497 for (int i = 0; i != 4; ++i) {
20498 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
20499 DAG.getVectorIdxConstant(i, DL));
20500 if (IsStrict) {
20501 SignCvts[i] =
20502 DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
20503 {Op.getOperand(0), Elt});
20504 Chains[i] = SignCvts[i].getValue(1);
20505 } else {
20506 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
20507 }
20508 }
20509 SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
20510
20511 SDValue Slow, Chain;
20512 if (IsStrict) {
20513 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
20514 Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
20515 {Chain, SignCvt, SignCvt});
20516 Chain = Slow.getValue(1);
20517 } else {
20518 Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
20519 }
20520
20521 IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
20522 SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
20523
20524 if (IsStrict)
20525 return DAG.getMergeValues({Cvt, Chain}, DL);
20526
20527 return Cvt;
20528}
20529
20531 SelectionDAG &DAG) {
20532 bool IsStrict = Op->isStrictFPOpcode();
20533 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20534 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20535 MVT VT = Op.getSimpleValueType();
20536 MVT NVT = VT.changeElementType(MVT::f32);
20537
20538 SDValue Rnd = DAG.getIntPtrConstant(0, dl, /*isTarget=*/true);
20539 if (IsStrict)
20540 return DAG.getNode(
20541 ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
20542 {Chain,
20543 DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
20544 Rnd});
20545 return DAG.getNode(ISD::FP_ROUND, dl, VT,
20546 DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
20547}
20548
20549static bool isLegalConversion(MVT VT, MVT FloatVT, bool IsSigned,
20550 const X86Subtarget &Subtarget) {
20551 if (FloatVT.getScalarType() != MVT::f16 || Subtarget.hasVLX()) {
20552 if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
20553 return true;
20554 if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
20555 return true;
20556 }
20557 if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
20558 return true;
20559 if (Subtarget.useAVX512Regs()) {
20560 if (VT == MVT::v16i32)
20561 return true;
20562 if (VT == MVT::v8i64 && FloatVT == MVT::v8f16 && Subtarget.hasFP16())
20563 return true;
20564 if (VT == MVT::v8i64 && Subtarget.hasDQI())
20565 return true;
20566 }
20567 if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
20568 (VT == MVT::v2i64 || VT == MVT::v4i64))
20569 return true;
20570 return false;
20571}
20572
20573SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20574 SelectionDAG &DAG) const {
20575 bool IsStrict = Op->isStrictFPOpcode();
20576 unsigned OpNo = IsStrict ? 1 : 0;
20577 SDValue Src = Op.getOperand(OpNo);
20578 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20579 MVT SrcVT = Src.getSimpleValueType();
20580 MVT VT = Op.getSimpleValueType();
20581 SDLoc dl(Op);
20582
20583 if (isBF16orSoftF16(VT, Subtarget))
20584 return promoteXINT_TO_FP(Op, dl, DAG);
20585 else if (isLegalConversion(SrcVT, VT, true, Subtarget))
20586 return Op;
20587
20588 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
20589 return LowerWin64_INT128_TO_FP(Op, DAG);
20590
20591 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
20592 return Extract;
20593
20594 if (SDValue R = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
20595 return R;
20596
20597 if (SrcVT.isVector()) {
20598 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
20599 // Note: Since v2f64 is a legal type. We don't need to zero extend the
20600 // source for strict FP.
20601 if (IsStrict)
20602 return DAG.getNode(
20603 X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
20604 {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20605 DAG.getUNDEF(SrcVT))});
20606 return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
20607 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20608 DAG.getUNDEF(SrcVT)));
20609 }
20610 if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
20611 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
20612
20613 return SDValue();
20614 }
20615
20616 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
20617 "Unknown SINT_TO_FP to lower!");
20618
20619 bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
20620
20621 // These are really Legal; return the operand so the caller accepts it as
20622 // Legal.
20623 if (SrcVT == MVT::i32 && UseSSEReg)
20624 return Op;
20625 if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
20626 return Op;
20627
20628 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
20629 return V;
20630 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
20631 return V;
20632
20633 // SSE doesn't have an i16 conversion so we need to promote.
20634 if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
20635 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
20636 if (IsStrict)
20637 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
20638 {Chain, Ext});
20639
20640 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
20641 }
20642
20643 if (VT == MVT::f128 || !Subtarget.hasX87())
20644 return SDValue();
20645
20646 SDValue ValueToStore = Src;
20647 if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
20648 // Bitcasting to f64 here allows us to do a single 64-bit store from
20649 // an SSE register, avoiding the store forwarding penalty that would come
20650 // with two 32-bit stores.
20651 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20652
20653 unsigned Size = SrcVT.getStoreSize();
20654 Align Alignment(Size);
20655 MachineFunction &MF = DAG.getMachineFunction();
20656 auto PtrVT = getPointerTy(MF.getDataLayout());
20657 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
20658 MachinePointerInfo MPI =
20660 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20661 Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
20662 std::pair<SDValue, SDValue> Tmp =
20663 BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
20664
20665 if (IsStrict)
20666 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20667
20668 return Tmp.first;
20669}
20670
20671std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
20672 EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
20673 MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
20674 // Build the FILD
20675 SDVTList Tys;
20676 bool useSSE = isScalarFPTypeInSSEReg(DstVT);
20677 if (useSSE)
20678 Tys = DAG.getVTList(MVT::f80, MVT::Other);
20679 else
20680 Tys = DAG.getVTList(DstVT, MVT::Other);
20681
20682 SDValue FILDOps[] = {Chain, Pointer};
20683 SDValue Result =
20684 DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
20685 Alignment, MachineMemOperand::MOLoad);
20686 Chain = Result.getValue(1);
20687
20688 if (useSSE) {
20690 unsigned SSFISize = DstVT.getStoreSize();
20691 int SSFI =
20692 MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
20693 auto PtrVT = getPointerTy(MF.getDataLayout());
20694 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20695 Tys = DAG.getVTList(MVT::Other);
20696 SDValue FSTOps[] = {Chain, Result, StackSlot};
20699 MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
20700
20701 Chain =
20702 DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
20703 Result = DAG.getLoad(
20704 DstVT, DL, Chain, StackSlot,
20706 Chain = Result.getValue(1);
20707 }
20708
20709 return { Result, Chain };
20710}
20711
20712/// Horizontal vector math instructions may be slower than normal math with
20713/// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
20714/// implementation, and likely shuffle complexity of the alternate sequence.
20715static bool shouldUseHorizontalOp(bool IsSingleSource, const SelectionDAG &DAG,
20716 const X86Subtarget &Subtarget) {
20717 bool IsOptimizingSize = DAG.shouldOptForSize();
20718 bool HasFastHOps = Subtarget.hasFastHorizontalOps();
20719 return !IsSingleSource || IsOptimizingSize || HasFastHOps;
20720}
20721
20722/// 64-bit unsigned integer to double expansion.
20724 SelectionDAG &DAG,
20725 const X86Subtarget &Subtarget) {
20726 // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
20727 // when converting 0 when rounding toward negative infinity. Caller will
20728 // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
20729 assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
20730 // This algorithm is not obvious. Here it is what we're trying to output:
20731 /*
20732 movq %rax, %xmm0
20733 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
20734 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
20735 #ifdef __SSE3__
20736 haddpd %xmm0, %xmm0
20737 #else
20738 pshufd $0x4e, %xmm0, %xmm1
20739 addpd %xmm1, %xmm0
20740 #endif
20741 */
20742
20743 LLVMContext *Context = DAG.getContext();
20744
20745 // Build some magic constants.
20746 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
20747 Constant *C0 = ConstantDataVector::get(*Context, CV0);
20748 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20749 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
20750
20752 CV1.push_back(
20753 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20754 APInt(64, 0x4330000000000000ULL))));
20755 CV1.push_back(
20756 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20757 APInt(64, 0x4530000000000000ULL))));
20758 Constant *C1 = ConstantVector::get(CV1);
20759 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
20760
20761 // Load the 64-bit value into an XMM register.
20762 SDValue XR1 =
20763 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
20764 SDValue CLod0 = DAG.getLoad(
20765 MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
20767 SDValue Unpck1 =
20768 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
20769
20770 SDValue CLod1 = DAG.getLoad(
20771 MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
20773 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
20774 // TODO: Are there any fast-math-flags to propagate here?
20775 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
20776 SDValue Result;
20777
20778 if (Subtarget.hasSSE3() &&
20779 shouldUseHorizontalOp(true, DAG, Subtarget)) {
20780 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
20781 } else {
20782 SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
20783 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
20784 }
20785 Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
20786 DAG.getVectorIdxConstant(0, dl));
20787 return Result;
20788}
20789
20790/// 32-bit unsigned integer to float expansion.
20792 SelectionDAG &DAG,
20793 const X86Subtarget &Subtarget) {
20794 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20795 // FP constant to bias correct the final result.
20796 SDValue Bias = DAG.getConstantFP(
20797 llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::f64);
20798
20799 // Load the 32-bit value into an XMM register.
20800 SDValue Load =
20801 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
20802
20803 // Zero out the upper parts of the register.
20804 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
20805
20806 // Or the load with the bias.
20807 SDValue Or = DAG.getNode(
20808 ISD::OR, dl, MVT::v2i64,
20809 DAG.getBitcast(MVT::v2i64, Load),
20810 DAG.getBitcast(MVT::v2i64,
20811 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
20812 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
20813 DAG.getBitcast(MVT::v2f64, Or),
20814 DAG.getVectorIdxConstant(0, dl));
20815
20816 if (Op.getNode()->isStrictFPOpcode()) {
20817 // Subtract the bias.
20818 // TODO: Are there any fast-math-flags to propagate here?
20819 SDValue Chain = Op.getOperand(0);
20820 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
20821 {Chain, Or, Bias});
20822
20823 if (Op.getValueType() == Sub.getValueType())
20824 return Sub;
20825
20826 // Handle final rounding.
20827 std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
20828 Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
20829
20830 return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
20831 }
20832
20833 // Subtract the bias.
20834 // TODO: Are there any fast-math-flags to propagate here?
20835 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
20836
20837 // Handle final rounding.
20838 return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
20839}
20840
20842 SelectionDAG &DAG,
20843 const X86Subtarget &Subtarget) {
20844 if (Op.getSimpleValueType() != MVT::v2f64)
20845 return SDValue();
20846
20847 bool IsStrict = Op->isStrictFPOpcode();
20848
20849 SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
20850 assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
20851
20852 if (Subtarget.hasAVX512()) {
20853 if (!Subtarget.hasVLX()) {
20854 // Let generic type legalization widen this.
20855 if (!IsStrict)
20856 return SDValue();
20857 // Otherwise pad the integer input with 0s and widen the operation.
20858 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20859 DAG.getConstant(0, DL, MVT::v2i32));
20860 SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
20861 {Op.getOperand(0), N0});
20862 SDValue Chain = Res.getValue(1);
20863 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
20864 DAG.getVectorIdxConstant(0, DL));
20865 return DAG.getMergeValues({Res, Chain}, DL);
20866 }
20867
20868 // Legalize to v4i32 type.
20869 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20870 DAG.getUNDEF(MVT::v2i32));
20871 if (IsStrict)
20872 return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
20873 {Op.getOperand(0), N0});
20874 return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
20875 }
20876
20877 // Zero extend to 2i64, OR with the floating point representation of 2^52.
20878 // This gives us the floating point equivalent of 2^52 + the i32 integer
20879 // since double has 52-bits of mantissa. Then subtract 2^52 in floating
20880 // point leaving just our i32 integers in double format.
20881 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
20882 SDValue VBias = DAG.getConstantFP(
20883 llvm::bit_cast<double>(0x4330000000000000ULL), DL, MVT::v2f64);
20884 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
20885 DAG.getBitcast(MVT::v2i64, VBias));
20886 Or = DAG.getBitcast(MVT::v2f64, Or);
20887
20888 if (IsStrict)
20889 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
20890 {Op.getOperand(0), Or, VBias});
20891 return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
20892}
20893
20895 SelectionDAG &DAG,
20896 const X86Subtarget &Subtarget) {
20897 bool IsStrict = Op->isStrictFPOpcode();
20898 SDValue V = Op->getOperand(IsStrict ? 1 : 0);
20899 MVT VecIntVT = V.getSimpleValueType();
20900 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
20901 "Unsupported custom type");
20902
20903 if (Subtarget.hasAVX512()) {
20904 // With AVX512, but not VLX we need to widen to get a 512-bit result type.
20905 assert(!Subtarget.hasVLX() && "Unexpected features");
20906 MVT VT = Op->getSimpleValueType(0);
20907
20908 // v8i32->v8f64 is legal with AVX512 so just return it.
20909 if (VT == MVT::v8f64)
20910 return Op;
20911
20912 assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64 ||
20913 VT == MVT::v8f16) &&
20914 "Unexpected VT!");
20915 MVT WideVT = VT == MVT::v8f16 ? MVT::v16f16 : MVT::v16f32;
20916 MVT WideIntVT = MVT::v16i32;
20917 if (VT == MVT::v4f64) {
20918 WideVT = MVT::v8f64;
20919 WideIntVT = MVT::v8i32;
20920 }
20921
20922 // Need to concat with zero vector for strict fp to avoid spurious
20923 // exceptions.
20924 SDValue Tmp =
20925 IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
20926 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
20927 DAG.getVectorIdxConstant(0, DL));
20928 SDValue Res, Chain;
20929 if (IsStrict) {
20930 Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
20931 {Op->getOperand(0), V});
20932 Chain = Res.getValue(1);
20933 } else {
20934 Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
20935 }
20936
20937 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20938 DAG.getVectorIdxConstant(0, DL));
20939
20940 if (IsStrict)
20941 return DAG.getMergeValues({Res, Chain}, DL);
20942 return Res;
20943 }
20944
20945 if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
20946 Op->getSimpleValueType(0) == MVT::v4f64) {
20947 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
20948 Constant *Bias = ConstantFP::get(
20949 *DAG.getContext(),
20950 APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
20951 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20952 SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
20953 SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
20954 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
20955 SDValue VBias = DAG.getMemIntrinsicNode(
20956 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
20959
20960 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
20961 DAG.getBitcast(MVT::v4i64, VBias));
20962 Or = DAG.getBitcast(MVT::v4f64, Or);
20963
20964 if (IsStrict)
20965 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
20966 {Op.getOperand(0), Or, VBias});
20967 return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20968 }
20969
20970 // The algorithm is the following:
20971 // #ifdef __SSE4_1__
20972 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20973 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20974 // (uint4) 0x53000000, 0xaa);
20975 // #else
20976 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20977 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20978 // #endif
20979 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20980 // return (float4) lo + fhi;
20981
20982 bool Is128 = VecIntVT == MVT::v4i32;
20983 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
20984 // If we convert to something else than the supported type, e.g., to v4f64,
20985 // abort early.
20986 if (VecFloatVT != Op->getSimpleValueType(0))
20987 return SDValue();
20988
20989 // In the #idef/#else code, we have in common:
20990 // - The vector of constants:
20991 // -- 0x4b000000
20992 // -- 0x53000000
20993 // - A shift:
20994 // -- v >> 16
20995
20996 // Create the splat vector for 0x4b000000.
20997 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
20998 // Create the splat vector for 0x53000000.
20999 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
21000
21001 // Create the right shift.
21002 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
21003 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
21004
21005 SDValue Low, High;
21006 if (Subtarget.hasSSE41()) {
21007 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
21008 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
21009 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
21010 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
21011 // Low will be bitcasted right away, so do not bother bitcasting back to its
21012 // original type.
21013 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
21014 VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21015 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
21016 // (uint4) 0x53000000, 0xaa);
21017 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
21018 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
21019 // High will be bitcasted right away, so do not bother bitcasting back to
21020 // its original type.
21021 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
21022 VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
21023 } else {
21024 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
21025 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
21026 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
21027 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
21028
21029 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
21030 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
21031 }
21032
21033 // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
21034 SDValue VecCstFSub = DAG.getConstantFP(
21035 APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
21036
21037 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
21038 // NOTE: By using fsub of a positive constant instead of fadd of a negative
21039 // constant, we avoid reassociation in MachineCombiner when reassoc is
21040 // enabled. See PR24512.
21041 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
21042 // TODO: Are there any fast-math-flags to propagate here?
21043 // (float4) lo;
21044 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
21045 // return (float4) lo + fhi;
21046 if (IsStrict) {
21047 SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
21048 {Op.getOperand(0), HighBitcast, VecCstFSub});
21049 return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
21050 {FHigh.getValue(1), LowBitcast, FHigh});
21051 }
21052
21053 SDValue FHigh =
21054 DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
21055 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
21056}
21057
21059 const X86Subtarget &Subtarget) {
21060 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
21061 SDValue N0 = Op.getOperand(OpNo);
21062 MVT SrcVT = N0.getSimpleValueType();
21063
21064 switch (SrcVT.SimpleTy) {
21065 default:
21066 llvm_unreachable("Custom UINT_TO_FP is not supported!");
21067 case MVT::v2i32:
21068 return lowerUINT_TO_FP_v2i32(Op, dl, DAG, Subtarget);
21069 case MVT::v4i32:
21070 case MVT::v8i32:
21071 return lowerUINT_TO_FP_vXi32(Op, dl, DAG, Subtarget);
21072 case MVT::v2i64:
21073 case MVT::v4i64:
21074 return lowerINT_TO_FP_vXi64(Op, dl, DAG, Subtarget);
21075 }
21076}
21077
21078SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
21079 SelectionDAG &DAG) const {
21080 bool IsStrict = Op->isStrictFPOpcode();
21081 unsigned OpNo = IsStrict ? 1 : 0;
21082 SDValue Src = Op.getOperand(OpNo);
21083 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21084 auto PtrVT = getPointerTy(DAG.getDataLayout());
21085 MVT SrcVT = Src.getSimpleValueType();
21086 MVT DstVT = Op->getSimpleValueType(0);
21087 SDLoc dl(Op);
21088
21089 if (isBF16orSoftF16(DstVT, Subtarget))
21090 return promoteXINT_TO_FP(Op, dl, DAG);
21091 else if (isLegalConversion(SrcVT, DstVT, false, Subtarget))
21092 return Op;
21093
21094 if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
21095 return LowerWin64_INT128_TO_FP(Op, DAG);
21096
21097 if (SDValue Extract = vectorizeExtractedCast(Op, dl, DAG, Subtarget))
21098 return Extract;
21099
21100 if (SDValue V = lowerFPToIntToFP(Op, dl, DAG, Subtarget))
21101 return V;
21102
21103 if (DstVT.isVector())
21104 return lowerUINT_TO_FP_vec(Op, dl, DAG, Subtarget);
21105
21106 // Bail out when we don't have native conversion instructions.
21107 if (DstVT == MVT::f128)
21108 return SDValue();
21109
21110 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
21111 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
21112 // Conversions from unsigned i32 to f32/f64 are legal,
21113 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
21114 return Op;
21115 }
21116
21117 // Promote i32 to i64 and use a signed conversion on 64-bit targets.
21118 if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
21119 Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
21120 if (IsStrict)
21121 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
21122 {Chain, Src});
21123 return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
21124 }
21125
21126 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, dl, DAG, Subtarget))
21127 return V;
21128 if (SDValue V = LowerI64IntToFP16(Op, dl, DAG, Subtarget))
21129 return V;
21130
21131 // The transform for i64->f64 isn't correct for 0 when rounding to negative
21132 // infinity. It produces -0.0, so disable under strictfp.
21133 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
21134 !IsStrict)
21135 return LowerUINT_TO_FP_i64(Op, dl, DAG, Subtarget);
21136 // The transform for i32->f64/f32 isn't correct for 0 when rounding to
21137 // negative infinity. So disable under strictfp. Using FILD instead.
21138 if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
21139 !IsStrict)
21140 return LowerUINT_TO_FP_i32(Op, dl, DAG, Subtarget);
21141 if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
21142 (DstVT == MVT::f32 || DstVT == MVT::f64))
21143 return SDValue();
21144
21145 // Make a 64-bit buffer, and use it to build an FILD.
21146 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
21147 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
21148 Align SlotAlign(8);
21149 MachinePointerInfo MPI =
21151 if (SrcVT == MVT::i32) {
21152 SDValue OffsetSlot =
21153 DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
21154 SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
21155 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
21156 OffsetSlot, MPI.getWithOffset(4), SlotAlign);
21157 std::pair<SDValue, SDValue> Tmp =
21158 BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
21159 if (IsStrict)
21160 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
21161
21162 return Tmp.first;
21163 }
21164
21165 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
21166 SDValue ValueToStore = Src;
21167 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
21168 // Bitcasting to f64 here allows us to do a single 64-bit store from
21169 // an SSE register, avoiding the store forwarding penalty that would come
21170 // with two 32-bit stores.
21171 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
21172 }
21173 SDValue Store =
21174 DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
<