LLVM 24.0.0git
LoongArchISelLowering.cpp
Go to the documentation of this file.
1//=- LoongArchISelLowering.cpp - LoongArch 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 LoongArch uses to lower LLVM code into
10// a selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
15#include "LoongArch.h"
19#include "LoongArchSubtarget.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/IntrinsicsLoongArch.h"
34#include "llvm/Support/Debug.h"
39
40using namespace llvm;
41
42#define DEBUG_TYPE "loongarch-isel-lowering"
43
44STATISTIC(NumTailCalls, "Number of tail calls");
45
54
56 "loongarch-materialize-float-imm", cl::Hidden,
57 cl::desc("Maximum number of instructions used (including code sequence "
58 "to generate the value and moving the value to FPR) when "
59 "materializing floating-point immediates (default = 3)"),
61 cl::values(clEnumValN(NoMaterializeFPImm, "0", "Use constant pool"),
63 "Materialize FP immediate within 2 instructions"),
65 "Materialize FP immediate within 3 instructions"),
67 "Materialize FP immediate within 4 instructions"),
69 "Materialize FP immediate within 5 instructions"),
71 "Materialize FP immediate within 6 instructions "
72 "(behaves same as 5 on loongarch64)")));
73
74static cl::opt<bool> ZeroDivCheck("loongarch-check-zero-division", cl::Hidden,
75 cl::desc("Trap on integer division by zero."),
76 cl::init(false));
77
79 const LoongArchSubtarget &STI)
80 : TargetLowering(TM, STI), Subtarget(STI) {
81
82 MVT GRLenVT = Subtarget.getGRLenVT();
83
84 // Set up the register classes.
85
86 addRegisterClass(GRLenVT, &LoongArch::GPRRegClass);
87 if (Subtarget.hasBasicF())
88 addRegisterClass(MVT::f32, &LoongArch::FPR32RegClass);
89 if (Subtarget.hasBasicD())
90 addRegisterClass(MVT::f64, &LoongArch::FPR64RegClass);
91
92 static const MVT::SimpleValueType LSXVTs[] = {
93 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32, MVT::v2f64};
94 static const MVT::SimpleValueType LASXVTs[] = {
95 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64, MVT::v8f32, MVT::v4f64};
96
97 if (Subtarget.hasExtLSX())
98 for (MVT VT : LSXVTs)
99 addRegisterClass(VT, &LoongArch::LSX128RegClass);
100
101 if (Subtarget.hasExtLASX())
102 for (MVT VT : LASXVTs)
103 addRegisterClass(VT, &LoongArch::LASX256RegClass);
104
105 // Set operations for LA32 and LA64.
106
108 MVT::i1, Promote);
109
114 if (Subtarget.hasBasicF())
118
121 GRLenVT, Custom);
122
124
129
131 setOperationAction(ISD::TRAP, MVT::Other, Legal);
132
136
138
139 // BITREV/REVB requires the 32S feature.
140 if (STI.has32S()) {
141 // Expand bitreverse.i16 with native-width bitrev and shift for now, before
142 // we get to know which of sll and revb.2h is faster.
145
146 // LA32 does not have REVB.2W and REVB.D due to the 64-bit operands, and
147 // the narrower REVB.W does not exist. But LA32 does have REVB.2H, so i16
148 // and i32 could still be byte-swapped relatively cheaply.
150 } else {
158 }
159
166
169
170 // Set operations for LA64 only.
171
172 if (Subtarget.is64Bit()) {
190
194 Custom);
196 }
197
198 // Set operations for LA32 only.
199
200 if (!Subtarget.is64Bit()) {
206 if (Subtarget.hasBasicD())
208 }
209
211
212 static const ISD::CondCode FPCCToExpand[] = {
215
216 // Set operations for 'F' feature.
217
218 if (Subtarget.hasBasicF()) {
219 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
220 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
222 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
223 setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
224
243 Subtarget.isSoftFPABI() ? LibCall : Custom);
245 Subtarget.isSoftFPABI() ? LibCall : Custom);
248 Subtarget.isSoftFPABI() ? LibCall : Custom);
251
252 if (Subtarget.is64Bit())
254
255 if (!Subtarget.hasBasicD()) {
257 if (Subtarget.is64Bit()) {
260 }
261 }
262 }
263
264 // Set operations for 'D' feature.
265
266 if (Subtarget.hasBasicD()) {
267 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
268 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
269 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
270 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
271 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
272 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
273 setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
274
294 Subtarget.isSoftFPABI() ? LibCall : Custom);
297 Subtarget.isSoftFPABI() ? LibCall : Custom);
298
299 if (Subtarget.is64Bit())
301 }
302
303 // Set operations for 'LSX' feature.
304
305 if (Subtarget.hasExtLSX()) {
307 // Expand all truncating stores and extending loads.
308 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
309 setTruncStoreAction(VT, InnerVT, Expand);
312 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
313 }
314 // By default everything must be expanded. Then we will selectively turn
315 // on ones that can be effectively codegen'd.
316 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
318 }
319
320 for (MVT VT : LSXVTs) {
324
328
333 }
334 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
337 Legal);
339 VT, Legal);
346 Expand);
361 }
362 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
364 for (MVT VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64})
366 for (MVT VT : {MVT::v4i32, MVT::v2i64}) {
370 }
372 for (MVT VT : {MVT::v4f32, MVT::v2f64}) {
380 VT, Expand);
388 }
390 setOperationAction(ISD::FCEIL, {MVT::f32, MVT::f64}, Legal);
391 setOperationAction(ISD::FFLOOR, {MVT::f32, MVT::f64}, Legal);
392 setOperationAction(ISD::FTRUNC, {MVT::f32, MVT::f64}, Legal);
393 setOperationAction(ISD::FROUNDEVEN, {MVT::f32, MVT::f64}, Legal);
394
395 for (MVT VT :
396 {MVT::v16i8, MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v8i16, MVT::v4i16,
397 MVT::v2i16, MVT::v4i32, MVT::v2i32, MVT::v2i64}) {
407 }
410 // We want to legalize this to an f64 load rather than an i64 load.
411 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
412 for (MVT VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16})
414 for (MVT VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64, MVT::v16i32, MVT::v8i64,
415 MVT::v16i64})
417
418 static const unsigned MLAOps[] = {ISD::PARTIAL_REDUCE_SMLA,
421
422 setPartialReduceMLAAction(MLAOps, MVT::v4i32, MVT::v16i8, Legal);
423 }
424
425 // Set operations for 'LASX' feature.
426
427 if (Subtarget.hasExtLASX()) {
428 for (MVT VT : LASXVTs) {
432
438
442 }
443 for (MVT VT : {MVT::v4i64, MVT::v8i32, MVT::v16i16, MVT::v32i8}) {
446 Legal);
448 VT, Legal);
455 Expand);
471 }
472 for (MVT VT : {MVT::v32i8, MVT::v16i16, MVT::v8i32})
474 for (MVT VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64})
476 for (MVT VT : {MVT::v8i32, MVT::v4i64})
478 for (MVT VT : {MVT::v8i32, MVT::v4i32, MVT::v4i64}) {
482 }
483 for (MVT VT : {MVT::v8f32, MVT::v4f64}) {
491 VT, Expand);
499 }
502 for (MVT VT : {MVT::v4i64, MVT::v8i32, MVT::v16i16}) {
506 }
507 for (MVT VT :
508 {MVT::v2i64, MVT::v4i32, MVT::v4i64, MVT::v8i16, MVT::v8i32}) {
511 }
512 for (MVT VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
514
515 static const unsigned MLAOps[] = {ISD::PARTIAL_REDUCE_SMLA,
518
519 setPartialReduceMLAAction(MLAOps, MVT::v8i32, MVT::v32i8, Legal);
520 }
521
522 // Set DAG combine for LA32 and LA64.
523 if (Subtarget.hasBasicF()) {
525 }
526
534
535 // On targets with the 32S feature, `select` is expanded into
536 // maskeqz + masknez + or (3 instructions), which is more expensive than
537 // on most other architectures where a single cmov-like instruction
538 // suffices. Enable a combine that can turn
539 // select cond, binop(X, Y), X -> binop X, (select cond, Y, 0)
540 // select cond, X, binop(X, Y) -> binop X, (select cond, 0, Y)
541 // for binop in {add, or, xor, sub}, replacing the 3-insn select (plus
542 // the original binop) with a single mask instruction plus the binop.
543 if (Subtarget.has32S())
545
546 // Set DAG combine for 'LSX' feature.
547
548 if (Subtarget.hasExtLSX()) {
562 }
563
564 // Set DAG combine for 'LASX' feature.
565 if (Subtarget.hasExtLASX()) {
568 }
569
570 // Compute derived properties from the register classes.
571 computeRegisterProperties(Subtarget.getRegisterInfo());
572
574
577
578 setMaxAtomicSizeInBitsSupported(Subtarget.getGRLen());
579
581
582 // Function alignments.
584 // Set preferred alignments.
585 setPrefFunctionAlignment(Subtarget.getPrefFunctionAlignment());
586 setPrefLoopAlignment(Subtarget.getPrefLoopAlignment());
587 setMaxBytesForAlignment(Subtarget.getMaxBytesForAlignment());
588
589 // cmpxchg sizes down to 8 bits become legal if LAMCAS is available.
590 if (Subtarget.hasLAMCAS())
592
593 if (Subtarget.hasSCQ()) {
596 }
597
598 // Disable strict node mutation.
599 IsStrictFPEnabled = true;
600}
601
603 const GlobalAddressSDNode *GA) const {
604 // In order to maximise the opportunity for common subexpression elimination,
605 // keep a separate ADD node for the global address offset instead of folding
606 // it in the global address node. Later peephole optimisations may choose to
607 // fold it back in when profitable.
608 return false;
609}
610
612 SelectionDAG &DAG) const {
613 switch (Op.getOpcode()) {
615 return lowerATOMIC_FENCE(Op, DAG);
617 return lowerEH_DWARF_CFA(Op, DAG);
619 return lowerGlobalAddress(Op, DAG);
621 return lowerGlobalTLSAddress(Op, DAG);
623 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
625 return lowerINTRINSIC_W_CHAIN(Op, DAG);
627 return lowerINTRINSIC_VOID(Op, DAG);
629 return lowerBlockAddress(Op, DAG);
630 case ISD::JumpTable:
631 return lowerJumpTable(Op, DAG);
632 case ISD::SHL_PARTS:
633 return lowerShiftLeftParts(Op, DAG);
634 case ISD::SRA_PARTS:
635 return lowerShiftRightParts(Op, DAG, true);
636 case ISD::SRL_PARTS:
637 return lowerShiftRightParts(Op, DAG, false);
639 return lowerConstantPool(Op, DAG);
640 case ISD::FP_TO_SINT:
641 return lowerFP_TO_SINT(Op, DAG);
642 case ISD::FP_TO_UINT:
643 return lowerFP_TO_UINT(Op, DAG);
645 return lowerFP_TO_SINT_SAT(Op, DAG);
646 case ISD::BITCAST:
647 return lowerBITCAST(Op, DAG);
648 case ISD::UINT_TO_FP:
649 return lowerUINT_TO_FP(Op, DAG);
650 case ISD::SINT_TO_FP:
651 return lowerSINT_TO_FP(Op, DAG);
652 case ISD::VASTART:
653 return lowerVASTART(Op, DAG);
654 case ISD::FRAMEADDR:
655 return lowerFRAMEADDR(Op, DAG);
656 case ISD::RETURNADDR:
657 return lowerRETURNADDR(Op, DAG);
659 return lowerSET_ROUNDING(Op, DAG);
661 return lowerGET_ROUNDING(Op, DAG);
663 return lowerWRITE_REGISTER(Op, DAG);
665 return lowerINSERT_VECTOR_ELT(Op, DAG);
667 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
669 return lowerBUILD_VECTOR(Op, DAG);
671 return lowerCONCAT_VECTORS(Op, DAG);
673 return lowerVECTOR_SHUFFLE(Op, DAG);
674 case ISD::BITREVERSE:
675 return lowerBITREVERSE(Op, DAG);
677 return lowerSCALAR_TO_VECTOR(Op, DAG);
678 case ISD::PREFETCH:
679 return lowerPREFETCH(Op, DAG);
680 case ISD::SELECT:
681 return lowerSELECT(Op, DAG);
682 case ISD::BRCOND:
683 return lowerBRCOND(Op, DAG);
684 case ISD::FP_TO_FP16:
685 return lowerFP_TO_FP16(Op, DAG);
686 case ISD::FP16_TO_FP:
687 return lowerFP16_TO_FP(Op, DAG);
688 case ISD::FP_TO_BF16:
689 return lowerFP_TO_BF16(Op, DAG);
690 case ISD::BF16_TO_FP:
691 return lowerBF16_TO_FP(Op, DAG);
693 return lowerVECREDUCE_ADD(Op, DAG);
694 case ISD::ROTL:
695 case ISD::ROTR:
696 return lowerRotate(Op, DAG);
704 return lowerVECREDUCE(Op, DAG);
705 case ISD::ConstantFP:
706 return lowerConstantFP(Op, DAG);
707 case ISD::SETCC:
708 return lowerSETCC(Op, DAG);
709 case ISD::FP_ROUND:
710 return lowerFP_ROUND(Op, DAG);
711 case ISD::FP_EXTEND:
712 return lowerFP_EXTEND(Op, DAG);
714 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
716 return lowerDYNAMIC_STACKALLOC(Op, DAG);
717 case ISD::ANY_EXTEND:
718 return lowerANY_EXTEND(Op, DAG);
719 case ISD::VSELECT:
720 return lowerVSELECT(Op, DAG);
721 }
722 return SDValue();
723}
724
725// Helper to attempt to return a cheaper, bit-inverted version of \p V.
727 // TODO: don't always ignore oneuse constraints.
729 EVT VT = V.getValueType();
730
731 // Match not(xor X, -1) -> X.
732 if (V.getOpcode() == ISD::XOR &&
733 (ISD::isBuildVectorAllOnes(V.getOperand(1)) ||
734 isAllOnesConstant(V.getOperand(1))))
735 return V.getOperand(0);
736
737 // Match not(extract_subvector(not(X)) -> extract_subvector(X).
738 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
739 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
740 if (SDValue Not = isNOT(V.getOperand(0), DAG)) {
741 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
742 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), VT, Not,
743 V.getOperand(1));
744 }
745 }
746
747 // Match not(SplatVector(not(X)) -> SplatVector(X).
748 if (V.getOpcode() == ISD::BUILD_VECTOR) {
749 if (SDValue SplatValue =
750 cast<BuildVectorSDNode>(V.getNode())->getSplatValue()) {
751 if (!V->isOnlyUserOf(SplatValue.getNode()))
752 return SDValue();
753
754 if (SDValue Not = isNOT(SplatValue, DAG)) {
755 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
756 return DAG.getSplat(VT, SDLoc(Not), Not);
757 }
758 }
759 }
760
761 // Match not(or(not(X),not(Y))) -> and(X, Y).
762 if (V.getOpcode() == ISD::OR && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
763 V.getOperand(0).hasOneUse() && V.getOperand(1).hasOneUse()) {
764 // TODO: Handle cases with single NOT operand -> VANDN
765 if (SDValue Op1 = isNOT(V.getOperand(1), DAG))
766 if (SDValue Op0 = isNOT(V.getOperand(0), DAG))
767 return DAG.getNode(ISD::AND, SDLoc(V), VT, DAG.getBitcast(VT, Op0),
768 DAG.getBitcast(VT, Op1));
769 }
770
771 // TODO: Add more matching patterns. Such as,
772 // not(concat_vectors(not(X), not(Y))) -> concat_vectors(X, Y).
773 // not(slt(C, X)) -> slt(X - 1, C)
774 return SDValue();
775}
776
777// Combine two ISD::FP_ROUND / LoongArchISD::VFCVT nodes with same type to
778// LoongArchISD::VFCVT. For example:
779// x1 = fp_round x, 0
780// y1 = fp_round y, 0
781// z = concat_vectors x1, y1
782// Or
783// x1 = LoongArch::VFCVT undef, x
784// y1 = LoongArch::VFCVT undef, y
785// z = LoongArchISD::VPACKEV y1, x1; or LoongArchISD::VPERMI y1, x1, 68
786// can be combined to:
787// z = LoongArch::VFCVT y, x
790 assert(((N->getOpcode() == ISD::CONCAT_VECTORS && N->getNumOperands() == 2) ||
791 (N->getOpcode() == LoongArchISD::VPACKEV) ||
792 (N->getOpcode() == LoongArchISD::VPERMI)) &&
793 "Invalid Node");
794
795 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
796 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
797 unsigned Opcode0 = Op0.getOpcode();
798 unsigned Opcode1 = Op1.getOpcode();
799 if (Opcode0 != Opcode1)
800 return SDValue();
801
802 if (Opcode0 != ISD::FP_ROUND && Opcode0 != LoongArchISD::VFCVT)
803 return SDValue();
804
805 // Check if two nodes have only one use.
806 if (!Op0.hasOneUse() || !Op1.hasOneUse())
807 return SDValue();
808
809 EVT VT = N.getValueType();
810 EVT SVT0 = Op0.getValueType();
811 EVT SVT1 = Op1.getValueType();
812 // Check if two nodes have the same result type.
813 if (SVT0 != SVT1)
814 return SDValue();
815
816 // Check if two nodes have the same operand type.
817 EVT SSVT0 = Op0.getOperand(0).getValueType();
818 EVT SSVT1 = Op1.getOperand(0).getValueType();
819 if (SSVT0 != SSVT1)
820 return SDValue();
821
822 if (N->getOpcode() == ISD::CONCAT_VECTORS && Opcode0 == ISD::FP_ROUND) {
823 if (Subtarget.hasExtLASX() && VT.is256BitVector() && SVT0 == MVT::v4f32 &&
824 SSVT0 == MVT::v4f64) {
825 // A vector_shuffle is required in the final step, as xvfcvt instruction
826 // operates on each 128-bit segament as a lane.
827 SDValue Res = DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v8f32,
828 Op1.getOperand(0), Op0.getOperand(0));
829 SDValue Undef = DAG.getUNDEF(Res.getValueType());
830 // After VFCVT, the high part of Res comes from the high parts of Op0 and
831 // Op1, and the low part comes from the low parts of Op0 and Op1. However,
832 // the desired order requires Op0 to fully occupy the lower half and Op1
833 // the upper half of Res. The Mask reorders the elements of Res to achieve
834 // this:
835 // - The first four elements (0, 1, 4, 5) come from Op0.
836 // - The next four elements (2, 3, 6, 7) come from Op1.
837 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
838 Res = DAG.getVectorShuffle(Res.getValueType(), DL, Res, Undef, Mask);
839 return DAG.getBitcast(VT, Res);
840 }
841 }
842
843 if ((N->getOpcode() == LoongArchISD::VPACKEV ||
844 N->getOpcode() == LoongArchISD::VPERMI) &&
845 Opcode0 == LoongArchISD::VFCVT) {
846 // For VPACKEV or VPERMI, check if the first operation of VFCVT is undef.
847 if (!Op0.getOperand(0).isUndef() || !Op1.getOperand(0).isUndef())
848 return SDValue();
849
850 if (!Subtarget.hasExtLSX() || SVT0 != MVT::v4f32 || SSVT0 != MVT::v2f64)
851 return SDValue();
852
853 if (N->getOpcode() == LoongArchISD::VPACKEV &&
854 (VT == MVT::v2i64 || VT == MVT::v2f64)) {
855 SDValue Res = DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32,
856 Op0.getOperand(1), Op1.getOperand(1));
857 return DAG.getBitcast(VT, Res);
858 }
859
860 if (N->getOpcode() == LoongArchISD::VPERMI && VT == MVT::v4f32) {
861 int64_t Imm = cast<ConstantSDNode>(N->getOperand(2))->getSExtValue();
862 if (Imm != 68)
863 return SDValue();
864 return DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32, Op0.getOperand(1),
865 Op1.getOperand(1));
866 }
867 }
868
869 return SDValue();
870}
871
872SDValue LoongArchTargetLowering::lowerFP_ROUND(SDValue Op,
873 SelectionDAG &DAG) const {
874 SDLoc DL(Op);
875 SDValue In = Op.getOperand(0);
876 MVT VT = Op.getSimpleValueType();
877 MVT SVT = In.getSimpleValueType();
878
879 if (VT == MVT::v4f32 && SVT == MVT::v4f64) {
880 SDValue Lo, Hi;
881 std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
882 return DAG.getNode(LoongArchISD::VFCVT, DL, VT, Hi, Lo);
883 }
884
885 return SDValue();
886}
887
888SDValue LoongArchTargetLowering::lowerFP_EXTEND(SDValue Op,
889 SelectionDAG &DAG) const {
890
891 SDLoc DL(Op);
892 EVT VT = Op.getValueType();
893 SDValue Src = Op->getOperand(0);
894 EVT SVT = Src.getValueType();
895
896 bool V2F32ToV2F64 =
897 VT == MVT::v2f64 && SVT == MVT::v2f32 && Subtarget.hasExtLSX();
898 bool V4F32ToV4F64 =
899 VT == MVT::v4f64 && SVT == MVT::v4f32 && Subtarget.hasExtLASX();
900 if (!V2F32ToV2F64 && !V4F32ToV4F64)
901 return SDValue();
902
903 // Check if Op is the high part of vector.
904 auto CheckVecHighPart = [](SDValue Op) {
906 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
907 SDValue SOp = Op.getOperand(0);
908 EVT SVT = SOp.getValueType();
909 if (!SVT.isVector() || (SVT.getVectorNumElements() % 2 != 0))
910 return SDValue();
911
912 const uint64_t Imm = Op.getConstantOperandVal(1);
913 if (Imm == SVT.getVectorNumElements() / 2)
914 return SOp;
915 return SDValue();
916 }
917 return SDValue();
918 };
919
920 unsigned Opcode;
921 SDValue VFCVTOp;
922 EVT WideOpVT = SVT.getSimpleVT().getDoubleNumVectorElementsVT();
923 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
924
925 // If the operand of ISD::FP_EXTEND comes from the high part of vector,
926 // generate LoongArchISD::VFCVTH, otherwise LoongArchISD::VFCVTL.
927 if (SDValue V = CheckVecHighPart(Src)) {
928 assert(V.getValueSizeInBits() == WideOpVT.getSizeInBits() &&
929 "Unexpected wide vector");
930 Opcode = LoongArchISD::VFCVTH;
931 VFCVTOp = DAG.getBitcast(WideOpVT, V);
932 } else {
933 Opcode = LoongArchISD::VFCVTL;
934 VFCVTOp = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideOpVT,
935 DAG.getUNDEF(WideOpVT), Src, ZeroIdx);
936 }
937
938 // v2f64 = fp_extend v2f32
939 if (V2F32ToV2F64)
940 return DAG.getNode(Opcode, DL, VT, VFCVTOp);
941
942 // v4f64 = fp_extend v4f32
943 if (V4F32ToV4F64) {
944 // XVFCVT instruction operates on each 128-bit segment as a lane, so a
945 // vector_shuffle is required firstly.
946 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
947 SDValue Res = DAG.getVectorShuffle(WideOpVT, DL, VFCVTOp,
948 DAG.getUNDEF(WideOpVT), Mask);
949 Res = DAG.getNode(Opcode, DL, VT, Res);
950 return Res;
951 }
952
953 return SDValue();
954}
955
956SDValue LoongArchTargetLowering::lowerVSELECT(SDValue Op,
957 SelectionDAG &DAG) const {
958 SDValue Cond = Op.getOperand(0);
959 SDValue LHS = Op.getOperand(1);
960 SDValue RHS = Op.getOperand(2);
961 MVT VT = Op.getSimpleValueType();
962 SDLoc DL(Op);
963
964 // Try to lower vselect to vector_shuffle. All cases with constant
965 // build_vector condition will be handled. NOTE: On 32-bit platform, vselect
966 // with v2i64/v4i64 type condition will never enter this because of the extra
967 // bitcast. It can be considered separately later.
969 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Cond.getNode());
970 APInt SplatValue, SplatUndef;
971 unsigned SplatBitSize;
972 bool HasAnyUndefs;
973
974 // If the Cond is a BUILD_VECTOR with splat constants, using a vldi or
975 // constant broadcast instruction and a vbitsel is better.
976 if (BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
977 /*MinSplatBits=*/8) &&
978 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
979 SplatBitSize == 64))
980 return Op;
981
983 EVT CondVT = Cond.getValueType();
984 int NumElts = CondVT.getVectorNumElements();
985 Mask.resize(NumElts, -1);
986 for (int i = 0; i < NumElts; ++i) {
987 SDValue CondOp = Cond.getOperand(i);
988 if (CondOp.isUndef())
989 continue;
990 auto *CondElt = dyn_cast<ConstantSDNode>(CondOp);
991 if (CondElt->getZExtValue() == 0)
992 Mask[i] = i + NumElts;
993 else
994 Mask[i] = i;
995 }
996
997 return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
998 }
999
1000 // Fallback to match patterns in tablegen.
1001 return Op;
1002}
1003
1004SDValue LoongArchTargetLowering::lowerConstantFP(SDValue Op,
1005 SelectionDAG &DAG) const {
1006 EVT VT = Op.getValueType();
1007 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
1008 const APFloat &FPVal = CFP->getValueAPF();
1009 SDLoc DL(CFP);
1010
1011 assert((VT == MVT::f32 && Subtarget.hasBasicF()) ||
1012 (VT == MVT::f64 && Subtarget.hasBasicD()));
1013
1014 // If value is 0.0 or -0.0, just ignore it.
1015 if (FPVal.isZero())
1016 return SDValue();
1017
1018 // If lsx enabled, use cheaper 'vldi' instruction if possible.
1019 if (isFPImmVLDILegal(FPVal, VT))
1020 return SDValue();
1021
1022 // The legalizer builds immediates the size of a GPR from their bits. Fall
1023 // back to a load from the constant pool for expensive immediates.
1024 if (VT.getSizeInBits() == Subtarget.getGRLen() ||
1025 !isFPImmCheapInGPR(FPVal, VT))
1026 return SDValue();
1027
1028 // Construct as integer, and move to float register.
1029 APInt INTVal = FPVal.bitcastToAPInt();
1030 if (VT == MVT::f32) {
1031 assert(Subtarget.is64Bit());
1032 SDValue NewVal = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
1033 DAG.getConstant(INTVal, DL, MVT::i32));
1034 return DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, VT, NewVal);
1035 }
1036
1037 assert(VT == MVT::f64 && !Subtarget.is64Bit());
1038 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
1039 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
1040 return DAG.getNode(LoongArchISD::MOVGR2FR_D_LO_HI, DL, VT, Lo, Hi);
1041}
1042
1043// Ensure SETCC result and operand have the same bit width; isel does not
1044// support mismatched widths.
1045SDValue LoongArchTargetLowering::lowerSETCC(SDValue Op,
1046 SelectionDAG &DAG) const {
1047 SDLoc DL(Op);
1048 EVT ResultVT = Op.getValueType();
1049 EVT OperandVT = Op.getOperand(0).getValueType();
1050
1051 EVT SetCCResultVT =
1052 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT);
1053
1054 if (ResultVT == SetCCResultVT)
1055 return Op;
1056
1057 assert(Op.getOperand(0).getValueType() == Op.getOperand(1).getValueType() &&
1058 "SETCC operands must have the same type!");
1059
1060 SDValue SetCCNode =
1061 DAG.getNode(ISD::SETCC, DL, SetCCResultVT, Op.getOperand(0),
1062 Op.getOperand(1), Op.getOperand(2));
1063
1064 if (ResultVT.bitsGT(SetCCResultVT))
1065 SetCCNode = DAG.getNode(ISD::SIGN_EXTEND, DL, ResultVT, SetCCNode);
1066 else if (ResultVT.bitsLT(SetCCResultVT))
1067 SetCCNode = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, SetCCNode);
1068
1069 return SetCCNode;
1070}
1071
1072// Lower SIGN_EXTEND_VECTOR_INREG with VSLLWIL, which sign-extends the low half
1073// of the source elements (and shifts them left by 0).
1074// For example:
1075// %b = sext <8 x i8> %a to <8 x i16>
1076// can be lowered to:
1077// VSLLWIL.H.B vr1, vr1, 0
1078//
1079// VSLLWIL is slower than VILVL and VSRAI, so a 4x extension instead
1080// replicates each source element across its destination element by
1081// interleaving the source with itself twice, then shifts the copy in the top
1082// bits down arithmetically:
1083// %b = sext <4 x i8> %a to <4 x i32>
1084// can be lowered to:
1085// VILVL.B vr1, vr1, vr1
1086// VILVL.H vr1, vr1, vr1
1087// VSRAI.W vr1, vr1, 24
1088//
1089// If every extended source element is already all-ones or all-zeros, e.g. a
1090// comparison result, the interleaves alone produce the sign extension, so
1091// neither VSLLWIL nor the VSRAI is needed:
1092// %b = sext <8 x i8> %mask to <8 x i16>
1093// can be lowered to:
1094// VILVL.B vr1, vr1, vr1
1095SDValue LoongArchTargetLowering::lowerSIGN_EXTEND_VECTOR_INREG(
1096 SDValue Op, SelectionDAG &DAG) const {
1097 SDLoc DL(Op);
1098 SDValue Src = Op.getOperand(0);
1099
1100 // Only whole 128-bit vectors of simple element types can be lowered this
1101 // way; fall back to the default lowering for other sources.
1102 if (!Src.getValueType().isSimple())
1103 return SDValue();
1104 MVT SrcVT = Src.getSimpleValueType();
1105 MVT DstVT = Op.getSimpleValueType();
1106 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
1107 unsigned DstEltBits = DstVT.getScalarSizeInBits();
1108
1109 // Leave larger ratios to the generic shuffle + shift expansion, which only
1110 // needs a single VEXTRINS to move the second element into place.
1111 unsigned Ratio = DstEltBits / SrcEltBits;
1112 if (!SrcVT.is128BitVector() || Ratio > 4)
1113 return SDValue();
1114
1115 // Only the low elements of the source are extended.
1116 APInt DemandedElts = APInt::getLowBitsSet(SrcVT.getVectorNumElements(),
1117 DstVT.getVectorNumElements());
1118 bool IsSignSplat = DAG.ComputeNumSignBits(Src, DemandedElts) == SrcEltBits;
1119
1120 if (Ratio == 2 && !IsSignSplat)
1121 return DAG.getNode(LoongArchISD::VSLLWIL, DL, DstVT, Src,
1122 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
1123
1124 SDValue Res = Src;
1125 for (unsigned EltBits = SrcEltBits; EltBits < DstEltBits; EltBits *= 2) {
1126 MVT VT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), 128 / EltBits);
1127 Res = DAG.getBitcast(VT, Res);
1128 Res = DAG.getNode(LoongArchISD::VILVL, DL, VT, Res, Res);
1129 }
1130 Res = DAG.getBitcast(DstVT, Res);
1131 if (IsSignSplat)
1132 return Res;
1133 return DAG.getNode(ISD::SRA, DL, DstVT, Res,
1134 DAG.getConstant(DstEltBits - SrcEltBits, DL, DstVT));
1135}
1136
1137// ANY_EXTEND can be replaced by ZERO_EXTEND when LASX is enabled.
1138SDValue LoongArchTargetLowering::lowerANY_EXTEND(SDValue Op,
1139 SelectionDAG &DAG) const {
1140 assert(Subtarget.hasExtLASX());
1141 // We don't have corresponding instrunction for ANY_EXTEND, lowering it to
1142 // ZERO_EXTEND won't break its semantics, while avoid scalar extract/insert.
1143 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(Op), Op.getValueType(),
1144 Op.getOperand(0));
1145}
1146
1147// Lower vecreduce_add using vhaddw instructions.
1148// For Example:
1149// call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %a)
1150// can be lowered to:
1151// VHADDW_D_W vr0, vr0, vr0
1152// VHADDW_Q_D vr0, vr0, vr0
1153// VPICKVE2GR_D a0, vr0, 0
1154// ADDI_W a0, a0, 0
1155SDValue LoongArchTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
1156 SelectionDAG &DAG) const {
1157
1158 SDLoc DL(Op);
1159 MVT OpVT = Op.getSimpleValueType();
1160 SDValue Val = Op.getOperand(0);
1161
1162 unsigned NumEles = Val.getSimpleValueType().getVectorNumElements();
1163 unsigned EleBits = Val.getSimpleValueType().getScalarSizeInBits();
1164 unsigned ResBits = OpVT.getScalarSizeInBits();
1165
1166 unsigned LegalVecSize = 128;
1167 bool isLASX256Vector =
1168 Subtarget.hasExtLASX() && Val.getValueSizeInBits() == 256;
1169
1170 // Ensure operand type legal or enable it legal.
1171 while (!isTypeLegal(Val.getSimpleValueType())) {
1172 Val = DAG.WidenVector(Val, DL);
1173 }
1174
1175 // NumEles is designed for iterations count, v4i32 for LSX
1176 // and v8i32 for LASX should have the same count.
1177 if (isLASX256Vector) {
1178 NumEles /= 2;
1179 LegalVecSize = 256;
1180 }
1181
1182 EleBits *= 2;
1183 for (unsigned i = 1; i < NumEles; i *= 2, EleBits *= 2) {
1184 EleBits = std::min(EleBits, 64u);
1185 MVT IntTy = MVT::getIntegerVT(EleBits);
1186 MVT VecTy = MVT::getVectorVT(IntTy, LegalVecSize / EleBits);
1187 Val = DAG.getNode(LoongArchISD::VHADDW, DL, VecTy, Val, Val);
1188 }
1189
1190 if (isLASX256Vector) {
1191 SDValue Tmp = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, Val,
1192 DAG.getConstant(2, DL, Subtarget.getGRLenVT()));
1193 Val = DAG.getNode(ISD::ADD, DL, MVT::v4i64, Tmp, Val);
1194 }
1195
1196 Val = DAG.getBitcast(MVT::getVectorVT(OpVT, LegalVecSize / ResBits), Val);
1197 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT, Val,
1198 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
1199}
1200
1201// Lower vecreduce_and/or/xor/[s/u]max/[s/u]min.
1202// For Example:
1203// call i32 @llvm.vector.reduce.smax.v4i32(<4 x i32> %a)
1204// can be lowered to:
1205// VBSRL_V vr1, vr0, 8
1206// VMAX_W vr0, vr1, vr0
1207// VBSRL_V vr1, vr0, 4
1208// VMAX_W vr0, vr1, vr0
1209// VPICKVE2GR_W a0, vr0, 0
1210// For 256 bit vector, it is illegal and will be spilt into
1211// two 128 bit vector by default then processed by this.
1212SDValue LoongArchTargetLowering::lowerVECREDUCE(SDValue Op,
1213 SelectionDAG &DAG) const {
1214 SDLoc DL(Op);
1215
1216 MVT OpVT = Op.getSimpleValueType();
1217 SDValue Val = Op.getOperand(0);
1218
1219 unsigned NumEles = Val.getSimpleValueType().getVectorNumElements();
1220 unsigned EleBits = Val.getSimpleValueType().getScalarSizeInBits();
1221
1222 // Ensure operand type legal or enable it legal.
1223 while (!isTypeLegal(Val.getSimpleValueType())) {
1224 Val = DAG.WidenVector(Val, DL);
1225 }
1226
1227 unsigned Opcode = ISD::getVecReduceBaseOpcode(Op.getOpcode());
1228 MVT VecTy = Val.getSimpleValueType();
1229 MVT GRLenVT = Subtarget.getGRLenVT();
1230
1231 for (int i = NumEles; i > 1; i /= 2) {
1232 SDValue ShiftAmt = DAG.getConstant(i * EleBits / 16, DL, GRLenVT);
1233 SDValue Tmp = DAG.getNode(LoongArchISD::VBSRL, DL, VecTy, Val, ShiftAmt);
1234 Val = DAG.getNode(Opcode, DL, VecTy, Tmp, Val);
1235 }
1236
1237 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT, Val,
1238 DAG.getConstant(0, DL, GRLenVT));
1239}
1240
1241SDValue LoongArchTargetLowering::lowerPREFETCH(SDValue Op,
1242 SelectionDAG &DAG) const {
1243 unsigned IsData = Op.getConstantOperandVal(4);
1244
1245 // We don't support non-data prefetch.
1246 // Just preserve the chain.
1247 if (!IsData)
1248 return Op.getOperand(0);
1249
1250 return Op;
1251}
1252
1253SDValue LoongArchTargetLowering::lowerRotate(SDValue Op,
1254 SelectionDAG &DAG) const {
1255 MVT VT = Op.getSimpleValueType();
1256 assert(VT.isVector() && "Unexpected type");
1257
1258 SDLoc DL(Op);
1259 SDValue R = Op.getOperand(0);
1260 SDValue Amt = Op.getOperand(1);
1261 unsigned Opcode = Op.getOpcode();
1262 unsigned EltSizeInBits = VT.getScalarSizeInBits();
1263
1264 auto checkCstSplat = [](SDValue V, APInt &CstSplatValue) {
1265 if (V.getOpcode() != ISD::BUILD_VECTOR)
1266 return false;
1267 if (SDValue SplatValue =
1268 cast<BuildVectorSDNode>(V.getNode())->getSplatValue()) {
1269 if (auto *C = dyn_cast<ConstantSDNode>(SplatValue)) {
1270 CstSplatValue = C->getAPIntValue();
1271 return true;
1272 }
1273 }
1274 return false;
1275 };
1276
1277 // Check for constant splat rotation amount.
1278 APInt CstSplatValue;
1279 bool IsCstSplat = checkCstSplat(Amt, CstSplatValue);
1280 bool isROTL = Opcode == ISD::ROTL;
1281
1282 // Check for splat rotate by zero.
1283 if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
1284 return R;
1285
1286 // LoongArch targets always prefer ISD::ROTR.
1287 if (isROTL) {
1288 SDValue Zero = DAG.getConstant(0, DL, VT);
1289 return DAG.getNode(ISD::ROTR, DL, VT, R,
1290 DAG.getNode(ISD::SUB, DL, VT, Zero, Amt));
1291 }
1292
1293 // Rotate by a immediate.
1294 if (IsCstSplat) {
1295 // ISD::ROTR: Attemp to rotate by a positive immediate.
1296 SDValue Bits = DAG.getConstant(EltSizeInBits, DL, VT);
1297 if (SDValue Urem =
1298 DAG.FoldConstantArithmetic(ISD::UREM, DL, VT, {Amt, Bits}))
1299 return DAG.getNode(Opcode, DL, VT, R, Urem);
1300 }
1301
1302 return Op;
1303}
1304
1305// Return true if Val is equal to (setcc LHS, RHS, CC).
1306// Return false if Val is the inverse of (setcc LHS, RHS, CC).
1307// Otherwise, return std::nullopt.
1308static std::optional<bool> matchSetCC(SDValue LHS, SDValue RHS,
1309 ISD::CondCode CC, SDValue Val) {
1310 assert(Val->getOpcode() == ISD::SETCC);
1311 SDValue LHS2 = Val.getOperand(0);
1312 SDValue RHS2 = Val.getOperand(1);
1313 ISD::CondCode CC2 = Val.getOperandCondCode(2);
1314
1315 if (LHS == LHS2 && RHS == RHS2) {
1316 if (CC == CC2)
1317 return true;
1318 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
1319 return false;
1320 } else if (LHS == RHS2 && RHS == LHS2) {
1322 if (CC == CC2)
1323 return true;
1324 if (CC == ISD::getSetCCInverse(CC2, LHS2.getValueType()))
1325 return false;
1326 }
1327
1328 return std::nullopt;
1329}
1330
1333 SDValue CondV = N->getOperand(0);
1334 SDValue TrueV = N->getOperand(1);
1335 SDValue FalseV = N->getOperand(2);
1336 MVT VT = N->getSimpleValueType(0);
1337 SDLoc DL(N);
1338
1339 // (select c, -1, y) -> -c | y
1340 if (isAllOnesConstant(TrueV)) {
1341 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1342 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(FalseV));
1343 }
1344 // (select c, y, -1) -> (c-1) | y
1345 if (isAllOnesConstant(FalseV)) {
1346 SDValue Neg =
1347 DAG.getNode(ISD::ADD, DL, VT, CondV, DAG.getAllOnesConstant(DL, VT));
1348 return DAG.getNode(ISD::OR, DL, VT, Neg, DAG.getFreeze(TrueV));
1349 }
1350
1351 // (select c, 0, y) -> (c-1) & y
1352 if (isNullConstant(TrueV)) {
1353 SDValue Neg =
1354 DAG.getNode(ISD::ADD, DL, VT, CondV, DAG.getAllOnesConstant(DL, VT));
1355 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(FalseV));
1356 }
1357 // (select c, y, 0) -> -c & y
1358 if (isNullConstant(FalseV)) {
1359 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1360 return DAG.getNode(ISD::AND, DL, VT, Neg, DAG.getFreeze(TrueV));
1361 }
1362
1363 // select c, ~x, x --> xor -c, x
1364 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV)) {
1365 const APInt &TrueVal = TrueV->getAsAPIntVal();
1366 const APInt &FalseVal = FalseV->getAsAPIntVal();
1367 if (~TrueVal == FalseVal) {
1368 SDValue Neg = DAG.getNegative(CondV, DL, VT);
1369 return DAG.getNode(ISD::XOR, DL, VT, Neg, FalseV);
1370 }
1371 }
1372
1373 // Try to fold (select (setcc lhs, rhs, cc), truev, falsev) into bitwise ops
1374 // when both truev and falsev are also setcc.
1375 if (CondV.getOpcode() == ISD::SETCC && TrueV.getOpcode() == ISD::SETCC &&
1376 FalseV.getOpcode() == ISD::SETCC) {
1377 SDValue LHS = CondV.getOperand(0);
1378 SDValue RHS = CondV.getOperand(1);
1380
1381 // (select x, x, y) -> x | y
1382 // (select !x, x, y) -> x & y
1383 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, TrueV)) {
1384 return DAG.getNode(*MatchResult ? ISD::OR : ISD::AND, DL, VT, TrueV,
1385 DAG.getFreeze(FalseV));
1386 }
1387 // (select x, y, x) -> x & y
1388 // (select !x, y, x) -> x | y
1389 if (std::optional<bool> MatchResult = matchSetCC(LHS, RHS, CC, FalseV)) {
1390 return DAG.getNode(*MatchResult ? ISD::AND : ISD::OR, DL, VT,
1391 DAG.getFreeze(TrueV), FalseV);
1392 }
1393 }
1394
1395 return SDValue();
1396}
1397
1398// Transform `binOp (select cond, x, c0), c1` where `c0` and `c1` are constants
1399// into `select cond, binOp(x, c1), binOp(c0, c1)` if profitable.
1400// For now we only consider transformation profitable if `binOp(c0, c1)` ends up
1401// being `0` or `-1`. In such cases we can replace `select` with `and`.
1402// TODO: Should we also do this if `binOp(c0, c1)` is cheaper to materialize
1403// than `c0`?
1404static SDValue
1407 unsigned SelOpNo = 0;
1408 SDValue Sel = BO->getOperand(0);
1409 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
1410 SelOpNo = 1;
1411 Sel = BO->getOperand(1);
1412 }
1413
1414 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1415 return SDValue();
1416
1417 unsigned ConstSelOpNo = 1;
1418 unsigned OtherSelOpNo = 2;
1419 if (!isa<ConstantSDNode>(Sel->getOperand(ConstSelOpNo))) {
1420 ConstSelOpNo = 2;
1421 OtherSelOpNo = 1;
1422 }
1423 SDValue ConstSelOp = Sel->getOperand(ConstSelOpNo);
1424 ConstantSDNode *ConstSelOpNode = dyn_cast<ConstantSDNode>(ConstSelOp);
1425 if (!ConstSelOpNode || ConstSelOpNode->isOpaque())
1426 return SDValue();
1427
1428 SDValue ConstBinOp = BO->getOperand(SelOpNo ^ 1);
1429 ConstantSDNode *ConstBinOpNode = dyn_cast<ConstantSDNode>(ConstBinOp);
1430 if (!ConstBinOpNode || ConstBinOpNode->isOpaque())
1431 return SDValue();
1432
1433 SDLoc DL(Sel);
1434 EVT VT = BO->getValueType(0);
1435
1436 SDValue NewConstOps[2] = {ConstSelOp, ConstBinOp};
1437 if (SelOpNo == 1)
1438 std::swap(NewConstOps[0], NewConstOps[1]);
1439
1440 SDValue NewConstOp =
1441 DAG.FoldConstantArithmetic(BO->getOpcode(), DL, VT, NewConstOps);
1442 if (!NewConstOp)
1443 return SDValue();
1444
1445 const APInt &NewConstAPInt = NewConstOp->getAsAPIntVal();
1446 if (!NewConstAPInt.isZero() && !NewConstAPInt.isAllOnes())
1447 return SDValue();
1448
1449 SDValue OtherSelOp = Sel->getOperand(OtherSelOpNo);
1450 SDValue NewNonConstOps[2] = {OtherSelOp, ConstBinOp};
1451 if (SelOpNo == 1)
1452 std::swap(NewNonConstOps[0], NewNonConstOps[1]);
1453 SDValue NewNonConstOp = DAG.getNode(BO->getOpcode(), DL, VT, NewNonConstOps);
1454
1455 SDValue NewT = (ConstSelOpNo == 1) ? NewConstOp : NewNonConstOp;
1456 SDValue NewF = (ConstSelOpNo == 1) ? NewNonConstOp : NewConstOp;
1457 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewT, NewF);
1458}
1459
1460// Changes the condition code and swaps operands if necessary, so the SetCC
1461// operation matches one of the comparisons supported directly by branches
1462// in the LoongArch ISA. May adjust compares to favor compare with 0 over
1463// compare with 1/-1.
1465 ISD::CondCode &CC, SelectionDAG &DAG) {
1466 // If this is a single bit test that can't be handled by ANDI, shift the
1467 // bit to be tested to the MSB and perform a signed compare with 0.
1468 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
1469 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
1470 isa<ConstantSDNode>(LHS.getOperand(1))) {
1471 uint64_t Mask = LHS.getConstantOperandVal(1);
1472 if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) {
1473 unsigned ShAmt = 0;
1474 if (isPowerOf2_64(Mask)) {
1476 ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
1477 } else {
1478 ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask);
1479 }
1480
1481 LHS = LHS.getOperand(0);
1482 if (ShAmt != 0)
1483 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
1484 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
1485 return;
1486 }
1487 }
1488
1489 if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1490 int64_t C = RHSC->getSExtValue();
1491 switch (CC) {
1492 default:
1493 break;
1494 case ISD::SETGT:
1495 // Convert X > -1 to X >= 0.
1496 if (C == -1) {
1497 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1498 CC = ISD::SETGE;
1499 return;
1500 }
1501 break;
1502 case ISD::SETLT:
1503 // Convert X < 1 to 0 >= X.
1504 if (C == 1) {
1505 RHS = LHS;
1506 LHS = DAG.getConstant(0, DL, RHS.getValueType());
1507 CC = ISD::SETGE;
1508 return;
1509 }
1510 break;
1511 }
1512 }
1513
1514 switch (CC) {
1515 default:
1516 break;
1517 case ISD::SETGT:
1518 case ISD::SETLE:
1519 case ISD::SETUGT:
1520 case ISD::SETULE:
1522 std::swap(LHS, RHS);
1523 break;
1524 }
1525}
1526
1527SDValue LoongArchTargetLowering::lowerSELECT(SDValue Op,
1528 SelectionDAG &DAG) const {
1529 SDValue CondV = Op.getOperand(0);
1530 SDValue TrueV = Op.getOperand(1);
1531 SDValue FalseV = Op.getOperand(2);
1532 SDLoc DL(Op);
1533 MVT VT = Op.getSimpleValueType();
1534 MVT GRLenVT = Subtarget.getGRLenVT();
1535
1536 if (SDValue V = combineSelectToBinOp(Op.getNode(), DAG, Subtarget))
1537 return V;
1538
1539 if (Op.hasOneUse()) {
1540 unsigned UseOpc = Op->user_begin()->getOpcode();
1541 if (isBinOp(UseOpc) && DAG.isSafeToSpeculativelyExecute(UseOpc)) {
1542 SDNode *BinOp = *Op->user_begin();
1543 if (SDValue NewSel = foldBinOpIntoSelectIfProfitable(*Op->user_begin(),
1544 DAG, Subtarget)) {
1545 DAG.ReplaceAllUsesWith(BinOp, &NewSel);
1546 // Opcode check is necessary because foldBinOpIntoSelectIfProfitable
1547 // may return a constant node and cause crash in lowerSELECT.
1548 if (NewSel.getOpcode() == ISD::SELECT)
1549 return lowerSELECT(NewSel, DAG);
1550 return NewSel;
1551 }
1552 }
1553 }
1554
1555 // If the condition is not an integer SETCC which operates on GRLenVT, we need
1556 // to emit a LoongArchISD::SELECT_CC comparing the condition to zero. i.e.:
1557 // (select condv, truev, falsev)
1558 // -> (loongarchisd::select_cc condv, zero, setne, truev, falsev)
1559 if (CondV.getOpcode() != ISD::SETCC ||
1560 CondV.getOperand(0).getSimpleValueType() != GRLenVT) {
1561 SDValue Zero = DAG.getConstant(0, DL, GRLenVT);
1562 SDValue SetNE = DAG.getCondCode(ISD::SETNE);
1563
1564 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
1565
1566 return DAG.getNode(LoongArchISD::SELECT_CC, DL, VT, Ops);
1567 }
1568
1569 // If the CondV is the output of a SETCC node which operates on GRLenVT
1570 // inputs, then merge the SETCC node into the lowered LoongArchISD::SELECT_CC
1571 // to take advantage of the integer compare+branch instructions. i.e.: (select
1572 // (setcc lhs, rhs, cc), truev, falsev)
1573 // -> (loongarchisd::select_cc lhs, rhs, cc, truev, falsev)
1574 SDValue LHS = CondV.getOperand(0);
1575 SDValue RHS = CondV.getOperand(1);
1576 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
1577
1578 // Special case for a select of 2 constants that have a difference of 1.
1579 // Normally this is done by DAGCombine, but if the select is introduced by
1580 // type legalization or op legalization, we miss it. Restricting to SETLT
1581 // case for now because that is what signed saturating add/sub need.
1582 // FIXME: We don't need the condition to be SETLT or even a SETCC,
1583 // but we would probably want to swap the true/false values if the condition
1584 // is SETGE/SETLE to avoid an XORI.
1585 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
1586 CCVal == ISD::SETLT) {
1587 const APInt &TrueVal = TrueV->getAsAPIntVal();
1588 const APInt &FalseVal = FalseV->getAsAPIntVal();
1589 if (TrueVal - 1 == FalseVal)
1590 return DAG.getNode(ISD::ADD, DL, VT, CondV, FalseV);
1591 if (TrueVal + 1 == FalseVal)
1592 return DAG.getNode(ISD::SUB, DL, VT, FalseV, CondV);
1593 }
1594
1595 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
1596 // 1 < x ? x : 1 -> 0 < x ? x : 1
1597 if (isOneConstant(LHS) && (CCVal == ISD::SETLT || CCVal == ISD::SETULT) &&
1598 RHS == TrueV && LHS == FalseV) {
1599 LHS = DAG.getConstant(0, DL, VT);
1600 // 0 <u x is the same as x != 0.
1601 if (CCVal == ISD::SETULT) {
1602 std::swap(LHS, RHS);
1603 CCVal = ISD::SETNE;
1604 }
1605 }
1606
1607 // x <s -1 ? x : -1 -> x <s 0 ? x : -1
1608 if (isAllOnesConstant(RHS) && CCVal == ISD::SETLT && LHS == TrueV &&
1609 RHS == FalseV) {
1610 RHS = DAG.getConstant(0, DL, VT);
1611 }
1612
1613 SDValue TargetCC = DAG.getCondCode(CCVal);
1614
1615 if (isa<ConstantSDNode>(TrueV) && !isa<ConstantSDNode>(FalseV)) {
1616 // (select (setcc lhs, rhs, CC), constant, falsev)
1617 // -> (select (setcc lhs, rhs, InverseCC), falsev, constant)
1618 std::swap(TrueV, FalseV);
1619 TargetCC = DAG.getCondCode(ISD::getSetCCInverse(CCVal, LHS.getValueType()));
1620 }
1621
1622 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
1623 return DAG.getNode(LoongArchISD::SELECT_CC, DL, VT, Ops);
1624}
1625
1626SDValue LoongArchTargetLowering::lowerBRCOND(SDValue Op,
1627 SelectionDAG &DAG) const {
1628 SDValue CondV = Op.getOperand(1);
1629 SDLoc DL(Op);
1630 MVT GRLenVT = Subtarget.getGRLenVT();
1631
1632 if (CondV.getOpcode() == ISD::SETCC) {
1633 if (CondV.getOperand(0).getValueType() == GRLenVT) {
1634 SDValue LHS = CondV.getOperand(0);
1635 SDValue RHS = CondV.getOperand(1);
1636 ISD::CondCode CCVal = CondV.getOperandCondCode(2);
1637
1638 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
1639
1640 SDValue TargetCC = DAG.getCondCode(CCVal);
1641 return DAG.getNode(LoongArchISD::BR_CC, DL, Op.getValueType(),
1642 Op.getOperand(0), LHS, RHS, TargetCC,
1643 Op.getOperand(2));
1644 } else if (CondV.getOperand(0).getValueType().isFloatingPoint()) {
1645 return DAG.getNode(LoongArchISD::BRCOND, DL, Op.getValueType(),
1646 Op.getOperand(0), CondV, Op.getOperand(2));
1647 }
1648 }
1649
1650 return DAG.getNode(LoongArchISD::BR_CC, DL, Op.getValueType(),
1651 Op.getOperand(0), CondV, DAG.getConstant(0, DL, GRLenVT),
1652 DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
1653}
1654
1655SDValue
1656LoongArchTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
1657 SelectionDAG &DAG) const {
1658 SDLoc DL(Op);
1659 MVT OpVT = Op.getSimpleValueType();
1660
1661 SDValue Vector = DAG.getUNDEF(OpVT);
1662 SDValue Val = Op.getOperand(0);
1663 SDValue Idx = DAG.getConstant(0, DL, Subtarget.getGRLenVT());
1664
1665 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, OpVT, Vector, Val, Idx);
1666}
1667
1668SDValue LoongArchTargetLowering::lowerBITREVERSE(SDValue Op,
1669 SelectionDAG &DAG) const {
1670 EVT ResTy = Op->getValueType(0);
1671 SDValue Src = Op->getOperand(0);
1672 SDLoc DL(Op);
1673
1674 // LoongArchISD::BITREV_8B is not supported on LA32.
1675 if (!Subtarget.is64Bit() && (ResTy == MVT::v16i8 || ResTy == MVT::v32i8))
1676 return SDValue();
1677
1678 EVT NewVT = ResTy.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
1679 unsigned int OrigEltNum = ResTy.getVectorNumElements();
1680 unsigned int NewEltNum = NewVT.getVectorNumElements();
1681
1682 SDValue NewSrc = DAG.getNode(ISD::BITCAST, DL, NewVT, Src);
1683
1685 for (unsigned int i = 0; i < NewEltNum; i++) {
1686 SDValue Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, NewSrc,
1687 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
1688 unsigned RevOp = (ResTy == MVT::v16i8 || ResTy == MVT::v32i8)
1689 ? (unsigned)LoongArchISD::BITREV_8B
1690 : (unsigned)ISD::BITREVERSE;
1691 Ops.push_back(DAG.getNode(RevOp, DL, MVT::i64, Op));
1692 }
1693 SDValue Res =
1694 DAG.getNode(ISD::BITCAST, DL, ResTy, DAG.getBuildVector(NewVT, DL, Ops));
1695
1696 switch (ResTy.getSimpleVT().SimpleTy) {
1697 default:
1698 return SDValue();
1699 case MVT::v16i8:
1700 case MVT::v32i8:
1701 return Res;
1702 case MVT::v8i16:
1703 case MVT::v16i16:
1704 case MVT::v4i32:
1705 case MVT::v8i32: {
1707 for (unsigned int i = 0; i < NewEltNum; i++)
1708 for (int j = OrigEltNum / NewEltNum - 1; j >= 0; j--)
1709 Mask.push_back(j + (OrigEltNum / NewEltNum) * i);
1710 return DAG.getVectorShuffle(ResTy, DL, Res, DAG.getUNDEF(ResTy), Mask);
1711 }
1712 }
1713}
1714
1715// Widen element type to get a new mask value (if possible).
1716// For example:
1717// shufflevector <4 x i32> %a, <4 x i32> %b,
1718// <4 x i32> <i32 6, i32 7, i32 2, i32 3>
1719// is equivalent to:
1720// shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
1721// can be lowered to:
1722// VPACKOD_D vr0, vr0, vr1
1724 SDValue V1, SDValue V2, SelectionDAG &DAG) {
1725 unsigned EltBits = VT.getScalarSizeInBits();
1726
1727 if (EltBits > 32 || EltBits == 1)
1728 return SDValue();
1729
1730 SmallVector<int, 8> NewMask;
1731 if (widenShuffleMaskElts(Mask, NewMask)) {
1732 MVT NewEltVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(EltBits * 2)
1733 : MVT::getIntegerVT(EltBits * 2);
1734 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
1735 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
1736 SDValue NewV1 = DAG.getBitcast(NewVT, V1);
1737 SDValue NewV2 = DAG.getBitcast(NewVT, V2);
1738 return DAG.getBitcast(
1739 VT, DAG.getVectorShuffle(NewVT, DL, NewV1, NewV2, NewMask));
1740 }
1741 }
1742
1743 return SDValue();
1744}
1745
1746/// Attempts to match a shuffle mask against the VBSLL, VBSRL, VSLLI and VSRLI
1747/// instruction.
1748// The funciton matches elements from one of the input vector shuffled to the
1749// left or right with zeroable elements 'shifted in'. It handles both the
1750// strictly bit-wise element shifts and the byte shfit across an entire 128-bit
1751// lane.
1752// Mostly copied from X86.
1753static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
1754 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
1755 int MaskOffset, const APInt &Zeroable) {
1756 int Size = Mask.size();
1757 unsigned SizeInBits = Size * ScalarSizeInBits;
1758
1759 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
1760 for (int i = 0; i < Size; i += Scale)
1761 for (int j = 0; j < Shift; ++j)
1762 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
1763 return false;
1764
1765 return true;
1766 };
1767
1768 auto isSequentialOrUndefInRange = [&](unsigned Pos, unsigned Size, int Low,
1769 int Step = 1) {
1770 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
1771 if (!(Mask[i] == -1 || Mask[i] == Low))
1772 return false;
1773 return true;
1774 };
1775
1776 auto MatchShift = [&](int Shift, int Scale, bool Left) {
1777 for (int i = 0; i != Size; i += Scale) {
1778 unsigned Pos = Left ? i + Shift : i;
1779 unsigned Low = Left ? i : i + Shift;
1780 unsigned Len = Scale - Shift;
1781 if (!isSequentialOrUndefInRange(Pos, Len, Low + MaskOffset))
1782 return -1;
1783 }
1784
1785 int ShiftEltBits = ScalarSizeInBits * Scale;
1786 bool ByteShift = ShiftEltBits > 64;
1787 Opcode = Left ? (ByteShift ? LoongArchISD::VBSLL : LoongArchISD::VSLLI)
1788 : (ByteShift ? LoongArchISD::VBSRL : LoongArchISD::VSRLI);
1789 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
1790
1791 // Normalize the scale for byte shifts to still produce an i64 element
1792 // type.
1793 Scale = ByteShift ? Scale / 2 : Scale;
1794
1795 // We need to round trip through the appropriate type for the shift.
1796 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
1797 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
1798 : MVT::getVectorVT(ShiftSVT, Size / Scale);
1799 return (int)ShiftAmt;
1800 };
1801
1802 unsigned MaxWidth = 128;
1803 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
1804 for (int Shift = 1; Shift != Scale; ++Shift)
1805 for (bool Left : {true, false})
1806 if (CheckZeros(Shift, Scale, Left)) {
1807 int ShiftAmt = MatchShift(Shift, Scale, Left);
1808 if (0 < ShiftAmt)
1809 return ShiftAmt;
1810 }
1811
1812 // no match
1813 return -1;
1814}
1815
1816/// Lower VECTOR_SHUFFLE as shift (if possible).
1817///
1818/// For example:
1819/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
1820/// <4 x i32> <i32 4, i32 0, i32 1, i32 2>
1821/// is lowered to:
1822/// (VBSLL_V $v0, $v0, 4)
1823///
1824/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
1825/// <4 x i32> <i32 4, i32 0, i32 4, i32 2>
1826/// is lowered to:
1827/// (VSLLI_D $v0, $v0, 32)
1829 MVT VT, SDValue V1, SDValue V2,
1830 SelectionDAG &DAG,
1832 const APInt &Zeroable) {
1833 int Size = Mask.size();
1834 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
1835
1836 MVT ShiftVT;
1837 SDValue V = V1;
1838 unsigned Opcode;
1839
1840 // Try to match shuffle against V1 shift.
1841 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
1842 Mask, 0, Zeroable);
1843
1844 // If V1 failed, try to match shuffle against V2 shift.
1845 if (ShiftAmt < 0) {
1846 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
1847 Mask, Size, Zeroable);
1848 V = V2;
1849 }
1850
1851 if (ShiftAmt < 0)
1852 return SDValue();
1853
1854 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
1855 "Illegal integer vector type");
1856 V = DAG.getBitcast(ShiftVT, V);
1857 V = DAG.getNode(Opcode, DL, ShiftVT, V,
1858 DAG.getConstant(ShiftAmt, DL, Subtarget.getGRLenVT()));
1859 return DAG.getBitcast(VT, V);
1860}
1861
1862/// Determine whether a range fits a regular pattern of values.
1863/// This function accounts for the possibility of jumping over the End iterator.
1864template <typename ValType>
1865static bool
1867 unsigned CheckStride,
1869 ValType ExpectedIndex, unsigned ExpectedIndexStride) {
1870 auto &I = Begin;
1871
1872 while (I != End) {
1873 if (*I != -1 && *I != ExpectedIndex)
1874 return false;
1875 ExpectedIndex += ExpectedIndexStride;
1876
1877 // Incrementing past End is undefined behaviour so we must increment one
1878 // step at a time and check for End at each step.
1879 for (unsigned n = 0; n < CheckStride && I != End; ++n, ++I)
1880 ; // Empty loop body.
1881 }
1882 return true;
1883}
1884
1885/// Compute whether each element of a shuffle is zeroable.
1886///
1887/// A "zeroable" vector shuffle element is one which can be lowered to zero.
1889 SDValue V2, APInt &KnownUndef,
1890 APInt &KnownZero) {
1891 int Size = Mask.size();
1892 KnownUndef = KnownZero = APInt::getZero(Size);
1893
1895 V2 = peekThroughBitcasts(V2);
1896
1897 bool V1IsZero = ISD::isBuildVectorAllZeros(V1);
1898 bool V2IsZero = ISD::isBuildVectorAllZeros(V2);
1899
1900 int VectorSizeInBits = V1.getValueSizeInBits();
1901 int ScalarSizeInBits = VectorSizeInBits / Size;
1902 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
1903 (void)ScalarSizeInBits;
1904
1905 for (int i = 0; i < Size; ++i) {
1906 int M = Mask[i];
1907 if (M < 0) {
1908 KnownUndef.setBit(i);
1909 continue;
1910 }
1911 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
1912 KnownZero.setBit(i);
1913 continue;
1914 }
1915 }
1916}
1917
1918/// Test whether a shuffle mask is equivalent within each sub-lane.
1919///
1920/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
1921/// non-trivial to compute in the face of undef lanes. The representation is
1922/// suitable for use with existing 128-bit shuffles as entries from the second
1923/// vector have been remapped to [LaneSize, 2*LaneSize).
1924static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
1925 ArrayRef<int> Mask,
1926 SmallVectorImpl<int> &RepeatedMask) {
1927 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
1928 RepeatedMask.assign(LaneSize, -1);
1929 int Size = Mask.size();
1930 for (int i = 0; i < Size; ++i) {
1931 assert(Mask[i] == -1 || Mask[i] >= 0);
1932 if (Mask[i] < 0)
1933 continue;
1934 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
1935 // This entry crosses lanes, so there is no way to model this shuffle.
1936 return false;
1937
1938 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
1939 // Adjust second vector indices to start at LaneSize instead of Size.
1940 int LocalM =
1941 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
1942 if (RepeatedMask[i % LaneSize] < 0)
1943 // This is the first non-undef entry in this slot of a 128-bit lane.
1944 RepeatedMask[i % LaneSize] = LocalM;
1945 else if (RepeatedMask[i % LaneSize] != LocalM)
1946 // Found a mismatch with the repeated mask.
1947 return false;
1948 }
1949 return true;
1950}
1951
1952/// Attempts to match vector shuffle as byte rotation.
1954 ArrayRef<int> Mask) {
1955
1956 SDValue Lo, Hi;
1957 SmallVector<int, 16> RepeatedMask;
1958
1959 if (!isRepeatedShuffleMask(128, VT, Mask, RepeatedMask))
1960 return -1;
1961
1962 int NumElts = RepeatedMask.size();
1963 int Rotation = 0;
1964 int Scale = 16 / NumElts;
1965
1966 for (int i = 0; i < NumElts; ++i) {
1967 int M = RepeatedMask[i];
1968 assert((M == -1 || (0 <= M && M < (2 * NumElts))) &&
1969 "Unexpected mask index.");
1970 if (M < 0)
1971 continue;
1972
1973 // Determine where a rotated vector would have started.
1974 int StartIdx = i - (M % NumElts);
1975 if (StartIdx == 0)
1976 return -1;
1977
1978 // If we found the tail of a vector the rotation must be the missing
1979 // front. If we found the head of a vector, it must be how much of the
1980 // head.
1981 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
1982
1983 if (Rotation == 0)
1984 Rotation = CandidateRotation;
1985 else if (Rotation != CandidateRotation)
1986 return -1;
1987
1988 // Compute which value this mask is pointing at.
1989 SDValue MaskV = M < NumElts ? V1 : V2;
1990
1991 // Compute which of the two target values this index should be assigned
1992 // to. This reflects whether the high elements are remaining or the low
1993 // elements are remaining.
1994 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
1995
1996 // Either set up this value if we've not encountered it before, or check
1997 // that it remains consistent.
1998 if (!TargetV)
1999 TargetV = MaskV;
2000 else if (TargetV != MaskV)
2001 return -1;
2002 }
2003
2004 // Check that we successfully analyzed the mask, and normalize the results.
2005 assert(Rotation != 0 && "Failed to locate a viable rotation!");
2006 assert((Lo || Hi) && "Failed to find a rotated input vector!");
2007 if (!Lo)
2008 Lo = Hi;
2009 else if (!Hi)
2010 Hi = Lo;
2011
2012 V1 = Lo;
2013 V2 = Hi;
2014
2015 return Rotation * Scale;
2016}
2017
2018/// Lower VECTOR_SHUFFLE as byte rotate (if possible).
2019///
2020/// For example:
2021/// %shuffle = shufflevector <2 x i64> %a, <2 x i64> %b,
2022/// <2 x i32> <i32 3, i32 0>
2023/// is lowered to:
2024/// (VBSRL_V $v1, $v1, 8)
2025/// (VBSLL_V $v0, $v0, 8)
2026/// (VOR_V $v0, $V0, $v1)
2027static SDValue
2029 SDValue V1, SDValue V2, SelectionDAG &DAG,
2031
2032 SDValue Lo = V1, Hi = V2;
2033 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
2034 if (ByteRotation <= 0)
2035 return SDValue();
2036
2037 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
2038 Lo = DAG.getBitcast(ByteVT, Lo);
2039 Hi = DAG.getBitcast(ByteVT, Hi);
2040
2041 int LoByteShift = 16 - ByteRotation;
2042 int HiByteShift = ByteRotation;
2043 MVT GRLenVT = Subtarget.getGRLenVT();
2044
2045 SDValue LoShift = DAG.getNode(LoongArchISD::VBSLL, DL, ByteVT, Lo,
2046 DAG.getConstant(LoByteShift, DL, GRLenVT));
2047 SDValue HiShift = DAG.getNode(LoongArchISD::VBSRL, DL, ByteVT, Hi,
2048 DAG.getConstant(HiByteShift, DL, GRLenVT));
2049 return DAG.getBitcast(VT, DAG.getNode(ISD::OR, DL, ByteVT, LoShift, HiShift));
2050}
2051
2052/// Lower VECTOR_SHUFFLE as ZERO_EXTEND Or ANY_EXTEND (if possible).
2053///
2054/// For example:
2055/// %2 = shufflevector <4 x i32> %0, <4 x i32> zeroinitializer,
2056/// <4 x i32> <i32 0, i32 4, i32 1, i32 4>
2057/// %3 = bitcast <4 x i32> %2 to <2 x i64>
2058/// is lowered to:
2059/// (VREPLI $v1, 0)
2060/// (VILVL $v0, $v1, $v0)
2062 ArrayRef<int> Mask, MVT VT,
2063 SDValue V1, SDValue V2,
2064 SelectionDAG &DAG,
2065 const APInt &Zeroable) {
2066 int Bits = VT.getSizeInBits();
2067 int EltBits = VT.getScalarSizeInBits();
2068 int NumElements = VT.getVectorNumElements();
2069
2070 if (Zeroable.isAllOnes())
2071 return DAG.getConstant(0, DL, VT);
2072
2073 // Define a helper function to check a particular ext-scale and lower to it if
2074 // valid.
2075 auto Lower = [&](int Scale) -> SDValue {
2076 SDValue InputV;
2077 bool AnyExt = true;
2078 int Offset = 0;
2079 for (int i = 0; i < NumElements; i++) {
2080 int M = Mask[i];
2081 if (M < 0)
2082 continue;
2083 if (i % Scale != 0) {
2084 // Each of the extended elements need to be zeroable.
2085 if (!Zeroable[i])
2086 return SDValue();
2087
2088 AnyExt = false;
2089 continue;
2090 }
2091
2092 // Each of the base elements needs to be consecutive indices into the
2093 // same input vector.
2094 SDValue V = M < NumElements ? V1 : V2;
2095 M = M % NumElements;
2096 if (!InputV) {
2097 InputV = V;
2098 Offset = M - (i / Scale);
2099
2100 // These offset can't be handled
2101 if (Offset % (NumElements / Scale))
2102 return SDValue();
2103 } else if (InputV != V)
2104 return SDValue();
2105
2106 if (M != (Offset + (i / Scale)))
2107 return SDValue(); // Non-consecutive strided elements.
2108 }
2109
2110 // If we fail to find an input, we have a zero-shuffle which should always
2111 // have already been handled.
2112 if (!InputV)
2113 return SDValue();
2114
2115 do {
2116 unsigned VilVLoHi = LoongArchISD::VILVL;
2117 if (Offset >= (NumElements / 2)) {
2118 VilVLoHi = LoongArchISD::VILVH;
2119 Offset -= (NumElements / 2);
2120 }
2121
2122 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
2123 SDValue Ext =
2124 AnyExt ? DAG.getFreeze(InputV) : DAG.getConstant(0, DL, InputVT);
2125 InputV = DAG.getBitcast(InputVT, InputV);
2126 Ext = DAG.getBitcast(InputVT, Ext);
2127 InputV = DAG.getNode(VilVLoHi, DL, InputVT, Ext, InputV);
2128 Scale /= 2;
2129 EltBits *= 2;
2130 NumElements /= 2;
2131 } while (Scale > 1);
2132 return DAG.getBitcast(VT, InputV);
2133 };
2134
2135 // Each iteration, try extending the elements half as much, but into twice as
2136 // many elements.
2137 for (int NumExtElements = Bits / 64; NumExtElements < NumElements;
2138 NumExtElements *= 2) {
2139 if (SDValue V = Lower(NumElements / NumExtElements))
2140 return V;
2141 }
2142 return SDValue();
2143}
2144
2145/// Lower VECTOR_SHUFFLE into VREPLVEI (if possible).
2146///
2147/// VREPLVEI performs vector broadcast based on an element specified by an
2148/// integer immediate, with its mask being similar to:
2149/// <x, x, x, ...>
2150/// where x is any valid index.
2151///
2152/// When undef's appear in the mask they are treated as if they were whatever
2153/// value is necessary in order to fit the above form.
2154static SDValue
2156 SDValue V1, SelectionDAG &DAG,
2158 int SplatIndex = -1;
2159 for (const auto &M : Mask) {
2160 if (M != -1) {
2161 SplatIndex = M;
2162 break;
2163 }
2164 }
2165
2166 if (SplatIndex == -1)
2167 return DAG.getUNDEF(VT);
2168
2169 assert(SplatIndex < (int)Mask.size() && "Out of bounds mask index");
2170 if (fitsRegularPattern<int>(Mask.begin(), 1, Mask.end(), SplatIndex, 0)) {
2171 return DAG.getNode(LoongArchISD::VREPLVEI, DL, VT, V1,
2172 DAG.getConstant(SplatIndex, DL, Subtarget.getGRLenVT()));
2173 }
2174
2175 return SDValue();
2176}
2177
2178/// Lower VECTOR_SHUFFLE into VSHUF4I (if possible).
2179///
2180/// VSHUF4I splits the vector into blocks of four elements, then shuffles these
2181/// elements according to a <4 x i2> constant (encoded as an integer immediate).
2182///
2183/// It is therefore possible to lower into VSHUF4I when the mask takes the form:
2184/// <a, b, c, d, a+4, b+4, c+4, d+4, a+8, b+8, c+8, d+8, ...>
2185/// When undef's appear they are treated as if they were whatever value is
2186/// necessary in order to fit the above forms.
2187///
2188/// For example:
2189/// %2 = shufflevector <8 x i16> %0, <8 x i16> undef,
2190/// <8 x i32> <i32 3, i32 2, i32 1, i32 0,
2191/// i32 7, i32 6, i32 5, i32 4>
2192/// is lowered to:
2193/// (VSHUF4I_H $v0, $v1, 27)
2194/// where the 27 comes from:
2195/// 3 + (2 << 2) + (1 << 4) + (0 << 6)
2196static SDValue
2198 SDValue V1, SDValue V2, SelectionDAG &DAG,
2200
2201 unsigned SubVecSize = 4;
2202 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2203 SubVecSize = 2;
2204
2205 int SubMask[4] = {-1, -1, -1, -1};
2206 for (unsigned i = 0; i < SubVecSize; ++i) {
2207 for (unsigned j = i; j < Mask.size(); j += SubVecSize) {
2208 int M = Mask[j];
2209
2210 // Convert from vector index to 4-element subvector index
2211 // If an index refers to an element outside of the subvector then give up
2212 if (M != -1) {
2213 M -= 4 * (j / SubVecSize);
2214 if (M < 0 || M >= 4)
2215 return SDValue();
2216 }
2217
2218 // If the mask has an undef, replace it with the current index.
2219 // Note that it might still be undef if the current index is also undef
2220 if (SubMask[i] == -1)
2221 SubMask[i] = M;
2222 // Check that non-undef values are the same as in the mask. If they
2223 // aren't then give up
2224 else if (M != -1 && M != SubMask[i])
2225 return SDValue();
2226 }
2227 }
2228
2229 // Calculate the immediate. Replace any remaining undefs with zero
2230 int Imm = 0;
2231 for (int i = SubVecSize - 1; i >= 0; --i) {
2232 int M = SubMask[i];
2233
2234 if (M == -1)
2235 M = 0;
2236
2237 Imm <<= 2;
2238 Imm |= M & 0x3;
2239 }
2240
2241 MVT GRLenVT = Subtarget.getGRLenVT();
2242
2243 // Return vshuf4i.d
2244 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2245 return DAG.getNode(LoongArchISD::VSHUF4I_D, DL, VT, V1, V2,
2246 DAG.getConstant(Imm, DL, GRLenVT));
2247
2248 return DAG.getNode(LoongArchISD::VSHUF4I, DL, VT, V1,
2249 DAG.getConstant(Imm, DL, GRLenVT));
2250}
2251
2252/// Lower VECTOR_SHUFFLE whose result is the reversed source vector.
2253///
2254/// It is possible to do optimization for VECTOR_SHUFFLE performing vector
2255/// reverse whose mask likes:
2256/// <7, 6, 5, 4, 3, 2, 1, 0>
2257///
2258/// When undef's appear in the mask they are treated as if they were whatever
2259/// value is necessary in order to fit the above forms.
2260static SDValue
2262 SDValue V1, SelectionDAG &DAG,
2264 // Only vectors with i8/i16 elements which cannot match other patterns
2265 // directly needs to do this.
2266 if (VT != MVT::v16i8 && VT != MVT::v8i16 && VT != MVT::v32i8 &&
2267 VT != MVT::v16i16)
2268 return SDValue();
2269
2270 if (!ShuffleVectorInst::isReverseMask(Mask, Mask.size()))
2271 return SDValue();
2272
2273 int WidenNumElts = VT.getVectorNumElements() / 4;
2274 SmallVector<int, 16> WidenMask(WidenNumElts, -1);
2275 for (int i = 0; i < WidenNumElts; ++i)
2276 WidenMask[i] = WidenNumElts - 1 - i;
2277
2278 MVT WidenVT = MVT::getVectorVT(
2279 VT.getVectorElementType() == MVT::i8 ? MVT::i32 : MVT::i64, WidenNumElts);
2280 SDValue NewV1 = DAG.getBitcast(WidenVT, V1);
2281 SDValue WidenRev = DAG.getVectorShuffle(WidenVT, DL, NewV1,
2282 DAG.getUNDEF(WidenVT), WidenMask);
2283
2284 return DAG.getNode(LoongArchISD::VSHUF4I, DL, VT,
2285 DAG.getBitcast(VT, WidenRev),
2286 DAG.getConstant(27, DL, Subtarget.getGRLenVT()));
2287}
2288
2289/// Lower VECTOR_SHUFFLE into VPACKEV (if possible).
2290///
2291/// VPACKEV interleaves the even elements from each vector.
2292///
2293/// It is possible to lower into VPACKEV when the mask consists of two of the
2294/// following forms interleaved:
2295/// <0, 2, 4, ...>
2296/// <n, n+2, n+4, ...>
2297/// where n is the number of elements in the vector.
2298/// For example:
2299/// <0, 0, 2, 2, 4, 4, ...>
2300/// <0, n, 2, n+2, 4, n+4, ...>
2301///
2302/// When undef's appear in the mask they are treated as if they were whatever
2303/// value is necessary in order to fit the above forms.
2305 MVT VT, SDValue V1, SDValue V2,
2306 SelectionDAG &DAG) {
2307
2308 const auto &Begin = Mask.begin();
2309 const auto &End = Mask.end();
2310 SDValue OriV1 = V1, OriV2 = V2;
2311
2312 if (fitsRegularPattern<int>(Begin, 2, End, 0, 2))
2313 V1 = OriV1;
2314 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size(), 2))
2315 V1 = OriV2;
2316 else
2317 return SDValue();
2318
2319 if (fitsRegularPattern<int>(Begin + 1, 2, End, 0, 2))
2320 V2 = OriV1;
2321 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size(), 2))
2322 V2 = OriV2;
2323 else
2324 return SDValue();
2325
2326 return DAG.getNode(LoongArchISD::VPACKEV, DL, VT, V2, V1);
2327}
2328
2329/// Lower VECTOR_SHUFFLE into VPACKOD (if possible).
2330///
2331/// VPACKOD interleaves the odd elements from each vector.
2332///
2333/// It is possible to lower into VPACKOD when the mask consists of two of the
2334/// following forms interleaved:
2335/// <1, 3, 5, ...>
2336/// <n+1, n+3, n+5, ...>
2337/// where n is the number of elements in the vector.
2338/// For example:
2339/// <1, 1, 3, 3, 5, 5, ...>
2340/// <1, n+1, 3, n+3, 5, n+5, ...>
2341///
2342/// When undef's appear in the mask they are treated as if they were whatever
2343/// value is necessary in order to fit the above forms.
2345 MVT VT, SDValue V1, SDValue V2,
2346 SelectionDAG &DAG) {
2347
2348 const auto &Begin = Mask.begin();
2349 const auto &End = Mask.end();
2350 SDValue OriV1 = V1, OriV2 = V2;
2351
2352 if (fitsRegularPattern<int>(Begin, 2, End, 1, 2))
2353 V1 = OriV1;
2354 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size() + 1, 2))
2355 V1 = OriV2;
2356 else
2357 return SDValue();
2358
2359 if (fitsRegularPattern<int>(Begin + 1, 2, End, 1, 2))
2360 V2 = OriV1;
2361 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size() + 1, 2))
2362 V2 = OriV2;
2363 else
2364 return SDValue();
2365
2366 return DAG.getNode(LoongArchISD::VPACKOD, DL, VT, V2, V1);
2367}
2368
2369/// Lower VECTOR_SHUFFLE into VILVH (if possible).
2370///
2371/// VILVH interleaves consecutive elements from the left (highest-indexed) half
2372/// of each vector.
2373///
2374/// It is possible to lower into VILVH when the mask consists of two of the
2375/// following forms interleaved:
2376/// <x, x+1, x+2, ...>
2377/// <n+x, n+x+1, n+x+2, ...>
2378/// where n is the number of elements in the vector and x is half n.
2379/// For example:
2380/// <x, x, x+1, x+1, x+2, x+2, ...>
2381/// <x, n+x, x+1, n+x+1, x+2, n+x+2, ...>
2382///
2383/// When undef's appear in the mask they are treated as if they were whatever
2384/// value is necessary in order to fit the above forms.
2386 MVT VT, SDValue V1, SDValue V2,
2387 SelectionDAG &DAG) {
2388
2389 const auto &Begin = Mask.begin();
2390 const auto &End = Mask.end();
2391 unsigned HalfSize = Mask.size() / 2;
2392 SDValue OriV1 = V1, OriV2 = V2;
2393
2394 if (fitsRegularPattern<int>(Begin, 2, End, HalfSize, 1))
2395 V1 = OriV1;
2396 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size() + HalfSize, 1))
2397 V1 = OriV2;
2398 else
2399 return SDValue();
2400
2401 if (fitsRegularPattern<int>(Begin + 1, 2, End, HalfSize, 1))
2402 V2 = OriV1;
2403 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size() + HalfSize,
2404 1))
2405 V2 = OriV2;
2406 else
2407 return SDValue();
2408
2409 return DAG.getNode(LoongArchISD::VILVH, DL, VT, V2, V1);
2410}
2411
2412/// Lower VECTOR_SHUFFLE into VILVL (if possible).
2413///
2414/// VILVL interleaves consecutive elements from the right (lowest-indexed) half
2415/// of each vector.
2416///
2417/// It is possible to lower into VILVL when the mask consists of two of the
2418/// following forms interleaved:
2419/// <0, 1, 2, ...>
2420/// <n, n+1, n+2, ...>
2421/// where n is the number of elements in the vector.
2422/// For example:
2423/// <0, 0, 1, 1, 2, 2, ...>
2424/// <0, n, 1, n+1, 2, n+2, ...>
2425///
2426/// When undef's appear in the mask they are treated as if they were whatever
2427/// value is necessary in order to fit the above forms.
2429 MVT VT, SDValue V1, SDValue V2,
2430 SelectionDAG &DAG) {
2431
2432 const auto &Begin = Mask.begin();
2433 const auto &End = Mask.end();
2434 SDValue OriV1 = V1, OriV2 = V2;
2435
2436 if (fitsRegularPattern<int>(Begin, 2, End, 0, 1))
2437 V1 = OriV1;
2438 else if (fitsRegularPattern<int>(Begin, 2, End, Mask.size(), 1))
2439 V1 = OriV2;
2440 else
2441 return SDValue();
2442
2443 if (fitsRegularPattern<int>(Begin + 1, 2, End, 0, 1))
2444 V2 = OriV1;
2445 else if (fitsRegularPattern<int>(Begin + 1, 2, End, Mask.size(), 1))
2446 V2 = OriV2;
2447 else
2448 return SDValue();
2449
2450 return DAG.getNode(LoongArchISD::VILVL, DL, VT, V2, V1);
2451}
2452
2453/// Lower VECTOR_SHUFFLE into VPICKEV (if possible).
2454///
2455/// VPICKEV copies the even elements of each vector into the result vector.
2456///
2457/// It is possible to lower into VPICKEV when the mask consists of two of the
2458/// following forms concatenated:
2459/// <0, 2, 4, ...>
2460/// <n, n+2, n+4, ...>
2461/// where n is the number of elements in the vector.
2462/// For example:
2463/// <0, 2, 4, ..., 0, 2, 4, ...>
2464/// <0, 2, 4, ..., n, n+2, n+4, ...>
2465///
2466/// When undef's appear in the mask they are treated as if they were whatever
2467/// value is necessary in order to fit the above forms.
2469 MVT VT, SDValue V1, SDValue V2,
2470 SelectionDAG &DAG) {
2471
2472 const auto &Begin = Mask.begin();
2473 const auto &Mid = Mask.begin() + Mask.size() / 2;
2474 const auto &End = Mask.end();
2475 SDValue OriV1 = V1, OriV2 = V2;
2476
2477 if (fitsRegularPattern<int>(Begin, 1, Mid, 0, 2))
2478 V1 = OriV1;
2479 else if (fitsRegularPattern<int>(Begin, 1, Mid, Mask.size(), 2))
2480 V1 = OriV2;
2481 else
2482 return SDValue();
2483
2484 if (fitsRegularPattern<int>(Mid, 1, End, 0, 2))
2485 V2 = OriV1;
2486 else if (fitsRegularPattern<int>(Mid, 1, End, Mask.size(), 2))
2487 V2 = OriV2;
2488
2489 else
2490 return SDValue();
2491
2492 return DAG.getNode(LoongArchISD::VPICKEV, DL, VT, V2, V1);
2493}
2494
2495/// Lower VECTOR_SHUFFLE into VPICKOD (if possible).
2496///
2497/// VPICKOD copies the odd elements of each vector into the result vector.
2498///
2499/// It is possible to lower into VPICKOD when the mask consists of two of the
2500/// following forms concatenated:
2501/// <1, 3, 5, ...>
2502/// <n+1, n+3, n+5, ...>
2503/// where n is the number of elements in the vector.
2504/// For example:
2505/// <1, 3, 5, ..., 1, 3, 5, ...>
2506/// <1, 3, 5, ..., n+1, n+3, n+5, ...>
2507///
2508/// When undef's appear in the mask they are treated as if they were whatever
2509/// value is necessary in order to fit the above forms.
2511 MVT VT, SDValue V1, SDValue V2,
2512 SelectionDAG &DAG) {
2513
2514 const auto &Begin = Mask.begin();
2515 const auto &Mid = Mask.begin() + Mask.size() / 2;
2516 const auto &End = Mask.end();
2517 SDValue OriV1 = V1, OriV2 = V2;
2518
2519 if (fitsRegularPattern<int>(Begin, 1, Mid, 1, 2))
2520 V1 = OriV1;
2521 else if (fitsRegularPattern<int>(Begin, 1, Mid, Mask.size() + 1, 2))
2522 V1 = OriV2;
2523 else
2524 return SDValue();
2525
2526 if (fitsRegularPattern<int>(Mid, 1, End, 1, 2))
2527 V2 = OriV1;
2528 else if (fitsRegularPattern<int>(Mid, 1, End, Mask.size() + 1, 2))
2529 V2 = OriV2;
2530 else
2531 return SDValue();
2532
2533 return DAG.getNode(LoongArchISD::VPICKOD, DL, VT, V2, V1);
2534}
2535
2536/// Lower VECTOR_SHUFFLE into VEXTRINS (if possible).
2537///
2538/// VEXTRINS copies one element of a vector into any place of the result
2539/// vector and makes no change to the rest elements of the result vector.
2540///
2541/// It is possible to lower into VEXTRINS when the mask takes the form:
2542/// <0, 1, 2, ..., n+i, ..., n-1> or <n, n+1, n+2, ..., i, ..., 2n-1> or
2543/// <0, 1, 2, ..., i, ..., n-1> or <n, n+1, n+2, ..., n+i, ..., 2n-1>
2544/// where n is the number of elements in the vector and i is in [0, n).
2545/// For example:
2546/// <0, 1, 2, 3, 4, 5, 6, 8> , <2, 9, 10, 11, 12, 13, 14, 15> ,
2547/// <0, 1, 2, 6, 4, 5, 6, 7> , <8, 9, 10, 11, 12, 9, 14, 15>
2548///
2549/// When undef's appear in the mask they are treated as if they were whatever
2550/// value is necessary in order to fit the above forms.
2551static SDValue
2553 SDValue V1, SDValue V2, SelectionDAG &DAG,
2555 unsigned NumElts = VT.getVectorNumElements();
2556 MVT EltVT = VT.getVectorElementType();
2557 MVT GRLenVT = Subtarget.getGRLenVT();
2558
2559 if (Mask.size() != NumElts)
2560 return SDValue();
2561
2562 auto tryLowerToExtrAndIns = [&](unsigned Base) -> SDValue {
2563 int DiffCount = 0;
2564 int DiffPos = -1;
2565 for (unsigned i = 0; i < NumElts; ++i) {
2566 if (Mask[i] == -1)
2567 continue;
2568 if (Mask[i] != int(Base + i)) {
2569 ++DiffCount;
2570 DiffPos = int(i);
2571 if (DiffCount > 1)
2572 return SDValue();
2573 }
2574 }
2575
2576 // Need exactly one differing element to lower into VEXTRINS.
2577 if (DiffCount != 1)
2578 return SDValue();
2579
2580 // DiffMask must be in [0, 2N).
2581 int DiffMask = Mask[DiffPos];
2582 if (DiffMask < 0 || DiffMask >= int(2 * NumElts))
2583 return SDValue();
2584
2585 // Determine source vector and source index.
2586 SDValue SrcVec;
2587 unsigned SrcIdx;
2588 if (unsigned(DiffMask) < NumElts) {
2589 SrcVec = V1;
2590 SrcIdx = unsigned(DiffMask);
2591 } else {
2592 SrcVec = V2;
2593 SrcIdx = unsigned(DiffMask) - NumElts;
2594 }
2595
2596 // Replace with EXTRACT_VECTOR_ELT + INSERT_VECTOR_ELT, it will match the
2597 // patterns of VEXTRINS in tablegen.
2598 SDValue Extracted = DAG.getNode(
2599 ISD::EXTRACT_VECTOR_ELT, DL, EltVT.isFloatingPoint() ? EltVT : GRLenVT,
2600 SrcVec, DAG.getConstant(SrcIdx, DL, GRLenVT));
2601 SDValue Result =
2602 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, (Base == 0) ? V1 : V2,
2603 Extracted, DAG.getConstant(DiffPos, DL, GRLenVT));
2604
2605 return Result;
2606 };
2607
2608 // Try [0, n-1) insertion then [n, 2n-1) insertion.
2609 if (SDValue Result = tryLowerToExtrAndIns(0))
2610 return Result;
2611 return tryLowerToExtrAndIns(NumElts);
2612}
2613
2614// Check the Mask and then build SrcVec and MaskImm infos which will
2615// be used to build LoongArchISD nodes for VPERMI_W or XVPERMI_W.
2616// On success, return true. Otherwise, return false.
2619 unsigned &MaskImm) {
2620 unsigned MaskSize = Mask.size();
2621
2622 auto isValid = [&](int M, int Off) {
2623 return (M == -1) || (M >= Off && M < Off + 4);
2624 };
2625
2626 auto buildImm = [&](int MLo, int MHi, unsigned Off, unsigned I) {
2627 auto immPart = [&](int M, unsigned Off) {
2628 return (M == -1 ? 0 : (M - Off)) & 0x3;
2629 };
2630 MaskImm |= immPart(MLo, Off) << (I * 2);
2631 MaskImm |= immPart(MHi, Off) << ((I + 1) * 2);
2632 };
2633
2634 for (unsigned i = 0; i < 4; i += 2) {
2635 int MLo = Mask[i];
2636 int MHi = Mask[i + 1];
2637
2638 if (MaskSize == 8) { // Only v8i32/v8f32 need this check.
2639 auto isValid2 = [&](int &M, int M2) {
2640 // If high half index is undef, it's always valid.
2641 if (M2 == -1)
2642 return true;
2643 if (M == -1) {
2644 // If low half index is undef, use index from high half,
2645 // remapped to low half.
2646 if ((M2 % MaskSize) < 4)
2647 return false;
2648 M = M2 - 4;
2649 return true;
2650 }
2651 // Index in low half must be same as index in high half.
2652 return M2 == M + 4;
2653 };
2654 if (!isValid2(MLo, Mask[i + 4]) || !isValid2(MHi, Mask[i + 5]))
2655 return false;
2656 }
2657
2658 if (isValid(MLo, 0) && isValid(MHi, 0)) {
2659 SrcVec.push_back(V1);
2660 buildImm(MLo, MHi, 0, i);
2661 } else if (isValid(MLo, MaskSize) && isValid(MHi, MaskSize)) {
2662 SrcVec.push_back(V2);
2663 buildImm(MLo, MHi, MaskSize, i);
2664 } else {
2665 return false;
2666 }
2667 }
2668
2669 return true;
2670}
2671
2672/// Lower VECTOR_SHUFFLE into VPERMI (if possible).
2673///
2674/// VPERMI selects two elements from each of the two vectors based on the
2675/// mask and places them in the corresponding positions of the result vector
2676/// in order. Only v4i32 and v4f32 types are allowed.
2677///
2678/// It is possible to lower into VPERMI when the mask consists of two of the
2679/// following forms concatenated:
2680/// <i, j, u, v>
2681/// <u, v, i, j>
2682/// where i,j are in [0,4) and u,v are in [4, 8).
2683/// For example:
2684/// <2, 3, 4, 5>
2685/// <5, 7, 0, 2>
2686///
2687/// When undef's appear in the mask they are treated as if they were whatever
2688/// value is necessary in order to fit the above forms.
2690 MVT VT, SDValue V1, SDValue V2,
2691 SelectionDAG &DAG,
2693 if ((VT != MVT::v4i32 && VT != MVT::v4f32) ||
2694 Mask.size() != VT.getVectorNumElements())
2695 return SDValue();
2696
2698 unsigned MaskImm = 0;
2699 if (!buildVPERMIInfo(Mask, V1, V2, SrcVec, MaskImm))
2700 return SDValue();
2701
2702 return DAG.getNode(LoongArchISD::VPERMI, DL, VT, SrcVec[1], SrcVec[0],
2703 DAG.getConstant(MaskImm, DL, Subtarget.getGRLenVT()));
2704}
2705
2706/// Lower VECTOR_SHUFFLE into VSHUF.
2707///
2708/// This mostly consists of converting the shuffle mask into a BUILD_VECTOR and
2709/// adding it as an operand to the resulting VSHUF.
2711 MVT VT, SDValue V1, SDValue V2,
2712 SelectionDAG &DAG,
2714
2716 for (auto M : Mask)
2717 Ops.push_back(DAG.getSignedConstant(M, DL, Subtarget.getGRLenVT()));
2718
2719 EVT MaskVecTy = VT.changeVectorElementTypeToInteger();
2720 SDValue MaskVec = DAG.getBuildVector(MaskVecTy, DL, Ops);
2721
2722 // VECTOR_SHUFFLE concatenates the vectors in an vectorwise fashion.
2723 // <0b00, 0b01> + <0b10, 0b11> -> <0b00, 0b01, 0b10, 0b11>
2724 // VSHF concatenates the vectors in a bitwise fashion:
2725 // <0b00, 0b01> + <0b10, 0b11> ->
2726 // 0b0100 + 0b1110 -> 0b01001110
2727 // <0b10, 0b11, 0b00, 0b01>
2728 // We must therefore swap the operands to get the correct result.
2729 return DAG.getNode(LoongArchISD::VSHUF, DL, VT, MaskVec, V2, V1);
2730}
2731
2732/// Dispatching routine to lower various 128-bit LoongArch vector shuffles.
2733///
2734/// This routine breaks down the specific type of 128-bit shuffle and
2735/// dispatches to the lowering routines accordingly.
2737 SDValue V1, SDValue V2, SelectionDAG &DAG,
2739 assert((VT.SimpleTy == MVT::v16i8 || VT.SimpleTy == MVT::v8i16 ||
2740 VT.SimpleTy == MVT::v4i32 || VT.SimpleTy == MVT::v2i64 ||
2741 VT.SimpleTy == MVT::v4f32 || VT.SimpleTy == MVT::v2f64) &&
2742 "Vector type is unsupported for lsx!");
2743 assert(V1.getSimpleValueType() == V2.getSimpleValueType() &&
2744 "Two operands have different types!");
2745 assert(VT.getVectorNumElements() == Mask.size() &&
2746 "Unexpected mask size for shuffle!");
2747 assert(Mask.size() % 2 == 0 && "Expected even mask size.");
2748
2749 APInt KnownUndef, KnownZero;
2750 computeZeroableShuffleElements(Mask, V1, V2, KnownUndef, KnownZero);
2751 APInt Zeroable = KnownUndef | KnownZero;
2752
2753 SDValue Result;
2754 // TODO: Add more comparison patterns.
2755 if (V2.isUndef()) {
2756 if ((Result =
2757 lowerVECTOR_SHUFFLE_VREPLVEI(DL, Mask, VT, V1, DAG, Subtarget)))
2758 return Result;
2759 if ((Result =
2760 lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2761 return Result;
2762 if ((Result =
2763 lowerVECTOR_SHUFFLE_IsReverse(DL, Mask, VT, V1, DAG, Subtarget)))
2764 return Result;
2765
2766 // TODO: This comment may be enabled in the future to better match the
2767 // pattern for instruction selection.
2768 /* V2 = V1; */
2769 }
2770
2771 // It is recommended not to change the pattern comparison order for better
2772 // performance.
2773 if ((Result = lowerVECTOR_SHUFFLE_VPACKEV(DL, Mask, VT, V1, V2, DAG)))
2774 return Result;
2775 if ((Result = lowerVECTOR_SHUFFLE_VPACKOD(DL, Mask, VT, V1, V2, DAG)))
2776 return Result;
2777 if ((Result = lowerVECTOR_SHUFFLE_VILVH(DL, Mask, VT, V1, V2, DAG)))
2778 return Result;
2779 if ((Result = lowerVECTOR_SHUFFLE_VILVL(DL, Mask, VT, V1, V2, DAG)))
2780 return Result;
2781 if ((Result = lowerVECTOR_SHUFFLE_VPICKEV(DL, Mask, VT, V1, V2, DAG)))
2782 return Result;
2783 if ((Result = lowerVECTOR_SHUFFLE_VPICKOD(DL, Mask, VT, V1, V2, DAG)))
2784 return Result;
2785 if ((VT.SimpleTy == MVT::v2i64 || VT.SimpleTy == MVT::v2f64) &&
2786 (Result =
2787 lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2788 return Result;
2789 if ((Result =
2790 lowerVECTOR_SHUFFLE_VEXTRINS(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2791 return Result;
2792 if ((Result = lowerVECTOR_SHUFFLEAsShift(DL, Mask, VT, V1, V2, DAG, Subtarget,
2793 Zeroable)))
2794 return Result;
2795 if ((Result =
2796 lowerVECTOR_SHUFFLE_VPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2797 return Result;
2798 if ((Result = lowerVECTOR_SHUFFLEAsZeroOrAnyExtend(DL, Mask, VT, V1, V2, DAG,
2799 Zeroable)))
2800 return Result;
2801 if ((Result = lowerVECTOR_SHUFFLEAsByteRotate(DL, Mask, VT, V1, V2, DAG,
2802 Subtarget)))
2803 return Result;
2804 if (SDValue NewShuffle = widenShuffleMask(DL, Mask, VT, V1, V2, DAG))
2805 return NewShuffle;
2806 if ((Result =
2807 lowerVECTOR_SHUFFLE_VSHUF(DL, Mask, VT, V1, V2, DAG, Subtarget)))
2808 return Result;
2809 return SDValue();
2810}
2811
2812/// Lower VECTOR_SHUFFLE into XVREPLVEI (if possible).
2813///
2814/// It is a XVREPLVEI when the mask is:
2815/// <x, x, x, ..., x+n, x+n, x+n, ...>
2816/// where the number of x is equal to n and n is half the length of vector.
2817///
2818/// When undef's appear in the mask they are treated as if they were whatever
2819/// value is necessary in order to fit the above form.
2820static SDValue
2822 SDValue V1, SelectionDAG &DAG,
2824 int SplatIndex = -1;
2825 for (const auto &M : Mask) {
2826 if (M != -1) {
2827 SplatIndex = M;
2828 break;
2829 }
2830 }
2831
2832 if (SplatIndex == -1)
2833 return DAG.getUNDEF(VT);
2834
2835 const auto &Begin = Mask.begin();
2836 const auto &End = Mask.end();
2837 int HalfSize = Mask.size() / 2;
2838
2839 if (SplatIndex >= HalfSize)
2840 return SDValue();
2841
2842 assert(SplatIndex < (int)Mask.size() && "Out of bounds mask index");
2843 if (fitsRegularPattern<int>(Begin, 1, End - HalfSize, SplatIndex, 0) &&
2844 fitsRegularPattern<int>(Begin + HalfSize, 1, End, SplatIndex + HalfSize,
2845 0)) {
2846 return DAG.getNode(LoongArchISD::VREPLVEI, DL, VT, V1,
2847 DAG.getConstant(SplatIndex, DL, Subtarget.getGRLenVT()));
2848 }
2849
2850 return SDValue();
2851}
2852
2853/// Lower VECTOR_SHUFFLE into XVSHUF4I (if possible).
2854static SDValue
2856 SDValue V1, SDValue V2, SelectionDAG &DAG,
2858 // XVSHUF4I_D must be handled separately because it is different from other
2859 // types of [X]VSHUF4I instructions.
2860 if (Mask.size() == 4) {
2861 unsigned MaskImm = 0;
2862 for (int i = 1; i >= 0; --i) {
2863 int MLo = Mask[i];
2864 int MHi = Mask[i + 2];
2865 if (!(MLo == -1 || (MLo >= 0 && MLo <= 1) || (MLo >= 4 && MLo <= 5)) ||
2866 !(MHi == -1 || (MHi >= 2 && MHi <= 3) || (MHi >= 6 && MHi <= 7)))
2867 return SDValue();
2868 if (MHi != -1 && MLo != -1 && MHi != MLo + 2)
2869 return SDValue();
2870
2871 MaskImm <<= 2;
2872 if (MLo != -1)
2873 MaskImm |= ((MLo <= 1) ? MLo : (MLo - 2)) & 0x3;
2874 else if (MHi != -1)
2875 MaskImm |= ((MHi <= 3) ? (MHi - 2) : (MHi - 4)) & 0x3;
2876 }
2877
2878 return DAG.getNode(LoongArchISD::VSHUF4I_D, DL, VT, V1, V2,
2879 DAG.getConstant(MaskImm, DL, Subtarget.getGRLenVT()));
2880 }
2881
2882 return lowerVECTOR_SHUFFLE_VSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget);
2883}
2884
2885/// Lower VECTOR_SHUFFLE into XVREPLVE0 (if possible).
2886///
2887/// It is a XVREPLVE0 when the VECTOR_SHUFFLE is a broadcast of element 0,
2888/// i.e. the mask is:
2889/// <0, 0, 0, ...>
2890///
2891/// When undef's appear in the mask they are treated as if they were whatever
2892/// value is necessary in order to fit the above form.
2894 ArrayRef<int> Mask, MVT VT,
2895 SDValue V1, SelectionDAG &DAG) {
2896 if (!ShuffleVectorInst::isZeroEltSplatMask(Mask, Mask.size()))
2897 return SDValue();
2898
2899 return DAG.getNode(LoongArchISD::XVREPLVE0, DL, VT, V1);
2900}
2901
2902/// Lower VECTOR_SHUFFLE into XVPERMI (if possible).
2903static SDValue
2905 SDValue V1, SDValue V2, SelectionDAG &DAG,
2907 MVT GRLenVT = Subtarget.getGRLenVT();
2908 unsigned MaskSize = Mask.size();
2909 if (MaskSize != VT.getVectorNumElements())
2910 return SDValue();
2911
2912 // Consider XVPERMI_W.
2913 if (VT == MVT::v8i32 || VT == MVT::v8f32) {
2915 unsigned MaskImm = 0;
2916 if (!buildVPERMIInfo(Mask, V1, V2, SrcVec, MaskImm))
2917 return SDValue();
2918
2919 return DAG.getNode(LoongArchISD::VPERMI, DL, VT, SrcVec[1], SrcVec[0],
2920 DAG.getConstant(MaskImm, DL, GRLenVT));
2921 }
2922
2923 // Consider XVPERMI_D.
2924 if (VT == MVT::v4i64 || VT == MVT::v4f64) {
2925 unsigned MaskImm = 0;
2926 for (unsigned i = 0; i < MaskSize; ++i) {
2927 if (Mask[i] == -1)
2928 continue;
2929 if (Mask[i] >= (int)MaskSize)
2930 return SDValue();
2931 MaskImm |= Mask[i] << (i * 2);
2932 }
2933
2934 return DAG.getNode(LoongArchISD::XVPERMI, DL, VT, V1,
2935 DAG.getConstant(MaskImm, DL, GRLenVT));
2936 }
2937
2938 return SDValue();
2939}
2940
2941/// Lower VECTOR_SHUFFLE into XVPERM (if possible).
2943 MVT VT, SDValue V1, SelectionDAG &DAG,
2945 // LoongArch LASX only have XVPERM_W.
2946 if (Mask.size() != 8 || (VT != MVT::v8i32 && VT != MVT::v8f32))
2947 return SDValue();
2948
2949 unsigned NumElts = VT.getVectorNumElements();
2950 unsigned HalfSize = NumElts / 2;
2951 bool FrontLo = true, FrontHi = true;
2952 bool BackLo = true, BackHi = true;
2953
2954 auto inRange = [](int val, int low, int high) {
2955 return (val == -1) || (val >= low && val < high);
2956 };
2957
2958 for (unsigned i = 0; i < HalfSize; ++i) {
2959 int Fronti = Mask[i];
2960 int Backi = Mask[i + HalfSize];
2961
2962 FrontLo &= inRange(Fronti, 0, HalfSize);
2963 FrontHi &= inRange(Fronti, HalfSize, NumElts);
2964 BackLo &= inRange(Backi, 0, HalfSize);
2965 BackHi &= inRange(Backi, HalfSize, NumElts);
2966 }
2967
2968 // If both the lower and upper 128-bit parts access only one half of the
2969 // vector (either lower or upper), avoid using xvperm.w. The latency of
2970 // xvperm.w(3) is higher than using xvshuf(1) and xvori(1).
2971 if ((FrontLo || FrontHi) && (BackLo || BackHi))
2972 return SDValue();
2973
2975 MVT GRLenVT = Subtarget.getGRLenVT();
2976 for (unsigned i = 0; i < NumElts; ++i)
2977 Masks.push_back(Mask[i] == -1 ? DAG.getUNDEF(GRLenVT)
2978 : DAG.getConstant(Mask[i], DL, GRLenVT));
2979 SDValue MaskVec = DAG.getBuildVector(MVT::v8i32, DL, Masks);
2980
2981 return DAG.getNode(LoongArchISD::XVPERM, DL, VT, V1, MaskVec);
2982}
2983
2984/// Lower VECTOR_SHUFFLE into XVPACKEV (if possible).
2986 MVT VT, SDValue V1, SDValue V2,
2987 SelectionDAG &DAG) {
2988 return lowerVECTOR_SHUFFLE_VPACKEV(DL, Mask, VT, V1, V2, DAG);
2989}
2990
2991/// Lower VECTOR_SHUFFLE into XVPACKOD (if possible).
2993 MVT VT, SDValue V1, SDValue V2,
2994 SelectionDAG &DAG) {
2995 return lowerVECTOR_SHUFFLE_VPACKOD(DL, Mask, VT, V1, V2, DAG);
2996}
2997
2998/// Lower VECTOR_SHUFFLE into XVILVH (if possible).
3000 MVT VT, SDValue V1, SDValue V2,
3001 SelectionDAG &DAG) {
3002
3003 const auto &Begin = Mask.begin();
3004 const auto &End = Mask.end();
3005 unsigned HalfSize = Mask.size() / 2;
3006 unsigned LeftSize = HalfSize / 2;
3007 SDValue OriV1 = V1, OriV2 = V2;
3008
3009 if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, HalfSize - LeftSize,
3010 1) &&
3011 fitsRegularPattern<int>(Begin + HalfSize, 2, End, HalfSize + LeftSize, 1))
3012 V1 = OriV1;
3013 else if (fitsRegularPattern<int>(Begin, 2, End - HalfSize,
3014 Mask.size() + HalfSize - LeftSize, 1) &&
3015 fitsRegularPattern<int>(Begin + HalfSize, 2, End,
3016 Mask.size() + HalfSize + LeftSize, 1))
3017 V1 = OriV2;
3018 else
3019 return SDValue();
3020
3021 if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, HalfSize - LeftSize,
3022 1) &&
3023 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End, HalfSize + LeftSize,
3024 1))
3025 V2 = OriV1;
3026 else if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize,
3027 Mask.size() + HalfSize - LeftSize, 1) &&
3028 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End,
3029 Mask.size() + HalfSize + LeftSize, 1))
3030 V2 = OriV2;
3031 else
3032 return SDValue();
3033
3034 return DAG.getNode(LoongArchISD::VILVH, DL, VT, V2, V1);
3035}
3036
3037/// Lower VECTOR_SHUFFLE into XVILVL (if possible).
3039 MVT VT, SDValue V1, SDValue V2,
3040 SelectionDAG &DAG) {
3041
3042 const auto &Begin = Mask.begin();
3043 const auto &End = Mask.end();
3044 unsigned HalfSize = Mask.size() / 2;
3045 SDValue OriV1 = V1, OriV2 = V2;
3046
3047 if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, 0, 1) &&
3048 fitsRegularPattern<int>(Begin + HalfSize, 2, End, HalfSize, 1))
3049 V1 = OriV1;
3050 else if (fitsRegularPattern<int>(Begin, 2, End - HalfSize, Mask.size(), 1) &&
3051 fitsRegularPattern<int>(Begin + HalfSize, 2, End,
3052 Mask.size() + HalfSize, 1))
3053 V1 = OriV2;
3054 else
3055 return SDValue();
3056
3057 if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, 0, 1) &&
3058 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End, HalfSize, 1))
3059 V2 = OriV1;
3060 else if (fitsRegularPattern<int>(Begin + 1, 2, End - HalfSize, Mask.size(),
3061 1) &&
3062 fitsRegularPattern<int>(Begin + 1 + HalfSize, 2, End,
3063 Mask.size() + HalfSize, 1))
3064 V2 = OriV2;
3065 else
3066 return SDValue();
3067
3068 return DAG.getNode(LoongArchISD::VILVL, DL, VT, V2, V1);
3069}
3070
3071/// Lower VECTOR_SHUFFLE into XVPICKEV (if possible).
3073 MVT VT, SDValue V1, SDValue V2,
3074 SelectionDAG &DAG) {
3075
3076 const auto &Begin = Mask.begin();
3077 const auto &LeftMid = Mask.begin() + Mask.size() / 4;
3078 const auto &Mid = Mask.begin() + Mask.size() / 2;
3079 const auto &RightMid = Mask.end() - Mask.size() / 4;
3080 const auto &End = Mask.end();
3081 unsigned HalfSize = Mask.size() / 2;
3082 SDValue OriV1 = V1, OriV2 = V2;
3083
3084 if (fitsRegularPattern<int>(Begin, 1, LeftMid, 0, 2) &&
3085 fitsRegularPattern<int>(Mid, 1, RightMid, HalfSize, 2))
3086 V1 = OriV1;
3087 else if (fitsRegularPattern<int>(Begin, 1, LeftMid, Mask.size(), 2) &&
3088 fitsRegularPattern<int>(Mid, 1, RightMid, Mask.size() + HalfSize, 2))
3089 V1 = OriV2;
3090 else
3091 return SDValue();
3092
3093 if (fitsRegularPattern<int>(LeftMid, 1, Mid, 0, 2) &&
3094 fitsRegularPattern<int>(RightMid, 1, End, HalfSize, 2))
3095 V2 = OriV1;
3096 else if (fitsRegularPattern<int>(LeftMid, 1, Mid, Mask.size(), 2) &&
3097 fitsRegularPattern<int>(RightMid, 1, End, Mask.size() + HalfSize, 2))
3098 V2 = OriV2;
3099
3100 else
3101 return SDValue();
3102
3103 return DAG.getNode(LoongArchISD::VPICKEV, DL, VT, V2, V1);
3104}
3105
3106/// Lower VECTOR_SHUFFLE into XVPICKOD (if possible).
3108 MVT VT, SDValue V1, SDValue V2,
3109 SelectionDAG &DAG) {
3110
3111 const auto &Begin = Mask.begin();
3112 const auto &LeftMid = Mask.begin() + Mask.size() / 4;
3113 const auto &Mid = Mask.begin() + Mask.size() / 2;
3114 const auto &RightMid = Mask.end() - Mask.size() / 4;
3115 const auto &End = Mask.end();
3116 unsigned HalfSize = Mask.size() / 2;
3117 SDValue OriV1 = V1, OriV2 = V2;
3118
3119 if (fitsRegularPattern<int>(Begin, 1, LeftMid, 1, 2) &&
3120 fitsRegularPattern<int>(Mid, 1, RightMid, HalfSize + 1, 2))
3121 V1 = OriV1;
3122 else if (fitsRegularPattern<int>(Begin, 1, LeftMid, Mask.size() + 1, 2) &&
3123 fitsRegularPattern<int>(Mid, 1, RightMid, Mask.size() + HalfSize + 1,
3124 2))
3125 V1 = OriV2;
3126 else
3127 return SDValue();
3128
3129 if (fitsRegularPattern<int>(LeftMid, 1, Mid, 1, 2) &&
3130 fitsRegularPattern<int>(RightMid, 1, End, HalfSize + 1, 2))
3131 V2 = OriV1;
3132 else if (fitsRegularPattern<int>(LeftMid, 1, Mid, Mask.size() + 1, 2) &&
3133 fitsRegularPattern<int>(RightMid, 1, End, Mask.size() + HalfSize + 1,
3134 2))
3135 V2 = OriV2;
3136 else
3137 return SDValue();
3138
3139 return DAG.getNode(LoongArchISD::VPICKOD, DL, VT, V2, V1);
3140}
3141
3142/// Lower VECTOR_SHUFFLE into XVEXTRINS (if possible).
3143static SDValue
3145 SDValue V1, SDValue V2, SelectionDAG &DAG,
3147 int NumElts = VT.getVectorNumElements();
3148 int HalfSize = NumElts / 2;
3149 MVT EltVT = VT.getVectorElementType();
3150 MVT GRLenVT = Subtarget.getGRLenVT();
3151
3152 if ((int)Mask.size() != NumElts)
3153 return SDValue();
3154
3155 auto tryLowerToExtrAndIns = [&](int Base) -> SDValue {
3156 SmallVector<int> DiffPos;
3157 for (int i = 0; i < NumElts; ++i) {
3158 if (Mask[i] == -1)
3159 continue;
3160 if (Mask[i] != Base + i) {
3161 DiffPos.push_back(i);
3162 if (DiffPos.size() > 2)
3163 return SDValue();
3164 }
3165 }
3166
3167 // Need exactly two differing element to lower into XVEXTRINS.
3168 // If only one differing element, the element at a distance of
3169 // HalfSize from it must be undef.
3170 if (DiffPos.size() == 1) {
3171 if (DiffPos[0] < HalfSize && Mask[DiffPos[0] + HalfSize] == -1)
3172 DiffPos.push_back(DiffPos[0] + HalfSize);
3173 else if (DiffPos[0] >= HalfSize && Mask[DiffPos[0] - HalfSize] == -1)
3174 DiffPos.insert(DiffPos.begin(), DiffPos[0] - HalfSize);
3175 else
3176 return SDValue();
3177 }
3178 if (DiffPos.size() != 2 || DiffPos[1] != DiffPos[0] + HalfSize)
3179 return SDValue();
3180
3181 // DiffMask must be in its low or high part.
3182 int DiffMaskLo = Mask[DiffPos[0]];
3183 int DiffMaskHi = Mask[DiffPos[1]];
3184 DiffMaskLo = DiffMaskLo == -1 ? DiffMaskHi - HalfSize : DiffMaskLo;
3185 DiffMaskHi = DiffMaskHi == -1 ? DiffMaskLo + HalfSize : DiffMaskHi;
3186 if (!(DiffMaskLo >= 0 && DiffMaskLo < HalfSize) &&
3187 !(DiffMaskLo >= NumElts && DiffMaskLo < NumElts + HalfSize))
3188 return SDValue();
3189 if (!(DiffMaskHi >= HalfSize && DiffMaskHi < NumElts) &&
3190 !(DiffMaskHi >= NumElts + HalfSize && DiffMaskHi < 2 * NumElts))
3191 return SDValue();
3192 if (DiffMaskHi != DiffMaskLo + HalfSize)
3193 return SDValue();
3194
3195 // Determine source vector and source index.
3196 SDValue SrcVec = (DiffMaskLo < HalfSize) ? V1 : V2;
3197 int SrcIdxLo =
3198 (DiffMaskLo < HalfSize) ? DiffMaskLo : (DiffMaskLo - NumElts);
3199 bool IsEltFP = EltVT.isFloatingPoint();
3200
3201 // Replace with 2*EXTRACT_VECTOR_ELT + 2*INSERT_VECTOR_ELT, it will match
3202 // the patterns of XVEXTRINS in tablegen.
3203 SDValue BaseVec = (Base == 0) ? V1 : V2;
3204 SDValue EltLo =
3205 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IsEltFP ? EltVT : GRLenVT,
3206 SrcVec, DAG.getConstant(SrcIdxLo, DL, GRLenVT));
3207 SDValue InsLo = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, BaseVec, EltLo,
3208 DAG.getConstant(DiffPos[0], DL, GRLenVT));
3209 SDValue EltHi =
3210 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IsEltFP ? EltVT : GRLenVT,
3211 SrcVec, DAG.getConstant(SrcIdxLo + HalfSize, DL, GRLenVT));
3212 SDValue Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, InsLo, EltHi,
3213 DAG.getConstant(DiffPos[1], DL, GRLenVT));
3214
3215 return Result;
3216 };
3217
3218 // Try [0, n-1) insertion then [n, 2n-1) insertion.
3219 if (SDValue Result = tryLowerToExtrAndIns(0))
3220 return Result;
3221 return tryLowerToExtrAndIns(NumElts);
3222}
3223
3224/// Lower VECTOR_SHUFFLE into XVINSVE0 (if possible).
3225static SDValue
3227 SDValue V1, SDValue V2, SelectionDAG &DAG,
3229 // LoongArch LASX only supports xvinsve0.{w/d}.
3230 if (VT != MVT::v8i32 && VT != MVT::v8f32 && VT != MVT::v4i64 &&
3231 VT != MVT::v4f64)
3232 return SDValue();
3233
3234 MVT GRLenVT = Subtarget.getGRLenVT();
3235 int MaskSize = Mask.size();
3236 assert(MaskSize == (int)VT.getVectorNumElements() && "Unexpected mask size");
3237
3238 // Check if exactly one element of the Mask is replaced by 'Replaced', while
3239 // all other elements are either 'Base + i' or undef (-1). On success, return
3240 // the index of the replaced element. Otherwise, just return -1.
3241 auto checkReplaceOne = [&](int Base, int Replaced) -> int {
3242 int Idx = -1;
3243 for (int i = 0; i < MaskSize; ++i) {
3244 if (Mask[i] == Base + i || Mask[i] == -1)
3245 continue;
3246 if (Mask[i] != Replaced)
3247 return -1;
3248 if (Idx == -1)
3249 Idx = i;
3250 else
3251 return -1;
3252 }
3253 return Idx;
3254 };
3255
3256 // Case 1: the lowest element of V2 replaces one element in V1.
3257 int Idx = checkReplaceOne(0, MaskSize);
3258 if (Idx != -1)
3259 return DAG.getNode(LoongArchISD::XVINSVE0, DL, VT, V1, V2,
3260 DAG.getConstant(Idx, DL, GRLenVT));
3261
3262 // Case 2: the lowest element of V1 replaces one element in V2.
3263 Idx = checkReplaceOne(MaskSize, 0);
3264 if (Idx != -1)
3265 return DAG.getNode(LoongArchISD::XVINSVE0, DL, VT, V2, V1,
3266 DAG.getConstant(Idx, DL, GRLenVT));
3267
3268 return SDValue();
3269}
3270
3271/// Lower VECTOR_SHUFFLE into XVSHUF (if possible).
3273 MVT VT, SDValue V1, SDValue V2,
3274 SelectionDAG &DAG) {
3275
3276 int MaskSize = Mask.size();
3277 int HalfSize = Mask.size() / 2;
3278 const auto &Begin = Mask.begin();
3279 const auto &Mid = Mask.begin() + HalfSize;
3280 const auto &End = Mask.end();
3281
3282 // VECTOR_SHUFFLE concatenates the vectors:
3283 // <0, 1, 2, 3, 4, 5, 6, 7> + <8, 9, 10, 11, 12, 13, 14, 15>
3284 // shuffling ->
3285 // <0, 1, 2, 3, 8, 9, 10, 11> <4, 5, 6, 7, 12, 13, 14, 15>
3286 //
3287 // XVSHUF concatenates the vectors:
3288 // <a0, a1, a2, a3, b0, b1, b2, b3> + <a4, a5, a6, a7, b4, b5, b6, b7>
3289 // shuffling ->
3290 // <a0, a1, a2, a3, a4, a5, a6, a7> + <b0, b1, b2, b3, b4, b5, b6, b7>
3291 SmallVector<SDValue, 8> MaskAlloc;
3292 for (auto it = Begin; it < Mid; it++) {
3293 if (*it < 0) // UNDEF
3294 MaskAlloc.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3295 else if ((*it >= 0 && *it < HalfSize) ||
3296 (*it >= MaskSize && *it < MaskSize + HalfSize)) {
3297 int M = *it < HalfSize ? *it : *it - HalfSize;
3298 MaskAlloc.push_back(DAG.getTargetConstant(M, DL, MVT::i64));
3299 } else
3300 return SDValue();
3301 }
3302 assert((int)MaskAlloc.size() == HalfSize && "xvshuf convert failed!");
3303
3304 for (auto it = Mid; it < End; it++) {
3305 if (*it < 0) // UNDEF
3306 MaskAlloc.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3307 else if ((*it >= HalfSize && *it < MaskSize) ||
3308 (*it >= MaskSize + HalfSize && *it < MaskSize * 2)) {
3309 int M = *it < MaskSize ? *it - HalfSize : *it - MaskSize;
3310 MaskAlloc.push_back(DAG.getTargetConstant(M, DL, MVT::i64));
3311 } else
3312 return SDValue();
3313 }
3314 assert((int)MaskAlloc.size() == MaskSize && "xvshuf convert failed!");
3315
3316 EVT MaskVecTy = VT.changeVectorElementTypeToInteger();
3317 SDValue MaskVec = DAG.getBuildVector(MaskVecTy, DL, MaskAlloc);
3318 return DAG.getNode(LoongArchISD::VSHUF, DL, VT, MaskVec, V2, V1);
3319}
3320
3321/// Shuffle vectors by lane to generate more optimized instructions.
3322/// 256-bit shuffles are always considered as 2-lane 128-bit shuffles.
3323///
3324/// Therefore, except for the following four cases, other cases are regarded
3325/// as cross-lane shuffles, where optimization is relatively limited.
3326///
3327/// - Shuffle high, low lanes of two inputs vector
3328/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <0, 5, 3, 6>
3329/// - Shuffle low, high lanes of two inputs vector
3330/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <3, 6, 0, 5>
3331/// - Shuffle low, low lanes of two inputs vector
3332/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <3, 6, 3, 6>
3333/// - Shuffle high, high lanes of two inputs vector
3334/// <0, 1, 2, 3> + <4, 5, 6, 7> --- <0, 5, 0, 5>
3335///
3336/// The first case is the closest to LoongArch instructions and the other
3337/// cases need to be converted to it for processing.
3338///
3339/// This function will return true for the last three cases above and will
3340/// modify V1, V2 and Mask. Otherwise, return false for the first case and
3341/// cross-lane shuffle cases.
3343 const SDLoc &DL, MutableArrayRef<int> Mask, MVT VT, SDValue &V1,
3345
3346 enum HalfMaskType { HighLaneTy, LowLaneTy, None };
3347
3348 int MaskSize = Mask.size();
3349 int HalfSize = Mask.size() / 2;
3350 MVT GRLenVT = Subtarget.getGRLenVT();
3351
3352 HalfMaskType preMask = None, postMask = None;
3353
3354 if (std::all_of(Mask.begin(), Mask.begin() + HalfSize, [&](int M) {
3355 return M < 0 || (M >= 0 && M < HalfSize) ||
3356 (M >= MaskSize && M < MaskSize + HalfSize);
3357 }))
3358 preMask = HighLaneTy;
3359 else if (std::all_of(Mask.begin(), Mask.begin() + HalfSize, [&](int M) {
3360 return M < 0 || (M >= HalfSize && M < MaskSize) ||
3361 (M >= MaskSize + HalfSize && M < MaskSize * 2);
3362 }))
3363 preMask = LowLaneTy;
3364
3365 if (std::all_of(Mask.begin() + HalfSize, Mask.end(), [&](int M) {
3366 return M < 0 || (M >= HalfSize && M < MaskSize) ||
3367 (M >= MaskSize + HalfSize && M < MaskSize * 2);
3368 }))
3369 postMask = LowLaneTy;
3370 else if (std::all_of(Mask.begin() + HalfSize, Mask.end(), [&](int M) {
3371 return M < 0 || (M >= 0 && M < HalfSize) ||
3372 (M >= MaskSize && M < MaskSize + HalfSize);
3373 }))
3374 postMask = HighLaneTy;
3375
3376 // The pre-half of mask is high lane type, and the post-half of mask
3377 // is low lane type, which is closest to the LoongArch instructions.
3378 //
3379 // Note: In the LoongArch architecture, the high lane of mask corresponds
3380 // to the lower 128-bit of vector register, and the low lane of mask
3381 // corresponds the higher 128-bit of vector register.
3382 if (preMask == HighLaneTy && postMask == LowLaneTy) {
3383 return false;
3384 }
3385 if (preMask == LowLaneTy && postMask == HighLaneTy) {
3386 V1 = DAG.getBitcast(MVT::v4i64, V1);
3387 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3388 DAG.getConstant(0b01001110, DL, GRLenVT));
3389 V1 = DAG.getBitcast(VT, V1);
3390
3391 if (!V2.isUndef()) {
3392 V2 = DAG.getBitcast(MVT::v4i64, V2);
3393 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3394 DAG.getConstant(0b01001110, DL, GRLenVT));
3395 V2 = DAG.getBitcast(VT, V2);
3396 }
3397
3398 for (auto it = Mask.begin(); it < Mask.begin() + HalfSize; it++) {
3399 *it = *it < 0 ? *it : *it - HalfSize;
3400 }
3401 for (auto it = Mask.begin() + HalfSize; it < Mask.end(); it++) {
3402 *it = *it < 0 ? *it : *it + HalfSize;
3403 }
3404 } else if (preMask == LowLaneTy && postMask == LowLaneTy) {
3405 V1 = DAG.getBitcast(MVT::v4i64, V1);
3406 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3407 DAG.getConstant(0b11101110, DL, GRLenVT));
3408 V1 = DAG.getBitcast(VT, V1);
3409
3410 if (!V2.isUndef()) {
3411 V2 = DAG.getBitcast(MVT::v4i64, V2);
3412 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3413 DAG.getConstant(0b11101110, DL, GRLenVT));
3414 V2 = DAG.getBitcast(VT, V2);
3415 }
3416
3417 for (auto it = Mask.begin(); it < Mask.begin() + HalfSize; it++) {
3418 *it = *it < 0 ? *it : *it - HalfSize;
3419 }
3420 } else if (preMask == HighLaneTy && postMask == HighLaneTy) {
3421 V1 = DAG.getBitcast(MVT::v4i64, V1);
3422 V1 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V1,
3423 DAG.getConstant(0b01000100, DL, GRLenVT));
3424 V1 = DAG.getBitcast(VT, V1);
3425
3426 if (!V2.isUndef()) {
3427 V2 = DAG.getBitcast(MVT::v4i64, V2);
3428 V2 = DAG.getNode(LoongArchISD::XVPERMI, DL, MVT::v4i64, V2,
3429 DAG.getConstant(0b01000100, DL, GRLenVT));
3430 V2 = DAG.getBitcast(VT, V2);
3431 }
3432
3433 for (auto it = Mask.begin() + HalfSize; it < Mask.end(); it++) {
3434 *it = *it < 0 ? *it : *it + HalfSize;
3435 }
3436 } else { // cross-lane
3437 return false;
3438 }
3439
3440 return true;
3441}
3442
3443/// Lower VECTOR_SHUFFLE into XVPERMI_Q (if possible).
3444///
3445/// For example:
3446/// %2 = shufflevector <4 x i64> %0, <4 x i64> %1,
3447/// <4 x i32> <i32 2, i32 3, i32 4, i32 5>
3448/// is lowered to:
3449/// (XVPERMI_Q $xr1, $xr0, 33)
3450static SDValue
3452 SDValue V1, SDValue V2, SelectionDAG &DAG,
3454 // Each 128-bit lane of the result must be a whole lane of V1 or V2.
3455 SmallVector<int, 2> LaneMask;
3456 if (!widenShuffleMaskElts(Mask.size() / 2, Mask, LaneMask))
3457 return SDValue();
3458
3459 // Lanes 0-3 are V1.lo, V1.hi, V2.lo and V2.hi, the same as the XVPERMI_Q
3460 // selector with xj = V1 and xd = V2.
3461 int Lo = LaneMask[0] < 0 ? 0 : LaneMask[0];
3462 int Hi = LaneMask[1] < 0 ? 1 : LaneMask[1];
3463 return DAG.getNode(
3464 LoongArchISD::XVPERMIQ, DL, VT, V2, V1,
3465 DAG.getConstant(Lo | (Hi << 4), DL, Subtarget.getGRLenVT()));
3466}
3467
3468/// Lower VECTOR_SHUFFLE as lane permute and then shuffle (if possible).
3469/// Only for 256-bit vector.
3470///
3471/// Each 128-bit lane of the result may use at most two lanes of the inputs.
3472/// These lanes are first moved into place, then shuffled within the lane.
3473///
3474/// For example:
3475/// %2 = shufflevector <4 x i64> %0, <4 x i64> posion,
3476/// <4 x i64> <i32 0, i32 3, i32 2, i32 0>
3477/// is lowerded to:
3478/// (XVPERMI $xr2, $xr0, 78)
3479/// (XVSHUF $xr1, $xr2, $xr0)
3480/// (XVORI $xr0, $xr1, 0)
3481///
3482/// and the splice:
3483/// %2 = shufflevector <8 x i32> %0, <8 x i32> %1,
3484/// <8 x i32> <i32 7, i32 8, i32 9, i32 10,
3485/// i32 11, i32 12, i32 13, i32 14>
3486/// is lowered to:
3487/// (XVBSLL_V $xr2, $xr1, 4)
3488/// (XVPERMI_Q $xr1, $xr0, 33)
3489/// (XVBSRL_V $xr0, $xr1, 12)
3490/// (XVOR_V $xr0, $xr2, $xr0)
3492 ArrayRef<int> Mask,
3493 MVT VT, SDValue V1,
3494 SDValue V2,
3495 SelectionDAG &DAG) {
3496 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
3497 int Size = Mask.size();
3498 int LaneSize = Size / 2;
3499
3500 // For each result lane, the input lanes (0/1: V1, 2/3: V2) used by the two
3501 // operands of the in-lane shuffle.
3502 int LaneSrcs[2][2] = {{-1, -1}, {-1, -1}};
3503 SmallVector<int, 32> InLaneMask(Size, -1);
3504 bool LaneCrossing = false;
3505 for (int i = 0; i < Size; ++i) {
3506 int M = Mask[i];
3507 if (M < 0)
3508 continue;
3509 int Lane = i / LaneSize;
3510 int SrcLane = M / LaneSize;
3511
3512 // Put lanes that stay in place in the first operand and the others in the
3513 // second one, so a single input becomes V1 and V1 with lanes swapped.
3514 int Op = (SrcLane % 2) != Lane;
3515 LaneCrossing |= Op;
3516 if (LaneSrcs[Lane][Op] >= 0 && LaneSrcs[Lane][Op] != SrcLane)
3517 Op ^= 1;
3518 if (LaneSrcs[Lane][Op] >= 0 && LaneSrcs[Lane][Op] != SrcLane)
3519 return SDValue();
3520 LaneSrcs[Lane][Op] = SrcLane;
3521 InLaneMask[i] = Op * Size + Lane * LaneSize + M % LaneSize;
3522 }
3523
3524 if (!LaneCrossing)
3525 return SDValue();
3526
3527 // Swap the operands of the high lane if that makes both lanes use the same
3528 // in-lane mask, which more patterns (e.g. XVPICKEV) can match.
3529 SmallVector<int, 16> RepeatedMask;
3530 if (!isRepeatedShuffleMask(128, VT, InLaneMask, RepeatedMask)) {
3531 SmallVector<int, 32> SwappedMask(InLaneMask);
3532 for (int i = LaneSize; i < Size; ++i)
3533 if (SwappedMask[i] >= 0)
3534 SwappedMask[i] = (SwappedMask[i] + Size) % (2 * Size);
3535 if (isRepeatedShuffleMask(128, VT, SwappedMask, RepeatedMask)) {
3536 std::swap(LaneSrcs[1][0], LaneSrcs[1][1]);
3537 InLaneMask = SwappedMask;
3538 }
3539 }
3540
3541 // Move the input lanes of each operand into place.
3542 SDValue Ops[2];
3543 for (int Op = 0; Op < 2; ++Op) {
3544 SmallVector<int, 32> LaneMask(Size, -1);
3545 for (int Lane = 0; Lane < 2; ++Lane)
3546 if (LaneSrcs[Lane][Op] >= 0)
3547 for (int i = 0; i < LaneSize; ++i)
3548 LaneMask[Lane * LaneSize + i] = LaneSrcs[Lane][Op] * LaneSize + i;
3549 Ops[Op] = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
3550
3551 // Exit if we got back the shuffle we started with, to avoid infinite
3552 // recursion.
3553 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Ops[Op]))
3554 if (SVN->getMask() == Mask)
3555 return SDValue();
3556 }
3557 return DAG.getVectorShuffle(VT, DL, Ops[0], Ops[1], InLaneMask);
3558}
3559
3560/// Dispatching routine to lower various 256-bit LoongArch vector shuffles.
3561///
3562/// This routine breaks down the specific type of 256-bit shuffle and
3563/// dispatches to the lowering routines accordingly.
3565 SDValue V1, SDValue V2, SelectionDAG &DAG,
3567 assert((VT.SimpleTy == MVT::v32i8 || VT.SimpleTy == MVT::v16i16 ||
3568 VT.SimpleTy == MVT::v8i32 || VT.SimpleTy == MVT::v4i64 ||
3569 VT.SimpleTy == MVT::v8f32 || VT.SimpleTy == MVT::v4f64) &&
3570 "Vector type is unsupported for lasx!");
3571 assert(V1.getSimpleValueType() == V2.getSimpleValueType() &&
3572 "Two operands have different types!");
3573 assert(VT.getVectorNumElements() == Mask.size() &&
3574 "Unexpected mask size for shuffle!");
3575 assert(Mask.size() % 2 == 0 && "Expected even mask size.");
3576 assert(Mask.size() >= 4 && "Mask size is less than 4.");
3577
3578 APInt KnownUndef, KnownZero;
3579 computeZeroableShuffleElements(Mask, V1, V2, KnownUndef, KnownZero);
3580 APInt Zeroable = KnownUndef | KnownZero;
3581
3582 SDValue Result;
3583 // TODO: Add more comparison patterns.
3584 if (V2.isUndef()) {
3585 if ((Result =
3586 lowerVECTOR_SHUFFLE_XVREPLVEI(DL, Mask, VT, V1, DAG, Subtarget)))
3587 return Result;
3588 if ((Result = lowerVECTOR_SHUFFLE_XVSHUF4I(DL, Mask, VT, V1, V2, DAG,
3589 Subtarget)))
3590 return Result;
3591 if ((Result = lowerVECTOR_SHUFFLE_XVREPLVE0(DL, Mask, VT, V1, DAG)))
3592 return Result;
3593 // Try to widen vectors to gain more optimization opportunities.
3594 if (SDValue NewShuffle = widenShuffleMask(DL, Mask, VT, V1, V2, DAG))
3595 return NewShuffle;
3596 if ((Result =
3597 lowerVECTOR_SHUFFLE_XVPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3598 return Result;
3599 if ((Result = lowerVECTOR_SHUFFLE_XVPERM(DL, Mask, VT, V1, DAG, Subtarget)))
3600 return Result;
3601 if ((Result =
3602 lowerVECTOR_SHUFFLE_IsReverse(DL, Mask, VT, V1, DAG, Subtarget)))
3603 return Result;
3604
3605 // TODO: This comment may be enabled in the future to better match the
3606 // pattern for instruction selection.
3607 /* V2 = V1; */
3608 }
3609
3610 // It is recommended not to change the pattern comparison order for better
3611 // performance.
3612 if ((Result = lowerVECTOR_SHUFFLE_XVPACKEV(DL, Mask, VT, V1, V2, DAG)))
3613 return Result;
3614 if ((Result = lowerVECTOR_SHUFFLE_XVPACKOD(DL, Mask, VT, V1, V2, DAG)))
3615 return Result;
3616 if ((Result = lowerVECTOR_SHUFFLE_XVILVH(DL, Mask, VT, V1, V2, DAG)))
3617 return Result;
3618 if ((Result = lowerVECTOR_SHUFFLE_XVILVL(DL, Mask, VT, V1, V2, DAG)))
3619 return Result;
3620 if ((Result = lowerVECTOR_SHUFFLE_XVPICKEV(DL, Mask, VT, V1, V2, DAG)))
3621 return Result;
3622 if ((Result = lowerVECTOR_SHUFFLE_XVPICKOD(DL, Mask, VT, V1, V2, DAG)))
3623 return Result;
3624 if ((VT.SimpleTy == MVT::v4i64 || VT.SimpleTy == MVT::v4f64) &&
3625 (Result =
3626 lowerVECTOR_SHUFFLE_XVSHUF4I(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3627 return Result;
3628 if ((Result =
3629 lowerVECTOR_SHUFFLE_XVEXTRINS(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3630 return Result;
3631 if ((Result = lowerVECTOR_SHUFFLEAsShift(DL, Mask, VT, V1, V2, DAG, Subtarget,
3632 Zeroable)))
3633 return Result;
3634 if ((Result =
3635 lowerVECTOR_SHUFFLE_XVPERMI(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3636 return Result;
3637 if ((Result =
3638 lowerVECTOR_SHUFFLE_XVINSVE0(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3639 return Result;
3640 if ((Result = lowerVECTOR_SHUFFLEAsByteRotate(DL, Mask, VT, V1, V2, DAG,
3641 Subtarget)))
3642 return Result;
3643
3644 if ((Result =
3645 lowerVECTOR_SHUFFLE_XVPERMIQ(DL, Mask, VT, V1, V2, DAG, Subtarget)))
3646 return Result;
3647
3648 // canonicalize non cross-lane shuffle vector
3649 SmallVector<int> NewMask(Mask);
3650 if (canonicalizeShuffleVectorByLane(DL, NewMask, VT, V1, V2, DAG, Subtarget))
3651 return lower256BitShuffle(DL, NewMask, VT, V1, V2, DAG, Subtarget);
3652
3653 // FIXME: Handling the remaining cases earlier can degrade performance
3654 // in some situations. Further analysis is required to enable more
3655 // effective optimizations.
3656 if ((Result = lowerVECTOR_SHUFFLEAsLanePermuteAndShuffle(DL, NewMask, VT, V1,
3657 V2, DAG)))
3658 return Result;
3659
3660 if (SDValue NewShuffle = widenShuffleMask(DL, NewMask, VT, V1, V2, DAG))
3661 return NewShuffle;
3662 if ((Result = lowerVECTOR_SHUFFLE_XVSHUF(DL, NewMask, VT, V1, V2, DAG)))
3663 return Result;
3664
3665 return SDValue();
3666}
3667
3668/// Lower \p Elts to [X]VREPLVE Src, Idx if each 128-bit lane L is a splat of
3669/// (extract_vector_elt Src, Idx + L * N), where N is the number of elements
3670/// per lane. For 256-bit vectors, Idx must be known to be less than N.
3671static SDValue
3673 SelectionDAG &DAG,
3675 unsigned NumElts = Elts.size();
3676 unsigned NumLanes = VT.getSizeInBits() / 128;
3677 unsigned NumLaneElts = NumElts / NumLanes;
3678 SDValue Src, Idx;
3679
3680 for (unsigned L = 0; L < NumLanes; ++L) {
3681 SDValue LaneElt;
3682 for (SDValue Elt : Elts.slice(L * NumLaneElts, NumLaneElts)) {
3683 if (!Elt || Elt.isUndef())
3684 continue;
3685 if (!LaneElt)
3686 LaneElt = Elt;
3687 else if (LaneElt != Elt)
3688 return SDValue();
3689 }
3690
3691 if (!LaneElt || LaneElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
3692 return SDValue();
3693 SDValue Vec = LaneElt.getOperand(0);
3694 SDValue EltIdx = LaneElt.getOperand(1);
3695 if (isa<ConstantSDNode>(EltIdx))
3696 return SDValue();
3697
3698 if (L == 0) {
3699 EVT SrcVT = Vec.getValueType();
3700 if (SrcVT.getSizeInBits() != VT.getSizeInBits() ||
3701 SrcVT.getVectorNumElements() != NumElts)
3702 return SDValue();
3703 Src = Vec;
3704 Idx = EltIdx;
3705 continue;
3706 }
3707
3708 // Must select the same position within the lane.
3709 if (Vec != Src || !DAG.isADDLike(EltIdx) || EltIdx.getOperand(0) != Idx)
3710 return SDValue();
3711 auto *Offset = dyn_cast<ConstantSDNode>(EltIdx.getOperand(1));
3712 if (!Offset || Offset->getZExtValue() != L * NumLaneElts)
3713 return SDValue();
3714 }
3715
3716 if (NumLanes > 1 && DAG.computeKnownBits(Idx).getMaxValue().uge(NumLaneElts))
3717 return SDValue();
3718
3720 Idx = DAG.getZExtOrTrunc(Idx, DL, Subtarget.getGRLenVT());
3721 SDValue Res = DAG.getNode(LoongArchISD::VREPLVE, DL, IntVT,
3722 DAG.getBitcast(IntVT, Src), Idx);
3723 return DAG.getBitcast(VT, Res);
3724}
3725
3726/// Lower a VECTOR_SHUFFLE of BUILD_VECTORs to [X]VREPLVE.
3727static SDValue
3729 SDValue V1, SDValue V2, SelectionDAG &DAG,
3731 int NumElts = Mask.size();
3733 for (int M : Mask) {
3734 if (M < 0) {
3735 Elts.push_back(SDValue());
3736 continue;
3737 }
3738 SDValue V = M < NumElts ? V1 : V2;
3739 if (V.isUndef()) {
3740 Elts.push_back(SDValue());
3741 continue;
3742 }
3743 if (V.getOpcode() != ISD::BUILD_VECTOR)
3744 return SDValue();
3745 Elts.push_back(V.getOperand(M % NumElts));
3746 }
3747
3748 return lowerSplatOfExtractAsVREPLVE(DL, VT, Elts, DAG, Subtarget);
3749}
3750
3751SDValue LoongArchTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
3752 SelectionDAG &DAG) const {
3753 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3754 ArrayRef<int> OrigMask = SVOp->getMask();
3755 SDValue V1 = Op.getOperand(0);
3756 SDValue V2 = Op.getOperand(1);
3757 MVT VT = Op.getSimpleValueType();
3758 int NumElements = VT.getVectorNumElements();
3759 SDLoc DL(Op);
3760
3761 bool V1IsUndef = V1.isUndef();
3762 bool V2IsUndef = V2.isUndef();
3763 if (V1IsUndef && V2IsUndef)
3764 return DAG.getUNDEF(VT);
3765
3766 // When we create a shuffle node we put the UNDEF node to second operand,
3767 // but in some cases the first operand may be transformed to UNDEF.
3768 // In this case we should just commute the node.
3769 if (V1IsUndef)
3770 return DAG.getCommutedVectorShuffle(*SVOp);
3771
3772 // Check for non-undef masks pointing at an undef vector and make the masks
3773 // undef as well. This makes it easier to match the shuffle based solely on
3774 // the mask.
3775 if (V2IsUndef &&
3776 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
3777 SmallVector<int, 8> NewMask(OrigMask);
3778 for (int &M : NewMask)
3779 if (M >= NumElements)
3780 M = -1;
3781 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
3782 }
3783
3784 // Check for illegal shuffle mask element index values.
3785 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
3786 (void)MaskUpperLimit;
3787 assert(llvm::all_of(OrigMask,
3788 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
3789 "Out of bounds shuffle index");
3790
3791 if (SDValue Result =
3792 lowerVECTOR_SHUFFLE_VREPLVE(DL, OrigMask, VT, V1, V2, DAG, Subtarget))
3793 return Result;
3794
3795 // For each vector width, delegate to a specialized lowering routine.
3796 if (VT.is128BitVector())
3797 return lower128BitShuffle(DL, OrigMask, VT, V1, V2, DAG, Subtarget);
3798
3799 if (VT.is256BitVector())
3800 return lower256BitShuffle(DL, OrigMask, VT, V1, V2, DAG, Subtarget);
3801
3802 return SDValue();
3803}
3804
3805SDValue LoongArchTargetLowering::lowerFP_TO_FP16(SDValue Op,
3806 SelectionDAG &DAG) const {
3807 // Custom lower to ensure the libcall return is passed in an FPR on hard
3808 // float ABIs.
3809 SDLoc DL(Op);
3810 MakeLibCallOptions CallOptions;
3811 SDValue Op0 = Op.getOperand(0);
3812 SDValue Chain = SDValue();
3813 RTLIB::Libcall LC = RTLIB::getFPROUND(Op0.getValueType(), MVT::f16);
3814 SDValue Res;
3815 std::tie(Res, Chain) =
3816 makeLibCall(DAG, LC, MVT::f32, Op0, CallOptions, DL, Chain);
3817 if (Subtarget.is64Bit())
3818 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Res);
3819 return DAG.getBitcast(MVT::i32, Res);
3820}
3821
3822SDValue LoongArchTargetLowering::lowerFP16_TO_FP(SDValue Op,
3823 SelectionDAG &DAG) const {
3824 // Custom lower to ensure the libcall argument is passed in an FPR on hard
3825 // float ABIs.
3826 SDLoc DL(Op);
3827 MakeLibCallOptions CallOptions;
3828 SDValue Op0 = Op.getOperand(0);
3829 SDValue Chain = SDValue();
3830 SDValue Arg = Subtarget.is64Bit() ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64,
3831 DL, MVT::f32, Op0)
3832 : DAG.getBitcast(MVT::f32, Op0);
3833 SDValue Res;
3834 std::tie(Res, Chain) = makeLibCall(DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Arg,
3835 CallOptions, DL, Chain);
3836 return Res;
3837}
3838
3839SDValue LoongArchTargetLowering::lowerFP_TO_BF16(SDValue Op,
3840 SelectionDAG &DAG) const {
3841 assert(Subtarget.hasBasicF() && "Unexpected custom legalization");
3842 SDLoc DL(Op);
3843 MakeLibCallOptions CallOptions;
3844 RTLIB::Libcall LC =
3845 RTLIB::getFPROUND(Op.getOperand(0).getValueType(), MVT::bf16);
3846 SDValue Res =
3847 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
3848 if (Subtarget.is64Bit())
3849 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Res);
3850 return DAG.getBitcast(MVT::i32, Res);
3851}
3852
3853SDValue LoongArchTargetLowering::lowerBF16_TO_FP(SDValue Op,
3854 SelectionDAG &DAG) const {
3855 assert(Subtarget.hasBasicF() && "Unexpected custom legalization");
3856 MVT VT = Op.getSimpleValueType();
3857 SDLoc DL(Op);
3858 Op = DAG.getNode(
3859 ISD::SHL, DL, Op.getOperand(0).getValueType(), Op.getOperand(0),
3860 DAG.getShiftAmountConstant(16, Op.getOperand(0).getValueType(), DL));
3861 SDValue Res = Subtarget.is64Bit() ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64,
3862 DL, MVT::f32, Op)
3863 : DAG.getBitcast(MVT::f32, Op);
3864 if (VT != MVT::f32)
3865 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Res);
3866 return Res;
3867}
3868
3869// Lower BUILD_VECTOR as broadcast load (if possible).
3870// For example:
3871// %a = load i8, ptr %ptr
3872// %b = build_vector %a, %a, %a, %a
3873// is lowered to :
3874// (VLDREPL_B $a0, 0)
3876 const SDLoc &DL,
3877 SelectionDAG &DAG) {
3878 MVT VT = BVOp->getSimpleValueType(0);
3879 int NumOps = BVOp->getNumOperands();
3880
3881 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3882 "Unsupported vector type for broadcast.");
3883
3884 SDValue IdentitySrc;
3885 bool IsIdeneity = true;
3886
3887 for (int i = 0; i != NumOps; i++) {
3888 SDValue Op = BVOp->getOperand(i);
3889 if (Op.getOpcode() != ISD::LOAD || (IdentitySrc && Op != IdentitySrc)) {
3890 IsIdeneity = false;
3891 break;
3892 }
3893 IdentitySrc = BVOp->getOperand(0);
3894 }
3895
3896 // make sure that this load is valid and only has one user.
3897 if (!IsIdeneity || !IdentitySrc || !BVOp->isOnlyUserOf(IdentitySrc.getNode()))
3898 return SDValue();
3899
3900 auto *LN = cast<LoadSDNode>(IdentitySrc);
3901 auto ExtType = LN->getExtensionType();
3902
3903 if ((ExtType == ISD::EXTLOAD || ExtType == ISD::NON_EXTLOAD) &&
3904 VT.getScalarSizeInBits() == LN->getMemoryVT().getScalarSizeInBits()) {
3905 // Indexed loads and stores are not supported on LoongArch.
3906 assert(LN->isUnindexed() && "Unexpected indexed load.");
3907
3908 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3909 // The offset operand of unindexed load is always undefined, so there is
3910 // no need to pass it to VLDREPL.
3911 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
3912 SDValue BCast = DAG.getNode(LoongArchISD::VLDREPL, DL, Tys, Ops);
3913 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
3914 return BCast;
3915 }
3916 return SDValue();
3917}
3918
3919// Sequentially insert elements from Ops into Vector, from low to high indices.
3920// Note: Ops can have fewer elements than Vector.
3923 EVT ResTy) {
3924 assert(Ops.size() <= ResTy.getVectorNumElements());
3925
3926 SDValue Op0 = Ops[0];
3927 if (!Op0.isUndef())
3928 Vector = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ResTy, Op0);
3929 for (unsigned i = 1; i < Ops.size(); ++i) {
3930 SDValue Opi = Ops[i];
3931 if (Opi.isUndef())
3932 continue;
3933 Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Vector, Opi,
3934 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
3935 }
3936}
3937
3938// Build a ResTy subvector from Node, taking NumElts elements starting at index
3939// 'first'.
3941 SelectionDAG &DAG, SDLoc DL,
3943 EVT ResTy, unsigned first) {
3944 unsigned NumElts = ResTy.getVectorNumElements();
3945
3946 assert(first + NumElts <= Node->getSimpleValueType(0).getVectorNumElements());
3947
3948 SmallVector<SDValue, 16> Ops(Node->op_begin() + first,
3949 Node->op_begin() + first + NumElts);
3950 SDValue Vector = DAG.getUNDEF(ResTy);
3951 fillVector(Ops, DAG, DL, Subtarget, Vector, ResTy);
3952 return Vector;
3953}
3954
3955SDValue LoongArchTargetLowering::lowerBUILD_VECTOR(SDValue Op,
3956 SelectionDAG &DAG) const {
3957 BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);
3958 MVT VT = Node->getSimpleValueType(0);
3959 EVT ResTy = Op->getValueType(0);
3960 unsigned NumElts = ResTy.getVectorNumElements();
3961 SDLoc DL(Op);
3962 APInt SplatValue, SplatUndef;
3963 unsigned SplatBitSize;
3964 bool HasAnyUndefs;
3965 bool IsConstant = false;
3966 bool UseSameConstant = true;
3967 SDValue ConstantValue;
3968 bool Is128Vec = ResTy.is128BitVector();
3969 bool Is256Vec = ResTy.is256BitVector();
3970
3971 if ((!Subtarget.hasExtLSX() || !Is128Vec) &&
3972 (!Subtarget.hasExtLASX() || !Is256Vec))
3973 return SDValue();
3974
3975 if (SDValue Result = lowerBUILD_VECTORAsBroadCastLoad(Node, DL, DAG))
3976 return Result;
3977
3978 if (Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
3979 /*MinSplatBits=*/8) &&
3980 SplatBitSize <= 64) {
3981 // We can only cope with 8, 16, 32, or 64-bit elements.
3982 if (SplatBitSize != 8 && SplatBitSize != 16 && SplatBitSize != 32 &&
3983 SplatBitSize != 64)
3984 return SDValue();
3985
3986 if (SplatBitSize == 64 && !Subtarget.is64Bit()) {
3987 // We can only handle 64-bit elements that are within
3988 // the signed 10-bit range or match vldi patterns on 32-bit targets.
3989 // See the BUILD_VECTOR case in LoongArchDAGToDAGISel::Select().
3990 if (!SplatValue.isSignedIntN(10) &&
3991 !isImmVLDILegalForMode1(SplatValue, SplatBitSize).first)
3992 return SDValue();
3993 if ((Is128Vec && ResTy == MVT::v4i32) ||
3994 (Is256Vec && ResTy == MVT::v8i32))
3995 return Op;
3996 }
3997
3998 EVT ViaVecTy;
3999
4000 switch (SplatBitSize) {
4001 default:
4002 return SDValue();
4003 case 8:
4004 ViaVecTy = Is128Vec ? MVT::v16i8 : MVT::v32i8;
4005 break;
4006 case 16:
4007 ViaVecTy = Is128Vec ? MVT::v8i16 : MVT::v16i16;
4008 break;
4009 case 32:
4010 ViaVecTy = Is128Vec ? MVT::v4i32 : MVT::v8i32;
4011 break;
4012 case 64:
4013 ViaVecTy = Is128Vec ? MVT::v2i64 : MVT::v4i64;
4014 break;
4015 }
4016
4017 // SelectionDAG::getConstant will promote SplatValue appropriately.
4018 SDValue Result = DAG.getConstant(SplatValue, DL, ViaVecTy);
4019
4020 // Bitcast to the type we originally wanted.
4021 if (ViaVecTy != ResTy)
4022 Result = DAG.getNode(ISD::BITCAST, SDLoc(Node), ResTy, Result);
4023
4024 return Result;
4025 }
4026
4027 // Lower per-lane splat of a variable-index extract to [X]VREPLVE.
4029 DL, VT, SmallVector<SDValue>(Node->op_values()), DAG, Subtarget))
4030 return Result;
4031
4032 if (DAG.isSplatValue(Op, /*AllowUndefs=*/false))
4033 return Op;
4034
4035 for (unsigned i = 0; i < NumElts; ++i) {
4036 SDValue Opi = Node->getOperand(i);
4037 if (isIntOrFPConstant(Opi)) {
4038 IsConstant = true;
4039 if (!ConstantValue.getNode())
4040 ConstantValue = Opi;
4041 else if (ConstantValue != Opi)
4042 UseSameConstant = false;
4043 }
4044 }
4045
4046 // If the type of BUILD_VECTOR is v2f64, custom legalizing it has no benefits.
4047 if (IsConstant && UseSameConstant && ResTy != MVT::v2f64) {
4048 SDValue Result = DAG.getSplatBuildVector(ResTy, DL, ConstantValue);
4049 for (unsigned i = 0; i < NumElts; ++i) {
4050 SDValue Opi = Node->getOperand(i);
4051 if (!isIntOrFPConstant(Opi))
4052 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Result, Opi,
4053 DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
4054 }
4055 return Result;
4056 }
4057
4058 if (!IsConstant) {
4060 BitVector UndefElements;
4061 bool IsRepeated = Node->getRepeatedSequence(Sequence, &UndefElements);
4062 unsigned SeqLen = Sequence.size();
4063 unsigned NumUndefElts = UndefElements.count();
4064
4065 // When a BUILD_VECTOR consists of the same element (ignoring undefs),
4066 // prefer emitting a broadcast instead of multiple insertions.
4067 if (IsRepeated && SeqLen == 1) {
4068 bool IsSplatBetter = true;
4069
4070 // Integer vectors benefit from splat except in the case where the only
4071 // non-undef element is at index 0 and is a load with a base+offset addr.
4072 if (ResTy.isInteger()) {
4073 SDValue Op0 = Node->getOperand(0);
4074 if (NumUndefElts == NumElts - 1 && Op0.getOpcode() == ISD::LOAD &&
4076 IsSplatBetter = false;
4077 }
4078
4079 // Several floating-point cases suffer performance regressions or have
4080 // no improvement when
4081 // only one element is non-undef,
4082 // one of the only two non-undefs at index 0,
4083 // the two non-undefs of v8f32 buildvector at index (1,2)/(1,3)/(2,3).
4084 if (ResTy.isFloatingPoint()) {
4085 if (NumUndefElts == NumElts - 1)
4086 IsSplatBetter = false;
4087 if (NumUndefElts == NumElts - 2 && !UndefElements[0])
4088 IsSplatBetter = false;
4089 if (ResTy == MVT::v8f32 && NumUndefElts == NumElts - 2 &&
4090 ((!UndefElements[1] && !UndefElements[2]) ||
4091 (!UndefElements[1] && !UndefElements[3]) ||
4092 (!UndefElements[2] && !UndefElements[3])))
4093 IsSplatBetter = false;
4094 }
4095
4096 if (IsSplatBetter)
4097 return DAG.getSplatBuildVector(ResTy, DL, Sequence[0]);
4098 }
4099
4100 // If the BUILD_VECTOR has a repeated pattern, use INSERT_VECTOR_ELT to fill
4101 // the sub-sequence of the vector and then broadcast the sub-sequence.
4102 //
4103 // TODO: If the BUILD_VECTOR contains undef elements, consider falling
4104 // back to use INSERT_VECTOR_ELT to materialize the vector, because it
4105 // generates worse code in some cases. This could be further optimized
4106 // with more consideration.
4107 if (IsRepeated && NumUndefElts == 0) {
4108 // Using LSX instructions to fill the sub-sequence of 256-bits vector,
4109 // because the high part can be simply treated as undef.
4110 SDValue Vector = DAG.getUNDEF(ResTy);
4111 EVT FillTy = Is256Vec
4113 : ResTy;
4114 SDValue FillVec =
4115 Is256Vec ? DAG.getExtractSubvector(DL, FillTy, Vector, 0) : Vector;
4116
4117 fillVector(Sequence, DAG, DL, Subtarget, FillVec, FillTy);
4118
4119 unsigned SplatLen = NumElts / SeqLen;
4120 MVT SplatEltTy = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
4121 MVT SplatTy = MVT::getVectorVT(SplatEltTy, SplatLen);
4122
4123 // If size of the sub-sequence is half of a 256-bits vector, bitcast the
4124 // vector to v4i64 type in order to match the pattern of XVREPLVE0Q.
4125 if (SplatEltTy == MVT::i128)
4126 SplatTy = MVT::v4i64;
4127
4128 SDValue SplatVec;
4129 SDValue SrcVec = DAG.getBitcast(
4130 SplatTy,
4131 Is256Vec ? DAG.getInsertSubvector(DL, Vector, FillVec, 0) : FillVec);
4132 if (Is256Vec) {
4133 SplatVec =
4134 DAG.getNode((SplatEltTy == MVT::i128) ? LoongArchISD::XVREPLVE0Q
4135 : LoongArchISD::XVREPLVE0,
4136 DL, SplatTy, SrcVec);
4137 } else {
4138 SplatVec = DAG.getNode(LoongArchISD::VREPLVEI, DL, SplatTy, SrcVec,
4139 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
4140 }
4141
4142 return DAG.getBitcast(ResTy, SplatVec);
4143 }
4144
4145 // Use INSERT_VECTOR_ELT operations rather than expand to stores, because
4146 // using memory operations is much lower.
4147 //
4148 // For 256-bit vectors, normally split into two halves and concatenate.
4149 // Special case: for v8i32/v8f32/v4i64/v4f64, if the upper half has only
4150 // one non-undef element, skip spliting to avoid a worse result.
4151 if (ResTy == MVT::v8i32 || ResTy == MVT::v8f32 || ResTy == MVT::v4i64 ||
4152 ResTy == MVT::v4f64) {
4153 unsigned NonUndefCount = 0;
4154 for (unsigned i = NumElts / 2; i < NumElts; ++i) {
4155 if (!Node->getOperand(i).isUndef()) {
4156 ++NonUndefCount;
4157 if (NonUndefCount > 1)
4158 break;
4159 }
4160 }
4161 if (NonUndefCount == 1)
4162 return fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget, ResTy, 0);
4163 }
4164
4165 EVT VecTy =
4166 Is256Vec ? ResTy.getHalfNumVectorElementsVT(*DAG.getContext()) : ResTy;
4167 SDValue Vector =
4168 fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget, VecTy, 0);
4169
4170 if (Is128Vec)
4171 return Vector;
4172
4173 SDValue VectorHi = fillSubVectorFromBuildVector(Node, DAG, DL, Subtarget,
4174 VecTy, NumElts / 2);
4175
4176 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResTy, Vector, VectorHi);
4177 }
4178
4179 return SDValue();
4180}
4181
4182SDValue LoongArchTargetLowering::lowerCONCAT_VECTORS(SDValue Op,
4183 SelectionDAG &DAG) const {
4184 SDLoc DL(Op);
4185 MVT ResVT = Op.getSimpleValueType();
4186 assert(ResVT.is256BitVector() && Op.getNumOperands() == 2);
4187
4188 if (Op.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4189 Op.getOperand(1).getOpcode() == ISD::TRUNCATE)
4190 return Op;
4191
4192 unsigned NumOperands = Op.getNumOperands();
4193 unsigned NumFreezeUndef = 0;
4194 unsigned NumZero = 0;
4195 unsigned NumNonZero = 0;
4196 unsigned NonZeros = 0;
4197 SmallSet<SDValue, 4> Undefs;
4198 for (unsigned i = 0; i != NumOperands; ++i) {
4199 SDValue SubVec = Op.getOperand(i);
4200 if (SubVec.isUndef())
4201 continue;
4202 if (ISD::isFreezeUndef(SubVec)) {
4203 // If the freeze(undef) has multiple uses then we must fold to zero.
4204 if (SubVec.hasOneUse()) {
4205 ++NumFreezeUndef;
4206 } else {
4207 ++NumZero;
4208 Undefs.insert(SubVec);
4209 }
4210 } else if (ISD::isBuildVectorAllZeros(SubVec))
4211 ++NumZero;
4212 else {
4213 assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
4214 NonZeros |= 1 << i;
4215 ++NumNonZero;
4216 }
4217 }
4218
4219 // If we have more than 2 non-zeros, build each half separately.
4220 if (NumNonZero > 2) {
4221 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
4222 ArrayRef<SDUse> Ops = Op->ops();
4223 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
4224 Ops.slice(0, NumOperands / 2));
4225 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT,
4226 Ops.slice(NumOperands / 2));
4227 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
4228 }
4229
4230 // Otherwise, build it up through insert_subvectors.
4231 SDValue Vec = NumZero ? DAG.getConstant(0, DL, ResVT)
4232 : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
4233 : DAG.getUNDEF(ResVT));
4234
4235 // Replace Undef operands with ZeroVector.
4236 for (SDValue U : Undefs)
4237 DAG.ReplaceAllUsesWith(U, DAG.getConstant(0, DL, U.getSimpleValueType()));
4238
4239 MVT SubVT = Op.getOperand(0).getSimpleValueType();
4240 unsigned NumSubElems = SubVT.getVectorNumElements();
4241 for (unsigned i = 0; i != NumOperands; ++i) {
4242 if ((NonZeros & (1 << i)) == 0)
4243 continue;
4244
4245 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResVT, Vec, Op.getOperand(i),
4246 DAG.getVectorIdxConstant(i * NumSubElems, DL));
4247 }
4248
4249 return Vec;
4250}
4251
4252SDValue
4253LoongArchTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4254 SelectionDAG &DAG) const {
4255 MVT EltVT = Op.getSimpleValueType();
4256 SDValue Vec = Op->getOperand(0);
4257 EVT VecTy = Vec->getValueType(0);
4258 SDValue Idx = Op->getOperand(1);
4259 SDLoc DL(Op);
4260 MVT GRLenVT = Subtarget.getGRLenVT();
4261
4262 assert(VecTy.is256BitVector() && "Unexpected EXTRACT_VECTOR_ELT vector type");
4263
4264 if (isa<ConstantSDNode>(Idx))
4265 return Op;
4266
4267 switch (VecTy.getSimpleVT().SimpleTy) {
4268 default:
4269 llvm_unreachable("Unexpected type");
4270 case MVT::v32i8:
4271 case MVT::v16i16:
4272 case MVT::v4i64:
4273 case MVT::v4f64: {
4274 // Extract the high half subvector and place it to the low half of a new
4275 // vector. It doesn't matter what the high half of the new vector is.
4276 EVT HalfTy = VecTy.getHalfNumVectorElementsVT(*DAG.getContext());
4277 SDValue VecHi =
4278 DAG.getExtractSubvector(DL, HalfTy, Vec, HalfTy.getVectorNumElements());
4279 SDValue TmpVec =
4280 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecTy, DAG.getUNDEF(VecTy),
4281 VecHi, DAG.getConstant(0, DL, GRLenVT));
4282
4283 // Shuffle the origin Vec and the TmpVec using MaskVec, the lowest element
4284 // of MaskVec is Idx, the rest do not matter. ResVec[0] will hold the
4285 // desired element.
4286 SDValue IdxCp =
4287 Subtarget.is64Bit()
4288 ? DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, Idx)
4289 : DAG.getBitcast(MVT::f32, Idx);
4290 SDValue IdxVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f32, IdxCp);
4291 SDValue MaskVec =
4292 DAG.getBitcast((VecTy == MVT::v4f64) ? MVT::v4i64 : VecTy, IdxVec);
4293 SDValue ResVec =
4294 DAG.getNode(LoongArchISD::VSHUF, DL, VecTy, MaskVec, TmpVec, Vec);
4295
4296 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ResVec,
4297 DAG.getConstant(0, DL, GRLenVT));
4298 }
4299 case MVT::v8i32:
4300 case MVT::v8f32: {
4301 SDValue SplatIdx = DAG.getSplatBuildVector(MVT::v8i32, DL, Idx);
4302 SDValue SplatValue =
4303 DAG.getNode(LoongArchISD::XVPERM, DL, VecTy, Vec, SplatIdx);
4304
4305 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, SplatValue,
4306 DAG.getConstant(0, DL, GRLenVT));
4307 }
4308 }
4309}
4310
4311SDValue
4312LoongArchTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4313 SelectionDAG &DAG) const {
4314 MVT VT = Op.getSimpleValueType();
4315 MVT EltVT = VT.getVectorElementType();
4316 unsigned NumElts = VT.getVectorNumElements();
4317 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
4318 SDLoc DL(Op);
4319 SDValue Op0 = Op.getOperand(0);
4320 SDValue Op1 = Op.getOperand(1);
4321 SDValue Op2 = Op.getOperand(2);
4322
4323 // Lower inserting a loaded integer into lane 0 of an undefined vector as a
4324 // vector load that writes the whole register: FLD.{S/D} for 32/64-bit
4325 // elements and [X]VLDREPL.{B/H} for 8/16-bit ones. Unlike a scalar load +
4326 // [X]VINSGR2VR, it has no false dependency on the previous value of the
4327 // destination and doesn't need to move the value from a GPR.
4328 // For example:
4329 // %a = load i64, ptr %ptr
4330 // %b = insert_vector_elt undef, %a, 0
4331 // is lowered to:
4332 // (FLD_D $a0, 0)
4333 if (Op0.isUndef() && isNullConstant(Op2) && EltVT.isInteger() &&
4334 Op1.getOpcode() == ISD::LOAD && Op1.hasOneUse()) {
4335 auto *LN = cast<LoadSDNode>(Op1);
4336 auto ExtType = LN->getExtensionType();
4337 if (LN->isSimple() &&
4338 (ExtType == ISD::EXTLOAD || ExtType == ISD::NON_EXTLOAD) &&
4339 LN->getMemoryVT().getSizeInBits() == EltSizeInBits) {
4340 // Indexed loads and stores are not supported on LoongArch.
4341 assert(LN->isUnindexed() && "Unexpected indexed load.");
4342 SDValue Res;
4343 if (EltSizeInBits >= 32) {
4344 MVT FltVT = MVT::getFloatingPointVT(EltSizeInBits);
4345 // Don't reuse the memory operand, its range metadata (if any) only
4346 // applies to integer loads.
4347 SDValue Ld = DAG.getLoad(
4348 FltVT, DL, LN->getChain(), LN->getBasePtr(), LN->getPointerInfo(),
4349 LN->getAlign(), LN->getMemOperand()->getFlags(), LN->getAAInfo());
4350 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL,
4351 MVT::getVectorVT(FltVT, NumElts), Ld);
4352 Res = DAG.getBitcast(VT, Res);
4353 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), Ld.getValue(1));
4354 } else {
4355 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
4356 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
4357 Res = DAG.getMemIntrinsicNode(LoongArchISD::VLDREPL, DL, Tys, Ops,
4358 LN->getMemoryVT(), LN->getMemOperand());
4359 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), Res.getValue(1));
4360 }
4361 return Res;
4362 }
4363 }
4364
4365 if (isa<ConstantSDNode>(Op2))
4366 return Op;
4367
4368 MVT IdxTy = MVT::getIntegerVT(EltSizeInBits);
4369 MVT IdxVTy = MVT::getVectorVT(IdxTy, NumElts);
4370
4371 if (!isTypeLegal(VT) || !isTypeLegal(IdxVTy))
4372 return SDValue();
4373
4374 SDValue SplatElt = DAG.getSplatBuildVector(VT, DL, Op1);
4375 SmallVector<SDValue, 32> RawIndices;
4376 SDValue SplatIdx;
4377 SDValue Indices;
4378
4379 if (!Subtarget.is64Bit() && IdxTy == MVT::i64) {
4380 MVT PairVTy = MVT::getVectorVT(MVT::i32, NumElts * 2);
4381 for (unsigned i = 0; i < NumElts; ++i) {
4382 RawIndices.push_back(Op2);
4383 RawIndices.push_back(DAG.getConstant(0, DL, MVT::i32));
4384 }
4385 SplatIdx = DAG.getBuildVector(PairVTy, DL, RawIndices);
4386 SplatIdx = DAG.getBitcast(IdxVTy, SplatIdx);
4387
4388 RawIndices.clear();
4389 for (unsigned i = 0; i < NumElts; ++i) {
4390 RawIndices.push_back(DAG.getConstant(i, DL, MVT::i32));
4391 RawIndices.push_back(DAG.getConstant(0, DL, MVT::i32));
4392 }
4393 Indices = DAG.getBuildVector(PairVTy, DL, RawIndices);
4394 Indices = DAG.getBitcast(IdxVTy, Indices);
4395 } else {
4396 SplatIdx = DAG.getSplatBuildVector(IdxVTy, DL, Op2);
4397
4398 for (unsigned i = 0; i < NumElts; ++i)
4399 RawIndices.push_back(DAG.getConstant(i, DL, Subtarget.getGRLenVT()));
4400 Indices = DAG.getBuildVector(IdxVTy, DL, RawIndices);
4401 }
4402
4403 // insert vec, elt, idx
4404 // =>
4405 // select (splatidx == {0,1,2...}) ? splatelt : vec
4406 SDValue SelectCC =
4407 DAG.getSetCC(DL, IdxVTy, SplatIdx, Indices, ISD::CondCode::SETEQ);
4408 return DAG.getNode(ISD::VSELECT, DL, VT, SelectCC, SplatElt, Op0);
4409}
4410
4411SDValue LoongArchTargetLowering::lowerATOMIC_FENCE(SDValue Op,
4412 SelectionDAG &DAG) const {
4413 SDLoc DL(Op);
4414 SyncScope::ID FenceSSID =
4415 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4416
4417 // singlethread fences only synchronize with signal handlers on the same
4418 // thread and thus only need to preserve instruction order, not actually
4419 // enforce memory ordering.
4420 if (FenceSSID == SyncScope::SingleThread)
4421 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
4422 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
4423
4424 return Op;
4425}
4426
4428 MVT GRLenVT, SDValue RMValue) {
4429 // LLVM rounding mode encoding differs from LoongArch FCSR encoding:
4430 // LLVM: 0=RTZ, 1=RNE, 2=RUP, 3=RDN
4431 // FCSR: 0=RNE, 1=RZ, 2=RP, 3=RN
4432 //
4433 // The conversion swaps encodings 0 and 1 while preserving 2 and 3.
4434 // Since the transformation is self-inverse, it applies in both directions:
4435 // LLVM RM <-> LoongArch FCSR RM
4436 //
4437 // Transformation: RM ^ (~(RM >> 1) & 1)
4438 SDValue ShiftRight1 = DAG.getNode(ISD::SRL, DL, GRLenVT, RMValue,
4439 DAG.getConstant(1, DL, GRLenVT));
4440
4441 SDValue SwapMask = DAG.getNode(ISD::AND, DL, GRLenVT,
4442 DAG.getNode(ISD::XOR, DL, GRLenVT, ShiftRight1,
4443 DAG.getConstant(1, DL, GRLenVT)),
4444 DAG.getConstant(1, DL, GRLenVT));
4445
4446 return DAG.getNode(ISD::XOR, DL, GRLenVT, RMValue, SwapMask);
4447}
4448
4449SDValue LoongArchTargetLowering::lowerSET_ROUNDING(SDValue Op,
4450 SelectionDAG &DAG) const {
4451 MVT GRLenVT = Subtarget.getGRLenVT();
4452 SDLoc DL(Op);
4453 SDValue Chain = Op.getOperand(0);
4454 SDValue RMValue = Op.getOperand(1);
4455
4456 if (auto *CVal = dyn_cast<ConstantSDNode>(RMValue)) {
4457 uint64_t RM = CVal->getZExtValue();
4458 if (RM > 3) {
4460 LLVMContext &C = MF.getFunction().getContext();
4461 C.diagnose(DiagnosticInfoUnsupported(
4462 MF.getFunction(),
4463 "rounding mode is not supported by LoongArch hardware",
4464 DiagnosticLocation(DL.getDebugLoc()), DS_Error));
4465 return Chain;
4466 }
4467 }
4468
4469 RMValue = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, RMValue);
4470 RMValue = convertRMEncoding(DAG, DL, GRLenVT, RMValue);
4471
4472 // The RM field in FCSR is at bits [9:8]. Shift the rounding mode value
4473 // into position before writing via WRFCSR.
4474 RMValue = DAG.getNode(ISD::SHL, DL, GRLenVT, RMValue,
4475 DAG.getConstant(8, DL, GRLenVT));
4476
4477 // FCSR3 is an alias of the RM field; writing it avoids clobbering
4478 // unrelated fields in FCSR0.
4479 SDValue FCSRNo = DAG.getTargetConstant(3, DL, GRLenVT);
4480 MachineSDNode *RN = DAG.getMachineNode(LoongArch::WRFCSR, DL, MVT::Other,
4481 FCSRNo, RMValue, Chain);
4482 return SDValue(RN, 0);
4483}
4484
4485SDValue LoongArchTargetLowering::lowerGET_ROUNDING(SDValue Op,
4486 SelectionDAG &DAG) const {
4487 MVT GRLenVT = Subtarget.getGRLenVT();
4488 SDLoc DL(Op);
4489 SDValue Chain = Op->getOperand(0);
4490
4491 // FCSR3 is an alias of the RM field.
4492 SDValue FCSRNo = DAG.getTargetConstant(3, DL, GRLenVT);
4493 MachineSDNode *FCSR = DAG.getMachineNode(LoongArch::RDFCSR, DL, GRLenVT,
4494 MVT::Other, FCSRNo, Chain);
4495 SDValue RMValue = SDValue(FCSR, 0);
4496 Chain = SDValue(FCSR, 1);
4497
4498 // The RM field in FCSR is at bits [9:8].
4499 RMValue = DAG.getNode(ISD::SRL, DL, GRLenVT, RMValue,
4500 DAG.getConstant(8, DL, GRLenVT));
4501 RMValue = convertRMEncoding(DAG, DL, GRLenVT, RMValue);
4502
4503 SDValue RetVal = DAG.getZExtOrTrunc(RMValue, DL, Op.getValueType());
4504 return DAG.getMergeValues({RetVal, Chain}, DL);
4505}
4506
4507SDValue LoongArchTargetLowering::lowerWRITE_REGISTER(SDValue Op,
4508 SelectionDAG &DAG) const {
4509
4510 if (Subtarget.is64Bit() && Op.getOperand(2).getValueType() == MVT::i32) {
4511 DAG.getContext()->emitError(
4512 "On LA64, only 64-bit registers can be written.");
4513 return Op.getOperand(0);
4514 }
4515
4516 if (!Subtarget.is64Bit() && Op.getOperand(2).getValueType() == MVT::i64) {
4517 DAG.getContext()->emitError(
4518 "On LA32, only 32-bit registers can be written.");
4519 return Op.getOperand(0);
4520 }
4521
4522 return Op;
4523}
4524
4525SDValue LoongArchTargetLowering::lowerFRAMEADDR(SDValue Op,
4526 SelectionDAG &DAG) const {
4527 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
4528 DAG.getContext()->emitError("argument to '__builtin_frame_address' must "
4529 "be a constant integer");
4530 return SDValue();
4531 }
4532
4535 Register FrameReg = Subtarget.getRegisterInfo()->getFrameRegister(MF);
4536 EVT VT = Op.getValueType();
4537 SDLoc DL(Op);
4538 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4539 unsigned Depth = Op.getConstantOperandVal(0);
4540 int GRLenInBytes = Subtarget.getGRLen() / 8;
4541
4542 while (Depth--) {
4543 int Offset = -(GRLenInBytes * 2);
4544 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4545 DAG.getSignedConstant(Offset, DL, VT));
4546 FrameAddr =
4547 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4548 }
4549 return FrameAddr;
4550}
4551
4552SDValue LoongArchTargetLowering::lowerRETURNADDR(SDValue Op,
4553 SelectionDAG &DAG) const {
4554 // Currently only support lowering return address for current frame.
4555 if (Op.getConstantOperandVal(0) != 0) {
4556 DAG.getContext()->emitError(
4557 "return address can only be determined for the current frame");
4558 return SDValue();
4559 }
4560
4563 MVT GRLenVT = Subtarget.getGRLenVT();
4564
4565 // Return the value of the return address register, marking it an implicit
4566 // live-in.
4567 Register Reg = MF.addLiveIn(Subtarget.getRegisterInfo()->getRARegister(),
4568 getRegClassFor(GRLenVT));
4569 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, GRLenVT);
4570}
4571
4572SDValue LoongArchTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
4573 SelectionDAG &DAG) const {
4575 auto Size = Subtarget.getGRLen() / 8;
4576 auto FI = MF.getFrameInfo().CreateFixedObject(Size, 0, false);
4577 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4578}
4579
4580SDValue LoongArchTargetLowering::lowerVASTART(SDValue Op,
4581 SelectionDAG &DAG) const {
4583 auto *FuncInfo = MF.getInfo<LoongArchMachineFunctionInfo>();
4584
4585 SDLoc DL(Op);
4586 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4588
4589 // vastart just stores the address of the VarArgsFrameIndex slot into the
4590 // memory location argument.
4591 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4592 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4593 MachinePointerInfo(SV));
4594}
4595
4596// Lower an unsigned vXi64 -> vXf32 conversion to the same round-to-odd
4597// sequence that the generic legalizer uses for the scalar case:
4598//
4599// Odd = (x >> 1) | (x & 1)
4600// Doubled = (float)(int64_t)Odd + (float)(int64_t)Odd // exact, no rounding
4601// Signed = (float)(int64_t)x // valid for x < 2^63
4602// Result = x < 0 ? Doubled : Signed
4603//
4604// The generic half-word expansion is not usable here: it converts the high and
4605// low 32-bit halves separately and adds them, rounding three times, which is
4606// not enough to emulate the single rounding required by uitofp.
4607SDValue LoongArchTargetLowering::lowerUINT_TO_FPToF32(SDValue Op,
4608 SelectionDAG &DAG) const {
4609 SDLoc DL(Op);
4610 SDValue Src = Op.getOperand(0);
4611 EVT SrcVT = Src.getValueType();
4612 EVT DstVT = Op.getValueType();
4613
4614 SDValue Shift = DAG.getShiftAmountConstant(1, SrcVT, DL);
4615 SDValue Half = DAG.getNode(ISD::SRL, DL, SrcVT, Src, Shift);
4616 SDValue Sticky =
4617 DAG.getNode(ISD::AND, DL, SrcVT, Src, DAG.getConstant(1, DL, SrcVT));
4618 SDValue Odd = DAG.getNode(ISD::OR, DL, SrcVT, Half, Sticky);
4619
4620 // Doubling a value with at most 24 significant bits is exact.
4621 SDValue RoundToOdd = DAG.getNode(ISD::SINT_TO_FP, DL, DstVT, Odd);
4622 SDValue Doubled = DAG.getNode(ISD::FADD, DL, DstVT, RoundToOdd, RoundToOdd);
4623
4624 // Values below 2^63 convert directly; above that the signed conversion is
4625 // negative, so the round-to-odd path is used instead.
4626 SDValue Signed = DAG.getNode(ISD::SINT_TO_FP, DL, DstVT, Src);
4627
4628 // The signed conversion is negative exactly when the source did not fit, so
4629 // its sign bit is the mask: broadcasting it with an arithmetic shift avoids
4630 // a comparison followed by a truncate of the 64-bit result to the width of
4631 // the result vector.
4632 EVT MaskVT = DstVT.changeVectorElementTypeToInteger();
4633 SDValue Mask =
4634 DAG.getNode(ISD::SRA, DL, MaskVT, DAG.getBitcast(MaskVT, Signed),
4635 DAG.getShiftAmountConstant(31, MaskVT, DL));
4636 return DAG.getSelect(DL, DstVT, Mask, Doubled, Signed);
4637}
4638
4639SDValue LoongArchTargetLowering::lowerUINT_TO_FP(SDValue Op,
4640 SelectionDAG &DAG) const {
4641 SDLoc DL(Op);
4642 SDValue Op0 = Op.getOperand(0);
4643 EVT VT = Op.getValueType();
4644 EVT Op0VT = Op0.getValueType();
4645
4646 if (VT.isVector()) {
4647 if (VT.getScalarSizeInBits() == Op0VT.getScalarSizeInBits())
4648 return Op;
4649
4650 // There is no unsigned 64-bit to 32-bit conversion instruction, so
4651 // synthesize one with a single rounding. A value known to be
4652 // non-negative converts exactly as signed, and that form is native.
4653 if (Subtarget.hasExtLASX() && Op0VT.getScalarType() == MVT::i64 &&
4654 VT.getScalarType() == MVT::f32) {
4655 if (DAG.SignBitIsZero(Op0) || Op->getFlags().hasNonNeg())
4656 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, Op0);
4657 return lowerUINT_TO_FPToF32(Op, DAG);
4658 }
4659
4660 return SDValue();
4661 }
4662
4663 if ((DAG.SignBitIsZero(Op0) || Op->getFlags().hasNonNeg()) &&
4666 return DAG.getNode(ISD::SINT_TO_FP, DL, VT, Op0);
4667
4668 // We can't do uint64 -> double -> float because of double-rounding issue.
4669 if (Subtarget.hasExtLSX() && Op0VT == MVT::i64 && VT == MVT::f64) {
4670 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2i64, Op0);
4671 SDValue Conv = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::v2f64, Op0);
4672 Conv = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64, Conv,
4673 DAG.getIntPtrConstant(0, DL));
4674 return Conv;
4675 }
4676
4677 if (!Subtarget.is64Bit() || !Subtarget.hasBasicF() || Subtarget.hasBasicD())
4678 return SDValue();
4679
4680 assert(Subtarget.is64Bit() && Subtarget.hasBasicF() &&
4681 !Subtarget.hasBasicD() && "unexpected target features");
4682
4683 if (Op0->getOpcode() == ISD::AND) {
4684 auto *C = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4685 if (C && C->getZExtValue() < UINT64_C(0xFFFFFFFF))
4686 return Op;
4687 }
4688
4689 if (Op0->getOpcode() == LoongArchISD::BSTRPICK &&
4690 Op0.getConstantOperandVal(1) < UINT64_C(0X1F) &&
4691 Op0.getConstantOperandVal(2) == UINT64_C(0))
4692 return Op;
4693
4694 if (Op0.getOpcode() == ISD::AssertZext &&
4695 dyn_cast<VTSDNode>(Op0.getOperand(1))->getVT().bitsLT(MVT::i32))
4696 return Op;
4697
4698 EVT OpVT = Op0.getValueType();
4699 EVT RetVT = Op.getValueType();
4700 RTLIB::Libcall LC = RTLIB::getUINTTOFP(OpVT, RetVT);
4701 MakeLibCallOptions CallOptions;
4702 CallOptions.setTypeListBeforeSoften(OpVT, RetVT);
4703 SDValue Chain = SDValue();
4705 std::tie(Result, Chain) =
4706 makeLibCall(DAG, LC, Op.getValueType(), Op0, CallOptions, DL, Chain);
4707 return Result;
4708}
4709
4710SDValue LoongArchTargetLowering::lowerSINT_TO_FP(SDValue Op,
4711 SelectionDAG &DAG) const {
4712 assert(Subtarget.is64Bit() && Subtarget.hasBasicF() &&
4713 !Subtarget.hasBasicD() && "unexpected target features");
4714
4715 SDLoc DL(Op);
4716 SDValue Op0 = Op.getOperand(0);
4717
4718 if ((Op0.getOpcode() == ISD::AssertSext ||
4720 dyn_cast<VTSDNode>(Op0.getOperand(1))->getVT().bitsLE(MVT::i32))
4721 return Op;
4722
4723 EVT OpVT = Op0.getValueType();
4724 EVT RetVT = Op.getValueType();
4725 RTLIB::Libcall LC = RTLIB::getSINTTOFP(OpVT, RetVT);
4726 MakeLibCallOptions CallOptions;
4727 CallOptions.setTypeListBeforeSoften(OpVT, RetVT);
4728 SDValue Chain = SDValue();
4730 std::tie(Result, Chain) =
4731 makeLibCall(DAG, LC, Op.getValueType(), Op0, CallOptions, DL, Chain);
4732 return Result;
4733}
4734
4735SDValue LoongArchTargetLowering::lowerBITCAST(SDValue Op,
4736 SelectionDAG &DAG) const {
4737
4738 SDLoc DL(Op);
4739 EVT VT = Op.getValueType();
4740 SDValue Op0 = Op.getOperand(0);
4741 EVT Op0VT = Op0.getValueType();
4742
4743 if (Op.getValueType() == MVT::f32 && Op0VT == MVT::i32 &&
4744 Subtarget.is64Bit() && Subtarget.hasBasicF()) {
4745 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4746 return DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, NewOp0);
4747 }
4748 if (VT == MVT::f64 && Op0VT == MVT::i64 && !Subtarget.is64Bit()) {
4749 SDValue Lo, Hi;
4750 std::tie(Lo, Hi) = DAG.SplitScalar(Op0, DL, MVT::i32, MVT::i32);
4751 return DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64, Lo, Hi);
4752 }
4753 return Op;
4754}
4755
4756SDValue LoongArchTargetLowering::lowerFP_TO_SINT(SDValue Op,
4757 SelectionDAG &DAG) const {
4758
4759 SDLoc DL(Op);
4760 SDValue Op0 = Op.getOperand(0);
4761
4762 if (Op0.getValueType() == MVT::f16)
4763 Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0);
4764
4765 if (Op.getValueSizeInBits() > 32 && Subtarget.hasBasicF() &&
4766 !Subtarget.hasBasicD()) {
4767 SDValue Dst = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f32, Op0);
4768 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Dst);
4769 }
4770
4771 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
4772 SDValue Trunc = DAG.getNode(LoongArchISD::FTINT, DL, FPTy, Op0);
4773 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Trunc);
4774}
4775
4776// [X]VFTINTRZ and FTINTRZ saturate out-of-range values and convert NaN to 0,
4777// which is exactly the semantics of FP_TO_SINT_SAT with a native saturation
4778// width.
4779SDValue LoongArchTargetLowering::lowerFP_TO_SINT_SAT(SDValue Op,
4780 SelectionDAG &DAG) const {
4781 SDLoc DL(Op);
4782 SDValue Src = Op.getOperand(0);
4783 EVT VT = Op.getValueType();
4784 EVT SrcVT = Src.getValueType();
4785 unsigned SatWidth = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4786
4787 // Vectors are selected by patterns.
4788 if (VT.isVector()) {
4789 if (SatWidth == VT.getScalarSizeInBits() &&
4790 SatWidth == SrcVT.getScalarSizeInBits())
4791 return Op;
4792 return SDValue();
4793 }
4794
4795 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
4796 return SDValue();
4797
4798 if (SatWidth == 32) {
4799 SDValue Ftint = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f32, Src);
4800 if (Subtarget.is64Bit())
4801 return DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, VT, Ftint);
4802 return DAG.getBitcast(VT, Ftint);
4803 }
4804
4805 if (SatWidth == 64 && Subtarget.is64Bit() && Subtarget.hasBasicD()) {
4806 SDValue Ftint = DAG.getNode(LoongArchISD::FTINT, DL, MVT::f64, Src);
4807 return DAG.getBitcast(VT, Ftint);
4808 }
4809
4810 return SDValue();
4811}
4812
4813SDValue LoongArchTargetLowering::lowerFP_TO_UINT(SDValue Op,
4814 SelectionDAG &DAG) const {
4815 if (!Subtarget.hasExtLSX())
4816 return SDValue();
4817
4818 SDLoc DL(Op);
4819 SDValue Src = Op.getOperand(0);
4820 EVT VT = Op.getValueType();
4821 EVT SrcVT = Src.getValueType();
4822
4823 if (VT != MVT::i64)
4824 return SDValue();
4825
4826 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
4827 return SDValue();
4828
4829 if (SrcVT == MVT::f32)
4830 Src = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Src);
4831 Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, Src);
4832 SDValue Conv = DAG.getNode(ISD::FP_TO_UINT, DL, MVT::v2i64, Src);
4833 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Conv,
4834 DAG.getIntPtrConstant(0, DL));
4835}
4836
4838 SelectionDAG &DAG, unsigned Flags) {
4839 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
4840}
4841
4843 SelectionDAG &DAG, unsigned Flags) {
4844 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
4845 Flags);
4846}
4847
4849 SelectionDAG &DAG, unsigned Flags) {
4850 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
4851 N->getOffset(), Flags);
4852}
4853
4855 SelectionDAG &DAG, unsigned Flags) {
4856 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
4857}
4858
4859template <class NodeTy>
4860SDValue LoongArchTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4862 bool IsLocal) const {
4863 SDLoc DL(N);
4864 EVT Ty = getPointerTy(DAG.getDataLayout());
4865 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
4866 SDValue Load;
4867
4868 switch (M) {
4869 default:
4870 report_fatal_error("Unsupported code model");
4871
4872 case CodeModel::Large: {
4873 assert(Subtarget.is64Bit() && "Large code model requires LA64");
4874
4875 // This is not actually used, but is necessary for successfully matching
4876 // the PseudoLA_*_LARGE nodes.
4877 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4878 if (IsLocal) {
4879 // This generates the pattern (PseudoLA_PCREL_LARGE tmp sym), that
4880 // eventually becomes the desired 5-insn code sequence.
4881 Load = SDValue(DAG.getMachineNode(LoongArch::PseudoLA_PCREL_LARGE, DL, Ty,
4882 Tmp, Addr),
4883 0);
4884 } else {
4885 // This generates the pattern (PseudoLA_GOT_LARGE tmp sym), that
4886 // eventually becomes the desired 5-insn code sequence.
4887 Load = SDValue(
4888 DAG.getMachineNode(LoongArch::PseudoLA_GOT_LARGE, DL, Ty, Tmp, Addr),
4889 0);
4890 }
4891 break;
4892 }
4893
4894 case CodeModel::Small:
4895 case CodeModel::Medium:
4896 if (IsLocal) {
4897 // This generates the pattern (PseudoLA_PCREL sym), which
4898 //
4899 // for la32r expands to:
4900 // (addi.w (pcaddu12i %pcadd_hi20(sym)) %pcadd_lo12(.Lpcadd_hi)).
4901 //
4902 // for la32s and la64 expands to:
4903 // (addi.w/d (pcalau12i %pc_hi20(sym)) %pc_lo12(sym)).
4904 Load = SDValue(
4905 DAG.getMachineNode(LoongArch::PseudoLA_PCREL, DL, Ty, Addr), 0);
4906 } else {
4907 // This generates the pattern (PseudoLA_GOT sym), which
4908 //
4909 // for la32r expands to:
4910 // (ld.w (pcaddu12i %got_pcadd_hi20(sym)) %pcadd_lo12(.Lpcadd_hi)).
4911 //
4912 // for la32s and la64 expands to:
4913 // (ld.w/d (pcalau12i %got_pc_hi20(sym)) %got_pc_lo12(sym)).
4914 Load =
4915 SDValue(DAG.getMachineNode(LoongArch::PseudoLA_GOT, DL, Ty, Addr), 0);
4916 }
4917 }
4918
4919 if (!IsLocal) {
4920 // Mark the load instruction as invariant to enable hoisting in MachineLICM.
4922 MachineMemOperand *MemOp = MF.getMachineMemOperand(
4926 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
4927 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
4928 }
4929
4930 return Load;
4931}
4932
4933SDValue LoongArchTargetLowering::lowerBlockAddress(SDValue Op,
4934 SelectionDAG &DAG) const {
4935 return getAddr(cast<BlockAddressSDNode>(Op), DAG,
4936 DAG.getTarget().getCodeModel());
4937}
4938
4939SDValue LoongArchTargetLowering::lowerJumpTable(SDValue Op,
4940 SelectionDAG &DAG) const {
4941 return getAddr(cast<JumpTableSDNode>(Op), DAG,
4942 DAG.getTarget().getCodeModel());
4943}
4944
4945SDValue LoongArchTargetLowering::lowerConstantPool(SDValue Op,
4946 SelectionDAG &DAG) const {
4947 return getAddr(cast<ConstantPoolSDNode>(Op), DAG,
4948 DAG.getTarget().getCodeModel());
4949}
4950
4951SDValue LoongArchTargetLowering::lowerGlobalAddress(SDValue Op,
4952 SelectionDAG &DAG) const {
4953 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
4954 assert(N->getOffset() == 0 && "unexpected offset in global node");
4955 auto CM = DAG.getTarget().getCodeModel();
4956 const GlobalValue *GV = N->getGlobal();
4957
4958 if (GV->isDSOLocal() && isa<GlobalVariable>(GV)) {
4959 if (auto GCM = dyn_cast<GlobalVariable>(GV)->getCodeModel())
4960 CM = *GCM;
4961 }
4962
4963 return getAddr(N, DAG, CM, GV->isDSOLocal());
4964}
4965
4966SDValue LoongArchTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
4967 SelectionDAG &DAG,
4968 unsigned Opc, bool UseGOT,
4969 bool Large) const {
4970 SDLoc DL(N);
4971 EVT Ty = getPointerTy(DAG.getDataLayout());
4972 MVT GRLenVT = Subtarget.getGRLenVT();
4973
4974 // This is not actually used, but is necessary for successfully matching the
4975 // PseudoLA_*_LARGE nodes.
4976 SDValue Tmp = DAG.getConstant(0, DL, Ty);
4977 SDValue Addr = DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, 0);
4978
4979 // Only IE needs an extra argument for large code model.
4980 SDValue Offset = Opc == LoongArch::PseudoLA_TLS_IE_LARGE
4981 ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
4982 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
4983
4984 // If it is LE for normal/medium code model, the add tp operation will occur
4985 // during the pseudo-instruction expansion.
4986 if (Opc == LoongArch::PseudoLA_TLS_LE && !Large)
4987 return Offset;
4988
4989 if (UseGOT) {
4990 // Mark the load instruction as invariant to enable hoisting in MachineLICM.
4992 MachineMemOperand *MemOp = MF.getMachineMemOperand(
4996 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
4997 DAG.setNodeMemRefs(cast<MachineSDNode>(Offset.getNode()), {MemOp});
4998 }
4999
5000 // Add the thread pointer.
5001 return DAG.getNode(ISD::ADD, DL, Ty, Offset,
5002 DAG.getRegister(LoongArch::R2, GRLenVT));
5003}
5004
5005SDValue LoongArchTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
5006 SelectionDAG &DAG,
5007 unsigned Opc,
5008 bool Large) const {
5009 SDLoc DL(N);
5010 EVT Ty = getPointerTy(DAG.getDataLayout());
5011 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
5012
5013 // This is not actually used, but is necessary for successfully matching the
5014 // PseudoLA_*_LARGE nodes.
5015 SDValue Tmp = DAG.getConstant(0, DL, Ty);
5016
5017 // Use a PC-relative addressing mode to access the dynamic GOT address.
5018 SDValue Addr = DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, 0);
5019 SDValue Load = Large ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
5020 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
5021
5022 // Prepare argument list to generate call.
5024 Args.emplace_back(Load, CallTy);
5025
5026 // Setup call to __tls_get_addr.
5027 TargetLowering::CallLoweringInfo CLI(DAG);
5028 CLI.setDebugLoc(DL)
5029 .setChain(DAG.getEntryNode())
5030 .setLibCallee(CallingConv::C, CallTy,
5031 DAG.getExternalSymbol("__tls_get_addr", Ty),
5032 std::move(Args));
5033
5034 return LowerCallTo(CLI).first;
5035}
5036
5037SDValue LoongArchTargetLowering::getTLSDescAddr(GlobalAddressSDNode *N,
5038 SelectionDAG &DAG, unsigned Opc,
5039 bool Large) const {
5040 SDLoc DL(N);
5041 EVT Ty = getPointerTy(DAG.getDataLayout());
5042 const GlobalValue *GV = N->getGlobal();
5043
5044 // This is not actually used, but is necessary for successfully matching the
5045 // PseudoLA_*_LARGE nodes.
5046 SDValue Tmp = DAG.getConstant(0, DL, Ty);
5047
5048 // Use a PC-relative addressing mode to access the global dynamic GOT address.
5049 // This generates the pattern (PseudoLA_TLS_DESC_PC{,LARGE} sym).
5050 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
5051 return Large ? SDValue(DAG.getMachineNode(Opc, DL, Ty, Tmp, Addr), 0)
5052 : SDValue(DAG.getMachineNode(Opc, DL, Ty, Addr), 0);
5053}
5054
5055SDValue
5056LoongArchTargetLowering::lowerGlobalTLSAddress(SDValue Op,
5057 SelectionDAG &DAG) const {
5060 report_fatal_error("In GHC calling convention TLS is not supported");
5061
5062 bool Large = DAG.getTarget().getCodeModel() == CodeModel::Large;
5063 assert((!Large || Subtarget.is64Bit()) && "Large code model requires LA64");
5064
5065 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
5066 assert(N->getOffset() == 0 && "unexpected offset in global node");
5067
5068 if (DAG.getTarget().useEmulatedTLS())
5069 reportFatalUsageError("the emulated TLS is prohibited");
5070
5071 bool IsDesc = DAG.getTarget().useTLSDESC();
5072
5073 switch (getTargetMachine().getTLSModel(N->getGlobal())) {
5075 // In this model, application code calls the dynamic linker function
5076 // __tls_get_addr to locate TLS offsets into the dynamic thread vector at
5077 // runtime.
5078 if (!IsDesc)
5079 return getDynamicTLSAddr(N, DAG,
5080 Large ? LoongArch::PseudoLA_TLS_GD_LARGE
5081 : LoongArch::PseudoLA_TLS_GD,
5082 Large);
5083 break;
5085 // Same as GeneralDynamic, except for assembly modifiers and relocation
5086 // records.
5087 if (!IsDesc)
5088 return getDynamicTLSAddr(N, DAG,
5089 Large ? LoongArch::PseudoLA_TLS_LD_LARGE
5090 : LoongArch::PseudoLA_TLS_LD,
5091 Large);
5092 break;
5094 // This model uses the GOT to resolve TLS offsets.
5095 return getStaticTLSAddr(N, DAG,
5096 Large ? LoongArch::PseudoLA_TLS_IE_LARGE
5097 : LoongArch::PseudoLA_TLS_IE,
5098 /*UseGOT=*/true, Large);
5100 // This model is used when static linking as the TLS offsets are resolved
5101 // during program linking.
5102 //
5103 // This node doesn't need an extra argument for the large code model.
5104 return getStaticTLSAddr(N, DAG, LoongArch::PseudoLA_TLS_LE,
5105 /*UseGOT=*/false, Large);
5106 }
5107
5108 return getTLSDescAddr(N, DAG,
5109 Large ? LoongArch::PseudoLA_TLS_DESC_LARGE
5110 : LoongArch::PseudoLA_TLS_DESC,
5111 Large);
5112}
5113
5114template <unsigned N>
5116 SelectionDAG &DAG, bool IsSigned = false) {
5117 auto *CImm = cast<ConstantSDNode>(Op->getOperand(ImmOp));
5118 // Check the ImmArg.
5119 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
5120 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
5121 DAG.getContext()->emitError(Op->getOperationName(0) +
5122 ": argument out of range.");
5123 return DAG.getNode(ISD::UNDEF, SDLoc(Op), Op.getValueType());
5124 }
5125 return SDValue();
5126}
5127
5128SDValue
5129LoongArchTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5130 SelectionDAG &DAG) const {
5131 switch (Op.getConstantOperandVal(0)) {
5132 default:
5133 return SDValue(); // Don't custom lower most intrinsics.
5134 case Intrinsic::thread_pointer: {
5135 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5136 return DAG.getRegister(LoongArch::R2, PtrVT);
5137 }
5138 case Intrinsic::loongarch_lsx_vpickve2gr_d:
5139 case Intrinsic::loongarch_lsx_vpickve2gr_du:
5140 case Intrinsic::loongarch_lsx_vreplvei_d:
5141 case Intrinsic::loongarch_lasx_xvrepl128vei_d:
5142 return checkIntrinsicImmArg<1>(Op, 2, DAG);
5143 case Intrinsic::loongarch_lsx_vreplvei_w:
5144 case Intrinsic::loongarch_lasx_xvrepl128vei_w:
5145 case Intrinsic::loongarch_lasx_xvpickve2gr_d:
5146 case Intrinsic::loongarch_lasx_xvpickve2gr_du:
5147 case Intrinsic::loongarch_lasx_xvpickve_d:
5148 case Intrinsic::loongarch_lasx_xvpickve_d_f:
5149 return checkIntrinsicImmArg<2>(Op, 2, DAG);
5150 case Intrinsic::loongarch_lasx_xvinsve0_d:
5151 return checkIntrinsicImmArg<2>(Op, 3, DAG);
5152 case Intrinsic::loongarch_lsx_vsat_b:
5153 case Intrinsic::loongarch_lsx_vsat_bu:
5154 case Intrinsic::loongarch_lsx_vrotri_b:
5155 case Intrinsic::loongarch_lsx_vsllwil_h_b:
5156 case Intrinsic::loongarch_lsx_vsllwil_hu_bu:
5157 case Intrinsic::loongarch_lsx_vsrlri_b:
5158 case Intrinsic::loongarch_lsx_vsrari_b:
5159 case Intrinsic::loongarch_lsx_vreplvei_h:
5160 case Intrinsic::loongarch_lasx_xvsat_b:
5161 case Intrinsic::loongarch_lasx_xvsat_bu:
5162 case Intrinsic::loongarch_lasx_xvrotri_b:
5163 case Intrinsic::loongarch_lasx_xvsllwil_h_b:
5164 case Intrinsic::loongarch_lasx_xvsllwil_hu_bu:
5165 case Intrinsic::loongarch_lasx_xvsrlri_b:
5166 case Intrinsic::loongarch_lasx_xvsrari_b:
5167 case Intrinsic::loongarch_lasx_xvrepl128vei_h:
5168 case Intrinsic::loongarch_lasx_xvpickve_w:
5169 case Intrinsic::loongarch_lasx_xvpickve_w_f:
5170 return checkIntrinsicImmArg<3>(Op, 2, DAG);
5171 case Intrinsic::loongarch_lasx_xvinsve0_w:
5172 return checkIntrinsicImmArg<3>(Op, 3, DAG);
5173 case Intrinsic::loongarch_lsx_vsat_h:
5174 case Intrinsic::loongarch_lsx_vsat_hu:
5175 case Intrinsic::loongarch_lsx_vrotri_h:
5176 case Intrinsic::loongarch_lsx_vsllwil_w_h:
5177 case Intrinsic::loongarch_lsx_vsllwil_wu_hu:
5178 case Intrinsic::loongarch_lsx_vsrlri_h:
5179 case Intrinsic::loongarch_lsx_vsrari_h:
5180 case Intrinsic::loongarch_lsx_vreplvei_b:
5181 case Intrinsic::loongarch_lasx_xvsat_h:
5182 case Intrinsic::loongarch_lasx_xvsat_hu:
5183 case Intrinsic::loongarch_lasx_xvrotri_h:
5184 case Intrinsic::loongarch_lasx_xvsllwil_w_h:
5185 case Intrinsic::loongarch_lasx_xvsllwil_wu_hu:
5186 case Intrinsic::loongarch_lasx_xvsrlri_h:
5187 case Intrinsic::loongarch_lasx_xvsrari_h:
5188 case Intrinsic::loongarch_lasx_xvrepl128vei_b:
5189 return checkIntrinsicImmArg<4>(Op, 2, DAG);
5190 case Intrinsic::loongarch_lsx_vsrlni_b_h:
5191 case Intrinsic::loongarch_lsx_vsrani_b_h:
5192 case Intrinsic::loongarch_lsx_vsrlrni_b_h:
5193 case Intrinsic::loongarch_lsx_vsrarni_b_h:
5194 case Intrinsic::loongarch_lsx_vssrlni_b_h:
5195 case Intrinsic::loongarch_lsx_vssrani_b_h:
5196 case Intrinsic::loongarch_lsx_vssrlni_bu_h:
5197 case Intrinsic::loongarch_lsx_vssrani_bu_h:
5198 case Intrinsic::loongarch_lsx_vssrlrni_b_h:
5199 case Intrinsic::loongarch_lsx_vssrarni_b_h:
5200 case Intrinsic::loongarch_lsx_vssrlrni_bu_h:
5201 case Intrinsic::loongarch_lsx_vssrarni_bu_h:
5202 case Intrinsic::loongarch_lasx_xvsrlni_b_h:
5203 case Intrinsic::loongarch_lasx_xvsrani_b_h:
5204 case Intrinsic::loongarch_lasx_xvsrlrni_b_h:
5205 case Intrinsic::loongarch_lasx_xvsrarni_b_h:
5206 case Intrinsic::loongarch_lasx_xvssrlni_b_h:
5207 case Intrinsic::loongarch_lasx_xvssrani_b_h:
5208 case Intrinsic::loongarch_lasx_xvssrlni_bu_h:
5209 case Intrinsic::loongarch_lasx_xvssrani_bu_h:
5210 case Intrinsic::loongarch_lasx_xvssrlrni_b_h:
5211 case Intrinsic::loongarch_lasx_xvssrarni_b_h:
5212 case Intrinsic::loongarch_lasx_xvssrlrni_bu_h:
5213 case Intrinsic::loongarch_lasx_xvssrarni_bu_h:
5214 return checkIntrinsicImmArg<4>(Op, 3, DAG);
5215 case Intrinsic::loongarch_lsx_vsat_w:
5216 case Intrinsic::loongarch_lsx_vsat_wu:
5217 case Intrinsic::loongarch_lsx_vrotri_w:
5218 case Intrinsic::loongarch_lsx_vsllwil_d_w:
5219 case Intrinsic::loongarch_lsx_vsllwil_du_wu:
5220 case Intrinsic::loongarch_lsx_vsrlri_w:
5221 case Intrinsic::loongarch_lsx_vsrari_w:
5222 case Intrinsic::loongarch_lsx_vslei_bu:
5223 case Intrinsic::loongarch_lsx_vslei_hu:
5224 case Intrinsic::loongarch_lsx_vslei_wu:
5225 case Intrinsic::loongarch_lsx_vslei_du:
5226 case Intrinsic::loongarch_lsx_vslti_bu:
5227 case Intrinsic::loongarch_lsx_vslti_hu:
5228 case Intrinsic::loongarch_lsx_vslti_wu:
5229 case Intrinsic::loongarch_lsx_vslti_du:
5230 case Intrinsic::loongarch_lsx_vbsll_v:
5231 case Intrinsic::loongarch_lsx_vbsrl_v:
5232 case Intrinsic::loongarch_lasx_xvsat_w:
5233 case Intrinsic::loongarch_lasx_xvsat_wu:
5234 case Intrinsic::loongarch_lasx_xvrotri_w:
5235 case Intrinsic::loongarch_lasx_xvsllwil_d_w:
5236 case Intrinsic::loongarch_lasx_xvsllwil_du_wu:
5237 case Intrinsic::loongarch_lasx_xvsrlri_w:
5238 case Intrinsic::loongarch_lasx_xvsrari_w:
5239 case Intrinsic::loongarch_lasx_xvslei_bu:
5240 case Intrinsic::loongarch_lasx_xvslei_hu:
5241 case Intrinsic::loongarch_lasx_xvslei_wu:
5242 case Intrinsic::loongarch_lasx_xvslei_du:
5243 case Intrinsic::loongarch_lasx_xvslti_bu:
5244 case Intrinsic::loongarch_lasx_xvslti_hu:
5245 case Intrinsic::loongarch_lasx_xvslti_wu:
5246 case Intrinsic::loongarch_lasx_xvslti_du:
5247 case Intrinsic::loongarch_lasx_xvbsll_v:
5248 case Intrinsic::loongarch_lasx_xvbsrl_v:
5249 return checkIntrinsicImmArg<5>(Op, 2, DAG);
5250 case Intrinsic::loongarch_lsx_vseqi_b:
5251 case Intrinsic::loongarch_lsx_vseqi_h:
5252 case Intrinsic::loongarch_lsx_vseqi_w:
5253 case Intrinsic::loongarch_lsx_vseqi_d:
5254 case Intrinsic::loongarch_lsx_vslei_b:
5255 case Intrinsic::loongarch_lsx_vslei_h:
5256 case Intrinsic::loongarch_lsx_vslei_w:
5257 case Intrinsic::loongarch_lsx_vslei_d:
5258 case Intrinsic::loongarch_lsx_vslti_b:
5259 case Intrinsic::loongarch_lsx_vslti_h:
5260 case Intrinsic::loongarch_lsx_vslti_w:
5261 case Intrinsic::loongarch_lsx_vslti_d:
5262 case Intrinsic::loongarch_lasx_xvseqi_b:
5263 case Intrinsic::loongarch_lasx_xvseqi_h:
5264 case Intrinsic::loongarch_lasx_xvseqi_w:
5265 case Intrinsic::loongarch_lasx_xvseqi_d:
5266 case Intrinsic::loongarch_lasx_xvslei_b:
5267 case Intrinsic::loongarch_lasx_xvslei_h:
5268 case Intrinsic::loongarch_lasx_xvslei_w:
5269 case Intrinsic::loongarch_lasx_xvslei_d:
5270 case Intrinsic::loongarch_lasx_xvslti_b:
5271 case Intrinsic::loongarch_lasx_xvslti_h:
5272 case Intrinsic::loongarch_lasx_xvslti_w:
5273 case Intrinsic::loongarch_lasx_xvslti_d:
5274 return checkIntrinsicImmArg<5>(Op, 2, DAG, /*IsSigned=*/true);
5275 case Intrinsic::loongarch_lsx_vsrlni_h_w:
5276 case Intrinsic::loongarch_lsx_vsrani_h_w:
5277 case Intrinsic::loongarch_lsx_vsrlrni_h_w:
5278 case Intrinsic::loongarch_lsx_vsrarni_h_w:
5279 case Intrinsic::loongarch_lsx_vssrlni_h_w:
5280 case Intrinsic::loongarch_lsx_vssrani_h_w:
5281 case Intrinsic::loongarch_lsx_vssrlni_hu_w:
5282 case Intrinsic::loongarch_lsx_vssrani_hu_w:
5283 case Intrinsic::loongarch_lsx_vssrlrni_h_w:
5284 case Intrinsic::loongarch_lsx_vssrarni_h_w:
5285 case Intrinsic::loongarch_lsx_vssrlrni_hu_w:
5286 case Intrinsic::loongarch_lsx_vssrarni_hu_w:
5287 case Intrinsic::loongarch_lsx_vfrstpi_b:
5288 case Intrinsic::loongarch_lsx_vfrstpi_h:
5289 case Intrinsic::loongarch_lasx_xvsrlni_h_w:
5290 case Intrinsic::loongarch_lasx_xvsrani_h_w:
5291 case Intrinsic::loongarch_lasx_xvsrlrni_h_w:
5292 case Intrinsic::loongarch_lasx_xvsrarni_h_w:
5293 case Intrinsic::loongarch_lasx_xvssrlni_h_w:
5294 case Intrinsic::loongarch_lasx_xvssrani_h_w:
5295 case Intrinsic::loongarch_lasx_xvssrlni_hu_w:
5296 case Intrinsic::loongarch_lasx_xvssrani_hu_w:
5297 case Intrinsic::loongarch_lasx_xvssrlrni_h_w:
5298 case Intrinsic::loongarch_lasx_xvssrarni_h_w:
5299 case Intrinsic::loongarch_lasx_xvssrlrni_hu_w:
5300 case Intrinsic::loongarch_lasx_xvssrarni_hu_w:
5301 case Intrinsic::loongarch_lasx_xvfrstpi_b:
5302 case Intrinsic::loongarch_lasx_xvfrstpi_h:
5303 return checkIntrinsicImmArg<5>(Op, 3, DAG);
5304 case Intrinsic::loongarch_lsx_vsat_d:
5305 case Intrinsic::loongarch_lsx_vsat_du:
5306 case Intrinsic::loongarch_lsx_vrotri_d:
5307 case Intrinsic::loongarch_lsx_vsrlri_d:
5308 case Intrinsic::loongarch_lsx_vsrari_d:
5309 case Intrinsic::loongarch_lasx_xvsat_d:
5310 case Intrinsic::loongarch_lasx_xvsat_du:
5311 case Intrinsic::loongarch_lasx_xvrotri_d:
5312 case Intrinsic::loongarch_lasx_xvsrlri_d:
5313 case Intrinsic::loongarch_lasx_xvsrari_d:
5314 return checkIntrinsicImmArg<6>(Op, 2, DAG);
5315 case Intrinsic::loongarch_lsx_vsrlni_w_d:
5316 case Intrinsic::loongarch_lsx_vsrani_w_d:
5317 case Intrinsic::loongarch_lsx_vsrlrni_w_d:
5318 case Intrinsic::loongarch_lsx_vsrarni_w_d:
5319 case Intrinsic::loongarch_lsx_vssrlni_w_d:
5320 case Intrinsic::loongarch_lsx_vssrani_w_d:
5321 case Intrinsic::loongarch_lsx_vssrlni_wu_d:
5322 case Intrinsic::loongarch_lsx_vssrani_wu_d:
5323 case Intrinsic::loongarch_lsx_vssrlrni_w_d:
5324 case Intrinsic::loongarch_lsx_vssrarni_w_d:
5325 case Intrinsic::loongarch_lsx_vssrlrni_wu_d:
5326 case Intrinsic::loongarch_lsx_vssrarni_wu_d:
5327 case Intrinsic::loongarch_lasx_xvsrlni_w_d:
5328 case Intrinsic::loongarch_lasx_xvsrani_w_d:
5329 case Intrinsic::loongarch_lasx_xvsrlrni_w_d:
5330 case Intrinsic::loongarch_lasx_xvsrarni_w_d:
5331 case Intrinsic::loongarch_lasx_xvssrlni_w_d:
5332 case Intrinsic::loongarch_lasx_xvssrani_w_d:
5333 case Intrinsic::loongarch_lasx_xvssrlni_wu_d:
5334 case Intrinsic::loongarch_lasx_xvssrani_wu_d:
5335 case Intrinsic::loongarch_lasx_xvssrlrni_w_d:
5336 case Intrinsic::loongarch_lasx_xvssrarni_w_d:
5337 case Intrinsic::loongarch_lasx_xvssrlrni_wu_d:
5338 case Intrinsic::loongarch_lasx_xvssrarni_wu_d:
5339 return checkIntrinsicImmArg<6>(Op, 3, DAG);
5340 case Intrinsic::loongarch_lsx_vsrlni_d_q:
5341 case Intrinsic::loongarch_lsx_vsrani_d_q:
5342 case Intrinsic::loongarch_lsx_vsrlrni_d_q:
5343 case Intrinsic::loongarch_lsx_vsrarni_d_q:
5344 case Intrinsic::loongarch_lsx_vssrlni_d_q:
5345 case Intrinsic::loongarch_lsx_vssrani_d_q:
5346 case Intrinsic::loongarch_lsx_vssrlni_du_q:
5347 case Intrinsic::loongarch_lsx_vssrani_du_q:
5348 case Intrinsic::loongarch_lsx_vssrlrni_d_q:
5349 case Intrinsic::loongarch_lsx_vssrarni_d_q:
5350 case Intrinsic::loongarch_lsx_vssrlrni_du_q:
5351 case Intrinsic::loongarch_lsx_vssrarni_du_q:
5352 case Intrinsic::loongarch_lasx_xvsrlni_d_q:
5353 case Intrinsic::loongarch_lasx_xvsrani_d_q:
5354 case Intrinsic::loongarch_lasx_xvsrlrni_d_q:
5355 case Intrinsic::loongarch_lasx_xvsrarni_d_q:
5356 case Intrinsic::loongarch_lasx_xvssrlni_d_q:
5357 case Intrinsic::loongarch_lasx_xvssrani_d_q:
5358 case Intrinsic::loongarch_lasx_xvssrlni_du_q:
5359 case Intrinsic::loongarch_lasx_xvssrani_du_q:
5360 case Intrinsic::loongarch_lasx_xvssrlrni_d_q:
5361 case Intrinsic::loongarch_lasx_xvssrarni_d_q:
5362 case Intrinsic::loongarch_lasx_xvssrlrni_du_q:
5363 case Intrinsic::loongarch_lasx_xvssrarni_du_q:
5364 return checkIntrinsicImmArg<7>(Op, 3, DAG);
5365 case Intrinsic::loongarch_lsx_vnori_b:
5366 case Intrinsic::loongarch_lsx_vshuf4i_b:
5367 case Intrinsic::loongarch_lsx_vshuf4i_h:
5368 case Intrinsic::loongarch_lsx_vshuf4i_w:
5369 case Intrinsic::loongarch_lasx_xvnori_b:
5370 case Intrinsic::loongarch_lasx_xvshuf4i_b:
5371 case Intrinsic::loongarch_lasx_xvshuf4i_h:
5372 case Intrinsic::loongarch_lasx_xvshuf4i_w:
5373 case Intrinsic::loongarch_lasx_xvpermi_d:
5374 return checkIntrinsicImmArg<8>(Op, 2, DAG);
5375 case Intrinsic::loongarch_lsx_vshuf4i_d:
5376 case Intrinsic::loongarch_lsx_vpermi_w:
5377 case Intrinsic::loongarch_lsx_vbitseli_b:
5378 case Intrinsic::loongarch_lsx_vextrins_b:
5379 case Intrinsic::loongarch_lsx_vextrins_h:
5380 case Intrinsic::loongarch_lsx_vextrins_w:
5381 case Intrinsic::loongarch_lsx_vextrins_d:
5382 case Intrinsic::loongarch_lasx_xvshuf4i_d:
5383 case Intrinsic::loongarch_lasx_xvpermi_w:
5384 case Intrinsic::loongarch_lasx_xvpermi_q:
5385 case Intrinsic::loongarch_lasx_xvbitseli_b:
5386 case Intrinsic::loongarch_lasx_xvextrins_b:
5387 case Intrinsic::loongarch_lasx_xvextrins_h:
5388 case Intrinsic::loongarch_lasx_xvextrins_w:
5389 case Intrinsic::loongarch_lasx_xvextrins_d:
5390 return checkIntrinsicImmArg<8>(Op, 3, DAG);
5391 case Intrinsic::loongarch_lsx_vrepli_b:
5392 case Intrinsic::loongarch_lsx_vrepli_h:
5393 case Intrinsic::loongarch_lsx_vrepli_w:
5394 case Intrinsic::loongarch_lsx_vrepli_d:
5395 case Intrinsic::loongarch_lasx_xvrepli_b:
5396 case Intrinsic::loongarch_lasx_xvrepli_h:
5397 case Intrinsic::loongarch_lasx_xvrepli_w:
5398 case Intrinsic::loongarch_lasx_xvrepli_d:
5399 return checkIntrinsicImmArg<10>(Op, 1, DAG, /*IsSigned=*/true);
5400 case Intrinsic::loongarch_lsx_vldi:
5401 case Intrinsic::loongarch_lasx_xvldi:
5402 return checkIntrinsicImmArg<13>(Op, 1, DAG, /*IsSigned=*/true);
5403 }
5404}
5405
5406// Helper function that emits error message for intrinsics with chain and return
5407// merge values of a UNDEF and the chain.
5409 StringRef ErrorMsg,
5410 SelectionDAG &DAG) {
5411 DAG.getContext()->emitError(Op->getOperationName(0) + ": " + ErrorMsg + ".");
5412 return DAG.getMergeValues({DAG.getUNDEF(Op.getValueType()), Op.getOperand(0)},
5413 SDLoc(Op));
5414}
5415
5416SDValue
5417LoongArchTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5418 SelectionDAG &DAG) const {
5419 SDLoc DL(Op);
5420 MVT GRLenVT = Subtarget.getGRLenVT();
5421 EVT VT = Op.getValueType();
5422 SDValue Chain = Op.getOperand(0);
5423 const StringRef ErrorMsgOOR = "argument out of range";
5424 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
5425 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
5426
5427 switch (Op.getConstantOperandVal(1)) {
5428 default:
5429 return Op;
5430 case Intrinsic::loongarch_crc_w_b_w:
5431 case Intrinsic::loongarch_crc_w_h_w:
5432 case Intrinsic::loongarch_crc_w_w_w:
5433 case Intrinsic::loongarch_crc_w_d_w:
5434 case Intrinsic::loongarch_crcc_w_b_w:
5435 case Intrinsic::loongarch_crcc_w_h_w:
5436 case Intrinsic::loongarch_crcc_w_w_w:
5437 case Intrinsic::loongarch_crcc_w_d_w:
5438 return emitIntrinsicWithChainErrorMessage(Op, ErrorMsgReqLA64, DAG);
5439 case Intrinsic::loongarch_csrrd_w:
5440 case Intrinsic::loongarch_csrrd_d: {
5441 unsigned Imm = Op.getConstantOperandVal(2);
5442 return !isUInt<14>(Imm)
5443 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5444 : DAG.getNode(LoongArchISD::CSRRD, DL, {GRLenVT, MVT::Other},
5445 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
5446 }
5447 case Intrinsic::loongarch_csrwr_w:
5448 case Intrinsic::loongarch_csrwr_d: {
5449 unsigned Imm = Op.getConstantOperandVal(3);
5450 return !isUInt<14>(Imm)
5451 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5452 : DAG.getNode(LoongArchISD::CSRWR, DL, {GRLenVT, MVT::Other},
5453 {Chain, Op.getOperand(2),
5454 DAG.getConstant(Imm, DL, GRLenVT)});
5455 }
5456 case Intrinsic::loongarch_csrxchg_w:
5457 case Intrinsic::loongarch_csrxchg_d: {
5458 unsigned Imm = Op.getConstantOperandVal(4);
5459 return !isUInt<14>(Imm)
5460 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5461 : DAG.getNode(LoongArchISD::CSRXCHG, DL, {GRLenVT, MVT::Other},
5462 {Chain, Op.getOperand(2), Op.getOperand(3),
5463 DAG.getConstant(Imm, DL, GRLenVT)});
5464 }
5465 case Intrinsic::loongarch_iocsrrd_d: {
5466 return DAG.getNode(
5467 LoongArchISD::IOCSRRD_D, DL, {GRLenVT, MVT::Other},
5468 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op.getOperand(2))});
5469 }
5470#define IOCSRRD_CASE(NAME, NODE) \
5471 case Intrinsic::loongarch_##NAME: { \
5472 return DAG.getNode(LoongArchISD::NODE, DL, {GRLenVT, MVT::Other}, \
5473 {Chain, Op.getOperand(2)}); \
5474 }
5475 IOCSRRD_CASE(iocsrrd_b, IOCSRRD_B);
5476 IOCSRRD_CASE(iocsrrd_h, IOCSRRD_H);
5477 IOCSRRD_CASE(iocsrrd_w, IOCSRRD_W);
5478#undef IOCSRRD_CASE
5479 case Intrinsic::loongarch_cpucfg: {
5480 return DAG.getNode(LoongArchISD::CPUCFG, DL, {GRLenVT, MVT::Other},
5481 {Chain, Op.getOperand(2)});
5482 }
5483 case Intrinsic::loongarch_lddir_d: {
5484 unsigned Imm = Op.getConstantOperandVal(3);
5485 return !isUInt<8>(Imm)
5486 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5487 : Op;
5488 }
5489 case Intrinsic::loongarch_movfcsr2gr: {
5490 if (!Subtarget.hasBasicF())
5491 return emitIntrinsicWithChainErrorMessage(Op, ErrorMsgReqF, DAG);
5492 unsigned Imm = Op.getConstantOperandVal(2);
5493 return !isUInt<2>(Imm)
5494 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5495 : DAG.getNode(LoongArchISD::MOVFCSR2GR, DL, {VT, MVT::Other},
5496 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
5497 }
5498 case Intrinsic::loongarch_lsx_vld:
5499 case Intrinsic::loongarch_lsx_vldrepl_b:
5500 case Intrinsic::loongarch_lasx_xvld:
5501 case Intrinsic::loongarch_lasx_xvldrepl_b:
5502 return !isInt<12>(cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5503 ? emitIntrinsicWithChainErrorMessage(Op, ErrorMsgOOR, DAG)
5504 : SDValue();
5505 case Intrinsic::loongarch_lsx_vldrepl_h:
5506 case Intrinsic::loongarch_lasx_xvldrepl_h:
5507 return !isShiftedInt<11, 1>(
5508 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5510 Op, "argument out of range or not a multiple of 2", DAG)
5511 : SDValue();
5512 case Intrinsic::loongarch_lsx_vldrepl_w:
5513 case Intrinsic::loongarch_lasx_xvldrepl_w:
5514 return !isShiftedInt<10, 2>(
5515 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5517 Op, "argument out of range or not a multiple of 4", DAG)
5518 : SDValue();
5519 case Intrinsic::loongarch_lsx_vldrepl_d:
5520 case Intrinsic::loongarch_lasx_xvldrepl_d:
5521 return !isShiftedInt<9, 3>(
5522 cast<ConstantSDNode>(Op.getOperand(3))->getSExtValue())
5524 Op, "argument out of range or not a multiple of 8", DAG)
5525 : SDValue();
5526 }
5527}
5528
5529// Helper function that emits error message for intrinsics with void return
5530// value and return the chain.
5532 SelectionDAG &DAG) {
5533
5534 DAG.getContext()->emitError(Op->getOperationName(0) + ": " + ErrorMsg + ".");
5535 return Op.getOperand(0);
5536}
5537
5538SDValue LoongArchTargetLowering::lowerINTRINSIC_VOID(SDValue Op,
5539 SelectionDAG &DAG) const {
5540 SDLoc DL(Op);
5541 MVT GRLenVT = Subtarget.getGRLenVT();
5542 SDValue Chain = Op.getOperand(0);
5543 uint64_t IntrinsicEnum = Op.getConstantOperandVal(1);
5544 SDValue Op2 = Op.getOperand(2);
5545 const StringRef ErrorMsgOOR = "argument out of range";
5546 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
5547 const StringRef ErrorMsgReqLA32 = "requires loongarch32";
5548 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
5549
5550 switch (IntrinsicEnum) {
5551 default:
5552 // TODO: Add more Intrinsics.
5553 return SDValue();
5554 case Intrinsic::loongarch_cacop_d:
5555 case Intrinsic::loongarch_cacop_w: {
5556 if (IntrinsicEnum == Intrinsic::loongarch_cacop_d && !Subtarget.is64Bit())
5557 return emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG);
5558 if (IntrinsicEnum == Intrinsic::loongarch_cacop_w && Subtarget.is64Bit())
5559 return emitIntrinsicErrorMessage(Op, ErrorMsgReqLA32, DAG);
5560 // call void @llvm.loongarch.cacop.[d/w](uimm5, rj, simm12)
5561 unsigned Imm1 = Op2->getAsZExtVal();
5562 int Imm2 = cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue();
5563 if (!isUInt<5>(Imm1) || !isInt<12>(Imm2))
5564 return emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG);
5565 return Op;
5566 }
5567 case Intrinsic::loongarch_dbar: {
5568 unsigned Imm = Op2->getAsZExtVal();
5569 return !isUInt<15>(Imm)
5570 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5571 : DAG.getNode(LoongArchISD::DBAR, DL, MVT::Other, Chain,
5572 DAG.getConstant(Imm, DL, GRLenVT));
5573 }
5574 case Intrinsic::loongarch_ibar: {
5575 unsigned Imm = Op2->getAsZExtVal();
5576 return !isUInt<15>(Imm)
5577 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5578 : DAG.getNode(LoongArchISD::IBAR, DL, MVT::Other, Chain,
5579 DAG.getConstant(Imm, DL, GRLenVT));
5580 }
5581 case Intrinsic::loongarch_break: {
5582 unsigned Imm = Op2->getAsZExtVal();
5583 return !isUInt<15>(Imm)
5584 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5585 : DAG.getNode(LoongArchISD::BREAK, DL, MVT::Other, Chain,
5586 DAG.getConstant(Imm, DL, GRLenVT));
5587 }
5588 case Intrinsic::loongarch_movgr2fcsr: {
5589 if (!Subtarget.hasBasicF())
5590 return emitIntrinsicErrorMessage(Op, ErrorMsgReqF, DAG);
5591 unsigned Imm = Op2->getAsZExtVal();
5592 return !isUInt<2>(Imm)
5593 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5594 : DAG.getNode(LoongArchISD::MOVGR2FCSR, DL, MVT::Other, Chain,
5595 DAG.getConstant(Imm, DL, GRLenVT),
5596 DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT,
5597 Op.getOperand(3)));
5598 }
5599 case Intrinsic::loongarch_syscall: {
5600 unsigned Imm = Op2->getAsZExtVal();
5601 return !isUInt<15>(Imm)
5602 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5603 : DAG.getNode(LoongArchISD::SYSCALL, DL, MVT::Other, Chain,
5604 DAG.getConstant(Imm, DL, GRLenVT));
5605 }
5606#define IOCSRWR_CASE(NAME, NODE) \
5607 case Intrinsic::loongarch_##NAME: { \
5608 SDValue Op3 = Op.getOperand(3); \
5609 return Subtarget.is64Bit() \
5610 ? DAG.getNode(LoongArchISD::NODE, DL, MVT::Other, Chain, \
5611 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2), \
5612 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op3)) \
5613 : DAG.getNode(LoongArchISD::NODE, DL, MVT::Other, Chain, Op2, \
5614 Op3); \
5615 }
5616 IOCSRWR_CASE(iocsrwr_b, IOCSRWR_B);
5617 IOCSRWR_CASE(iocsrwr_h, IOCSRWR_H);
5618 IOCSRWR_CASE(iocsrwr_w, IOCSRWR_W);
5619#undef IOCSRWR_CASE
5620 case Intrinsic::loongarch_iocsrwr_d: {
5621 return !Subtarget.is64Bit()
5622 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG)
5623 : DAG.getNode(LoongArchISD::IOCSRWR_D, DL, MVT::Other, Chain,
5624 Op2,
5625 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
5626 Op.getOperand(3)));
5627 }
5628#define ASRT_LE_GT_CASE(NAME) \
5629 case Intrinsic::loongarch_##NAME: { \
5630 return !Subtarget.is64Bit() \
5631 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG) \
5632 : Op; \
5633 }
5634 ASRT_LE_GT_CASE(asrtle_d)
5635 ASRT_LE_GT_CASE(asrtgt_d)
5636#undef ASRT_LE_GT_CASE
5637 case Intrinsic::loongarch_ldpte_d: {
5638 unsigned Imm = Op.getConstantOperandVal(3);
5639 return !Subtarget.is64Bit()
5640 ? emitIntrinsicErrorMessage(Op, ErrorMsgReqLA64, DAG)
5641 : !isUInt<8>(Imm) ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5642 : Op;
5643 }
5644 case Intrinsic::loongarch_lsx_vst:
5645 case Intrinsic::loongarch_lasx_xvst:
5646 return !isInt<12>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue())
5647 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5648 : SDValue();
5649 case Intrinsic::loongarch_lasx_xvstelm_b:
5650 return (!isInt<8>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5651 !isUInt<5>(Op.getConstantOperandVal(5)))
5652 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5653 : SDValue();
5654 case Intrinsic::loongarch_lsx_vstelm_b:
5655 return (!isInt<8>(cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5656 !isUInt<4>(Op.getConstantOperandVal(5)))
5657 ? emitIntrinsicErrorMessage(Op, ErrorMsgOOR, DAG)
5658 : SDValue();
5659 case Intrinsic::loongarch_lasx_xvstelm_h:
5660 return (!isShiftedInt<8, 1>(
5661 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5662 !isUInt<4>(Op.getConstantOperandVal(5)))
5664 Op, "argument out of range or not a multiple of 2", DAG)
5665 : SDValue();
5666 case Intrinsic::loongarch_lsx_vstelm_h:
5667 return (!isShiftedInt<8, 1>(
5668 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5669 !isUInt<3>(Op.getConstantOperandVal(5)))
5671 Op, "argument out of range or not a multiple of 2", DAG)
5672 : SDValue();
5673 case Intrinsic::loongarch_lasx_xvstelm_w:
5674 return (!isShiftedInt<8, 2>(
5675 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5676 !isUInt<3>(Op.getConstantOperandVal(5)))
5678 Op, "argument out of range or not a multiple of 4", DAG)
5679 : SDValue();
5680 case Intrinsic::loongarch_lsx_vstelm_w:
5681 return (!isShiftedInt<8, 2>(
5682 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5683 !isUInt<2>(Op.getConstantOperandVal(5)))
5685 Op, "argument out of range or not a multiple of 4", DAG)
5686 : SDValue();
5687 case Intrinsic::loongarch_lasx_xvstelm_d:
5688 return (!isShiftedInt<8, 3>(
5689 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5690 !isUInt<2>(Op.getConstantOperandVal(5)))
5692 Op, "argument out of range or not a multiple of 8", DAG)
5693 : SDValue();
5694 case Intrinsic::loongarch_lsx_vstelm_d:
5695 return (!isShiftedInt<8, 3>(
5696 cast<ConstantSDNode>(Op.getOperand(4))->getSExtValue()) ||
5697 !isUInt<1>(Op.getConstantOperandVal(5)))
5699 Op, "argument out of range or not a multiple of 8", DAG)
5700 : SDValue();
5701 }
5702}
5703
5704SDValue LoongArchTargetLowering::lowerShiftLeftParts(SDValue Op,
5705 SelectionDAG &DAG) const {
5706 SDLoc DL(Op);
5707 SDValue Lo = Op.getOperand(0);
5708 SDValue Hi = Op.getOperand(1);
5709 SDValue Shamt = Op.getOperand(2);
5710 EVT VT = Lo.getValueType();
5711
5712 // if Shamt-GRLen < 0: // Shamt < GRLen
5713 // Lo = Lo << Shamt
5714 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (GRLen-1 ^ Shamt))
5715 // else:
5716 // Lo = 0
5717 // Hi = Lo << (Shamt-GRLen)
5718
5719 SDValue Zero = DAG.getConstant(0, DL, VT);
5720 SDValue One = DAG.getConstant(1, DL, VT);
5721 SDValue MinusGRLen =
5722 DAG.getSignedConstant(-(int)Subtarget.getGRLen(), DL, VT);
5723 SDValue GRLenMinus1 = DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT);
5724 SDValue ShamtMinusGRLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusGRLen);
5725 SDValue GRLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, GRLenMinus1);
5726
5727 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
5728 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
5729 SDValue ShiftRightLo =
5730 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, GRLenMinus1Shamt);
5731 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
5732 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
5733 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusGRLen);
5734
5735 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusGRLen, Zero, ISD::SETLT);
5736
5737 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
5738 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
5739
5740 SDValue Parts[2] = {Lo, Hi};
5741 return DAG.getMergeValues(Parts, DL);
5742}
5743
5744SDValue LoongArchTargetLowering::lowerShiftRightParts(SDValue Op,
5745 SelectionDAG &DAG,
5746 bool IsSRA) const {
5747 SDLoc DL(Op);
5748 SDValue Lo = Op.getOperand(0);
5749 SDValue Hi = Op.getOperand(1);
5750 SDValue Shamt = Op.getOperand(2);
5751 EVT VT = Lo.getValueType();
5752
5753 // SRA expansion:
5754 // if Shamt-GRLen < 0: // Shamt < GRLen
5755 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ GRLen-1))
5756 // Hi = Hi >>s Shamt
5757 // else:
5758 // Lo = Hi >>s (Shamt-GRLen);
5759 // Hi = Hi >>s (GRLen-1)
5760 //
5761 // SRL expansion:
5762 // if Shamt-GRLen < 0: // Shamt < GRLen
5763 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ GRLen-1))
5764 // Hi = Hi >>u Shamt
5765 // else:
5766 // Lo = Hi >>u (Shamt-GRLen);
5767 // Hi = 0;
5768
5769 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
5770
5771 SDValue Zero = DAG.getConstant(0, DL, VT);
5772 SDValue One = DAG.getConstant(1, DL, VT);
5773 SDValue MinusGRLen =
5774 DAG.getSignedConstant(-(int)Subtarget.getGRLen(), DL, VT);
5775 SDValue GRLenMinus1 = DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT);
5776 SDValue ShamtMinusGRLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusGRLen);
5777 SDValue GRLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, GRLenMinus1);
5778
5779 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
5780 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
5781 SDValue ShiftLeftHi =
5782 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, GRLenMinus1Shamt);
5783 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
5784 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
5785 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusGRLen);
5786 SDValue HiFalse =
5787 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, GRLenMinus1) : Zero;
5788
5789 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusGRLen, Zero, ISD::SETLT);
5790
5791 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
5792 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
5793
5794 SDValue Parts[2] = {Lo, Hi};
5795 return DAG.getMergeValues(Parts, DL);
5796}
5797
5798// Returns the opcode of the target-specific SDNode that implements the 32-bit
5799// form of the given Opcode.
5800static unsigned getLoongArchWOpcode(unsigned Opcode) {
5801 switch (Opcode) {
5802 default:
5803 llvm_unreachable("Unexpected opcode");
5804 case ISD::SDIV:
5805 return LoongArchISD::DIV_W;
5806 case ISD::UDIV:
5807 return LoongArchISD::DIV_WU;
5808 case ISD::SREM:
5809 return LoongArchISD::MOD_W;
5810 case ISD::UREM:
5811 return LoongArchISD::MOD_WU;
5812 case ISD::SHL:
5813 return LoongArchISD::SLL_W;
5814 case ISD::SRA:
5815 return LoongArchISD::SRA_W;
5816 case ISD::SRL:
5817 return LoongArchISD::SRL_W;
5818 case ISD::ROTL:
5819 case ISD::ROTR:
5820 return LoongArchISD::ROTR_W;
5821 case ISD::CTTZ:
5822 return LoongArchISD::CTZ_W;
5823 case ISD::CTLZ:
5824 return LoongArchISD::CLZ_W;
5825 }
5826}
5827
5828// Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5829// node. Because i8/i16/i32 isn't a legal type for LA64, these operations would
5830// otherwise be promoted to i64, making it difficult to select the
5831// SLL_W/.../*W later one because the fact the operation was originally of
5832// type i8/i16/i32 is lost.
5834 unsigned ExtOpc = ISD::ANY_EXTEND) {
5835 SDLoc DL(N);
5836 unsigned WOpcode = getLoongArchWOpcode(N->getOpcode());
5837 SDValue NewOp0, NewRes;
5838
5839 switch (NumOp) {
5840 default:
5841 llvm_unreachable("Unexpected NumOp");
5842 case 1: {
5843 NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5844 NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0);
5845 break;
5846 }
5847 case 2: {
5848 NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5849 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5850 if (N->getOpcode() == ISD::ROTL) {
5851 SDValue TmpOp = DAG.getConstant(32, DL, MVT::i64);
5852 NewOp1 = DAG.getNode(ISD::SUB, DL, MVT::i64, TmpOp, NewOp1);
5853 }
5854 NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5855 break;
5856 }
5857 // TODO:Handle more NumOp.
5858 }
5859
5860 // ReplaceNodeResults requires we maintain the same type for the return
5861 // value.
5862 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5863}
5864
5865// Converts the given 32-bit operation to a i64 operation with signed extension
5866// semantic to reduce the signed extension instructions.
5868 SDLoc DL(N);
5869 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5870 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5871 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5872 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5873 DAG.getValueType(MVT::i32));
5874 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5875}
5876
5877// Helper function that emits error message for intrinsics with/without chain
5878// and return a UNDEF or and the chain as the results.
5881 StringRef ErrorMsg, bool WithChain = true) {
5882 DAG.getContext()->emitError(N->getOperationName(0) + ": " + ErrorMsg + ".");
5883 Results.push_back(DAG.getUNDEF(N->getValueType(0)));
5884 if (!WithChain)
5885 return;
5886 Results.push_back(N->getOperand(0));
5887}
5888
5889template <unsigned N>
5890static void
5893 unsigned ResOp) {
5894 const StringRef ErrorMsgOOR = "argument out of range";
5895 unsigned Imm = Node->getConstantOperandVal(2);
5896 if (!isUInt<N>(Imm)) {
5898 /*WithChain=*/false);
5899 return;
5900 }
5901 SDLoc DL(Node);
5902 SDValue Vec = Node->getOperand(1);
5903
5904 SDValue PickElt =
5905 DAG.getNode(ResOp, DL, Subtarget.getGRLenVT(), Vec,
5906 DAG.getConstant(Imm, DL, Subtarget.getGRLenVT()),
5908 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, Node->getValueType(0),
5909 PickElt.getValue(0)));
5910}
5911
5914 SelectionDAG &DAG,
5916 unsigned ResOp) {
5917 SDLoc DL(N);
5918 SDValue Vec = N->getOperand(1);
5919
5920 SDValue CB = DAG.getNode(ResOp, DL, Subtarget.getGRLenVT(), Vec);
5921 Results.push_back(
5922 DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), CB.getValue(0)));
5923}
5924
5925static void
5927 SelectionDAG &DAG,
5929 switch (N->getConstantOperandVal(0)) {
5930 default:
5931 llvm_unreachable("Unexpected Intrinsic.");
5932 case Intrinsic::loongarch_lsx_vpickve2gr_b:
5934 LoongArchISD::VPICK_SEXT_ELT);
5935 break;
5936 case Intrinsic::loongarch_lsx_vpickve2gr_h:
5937 case Intrinsic::loongarch_lasx_xvpickve2gr_w:
5939 LoongArchISD::VPICK_SEXT_ELT);
5940 break;
5941 case Intrinsic::loongarch_lsx_vpickve2gr_w:
5943 LoongArchISD::VPICK_SEXT_ELT);
5944 break;
5945 case Intrinsic::loongarch_lsx_vpickve2gr_bu:
5947 LoongArchISD::VPICK_ZEXT_ELT);
5948 break;
5949 case Intrinsic::loongarch_lsx_vpickve2gr_hu:
5950 case Intrinsic::loongarch_lasx_xvpickve2gr_wu:
5952 LoongArchISD::VPICK_ZEXT_ELT);
5953 break;
5954 case Intrinsic::loongarch_lsx_vpickve2gr_wu:
5956 LoongArchISD::VPICK_ZEXT_ELT);
5957 break;
5958 case Intrinsic::loongarch_lsx_bz_b:
5959 case Intrinsic::loongarch_lsx_bz_h:
5960 case Intrinsic::loongarch_lsx_bz_w:
5961 case Intrinsic::loongarch_lsx_bz_d:
5962 case Intrinsic::loongarch_lasx_xbz_b:
5963 case Intrinsic::loongarch_lasx_xbz_h:
5964 case Intrinsic::loongarch_lasx_xbz_w:
5965 case Intrinsic::loongarch_lasx_xbz_d:
5967 LoongArchISD::VALL_ZERO);
5968 break;
5969 case Intrinsic::loongarch_lsx_bz_v:
5970 case Intrinsic::loongarch_lasx_xbz_v:
5972 LoongArchISD::VANY_ZERO);
5973 break;
5974 case Intrinsic::loongarch_lsx_bnz_b:
5975 case Intrinsic::loongarch_lsx_bnz_h:
5976 case Intrinsic::loongarch_lsx_bnz_w:
5977 case Intrinsic::loongarch_lsx_bnz_d:
5978 case Intrinsic::loongarch_lasx_xbnz_b:
5979 case Intrinsic::loongarch_lasx_xbnz_h:
5980 case Intrinsic::loongarch_lasx_xbnz_w:
5981 case Intrinsic::loongarch_lasx_xbnz_d:
5983 LoongArchISD::VALL_NONZERO);
5984 break;
5985 case Intrinsic::loongarch_lsx_bnz_v:
5986 case Intrinsic::loongarch_lasx_xbnz_v:
5988 LoongArchISD::VANY_NONZERO);
5989 break;
5990 }
5991}
5992
5995 SelectionDAG &DAG) {
5996 assert(N->getValueType(0) == MVT::i128 &&
5997 "AtomicCmpSwap on types less than 128 should be legal");
5998 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
5999
6000 unsigned Opcode;
6001 switch (MemOp->getMergedOrdering()) {
6005 Opcode = LoongArch::PseudoCmpXchg128Acquire;
6006 break;
6009 Opcode = LoongArch::PseudoCmpXchg128;
6010 break;
6011 default:
6012 llvm_unreachable("Unexpected ordering!");
6013 }
6014
6015 SDLoc DL(N);
6016 auto CmpVal = DAG.SplitScalar(N->getOperand(2), DL, MVT::i64, MVT::i64);
6017 auto NewVal = DAG.SplitScalar(N->getOperand(3), DL, MVT::i64, MVT::i64);
6018 SDValue Ops[] = {N->getOperand(1), CmpVal.first, CmpVal.second,
6019 NewVal.first, NewVal.second, N->getOperand(0)};
6020
6021 SDNode *CmpSwap = DAG.getMachineNode(
6022 Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i64, MVT::Other),
6023 Ops);
6024 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
6025 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128,
6026 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
6027 Results.push_back(SDValue(CmpSwap, 3));
6028}
6029
6032 SDLoc DL(N);
6033 EVT VT = N->getValueType(0);
6034 switch (N->getOpcode()) {
6035 default:
6036 llvm_unreachable("Don't know how to legalize this operation");
6037 case ISD::ADD:
6038 case ISD::SUB:
6039 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6040 "Unexpected custom legalisation");
6041 Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6042 break;
6043 case ISD::SDIV:
6044 case ISD::UDIV:
6045 case ISD::SREM:
6046 case ISD::UREM:
6047 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6048 "Unexpected custom legalisation");
6049 Results.push_back(customLegalizeToWOp(N, DAG, 2,
6050 Subtarget.hasDiv32() && VT == MVT::i32
6052 : ISD::SIGN_EXTEND));
6053 break;
6054 case ISD::SHL:
6055 case ISD::SRA:
6056 case ISD::SRL:
6057 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6058 "Unexpected custom legalisation");
6059 if (N->getOperand(1).getOpcode() != ISD::Constant) {
6060 Results.push_back(customLegalizeToWOp(N, DAG, 2));
6061 break;
6062 }
6063 break;
6064 case ISD::ROTL:
6065 case ISD::ROTR:
6066 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6067 "Unexpected custom legalisation");
6068 Results.push_back(customLegalizeToWOp(N, DAG, 2));
6069 break;
6070 case ISD::LOAD: {
6071 // Use an f64 load and a scalar_to_vector for v2f32 loads. This avoids
6072 // scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
6073 // cast since type legalization will try to use an i64 load.
6074 MVT VT = N->getSimpleValueType(0);
6075 assert(VT == MVT::v2f32 && Subtarget.hasExtLSX() &&
6076 "Unexpected custom legalisation");
6078 "Unexpected type action!");
6079 if (!ISD::isNON_EXTLoad(N))
6080 return;
6081 auto *Ld = cast<LoadSDNode>(N);
6082 SDValue Res = DAG.getLoad(MVT::f64, DL, Ld->getChain(), Ld->getBasePtr(),
6083 Ld->getPointerInfo(), Ld->getBaseAlign(),
6084 Ld->getMemOperand()->getFlags());
6085 SDValue Chain = Res.getValue(1);
6086 MVT VecVT = MVT::getVectorVT(MVT::f64, 2);
6087 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Res);
6088 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
6089 Res = DAG.getBitcast(WideVT, Res);
6090 Results.push_back(Res);
6091 Results.push_back(Chain);
6092 break;
6093 }
6094 case ISD::FP_TO_SINT: {
6095 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6096 "Unexpected custom legalisation");
6097 SDValue Src = N->getOperand(0);
6098 EVT FVT = EVT::getFloatingPointVT(N->getValueSizeInBits(0));
6099 if (getTypeAction(*DAG.getContext(), Src.getValueType()) !=
6101 if (!isTypeLegal(Src.getValueType()))
6102 return;
6103 if (Src.getValueType() == MVT::f16)
6104 Src = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
6105 SDValue Dst = DAG.getNode(LoongArchISD::FTINT, DL, FVT, Src);
6106 Results.push_back(DAG.getNode(ISD::BITCAST, DL, VT, Dst));
6107 return;
6108 }
6109 // If the FP type needs to be softened, emit a library call using the 'si'
6110 // version. If we left it to default legalization we'd end up with 'di'.
6111 RTLIB::Libcall LC;
6112 LC = RTLIB::getFPTOSINT(Src.getValueType(), VT);
6113 MakeLibCallOptions CallOptions;
6114 EVT OpVT = Src.getValueType();
6115 CallOptions.setTypeListBeforeSoften(OpVT, VT);
6116 SDValue Chain = SDValue();
6117 SDValue Result;
6118 std::tie(Result, Chain) =
6119 makeLibCall(DAG, LC, VT, Src, CallOptions, DL, Chain);
6120 Results.push_back(Result);
6121 break;
6122 }
6123 case ISD::BITCAST: {
6124 SDValue Src = N->getOperand(0);
6125 EVT SrcVT = Src.getValueType();
6126 if (VT == MVT::i32 && SrcVT == MVT::f32 && Subtarget.is64Bit() &&
6127 Subtarget.hasBasicF()) {
6128 SDValue Dst =
6129 DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Src);
6130 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Dst));
6131 } else if (VT == MVT::i64 && SrcVT == MVT::f64 && !Subtarget.is64Bit()) {
6132 SDValue NewReg = DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
6133 DAG.getVTList(MVT::i32, MVT::i32), Src);
6134 SDValue RetReg = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6135 NewReg.getValue(0), NewReg.getValue(1));
6136 Results.push_back(RetReg);
6137 }
6138 break;
6139 }
6140 case ISD::FP_TO_UINT: {
6141 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6142 "Unexpected custom legalisation");
6143 auto &TLI = DAG.getTargetLoweringInfo();
6144 SDValue Tmp1, Tmp2;
6145 TLI.expandFP_TO_UINT(N, Tmp1, Tmp2, DAG);
6146 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Tmp1));
6147 break;
6148 }
6149 case ISD::FP_ROUND: {
6150 assert(VT == MVT::v2f32 && Subtarget.hasExtLSX() &&
6151 "Unexpected custom legalisation");
6152 // On LSX platforms, rounding from v2f64 to v4f32 (after legalization from
6153 // v2f32) is scalarized. Add a customized v2f32 widening to convert it into
6154 // a target-specific LoongArchISD::VFCVT to optimize it.
6155 SDValue Op0 = N->getOperand(0);
6156 EVT OpVT = Op0.getValueType();
6157 if (OpVT == MVT::v2f64) {
6158 SDValue Undef = DAG.getUNDEF(OpVT);
6159 SDValue Dst =
6160 DAG.getNode(LoongArchISD::VFCVT, DL, MVT::v4f32, Undef, Op0);
6161 Results.push_back(Dst);
6162 }
6163 break;
6164 }
6165 case ISD::BSWAP: {
6166 SDValue Src = N->getOperand(0);
6167 assert((VT == MVT::i16 || VT == MVT::i32) &&
6168 "Unexpected custom legalization");
6169 MVT GRLenVT = Subtarget.getGRLenVT();
6170 SDValue NewSrc = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, Src);
6171 SDValue Tmp;
6172 switch (VT.getSizeInBits()) {
6173 default:
6174 llvm_unreachable("Unexpected operand width");
6175 case 16:
6176 Tmp = DAG.getNode(LoongArchISD::REVB_2H, DL, GRLenVT, NewSrc);
6177 break;
6178 case 32:
6179 // Only LA64 will get to here due to the size mismatch between VT and
6180 // GRLenVT, LA32 lowering is directly defined in LoongArchInstrInfo.
6181 Tmp = DAG.getNode(LoongArchISD::REVB_2W, DL, GRLenVT, NewSrc);
6182 break;
6183 }
6184 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Tmp));
6185 break;
6186 }
6187 case ISD::BITREVERSE: {
6188 SDValue Src = N->getOperand(0);
6189 assert((VT == MVT::i8 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6190 "Unexpected custom legalization");
6191 MVT GRLenVT = Subtarget.getGRLenVT();
6192 SDValue NewSrc = DAG.getNode(ISD::ANY_EXTEND, DL, GRLenVT, Src);
6193 SDValue Tmp;
6194 switch (VT.getSizeInBits()) {
6195 default:
6196 llvm_unreachable("Unexpected operand width");
6197 case 8:
6198 Tmp = DAG.getNode(LoongArchISD::BITREV_4B, DL, GRLenVT, NewSrc);
6199 break;
6200 case 32:
6201 Tmp = DAG.getNode(LoongArchISD::BITREV_W, DL, GRLenVT, NewSrc);
6202 break;
6203 }
6204 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Tmp));
6205 break;
6206 }
6207 case ISD::CTLZ:
6208 case ISD::CTTZ: {
6209 assert(VT == MVT::i32 && Subtarget.is64Bit() &&
6210 "Unexpected custom legalisation");
6211 Results.push_back(customLegalizeToWOp(N, DAG, 1));
6212 break;
6213 }
6215 SDValue Chain = N->getOperand(0);
6216 SDValue Op2 = N->getOperand(2);
6217 MVT GRLenVT = Subtarget.getGRLenVT();
6218 const StringRef ErrorMsgOOR = "argument out of range";
6219 const StringRef ErrorMsgReqLA64 = "requires loongarch64";
6220 const StringRef ErrorMsgReqF = "requires basic 'f' target feature";
6221
6222 switch (N->getConstantOperandVal(1)) {
6223 default:
6224 llvm_unreachable("Unexpected Intrinsic.");
6225 case Intrinsic::loongarch_movfcsr2gr: {
6226 if (!Subtarget.hasBasicF()) {
6227 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqF);
6228 return;
6229 }
6230 unsigned Imm = Op2->getAsZExtVal();
6231 if (!isUInt<2>(Imm)) {
6232 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6233 return;
6234 }
6235 SDValue MOVFCSR2GRResults = DAG.getNode(
6236 LoongArchISD::MOVFCSR2GR, SDLoc(N), {MVT::i64, MVT::Other},
6237 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
6238 Results.push_back(
6239 DAG.getNode(ISD::TRUNCATE, DL, VT, MOVFCSR2GRResults.getValue(0)));
6240 Results.push_back(MOVFCSR2GRResults.getValue(1));
6241 break;
6242 }
6243#define CRC_CASE_EXT_BINARYOP(NAME, NODE) \
6244 case Intrinsic::loongarch_##NAME: { \
6245 SDValue NODE = DAG.getNode( \
6246 LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6247 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2), \
6248 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3))}); \
6249 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NODE.getValue(0))); \
6250 Results.push_back(NODE.getValue(1)); \
6251 break; \
6252 }
6253 CRC_CASE_EXT_BINARYOP(crc_w_b_w, CRC_W_B_W)
6254 CRC_CASE_EXT_BINARYOP(crc_w_h_w, CRC_W_H_W)
6255 CRC_CASE_EXT_BINARYOP(crc_w_w_w, CRC_W_W_W)
6256 CRC_CASE_EXT_BINARYOP(crcc_w_b_w, CRCC_W_B_W)
6257 CRC_CASE_EXT_BINARYOP(crcc_w_h_w, CRCC_W_H_W)
6258 CRC_CASE_EXT_BINARYOP(crcc_w_w_w, CRCC_W_W_W)
6259#undef CRC_CASE_EXT_BINARYOP
6260
6261#define CRC_CASE_EXT_UNARYOP(NAME, NODE) \
6262 case Intrinsic::loongarch_##NAME: { \
6263 SDValue NODE = DAG.getNode( \
6264 LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6265 {Chain, Op2, \
6266 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3))}); \
6267 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NODE.getValue(0))); \
6268 Results.push_back(NODE.getValue(1)); \
6269 break; \
6270 }
6271 CRC_CASE_EXT_UNARYOP(crc_w_d_w, CRC_W_D_W)
6272 CRC_CASE_EXT_UNARYOP(crcc_w_d_w, CRCC_W_D_W)
6273#undef CRC_CASE_EXT_UNARYOP
6274#define CSR_CASE(ID) \
6275 case Intrinsic::loongarch_##ID: { \
6276 if (!Subtarget.is64Bit()) \
6277 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqLA64); \
6278 break; \
6279 }
6280 CSR_CASE(csrrd_d);
6281 CSR_CASE(csrwr_d);
6282 CSR_CASE(csrxchg_d);
6283 CSR_CASE(iocsrrd_d);
6284#undef CSR_CASE
6285 case Intrinsic::loongarch_csrrd_w: {
6286 unsigned Imm = Op2->getAsZExtVal();
6287 if (!isUInt<14>(Imm)) {
6288 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6289 return;
6290 }
6291 SDValue CSRRDResults =
6292 DAG.getNode(LoongArchISD::CSRRD, DL, {GRLenVT, MVT::Other},
6293 {Chain, DAG.getConstant(Imm, DL, GRLenVT)});
6294 Results.push_back(
6295 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRRDResults.getValue(0)));
6296 Results.push_back(CSRRDResults.getValue(1));
6297 break;
6298 }
6299 case Intrinsic::loongarch_csrwr_w: {
6300 unsigned Imm = N->getConstantOperandVal(3);
6301 if (!isUInt<14>(Imm)) {
6302 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6303 return;
6304 }
6305 SDValue CSRWRResults =
6306 DAG.getNode(LoongArchISD::CSRWR, DL, {GRLenVT, MVT::Other},
6307 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2),
6308 DAG.getConstant(Imm, DL, GRLenVT)});
6309 Results.push_back(
6310 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRWRResults.getValue(0)));
6311 Results.push_back(CSRWRResults.getValue(1));
6312 break;
6313 }
6314 case Intrinsic::loongarch_csrxchg_w: {
6315 unsigned Imm = N->getConstantOperandVal(4);
6316 if (!isUInt<14>(Imm)) {
6317 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgOOR);
6318 return;
6319 }
6320 SDValue CSRXCHGResults = DAG.getNode(
6321 LoongArchISD::CSRXCHG, DL, {GRLenVT, MVT::Other},
6322 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2),
6323 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)),
6324 DAG.getConstant(Imm, DL, GRLenVT)});
6325 Results.push_back(
6326 DAG.getNode(ISD::TRUNCATE, DL, VT, CSRXCHGResults.getValue(0)));
6327 Results.push_back(CSRXCHGResults.getValue(1));
6328 break;
6329 }
6330#define IOCSRRD_CASE(NAME, NODE) \
6331 case Intrinsic::loongarch_##NAME: { \
6332 SDValue IOCSRRDResults = \
6333 DAG.getNode(LoongArchISD::NODE, DL, {MVT::i64, MVT::Other}, \
6334 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2)}); \
6335 Results.push_back( \
6336 DAG.getNode(ISD::TRUNCATE, DL, VT, IOCSRRDResults.getValue(0))); \
6337 Results.push_back(IOCSRRDResults.getValue(1)); \
6338 break; \
6339 }
6340 IOCSRRD_CASE(iocsrrd_b, IOCSRRD_B);
6341 IOCSRRD_CASE(iocsrrd_h, IOCSRRD_H);
6342 IOCSRRD_CASE(iocsrrd_w, IOCSRRD_W);
6343#undef IOCSRRD_CASE
6344 case Intrinsic::loongarch_cpucfg: {
6345 SDValue CPUCFGResults =
6346 DAG.getNode(LoongArchISD::CPUCFG, DL, {GRLenVT, MVT::Other},
6347 {Chain, DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op2)});
6348 Results.push_back(
6349 DAG.getNode(ISD::TRUNCATE, DL, VT, CPUCFGResults.getValue(0)));
6350 Results.push_back(CPUCFGResults.getValue(1));
6351 break;
6352 }
6353 case Intrinsic::loongarch_lddir_d: {
6354 if (!Subtarget.is64Bit()) {
6355 emitErrorAndReplaceIntrinsicResults(N, Results, DAG, ErrorMsgReqLA64);
6356 return;
6357 }
6358 break;
6359 }
6360 }
6361 break;
6362 }
6363 case ISD::READ_REGISTER: {
6364 if (Subtarget.is64Bit())
6365 DAG.getContext()->emitError(
6366 "On LA64, only 64-bit registers can be read.");
6367 else
6368 DAG.getContext()->emitError(
6369 "On LA32, only 32-bit registers can be read.");
6370 Results.push_back(DAG.getUNDEF(VT));
6371 Results.push_back(N->getOperand(0));
6372 break;
6373 }
6375 replaceINTRINSIC_WO_CHAINResults(N, Results, DAG, Subtarget);
6376 break;
6377 }
6378 case ISD::LROUND: {
6379 SDValue Op0 = N->getOperand(0);
6380 EVT OpVT = Op0.getValueType();
6381 RTLIB::Libcall LC =
6382 OpVT == MVT::f64 ? RTLIB::LROUND_F64 : RTLIB::LROUND_F32;
6383 MakeLibCallOptions CallOptions;
6384 CallOptions.setTypeListBeforeSoften(OpVT, MVT::i64);
6385 SDValue Result = makeLibCall(DAG, LC, MVT::i64, Op0, CallOptions, DL).first;
6386 Result = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Result);
6387 Results.push_back(Result);
6388 break;
6389 }
6390 case ISD::ATOMIC_CMP_SWAP: {
6392 break;
6393 }
6394 case ISD::TRUNCATE: {
6395 MVT VT = N->getSimpleValueType(0);
6396 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
6397 return;
6398
6399 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
6400 SDValue In = N->getOperand(0);
6401 EVT InVT = In.getValueType();
6402 EVT InEltVT = InVT.getVectorElementType();
6403 EVT EltVT = VT.getVectorElementType();
6404 unsigned MinElts = VT.getVectorNumElements();
6405 unsigned WidenNumElts = WidenVT.getVectorNumElements();
6406 unsigned InBits = InVT.getSizeInBits();
6407
6408 // v8i64 -> (v8i32) -> v8i8
6409 if (InVT == MVT::v8i64 && WidenVT.is128BitVector()) {
6410 InVT = MVT::getVectorVT(MVT::getIntegerVT(256 / MinElts), MinElts);
6411 In = DAG.getNode(N->getOpcode(), DL, InVT, In);
6412 InBits = 256;
6413 }
6414
6415 // v8i32 -> v8i8 / v4i64 -> v4i16 / v4i64 -> v4i8
6416 if ((InVT == MVT::v8i32 || InVT == MVT::v4i64) &&
6417 WidenVT.is128BitVector()) {
6418 InVT = MVT::getVectorVT(MVT::getIntegerVT(128 / MinElts), MinElts);
6419 In = DAG.getNode(N->getOpcode(), DL, InVT, In);
6420 InBits = 128;
6421 InEltVT = InVT.getVectorElementType();
6422 }
6423
6424 if ((128 % InBits) == 0 && WidenVT.is128BitVector()) {
6425 if ((InEltVT.getSizeInBits() % EltVT.getSizeInBits()) == 0) {
6426 int Scale = InEltVT.getSizeInBits() / EltVT.getSizeInBits();
6427 SmallVector<int, 16> TruncMask(WidenNumElts, -1);
6428 for (unsigned I = 0; I < MinElts; ++I)
6429 TruncMask[I] = Scale * I;
6430
6431 unsigned WidenNumElts = 128 / In.getScalarValueSizeInBits();
6432 MVT SVT = In.getSimpleValueType().getScalarType();
6433 MVT VT = MVT::getVectorVT(SVT, WidenNumElts);
6434 SDValue WidenIn =
6435 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), In,
6436 DAG.getVectorIdxConstant(0, DL));
6437 assert(isTypeLegal(WidenVT) && isTypeLegal(WidenIn.getValueType()) &&
6438 "Illegal vector type in truncation");
6439 WidenIn = DAG.getBitcast(WidenVT, WidenIn);
6440 Results.push_back(
6441 DAG.getVectorShuffle(WidenVT, DL, WidenIn, WidenIn, TruncMask));
6442 return;
6443 }
6444 }
6445
6446 break;
6447 }
6448 case ISD::SIGN_EXTEND: {
6449 // LASX has native VEXT2XV_* for sign extension.
6450 if (!Subtarget.hasExtLSX() || Subtarget.hasExtLASX())
6451 return;
6452
6453 EVT DstVT = N->getValueType(0);
6454 SDValue Src = N->getOperand(0);
6455
6456 // The VSLTI + VILVL/VILVH expansion below only supports simple vector
6457 // sources no wider than 128 bits. Fall back to the default legalization
6458 // for anything else, e.g. when the mask of an i24 vector compare is
6459 // sign-extended, the promoted <4 x i24> source is not a simple type.
6460 EVT SrcEVT = Src.getValueType();
6461 if (!SrcEVT.isSimple() || SrcEVT.getSizeInBits() > 128)
6462 return;
6463 MVT SrcVT = SrcEVT.getSimpleVT();
6464
6465 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
6466 unsigned DstEltBits = DstVT.getScalarSizeInBits();
6467 unsigned NumElts = DstVT.getVectorNumElements();
6468
6469 if (!DstVT.isVector() || DstVT.getSizeInBits() <= 128)
6470 return;
6471
6472 // If every source element is all-ones or all-zeros, so is every extended
6473 // element, and interleaving a block with itself extends its low half.
6474 bool IsSignSplat = DAG.ComputeNumSignBits(Src) == SrcEltBits;
6475
6476 // Legalize and extend the src to 128-bit first.
6477 if (SrcVT.getSizeInBits() < 128) {
6478 unsigned WidenSrcElts = 128 / SrcEltBits;
6479 MVT WidenSrcVT = MVT::getVectorVT(SrcVT.getScalarType(), WidenSrcElts);
6480 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WidenSrcVT,
6481 DAG.getUNDEF(WidenSrcVT), Src,
6482 DAG.getVectorIdxConstant(0, DL));
6483 SrcVT = WidenSrcVT;
6484
6485 unsigned FirstStageEltBits = 128 / NumElts;
6486 MVT FirstStageEltVT = MVT::getIntegerVT(FirstStageEltBits);
6487 MVT FirstStageVT = MVT::getVectorVT(FirstStageEltVT, NumElts);
6488 Src = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, FirstStageVT, Src);
6489 SrcVT = FirstStageVT;
6490 SrcEltBits = FirstStageEltBits;
6491 }
6492
6494 Blocks.push_back(Src);
6495
6496 // Sign-extend the src by using VSLLWIL (or VILVL for a sign splat) + VEXTH
6497 // recursively.
6498 while (SrcEltBits < DstEltBits) {
6499 unsigned NextEltBits = SrcEltBits * 2;
6500 MVT NextEltVT = MVT::getIntegerVT(NextEltBits);
6501 unsigned CurEltsPerBlock = SrcVT.getVectorNumElements();
6502 unsigned NextEltsPerBlock = CurEltsPerBlock / 2;
6503 MVT NextBlockVT = MVT::getVectorVT(NextEltVT, NextEltsPerBlock);
6504
6505 SmallVector<SDValue, 8> NextBlocks;
6506 NextBlocks.reserve(Blocks.size() * 2);
6507 for (SDValue Block : Blocks) {
6508 SDValue Lo;
6509 if (IsSignSplat) {
6510 Lo = DAG.getNode(LoongArchISD::VILVL, DL, SrcVT, Block, Block);
6511 Lo = DAG.getBitcast(NextBlockVT, Lo);
6512 } else {
6513 Lo = DAG.getNode(LoongArchISD::VSLLWIL, DL, NextBlockVT, Block,
6514 DAG.getConstant(0, DL, Subtarget.getGRLenVT()));
6515 }
6516 NextBlocks.push_back(Lo);
6517 NextBlocks.push_back(
6518 DAG.getNode(LoongArchISD::VEXTH, DL, NextBlockVT, Block));
6519 }
6520
6521 Blocks = std::move(NextBlocks);
6522 SrcVT = NextBlockVT;
6523 SrcEltBits = NextEltBits;
6524 }
6525
6526 Results.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Blocks));
6527 break;
6528 }
6529 case ISD::FP_EXTEND:
6530 // FP_EXTEND may reach here due to the Custom action for v2f32 results, but
6531 // no target-specific lowering is required. Leave it unchanged and rely on
6532 // the default type legalization.
6533 break;
6534 }
6535}
6536
6537/// Try to fold: (and (xor X, -1), Y) -> (vandn X, Y).
6539 SelectionDAG &DAG) {
6540 assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDN");
6541
6542 MVT VT = N->getSimpleValueType(0);
6543 if (!VT.is128BitVector() && !VT.is256BitVector())
6544 return SDValue();
6545
6546 SDValue X, Y;
6547 SDValue N0 = N->getOperand(0);
6548 SDValue N1 = N->getOperand(1);
6549
6550 if (SDValue Not = isNOT(N0, DAG)) {
6551 X = Not;
6552 Y = N1;
6553 } else if (SDValue Not = isNOT(N1, DAG)) {
6554 X = Not;
6555 Y = N0;
6556 } else
6557 return SDValue();
6558
6559 X = DAG.getBitcast(VT, X);
6560 Y = DAG.getBitcast(VT, Y);
6561 return DAG.getNode(LoongArchISD::VANDN, DL, VT, X, Y);
6562}
6563
6564static bool isConstantSplatVector(SDValue N, APInt &SplatValue,
6565 unsigned MinSizeInBits) {
6568
6569 if (!Node)
6570 return false;
6571
6572 APInt SplatUndef;
6573 unsigned SplatBitSize;
6574 bool HasAnyUndefs;
6575
6576 return Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6577 HasAnyUndefs, MinSizeInBits,
6578 /*IsBigEndian=*/false);
6579}
6580
6581static SDValue matchDeinterleaveBuildVector(SDValue N, unsigned &StartIndex) {
6582 auto *BV = dyn_cast<BuildVectorSDNode>(N);
6583 if (!BV)
6584 return SDValue();
6585
6586 SDValue Src;
6587 int Start = -1;
6588
6589 for (unsigned i = 0, NumElts = BV->getNumOperands(); i < NumElts; ++i) {
6590 SDValue Op = BV->getOperand(i);
6591 if (Op.isUndef())
6592 continue;
6593 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6594 return SDValue();
6595
6596 auto *IdxC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6597 if (!IdxC)
6598 return SDValue();
6599
6600 unsigned EltIdx = IdxC->getZExtValue();
6601 if (Start < 0)
6602 Start = (int)EltIdx - (int)(i * 2);
6603 if (Start < 0 || Start > 1 || EltIdx != (unsigned)(Start + (int)(i * 2)))
6604 return SDValue();
6605
6606 SDValue CurSrc = Op.getOperand(0);
6607 if (!Src)
6608 Src = CurSrc;
6609 else if (Src != CurSrc)
6610 return SDValue();
6611 }
6612
6613 if (!Src || Start < 0)
6614 return SDValue();
6615
6616 StartIndex = (unsigned)Start;
6617 return Src;
6618}
6619
6620// Return true if values of type VT are kept in vector registers, i.e. VT is
6621// a vector type whose elements are legal in LSX vectors.
6622static bool isVectorRegisterVT(EVT VT, SelectionDAG &DAG) {
6623 if (!VT.isVector())
6624 return false;
6625 EVT EltVT = VT.getVectorElementType();
6626 unsigned EltBits = EltVT.getSizeInBits();
6627 if (EltBits < 8 || EltBits > 64)
6628 return false;
6629 EVT LSXVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 128 / EltBits);
6630 return DAG.getTargetLoweringInfo().isTypeLegal(LSXVT);
6631}
6632
6633// Return true if all users of the value loaded by Ld can use it in vector
6634// registers.
6636 EVT VT = Ld->getValueType(0);
6637 for (SDUse &U : Ld->uses()) {
6638 if (U.getResNo() != 0)
6639 continue;
6640 SDNode *User = U.getUser();
6641 switch (User->getOpcode()) {
6642 case ISD::ADD:
6643 case ISD::SUB:
6644 if (User->getValueType(0) == VT)
6645 continue;
6646 break;
6647 case ISD::STORE:
6648 // The stored value, not the address.
6649 if (U.getOperandNo() == 1)
6650 continue;
6651 break;
6652 case ISD::BITCAST:
6653 if (isVectorRegisterVT(User->getValueType(0), DAG))
6654 continue;
6655 break;
6656 }
6657 return false;
6658 }
6659 return true;
6660}
6661
6662// Return true if V, a vNi128 value, is cheap to obtain in vector registers
6663// of type PartVT.
6665 SelectionDAG &DAG) {
6666 switch (V.getOpcode()) {
6667 case ISD::LOAD: {
6668 auto *Ld = cast<LoadSDNode>(V);
6669 unsigned Fast = 0;
6670 return ISD::isNormalLoad(Ld) && Ld->isSimple() &&
6672 *DAG.getContext(), DAG.getDataLayout(), PartVT,
6673 *Ld->getMemOperand(), &Fast) &&
6674 Fast && hasOnlyVectorUsers(Ld, DAG);
6675 }
6676 case ISD::BITCAST: {
6677 // Vectors built from GPRs are not in vector registers.
6678 SDValue Src = V.getOperand(0);
6679 switch (Src.getOpcode()) {
6680 case ISD::BUILD_VECTOR:
6684 return false;
6685 }
6686 return isVectorRegisterVT(Src.getValueType(), DAG);
6687 }
6688 default:
6690 }
6691}
6692
6693// Combine add/sub on vNi128 to [X]VADD.Q/[X]VSUB.Q:
6694//
6695// (add vNi128:a, vNi128:b)
6696// -> (bitcast (VADD_Q (bitcast a to vMi64), (bitcast b to vMi64)))
6697//
6698// vNi128 types are not legal and would otherwise be expanded to scalar
6699// add/sub with carry on GPRs, so this has to happen before type legalization.
6700// Vectors wider than a vector register are split into register-sized parts.
6701// Only do it when both operands are already in, or cheap to get into, vector
6702// registers, e.g. loaded from memory. Values passed in GPRs (such as function
6703// arguments) are better handled in GPRs.
6707 if (!Subtarget.hasExtLSX())
6708 return SDValue();
6709 if (!DCI.isBeforeLegalize())
6710 return SDValue();
6711
6712 EVT VT = N->getValueType(0);
6713 if (!VT.isFixedLengthVector() || VT.getVectorElementType() != MVT::i128)
6714 return SDValue();
6715
6716 // Use 256-bit parts with LASX and 128-bit parts for the rest.
6717 unsigned NumElts = VT.getVectorNumElements();
6718 bool UseLASX = Subtarget.hasExtLASX() && NumElts >= 2;
6719 MVT PartVT = UseLASX ? MVT::v4i64 : MVT::v2i64;
6720 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i64, NumElts * 2);
6721
6722 SDValue LHS = N->getOperand(0);
6723 SDValue RHS = N->getOperand(1);
6724 if (!isCheapVNi128VectorOperand(LHS, PartVT, DAG) ||
6725 !isCheapVNi128VectorOperand(RHS, PartVT, DAG))
6726 return SDValue();
6727
6728 // Replace loads with loads of the i64 vector type, so that the other users
6729 // of the loaded value (e.g. another add/sub) can use it directly as well.
6730 // The range metadata, if any, is dropped as it doesn't match the new type.
6731 // The old loads are only replaced after N, as replacing them may CSE N into
6732 // another node and delete it.
6734 auto ConvertOperand = [&](SDValue V) {
6735 auto *Ld = dyn_cast<LoadSDNode>(V);
6736 if (!Ld)
6737 return DAG.getBitcast(NewVT, V);
6738 SDValue NewLd =
6739 DAG.getLoad(NewVT, SDLoc(Ld), Ld->getChain(), Ld->getBasePtr(),
6740 Ld->getPointerInfo(), Ld->getBaseAlign(),
6741 Ld->getMemOperand()->getFlags(), Ld->getAAInfo());
6742 LoadsToReplace.push_back({Ld, NewLd});
6743 return NewLd;
6744 };
6745 SDValue NewLHS = ConvertOperand(LHS);
6746 SDValue NewRHS = LHS == RHS ? NewLHS : ConvertOperand(RHS);
6747
6748 SDLoc DL(N);
6749 unsigned Opc =
6750 N->getOpcode() == ISD::ADD ? LoongArchISD::VADD_Q : LoongArchISD::VSUB_Q;
6751 SDValue Res = DAG.getUNDEF(NewVT);
6752 for (unsigned Idx = 0, End = NumElts * 2; Idx != End;) {
6753 MVT CurVT = UseLASX && End - Idx >= 4 ? MVT::v4i64 : MVT::v2i64;
6754 SDValue PartLHS = DAG.getExtractSubvector(DL, CurVT, NewLHS, Idx);
6755 SDValue PartRHS = DAG.getExtractSubvector(DL, CurVT, NewRHS, Idx);
6756 SDValue Part = DAG.getNode(Opc, DL, CurVT, PartLHS, PartRHS);
6757 Res = DAG.getInsertSubvector(DL, Res, Part, Idx);
6758 Idx += CurVT.getVectorNumElements();
6759 }
6760 DCI.CombineTo(N, DAG.getBitcast(VT, Res));
6761 for (auto [Ld, NewLd] : LoadsToReplace)
6762 DCI.CombineTo(Ld, DAG.getBitcast(VT, NewLd), NewLd.getValue(1));
6763 return SDValue(N, 0);
6764}
6765
6766static SDValue
6769 if (!Subtarget.hasExtLSX())
6770 return SDValue();
6771
6772 unsigned Opc = N->getOpcode();
6773 assert((Opc == ISD::ADD || Opc == ISD::SUB) && "Unexpected opcode");
6774
6775 EVT VT = N->getValueType(0);
6776 SDLoc DL(N);
6777
6778 SDValue LHS = N->getOperand(0);
6779 SDValue RHS = N->getOperand(1);
6780
6781 bool isSigned;
6782 unsigned ExtOpc = LHS.getOpcode();
6783 if (ExtOpc == ISD::SIGN_EXTEND)
6784 isSigned = true;
6785 else if (ExtOpc == ISD::ZERO_EXTEND)
6786 isSigned = false;
6787 else
6788 return SDValue();
6789
6790 if (ExtOpc != RHS.getOpcode())
6791 return SDValue();
6792
6793 if (!LHS.hasOneUse() || !RHS.hasOneUse())
6794 return SDValue();
6795
6796 unsigned OddIdx, EvenIdx;
6797 SDValue LHSVec = matchDeinterleaveBuildVector(LHS.getOperand(0), OddIdx);
6798 SDValue RHSVec = matchDeinterleaveBuildVector(RHS.getOperand(0), EvenIdx);
6799
6800 if (!LHSVec || !RHSVec)
6801 return SDValue();
6802 if (OddIdx != 1 || EvenIdx != 0)
6803 return SDValue();
6804 if (LHSVec.getValueType() != RHSVec.getValueType())
6805 return SDValue();
6806
6807 EVT SrcVT = LHSVec.getValueType();
6808 EVT SrcEltVT = SrcVT.getVectorElementType();
6809 EVT DstEltVT = VT.getVectorElementType();
6810 auto &TLI = DAG.getTargetLoweringInfo();
6811
6812 if (!TLI.isTypeLegal(VT) || !TLI.isTypeLegal(SrcVT))
6813 return SDValue();
6814 if (!SrcVT.isVector() || !VT.isVector())
6815 return SDValue();
6816 if (SrcVT.getSizeInBits() != VT.getSizeInBits())
6817 return SDValue();
6818 if (DstEltVT.getSizeInBits() != SrcEltVT.getSizeInBits() * 2)
6819 return SDValue();
6820 if (!SrcEltVT.isInteger() || SrcEltVT.getSizeInBits() > 32)
6821 return SDValue();
6822
6823 unsigned TargetOpc;
6824 if (Opc == ISD::ADD)
6825 TargetOpc = isSigned ? LoongArchISD::VHADDW : LoongArchISD::VHADDW_U;
6826 else
6827 TargetOpc = isSigned ? LoongArchISD::VHSUBW : LoongArchISD::VHSUBW_U;
6828
6829 return DAG.getNode(TargetOpc, DL, VT, LHSVec, RHSVec);
6830}
6831
6836 return V;
6837
6839 return V;
6840
6841 if (DCI.isBeforeLegalizeOps())
6842 return SDValue();
6843
6844 EVT VT = N->getValueType(0);
6845 if (!VT.isVector())
6846 return SDValue();
6847
6848 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6849 return SDValue();
6850
6851 EVT EltVT = VT.getVectorElementType();
6852 if (!EltVT.isInteger())
6853 return SDValue();
6854
6855 // match:
6856 //
6857 // add
6858 // (and
6859 // (srl X, shift-1) / X
6860 // 1)
6861 // (srl/sra X, shift)
6862
6863 SDValue Add0 = N->getOperand(0);
6864 SDValue Add1 = N->getOperand(1);
6865 SDValue And;
6866 SDValue Shr;
6867
6868 if (Add0.getOpcode() == ISD::AND) {
6869 And = Add0;
6870 Shr = Add1;
6871 } else if (Add1.getOpcode() == ISD::AND) {
6872 And = Add1;
6873 Shr = Add0;
6874 } else {
6875 return SDValue();
6876 }
6877
6878 // match:
6879 //
6880 // srl/sra X, shift
6881
6882 if (Shr.getOpcode() != ISD::SRL && Shr.getOpcode() != ISD::SRA)
6883 return SDValue();
6884
6885 SDValue X = Shr.getOperand(0);
6886 SDValue Shift = Shr.getOperand(1);
6887 APInt ShiftVal;
6888
6889 if (!isConstantSplatVector(Shift, ShiftVal, EltVT.getSizeInBits()))
6890 return SDValue();
6891
6892 if (ShiftVal == 0)
6893 return SDValue();
6894
6895 // match:
6896 //
6897 // and
6898 // (srl X, shift-1) / X
6899 // 1
6900
6901 SDValue One = And.getOperand(1);
6902 APInt SplatVal;
6903
6904 if (!isConstantSplatVector(One, SplatVal, EltVT.getSizeInBits()))
6905 return SDValue();
6906
6907 if (SplatVal != 1)
6908 return SDValue();
6909
6910 if (And.getOperand(0) == X) {
6911 // match:
6912 //
6913 // shift == 1
6914
6915 if (ShiftVal != 1)
6916 return SDValue();
6917 } else {
6918 // match:
6919 //
6920 // srl X, shift-1
6921
6922 SDValue Srl = And.getOperand(0);
6923
6924 if (Srl.getOpcode() != ISD::SRL)
6925 return SDValue();
6926
6927 if (Srl.getOperand(0) != X)
6928 return SDValue();
6929
6930 // match:
6931 //
6932 // shift-1
6933
6934 SDValue ShiftMinus1 = Srl.getOperand(1);
6935
6936 if (!isConstantSplatVector(ShiftMinus1, SplatVal, EltVT.getSizeInBits()))
6937 return SDValue();
6938
6939 if (ShiftVal != (SplatVal + 1))
6940 return SDValue();
6941 }
6942
6943 // We matched a rounded right shift pattern and can lower it
6944 // to a single vector rounded shift instruction.
6945
6946 SDLoc DL(N);
6947 return DAG.getNode(Shr.getOpcode() == ISD::SRL ? LoongArchISD::VSRLR
6948 : LoongArchISD::VSRAR,
6949 DL, VT, X, Shift);
6950}
6951
6955 if (DCI.isBeforeLegalizeOps())
6956 return SDValue();
6957
6958 SDValue FirstOperand = N->getOperand(0);
6959 SDValue SecondOperand = N->getOperand(1);
6960 unsigned FirstOperandOpc = FirstOperand.getOpcode();
6961 EVT ValTy = N->getValueType(0);
6962 SDLoc DL(N);
6963 uint64_t lsb, msb;
6964 unsigned SMIdx, SMLen;
6965 ConstantSDNode *CN;
6966 SDValue NewOperand;
6967 MVT GRLenVT = Subtarget.getGRLenVT();
6968
6969 if (SDValue R = combineAndNotIntoVANDN(N, DL, DAG))
6970 return R;
6971
6972 // BSTRPICK requires the 32S feature.
6973 if (!Subtarget.has32S())
6974 return SDValue();
6975
6976 // Op's second operand must be a shifted mask.
6977 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)) ||
6978 !isShiftedMask_64(CN->getZExtValue(), SMIdx, SMLen))
6979 return SDValue();
6980
6981 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
6982 // Pattern match BSTRPICK.
6983 // $dst = and ((sra or srl) $src , lsb), (2**len - 1)
6984 // => BSTRPICK $dst, $src, msb, lsb
6985 // where msb = lsb + len - 1
6986
6987 // The second operand of the shift must be an immediate.
6988 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
6989 return SDValue();
6990
6991 lsb = CN->getZExtValue();
6992
6993 // Return if the shifted mask does not start at bit 0 or the sum of its
6994 // length and lsb exceeds the word's size.
6995 if (SMIdx != 0 || lsb + SMLen > ValTy.getSizeInBits())
6996 return SDValue();
6997
6998 NewOperand = FirstOperand.getOperand(0);
6999 } else {
7000 // Pattern match BSTRPICK.
7001 // $dst = and $src, (2**len- 1) , if len > 12
7002 // => BSTRPICK $dst, $src, msb, lsb
7003 // where lsb = 0 and msb = len - 1
7004
7005 // If the mask is <= 0xfff, andi can be used instead.
7006 if (CN->getZExtValue() <= 0xfff)
7007 return SDValue();
7008
7009 // Return if the MSB exceeds.
7010 if (SMIdx + SMLen > ValTy.getSizeInBits())
7011 return SDValue();
7012
7013 if (SMIdx > 0) {
7014 // Omit if the constant has more than 2 uses. This a conservative
7015 // decision. Whether it is a win depends on the HW microarchitecture.
7016 // However it should always be better for 1 and 2 uses.
7017 if (CN->use_size() > 2)
7018 return SDValue();
7019 // Return if the constant can be composed by a single LU12I.W.
7020 if ((CN->getZExtValue() & 0xfff) == 0)
7021 return SDValue();
7022 // Return if the constand can be composed by a single ADDI with
7023 // the zero register.
7024 if (CN->getSExtValue() >= -2048 && CN->getSExtValue() < 0)
7025 return SDValue();
7026 }
7027
7028 lsb = SMIdx;
7029 NewOperand = FirstOperand;
7030 }
7031
7032 msb = lsb + SMLen - 1;
7033 SDValue NR0 = DAG.getNode(LoongArchISD::BSTRPICK, DL, ValTy, NewOperand,
7034 DAG.getConstant(msb, DL, GRLenVT),
7035 DAG.getConstant(lsb, DL, GRLenVT));
7036 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL || lsb == 0)
7037 return NR0;
7038 // Try to optimize to
7039 // bstrpick $Rd, $Rs, msb, lsb
7040 // slli $Rd, $Rd, lsb
7041 return DAG.getNode(ISD::SHL, DL, ValTy, NR0,
7042 DAG.getConstant(lsb, DL, GRLenVT));
7043}
7044
7045// Return the original source vector if N consists of the half
7046// of each 128-bit lane.
7049
7050 EVT DstVT = N.getValueType();
7051 if (!DstVT.isVector())
7052 return SDValue();
7053
7054 unsigned NumElts = DstVT.getVectorNumElements();
7055
7056 // LSX canonical form:
7057 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7058 SDValue Src = N.getOperand(0);
7059 EVT SrcVT = Src.getValueType();
7060
7061 if (!SrcVT.isVector() || !SrcVT.is128BitVector())
7062 return SDValue();
7063 if (SrcVT.getSizeInBits() != DstVT.getSizeInBits() * 2)
7064 return SDValue();
7065 if (SrcVT.getVectorNumElements() != NumElts * 2)
7066 return SDValue();
7067 if (N.getConstantOperandVal(1) != (isLow ? 0 : NumElts))
7068 return SDValue();
7069
7070 return Src;
7071 }
7072
7073 // LASX canonical form:
7074 auto *BV = dyn_cast<BuildVectorSDNode>(N);
7075 if (!BV)
7076 return SDValue();
7077
7078 if (NumElts % 2 != 0)
7079 return SDValue();
7080
7081 SDValue Src;
7082 EVT SrcVT;
7083
7084 for (unsigned I = 0; I != NumElts; ++I) {
7085 SDValue Elt = BV->getOperand(I);
7086 if (Elt.isUndef())
7087 continue;
7089 return SDValue();
7090
7091 SDValue ThisSrc = Elt.getOperand(0);
7092 SDValue Idx = Elt.getOperand(1);
7093 auto *CI = dyn_cast<ConstantSDNode>(Idx);
7094 if (!CI)
7095 return SDValue();
7096
7097 if (!Src) {
7098 Src = ThisSrc;
7099 SrcVT = Src.getValueType();
7100 if (!SrcVT.isVector())
7101 return SDValue();
7102
7103 if (!SrcVT.is256BitVector())
7104 return SDValue();
7105 if (SrcVT.getSizeInBits() != DstVT.getSizeInBits() * 2)
7106 return SDValue();
7107 if (SrcVT.getVectorNumElements() != NumElts * 2)
7108 return SDValue();
7109 } else if (ThisSrc != Src) {
7110 return SDValue();
7111 }
7112
7113 unsigned Half = NumElts / 2;
7114 unsigned ExpectedIdx = (I < Half) ? I : (I + Half);
7115 ExpectedIdx += isLow ? 0 : Half;
7116
7117 if (CI->getZExtValue() != ExpectedIdx)
7118 return SDValue();
7119 }
7120
7121 return Src;
7122}
7123
7127 assert(N->getOpcode() == ISD::SHL && "Unexpected opcode");
7128
7129 EVT VT = N->getValueType(0);
7130 SDLoc DL(N);
7131
7132 SDValue LHS = N->getOperand(0);
7133 SDValue RHS = N->getOperand(1);
7134
7135 bool isSigned;
7136 unsigned ExtOpc = LHS.getOpcode();
7137 if (ExtOpc == ISD::SIGN_EXTEND)
7138 isSigned = true;
7139 else if (ExtOpc == ISD::ZERO_EXTEND)
7140 isSigned = false;
7141 else
7142 return SDValue();
7143
7144 if (!LHS.hasOneUse())
7145 return SDValue();
7146
7147 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) ||
7148 N->getValueSizeInBits(0) != LHS->getOperand(0).getValueSizeInBits() * 2)
7149 return SDValue();
7150
7151 SDValue Vec = matchHalfOf128BitLanes(LHS.getOperand(0), /*isLow=*/true);
7152 if (!Vec)
7153 return SDValue();
7154
7155 EVT SrcVT = Vec.getValueType();
7156 EVT SrcEltVT = SrcVT.getVectorElementType();
7157 EVT DstEltVT = VT.getVectorElementType();
7158 APInt Imm;
7159 if (!isConstantSplatVector(RHS, Imm, DstEltVT.getSizeInBits()))
7160 return SDValue();
7161 if (!Imm.ult(SrcEltVT.getSizeInBits()))
7162 return SDValue();
7163
7164 unsigned Opc = isSigned ? LoongArchISD::VSLLWIL : LoongArchISD::VSLLWIL_U;
7165 SDValue Sht = DAG.getConstant(Imm.getZExtValue(), DL, Subtarget.getGRLenVT());
7166 return DAG.getNode(Opc, DL, VT, Vec, Sht);
7167}
7168
7172 // BSTRPICK requires the 32S feature.
7173 if (!Subtarget.has32S())
7174 return SDValue();
7175
7176 if (DCI.isBeforeLegalizeOps())
7177 return SDValue();
7178
7179 // $dst = srl (and $src, Mask), Shamt
7180 // =>
7181 // BSTRPICK $dst, $src, MaskIdx+MaskLen-1, Shamt
7182 // when Mask is a shifted mask, and MaskIdx <= Shamt <= MaskIdx+MaskLen-1
7183 //
7184
7185 SDValue FirstOperand = N->getOperand(0);
7186 ConstantSDNode *CN;
7187 EVT ValTy = N->getValueType(0);
7188 SDLoc DL(N);
7189 MVT GRLenVT = Subtarget.getGRLenVT();
7190 unsigned MaskIdx, MaskLen;
7191 uint64_t Shamt;
7192
7193 // The first operand must be an AND and the second operand of the AND must be
7194 // a shifted mask.
7195 if (FirstOperand.getOpcode() != ISD::AND ||
7196 !(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
7197 !isShiftedMask_64(CN->getZExtValue(), MaskIdx, MaskLen))
7198 return SDValue();
7199
7200 // The second operand (shift amount) must be an immediate.
7201 if (!(CN = dyn_cast<ConstantSDNode>(N->getOperand(1))))
7202 return SDValue();
7203
7204 Shamt = CN->getZExtValue();
7205 if (MaskIdx <= Shamt && Shamt <= MaskIdx + MaskLen - 1)
7206 return DAG.getNode(LoongArchISD::BSTRPICK, DL, ValTy,
7207 FirstOperand->getOperand(0),
7208 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7209 DAG.getConstant(Shamt, DL, GRLenVT));
7210
7211 return SDValue();
7212}
7213
7214// Try to turn a sub boolean RHS and constant LHS into an addi. LoongArch's
7215// SUB has no immediate form, so (sub C, X) normally requires either
7216// materializing C or using sub with R0 plus an addi; rewriting it as
7217// (add X', C - 1) lets the immediate fold into a single ADDI.
7219 SDValue N0 = N->getOperand(0);
7220 SDValue N1 = N->getOperand(1);
7221 EVT VT = N->getValueType(0);
7222 SDLoc DL(N);
7223
7224 // Require a constant LHS.
7225 auto *N0C = dyn_cast<ConstantSDNode>(N0);
7226 if (!N0C)
7227 return SDValue();
7228
7229 // (sub 0, X) is a negation, not a constant materialization; rewriting it
7230 // as (add (setcc inv), -1) changes the condition code and can duplicate a
7231 // compare, without saving any instruction.
7232 if (N0C->isZero() && !N->hasOneUse())
7233 return SDValue();
7234
7235 // The result of this fold is only folded into an ADDI when it is used
7236 // directly. When it feeds an extend, the original (sub C, X) form usually
7237 // combines better with the surrounding zext/negate/xor.
7238 if (N->hasOneUse()) {
7239 unsigned UserOpc = N->use_begin()->getUser()->getOpcode();
7240 if (UserOpc == ISD::ZERO_EXTEND || UserOpc == ISD::SIGN_EXTEND ||
7241 UserOpc == ISD::ANY_EXTEND || UserOpc == ISD::SUB)
7242 return SDValue();
7243 }
7244
7245 // All our optimizations involve subtracting 1 from the immediate and
7246 // forming an ADDI. Make sure the new immediate is valid for an ADDI.
7247 APInt ImmValMinus1 = N0C->getAPIntValue() - 1;
7248 if (!ImmValMinus1.isSignedIntN(12))
7249 return SDValue();
7250
7251 SDValue NewLHS;
7252 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse()) {
7253 // (sub constant, (setcc x, y, eq/neq)) ->
7254 // (add (setcc x, y, neq/eq), constant - 1)
7255 ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get();
7256 EVT SetCCOpVT = N1.getOperand(0).getValueType();
7257 if (!ISD::isIntEqualitySetCC(CCVal) || !SetCCOpVT.isInteger())
7258 return SDValue();
7259 CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT);
7260 NewLHS =
7261 DAG.getSetCC(SDLoc(N1), VT, N1.getOperand(0), N1.getOperand(1), CCVal);
7262 } else if (N1.getOpcode() == ISD::XOR && isOneConstant(N1.getOperand(1)) &&
7263 N1.getOperand(0).getOpcode() == ISD::SETCC) {
7264 // (sub C, (xor (setcc), 1)) -> (add (setcc), C-1).
7265 // Since setcc returns a bool the xor is equivalent to 1-setcc.
7266 NewLHS = N1.getOperand(0);
7267 } else
7268 return SDValue();
7269
7270 SDValue NewRHS = DAG.getConstant(ImmValMinus1, DL, VT);
7271 return DAG.getNode(ISD::ADD, DL, VT, NewLHS, NewRHS);
7272}
7273
7278 return V;
7279
7281 return V;
7282
7283 if (N->getValueType(0) != Subtarget.getGRLenVT())
7284 return SDValue();
7285
7286 SDValue N0 = N->getOperand(0);
7287 SDValue N1 = N->getOperand(1);
7288 EVT VT = N->getValueType(0);
7289
7290 if (SDValue V = combineSubOfBoolean(N, DAG))
7291 return V;
7292
7293 // fold (sub 0, (setcc x, 0, setlt)) -> (sra x, xlen - 1)
7294 if (isNullConstant(N0) && N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
7295 isNullConstant(N1.getOperand(1)) &&
7296 N1.getValueType() == N1.getOperand(0).getValueType()) {
7297 ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get();
7298 if (CCVal == ISD::SETLT) {
7299 SDLoc DL(N);
7300 unsigned ShAmt = N0.getValueSizeInBits() - 1;
7301 return DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0),
7302 DAG.getConstant(ShAmt, DL, VT));
7303 }
7304 }
7305
7306 return SDValue();
7307}
7308
7309// Helper to peek through bitops/trunc/setcc to determine size of source vector.
7310// Allows BITCASTCombine to determine what size vector generated a <X x i1>.
7311static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
7312 unsigned Depth) {
7313 // Limit recursion.
7315 return false;
7316 switch (Src.getOpcode()) {
7317 case ISD::SETCC:
7318 case ISD::TRUNCATE:
7319 return Src.getOperand(0).getValueSizeInBits() == Size;
7320 case ISD::FREEZE:
7321 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, Depth + 1);
7322 case ISD::AND:
7323 case ISD::XOR:
7324 case ISD::OR:
7325 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, Depth + 1) &&
7326 checkBitcastSrcVectorSize(Src.getOperand(1), Size, Depth + 1);
7327 case ISD::SELECT:
7328 case ISD::VSELECT:
7329 return Src.getOperand(0).getScalarValueSizeInBits() == 1 &&
7330 checkBitcastSrcVectorSize(Src.getOperand(1), Size, Depth + 1) &&
7331 checkBitcastSrcVectorSize(Src.getOperand(2), Size, Depth + 1);
7332 case ISD::BUILD_VECTOR:
7334 }
7335 return false;
7336}
7337
7338// Helper to push sign extension of vXi1 SETCC result through bitops.
7340 SDValue Src, const SDLoc &DL) {
7341 switch (Src.getOpcode()) {
7342 case ISD::SETCC:
7343 case ISD::FREEZE:
7344 case ISD::TRUNCATE:
7345 case ISD::BUILD_VECTOR:
7346 return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
7347 case ISD::AND:
7348 case ISD::XOR:
7349 case ISD::OR:
7350 return DAG.getNode(
7351 Src.getOpcode(), DL, SExtVT,
7352 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
7353 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
7354 case ISD::SELECT:
7355 case ISD::VSELECT:
7356 return DAG.getSelect(
7357 DL, SExtVT, Src.getOperand(0),
7358 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL),
7359 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(2), DL));
7360 }
7361 llvm_unreachable("Unexpected node type for vXi1 sign extension");
7362}
7363
7364static SDValue
7368 SDLoc DL(N);
7369 EVT VT = N->getValueType(0);
7370 SDValue Src = N->getOperand(0);
7371 EVT SrcVT = Src.getValueType();
7372
7373 if (Src.getOpcode() != ISD::SETCC || !Src.hasOneUse())
7374 return SDValue();
7375
7376 bool UseLASX;
7377 unsigned Opc = ISD::DELETED_NODE;
7378 EVT CmpVT = Src.getOperand(0).getValueType();
7379 EVT EltVT = CmpVT.getVectorElementType();
7380
7381 if (Subtarget.hasExtLSX() && CmpVT.getSizeInBits() == 128)
7382 UseLASX = false;
7383 else if (Subtarget.has32S() && Subtarget.hasExtLASX() &&
7384 CmpVT.getSizeInBits() == 256)
7385 UseLASX = true;
7386 else
7387 return SDValue();
7388
7389 SDValue SrcN1 = Src.getOperand(1);
7390 switch (Src.getOperandCondCode(2)) {
7391 default:
7392 break;
7393 case ISD::SETEQ:
7394 // x == 0 => not (vmsknez.b x)
7395 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7396 Opc = UseLASX ? LoongArchISD::XVMSKEQZ : LoongArchISD::VMSKEQZ;
7397 break;
7398 case ISD::SETGT:
7399 // x > -1 => vmskgez.b x
7400 if (ISD::isBuildVectorAllOnes(SrcN1) && EltVT == MVT::i8)
7401 Opc = UseLASX ? LoongArchISD::XVMSKGEZ : LoongArchISD::VMSKGEZ;
7402 break;
7403 case ISD::SETGE:
7404 // x >= 0 => vmskgez.b x
7405 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7406 Opc = UseLASX ? LoongArchISD::XVMSKGEZ : LoongArchISD::VMSKGEZ;
7407 break;
7408 case ISD::SETLT:
7409 // x < 0 => vmskltz.{b,h,w,d} x
7410 if (ISD::isBuildVectorAllZeros(SrcN1) &&
7411 (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
7412 EltVT == MVT::i64))
7413 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7414 break;
7415 case ISD::SETLE:
7416 // x <= -1 => vmskltz.{b,h,w,d} x
7417 if (ISD::isBuildVectorAllOnes(SrcN1) &&
7418 (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
7419 EltVT == MVT::i64))
7420 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7421 break;
7422 case ISD::SETNE:
7423 // x != 0 => vmsknez.b x
7424 if (ISD::isBuildVectorAllZeros(SrcN1) && EltVT == MVT::i8)
7425 Opc = UseLASX ? LoongArchISD::XVMSKNEZ : LoongArchISD::VMSKNEZ;
7426 break;
7427 }
7428
7429 if (Opc == ISD::DELETED_NODE)
7430 return SDValue();
7431
7432 SDValue V = DAG.getNode(Opc, DL, Subtarget.getGRLenVT(), Src.getOperand(0));
7434 V = DAG.getZExtOrTrunc(V, DL, T);
7435 return DAG.getBitcast(VT, V);
7436}
7437
7441 SDLoc DL(N);
7442 EVT VT = N->getValueType(0);
7443 SDValue Src = N->getOperand(0);
7444 EVT SrcVT = Src.getValueType();
7445 MVT GRLenVT = Subtarget.getGRLenVT();
7446
7447 if (!DCI.isBeforeLegalizeOps())
7448 return SDValue();
7449
7450 if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
7451 return SDValue();
7452
7453 // Combine SETCC and BITCAST into [X]VMSK{LT,GE,NE} when possible
7455 if (Res)
7456 return Res;
7457
7458 // Generate vXi1 using [X]VMSKLTZ
7459 MVT SExtVT;
7460 unsigned Opc;
7461 bool UseLASX = false;
7462 bool PropagateSExt = false;
7463
7464 if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse()) {
7465 EVT CmpVT = Src.getOperand(0).getValueType();
7466 if (CmpVT.getSizeInBits() > 256)
7467 return SDValue();
7468 }
7469
7470 switch (SrcVT.getSimpleVT().SimpleTy) {
7471 default:
7472 return SDValue();
7473 case MVT::v2i1:
7474 SExtVT = MVT::v2i64;
7475 break;
7476 case MVT::v4i1:
7477 SExtVT = MVT::v4i32;
7478 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7479 SExtVT = MVT::v4i64;
7480 UseLASX = true;
7481 PropagateSExt = true;
7482 }
7483 break;
7484 case MVT::v8i1:
7485 SExtVT = MVT::v8i16;
7486 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7487 SExtVT = MVT::v8i32;
7488 UseLASX = true;
7489 PropagateSExt = true;
7490 }
7491 break;
7492 case MVT::v16i1:
7493 SExtVT = MVT::v16i8;
7494 if (Subtarget.hasExtLASX() && checkBitcastSrcVectorSize(Src, 256, 0)) {
7495 SExtVT = MVT::v16i16;
7496 UseLASX = true;
7497 PropagateSExt = true;
7498 }
7499 break;
7500 case MVT::v32i1:
7501 SExtVT = MVT::v32i8;
7502 UseLASX = true;
7503 break;
7504 };
7505 Src = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
7506 : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
7507
7508 SDValue V;
7509 if (!Subtarget.has32S() || !Subtarget.hasExtLASX()) {
7510 if (Src.getSimpleValueType() == MVT::v32i8) {
7511 SDValue Lo, Hi;
7512 std::tie(Lo, Hi) = DAG.SplitVector(Src, DL);
7513 Lo = DAG.getNode(LoongArchISD::VMSKLTZ, DL, GRLenVT, Lo);
7514 Hi = DAG.getNode(LoongArchISD::VMSKLTZ, DL, GRLenVT, Hi);
7515 Hi = DAG.getNode(ISD::SHL, DL, GRLenVT, Hi,
7516 DAG.getShiftAmountConstant(16, GRLenVT, DL));
7517 V = DAG.getNode(ISD::OR, DL, GRLenVT, Lo, Hi);
7518 } else if (UseLASX) {
7519 return SDValue();
7520 }
7521 }
7522
7523 if (!V) {
7524 Opc = UseLASX ? LoongArchISD::XVMSKLTZ : LoongArchISD::VMSKLTZ;
7525 V = DAG.getNode(Opc, DL, GRLenVT, Src);
7526 }
7527
7529 V = DAG.getZExtOrTrunc(V, DL, T);
7530 return DAG.getBitcast(VT, V);
7531}
7532
7533// OP(bitcast(shl(splat(1), y)), x) -> bitcast(OP(shl(splat(1), y), bitcast(x)))
7534// for OP in {or, xor}. Perform the bitwise operation in the element type of
7535// the shift so that it can be selected as [x]vbitset.{b/h/w} or
7536// [x]vbitrev.{b/h/w}. Only fold when the shift's element type is strictly
7537// narrower than that of OP; otherwise OP of two bitcasted shifts with different
7538// element types would be folded back and forth forever.
7540 EVT VT = N->getValueType(0);
7542 if (!VT.isVector() || !TLI.isTypeLegal(VT))
7543 return SDValue();
7544
7545 for (unsigned I = 0; I < 2; ++I) {
7546 SDValue N0 = N->getOperand(I);
7547 SDValue N1 = N->getOperand(1 - I);
7548 if (N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse())
7549 continue;
7550 SDValue Shl = N0.getOperand(0);
7551 EVT ShlVT = Shl.getValueType();
7552 APInt SplatVal;
7553 if (Shl.getOpcode() == ISD::SHL && ShlVT.isVector() && ShlVT.isInteger() &&
7555 ShlVT.getSizeInBits() == VT.getSizeInBits() && TLI.isTypeLegal(ShlVT) &&
7556 ISD::isConstantSplatVector(Shl.getOperand(0), SplatVal) &&
7557 SplatVal.isOne()) {
7558 SDLoc DL(N);
7559 SDValue V = DAG.getNode(N->getOpcode(), DL, ShlVT, Shl,
7560 DAG.getBitcast(ShlVT, N1));
7561 return DAG.getBitcast(VT, V);
7562 }
7563 }
7564
7565 return SDValue();
7566}
7567
7571 MVT GRLenVT = Subtarget.getGRLenVT();
7572 EVT ValTy = N->getValueType(0);
7573 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7574 ConstantSDNode *CN0, *CN1;
7575 SDLoc DL(N);
7576 unsigned ValBits = ValTy.getSizeInBits();
7577 unsigned MaskIdx0, MaskLen0, MaskIdx1, MaskLen1;
7578 unsigned Shamt;
7579 bool SwapAndRetried = false;
7580
7582 return V;
7583
7584 // BSTRPICK requires the 32S feature.
7585 if (!Subtarget.has32S())
7586 return SDValue();
7587
7588 if (DCI.isBeforeLegalizeOps())
7589 return SDValue();
7590
7591 if (ValBits != 32 && ValBits != 64)
7592 return SDValue();
7593
7594Retry:
7595 // 1st pattern to match BSTRINS:
7596 // R = or (and X, mask0), (and (shl Y, lsb), mask1)
7597 // where mask1 = (2**size - 1) << lsb, mask0 = ~mask1
7598 // =>
7599 // R = BSTRINS X, Y, msb, lsb (where msb = lsb + size - 1)
7600 if (N0.getOpcode() == ISD::AND &&
7601 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7602 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7603 N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL &&
7604 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7605 isShiftedMask_64(CN1->getZExtValue(), MaskIdx1, MaskLen1) &&
7606 MaskIdx0 == MaskIdx1 && MaskLen0 == MaskLen1 &&
7607 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7608 (Shamt = CN1->getZExtValue()) == MaskIdx0 &&
7609 (MaskIdx0 + MaskLen0 <= ValBits)) {
7610 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 1\n");
7611 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7612 N1.getOperand(0).getOperand(0),
7613 DAG.getConstant((MaskIdx0 + MaskLen0 - 1), DL, GRLenVT),
7614 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7615 }
7616
7617 // 2nd pattern to match BSTRINS:
7618 // R = or (and X, mask0), (shl (and Y, mask1), lsb)
7619 // where mask1 = (2**size - 1), mask0 = ~(mask1 << lsb)
7620 // =>
7621 // R = BSTRINS X, Y, msb, lsb (where msb = lsb + size - 1)
7622 if (N0.getOpcode() == ISD::AND &&
7623 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7624 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7625 N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::AND &&
7626 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7627 (Shamt = CN1->getZExtValue()) == MaskIdx0 &&
7628 (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7629 isShiftedMask_64(CN1->getZExtValue(), MaskIdx1, MaskLen1) &&
7630 MaskLen0 == MaskLen1 && MaskIdx1 == 0 &&
7631 (MaskIdx0 + MaskLen0 <= ValBits)) {
7632 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 2\n");
7633 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7634 N1.getOperand(0).getOperand(0),
7635 DAG.getConstant((MaskIdx0 + MaskLen0 - 1), DL, GRLenVT),
7636 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7637 }
7638
7639 // 3rd pattern to match BSTRINS:
7640 // R = or (and X, mask0), (and Y, mask1)
7641 // where ~mask0 = (2**size - 1) << lsb, mask0 & mask1 = 0
7642 // =>
7643 // R = BSTRINS X, (shr (and Y, mask1), lsb), msb, lsb
7644 // where msb = lsb + size - 1
7645 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
7646 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7647 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7648 (MaskIdx0 + MaskLen0 <= 64) &&
7649 (CN1 = dyn_cast<ConstantSDNode>(N1->getOperand(1))) &&
7650 (CN1->getSExtValue() & CN0->getSExtValue()) == 0) {
7651 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 3\n");
7652 // For complementary masks, insert the low bits without masking or shifting.
7653 if (CN0->getSExtValue() == ~CN1->getSExtValue() &&
7654 (isMask_64(CN0->getZExtValue()) || isMask_64(CN1->getZExtValue()))) {
7655 bool Swap = isMask_64(CN0->getZExtValue());
7656 unsigned Width = llvm::countr_one((Swap ? CN0 : CN1)->getZExtValue());
7657 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy,
7658 (Swap ? N1 : N0).getOperand(0),
7659 (Swap ? N0 : N1).getOperand(0),
7660 DAG.getConstant(Width - 1, DL, GRLenVT),
7661 DAG.getConstant(0, DL, GRLenVT));
7662 }
7663 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7664 DAG.getNode(ISD::SRL, DL, N1->getValueType(0), N1,
7665 DAG.getConstant(MaskIdx0, DL, GRLenVT)),
7666 DAG.getConstant(ValBits == 32
7667 ? (MaskIdx0 + (MaskLen0 & 31) - 1)
7668 : (MaskIdx0 + MaskLen0 - 1),
7669 DL, GRLenVT),
7670 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7671 }
7672
7673 // 4th pattern to match BSTRINS:
7674 // R = or (and X, mask), (shl Y, shamt)
7675 // where mask = (2**shamt - 1)
7676 // =>
7677 // R = BSTRINS X, Y, ValBits - 1, shamt
7678 // where ValBits = 32 or 64
7679 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::SHL &&
7680 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7681 isShiftedMask_64(CN0->getZExtValue(), MaskIdx0, MaskLen0) &&
7682 MaskIdx0 == 0 && (CN1 = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7683 (Shamt = CN1->getZExtValue()) == MaskLen0 &&
7684 (MaskIdx0 + MaskLen0 <= ValBits)) {
7685 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 4\n");
7686 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7687 N1.getOperand(0),
7688 DAG.getConstant((ValBits - 1), DL, GRLenVT),
7689 DAG.getConstant(Shamt, DL, GRLenVT));
7690 }
7691
7692 // 5th pattern to match BSTRINS:
7693 // R = or (and X, mask), const
7694 // where ~mask = (2**size - 1) << lsb, mask & const = 0
7695 // =>
7696 // R = BSTRINS X, (const >> lsb), msb, lsb
7697 // where msb = lsb + size - 1
7698 if (N0.getOpcode() == ISD::AND &&
7699 (CN0 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) &&
7700 isShiftedMask_64(~CN0->getSExtValue(), MaskIdx0, MaskLen0) &&
7701 (CN1 = dyn_cast<ConstantSDNode>(N1)) &&
7702 (CN1->getSExtValue() & CN0->getSExtValue()) == 0) {
7703 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 5\n");
7704 return DAG.getNode(
7705 LoongArchISD::BSTRINS, DL, ValTy, N0.getOperand(0),
7706 DAG.getSignedConstant(CN1->getSExtValue() >> MaskIdx0, DL, ValTy),
7707 DAG.getConstant(ValBits == 32 ? (MaskIdx0 + (MaskLen0 & 31) - 1)
7708 : (MaskIdx0 + MaskLen0 - 1),
7709 DL, GRLenVT),
7710 DAG.getConstant(MaskIdx0, DL, GRLenVT));
7711 }
7712
7713 // 6th pattern.
7714 // a = b | ((c & mask) << shamt), where all positions in b to be overwritten
7715 // by the incoming bits are known to be zero.
7716 // =>
7717 // a = BSTRINS b, c, shamt + MaskLen - 1, shamt
7718 //
7719 // Note that the 1st pattern is a special situation of the 6th, i.e. the 6th
7720 // pattern is more common than the 1st. So we put the 1st before the 6th in
7721 // order to match as many nodes as possible.
7722 ConstantSDNode *CNMask, *CNShamt;
7723 unsigned MaskIdx, MaskLen;
7724 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::AND &&
7725 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7726 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen) &&
7727 MaskIdx == 0 && (CNShamt = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7728 CNShamt->getZExtValue() + MaskLen <= ValBits) {
7729 Shamt = CNShamt->getZExtValue();
7730 APInt ShMask(ValBits, CNMask->getZExtValue() << Shamt);
7731 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7732 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 6\n");
7733 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7734 N1.getOperand(0).getOperand(0),
7735 DAG.getConstant(Shamt + MaskLen - 1, DL, GRLenVT),
7736 DAG.getConstant(Shamt, DL, GRLenVT));
7737 }
7738 }
7739
7740 // 7th pattern.
7741 // a = b | ((c << shamt) & shifted_mask), where all positions in b to be
7742 // overwritten by the incoming bits are known to be zero.
7743 // =>
7744 // a = BSTRINS b, c, MaskIdx + MaskLen - 1, MaskIdx
7745 //
7746 // Similarly, the 7th pattern is more common than the 2nd. So we put the 2nd
7747 // before the 7th in order to match as many nodes as possible.
7748 if (N1.getOpcode() == ISD::AND &&
7749 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7750 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen) &&
7751 N1.getOperand(0).getOpcode() == ISD::SHL &&
7752 (CNShamt = dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(1))) &&
7753 CNShamt->getZExtValue() == MaskIdx) {
7754 APInt ShMask(ValBits, CNMask->getZExtValue());
7755 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7756 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 7\n");
7757 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7758 N1.getOperand(0).getOperand(0),
7759 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7760 DAG.getConstant(MaskIdx, DL, GRLenVT));
7761 }
7762 }
7763
7764 // (or a, b) and (or b, a) are equivalent, so swap the operands and retry.
7765 if (!SwapAndRetried) {
7766 std::swap(N0, N1);
7767 SwapAndRetried = true;
7768 goto Retry;
7769 }
7770
7771 SwapAndRetried = false;
7772Retry2:
7773 // 8th pattern.
7774 // a = b | (c & shifted_mask), where all positions in b to be overwritten by
7775 // the incoming bits are known to be zero.
7776 // =>
7777 // a = BSTRINS b, c >> MaskIdx, MaskIdx + MaskLen - 1, MaskIdx
7778 //
7779 // Similarly, the 8th pattern is more common than the 4th and 5th patterns. So
7780 // we put it here in order to match as many nodes as possible or generate less
7781 // instructions.
7782 if (N1.getOpcode() == ISD::AND &&
7783 (CNMask = dyn_cast<ConstantSDNode>(N1.getOperand(1))) &&
7784 isShiftedMask_64(CNMask->getZExtValue(), MaskIdx, MaskLen)) {
7785 APInt ShMask(ValBits, CNMask->getZExtValue());
7786 if (ShMask.isSubsetOf(DAG.computeKnownBits(N0).Zero)) {
7787 LLVM_DEBUG(dbgs() << "Perform OR combine: match pattern 8\n");
7788 return DAG.getNode(LoongArchISD::BSTRINS, DL, ValTy, N0,
7789 DAG.getNode(ISD::SRL, DL, N1->getValueType(0),
7790 N1->getOperand(0),
7791 DAG.getConstant(MaskIdx, DL, GRLenVT)),
7792 DAG.getConstant(MaskIdx + MaskLen - 1, DL, GRLenVT),
7793 DAG.getConstant(MaskIdx, DL, GRLenVT));
7794 }
7795 }
7796 // Swap N0/N1 and retry.
7797 if (!SwapAndRetried) {
7798 std::swap(N0, N1);
7799 SwapAndRetried = true;
7800 goto Retry2;
7801 }
7802
7803 return SDValue();
7804}
7805
7809 return V;
7810
7811 EVT VT = N->getValueType(0);
7812 // LA64 promotes i32 integer operations to GPR-width operations during
7813 // legalization. Match the idiom before that promotion as well as after
7814 // it, otherwise common unsigned 32-bit bit tests miss this combine.
7815 if (VT != Subtarget.getGRLenVT() && !(Subtarget.is64Bit() && VT == MVT::i32))
7816 return SDValue();
7817
7818 SDValue XorOps[] = {N->getOperand(0), N->getOperand(1)};
7819 for (unsigned AndIdx = 0; AndIdx != 2; ++AndIdx) {
7820 SDValue And = XorOps[AndIdx];
7821 SDValue Mask = XorOps[1 - AndIdx];
7822 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
7823 continue;
7824
7825 for (unsigned MaskIdx = 0; MaskIdx != 2; ++MaskIdx) {
7826 // Match by SDValue identity so that (X & M1) ^ M2 is never folded
7827 // unless M1 and M2 are the same value. Canonicalize before
7828 // instruction selection, where the AND operand may already have been
7829 // selected to a target machine node.
7830 if (And.getOperand(MaskIdx) != Mask)
7831 continue;
7832 SDLoc DL(N);
7833 SDValue X = And.getOperand(1 - MaskIdx);
7834 return DAG.getNode(ISD::AND, DL, VT, Mask, DAG.getNOT(DL, X, VT));
7835 }
7836 }
7837 return SDValue();
7838}
7839
7841 ExtType = ISD::NON_EXTLOAD;
7842
7843 switch (V.getNode()->getOpcode()) {
7844 case ISD::LOAD: {
7845 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
7846 if ((LoadNode->getMemoryVT() == MVT::i8) ||
7847 (LoadNode->getMemoryVT() == MVT::i16)) {
7848 ExtType = LoadNode->getExtensionType();
7849 return true;
7850 }
7851 return false;
7852 }
7853 case ISD::AssertSext: {
7854 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
7855 if ((TypeNode->getVT() == MVT::i8) || (TypeNode->getVT() == MVT::i16)) {
7856 ExtType = ISD::SEXTLOAD;
7857 return true;
7858 }
7859 return false;
7860 }
7861 case ISD::AssertZext: {
7862 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
7863 if ((TypeNode->getVT() == MVT::i8) || (TypeNode->getVT() == MVT::i16)) {
7864 ExtType = ISD::ZEXTLOAD;
7865 return true;
7866 }
7867 return false;
7868 }
7869 default:
7870 return false;
7871 }
7872
7873 return false;
7874}
7875
7876// Fold a lane-mask extraction that is only compared against zero into one of
7877// all-lane check instructions, which write the results into fcc register, so
7878// BCEQZ could use it directly.
7879//
7880// (VMSKLTZ X) != 0 -> VSETNEZ.V X
7881// (VMSKLTZ X) == 0 -> VSETEQZ.V X
7882//
7883// This is valid when X is the result of a vector compare instruction,
7884// so each lane of X has to be all-ones or all-zeros.
7886 const SDLoc &DL, SelectionDAG &DAG,
7888 if (CC != ISD::SETEQ && CC != ISD::SETNE)
7889 return SDValue();
7890 if (!isNullConstant(RHS))
7891 return SDValue();
7892
7893 unsigned MskOpc = LHS.getOpcode();
7894 if (MskOpc != LoongArchISD::VMSKLTZ && MskOpc != LoongArchISD::XVMSKLTZ)
7895 return SDValue();
7896 // Keeping the mask alive for another user would defeat the purpose.
7897 if (!LHS.hasOneUse())
7898 return SDValue();
7899
7900 SDValue Src = LHS.getOperand(0);
7901 EVT SrcVT = Src.getValueType();
7902 // Make sure every lane is all-ones or all-zeros.
7903 if (!SrcVT.isVector() ||
7904 DAG.ComputeNumSignBits(Src) != SrcVT.getScalarSizeInBits())
7905 return SDValue();
7906
7907 return DAG.getNode(CC == ISD::SETNE ? LoongArchISD::VANYNONZERO
7908 : LoongArchISD::VALLZERO,
7909 DL, Subtarget.getGRLenVT(), Src);
7910}
7911
7912// Eliminate redundant truncation and zero-extension nodes.
7913// * Case 1:
7914// +------------+ +------------+ +------------+
7915// | Input1 | | Input2 | | CC |
7916// +------------+ +------------+ +------------+
7917// | | |
7918// V V +----+
7919// +------------+ +------------+ |
7920// | TRUNCATE | | TRUNCATE | |
7921// +------------+ +------------+ |
7922// | | |
7923// V V |
7924// +------------+ +------------+ |
7925// | ZERO_EXT | | ZERO_EXT | |
7926// +------------+ +------------+ |
7927// | | |
7928// | +-------------+ |
7929// V V | |
7930// +----------------+ | |
7931// | AND | | |
7932// +----------------+ | |
7933// | | |
7934// +---------------+ | |
7935// | | |
7936// V V V
7937// +-------------+
7938// | CMP |
7939// +-------------+
7940// * Case 2:
7941// +------------+ +------------+ +-------------+ +------------+ +------------+
7942// | Input1 | | Input2 | | Constant -1 | | Constant 0 | | CC |
7943// +------------+ +------------+ +-------------+ +------------+ +------------+
7944// | | | | |
7945// V | | | |
7946// +------------+ | | | |
7947// | XOR |<---------------------+ | |
7948// +------------+ | | |
7949// | | | |
7950// V V +---------------+ |
7951// +------------+ +------------+ | |
7952// | TRUNCATE | | TRUNCATE | | +-------------------------+
7953// +------------+ +------------+ | |
7954// | | | |
7955// V V | |
7956// +------------+ +------------+ | |
7957// | ZERO_EXT | | ZERO_EXT | | |
7958// +------------+ +------------+ | |
7959// | | | |
7960// V V | |
7961// +----------------+ | |
7962// | AND | | |
7963// +----------------+ | |
7964// | | |
7965// +---------------+ | |
7966// | | |
7967// V V V
7968// +-------------+
7969// | CMP |
7970// +-------------+
7974 ISD::CondCode CC = N->getOperandCondCode(2);
7975
7976 if (N->getValueType(0) == Subtarget.getGRLenVT())
7977 if (SDValue V = foldVMskZeroTest(N->getOperand(0), N->getOperand(1), CC,
7978 SDLoc(N), DAG, Subtarget))
7979 return V;
7980
7981 SDNode *AndNode = N->getOperand(0).getNode();
7982 if (AndNode->getOpcode() != ISD::AND)
7983 return SDValue();
7984
7985 SDValue AndInputValue2 = AndNode->getOperand(1);
7986 if (AndInputValue2.getOpcode() != ISD::ZERO_EXTEND)
7987 return SDValue();
7988
7989 SDValue CmpInputValue = N->getOperand(1);
7990 SDValue AndInputValue1 = AndNode->getOperand(0);
7991 if (AndInputValue1.getOpcode() == ISD::XOR) {
7992 if (CC != ISD::SETEQ && CC != ISD::SETNE)
7993 return SDValue();
7994 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndInputValue1.getOperand(1));
7995 if (!CN || !CN->isAllOnes())
7996 return SDValue();
7997 CN = dyn_cast<ConstantSDNode>(CmpInputValue);
7998 if (!CN || !CN->isZero())
7999 return SDValue();
8000 AndInputValue1 = AndInputValue1.getOperand(0);
8001 if (AndInputValue1.getOpcode() != ISD::ZERO_EXTEND)
8002 return SDValue();
8003 } else if (AndInputValue1.getOpcode() == ISD::ZERO_EXTEND) {
8004 if (AndInputValue2 != CmpInputValue)
8005 return SDValue();
8006 } else {
8007 return SDValue();
8008 }
8009
8010 SDValue TruncValue1 = AndInputValue1.getNode()->getOperand(0);
8011 if (TruncValue1.getOpcode() != ISD::TRUNCATE)
8012 return SDValue();
8013
8014 SDValue TruncValue2 = AndInputValue2.getNode()->getOperand(0);
8015 if (TruncValue2.getOpcode() != ISD::TRUNCATE)
8016 return SDValue();
8017
8018 SDValue TruncInputValue1 = TruncValue1.getNode()->getOperand(0);
8019 SDValue TruncInputValue2 = TruncValue2.getNode()->getOperand(0);
8020 ISD::LoadExtType ExtType1;
8021 ISD::LoadExtType ExtType2;
8022
8023 if (!checkValueWidth(TruncInputValue1, ExtType1) ||
8024 !checkValueWidth(TruncInputValue2, ExtType2))
8025 return SDValue();
8026
8027 if (TruncInputValue1->getValueType(0) != TruncInputValue2->getValueType(0) ||
8028 AndNode->getValueType(0) != TruncInputValue1->getValueType(0))
8029 return SDValue();
8030
8031 if ((ExtType2 != ISD::ZEXTLOAD) &&
8032 ((ExtType2 != ISD::SEXTLOAD) && (ExtType1 != ISD::SEXTLOAD)))
8033 return SDValue();
8034
8035 // These truncation and zero-extension nodes are not necessary, remove them.
8036 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N), AndNode->getValueType(0),
8037 TruncInputValue1, TruncInputValue2);
8038 SDValue NewSetCC =
8039 DAG.getSetCC(SDLoc(N), N->getValueType(0), NewAnd, TruncInputValue2, CC);
8040 DAG.ReplaceAllUsesWith(N, NewSetCC.getNode());
8041 return SDValue(N, 0);
8042}
8043
8044// Strip a single outer ISD::SIGN_EXTEND_INREG from \p V, if present, and
8045// return the inner value together with the narrow VT it was extending
8046// from. If no such node is present, returns \p V unchanged and an invalid
8047// EVT.
8048//
8049// i32 (and other sub-GRLen) arithmetic is legalized to operate on the full
8050// GRLen-width register, with a `sign_extend_inreg` re-normalizing the
8051// result back into the narrow type's range afterwards (see e.g. the
8052// `add i32` -> `add` + `sign_extend_inreg ..., i32` legalization). Any
8053// combine that reassociates such a binop must track and reapply this
8054// extension, otherwise the transformed code can produce a value whose
8055// high bits no longer match the narrow-type semantics.
8056static std::pair<SDValue, EVT> stripSignExtendInReg(SDValue V) {
8057 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
8058 return {V.getOperand(0), cast<VTSDNode>(V.getOperand(1))->getVT()};
8059 return {V, EVT()};
8060}
8061
8062// Try to match \p BinV (after optionally stripping an outer
8063// sign_extend_inreg) as a supported binary operation that has \p X as one
8064// of its operands, returning the matched opcode, the other operand (the
8065// "delta"), and the narrow VT of the sign_extend_inreg that was stripped
8066// (invalid EVT if none was present).
8067//
8068// For commutative ops (add/or/xor), \p X may be either operand, since
8069// `binop(X, Y) == binop(Y, X)` and the identity element (0) works on
8070// either side.
8071//
8072// For `sub`, the operation is NOT commutative: `sub(X, Y) != sub(Y, X)`.
8073// Only `sub(X, Y)` (i.e. \p X is the *minuend*, the first operand) can be
8074// rewritten using the identity `X - 0 == X`. If \p X were the *subtrahend*
8075// (second operand, i.e. the pattern is actually `sub(Y, X)`), there is no
8076// way to express `cond ? (Y - X) : X` (or the symmetric case) as
8077// `X op (select ...)` without introducing an extra negation, so that case
8078// must be rejected instead of "optimized" into worse code.
8079static std::tuple<unsigned, SDValue, EVT>
8081 auto [Inner, ExtVT] = stripSignExtendInReg(BinV);
8082
8083 unsigned Opc = Inner.getOpcode();
8084 switch (Opc) {
8085 case ISD::ADD:
8086 case ISD::OR:
8087 case ISD::XOR:
8088 if (Inner.getOperand(0) == X)
8089 return {Opc, Inner.getOperand(1), ExtVT};
8090 if (Inner.getOperand(1) == X)
8091 return {Opc, Inner.getOperand(0), ExtVT};
8092 return {0, SDValue(), EVT()};
8093 case ISD::SUB:
8094 // Only accept X as the minuend (first operand); see comment above.
8095 if (Inner.getOperand(0) == X)
8096 return {Opc, Inner.getOperand(1), ExtVT};
8097 return {0, SDValue(), EVT()};
8098 default:
8099 return {0, SDValue(), EVT()};
8100 }
8101}
8102
8103// Try to combine:
8104// select cond, binop(X, Y), X -> binop X, (select cond, Y, 0)
8105// select cond, X, binop(X, Y) -> binop X, (select cond, 0, Y)
8106// for binop in {add, or, xor, sub}, where 0 is the identity element of the
8107// respective operation, additionally handling the common legalized form
8108// where the binop result is wrapped in a `sign_extend_inreg` (as happens
8109// for sub-GRLen types such as i32 on a 64-bit GRLen target). See
8110// matchBinOpWithSharedOperand() for the restrictions applied to
8111// non-commutative operations (currently only `sub`).
8115 if (DCI.isBeforeLegalizeOps())
8116 return SDValue();
8117
8118 EVT VT = N->getValueType(0);
8119 // Restrict to the scalar GRLen integer type that maskeqz/masknez operate
8120 // on; this also naturally excludes float and vector selects.
8121 if (VT != Subtarget.getGRLenVT())
8122 return SDValue();
8123
8124 SDValue Cond = N->getOperand(0);
8125 SDValue TrueV = N->getOperand(1);
8126 SDValue FalseV = N->getOperand(2);
8127 SDLoc DL(N);
8128
8129 auto TryFold = [&](SDValue BinV, SDValue SharedV,
8130 bool BinIsTrueArm) -> SDValue {
8131 auto [Opc, Delta, ExtVT] = matchBinOpWithSharedOperand(BinV, SharedV);
8132 if (!Opc)
8133 return SDValue();
8134
8135 // Avoid infinite combine loops: bail out if Delta is trivially the
8136 // same node we would otherwise be selecting on (shouldn't normally
8137 // happen, but guards against degenerate/self-referential IR).
8138 if (Delta.getNode() == N)
8139 return SDValue();
8140
8141 SDValue Zero = DAG.getConstant(0, DL, VT);
8142 SDValue NewSel = BinIsTrueArm ? DAG.getSelect(DL, VT, Cond, Delta, Zero)
8143 : DAG.getSelect(DL, VT, Cond, Zero, Delta);
8144 SDValue NewBin = DAG.getNode(Opc, DL, VT, SharedV, NewSel);
8145
8146 // If the original binop result was normalized back into a narrower
8147 // type via sign_extend_inreg (e.g. i32 arithmetic on a 64-bit GRLen
8148 // target), the new binop must be re-normalized the same way: SharedV
8149 // is already known-sign-extended for that narrow type, but NewSel
8150 // (Delta or 0, selected) combined with SharedV via Opc can still
8151 // produce a 64-bit result whose high bits don't match the narrow
8152 // type's sign-extended representation.
8153 if (ExtVT != EVT())
8154 NewBin = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, NewBin,
8155 DAG.getValueType(ExtVT));
8156
8157 return NewBin;
8158 };
8159
8160 if (SDValue R = TryFold(TrueV, FalseV, /*BinIsTrueArm=*/true))
8161 return R;
8162 if (SDValue R = TryFold(FalseV, TrueV, /*BinIsTrueArm=*/false))
8163 return R;
8164
8165 return SDValue();
8166}
8167
8168// Combine (loongarch_bitrev_w (loongarch_revb_2w X)) to loongarch_bitrev_4b.
8172 if (DCI.isBeforeLegalizeOps())
8173 return SDValue();
8174
8175 SDValue Src = N->getOperand(0);
8176 if (Src.getOpcode() != LoongArchISD::REVB_2W)
8177 return SDValue();
8178
8179 return DAG.getNode(LoongArchISD::BITREV_4B, SDLoc(N), N->getValueType(0),
8180 Src.getOperand(0));
8181}
8182
8183// Perform common combines for BR_CC and SELECT_CC conditions.
8184static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL,
8186 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8187
8188 // As far as arithmetic right shift always saves the sign,
8189 // shift can be omitted.
8190 // Fold setlt (sra X, N), 0 -> setlt X, 0 and
8191 // setge (sra X, N), 0 -> setge X, 0
8192 if (isNullConstant(RHS) && (CCVal == ISD::SETGE || CCVal == ISD::SETLT) &&
8193 LHS.getOpcode() == ISD::SRA) {
8194 LHS = LHS.getOperand(0);
8195 return true;
8196 }
8197
8198 if (!ISD::isIntEqualitySetCC(CCVal))
8199 return false;
8200
8201 // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt)
8202 // Sometimes the setcc is introduced after br_cc/select_cc has been formed.
8203 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8204 LHS.getOperand(0).getValueType() == Subtarget.getGRLenVT()) {
8205 // If we're looking for eq 0 instead of ne 0, we need to invert the
8206 // condition.
8207 bool Invert = CCVal == ISD::SETEQ;
8208 CCVal = LHS.getOperandCondCode(2);
8209 if (Invert)
8210 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8211
8212 RHS = LHS.getOperand(1);
8213 LHS = LHS.getOperand(0);
8214 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8215
8216 CC = DAG.getCondCode(CCVal);
8217 return true;
8218 }
8219
8220 // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, GRLen-1-C), 0, ge/lt)
8221 if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() &&
8222 LHS.getOperand(1).getOpcode() == ISD::Constant) {
8223 SDValue LHS0 = LHS.getOperand(0);
8224 if (LHS0.getOpcode() == ISD::AND &&
8225 LHS0.getOperand(1).getOpcode() == ISD::Constant) {
8226 uint64_t Mask = LHS0.getConstantOperandVal(1);
8227 uint64_t ShAmt = LHS.getConstantOperandVal(1);
8228 if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) {
8229 CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
8230 CC = DAG.getCondCode(CCVal);
8231
8232 ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt;
8233 LHS = LHS0.getOperand(0);
8234 if (ShAmt != 0)
8235 LHS =
8236 DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0),
8237 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
8238 return true;
8239 }
8240 }
8241 }
8242
8243 // (X, 1, setne) -> (X, 0, seteq) if we can prove X is 0/1.
8244 // This can occur when legalizing some floating point comparisons.
8245 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8246 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8247 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8248 CC = DAG.getCondCode(CCVal);
8249 RHS = DAG.getConstant(0, DL, LHS.getValueType());
8250 return true;
8251 }
8252
8253 // Fold ((shl (extract_vector_elt X, I), GRLen - EleBits)), 0, eq/ne) ->
8254 // ((extract_vector_elt X, I), 0, eq/ne)
8255 if (isNullConstant(RHS) && (CCVal == ISD::SETEQ || CCVal == ISD::SETNE) &&
8256 LHS.getOpcode() == ISD::SHL && LHS.hasOneUse() &&
8257 isa<ConstantSDNode>(LHS.getOperand(1))) {
8258 SDValue Ext = LHS.getOperand(0);
8259 unsigned Sht = LHS.getConstantOperandVal(1);
8260 if (Ext.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8261 SDValue Vec = Ext.getOperand(0);
8262 unsigned EleBits = Vec.getScalarValueSizeInBits();
8263 if ((EleBits + Sht) == Subtarget.getGRLen()) {
8264 LHS = Ext;
8265 return true;
8266 }
8267 }
8268 }
8269
8270 // Fold (C1, C2, cond) -> (0, 0, seteq/setne)
8272 const LoongArchTargetLowering *TLI = Subtarget.getTargetLowering();
8273 EVT VT = LHS.getValueType();
8274 EVT SetCCResVT =
8275 TLI->getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8276 if (SDValue Folded = DAG.FoldSetCC(SetCCResVT, LHS, RHS, CCVal, DL)) {
8277 LHS = DAG.getConstant(0, DL, VT);
8278 RHS = DAG.getConstant(0, DL, VT);
8280 return true;
8281 }
8282 }
8283
8284 return false;
8285}
8286
8290 SDValue LHS = N->getOperand(1);
8291 SDValue RHS = N->getOperand(2);
8292 SDValue CC = N->getOperand(3);
8293 SDLoc DL(N);
8294
8295 // CC was folded into V, so always return ISD::SETNE is fine.
8297 DL, DAG, Subtarget))
8298 return DAG.getNode(LoongArchISD::BR_CC, DL, N->getValueType(0),
8299 N->getOperand(0), V,
8300 DAG.getConstant(0, DL, Subtarget.getGRLenVT()),
8301 DAG.getCondCode(ISD::SETNE), N->getOperand(4));
8302
8303 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
8304 return DAG.getNode(LoongArchISD::BR_CC, DL, N->getValueType(0),
8305 N->getOperand(0), LHS, RHS, CC, N->getOperand(4));
8306
8307 return SDValue();
8308}
8309
8313 // Transform
8314 SDValue LHS = N->getOperand(0);
8315 SDValue RHS = N->getOperand(1);
8316 SDValue CC = N->getOperand(2);
8317 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8318 SDValue TrueV = N->getOperand(3);
8319 SDValue FalseV = N->getOperand(4);
8320 SDLoc DL(N);
8321 EVT VT = N->getValueType(0);
8322
8323 // If the True and False values are the same, we don't need a select_cc.
8324 if (TrueV == FalseV)
8325 return TrueV;
8326
8327 // (select (x < 0), y, z) -> x >> (GRLEN - 1) & (y - z) + z
8328 // (select (x >= 0), y, z) -> x >> (GRLEN - 1) & (z - y) + y
8329 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
8331 (CCVal == ISD::CondCode::SETLT || CCVal == ISD::CondCode::SETGE)) {
8332 if (CCVal == ISD::CondCode::SETGE)
8333 std::swap(TrueV, FalseV);
8334
8335 int64_t TrueSImm = cast<ConstantSDNode>(TrueV)->getSExtValue();
8336 int64_t FalseSImm = cast<ConstantSDNode>(FalseV)->getSExtValue();
8337 // Only handle simm12, if it is not in this range, it can be considered as
8338 // register.
8339 if (isInt<12>(TrueSImm) && isInt<12>(FalseSImm) &&
8340 isInt<12>(TrueSImm - FalseSImm)) {
8341 SDValue SRA =
8342 DAG.getNode(ISD::SRA, DL, VT, LHS,
8343 DAG.getConstant(Subtarget.getGRLen() - 1, DL, VT));
8344 SDValue AND =
8345 DAG.getNode(ISD::AND, DL, VT, SRA,
8346 DAG.getSignedConstant(TrueSImm - FalseSImm, DL, VT));
8347 return DAG.getNode(ISD::ADD, DL, VT, AND, FalseV);
8348 }
8349
8350 if (CCVal == ISD::CondCode::SETGE)
8351 std::swap(TrueV, FalseV);
8352 }
8353
8354 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
8355 return DAG.getNode(LoongArchISD::SELECT_CC, DL, N->getValueType(0),
8356 {LHS, RHS, CC, TrueV, FalseV});
8357
8358 return SDValue();
8359}
8360
8361template <unsigned N>
8363 SelectionDAG &DAG,
8365 bool IsSigned = false) {
8366 SDLoc DL(Node);
8367 auto *CImm = cast<ConstantSDNode>(Node->getOperand(ImmOp));
8368 // Check the ImmArg.
8369 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
8370 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
8371 DAG.getContext()->emitError(Node->getOperationName(0) +
8372 ": argument out of range.");
8373 return DAG.getNode(ISD::UNDEF, DL, Subtarget.getGRLenVT());
8374 }
8375 return DAG.getConstant(CImm->getZExtValue(), DL, Subtarget.getGRLenVT());
8376}
8377
8378template <unsigned N>
8379static SDValue lowerVectorSplatImm(SDNode *Node, unsigned ImmOp,
8380 SelectionDAG &DAG, bool IsSigned = false) {
8381 SDLoc DL(Node);
8382 EVT ResTy = Node->getValueType(0);
8383 auto *CImm = cast<ConstantSDNode>(Node->getOperand(ImmOp));
8384
8385 // Check the ImmArg.
8386 if ((IsSigned && !isInt<N>(CImm->getSExtValue())) ||
8387 (!IsSigned && !isUInt<N>(CImm->getZExtValue()))) {
8388 DAG.getContext()->emitError(Node->getOperationName(0) +
8389 ": argument out of range.");
8390 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8391 }
8392 return DAG.getConstant(
8394 IsSigned ? CImm->getSExtValue() : CImm->getZExtValue(), IsSigned),
8395 DL, ResTy);
8396}
8397
8399 SDLoc DL(Node);
8400 EVT ResTy = Node->getValueType(0);
8401 SDValue Vec = Node->getOperand(2);
8402 SDValue Mask = DAG.getConstant(Vec.getScalarValueSizeInBits() - 1, DL, ResTy);
8403 return DAG.getNode(ISD::AND, DL, ResTy, Vec, Mask);
8404}
8405
8407 SDLoc DL(Node);
8408 EVT ResTy = Node->getValueType(0);
8409 SDValue One = DAG.getConstant(1, DL, ResTy);
8410 SDValue Bit =
8411 DAG.getNode(ISD::SHL, DL, ResTy, One, truncateVecElts(Node, DAG));
8412
8413 return DAG.getNode(ISD::AND, DL, ResTy, Node->getOperand(1),
8414 DAG.getNOT(DL, Bit, ResTy));
8415}
8416
8417template <unsigned N>
8419 SDLoc DL(Node);
8420 EVT ResTy = Node->getValueType(0);
8421 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8422 // Check the unsigned ImmArg.
8423 if (!isUInt<N>(CImm->getZExtValue())) {
8424 DAG.getContext()->emitError(Node->getOperationName(0) +
8425 ": argument out of range.");
8426 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8427 }
8428
8429 APInt BitImm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8430 SDValue Mask = DAG.getConstant(~BitImm, DL, ResTy);
8431
8432 return DAG.getNode(ISD::AND, DL, ResTy, Node->getOperand(1), Mask);
8433}
8434
8435template <unsigned N>
8437 SDLoc DL(Node);
8438 EVT ResTy = Node->getValueType(0);
8439 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8440 // Check the unsigned ImmArg.
8441 if (!isUInt<N>(CImm->getZExtValue())) {
8442 DAG.getContext()->emitError(Node->getOperationName(0) +
8443 ": argument out of range.");
8444 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8445 }
8446
8447 APInt Imm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8448 SDValue BitImm = DAG.getConstant(Imm, DL, ResTy);
8449 return DAG.getNode(ISD::OR, DL, ResTy, Node->getOperand(1), BitImm);
8450}
8451
8452template <unsigned N>
8454 SDLoc DL(Node);
8455 EVT ResTy = Node->getValueType(0);
8456 auto *CImm = cast<ConstantSDNode>(Node->getOperand(2));
8457 // Check the unsigned ImmArg.
8458 if (!isUInt<N>(CImm->getZExtValue())) {
8459 DAG.getContext()->emitError(Node->getOperationName(0) +
8460 ": argument out of range.");
8461 return DAG.getNode(ISD::UNDEF, DL, ResTy);
8462 }
8463
8464 APInt Imm = APInt(ResTy.getScalarSizeInBits(), 1) << CImm->getAPIntValue();
8465 SDValue BitImm = DAG.getConstant(Imm, DL, ResTy);
8466 return DAG.getNode(ISD::XOR, DL, ResTy, Node->getOperand(1), BitImm);
8467}
8468
8469template <unsigned W>
8471 unsigned ResOp) {
8472 unsigned Imm = N->getConstantOperandVal(2);
8473 if (!isUInt<W>(Imm)) {
8474 const StringRef ErrorMsg = "argument out of range";
8475 DAG.getContext()->emitError(N->getOperationName(0) + ": " + ErrorMsg + ".");
8476 return DAG.getUNDEF(N->getValueType(0));
8477 }
8478 SDLoc DL(N);
8479 SDValue Vec = N->getOperand(1);
8480 SDValue Idx = DAG.getConstant(Imm, DL, MVT::i32);
8482 return DAG.getNode(ResOp, DL, N->getValueType(0), Vec, Idx, EltVT);
8483}
8484
8485static SDValue
8489 SDLoc DL(N);
8490 switch (N->getConstantOperandVal(0)) {
8491 default:
8492 break;
8493 case Intrinsic::loongarch_lsx_vadd_b:
8494 case Intrinsic::loongarch_lsx_vadd_h:
8495 case Intrinsic::loongarch_lsx_vadd_w:
8496 case Intrinsic::loongarch_lsx_vadd_d:
8497 case Intrinsic::loongarch_lasx_xvadd_b:
8498 case Intrinsic::loongarch_lasx_xvadd_h:
8499 case Intrinsic::loongarch_lasx_xvadd_w:
8500 case Intrinsic::loongarch_lasx_xvadd_d:
8501 return DAG.getNode(ISD::ADD, DL, N->getValueType(0), N->getOperand(1),
8502 N->getOperand(2));
8503 case Intrinsic::loongarch_lsx_vaddi_bu:
8504 case Intrinsic::loongarch_lsx_vaddi_hu:
8505 case Intrinsic::loongarch_lsx_vaddi_wu:
8506 case Intrinsic::loongarch_lsx_vaddi_du:
8507 case Intrinsic::loongarch_lasx_xvaddi_bu:
8508 case Intrinsic::loongarch_lasx_xvaddi_hu:
8509 case Intrinsic::loongarch_lasx_xvaddi_wu:
8510 case Intrinsic::loongarch_lasx_xvaddi_du:
8511 return DAG.getNode(ISD::ADD, DL, N->getValueType(0), N->getOperand(1),
8512 lowerVectorSplatImm<5>(N, 2, DAG));
8513 case Intrinsic::loongarch_lsx_vsub_b:
8514 case Intrinsic::loongarch_lsx_vsub_h:
8515 case Intrinsic::loongarch_lsx_vsub_w:
8516 case Intrinsic::loongarch_lsx_vsub_d:
8517 case Intrinsic::loongarch_lasx_xvsub_b:
8518 case Intrinsic::loongarch_lasx_xvsub_h:
8519 case Intrinsic::loongarch_lasx_xvsub_w:
8520 case Intrinsic::loongarch_lasx_xvsub_d:
8521 return DAG.getNode(ISD::SUB, DL, N->getValueType(0), N->getOperand(1),
8522 N->getOperand(2));
8523 case Intrinsic::loongarch_lsx_vsubi_bu:
8524 case Intrinsic::loongarch_lsx_vsubi_hu:
8525 case Intrinsic::loongarch_lsx_vsubi_wu:
8526 case Intrinsic::loongarch_lsx_vsubi_du:
8527 case Intrinsic::loongarch_lasx_xvsubi_bu:
8528 case Intrinsic::loongarch_lasx_xvsubi_hu:
8529 case Intrinsic::loongarch_lasx_xvsubi_wu:
8530 case Intrinsic::loongarch_lasx_xvsubi_du:
8531 return DAG.getNode(ISD::SUB, DL, N->getValueType(0), N->getOperand(1),
8532 lowerVectorSplatImm<5>(N, 2, DAG));
8533 case Intrinsic::loongarch_lsx_vneg_b:
8534 case Intrinsic::loongarch_lsx_vneg_h:
8535 case Intrinsic::loongarch_lsx_vneg_w:
8536 case Intrinsic::loongarch_lsx_vneg_d:
8537 case Intrinsic::loongarch_lasx_xvneg_b:
8538 case Intrinsic::loongarch_lasx_xvneg_h:
8539 case Intrinsic::loongarch_lasx_xvneg_w:
8540 case Intrinsic::loongarch_lasx_xvneg_d:
8541 return DAG.getNode(
8542 ISD::SUB, DL, N->getValueType(0),
8543 DAG.getConstant(
8544 APInt(N->getValueType(0).getScalarType().getSizeInBits(), 0,
8545 /*isSigned=*/true),
8546 SDLoc(N), N->getValueType(0)),
8547 N->getOperand(1));
8548 case Intrinsic::loongarch_lsx_vmax_b:
8549 case Intrinsic::loongarch_lsx_vmax_h:
8550 case Intrinsic::loongarch_lsx_vmax_w:
8551 case Intrinsic::loongarch_lsx_vmax_d:
8552 case Intrinsic::loongarch_lasx_xvmax_b:
8553 case Intrinsic::loongarch_lasx_xvmax_h:
8554 case Intrinsic::loongarch_lasx_xvmax_w:
8555 case Intrinsic::loongarch_lasx_xvmax_d:
8556 return DAG.getNode(ISD::SMAX, DL, N->getValueType(0), N->getOperand(1),
8557 N->getOperand(2));
8558 case Intrinsic::loongarch_lsx_vmax_bu:
8559 case Intrinsic::loongarch_lsx_vmax_hu:
8560 case Intrinsic::loongarch_lsx_vmax_wu:
8561 case Intrinsic::loongarch_lsx_vmax_du:
8562 case Intrinsic::loongarch_lasx_xvmax_bu:
8563 case Intrinsic::loongarch_lasx_xvmax_hu:
8564 case Intrinsic::loongarch_lasx_xvmax_wu:
8565 case Intrinsic::loongarch_lasx_xvmax_du:
8566 return DAG.getNode(ISD::UMAX, DL, N->getValueType(0), N->getOperand(1),
8567 N->getOperand(2));
8568 case Intrinsic::loongarch_lsx_vmaxi_b:
8569 case Intrinsic::loongarch_lsx_vmaxi_h:
8570 case Intrinsic::loongarch_lsx_vmaxi_w:
8571 case Intrinsic::loongarch_lsx_vmaxi_d:
8572 case Intrinsic::loongarch_lasx_xvmaxi_b:
8573 case Intrinsic::loongarch_lasx_xvmaxi_h:
8574 case Intrinsic::loongarch_lasx_xvmaxi_w:
8575 case Intrinsic::loongarch_lasx_xvmaxi_d:
8576 return DAG.getNode(ISD::SMAX, DL, N->getValueType(0), N->getOperand(1),
8577 lowerVectorSplatImm<5>(N, 2, DAG, /*IsSigned=*/true));
8578 case Intrinsic::loongarch_lsx_vmaxi_bu:
8579 case Intrinsic::loongarch_lsx_vmaxi_hu:
8580 case Intrinsic::loongarch_lsx_vmaxi_wu:
8581 case Intrinsic::loongarch_lsx_vmaxi_du:
8582 case Intrinsic::loongarch_lasx_xvmaxi_bu:
8583 case Intrinsic::loongarch_lasx_xvmaxi_hu:
8584 case Intrinsic::loongarch_lasx_xvmaxi_wu:
8585 case Intrinsic::loongarch_lasx_xvmaxi_du:
8586 return DAG.getNode(ISD::UMAX, DL, N->getValueType(0), N->getOperand(1),
8587 lowerVectorSplatImm<5>(N, 2, DAG));
8588 case Intrinsic::loongarch_lsx_vmin_b:
8589 case Intrinsic::loongarch_lsx_vmin_h:
8590 case Intrinsic::loongarch_lsx_vmin_w:
8591 case Intrinsic::loongarch_lsx_vmin_d:
8592 case Intrinsic::loongarch_lasx_xvmin_b:
8593 case Intrinsic::loongarch_lasx_xvmin_h:
8594 case Intrinsic::loongarch_lasx_xvmin_w:
8595 case Intrinsic::loongarch_lasx_xvmin_d:
8596 return DAG.getNode(ISD::SMIN, DL, N->getValueType(0), N->getOperand(1),
8597 N->getOperand(2));
8598 case Intrinsic::loongarch_lsx_vmin_bu:
8599 case Intrinsic::loongarch_lsx_vmin_hu:
8600 case Intrinsic::loongarch_lsx_vmin_wu:
8601 case Intrinsic::loongarch_lsx_vmin_du:
8602 case Intrinsic::loongarch_lasx_xvmin_bu:
8603 case Intrinsic::loongarch_lasx_xvmin_hu:
8604 case Intrinsic::loongarch_lasx_xvmin_wu:
8605 case Intrinsic::loongarch_lasx_xvmin_du:
8606 return DAG.getNode(ISD::UMIN, DL, N->getValueType(0), N->getOperand(1),
8607 N->getOperand(2));
8608 case Intrinsic::loongarch_lsx_vmini_b:
8609 case Intrinsic::loongarch_lsx_vmini_h:
8610 case Intrinsic::loongarch_lsx_vmini_w:
8611 case Intrinsic::loongarch_lsx_vmini_d:
8612 case Intrinsic::loongarch_lasx_xvmini_b:
8613 case Intrinsic::loongarch_lasx_xvmini_h:
8614 case Intrinsic::loongarch_lasx_xvmini_w:
8615 case Intrinsic::loongarch_lasx_xvmini_d:
8616 return DAG.getNode(ISD::SMIN, DL, N->getValueType(0), N->getOperand(1),
8617 lowerVectorSplatImm<5>(N, 2, DAG, /*IsSigned=*/true));
8618 case Intrinsic::loongarch_lsx_vmini_bu:
8619 case Intrinsic::loongarch_lsx_vmini_hu:
8620 case Intrinsic::loongarch_lsx_vmini_wu:
8621 case Intrinsic::loongarch_lsx_vmini_du:
8622 case Intrinsic::loongarch_lasx_xvmini_bu:
8623 case Intrinsic::loongarch_lasx_xvmini_hu:
8624 case Intrinsic::loongarch_lasx_xvmini_wu:
8625 case Intrinsic::loongarch_lasx_xvmini_du:
8626 return DAG.getNode(ISD::UMIN, DL, N->getValueType(0), N->getOperand(1),
8627 lowerVectorSplatImm<5>(N, 2, DAG));
8628 case Intrinsic::loongarch_lsx_vmul_b:
8629 case Intrinsic::loongarch_lsx_vmul_h:
8630 case Intrinsic::loongarch_lsx_vmul_w:
8631 case Intrinsic::loongarch_lsx_vmul_d:
8632 case Intrinsic::loongarch_lasx_xvmul_b:
8633 case Intrinsic::loongarch_lasx_xvmul_h:
8634 case Intrinsic::loongarch_lasx_xvmul_w:
8635 case Intrinsic::loongarch_lasx_xvmul_d:
8636 return DAG.getNode(ISD::MUL, DL, N->getValueType(0), N->getOperand(1),
8637 N->getOperand(2));
8638 case Intrinsic::loongarch_lsx_vmadd_b:
8639 case Intrinsic::loongarch_lsx_vmadd_h:
8640 case Intrinsic::loongarch_lsx_vmadd_w:
8641 case Intrinsic::loongarch_lsx_vmadd_d:
8642 case Intrinsic::loongarch_lasx_xvmadd_b:
8643 case Intrinsic::loongarch_lasx_xvmadd_h:
8644 case Intrinsic::loongarch_lasx_xvmadd_w:
8645 case Intrinsic::loongarch_lasx_xvmadd_d: {
8646 EVT ResTy = N->getValueType(0);
8647 return DAG.getNode(ISD::ADD, SDLoc(N), ResTy, N->getOperand(1),
8648 DAG.getNode(ISD::MUL, SDLoc(N), ResTy, N->getOperand(2),
8649 N->getOperand(3)));
8650 }
8651 case Intrinsic::loongarch_lsx_vmsub_b:
8652 case Intrinsic::loongarch_lsx_vmsub_h:
8653 case Intrinsic::loongarch_lsx_vmsub_w:
8654 case Intrinsic::loongarch_lsx_vmsub_d:
8655 case Intrinsic::loongarch_lasx_xvmsub_b:
8656 case Intrinsic::loongarch_lasx_xvmsub_h:
8657 case Intrinsic::loongarch_lasx_xvmsub_w:
8658 case Intrinsic::loongarch_lasx_xvmsub_d: {
8659 EVT ResTy = N->getValueType(0);
8660 return DAG.getNode(ISD::SUB, SDLoc(N), ResTy, N->getOperand(1),
8661 DAG.getNode(ISD::MUL, SDLoc(N), ResTy, N->getOperand(2),
8662 N->getOperand(3)));
8663 }
8664 case Intrinsic::loongarch_lsx_vdiv_b:
8665 case Intrinsic::loongarch_lsx_vdiv_h:
8666 case Intrinsic::loongarch_lsx_vdiv_w:
8667 case Intrinsic::loongarch_lsx_vdiv_d:
8668 case Intrinsic::loongarch_lasx_xvdiv_b:
8669 case Intrinsic::loongarch_lasx_xvdiv_h:
8670 case Intrinsic::loongarch_lasx_xvdiv_w:
8671 case Intrinsic::loongarch_lasx_xvdiv_d:
8672 return DAG.getNode(ISD::SDIV, DL, N->getValueType(0), N->getOperand(1),
8673 N->getOperand(2));
8674 case Intrinsic::loongarch_lsx_vdiv_bu:
8675 case Intrinsic::loongarch_lsx_vdiv_hu:
8676 case Intrinsic::loongarch_lsx_vdiv_wu:
8677 case Intrinsic::loongarch_lsx_vdiv_du:
8678 case Intrinsic::loongarch_lasx_xvdiv_bu:
8679 case Intrinsic::loongarch_lasx_xvdiv_hu:
8680 case Intrinsic::loongarch_lasx_xvdiv_wu:
8681 case Intrinsic::loongarch_lasx_xvdiv_du:
8682 return DAG.getNode(ISD::UDIV, DL, N->getValueType(0), N->getOperand(1),
8683 N->getOperand(2));
8684 case Intrinsic::loongarch_lsx_vmod_b:
8685 case Intrinsic::loongarch_lsx_vmod_h:
8686 case Intrinsic::loongarch_lsx_vmod_w:
8687 case Intrinsic::loongarch_lsx_vmod_d:
8688 case Intrinsic::loongarch_lasx_xvmod_b:
8689 case Intrinsic::loongarch_lasx_xvmod_h:
8690 case Intrinsic::loongarch_lasx_xvmod_w:
8691 case Intrinsic::loongarch_lasx_xvmod_d:
8692 return DAG.getNode(ISD::SREM, DL, N->getValueType(0), N->getOperand(1),
8693 N->getOperand(2));
8694 case Intrinsic::loongarch_lsx_vmod_bu:
8695 case Intrinsic::loongarch_lsx_vmod_hu:
8696 case Intrinsic::loongarch_lsx_vmod_wu:
8697 case Intrinsic::loongarch_lsx_vmod_du:
8698 case Intrinsic::loongarch_lasx_xvmod_bu:
8699 case Intrinsic::loongarch_lasx_xvmod_hu:
8700 case Intrinsic::loongarch_lasx_xvmod_wu:
8701 case Intrinsic::loongarch_lasx_xvmod_du:
8702 return DAG.getNode(ISD::UREM, DL, N->getValueType(0), N->getOperand(1),
8703 N->getOperand(2));
8704 case Intrinsic::loongarch_lsx_vand_v:
8705 case Intrinsic::loongarch_lasx_xvand_v:
8706 return DAG.getNode(ISD::AND, DL, N->getValueType(0), N->getOperand(1),
8707 N->getOperand(2));
8708 case Intrinsic::loongarch_lsx_vor_v:
8709 case Intrinsic::loongarch_lasx_xvor_v:
8710 return DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8711 N->getOperand(2));
8712 case Intrinsic::loongarch_lsx_vxor_v:
8713 case Intrinsic::loongarch_lasx_xvxor_v:
8714 return DAG.getNode(ISD::XOR, DL, N->getValueType(0), N->getOperand(1),
8715 N->getOperand(2));
8716 case Intrinsic::loongarch_lsx_vnor_v:
8717 case Intrinsic::loongarch_lasx_xvnor_v: {
8718 SDValue Res = DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8719 N->getOperand(2));
8720 return DAG.getNOT(DL, Res, Res->getValueType(0));
8721 }
8722 case Intrinsic::loongarch_lsx_vandi_b:
8723 case Intrinsic::loongarch_lasx_xvandi_b:
8724 return DAG.getNode(ISD::AND, DL, N->getValueType(0), N->getOperand(1),
8725 lowerVectorSplatImm<8>(N, 2, DAG));
8726 case Intrinsic::loongarch_lsx_vori_b:
8727 case Intrinsic::loongarch_lasx_xvori_b:
8728 return DAG.getNode(ISD::OR, DL, N->getValueType(0), N->getOperand(1),
8729 lowerVectorSplatImm<8>(N, 2, DAG));
8730 case Intrinsic::loongarch_lsx_vxori_b:
8731 case Intrinsic::loongarch_lasx_xvxori_b:
8732 return DAG.getNode(ISD::XOR, DL, N->getValueType(0), N->getOperand(1),
8733 lowerVectorSplatImm<8>(N, 2, DAG));
8734 case Intrinsic::loongarch_lsx_vsll_b:
8735 case Intrinsic::loongarch_lsx_vsll_h:
8736 case Intrinsic::loongarch_lsx_vsll_w:
8737 case Intrinsic::loongarch_lsx_vsll_d:
8738 case Intrinsic::loongarch_lasx_xvsll_b:
8739 case Intrinsic::loongarch_lasx_xvsll_h:
8740 case Intrinsic::loongarch_lasx_xvsll_w:
8741 case Intrinsic::loongarch_lasx_xvsll_d:
8742 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8743 truncateVecElts(N, DAG));
8744 case Intrinsic::loongarch_lsx_vslli_b:
8745 case Intrinsic::loongarch_lasx_xvslli_b:
8746 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8747 lowerVectorSplatImm<3>(N, 2, DAG));
8748 case Intrinsic::loongarch_lsx_vslli_h:
8749 case Intrinsic::loongarch_lasx_xvslli_h:
8750 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8751 lowerVectorSplatImm<4>(N, 2, DAG));
8752 case Intrinsic::loongarch_lsx_vslli_w:
8753 case Intrinsic::loongarch_lasx_xvslli_w:
8754 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8755 lowerVectorSplatImm<5>(N, 2, DAG));
8756 case Intrinsic::loongarch_lsx_vslli_d:
8757 case Intrinsic::loongarch_lasx_xvslli_d:
8758 return DAG.getNode(ISD::SHL, DL, N->getValueType(0), N->getOperand(1),
8759 lowerVectorSplatImm<6>(N, 2, DAG));
8760 case Intrinsic::loongarch_lsx_vsrl_b:
8761 case Intrinsic::loongarch_lsx_vsrl_h:
8762 case Intrinsic::loongarch_lsx_vsrl_w:
8763 case Intrinsic::loongarch_lsx_vsrl_d:
8764 case Intrinsic::loongarch_lasx_xvsrl_b:
8765 case Intrinsic::loongarch_lasx_xvsrl_h:
8766 case Intrinsic::loongarch_lasx_xvsrl_w:
8767 case Intrinsic::loongarch_lasx_xvsrl_d:
8768 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8769 truncateVecElts(N, DAG));
8770 case Intrinsic::loongarch_lsx_vsrli_b:
8771 case Intrinsic::loongarch_lasx_xvsrli_b:
8772 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8773 lowerVectorSplatImm<3>(N, 2, DAG));
8774 case Intrinsic::loongarch_lsx_vsrli_h:
8775 case Intrinsic::loongarch_lasx_xvsrli_h:
8776 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8777 lowerVectorSplatImm<4>(N, 2, DAG));
8778 case Intrinsic::loongarch_lsx_vsrli_w:
8779 case Intrinsic::loongarch_lasx_xvsrli_w:
8780 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8781 lowerVectorSplatImm<5>(N, 2, DAG));
8782 case Intrinsic::loongarch_lsx_vsrli_d:
8783 case Intrinsic::loongarch_lasx_xvsrli_d:
8784 return DAG.getNode(ISD::SRL, DL, N->getValueType(0), N->getOperand(1),
8785 lowerVectorSplatImm<6>(N, 2, DAG));
8786 case Intrinsic::loongarch_lsx_vsra_b:
8787 case Intrinsic::loongarch_lsx_vsra_h:
8788 case Intrinsic::loongarch_lsx_vsra_w:
8789 case Intrinsic::loongarch_lsx_vsra_d:
8790 case Intrinsic::loongarch_lasx_xvsra_b:
8791 case Intrinsic::loongarch_lasx_xvsra_h:
8792 case Intrinsic::loongarch_lasx_xvsra_w:
8793 case Intrinsic::loongarch_lasx_xvsra_d:
8794 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8795 truncateVecElts(N, DAG));
8796 case Intrinsic::loongarch_lsx_vsrai_b:
8797 case Intrinsic::loongarch_lasx_xvsrai_b:
8798 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8799 lowerVectorSplatImm<3>(N, 2, DAG));
8800 case Intrinsic::loongarch_lsx_vsrai_h:
8801 case Intrinsic::loongarch_lasx_xvsrai_h:
8802 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8803 lowerVectorSplatImm<4>(N, 2, DAG));
8804 case Intrinsic::loongarch_lsx_vsrai_w:
8805 case Intrinsic::loongarch_lasx_xvsrai_w:
8806 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8807 lowerVectorSplatImm<5>(N, 2, DAG));
8808 case Intrinsic::loongarch_lsx_vsrai_d:
8809 case Intrinsic::loongarch_lasx_xvsrai_d:
8810 return DAG.getNode(ISD::SRA, DL, N->getValueType(0), N->getOperand(1),
8811 lowerVectorSplatImm<6>(N, 2, DAG));
8812 case Intrinsic::loongarch_lsx_vclz_b:
8813 case Intrinsic::loongarch_lsx_vclz_h:
8814 case Intrinsic::loongarch_lsx_vclz_w:
8815 case Intrinsic::loongarch_lsx_vclz_d:
8816 case Intrinsic::loongarch_lasx_xvclz_b:
8817 case Intrinsic::loongarch_lasx_xvclz_h:
8818 case Intrinsic::loongarch_lasx_xvclz_w:
8819 case Intrinsic::loongarch_lasx_xvclz_d:
8820 return DAG.getNode(ISD::CTLZ, DL, N->getValueType(0), N->getOperand(1));
8821 case Intrinsic::loongarch_lsx_vpcnt_b:
8822 case Intrinsic::loongarch_lsx_vpcnt_h:
8823 case Intrinsic::loongarch_lsx_vpcnt_w:
8824 case Intrinsic::loongarch_lsx_vpcnt_d:
8825 case Intrinsic::loongarch_lasx_xvpcnt_b:
8826 case Intrinsic::loongarch_lasx_xvpcnt_h:
8827 case Intrinsic::loongarch_lasx_xvpcnt_w:
8828 case Intrinsic::loongarch_lasx_xvpcnt_d:
8829 return DAG.getNode(ISD::CTPOP, DL, N->getValueType(0), N->getOperand(1));
8830 case Intrinsic::loongarch_lsx_vbitclr_b:
8831 case Intrinsic::loongarch_lsx_vbitclr_h:
8832 case Intrinsic::loongarch_lsx_vbitclr_w:
8833 case Intrinsic::loongarch_lsx_vbitclr_d:
8834 case Intrinsic::loongarch_lasx_xvbitclr_b:
8835 case Intrinsic::loongarch_lasx_xvbitclr_h:
8836 case Intrinsic::loongarch_lasx_xvbitclr_w:
8837 case Intrinsic::loongarch_lasx_xvbitclr_d:
8838 return lowerVectorBitClear(N, DAG);
8839 case Intrinsic::loongarch_lsx_vbitclri_b:
8840 case Intrinsic::loongarch_lasx_xvbitclri_b:
8841 return lowerVectorBitClearImm<3>(N, DAG);
8842 case Intrinsic::loongarch_lsx_vbitclri_h:
8843 case Intrinsic::loongarch_lasx_xvbitclri_h:
8844 return lowerVectorBitClearImm<4>(N, DAG);
8845 case Intrinsic::loongarch_lsx_vbitclri_w:
8846 case Intrinsic::loongarch_lasx_xvbitclri_w:
8847 return lowerVectorBitClearImm<5>(N, DAG);
8848 case Intrinsic::loongarch_lsx_vbitclri_d:
8849 case Intrinsic::loongarch_lasx_xvbitclri_d:
8850 return lowerVectorBitClearImm<6>(N, DAG);
8851 case Intrinsic::loongarch_lsx_vbitset_b:
8852 case Intrinsic::loongarch_lsx_vbitset_h:
8853 case Intrinsic::loongarch_lsx_vbitset_w:
8854 case Intrinsic::loongarch_lsx_vbitset_d:
8855 case Intrinsic::loongarch_lasx_xvbitset_b:
8856 case Intrinsic::loongarch_lasx_xvbitset_h:
8857 case Intrinsic::loongarch_lasx_xvbitset_w:
8858 case Intrinsic::loongarch_lasx_xvbitset_d: {
8859 EVT VecTy = N->getValueType(0);
8860 SDValue One = DAG.getConstant(1, DL, VecTy);
8861 return DAG.getNode(
8862 ISD::OR, DL, VecTy, N->getOperand(1),
8863 DAG.getNode(ISD::SHL, DL, VecTy, One, truncateVecElts(N, DAG)));
8864 }
8865 case Intrinsic::loongarch_lsx_vbitseti_b:
8866 case Intrinsic::loongarch_lasx_xvbitseti_b:
8867 return lowerVectorBitSetImm<3>(N, DAG);
8868 case Intrinsic::loongarch_lsx_vbitseti_h:
8869 case Intrinsic::loongarch_lasx_xvbitseti_h:
8870 return lowerVectorBitSetImm<4>(N, DAG);
8871 case Intrinsic::loongarch_lsx_vbitseti_w:
8872 case Intrinsic::loongarch_lasx_xvbitseti_w:
8873 return lowerVectorBitSetImm<5>(N, DAG);
8874 case Intrinsic::loongarch_lsx_vbitseti_d:
8875 case Intrinsic::loongarch_lasx_xvbitseti_d:
8876 return lowerVectorBitSetImm<6>(N, DAG);
8877 case Intrinsic::loongarch_lsx_vbitrev_b:
8878 case Intrinsic::loongarch_lsx_vbitrev_h:
8879 case Intrinsic::loongarch_lsx_vbitrev_w:
8880 case Intrinsic::loongarch_lsx_vbitrev_d:
8881 case Intrinsic::loongarch_lasx_xvbitrev_b:
8882 case Intrinsic::loongarch_lasx_xvbitrev_h:
8883 case Intrinsic::loongarch_lasx_xvbitrev_w:
8884 case Intrinsic::loongarch_lasx_xvbitrev_d: {
8885 EVT VecTy = N->getValueType(0);
8886 SDValue One = DAG.getConstant(1, DL, VecTy);
8887 return DAG.getNode(
8888 ISD::XOR, DL, VecTy, N->getOperand(1),
8889 DAG.getNode(ISD::SHL, DL, VecTy, One, truncateVecElts(N, DAG)));
8890 }
8891 case Intrinsic::loongarch_lsx_vbitrevi_b:
8892 case Intrinsic::loongarch_lasx_xvbitrevi_b:
8893 return lowerVectorBitRevImm<3>(N, DAG);
8894 case Intrinsic::loongarch_lsx_vbitrevi_h:
8895 case Intrinsic::loongarch_lasx_xvbitrevi_h:
8896 return lowerVectorBitRevImm<4>(N, DAG);
8897 case Intrinsic::loongarch_lsx_vbitrevi_w:
8898 case Intrinsic::loongarch_lasx_xvbitrevi_w:
8899 return lowerVectorBitRevImm<5>(N, DAG);
8900 case Intrinsic::loongarch_lsx_vbitrevi_d:
8901 case Intrinsic::loongarch_lasx_xvbitrevi_d:
8902 return lowerVectorBitRevImm<6>(N, DAG);
8903 case Intrinsic::loongarch_lsx_vfadd_s:
8904 case Intrinsic::loongarch_lsx_vfadd_d:
8905 case Intrinsic::loongarch_lasx_xvfadd_s:
8906 case Intrinsic::loongarch_lasx_xvfadd_d:
8907 return DAG.getNode(ISD::FADD, DL, N->getValueType(0), N->getOperand(1),
8908 N->getOperand(2));
8909 case Intrinsic::loongarch_lsx_vfsub_s:
8910 case Intrinsic::loongarch_lsx_vfsub_d:
8911 case Intrinsic::loongarch_lasx_xvfsub_s:
8912 case Intrinsic::loongarch_lasx_xvfsub_d:
8913 return DAG.getNode(ISD::FSUB, DL, N->getValueType(0), N->getOperand(1),
8914 N->getOperand(2));
8915 case Intrinsic::loongarch_lsx_vfmul_s:
8916 case Intrinsic::loongarch_lsx_vfmul_d:
8917 case Intrinsic::loongarch_lasx_xvfmul_s:
8918 case Intrinsic::loongarch_lasx_xvfmul_d:
8919 return DAG.getNode(ISD::FMUL, DL, N->getValueType(0), N->getOperand(1),
8920 N->getOperand(2));
8921 case Intrinsic::loongarch_lsx_vfdiv_s:
8922 case Intrinsic::loongarch_lsx_vfdiv_d:
8923 case Intrinsic::loongarch_lasx_xvfdiv_s:
8924 case Intrinsic::loongarch_lasx_xvfdiv_d:
8925 return DAG.getNode(ISD::FDIV, DL, N->getValueType(0), N->getOperand(1),
8926 N->getOperand(2));
8927 case Intrinsic::loongarch_lsx_vfmadd_s:
8928 case Intrinsic::loongarch_lsx_vfmadd_d:
8929 case Intrinsic::loongarch_lasx_xvfmadd_s:
8930 case Intrinsic::loongarch_lasx_xvfmadd_d:
8931 return DAG.getNode(ISD::FMA, DL, N->getValueType(0), N->getOperand(1),
8932 N->getOperand(2), N->getOperand(3));
8933 case Intrinsic::loongarch_lsx_vinsgr2vr_b:
8934 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8935 N->getOperand(1), N->getOperand(2),
8937 case Intrinsic::loongarch_lsx_vinsgr2vr_h:
8938 case Intrinsic::loongarch_lasx_xvinsgr2vr_w:
8939 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8940 N->getOperand(1), N->getOperand(2),
8942 case Intrinsic::loongarch_lsx_vinsgr2vr_w:
8943 case Intrinsic::loongarch_lasx_xvinsgr2vr_d:
8944 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8945 N->getOperand(1), N->getOperand(2),
8947 case Intrinsic::loongarch_lsx_vinsgr2vr_d:
8948 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), N->getValueType(0),
8949 N->getOperand(1), N->getOperand(2),
8951 case Intrinsic::loongarch_lsx_vreplgr2vr_b:
8952 case Intrinsic::loongarch_lsx_vreplgr2vr_h:
8953 case Intrinsic::loongarch_lsx_vreplgr2vr_w:
8954 case Intrinsic::loongarch_lsx_vreplgr2vr_d:
8955 case Intrinsic::loongarch_lasx_xvreplgr2vr_b:
8956 case Intrinsic::loongarch_lasx_xvreplgr2vr_h:
8957 case Intrinsic::loongarch_lasx_xvreplgr2vr_w:
8958 case Intrinsic::loongarch_lasx_xvreplgr2vr_d:
8959 return DAG.getNode(LoongArchISD::VREPLGR2VR, DL, N->getValueType(0),
8960 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getGRLenVT(),
8961 N->getOperand(1)));
8962 case Intrinsic::loongarch_lsx_vreplve_b:
8963 case Intrinsic::loongarch_lsx_vreplve_h:
8964 case Intrinsic::loongarch_lsx_vreplve_w:
8965 case Intrinsic::loongarch_lsx_vreplve_d:
8966 case Intrinsic::loongarch_lasx_xvreplve_b:
8967 case Intrinsic::loongarch_lasx_xvreplve_h:
8968 case Intrinsic::loongarch_lasx_xvreplve_w:
8969 case Intrinsic::loongarch_lasx_xvreplve_d:
8970 return DAG.getNode(LoongArchISD::VREPLVE, DL, N->getValueType(0),
8971 N->getOperand(1),
8972 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getGRLenVT(),
8973 N->getOperand(2)));
8974 case Intrinsic::loongarch_lsx_vpickve2gr_b:
8975 if (!Subtarget.is64Bit())
8976 return lowerVectorPickVE2GR<4>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8977 break;
8978 case Intrinsic::loongarch_lsx_vpickve2gr_h:
8979 case Intrinsic::loongarch_lasx_xvpickve2gr_w:
8980 if (!Subtarget.is64Bit())
8981 return lowerVectorPickVE2GR<3>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8982 break;
8983 case Intrinsic::loongarch_lsx_vpickve2gr_w:
8984 if (!Subtarget.is64Bit())
8985 return lowerVectorPickVE2GR<2>(N, DAG, LoongArchISD::VPICK_SEXT_ELT);
8986 break;
8987 case Intrinsic::loongarch_lsx_vpickve2gr_bu:
8988 if (!Subtarget.is64Bit())
8989 return lowerVectorPickVE2GR<4>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8990 break;
8991 case Intrinsic::loongarch_lsx_vpickve2gr_hu:
8992 case Intrinsic::loongarch_lasx_xvpickve2gr_wu:
8993 if (!Subtarget.is64Bit())
8994 return lowerVectorPickVE2GR<3>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8995 break;
8996 case Intrinsic::loongarch_lsx_vpickve2gr_wu:
8997 if (!Subtarget.is64Bit())
8998 return lowerVectorPickVE2GR<2>(N, DAG, LoongArchISD::VPICK_ZEXT_ELT);
8999 break;
9000 case Intrinsic::loongarch_lsx_bz_b:
9001 case Intrinsic::loongarch_lsx_bz_h:
9002 case Intrinsic::loongarch_lsx_bz_w:
9003 case Intrinsic::loongarch_lsx_bz_d:
9004 case Intrinsic::loongarch_lasx_xbz_b:
9005 case Intrinsic::loongarch_lasx_xbz_h:
9006 case Intrinsic::loongarch_lasx_xbz_w:
9007 case Intrinsic::loongarch_lasx_xbz_d:
9008 if (!Subtarget.is64Bit())
9009 return DAG.getNode(LoongArchISD::VALL_ZERO, DL, N->getValueType(0),
9010 N->getOperand(1));
9011 break;
9012 case Intrinsic::loongarch_lsx_bz_v:
9013 case Intrinsic::loongarch_lasx_xbz_v:
9014 if (!Subtarget.is64Bit())
9015 return DAG.getNode(LoongArchISD::VANY_ZERO, DL, N->getValueType(0),
9016 N->getOperand(1));
9017 break;
9018 case Intrinsic::loongarch_lsx_bnz_b:
9019 case Intrinsic::loongarch_lsx_bnz_h:
9020 case Intrinsic::loongarch_lsx_bnz_w:
9021 case Intrinsic::loongarch_lsx_bnz_d:
9022 case Intrinsic::loongarch_lasx_xbnz_b:
9023 case Intrinsic::loongarch_lasx_xbnz_h:
9024 case Intrinsic::loongarch_lasx_xbnz_w:
9025 case Intrinsic::loongarch_lasx_xbnz_d:
9026 if (!Subtarget.is64Bit())
9027 return DAG.getNode(LoongArchISD::VALL_NONZERO, DL, N->getValueType(0),
9028 N->getOperand(1));
9029 break;
9030 case Intrinsic::loongarch_lsx_bnz_v:
9031 case Intrinsic::loongarch_lasx_xbnz_v:
9032 if (!Subtarget.is64Bit())
9033 return DAG.getNode(LoongArchISD::VANY_NONZERO, DL, N->getValueType(0),
9034 N->getOperand(1));
9035 break;
9036 case Intrinsic::loongarch_lasx_concat_128_s:
9037 case Intrinsic::loongarch_lasx_concat_128_d:
9038 case Intrinsic::loongarch_lasx_concat_128:
9039 return DAG.getNode(ISD::CONCAT_VECTORS, DL, N->getValueType(0),
9040 N->getOperand(1), N->getOperand(2));
9041 }
9042 return SDValue();
9043}
9044
9048 // If the input to MOVGR2FR_W_LA64 is just MOVFR2GR_S_LA64 the the
9049 // conversion is unnecessary and can be replaced with the
9050 // MOVFR2GR_S_LA64 operand.
9051 SDValue Op0 = N->getOperand(0);
9052 if (Op0.getOpcode() == LoongArchISD::MOVFR2GR_S_LA64)
9053 return Op0.getOperand(0);
9054 return SDValue();
9055}
9056
9060 // If the input to MOVFR2GR_S_LA64 is just MOVGR2FR_W_LA64 then the
9061 // conversion is unnecessary and can be replaced with the MOVGR2FR_W_LA64
9062 // operand.
9063 SDValue Op0 = N->getOperand(0);
9064 if (Op0->getOpcode() == LoongArchISD::MOVGR2FR_W_LA64) {
9065 assert(Op0.getOperand(0).getValueType() == N->getSimpleValueType(0) &&
9066 "Unexpected value type!");
9067 return Op0.getOperand(0);
9068 }
9069 return SDValue();
9070}
9071
9072static SDValue
9075 MVT VT = N->getSimpleValueType(0);
9076 unsigned NumBits = VT.getScalarSizeInBits();
9077
9078 // Simplify the inputs.
9080 APInt DemandedMask(APInt::getAllOnes(NumBits));
9081 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
9082 return SDValue(N, 0);
9083
9084 return SDValue();
9085}
9086
9087static SDValue
9091 SDValue Op0 = N->getOperand(0);
9092 SDLoc DL(N);
9093
9094 // If the input to SplitPairF64 is just BuildPairF64 then the operation is
9095 // redundant. Instead, use BuildPairF64's operands directly.
9096 if (Op0->getOpcode() == LoongArchISD::BUILD_PAIR_F64)
9097 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
9098
9099 if (Op0->isUndef()) {
9100 SDValue Lo = DAG.getUNDEF(MVT::i32);
9101 SDValue Hi = DAG.getUNDEF(MVT::i32);
9102 return DCI.CombineTo(N, Lo, Hi);
9103 }
9104
9105 // It's cheaper to materialise two 32-bit integers than to load a double
9106 // from the constant pool and transfer it to integer registers through the
9107 // stack.
9109 APInt V = C->getValueAPF().bitcastToAPInt();
9110 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
9111 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
9112 return DCI.CombineTo(N, Lo, Hi);
9113 }
9114
9115 return SDValue();
9116}
9117
9118/// Do target-specific dag combines on LoongArchISD::VREPLVE nodes.
9122 // [X]VREPLVE only uses the low log2(N) bits of the index, where N is the
9123 // number of elements per 128-bit lane.
9124 SDValue Idx = N->getOperand(1);
9125 unsigned NumLaneElts = 128 / N->getSimpleValueType(0).getScalarSizeInBits();
9127 APInt::getLowBitsSet(Idx.getValueSizeInBits(), Log2_32(NumLaneElts));
9129 if (TLI.SimplifyDemandedBits(Idx, DemandedBits, DCI))
9130 return SDValue(N, 0);
9131 return SDValue();
9132}
9133
9134/// Do target-specific dag combines on LoongArchISD::VANDN nodes.
9138 SDValue N0 = N->getOperand(0);
9139 SDValue N1 = N->getOperand(1);
9140 MVT VT = N->getSimpleValueType(0);
9141 SDLoc DL(N);
9142
9143 // VANDN(undef, x) -> 0
9144 // VANDN(x, undef) -> 0
9145 if (N0.isUndef() || N1.isUndef())
9146 return DAG.getConstant(0, DL, VT);
9147
9148 // VANDN(0, x) -> x
9150 return N1;
9151
9152 // VANDN(x, 0) -> 0
9154 return DAG.getConstant(0, DL, VT);
9155
9156 // VANDN(x, -1) -> NOT(x) -> XOR(x, -1)
9158 return DAG.getNOT(DL, N0, VT);
9159
9160 // Turn VANDN back to AND if input is inverted.
9161 if (SDValue Not = isNOT(N0, DAG))
9162 return DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, Not), N1);
9163
9164 // VANDN(bitcast(shl(splat(1), y)), x)
9165 // -> bitcast(VANDN(shl(splat(1), y), bitcast(x)))
9166 // Perform the VANDN in the element type of the shift so that it can be
9167 // selected as [x]vbitclr.{b/h/w/d}.
9168 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
9169 SDValue Shl = N0.getOperand(0);
9170 EVT ShlVT = Shl.getValueType();
9171 APInt SplatVal;
9172 if (Shl.getOpcode() == ISD::SHL && ShlVT.isVector() && ShlVT.isInteger() &&
9173 ShlVT != VT && ShlVT.getSizeInBits() == VT.getSizeInBits() &&
9174 DAG.getTargetLoweringInfo().isTypeLegal(ShlVT) &&
9175 ISD::isConstantSplatVector(Shl.getOperand(0), SplatVal) &&
9176 SplatVal.isOne()) {
9177 SDValue V = DAG.getNode(LoongArchISD::VANDN, DL, ShlVT, Shl,
9178 DAG.getBitcast(ShlVT, N1));
9179 return DAG.getBitcast(VT, V);
9180 }
9181 }
9182
9183 // Folds for better commutativity:
9184 if (N1->hasOneUse()) {
9185 // VANDN(x,NOT(y)) -> AND(NOT(x),NOT(y)) -> NOT(OR(X,Y)).
9186 if (SDValue Not = isNOT(N1, DAG))
9187 return DAG.getNOT(
9188 DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)), VT);
9189
9190 // VANDN(x, SplatVector(Imm)) -> AND(NOT(x), NOT(SplatVector(~Imm)))
9191 // -> NOT(OR(x, SplatVector(-Imm))
9192 // Combination is performed only when VT is v16i8/v32i8, using `vnori.b` to
9193 // gain benefits.
9194 if (!DCI.isBeforeLegalizeOps() && (VT == MVT::v16i8 || VT == MVT::v32i8) &&
9195 N1.getOpcode() == ISD::BUILD_VECTOR) {
9196 if (SDValue SplatValue =
9197 cast<BuildVectorSDNode>(N1.getNode())->getSplatValue()) {
9198 if (!N1->isOnlyUserOf(SplatValue.getNode()))
9199 return SDValue();
9200
9201 if (auto *C = dyn_cast<ConstantSDNode>(SplatValue)) {
9202 uint8_t NCVal = static_cast<uint8_t>(~(C->getSExtValue()));
9203 SDValue Not =
9204 DAG.getSplat(VT, DL, DAG.getTargetConstant(NCVal, DL, MVT::i8));
9205 return DAG.getNOT(
9206 DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)),
9207 VT);
9208 }
9209 }
9210 }
9211 }
9212
9213 return SDValue();
9214}
9215
9216static SDValue ExtendSrcToDst(SDNode *N, SelectionDAG &DAG, unsigned ExtendOp) {
9217 SDLoc DL(N);
9218 EVT VT = N->getValueType(0);
9219 SDValue Src = N->getOperand(0);
9220 EVT SrcVT = Src.getValueType();
9221
9222 unsigned DstElts = VT.getVectorNumElements();
9223 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9224 unsigned DstEltBits = VT.getScalarSizeInBits();
9225
9226 if (SrcEltBits >= DstEltBits)
9227 return SDValue();
9228
9229 MVT WidenEltVT = MVT::getIntegerVT(DstEltBits);
9230 EVT WidenSrcVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, DstElts);
9231
9232 SDValue Extend = DAG.getNode(ExtendOp, DL, WidenSrcVT, Src);
9233 return DAG.getNode(N->getOpcode(), DL, VT, Extend);
9234}
9235
9236// Merge two 64 to 32 convert instructions into one,
9237// e.g.
9238// vffint.s.l $vr0, $vr1, $vr2
9239// will convert 4 si64 into 4 float at once.
9240// or
9241// vftintrz.w.d $vr0, $vr1, $vr2
9242// which will convert 4 double into 4 si32 at once.
9243// also deal with their 256-bits LASX version.
9244static SDValue MergeBlocksConvert(SDNode *N, SelectionDAG &DAG, unsigned Opcode,
9245 unsigned BlockBits) {
9246 SDLoc DL(N);
9247 MVT DstVT = N->getSimpleValueType(0);
9248 SDValue Src = N->getOperand(0);
9249 MVT SrcVT = Src.getSimpleValueType();
9250 unsigned SrcBits = SrcVT.getSizeInBits();
9251
9253 unsigned BlockNumElts = BlockBits / SrcVT.getScalarSizeInBits();
9254 MVT BlockVT = MVT::getVectorVT(SrcVT.getScalarType(), BlockNumElts);
9255 if (Src.getOpcode() == ISD::CONCAT_VECTORS &&
9256 Src.getOperand(0).getValueType() == BlockVT) {
9257 for (unsigned i = 0; i < Src.getNumOperands(); ++i)
9258 Blocks.push_back(Src.getOperand(i));
9259 } else if (SrcBits > BlockBits) {
9260 // Wider than one register: extract each BlockBits-wide sub-vector.
9261 for (unsigned i = 0; i < SrcBits / BlockBits; ++i)
9262 Blocks.push_back(
9263 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, BlockVT, Src,
9264 DAG.getVectorIdxConstant(i * BlockNumElts, DL)));
9265 } else {
9266 BlockBits = SrcBits;
9267 Blocks.push_back(Src);
9268 }
9269
9270 MVT NativeVecVT = MVT::getVectorVT(DstVT.getScalarType(),
9271 BlockBits / DstVT.getScalarSizeInBits());
9273 for (unsigned i = 0; i < Blocks.size(); i += 2) {
9274 SDValue Lo = Blocks[i];
9275 SDValue Hi = Blocks.size() > 1 ? Blocks[i + 1] : Lo;
9276 SDValue Res = DAG.getNode(Opcode, DL, NativeVecVT, Hi, Lo);
9277
9278 if (BlockBits == 256) {
9279 SDValue Undef = DAG.getUNDEF(NativeVecVT);
9280 SmallVector<int, 8> Mask = {0, 1, 4, 5, 2, 3, 6, 7};
9281 Res = DAG.getVectorShuffle(NativeVecVT, DL, Res, Undef, Mask);
9282 Res = DAG.getBitcast(NativeVecVT, Res);
9283 }
9284
9285 Parts.push_back(Res);
9286 }
9287
9288 if (Blocks.size() == 1)
9289 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, DstVT, Parts[0],
9290 DAG.getVectorIdxConstant(0, DL));
9291 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Parts);
9292}
9293
9297 SDLoc DL(N);
9298 EVT VT = N->getValueType(0);
9299 SDValue Src = N->getOperand(0);
9300 EVT SrcVT = Src.getValueType();
9301
9302 if (VT.isVector()) {
9303 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9304 unsigned DstEltBits = VT.getScalarSizeInBits();
9305 unsigned NumElts = VT.getVectorNumElements();
9306 unsigned BlockBits = Subtarget.hasExtLASX() ? 256 : 128;
9307
9308 // Sign-extend src to avoid scalarization.
9309 if (SrcEltBits <= DstEltBits)
9310 return ExtendSrcToDst(N, DAG, ISD::SIGN_EXTEND);
9311
9312 if (SrcEltBits != 64 || DstEltBits != 32 || !isPowerOf2_32(NumElts))
9313 return SDValue();
9314
9315 if (!SrcVT.isSimple() || !VT.isSimple())
9316 return SDValue();
9317
9318 // [x]vffint.s.l needs LSX and at least one full 128-bit source register.
9319 if (!Subtarget.hasExtLSX() || SrcVT.getSizeInBits() < 128)
9320 return SDValue();
9321
9322 // Combine [x]vffint.s.l for vector si64 to float conversion.
9323 return MergeBlocksConvert(N, DAG, LoongArchISD::VFFINT, BlockBits);
9324 }
9325
9326 if (VT != MVT::f32 && VT != MVT::f64)
9327 return SDValue();
9328 if (VT == MVT::f32 && !Subtarget.hasBasicF())
9329 return SDValue();
9330 if (VT == MVT::f64 && !Subtarget.hasBasicD())
9331 return SDValue();
9332
9333 // Only optimize when the source and destination types have the same width.
9334 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9335 return SDValue();
9336
9337 // If the result of an integer load is only used by an integer-to-float
9338 // conversion, use a fp load instead. This eliminates an integer-to-float-move
9339 // (movgr2fr) instruction.
9340 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse() &&
9341 // Do not change the width of a volatile load. This condition check is
9342 // inspired by AArch64.
9343 !cast<LoadSDNode>(Src)->isVolatile()) {
9344 LoadSDNode *LN0 = cast<LoadSDNode>(Src);
9345 SDValue Load = DAG.getLoad(VT, DL, LN0->getChain(), LN0->getBasePtr(),
9346 LN0->getPointerInfo(), LN0->getAlign(),
9347 LN0->getMemOperand()->getFlags());
9348
9349 // Make sure successors of the original load stay after it by updating them
9350 // to use the new Chain.
9351 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9352 return DAG.getNode(LoongArchISD::SITOF, SDLoc(N), VT, Load);
9353 }
9354
9355 return SDValue();
9356}
9357
9361 SDLoc DL(N);
9362 EVT VT = N->getValueType(0);
9363
9364 // Zero-extend src to avoid scalarization.
9365 if (VT.isVector())
9366 return ExtendSrcToDst(N, DAG, ISD::ZERO_EXTEND);
9367
9368 return SDValue();
9369}
9370
9371// Using [X]VFTINTRZ_W_D for double to signed 32-bit integer conversion.
9372// For example:
9373// v4i32 = fp_to_sint (concat_vectors v2f64, v2f64)
9374// Can be combined into:
9375// v4i32 = VFTINTRZ_W_D v2f64. v2f64
9379 if (!Subtarget.hasExtLSX())
9380 return SDValue();
9381
9382 SDLoc DL(N);
9383 EVT DstVT = N->getValueType(0);
9384 SDValue Src = N->getOperand(0);
9385 EVT SrcVT = Src.getValueType();
9386 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9387
9388 if (!DstVT.isVector() || !DstVT.isSimple() || !SrcVT.isSimple())
9389 return SDValue();
9390
9391 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9392 unsigned SrcBits = SrcVT.getSizeInBits();
9393 unsigned DstEltBits = DstVT.getScalarSizeInBits();
9394 unsigned NumElts = DstVT.getVectorNumElements();
9395 unsigned BlockBits = Subtarget.hasExtLASX() ? 256 : 128;
9396
9397 if (!isPowerOf2_32(NumElts) || !isPowerOf2_32(DstEltBits))
9398 return SDValue();
9399
9400 if (SrcBits % BlockBits != 0 && SrcBits != 128)
9401 return SDValue();
9402
9403 if (DstEltBits < 32) {
9404 MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(32), NumElts);
9405 SDValue Conv = DAG.getNode(N->getOpcode(), DL, PromoteVT, Src);
9406 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Conv);
9407 }
9408
9409 if (SrcEltBits != 64 || DstEltBits != 32)
9410 return SDValue();
9411
9412 if (!IsSigned) {
9413 // LASX already has pattern for double convert to uint32.
9414 if (Subtarget.hasExtLASX())
9415 return SDValue();
9416 MVT TmpVT = MVT::getVectorVT(MVT::i64, NumElts);
9417 SDValue Tmp = DAG.getNode(ISD::FP_TO_SINT, DL, TmpVT, Src);
9418 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Tmp);
9419 }
9420
9421 return MergeBlocksConvert(N, DAG, LoongArchISD::VFTINTRZ, BlockBits);
9422}
9423
9424// Try to widen AND, OR and XOR nodes to VT in order to remove casts around
9425// logical operations, like in the example below.
9426// or (and (truncate x, truncate y)),
9427// (xor (truncate z, build_vector (constants)))
9428// Given a target type \p VT, we generate
9429// or (and x, y), (xor z, zext(build_vector (constants)))
9430// given x, y and z are of type \p VT. We can do so, if operands are either
9431// truncates from VT types, the second operand is a vector of constants, can
9432// be recursively promoted or is an existing extension we can extend further.
9434 SelectionDAG &DAG,
9436 unsigned Depth) {
9437 // Limit recursion to avoid excessive compile times.
9439 return SDValue();
9440
9441 if (!ISD::isBitwiseLogicOp(N.getOpcode()))
9442 return SDValue();
9443
9444 SDValue N0 = N.getOperand(0);
9445 SDValue N1 = N.getOperand(1);
9446
9448 if (!TLI.isOperationLegalOrPromote(N.getOpcode(), VT))
9449 return SDValue();
9450
9451 if (SDValue NN0 =
9452 PromoteMaskArithmetic(N0, DL, VT, DAG, Subtarget, Depth + 1))
9453 N0 = NN0;
9454 else {
9455 // The left side has to be a 'trunc'.
9456 bool LHSTrunc = N0.getOpcode() == ISD::TRUNCATE &&
9457 N0.getOperand(0).getValueType() == VT;
9458 if (LHSTrunc)
9459 N0 = N0.getOperand(0);
9460 else
9461 return SDValue();
9462 }
9463
9464 if (SDValue NN1 =
9465 PromoteMaskArithmetic(N1, DL, VT, DAG, Subtarget, Depth + 1))
9466 N1 = NN1;
9467 else {
9468 // The right side has to be a 'trunc', a (foldable) constant or an
9469 // existing extension we can extend further.
9470 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
9471 N1.getOperand(0).getValueType() == VT;
9472 if (RHSTrunc)
9473 N1 = N1.getOperand(0);
9474 else if (ISD::isExtVecInRegOpcode(N1.getOpcode()) && VT.is256BitVector() &&
9475 Subtarget.hasExtLASX() && N1.hasOneUse())
9476 N1 = DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0));
9477 // On 32-bit platform, i64 is an illegal integer scalar type, and
9478 // FoldConstantArithmetic will fail for v4i64. This may be optimized in the
9479 // future.
9480 else if (SDValue Cst =
9482 N1 = Cst;
9483 else
9484 return SDValue();
9485 }
9486
9487 return DAG.getNode(N.getOpcode(), DL, VT, N0, N1);
9488}
9489
9490// On LASX the type v4i1/v8i1/v16i1 may be legalized to v4i32/v8i16/v16i8, which
9491// is LSX-sized register. In most cases we actually compare or select LASX-sized
9492// registers and mixing the two types creates horrible code. This method
9493// optimizes some of the transition sequences.
9495 SelectionDAG &DAG,
9497 EVT VT = N.getValueType();
9498 assert(VT.isVector() && "Expected vector type");
9499 assert((N.getOpcode() == ISD::ANY_EXTEND ||
9500 N.getOpcode() == ISD::ZERO_EXTEND ||
9501 N.getOpcode() == ISD::SIGN_EXTEND) &&
9502 "Invalid Node");
9503
9504 if (!Subtarget.hasExtLASX() || !VT.is256BitVector())
9505 return SDValue();
9506
9507 SDValue Narrow = N.getOperand(0);
9508 EVT NarrowVT = Narrow.getValueType();
9509
9510 // Generate the wide operation.
9511 SDValue Op = PromoteMaskArithmetic(Narrow, DL, VT, DAG, Subtarget, 0);
9512 if (!Op)
9513 return SDValue();
9514 switch (N.getOpcode()) {
9515 default:
9516 llvm_unreachable("Unexpected opcode");
9517 case ISD::ANY_EXTEND:
9518 return Op;
9519 case ISD::ZERO_EXTEND:
9520 return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
9521 case ISD::SIGN_EXTEND:
9522 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
9523 DAG.getValueType(NarrowVT));
9524 }
9525}
9526
9530 EVT VT = N->getValueType(0);
9531 SDLoc DL(N);
9532
9533 if (VT.isVector()) {
9534 if (SDValue R = PromoteMaskArithmetic(SDValue(N, 0), DL, DAG, Subtarget))
9535 return R;
9536
9537 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) ||
9538 N->getValueSizeInBits(0) != N->getOperand(0).getValueSizeInBits() * 2)
9539 return SDValue();
9540
9541 if (SDValue R = matchHalfOf128BitLanes(N->getOperand(0), /*isLow=*/false)) {
9542 if (N->getOpcode() == ISD::SIGN_EXTEND)
9543 return DAG.getNode(LoongArchISD::VEXTH, DL, VT, R);
9544 if (N->getOpcode() == ISD::ZERO_EXTEND)
9545 return DAG.getNode(LoongArchISD::VEXTH_U, DL, VT, R);
9546 }
9547 }
9548
9549 return SDValue();
9550}
9551
9552static SDValue
9556 SDLoc DL(N);
9557 EVT VT = N->getValueType(0);
9558
9559 if (VT.isVector() && N->getNumOperands() == 2)
9560 if (SDValue R = combineFP_ROUND(SDValue(N, 0), DL, DAG, Subtarget))
9561 return R;
9562
9563 return SDValue();
9564}
9565
9566// Match (seteq X, splat(C)) where C satisfies Pred.
9568 function_ref<bool(const APInt &)> Pred) {
9569 if (V.getOpcode() != ISD::SETCC ||
9570 cast<CondCodeSDNode>(V.getOperand(2))->get() != ISD::SETEQ)
9571 return false;
9572
9573 SDValue LHS = V.getOperand(0);
9574 SDValue RHS = V.getOperand(1);
9575 if (RHS == X)
9576 std::swap(LHS, RHS);
9577 if (LHS != X)
9578 return false;
9579
9580 ConstantSDNode *C = isConstOrConstSplat(RHS, /*AllowUndefs=*/false,
9581 /*AllowTruncation=*/true);
9582 return C && Pred(C->getAPIntValue().trunc(X.getScalarValueSizeInBits()));
9583}
9584
9585// The [x]vdiv/[x]vmod instructions return x / 0 = 0, x % 0 = 0,
9586// MIN / -1 = MIN and MIN % -1 = 0. Return true if, in the lanes where Cond is
9587// set, dividing A by 1 gives the same result as the instruction with B. For
9588// division, the caller must zero the lanes where B is zero.
9590 unsigned Opc, unsigned Depth = 0) {
9591 if (Depth >= 6)
9592 return false;
9593
9594 switch (Cond.getOpcode()) {
9595 case ISD::OR:
9596 return isRedundantDivisorGuard(Cond.getOperand(0), A, B, Opc, Depth + 1) &&
9597 isRedundantDivisorGuard(Cond.getOperand(1), A, B, Opc, Depth + 1);
9598 case ISD::AND: {
9599 SDValue Op0 = Cond.getOperand(0);
9600 SDValue Op1 = Cond.getOperand(1);
9601 if (isRedundantDivisorGuard(Op0, A, B, Opc, Depth + 1) ||
9602 isRedundantDivisorGuard(Op1, A, B, Opc, Depth + 1))
9603 return true;
9604
9605 // MIN / -1 = MIN / 1.
9606 auto IsOverflow = [&](SDValue X, SDValue Y) {
9607 return isSetEqSplat(
9608 X, A, [](const APInt &C) { return C.isMinSignedValue(); }) &&
9609 isSetEqSplat(Y, B, [](const APInt &C) { return C.isAllOnes(); });
9610 };
9611 return Opc == ISD::SDIV && (IsOverflow(Op0, Op1) || IsOverflow(Op1, Op0));
9612 }
9613 default:
9614 break;
9615 }
9616
9617 // x / 1 = x and x % 1 = x % 0 = 0.
9618 if (isSetEqSplat(Cond, B, [](const APInt &C) { return C.isOne(); }) ||
9619 isSetEqSplat(Cond, B, [](const APInt &C) { return C.isZero(); }))
9620 return true;
9621
9622 // x % -1 = x % 1 = 0.
9623 return Opc == ISD::SREM &&
9624 isSetEqSplat(Cond, B, [](const APInt &C) { return C.isAllOnes(); });
9625}
9626
9627// Match B guarded by a redundant select or umax, and return B.
9629 // umax(b, 1) == select(b == 0, 1, b).
9630 if (D.getOpcode() == ISD::UMAX && isOneOrOneSplat(D.getOperand(1)))
9631 return D.getOperand(0);
9632
9633 if (D.getOpcode() == ISD::VSELECT && isOneOrOneSplat(D.getOperand(1)) &&
9634 isRedundantDivisorGuard(D.getOperand(0), A, D.getOperand(2), Opc))
9635 return D.getOperand(2);
9636
9637 return SDValue();
9638}
9639
9640// (srem/urem a, (guarded b)) -> (VMOD/VMOD_U a, b)
9644 EVT VT = N->getValueType(0);
9645 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9646 return SDValue();
9647
9648 unsigned Opc = N->getOpcode();
9649 SDValue A = N->getOperand(0);
9650 SDValue B = matchGuardedDivisor(N->getOperand(1), A, Opc);
9651 if (!B)
9652 return SDValue();
9653
9654 return DAG.getNode(Opc == ISD::SREM ? LoongArchISD::VMOD
9655 : LoongArchISD::VMOD_U,
9656 SDLoc(N), VT, A, B);
9657}
9658
9659// (vselect (seteq b, 0), 0, (sdiv/udiv a, (guarded b))) -> (VDIV/VDIV_U a, b)
9661 EVT VT = N->getValueType(0);
9662 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9663 return SDValue();
9664
9665 SDValue Div = N->getOperand(2);
9666 unsigned Opc = Div.getOpcode();
9667 if ((Opc != ISD::SDIV && Opc != ISD::UDIV) || !Div.hasOneUse() ||
9668 !ISD::isConstantSplatVectorAllZeros(N->getOperand(1)))
9669 return SDValue();
9670
9671 SDValue A = Div.getOperand(0);
9672 SDValue B = matchGuardedDivisor(Div.getOperand(1), A, Opc);
9673 if (!B || !isSetEqSplat(N->getOperand(0), B,
9674 [](const APInt &C) { return C.isZero(); }))
9675 return SDValue();
9676
9677 return DAG.getNode(Opc == ISD::SDIV ? LoongArchISD::VDIV
9678 : LoongArchISD::VDIV_U,
9679 SDLoc(N), VT, A, B);
9680}
9681
9685 if (SDValue V = combineGuardedVectorDiv(N, DAG))
9686 return V;
9687
9688 if (DCI.isBeforeLegalizeOps())
9689 return SDValue();
9690
9691 EVT VT = N->getValueType(0);
9692 if (!VT.isVector())
9693 return SDValue();
9694
9695 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9696 return SDValue();
9697
9698 EVT EltVT = VT.getVectorElementType();
9699 if (!EltVT.isInteger())
9700 return SDValue();
9701
9702 SDValue Cond = N->getOperand(0);
9703 SDValue TrueVal = N->getOperand(1);
9704 SDValue FalseVal = N->getOperand(2);
9705
9706 // match:
9707 //
9708 // vselect (setcc shift, 0, seteq),
9709 // x,
9710 // rounded_shift
9711
9712 if (Cond.getOpcode() != ISD::SETCC)
9713 return SDValue();
9714
9715 if (!ISD::isConstantSplatVectorAllZeros(Cond.getOperand(1)))
9716 return SDValue();
9717
9718 if (Cond.getOperandCondCode(2) != ISD::SETEQ)
9719 return SDValue();
9720
9721 SDValue Shift = Cond.getOperand(0);
9722
9723 // True branch must be original value:
9724 //
9725 // vselect cond, x, ...
9726
9727 SDValue X = TrueVal;
9728
9729 // Now match rounded shift pattern:
9730 //
9731 // add
9732 // (and
9733 // (srl X, shift-1)
9734 // 1)
9735 // (srl/sra X, shift)
9736
9737 if (FalseVal.getOpcode() != ISD::ADD)
9738 return SDValue();
9739
9740 SDValue Add0 = FalseVal.getOperand(0);
9741 SDValue Add1 = FalseVal.getOperand(1);
9742 SDValue And;
9743 SDValue Shr;
9744
9745 if (Add0.getOpcode() == ISD::AND) {
9746 And = Add0;
9747 Shr = Add1;
9748 } else if (Add1.getOpcode() == ISD::AND) {
9749 And = Add1;
9750 Shr = Add0;
9751 } else {
9752 return SDValue();
9753 }
9754
9755 // match:
9756 //
9757 // srl/sra X, shift
9758
9759 if (Shr.getOpcode() != ISD::SRL && Shr.getOpcode() != ISD::SRA)
9760 return SDValue();
9761
9762 if (Shr.getOperand(0) != X)
9763 return SDValue();
9764
9765 if (Shr.getOperand(1) != Shift)
9766 return SDValue();
9767
9768 // match:
9769 //
9770 // and
9771 // (srl X, shift-1)
9772 // 1
9773
9774 SDValue Srl = And.getOperand(0);
9775 SDValue One = And.getOperand(1);
9776 APInt SplatVal;
9777
9778 if (Srl.getOpcode() != ISD::SRL)
9779 return SDValue();
9780
9781 One = peekThroughBitcasts(One);
9782 if (!isConstantSplatVector(One, SplatVal, EltVT.getSizeInBits()))
9783 return SDValue();
9784
9785 if (SplatVal != 1)
9786 return SDValue();
9787
9788 if (Srl.getOperand(0) != X)
9789 return SDValue();
9790
9791 // match:
9792 //
9793 // shift-1
9794
9795 SDValue ShiftMinus1 = Srl.getOperand(1);
9796
9797 if (ShiftMinus1.getOpcode() != ISD::ADD)
9798 return SDValue();
9799
9800 if (ShiftMinus1.getOperand(0) != Shift)
9801 return SDValue();
9802
9803 if (!ISD::isConstantSplatVectorAllOnes(ShiftMinus1.getOperand(1)))
9804 return SDValue();
9805
9806 // We matched a rounded right shift pattern and can lower it
9807 // to a single vector rounded shift instruction.
9808
9809 SDLoc DL(N);
9810 return DAG.getNode(Shr.getOpcode() == ISD::SRL ? LoongArchISD::VSRLR
9811 : LoongArchISD::VSRAR,
9812 DL, VT, X, Shift);
9813}
9814
9818 if (!DCI.isBeforeLegalize())
9819 return SDValue();
9820
9821 SDLoc DL(N);
9822 EVT ResTy = N->getValueType(0);
9823 SDValue N0 = N->getOperand(0);
9824 SDValue N1 = N->getOperand(1);
9825
9826 bool HasLSXOnly = Subtarget.hasExtLSX() && !Subtarget.hasExtLASX();
9827 if (ResTy != MVT::v8i16 && ResTy != MVT::v4i32 && ResTy != MVT::v2i64 &&
9828 ResTy != MVT::i128 && ResTy != MVT::v16i16 && ResTy != MVT::v8i32 &&
9829 ResTy != MVT::v4i64 && ResTy != MVT::v2i128)
9830 return SDValue();
9831 if (HasLSXOnly && (ResTy.is256BitVector() || ResTy == MVT::v2i128))
9832 return SDValue();
9833
9834 // Combine:
9835 // ti,tii,...,tx = extract_vector_elt t0, {0,2,4,.../1,3,5,...}
9836 // tj,tjj,...,ty = extract_vector_elt t1, {0,2,4,.../1,3,5,...}
9837 // tm = BUILD_VECTOR ti,tii,...,tx (Only when ResTy != MVT::i128)
9838 // tn = BUILD_VECTOR tj,tjj,...,ty (Only when ResTy != MVT::i128)
9839 // ta = {sign/zero}_extend tm
9840 // tb = {sign/zero}_extend tn
9841 // tr = mul ta, tb
9842 // to:
9843 // tr = VMULW{EV/OD}[U/US] t0, t1
9844 auto getExtType = [](unsigned Op0, unsigned Op1) -> int {
9845 if (Op0 == ISD::SIGN_EXTEND && Op1 == ISD::SIGN_EXTEND)
9846 return 0;
9847 if (Op0 == ISD::ZERO_EXTEND && Op1 == ISD::ZERO_EXTEND)
9848 return 1;
9849 if (Op0 == ISD::ZERO_EXTEND && Op1 == ISD::SIGN_EXTEND)
9850 return 2;
9851 if (Op0 == ISD::SIGN_EXTEND && Op1 == ISD::ZERO_EXTEND)
9852 return 3;
9853 return -1;
9854 };
9855
9856 int ExtType = getExtType(N0.getOpcode(), N1.getOpcode());
9857 if (ExtType < 0)
9858 return SDValue();
9859
9860 // Avoid the regressions on LA64 introduced by combining
9861 // i128-type multiplications.
9862 bool IsScalar = (ResTy == MVT::i128);
9863 if (IsScalar && ExtType < 2 && Subtarget.is64Bit())
9864 return SDValue();
9865
9866 SDValue Src0 = N0.getOperand(0);
9867 SDValue Src1 = N1.getOperand(0);
9868 if (IsScalar && (Src0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9869 Src1.getOpcode() != ISD::EXTRACT_VECTOR_ELT))
9870 return SDValue();
9871 if (!IsScalar && (Src0.getOpcode() != ISD::BUILD_VECTOR ||
9872 Src1.getOpcode() != ISD::BUILD_VECTOR))
9873 return SDValue();
9874
9875 unsigned ResBits = ResTy.getScalarSizeInBits();
9876 unsigned Src0Bits = Src0.getValueType().getScalarSizeInBits();
9877 unsigned Src1Bits = Src1.getValueType().getScalarSizeInBits();
9878 if (Src0Bits != Src1Bits || ResBits != Src0Bits * 2)
9879 return SDValue();
9880
9881 // Collect all EXTRACT_VECTOR_ELT.
9883 if (IsScalar) {
9884 Elems.emplace_back(Src0, Src1);
9885 } else {
9886 for (unsigned i = 0; i < Src0.getNumOperands(); ++i)
9887 Elems.emplace_back(Src0.getOperand(i), Src1.getOperand(i));
9888 }
9889
9890 unsigned Index;
9891 SDValue OrigN0, OrigN1;
9892 bool First = true;
9893 for (auto &[Op0, Op1] : Elems) {
9894 // Each element must be EXTRACT_VECTOR_ELT.
9895 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9897 return SDValue();
9898
9899 // Check each EXTRACT_VECTOR_ELT's source vector and index.
9900 if (Op0.getOperand(1) != Op1.getOperand(1))
9901 return SDValue();
9902
9903 auto *IdxC = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9904 if (!IdxC)
9905 return SDValue();
9906
9907 unsigned CurIdx = IdxC->getZExtValue();
9908 if (First) {
9909 if (CurIdx != 0 && CurIdx != 1)
9910 return SDValue();
9911 OrigN0 = Op0.getOperand(0);
9912 OrigN1 = Op1.getOperand(0);
9913 First = false;
9914 } else {
9915 if (CurIdx != Index + 2 || Op0.getOperand(0) != OrigN0 ||
9916 Op1.getOperand(0) != OrigN1)
9917 return SDValue();
9918 }
9919 Index = CurIdx;
9920 }
9921
9922 if (OrigN0.getValueType() != OrigN1.getValueType())
9923 return SDValue();
9924 if (OrigN0.getValueType().getVectorNumElements() !=
9925 (IsScalar ? 1 : ResTy.getVectorNumElements()) * 2)
9926 return SDValue();
9927
9928 SDValue Result;
9929 EVT OrigTy = OrigN0.getValueType();
9930 bool IsEven = (Index % 2 == 0);
9931
9932 static const unsigned OpcTable[3][2] = {
9933 {LoongArchISD::VMULWOD, LoongArchISD::VMULWEV},
9934 {LoongArchISD::VMULWODU, LoongArchISD::VMULWEVU},
9935 {LoongArchISD::VMULWODUS, LoongArchISD::VMULWEVUS}};
9936
9937 if (ExtType == 3)
9938 Result = DAG.getNode(OpcTable[2][IsEven], DL, OrigTy, OrigN1, OrigN0);
9939 else
9940 Result = DAG.getNode(OpcTable[ExtType][IsEven], DL, OrigTy, OrigN0, OrigN1);
9941
9942 return DAG.getBitcast(ResTy, Result);
9943}
9944
9945static SDValue
9948 SelectionDAG &DAG = DCI.DAG;
9949 SDValue Src = N->getOperand(0);
9950 EVT VT = N->getValueType(0);
9951 EVT SrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9952 unsigned Opc = Src.getOpcode();
9953 SDLoc DL(N);
9954
9955 // Leave the sign extension in place when it feeds an xor with another
9956 // sign-extended value; the generic xor-of-sext_inregs combine can then
9957 // fold both extensions into a single one.
9958 if (N->hasOneUse()) {
9959 SDNode *User = N->use_begin()->getUser();
9960 if (User->getOpcode() == ISD::XOR) {
9961 SDValue Other = User->getOperand(0).getNode() == N ? User->getOperand(1)
9962 : User->getOperand(0);
9963 if (Other.getOpcode() == ISD::SIGN_EXTEND_INREG)
9964 return SDValue();
9965 }
9966 }
9967
9968 // Do not hide a sign-extended boolean from a compare against zero: the
9969 // generic combiner folds (setcc (sext_inreg X, i1), 0, setlt) back to X.
9970 for (SDNode *User : N->users()) {
9971 if (User->getOpcode() != ISD::SETCC)
9972 continue;
9973 if ((User->getOperand(0).getNode() == N &&
9975 (User->getOperand(1).getNode() == N &&
9977 return SDValue();
9978 }
9979
9980 // Fold (sext_inreg (shl X, Y), i32) -> (sll.w X, Y) iff Y u< 32.
9981 if (DCI.isAfterLegalizeDAG() && Subtarget.is64Bit() && SrcVT == MVT::i32 &&
9982 VT == MVT::i64 && Opc == ISD::SHL &&
9983 !isa<ConstantSDNode>(Src.getOperand(1)) &&
9984 DAG.computeKnownBits(Src.getOperand(1)).countMaxActiveBits() <= 5) {
9985 return DAG.getNode(LoongArchISD::SLL_W, DL, VT, Src.getOperand(0),
9986 Src.getOperand(1));
9987 }
9988
9989 // The SETCC/XOR folds replace the sign extension itself. When the result
9990 // has several users they do not save an instruction and can duplicate the
9991 // compare; leave it to the generic combiner.
9992 if (!N->hasOneUse())
9993 return SDValue();
9994
9995 // Similarly, a sign-extended boolean that feeds a sign-bit extraction is
9996 // usually part of a compare that the generic combiner can fold away.
9997 for (SDNode *User : N->users()) {
9998 if ((User->getOpcode() == ISD::SRL || User->getOpcode() == ISD::SRA) &&
10000 return SDValue();
10001 }
10002
10003 // Fold (sext_inreg (setcc X, Y, CC), i1) -> (sub 0, (setcc X, Y, CC)) if CC
10004 // can be selected with a single instruction, or
10005 // (add (setcc X, Y, inv(CC)), -1) if the inverted CC is cheaper. LoongArch
10006 // selects setge/setle/setuge/setule as slt + xori, so inverting such an
10007 // integer compare avoids the extra xor. Inverting replaces the original
10008 // setcc, so only do it when it has a single use; otherwise (e.g. an FP
10009 // compare shared with another user) this would introduce a second compare.
10010 if (Opc == ISD::SETCC && SrcVT == MVT::i1) {
10011 ISD::CondCode CC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
10012 if (Src.hasOneUse() && Src.getOperand(0).getValueType().isInteger()) {
10013 switch (CC) {
10014 case ISD::SETGE:
10015 case ISD::SETLE:
10016 case ISD::SETUGE:
10017 case ISD::SETULE:
10018 // (sub 0, X >= Y) == (add (X < Y), -1), etc.
10019 return DAG.getNode(
10020 ISD::ADD, DL, VT,
10021 DAG.getSetCC(
10022 SDLoc(N), Src.getValueType(), Src.getOperand(0),
10023 Src.getOperand(1),
10024 ISD::getSetCCInverse(CC, Src.getOperand(0).getValueType())),
10025 DAG.getAllOnesConstant(DL, VT));
10026 default:
10027 break;
10028 }
10029 }
10030 return DAG.getNegative(Src, DL, VT);
10031 }
10032
10033 // Fold (sext_inreg (xor (setcc), C), i1) -> (add (setcc), -1) where C is
10034 // either 1 or -1. Since setcc only produces 0 or 1, the xor only flips the
10035 // low bit, so the sign extension of that bit is -(1 - setcc) == setcc - 1.
10036 // The setcc may be wrapped in a truncate/any_extend when the boolean is
10037 // extended to VT (e.g. by a zext, which knows the upper bits are zero).
10038 if (Opc == ISD::XOR && SrcVT == MVT::i1 &&
10039 (isOneConstant(Src.getOperand(1)) ||
10040 isAllOnesConstant(Src.getOperand(1)))) {
10041 SDValue XorOp = Src.getOperand(0);
10042 if (XorOp.getOpcode() == ISD::TRUNCATE ||
10043 XorOp.getOpcode() == ISD::ANY_EXTEND)
10044 XorOp = XorOp.getOperand(0);
10045 if (XorOp.getOpcode() != ISD::SETCC)
10046 return SDValue();
10047 // The setcc may still have an i1 result type, in which case rebuild it
10048 // with VT so that both ADD operands have the same type. A setcc produces
10049 // a canonical 0/1 value, so this is exact while the any_extend leaves the
10050 // upper bits undefined.
10052 EVT OpVT = XorOp.getOperand(0).getValueType();
10053
10054 // Inverting an FP compare is free, so this fold does not save anything
10055 // and can duplicate a shared fcmp. Keep the original form.
10056 if (OpVT.isFloatingPoint())
10057 return SDValue();
10058
10059 // Reusing the original compare is only possible when the setcc is
10060 // otherwise dead. Inverting a shared compare duplicates it (e.g. an FP
10061 // compare used by a zext as well).
10062 if (!XorOp.hasOneUse())
10063 return SDValue();
10064
10065 // A constant compare with a greater-than style condition code cannot use
10066 // the slti/sltui immediate patterns; leave it to the generic combiner,
10067 // which canonicalizes it to setlt/setult first.
10068 if (isa<ConstantSDNode>(XorOp.getOperand(1)) && CC != ISD::SETLT &&
10069 CC != ISD::SETULT)
10070 return SDValue();
10071
10072 // The generic (sub X, (0 - Y)) -> (add X, Y) fold is better than
10073 // rewriting the sign-extended boolean here.
10074 if (N->hasOneUse() && N->use_begin()->getUser()->getOpcode() == ISD::SUB)
10075 return SDValue();
10076
10077 // For integer compares, sext(!setcc CC) == -(setcc inv(CC)). Only keep
10078 // CC (as add -1) when CC itself is the single-instruction form; otherwise
10079 // negate the inverted setcc, which also CSEs with an existing one.
10080 if (OpVT.isInteger() && CC != ISD::SETLT && CC != ISD::SETGT &&
10081 CC != ISD::SETULT && CC != ISD::SETUGT)
10082 return DAG.getNegative(DAG.getSetCC(DL, VT, XorOp.getOperand(0),
10083 XorOp.getOperand(1),
10084 ISD::getSetCCInverse(CC, OpVT)),
10085 DL, VT);
10086 if (XorOp.getValueType() != VT)
10087 XorOp =
10088 DAG.getSetCC(DL, VT, XorOp.getOperand(0), XorOp.getOperand(1), CC);
10089 return DAG.getNode(ISD::ADD, DL, VT, XorOp, DAG.getAllOnesConstant(DL, VT));
10090 }
10091
10092 return SDValue();
10093}
10094
10096 DAGCombinerInfo &DCI) const {
10097 SelectionDAG &DAG = DCI.DAG;
10098 switch (N->getOpcode()) {
10099 default:
10100 break;
10101 case ISD::ADD:
10102 return performADDCombine(N, DAG, DCI, Subtarget);
10103 case ISD::AND:
10104 return performANDCombine(N, DAG, DCI, Subtarget);
10105 case ISD::OR:
10106 return performORCombine(N, DAG, DCI, Subtarget);
10107 case ISD::XOR:
10108 return performXORCombine(N, DAG, Subtarget);
10109 case ISD::SETCC:
10110 return performSETCCCombine(N, DAG, DCI, Subtarget);
10111 case ISD::SELECT:
10112 return performSELECTCombine(N, DAG, DCI, Subtarget);
10113 case ISD::SHL:
10114 return performSHLCombine(N, DAG, DCI, Subtarget);
10115 case ISD::SRL:
10116 return performSRLCombine(N, DAG, DCI, Subtarget);
10117 case ISD::SUB:
10118 return performSUBCombine(N, DAG, DCI, Subtarget);
10119 case ISD::BITCAST:
10120 return performBITCASTCombine(N, DAG, DCI, Subtarget);
10121 case ISD::ANY_EXTEND:
10122 case ISD::ZERO_EXTEND:
10123 case ISD::SIGN_EXTEND:
10124 return performEXTENDCombine(N, DAG, DCI, Subtarget);
10126 return performSIGN_EXTEND_INREGCombine(N, DCI, Subtarget);
10127 case ISD::SINT_TO_FP:
10128 return performSINT_TO_FPCombine(N, DAG, DCI, Subtarget);
10129 case ISD::UINT_TO_FP:
10130 return performUINT_TO_FPCombine(N, DAG, DCI, Subtarget);
10131 case ISD::FP_TO_SINT:
10132 case ISD::FP_TO_UINT:
10133 return performFP_TO_INTCombine(N, DAG, DCI, Subtarget);
10134 case LoongArchISD::BITREV_W:
10135 return performBITREV_WCombine(N, DAG, DCI, Subtarget);
10136 case LoongArchISD::BR_CC:
10137 return performBR_CCCombine(N, DAG, DCI, Subtarget);
10138 case LoongArchISD::SELECT_CC:
10139 return performSELECT_CCCombine(N, DAG, DCI, Subtarget);
10141 return performINTRINSIC_WO_CHAINCombine(N, DAG, DCI, Subtarget);
10142 case LoongArchISD::MOVGR2FR_W_LA64:
10143 return performMOVGR2FR_WCombine(N, DAG, DCI, Subtarget);
10144 case LoongArchISD::MOVFR2GR_S_LA64:
10145 return performMOVFR2GR_SCombine(N, DAG, DCI, Subtarget);
10146 case LoongArchISD::CRC_W_B_W:
10147 case LoongArchISD::CRC_W_H_W:
10148 case LoongArchISD::CRCC_W_B_W:
10149 case LoongArchISD::CRCC_W_H_W:
10150 case LoongArchISD::VMSKLTZ:
10151 case LoongArchISD::XVMSKLTZ:
10152 return performDemandedBitsCombine(N, DAG, DCI);
10153 case LoongArchISD::SPLIT_PAIR_F64:
10154 return performSPLIT_PAIR_F64Combine(N, DAG, DCI, Subtarget);
10155 case LoongArchISD::VANDN:
10156 return performVANDNCombine(N, DAG, DCI, Subtarget);
10157 case LoongArchISD::VREPLVE:
10158 return performVREPLVECombine(N, DAG, DCI, Subtarget);
10160 return performCONCAT_VECTORSCombine(N, DAG, DCI, Subtarget);
10161 case ISD::VSELECT:
10162 return performVSELECTCombine(N, DAG, DCI, Subtarget);
10163 case LoongArchISD::VPACKEV:
10164 case LoongArchISD::VPERMI:
10165 if (SDValue Result =
10166 combineFP_ROUND(SDValue(N, 0), SDLoc(N), DAG, Subtarget))
10167 return Result;
10168 break;
10169 case ISD::MUL:
10170 return performMULCombine(N, DAG, DCI, Subtarget);
10171 case ISD::SREM:
10172 case ISD::UREM:
10173 return performREMCombine(N, DAG, DCI, Subtarget);
10174 }
10175 return SDValue();
10176}
10177
10180 if (!ZeroDivCheck)
10181 return MBB;
10182
10183 // Build instructions:
10184 // MBB:
10185 // div(or mod) $dst, $dividend, $divisor
10186 // bne $divisor, $zero, SinkMBB
10187 // BreakMBB:
10188 // break 7 // BRK_DIVZERO
10189 // SinkMBB:
10190 // fallthrough
10191 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10192 MachineFunction::iterator It = ++MBB->getIterator();
10193 MachineFunction *MF = MBB->getParent();
10194 auto BreakMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10195 auto SinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10196 MF->insert(It, BreakMBB);
10197 MF->insert(It, SinkMBB);
10198
10199 // Transfer the remainder of MBB and its successor edges to SinkMBB.
10200 SinkMBB->splice(SinkMBB->end(), MBB, std::next(MI.getIterator()), MBB->end());
10201 SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10202
10203 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
10204 DebugLoc DL = MI.getDebugLoc();
10205 MachineOperand &Divisor = MI.getOperand(2);
10206 Register DivisorReg = Divisor.getReg();
10207
10208 // MBB:
10209 BuildMI(MBB, DL, TII.get(LoongArch::BNE))
10210 .addReg(DivisorReg, getKillRegState(Divisor.isKill()))
10211 .addReg(LoongArch::R0)
10212 .addMBB(SinkMBB);
10213 MBB->addSuccessor(BreakMBB);
10214 MBB->addSuccessor(SinkMBB);
10215
10216 // BreakMBB:
10217 // See linux header file arch/loongarch/include/uapi/asm/break.h for the
10218 // definition of BRK_DIVZERO.
10219 BuildMI(BreakMBB, DL, TII.get(LoongArch::BREAK)).addImm(7 /*BRK_DIVZERO*/);
10220 BreakMBB->addSuccessor(SinkMBB);
10221
10222 // Clear Divisor's kill flag.
10223 Divisor.setIsKill(false);
10224
10225 return SinkMBB;
10226}
10227
10228static MachineBasicBlock *
10231 unsigned InsOp;
10232 unsigned BroadcastOp;
10233 unsigned HalfSize;
10234 switch (MI.getOpcode()) {
10235 default:
10236 llvm_unreachable("Unexpected opcode");
10237 case LoongArch::PseudoXVINSGR2VR_B:
10238 HalfSize = 16;
10239 BroadcastOp = LoongArch::XVREPLGR2VR_B;
10240 InsOp = LoongArch::XVEXTRINS_B;
10241 break;
10242 case LoongArch::PseudoXVINSGR2VR_H:
10243 HalfSize = 8;
10244 BroadcastOp = LoongArch::XVREPLGR2VR_H;
10245 InsOp = LoongArch::XVEXTRINS_H;
10246 break;
10247 }
10248 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10249 const TargetRegisterClass *RC = &LoongArch::LASX256RegClass;
10250 const TargetRegisterClass *SubRC = &LoongArch::LSX128RegClass;
10251 DebugLoc DL = MI.getDebugLoc();
10253 // XDst = vector_insert XSrc, Elt, Idx
10254 Register XDst = MI.getOperand(0).getReg();
10255 Register XSrc = MI.getOperand(1).getReg();
10256 Register Elt = MI.getOperand(2).getReg();
10257 unsigned Idx = MI.getOperand(3).getImm();
10258
10259 if (XSrc.isVirtual() && MRI.getVRegDef(XSrc)->isImplicitDef() &&
10260 Idx < HalfSize) {
10261 Register ScratchSubReg1 = MRI.createVirtualRegister(SubRC);
10262 Register ScratchSubReg2 = MRI.createVirtualRegister(SubRC);
10263
10264 BuildMI(*BB, MI, DL, TII->get(LoongArch::COPY), ScratchSubReg1)
10265 .addReg(XSrc, {}, LoongArch::sub_128);
10266 BuildMI(*BB, MI, DL,
10267 TII->get(HalfSize == 8 ? LoongArch::VINSGR2VR_H
10268 : LoongArch::VINSGR2VR_B),
10269 ScratchSubReg2)
10270 .addReg(ScratchSubReg1)
10271 .addReg(Elt)
10272 .addImm(Idx);
10273
10274 BuildMI(*BB, MI, DL, TII->get(LoongArch::INSERT_SUBREG), XDst)
10275 .addReg(XSrc)
10276 .addReg(ScratchSubReg2)
10277 .addImm(LoongArch::sub_128);
10278 } else {
10279 Register ScratchReg1 = MRI.createVirtualRegister(RC);
10280 Register ScratchReg2 = MRI.createVirtualRegister(RC);
10281
10282 BuildMI(*BB, MI, DL, TII->get(BroadcastOp), ScratchReg1).addReg(Elt);
10283
10284 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPERMI_Q), ScratchReg2)
10285 .addReg(ScratchReg1)
10286 .addReg(XSrc)
10287 .addImm(Idx >= HalfSize ? 48 : 18);
10288
10289 BuildMI(*BB, MI, DL, TII->get(InsOp), XDst)
10290 .addReg(XSrc)
10291 .addReg(ScratchReg2)
10292 .addImm((Idx >= HalfSize ? Idx - HalfSize : Idx) * 17);
10293 }
10294
10295 MI.eraseFromParent();
10296 return BB;
10297}
10298
10302 assert(Subtarget.hasExtLSX());
10303 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10304 const TargetRegisterClass *RC = &LoongArch::LSX128RegClass;
10305 DebugLoc DL = MI.getDebugLoc();
10307 Register Dst = MI.getOperand(0).getReg();
10308 Register Src = MI.getOperand(1).getReg();
10309
10310 unsigned BroadcastOp, CTOp, PickOp;
10311 switch (MI.getOpcode()) {
10312 default:
10313 llvm_unreachable("Unexpected opcode");
10314 case LoongArch::PseudoCTPOP_B:
10315 BroadcastOp = LoongArch::VREPLGR2VR_B;
10316 CTOp = LoongArch::VPCNT_B;
10317 PickOp = LoongArch::VPICKVE2GR_B;
10318 break;
10319 case LoongArch::PseudoCTPOP_H:
10320 case LoongArch::PseudoCTPOP_H_LA32:
10321 BroadcastOp = LoongArch::VREPLGR2VR_H;
10322 CTOp = LoongArch::VPCNT_H;
10323 PickOp = LoongArch::VPICKVE2GR_H;
10324 break;
10325 case LoongArch::PseudoCTPOP_W:
10326 case LoongArch::PseudoCTPOP_W_LA32:
10327 BroadcastOp = LoongArch::VREPLGR2VR_W;
10328 CTOp = LoongArch::VPCNT_W;
10329 PickOp = LoongArch::VPICKVE2GR_W;
10330 break;
10331 case LoongArch::PseudoCTPOP_D:
10332 BroadcastOp = LoongArch::VREPLGR2VR_D;
10333 CTOp = LoongArch::VPCNT_D;
10334 PickOp = LoongArch::VPICKVE2GR_D;
10335 break;
10336 }
10337
10338 Register ScratchReg1 = MRI.createVirtualRegister(RC);
10339 Register ScratchReg2 = MRI.createVirtualRegister(RC);
10340 BuildMI(*BB, MI, DL, TII->get(BroadcastOp), ScratchReg1).addReg(Src);
10341 BuildMI(*BB, MI, DL, TII->get(CTOp), ScratchReg2).addReg(ScratchReg1);
10342 BuildMI(*BB, MI, DL, TII->get(PickOp), Dst).addReg(ScratchReg2).addImm(0);
10343
10344 MI.eraseFromParent();
10345 return BB;
10346}
10347
10348static MachineBasicBlock *
10351 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10352 const TargetRegisterClass *RC = &LoongArch::LSX128RegClass;
10353 const LoongArchRegisterInfo *TRI = Subtarget.getRegisterInfo();
10355 Register Dst = MI.getOperand(0).getReg();
10356 Register Src = MI.getOperand(1).getReg();
10357 DebugLoc DL = MI.getDebugLoc();
10358 unsigned EleBits = 8;
10359 unsigned NotOpc = 0;
10360 unsigned MskOpc;
10361
10362 switch (MI.getOpcode()) {
10363 default:
10364 llvm_unreachable("Unexpected opcode");
10365 case LoongArch::PseudoVMSKLTZ_B:
10366 MskOpc = LoongArch::VMSKLTZ_B;
10367 break;
10368 case LoongArch::PseudoVMSKLTZ_H:
10369 MskOpc = LoongArch::VMSKLTZ_H;
10370 EleBits = 16;
10371 break;
10372 case LoongArch::PseudoVMSKLTZ_W:
10373 MskOpc = LoongArch::VMSKLTZ_W;
10374 EleBits = 32;
10375 break;
10376 case LoongArch::PseudoVMSKLTZ_D:
10377 MskOpc = LoongArch::VMSKLTZ_D;
10378 EleBits = 64;
10379 break;
10380 case LoongArch::PseudoVMSKGEZ_B:
10381 MskOpc = LoongArch::VMSKGEZ_B;
10382 break;
10383 case LoongArch::PseudoVMSKEQZ_B:
10384 MskOpc = LoongArch::VMSKNZ_B;
10385 NotOpc = LoongArch::VNOR_V;
10386 break;
10387 case LoongArch::PseudoVMSKNEZ_B:
10388 MskOpc = LoongArch::VMSKNZ_B;
10389 break;
10390 case LoongArch::PseudoXVMSKLTZ_B:
10391 MskOpc = LoongArch::XVMSKLTZ_B;
10392 RC = &LoongArch::LASX256RegClass;
10393 break;
10394 case LoongArch::PseudoXVMSKLTZ_H:
10395 MskOpc = LoongArch::XVMSKLTZ_H;
10396 RC = &LoongArch::LASX256RegClass;
10397 EleBits = 16;
10398 break;
10399 case LoongArch::PseudoXVMSKLTZ_W:
10400 MskOpc = LoongArch::XVMSKLTZ_W;
10401 RC = &LoongArch::LASX256RegClass;
10402 EleBits = 32;
10403 break;
10404 case LoongArch::PseudoXVMSKLTZ_D:
10405 MskOpc = LoongArch::XVMSKLTZ_D;
10406 RC = &LoongArch::LASX256RegClass;
10407 EleBits = 64;
10408 break;
10409 case LoongArch::PseudoXVMSKGEZ_B:
10410 MskOpc = LoongArch::XVMSKGEZ_B;
10411 RC = &LoongArch::LASX256RegClass;
10412 break;
10413 case LoongArch::PseudoXVMSKEQZ_B:
10414 MskOpc = LoongArch::XVMSKNZ_B;
10415 NotOpc = LoongArch::XVNOR_V;
10416 RC = &LoongArch::LASX256RegClass;
10417 break;
10418 case LoongArch::PseudoXVMSKNEZ_B:
10419 MskOpc = LoongArch::XVMSKNZ_B;
10420 RC = &LoongArch::LASX256RegClass;
10421 break;
10422 }
10423
10424 Register Msk = MRI.createVirtualRegister(RC);
10425 if (NotOpc) {
10426 Register Tmp = MRI.createVirtualRegister(RC);
10427 BuildMI(*BB, MI, DL, TII->get(MskOpc), Tmp).addReg(Src);
10428 BuildMI(*BB, MI, DL, TII->get(NotOpc), Msk).addReg(Tmp).addReg(Tmp);
10429 } else {
10430 BuildMI(*BB, MI, DL, TII->get(MskOpc), Msk).addReg(Src);
10431 }
10432
10433 if (TRI->getRegSizeInBits(*RC) > 128) {
10434 Register Lo = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
10435 Register Hi = MRI.createVirtualRegister(&LoongArch::GPRRegClass);
10436 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPICKVE2GR_WU), Lo)
10437 .addReg(Msk)
10438 .addImm(0);
10439 BuildMI(*BB, MI, DL, TII->get(LoongArch::XVPICKVE2GR_WU), Hi)
10440 .addReg(Msk)
10441 .addImm(4);
10442 BuildMI(*BB, MI, DL,
10443 TII->get(Subtarget.is64Bit() ? LoongArch::BSTRINS_D
10444 : LoongArch::BSTRINS_W),
10445 Dst)
10446 .addReg(Lo)
10447 .addReg(Hi)
10448 .addImm(256 / EleBits - 1)
10449 .addImm(128 / EleBits);
10450 } else {
10451 BuildMI(*BB, MI, DL, TII->get(LoongArch::VPICKVE2GR_HU), Dst)
10452 .addReg(Msk)
10453 .addImm(0);
10454 }
10455
10456 MI.eraseFromParent();
10457 return BB;
10458}
10459
10460static MachineBasicBlock *
10463 assert(MI.getOpcode() == LoongArch::SplitPairF64Pseudo &&
10464 "Unexpected instruction");
10465
10466 MachineFunction &MF = *BB->getParent();
10467 DebugLoc DL = MI.getDebugLoc();
10469 Register LoReg = MI.getOperand(0).getReg();
10470 Register HiReg = MI.getOperand(1).getReg();
10471 Register SrcReg = MI.getOperand(2).getReg();
10472
10473 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVFR2GR_S_64), LoReg).addReg(SrcReg);
10474 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVFRH2GR_S), HiReg)
10475 .addReg(SrcReg, getKillRegState(MI.getOperand(2).isKill()));
10476 MI.eraseFromParent(); // The pseudo instruction is gone now.
10477 return BB;
10478}
10479
10480static MachineBasicBlock *
10483 assert(MI.getOpcode() == LoongArch::BuildPairF64Pseudo &&
10484 "Unexpected instruction");
10485
10486 MachineFunction &MF = *BB->getParent();
10487 DebugLoc DL = MI.getDebugLoc();
10490 Register TmpReg = MRI.createVirtualRegister(&LoongArch::FPR64RegClass);
10491 Register DstReg = MI.getOperand(0).getReg();
10492 Register LoReg = MI.getOperand(1).getReg();
10493 Register HiReg = MI.getOperand(2).getReg();
10494
10495 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVGR2FR_W_64), TmpReg)
10496 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()));
10497 BuildMI(*BB, MI, DL, TII.get(LoongArch::MOVGR2FRH_W), DstReg)
10498 .addReg(TmpReg)
10499 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()));
10500 MI.eraseFromParent(); // The pseudo instruction is gone now.
10501 return BB;
10502}
10503
10505 switch (MI.getOpcode()) {
10506 default:
10507 return false;
10508 case LoongArch::Select_GPR_Using_CC_GPR:
10509 return true;
10510 }
10511}
10512
10513static MachineBasicBlock *
10516 // To "insert" Select_* instructions, we actually have to insert the triangle
10517 // control-flow pattern. The incoming instructions know the destination vreg
10518 // to set, the condition code register to branch on, the true/false values to
10519 // select between, and the condcode to use to select the appropriate branch.
10520 //
10521 // We produce the following control flow:
10522 // HeadMBB
10523 // | \
10524 // | IfFalseMBB
10525 // | /
10526 // TailMBB
10527 //
10528 // When we find a sequence of selects we attempt to optimize their emission
10529 // by sharing the control flow. Currently we only handle cases where we have
10530 // multiple selects with the exact same condition (same LHS, RHS and CC).
10531 // The selects may be interleaved with other instructions if the other
10532 // instructions meet some requirements we deem safe:
10533 // - They are not pseudo instructions.
10534 // - They are debug instructions. Otherwise,
10535 // - They do not have side-effects, do not access memory and their inputs do
10536 // not depend on the results of the select pseudo-instructions.
10537 // The TrueV/FalseV operands of the selects cannot depend on the result of
10538 // previous selects in the sequence.
10539 // These conditions could be further relaxed. See the X86 target for a
10540 // related approach and more information.
10541
10542 Register LHS = MI.getOperand(1).getReg();
10543 Register RHS;
10544 if (MI.getOperand(2).isReg())
10545 RHS = MI.getOperand(2).getReg();
10546 auto CC = static_cast<unsigned>(MI.getOperand(3).getImm());
10547
10548 SmallVector<MachineInstr *, 4> SelectDebugValues;
10549 SmallSet<Register, 4> SelectDests;
10550 SelectDests.insert(MI.getOperand(0).getReg());
10551
10552 MachineInstr *LastSelectPseudo = &MI;
10553 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
10554 SequenceMBBI != E; ++SequenceMBBI) {
10555 if (SequenceMBBI->isDebugInstr())
10556 continue;
10557 if (isSelectPseudo(*SequenceMBBI)) {
10558 if (SequenceMBBI->getOperand(1).getReg() != LHS ||
10559 !SequenceMBBI->getOperand(2).isReg() ||
10560 SequenceMBBI->getOperand(2).getReg() != RHS ||
10561 SequenceMBBI->getOperand(3).getImm() != CC ||
10562 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
10563 SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
10564 break;
10565 LastSelectPseudo = &*SequenceMBBI;
10566 SequenceMBBI->collectDebugValues(SelectDebugValues);
10567 SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
10568 continue;
10569 }
10570 if (SequenceMBBI->hasUnmodeledSideEffects() ||
10571 SequenceMBBI->mayLoadOrStore() ||
10572 SequenceMBBI->usesCustomInsertionHook())
10573 break;
10574 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
10575 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
10576 }))
10577 break;
10578 }
10579
10580 const LoongArchInstrInfo &TII = *Subtarget.getInstrInfo();
10581 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10582 DebugLoc DL = MI.getDebugLoc();
10584
10585 MachineBasicBlock *HeadMBB = BB;
10586 MachineFunction *F = BB->getParent();
10587 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
10588 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
10589
10590 F->insert(I, IfFalseMBB);
10591 F->insert(I, TailMBB);
10592
10593 // Set the call frame size on entry to the new basic blocks.
10594 unsigned CallFrameSize = TII.getCallFrameSizeAt(*LastSelectPseudo);
10595 IfFalseMBB->setCallFrameSize(CallFrameSize);
10596 TailMBB->setCallFrameSize(CallFrameSize);
10597
10598 // Transfer debug instructions associated with the selects to TailMBB.
10599 for (MachineInstr *DebugInstr : SelectDebugValues) {
10600 TailMBB->push_back(DebugInstr->removeFromParent());
10601 }
10602
10603 // Move all instructions after the sequence to TailMBB.
10604 TailMBB->splice(TailMBB->end(), HeadMBB,
10605 std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
10606 // Update machine-CFG edges by transferring all successors of the current
10607 // block to the new block which will contain the Phi nodes for the selects.
10608 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
10609 // Set the successors for HeadMBB.
10610 HeadMBB->addSuccessor(IfFalseMBB);
10611 HeadMBB->addSuccessor(TailMBB);
10612
10613 // Insert appropriate branch.
10614 if (MI.getOperand(2).isImm())
10615 BuildMI(HeadMBB, DL, TII.get(CC))
10616 .addReg(LHS)
10617 .addImm(MI.getOperand(2).getImm())
10618 .addMBB(TailMBB);
10619 else
10620 BuildMI(HeadMBB, DL, TII.get(CC)).addReg(LHS).addReg(RHS).addMBB(TailMBB);
10621
10622 // IfFalseMBB just falls through to TailMBB.
10623 IfFalseMBB->addSuccessor(TailMBB);
10624
10625 // Create PHIs for all of the select pseudo-instructions.
10626 auto SelectMBBI = MI.getIterator();
10627 auto SelectEnd = std::next(LastSelectPseudo->getIterator());
10628 auto InsertionPoint = TailMBB->begin();
10629 while (SelectMBBI != SelectEnd) {
10630 auto Next = std::next(SelectMBBI);
10631 if (isSelectPseudo(*SelectMBBI)) {
10632 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
10633 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
10634 TII.get(LoongArch::PHI), SelectMBBI->getOperand(0).getReg())
10635 .addReg(SelectMBBI->getOperand(4).getReg())
10636 .addMBB(HeadMBB)
10637 .addReg(SelectMBBI->getOperand(5).getReg())
10638 .addMBB(IfFalseMBB);
10639 SelectMBBI->eraseFromParent();
10640 }
10641 SelectMBBI = Next;
10642 }
10643
10644 F->getProperties().resetNoPHIs();
10645 return TailMBB;
10646}
10647
10648MachineBasicBlock *LoongArchTargetLowering::EmitInstrWithCustomInserter(
10649 MachineInstr &MI, MachineBasicBlock *BB) const {
10650 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10651 DebugLoc DL = MI.getDebugLoc();
10652
10653 switch (MI.getOpcode()) {
10654 default:
10655 llvm_unreachable("Unexpected instr type to insert");
10656 case LoongArch::DIV_W:
10657 case LoongArch::DIV_WU:
10658 case LoongArch::MOD_W:
10659 case LoongArch::MOD_WU:
10660 case LoongArch::DIV_D:
10661 case LoongArch::DIV_DU:
10662 case LoongArch::MOD_D:
10663 case LoongArch::MOD_DU:
10664 return insertDivByZeroTrap(MI, BB);
10665 break;
10666 case LoongArch::WRFCSR: {
10667 BuildMI(*BB, MI, DL, TII->get(LoongArch::MOVGR2FCSR),
10668 LoongArch::FCSR0 + MI.getOperand(0).getImm())
10669 .addReg(MI.getOperand(1).getReg());
10670 MI.eraseFromParent();
10671 return BB;
10672 }
10673 case LoongArch::RDFCSR: {
10674 MachineInstr *ReadFCSR =
10675 BuildMI(*BB, MI, DL, TII->get(LoongArch::MOVFCSR2GR),
10676 MI.getOperand(0).getReg())
10677 .addReg(LoongArch::FCSR0 + MI.getOperand(1).getImm());
10678 ReadFCSR->getOperand(1).setIsUndef();
10679 MI.eraseFromParent();
10680 return BB;
10681 }
10682 case LoongArch::Select_GPR_Using_CC_GPR:
10683 return emitSelectPseudo(MI, BB, Subtarget);
10684 case LoongArch::BuildPairF64Pseudo:
10685 return emitBuildPairF64Pseudo(MI, BB, Subtarget);
10686 case LoongArch::SplitPairF64Pseudo:
10687 return emitSplitPairF64Pseudo(MI, BB, Subtarget);
10688 case LoongArch::PseudoXVINSGR2VR_B:
10689 case LoongArch::PseudoXVINSGR2VR_H:
10690 return emitPseudoXVINSGR2VR(MI, BB, Subtarget);
10691 case LoongArch::PseudoCTPOP_B:
10692 case LoongArch::PseudoCTPOP_H:
10693 case LoongArch::PseudoCTPOP_W:
10694 case LoongArch::PseudoCTPOP_D:
10695 case LoongArch::PseudoCTPOP_H_LA32:
10696 case LoongArch::PseudoCTPOP_W_LA32:
10697 return emitPseudoCTPOP(MI, BB, Subtarget);
10698 case LoongArch::PseudoVMSKLTZ_B:
10699 case LoongArch::PseudoVMSKLTZ_H:
10700 case LoongArch::PseudoVMSKLTZ_W:
10701 case LoongArch::PseudoVMSKLTZ_D:
10702 case LoongArch::PseudoVMSKGEZ_B:
10703 case LoongArch::PseudoVMSKEQZ_B:
10704 case LoongArch::PseudoVMSKNEZ_B:
10705 case LoongArch::PseudoXVMSKLTZ_B:
10706 case LoongArch::PseudoXVMSKLTZ_H:
10707 case LoongArch::PseudoXVMSKLTZ_W:
10708 case LoongArch::PseudoXVMSKLTZ_D:
10709 case LoongArch::PseudoXVMSKGEZ_B:
10710 case LoongArch::PseudoXVMSKEQZ_B:
10711 case LoongArch::PseudoXVMSKNEZ_B:
10712 return emitPseudoVMSKCOND(MI, BB, Subtarget);
10713 case TargetOpcode::STATEPOINT:
10714 // STATEPOINT is a pseudo instruction which has no implicit defs/uses
10715 // while bl call instruction (where statepoint will be lowered at the
10716 // end) has implicit def. This def is early-clobber as it will be set at
10717 // the moment of the call and earlier than any use is read.
10718 // Add this implicit dead def here as a workaround.
10719 MI.addOperand(*MI.getMF(),
10721 LoongArch::R1, /*isDef*/ true,
10722 /*isImp*/ true, /*isKill*/ false, /*isDead*/ true,
10723 /*isUndef*/ false, /*isEarlyClobber*/ true));
10724 if (!Subtarget.is64Bit())
10725 report_fatal_error("STATEPOINT is only supported on 64-bit targets");
10726 return emitPatchPoint(MI, BB);
10727 case LoongArch::PROBED_STACKALLOC_DYN:
10728 return emitDynamicProbedAlloc(MI, BB);
10729 }
10730}
10731
10733 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10734 unsigned *Fast) const {
10735 if (!Subtarget.hasUAL())
10736 return false;
10737
10738 // TODO: set reasonable speed number.
10739 if (Fast)
10740 *Fast = 1;
10741 return true;
10742}
10743
10744//===----------------------------------------------------------------------===//
10745// Calling Convention Implementation
10746//===----------------------------------------------------------------------===//
10747
10748// Eight general-purpose registers a0-a7 used for passing integer arguments,
10749// with a0-a1 reused to return values. Generally, the GPRs are used to pass
10750// fixed-point arguments, and floating-point arguments when no FPR is available
10751// or with soft float ABI.
10752const MCPhysReg ArgGPRs[] = {LoongArch::R4, LoongArch::R5, LoongArch::R6,
10753 LoongArch::R7, LoongArch::R8, LoongArch::R9,
10754 LoongArch::R10, LoongArch::R11};
10755
10756// PreserveNone calling convention:
10757// Arguments may be passed in any general-purpose registers except:
10758// - R1 : return address register
10759// - R22 : frame pointer
10760// - R31 : base pointer
10761//
10762// All general-purpose registers are treated as caller-saved,
10763// except R1 (RA) and R22 (FP).
10764//
10765// Non-volatile registers are allocated first so that a function
10766// can call normal functions without having to spill and reload
10767// argument registers.
10769 LoongArch::R23, LoongArch::R24, LoongArch::R25, LoongArch::R26,
10770 LoongArch::R27, LoongArch::R28, LoongArch::R29, LoongArch::R30,
10771 LoongArch::R4, LoongArch::R5, LoongArch::R6, LoongArch::R7,
10772 LoongArch::R8, LoongArch::R9, LoongArch::R10, LoongArch::R11,
10773 LoongArch::R12, LoongArch::R13, LoongArch::R14, LoongArch::R15,
10774 LoongArch::R16, LoongArch::R17, LoongArch::R18, LoongArch::R19,
10775 LoongArch::R20};
10776
10777// Eight floating-point registers fa0-fa7 used for passing floating-point
10778// arguments, and fa0-fa1 are also used to return values.
10779const MCPhysReg ArgFPR32s[] = {LoongArch::F0, LoongArch::F1, LoongArch::F2,
10780 LoongArch::F3, LoongArch::F4, LoongArch::F5,
10781 LoongArch::F6, LoongArch::F7};
10782// FPR32 and FPR64 alias each other.
10784 LoongArch::F0_64, LoongArch::F1_64, LoongArch::F2_64, LoongArch::F3_64,
10785 LoongArch::F4_64, LoongArch::F5_64, LoongArch::F6_64, LoongArch::F7_64};
10786
10787const MCPhysReg ArgVRs[] = {LoongArch::VR0, LoongArch::VR1, LoongArch::VR2,
10788 LoongArch::VR3, LoongArch::VR4, LoongArch::VR5,
10789 LoongArch::VR6, LoongArch::VR7};
10790
10791const MCPhysReg ArgXRs[] = {LoongArch::XR0, LoongArch::XR1, LoongArch::XR2,
10792 LoongArch::XR3, LoongArch::XR4, LoongArch::XR5,
10793 LoongArch::XR6, LoongArch::XR7};
10794
10796 switch (State.getCallingConv()) {
10798 if (!State.isVarArg())
10799 return State.AllocateReg(PreserveNoneArgGPRs);
10800 [[fallthrough]];
10801 default:
10802 return State.AllocateReg(ArgGPRs);
10803 }
10804}
10805
10806// Pass a 2*GRLen argument that has been split into two GRLen values through
10807// registers or the stack as necessary.
10808static bool CC_LoongArchAssign2GRLen(unsigned GRLen, CCState &State,
10809 CCValAssign VA1, ISD::ArgFlagsTy ArgFlags1,
10810 unsigned ValNo2, MVT ValVT2, MVT LocVT2,
10811 ISD::ArgFlagsTy ArgFlags2) {
10812 unsigned GRLenInBytes = GRLen / 8;
10813 if (Register Reg = allocateArgGPR(State)) {
10814 // At least one half can be passed via register.
10815 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10816 VA1.getLocVT(), CCValAssign::Full));
10817 } else {
10818 // Both halves must be passed on the stack, with proper alignment.
10819 Align StackAlign =
10820 std::max(Align(GRLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10821 State.addLoc(
10823 State.AllocateStack(GRLenInBytes, StackAlign),
10824 VA1.getLocVT(), CCValAssign::Full));
10825 State.addLoc(CCValAssign::getMem(
10826 ValNo2, ValVT2, State.AllocateStack(GRLenInBytes, Align(GRLenInBytes)),
10827 LocVT2, CCValAssign::Full));
10828 return false;
10829 }
10830 if (Register Reg = allocateArgGPR(State)) {
10831 // The second half can also be passed via register.
10832 State.addLoc(
10833 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10834 } else {
10835 // The second half is passed via the stack, without additional alignment.
10836 State.addLoc(CCValAssign::getMem(
10837 ValNo2, ValVT2, State.AllocateStack(GRLenInBytes, Align(GRLenInBytes)),
10838 LocVT2, CCValAssign::Full));
10839 }
10840 return false;
10841}
10842
10843// Implements the LoongArch calling convention. Returns true upon failure.
10845 unsigned ValNo, MVT ValVT,
10846 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
10847 CCState &State, bool IsRet, Type *OrigTy) {
10848 unsigned GRLen = DL.getLargestLegalIntTypeSizeInBits();
10849 assert((GRLen == 32 || GRLen == 64) && "Unspport GRLen");
10850 MVT GRLenVT = GRLen == 32 ? MVT::i32 : MVT::i64;
10851 MVT LocVT = ValVT;
10852
10853 // Any return value split into more than two values can't be returned
10854 // directly.
10855 if (IsRet && ValNo > 1)
10856 return true;
10857
10858 // If passing a variadic argument, or if no FPR is available.
10859 bool UseGPRForFloat = true;
10860
10861 switch (ABI) {
10862 default:
10863 llvm_unreachable("Unexpected ABI");
10864 break;
10869 UseGPRForFloat = ArgFlags.isVarArg();
10870 break;
10873 break;
10874 }
10875
10876 // If this is a variadic argument, the LoongArch calling convention requires
10877 // that it is assigned an 'even' or 'aligned' register if it has (2*GRLen)/8
10878 // byte alignment. An aligned register should be used regardless of whether
10879 // the original argument was split during legalisation or not. The argument
10880 // will not be passed by registers if the original type is larger than
10881 // 2*GRLen, so the register alignment rule does not apply.
10882 unsigned TwoGRLenInBytes = (2 * GRLen) / 8;
10883 if (ArgFlags.isVarArg() &&
10884 ArgFlags.getNonZeroOrigAlign() == TwoGRLenInBytes &&
10885 DL.getTypeAllocSize(OrigTy) == TwoGRLenInBytes) {
10886 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10887 // Skip 'odd' register if necessary.
10888 if (RegIdx != std::size(ArgGPRs) && RegIdx % 2 == 1)
10889 State.AllocateReg(ArgGPRs);
10890 }
10891
10892 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10893 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10894 State.getPendingArgFlags();
10895
10896 assert(PendingLocs.size() == PendingArgFlags.size() &&
10897 "PendingLocs and PendingArgFlags out of sync");
10898
10899 // FPR32 and FPR64 alias each other.
10900 if (State.getFirstUnallocated(ArgFPR32s) == std::size(ArgFPR32s))
10901 UseGPRForFloat = true;
10902
10903 if (UseGPRForFloat && ValVT == MVT::f32) {
10904 LocVT = GRLenVT;
10905 LocInfo = CCValAssign::BCvt;
10906 } else if (UseGPRForFloat && GRLen == 64 && ValVT == MVT::f64) {
10907 LocVT = MVT::i64;
10908 LocInfo = CCValAssign::BCvt;
10909 } else if (UseGPRForFloat && GRLen == 32 && ValVT == MVT::f64) {
10910 // Handle passing f64 on LA32D with a soft float ABI or when floating point
10911 // registers are exhausted.
10912 assert(PendingLocs.empty() && "Can't lower f64 if it is split");
10913 // Depending on available argument GPRS, f64 may be passed in a pair of
10914 // GPRs, split between a GPR and the stack, or passed completely on the
10915 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10916 // cases.
10917 MCRegister Reg = allocateArgGPR(State);
10918 if (!Reg) {
10919 int64_t StackOffset = State.AllocateStack(8, Align(8));
10920 State.addLoc(
10921 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10922 return false;
10923 }
10924 LocVT = MVT::i32;
10925 State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10926 MCRegister HiReg = allocateArgGPR(State);
10927 if (HiReg) {
10928 State.addLoc(
10929 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
10930 } else {
10931 int64_t StackOffset = State.AllocateStack(4, Align(4));
10932 State.addLoc(
10933 CCValAssign::getCustomMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10934 }
10935 return false;
10936 }
10937
10938 // Split arguments might be passed indirectly, so keep track of the pending
10939 // values.
10940 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10941 LocVT = GRLenVT;
10942 LocInfo = CCValAssign::Indirect;
10943 PendingLocs.push_back(
10944 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10945 PendingArgFlags.push_back(ArgFlags);
10946 if (!ArgFlags.isSplitEnd()) {
10947 return false;
10948 }
10949 }
10950
10951 // If the split argument only had two elements, it should be passed directly
10952 // in registers or on the stack.
10953 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10954 PendingLocs.size() <= 2) {
10955 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10956 // Apply the normal calling convention rules to the first half of the
10957 // split argument.
10958 CCValAssign VA = PendingLocs[0];
10959 ISD::ArgFlagsTy AF = PendingArgFlags[0];
10960 PendingLocs.clear();
10961 PendingArgFlags.clear();
10962 return CC_LoongArchAssign2GRLen(GRLen, State, VA, AF, ValNo, ValVT, LocVT,
10963 ArgFlags);
10964 }
10965
10966 // Allocate to a register if possible, or else a stack slot.
10967 Register Reg;
10968 unsigned StoreSizeBytes = GRLen / 8;
10969 Align StackAlign = Align(GRLen / 8);
10970
10971 if (ValVT == MVT::f32 && !UseGPRForFloat) {
10972 Reg = State.AllocateReg(ArgFPR32s);
10973 } else if (ValVT == MVT::f64 && !UseGPRForFloat) {
10974 Reg = State.AllocateReg(ArgFPR64s);
10975 } else if (ValVT.is128BitVector()) {
10976 Reg = State.AllocateReg(ArgVRs);
10977 UseGPRForFloat = false;
10978 StoreSizeBytes = 16;
10979 StackAlign = Align(16);
10980 } else if (ValVT.is256BitVector()) {
10981 Reg = State.AllocateReg(ArgXRs);
10982 UseGPRForFloat = false;
10983 StoreSizeBytes = 32;
10984 StackAlign = Align(32);
10985 } else {
10986 Reg = allocateArgGPR(State);
10987 }
10988
10989 unsigned StackOffset =
10990 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10991
10992 // If we reach this point and PendingLocs is non-empty, we must be at the
10993 // end of a split argument that must be passed indirectly.
10994 if (!PendingLocs.empty()) {
10995 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10996 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10997 for (auto &It : PendingLocs) {
10998 if (Reg)
10999 It.convertToReg(Reg);
11000 else
11001 It.convertToMem(StackOffset);
11002 State.addLoc(It);
11003 }
11004 PendingLocs.clear();
11005 PendingArgFlags.clear();
11006 return false;
11007 }
11008 assert((!UseGPRForFloat || LocVT == GRLenVT) &&
11009 "Expected an GRLenVT at this stage");
11010
11011 if (Reg) {
11012 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
11013 return false;
11014 }
11015
11016 // When a floating-point value is passed on the stack, no bit-cast is needed.
11017 if (ValVT.isFloatingPoint()) {
11018 LocVT = ValVT;
11019 LocInfo = CCValAssign::Full;
11020 }
11021
11022 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
11023 return false;
11024}
11025
11026void LoongArchTargetLowering::analyzeInputArgs(
11027 MachineFunction &MF, CCState &CCInfo,
11028 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
11029 LoongArchCCAssignFn Fn) const {
11030 FunctionType *FType = MF.getFunction().getFunctionType();
11031 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11032 MVT ArgVT = Ins[i].VT;
11033 Type *ArgTy = nullptr;
11034 if (IsRet)
11035 ArgTy = FType->getReturnType();
11036 else if (Ins[i].isOrigArg())
11037 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
11039 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
11040 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, CCValAssign::Full, Ins[i].Flags,
11041 CCInfo, IsRet, ArgTy)) {
11042 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " << ArgVT
11043 << '\n');
11044 llvm_unreachable("");
11045 }
11046 }
11047}
11048
11049void LoongArchTargetLowering::analyzeOutputArgs(
11050 MachineFunction &MF, CCState &CCInfo,
11051 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
11052 CallLoweringInfo *CLI, LoongArchCCAssignFn Fn) const {
11053 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11054 MVT ArgVT = Outs[i].VT;
11055 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
11057 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
11058 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, CCValAssign::Full, Outs[i].Flags,
11059 CCInfo, IsRet, OrigTy)) {
11060 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " << ArgVT
11061 << "\n");
11062 llvm_unreachable("");
11063 }
11064 }
11065}
11066
11067// Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
11068// values.
11070 const CCValAssign &VA, const SDLoc &DL) {
11071 switch (VA.getLocInfo()) {
11072 default:
11073 llvm_unreachable("Unexpected CCValAssign::LocInfo");
11074 case CCValAssign::Full:
11076 break;
11077 case CCValAssign::BCvt:
11078 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
11079 Val = DAG.getNode(LoongArchISD::MOVGR2FR_W_LA64, DL, MVT::f32, Val);
11080 else
11081 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
11082 break;
11083 }
11084 return Val;
11085}
11086
11088 const CCValAssign &VA, const SDLoc &DL,
11089 const ISD::InputArg &In,
11093 EVT LocVT = VA.getLocVT();
11094 SDValue Val;
11095 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
11096 Register VReg = RegInfo.createVirtualRegister(RC);
11097 RegInfo.addLiveIn(VA.getLocReg(), VReg);
11098 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
11099
11100 // If input is sign extended from 32 bits, note it for the OptW pass.
11101 if (In.isOrigArg()) {
11102 Argument *OrigArg = MF.getFunction().getArg(In.getOrigArgIndex());
11103 if (OrigArg->getType()->isIntegerTy()) {
11104 unsigned BitWidth = OrigArg->getType()->getIntegerBitWidth();
11105 // An input zero extended from i31 can also be considered sign extended.
11106 if ((BitWidth <= 32 && In.Flags.isSExt()) ||
11107 (BitWidth < 32 && In.Flags.isZExt())) {
11110 LAFI->addSExt32Register(VReg);
11111 }
11112 }
11113 }
11114
11115 return convertLocVTToValVT(DAG, Val, VA, DL);
11116}
11117
11118// The caller is responsible for loading the full value if the argument is
11119// passed with CCValAssign::Indirect.
11121 const CCValAssign &VA, const SDLoc &DL) {
11123 MachineFrameInfo &MFI = MF.getFrameInfo();
11124 EVT ValVT = VA.getValVT();
11125 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
11126 /*IsImmutable=*/true);
11127 SDValue FIN = DAG.getFrameIndex(
11129
11130 ISD::LoadExtType ExtType;
11131 switch (VA.getLocInfo()) {
11132 default:
11133 llvm_unreachable("Unexpected CCValAssign::LocInfo");
11134 case CCValAssign::Full:
11136 case CCValAssign::BCvt:
11137 ExtType = ISD::NON_EXTLOAD;
11138 break;
11139 }
11140 return DAG.getExtLoad(
11141 ExtType, DL, VA.getLocVT(), Chain, FIN,
11143}
11144
11146 const CCValAssign &VA,
11147 const CCValAssign &HiVA,
11148 const SDLoc &DL) {
11149 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
11150 "Unexpected VA");
11152 MachineFrameInfo &MFI = MF.getFrameInfo();
11154
11155 assert(VA.isRegLoc() && "Expected register VA assignment");
11156
11157 Register LoVReg = RegInfo.createVirtualRegister(&LoongArch::GPRRegClass);
11158 RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
11159 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
11160 SDValue Hi;
11161 if (HiVA.isMemLoc()) {
11162 // Second half of f64 is passed on the stack.
11163 int FI = MFI.CreateFixedObject(4, HiVA.getLocMemOffset(),
11164 /*IsImmutable=*/true);
11165 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
11166 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
11168 } else {
11169 // Second half of f64 is passed in another GPR.
11170 Register HiVReg = RegInfo.createVirtualRegister(&LoongArch::GPRRegClass);
11171 RegInfo.addLiveIn(HiVA.getLocReg(), HiVReg);
11172 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
11173 }
11174 return DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64, Lo, Hi);
11175}
11176
11178 const CCValAssign &VA, const SDLoc &DL) {
11179 EVT LocVT = VA.getLocVT();
11180
11181 switch (VA.getLocInfo()) {
11182 default:
11183 llvm_unreachable("Unexpected CCValAssign::LocInfo");
11184 case CCValAssign::Full:
11185 break;
11186 case CCValAssign::BCvt:
11187 if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
11188 Val = DAG.getNode(LoongArchISD::MOVFR2GR_S_LA64, DL, MVT::i64, Val);
11189 else
11190 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
11191 break;
11192 }
11193 return Val;
11194}
11195
11196static bool CC_LoongArch_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
11197 CCValAssign::LocInfo LocInfo,
11198 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
11199 CCState &State) {
11200 if (LocVT == MVT::i32 || LocVT == MVT::i64) {
11201 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, SpLim
11202 // s0 s1 s2 s3 s4 s5 s6 s7 s8
11203 static const MCPhysReg GPRList[] = {
11204 LoongArch::R23, LoongArch::R24, LoongArch::R25,
11205 LoongArch::R26, LoongArch::R27, LoongArch::R28,
11206 LoongArch::R29, LoongArch::R30, LoongArch::R31};
11207 if (MCRegister Reg = State.AllocateReg(GPRList)) {
11208 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
11209 return false;
11210 }
11211 }
11212
11213 if (LocVT == MVT::f32) {
11214 // Pass in STG registers: F1, F2, F3, F4
11215 // fs0,fs1,fs2,fs3
11216 static const MCPhysReg FPR32List[] = {LoongArch::F24, LoongArch::F25,
11217 LoongArch::F26, LoongArch::F27};
11218 if (MCRegister Reg = State.AllocateReg(FPR32List)) {
11219 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
11220 return false;
11221 }
11222 }
11223
11224 if (LocVT == MVT::f64) {
11225 // Pass in STG registers: D1, D2, D3, D4
11226 // fs4,fs5,fs6,fs7
11227 static const MCPhysReg FPR64List[] = {LoongArch::F28_64, LoongArch::F29_64,
11228 LoongArch::F30_64, LoongArch::F31_64};
11229 if (MCRegister Reg = State.AllocateReg(FPR64List)) {
11230 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
11231 return false;
11232 }
11233 }
11234
11235 report_fatal_error("No registers left in GHC calling convention");
11236 return true;
11237}
11238
11239// Transform physical registers into virtual registers.
11241 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
11242 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
11243 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
11244
11246
11247 switch (CallConv) {
11248 default:
11249 llvm_unreachable("Unsupported calling convention");
11250 case CallingConv::C:
11251 case CallingConv::Fast:
11254 break;
11255 case CallingConv::GHC:
11256 if (!MF.getSubtarget().hasFeature(LoongArch::FeatureBasicF) ||
11257 !MF.getSubtarget().hasFeature(LoongArch::FeatureBasicD))
11259 "GHC calling convention requires the F and D extensions");
11260 }
11261
11262 const Function &Func = MF.getFunction();
11263 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11264 MVT GRLenVT = Subtarget.getGRLenVT();
11265 unsigned GRLenInBytes = Subtarget.getGRLen() / 8;
11266
11267 // Check if this function has any musttail calls. If so, incoming indirect
11268 // arg pointers must be saved in virtual registers so they survive across
11269 // basic blocks (the SelectionDAG is cleared between BBs). Only do this
11270 // when needed to avoid adding register pressure to non-musttail functions.
11271 bool HasMusttail = llvm::any_of(Func, [](const BasicBlock &BB) {
11272 return llvm::any_of(BB, [](const Instruction &I) {
11273 if (const auto *CI = dyn_cast<CallInst>(&I))
11274 return CI->isMustTailCall();
11275 return false;
11276 });
11277 });
11278 // Used with varargs to acumulate store chains.
11279 std::vector<SDValue> OutChains;
11280
11281 // Assign locations to all of the incoming arguments.
11283 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11284
11285 if (CallConv == CallingConv::GHC)
11287 else
11288 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, CC_LoongArch);
11289
11290 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
11291 CCValAssign &VA = ArgLocs[i];
11292 SDValue ArgValue;
11293 // Passing f64 on LA32D with a soft float ABI must be handled as a special
11294 // case.
11295 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11296 assert(VA.needsCustom());
11297 ArgValue = unpackF64OnLA32DSoftABI(DAG, Chain, VA, ArgLocs[++i], DL);
11298 } else if (VA.isRegLoc())
11299 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, Ins[InsIdx], *this);
11300 else
11301 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
11302 if (VA.getLocInfo() == CCValAssign::Indirect) {
11303 // If the original argument was split and passed by reference, we need to
11304 // load all parts of it here (using the same address).
11305 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
11307 unsigned ArgIndex = Ins[InsIdx].OrigArgIndex;
11308 if (HasMusttail) {
11311 Register VReg =
11312 MF.getRegInfo().createVirtualRegister(&LoongArch::GPRRegClass);
11313 Chain = DAG.getCopyToReg(Chain, DL, VReg, ArgValue);
11314 LAFI->setIncomingIndirectArg(ArgIndex, VReg);
11315 }
11316 unsigned ArgPartOffset = Ins[InsIdx].PartOffset;
11317 assert(ArgPartOffset == 0);
11318 while (i + 1 != e && Ins[InsIdx + 1].OrigArgIndex == ArgIndex) {
11319 CCValAssign &PartVA = ArgLocs[i + 1];
11320 unsigned PartOffset = Ins[InsIdx + 1].PartOffset - ArgPartOffset;
11321 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11322 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
11323 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
11325 ++i;
11326 ++InsIdx;
11327 }
11328 continue;
11329 }
11330 InVals.push_back(ArgValue);
11331 }
11332
11333 if (IsVarArg) {
11335 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
11336 const TargetRegisterClass *RC = &LoongArch::GPRRegClass;
11337 MachineFrameInfo &MFI = MF.getFrameInfo();
11338 MachineRegisterInfo &RegInfo = MF.getRegInfo();
11339 auto *LoongArchFI = MF.getInfo<LoongArchMachineFunctionInfo>();
11340
11341 // Offset of the first variable argument from stack pointer, and size of
11342 // the vararg save area. For now, the varargs save area is either zero or
11343 // large enough to hold a0-a7.
11344 int VaArgOffset, VarArgsSaveSize;
11345
11346 // If all registers are allocated, then all varargs must be passed on the
11347 // stack and we don't need to save any argregs.
11348 if (ArgRegs.size() == Idx) {
11349 VaArgOffset = CCInfo.getStackSize();
11350 VarArgsSaveSize = 0;
11351 } else {
11352 VarArgsSaveSize = GRLenInBytes * (ArgRegs.size() - Idx);
11353 VaArgOffset = -VarArgsSaveSize;
11354 }
11355
11356 // Record the frame index of the first variable argument
11357 // which is a value necessary to VASTART.
11358 int FI = MFI.CreateFixedObject(GRLenInBytes, VaArgOffset, true);
11359 LoongArchFI->setVarArgsFrameIndex(FI);
11360
11361 // If saving an odd number of registers then create an extra stack slot to
11362 // ensure that the frame pointer is 2*GRLen-aligned, which in turn ensures
11363 // offsets to even-numbered registered remain 2*GRLen-aligned.
11364 if (Idx % 2) {
11365 MFI.CreateFixedObject(GRLenInBytes, VaArgOffset - (int)GRLenInBytes,
11366 true);
11367 VarArgsSaveSize += GRLenInBytes;
11368 }
11369
11370 // Copy the integer registers that may have been used for passing varargs
11371 // to the vararg save area.
11372 for (unsigned I = Idx; I < ArgRegs.size();
11373 ++I, VaArgOffset += GRLenInBytes) {
11374 const Register Reg = RegInfo.createVirtualRegister(RC);
11375 RegInfo.addLiveIn(ArgRegs[I], Reg);
11376 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, GRLenVT);
11377 FI = MFI.CreateFixedObject(GRLenInBytes, VaArgOffset, true);
11378 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11379 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
11381 cast<StoreSDNode>(Store.getNode())
11382 ->getMemOperand()
11383 ->setValue((Value *)nullptr);
11384 OutChains.push_back(Store);
11385 }
11386 LoongArchFI->setVarArgsSaveSize(VarArgsSaveSize);
11387 }
11388
11389 // All stores are grouped in one node to allow the matching between
11390 // the size of Ins and InVals. This only happens for vararg functions.
11391 if (!OutChains.empty()) {
11392 OutChains.push_back(Chain);
11393 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
11394 }
11395
11396 return Chain;
11397}
11398
11400 return CI->isTailCall();
11401}
11402
11403// Check if the return value is used as only a return value, as otherwise
11404// we can't perform a tail-call.
11406 SDValue &Chain) const {
11407 if (N->getNumValues() != 1)
11408 return false;
11409 if (!N->hasNUsesOfValue(1, 0))
11410 return false;
11411
11412 SDNode *Copy = *N->user_begin();
11413 if (Copy->getOpcode() != ISD::CopyToReg)
11414 return false;
11415
11416 // If the ISD::CopyToReg has a glue operand, we conservatively assume it
11417 // isn't safe to perform a tail call.
11418 if (Copy->getGluedNode())
11419 return false;
11420
11421 // The copy must be used by a LoongArchISD::RET, and nothing else.
11422 bool HasRet = false;
11423 for (SDNode *Node : Copy->users()) {
11424 if (Node->getOpcode() != LoongArchISD::RET)
11425 return false;
11426 HasRet = true;
11427 }
11428
11429 if (!HasRet)
11430 return false;
11431
11432 Chain = Copy->getOperand(0);
11433 return true;
11434}
11435
11436// Check whether the call is eligible for tail call optimization.
11437bool LoongArchTargetLowering::isEligibleForTailCallOptimization(
11438 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
11439 const SmallVectorImpl<CCValAssign> &ArgLocs) const {
11440
11441 auto CalleeCC = CLI.CallConv;
11442 auto &Outs = CLI.Outs;
11443 auto &Caller = MF.getFunction();
11444 auto CallerCC = Caller.getCallingConv();
11445
11446 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
11447
11448 // Byval parameters hand the function a pointer directly into the stack area
11449 // we want to reuse during a tail call. Working around this *is* possible
11450 // but less efficient and uglier in LowerCall. For musttail, there is no
11451 // workaround today: a byval arg requires a local copy that becomes invalid
11452 // after the tail call deallocates the caller's frame, so rejecting here
11453 // (and triggering reportFatalInternalError in LowerCall) is safer than
11454 // miscompiling.
11455 for (auto &Arg : Outs)
11456 if (Arg.Flags.isByVal())
11457 return false;
11458
11459 // musttail bypasses the remaining checks: the checks either reject cases
11460 // we handle specially (indirect args are forwarded via incoming pointers,
11461 // stack-passed args reuse the matching incoming layout, sret is forwarded
11462 // like any other pointer arg) or are optimizations not applicable to
11463 // mandatory tail calls.
11464 if (IsMustTail)
11465 return true;
11466
11467 // Do not tail call opt if the stack is used to pass parameters.
11468 if (CCInfo.getStackSize() != 0)
11469 return false;
11470
11471 // Do not tail call opt if any parameters need to be passed indirectly.
11472 for (auto &VA : ArgLocs)
11473 if (VA.getLocInfo() == CCValAssign::Indirect)
11474 return false;
11475
11476 // Do not tail call opt if either caller or callee uses struct return
11477 // semantics.
11478 auto IsCallerStructRet = Caller.hasStructRetAttr();
11479 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
11480 if (IsCallerStructRet || IsCalleeStructRet)
11481 return false;
11482
11483 // The callee has to preserve all registers the caller needs to preserve.
11484 const LoongArchRegisterInfo *TRI = Subtarget.getRegisterInfo();
11485 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
11486 if (CalleeCC != CallerCC) {
11487 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
11488 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
11489 return false;
11490 }
11491 return true;
11492}
11493
11495 return DAG.getDataLayout().getPrefTypeAlign(
11496 VT.getTypeForEVT(*DAG.getContext()));
11497}
11498
11499// Lower a call to a callseq_start + CALL + callseq_end chain, and add input
11500// and output parameter nodes.
11501SDValue
11503 SmallVectorImpl<SDValue> &InVals) const {
11504 SelectionDAG &DAG = CLI.DAG;
11505 SDLoc &DL = CLI.DL;
11507 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
11509 SDValue Chain = CLI.Chain;
11510 SDValue Callee = CLI.Callee;
11511 CallingConv::ID CallConv = CLI.CallConv;
11512 bool IsVarArg = CLI.IsVarArg;
11513 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11514 MVT GRLenVT = Subtarget.getGRLenVT();
11515 bool &IsTailCall = CLI.IsTailCall;
11516
11518
11519 // Analyze the operands of the call, assigning locations to each operand.
11521 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11522
11523 if (CallConv == CallingConv::GHC)
11524 ArgCCInfo.AnalyzeCallOperands(Outs, CC_LoongArch_GHC);
11525 else
11526 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, CC_LoongArch);
11527
11528 // Check if it's really possible to do a tail call.
11529 if (IsTailCall)
11530 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
11531
11532 if (IsTailCall)
11533 ++NumTailCalls;
11534 else if (CLI.CB && CLI.CB->isMustTailCall())
11535 report_fatal_error("failed to perform tail call elimination on a call "
11536 "site marked musttail");
11537
11538 // Get a count of how many bytes are to be pushed on the stack.
11539 unsigned NumBytes = ArgCCInfo.getStackSize();
11540
11541 // Create local copies for byval args.
11542 SmallVector<SDValue> ByValArgs;
11543 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11544 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11545 if (!Flags.isByVal())
11546 continue;
11547
11548 SDValue Arg = OutVals[i];
11549 unsigned Size = Flags.getByValSize();
11550 Align Alignment = Flags.getNonZeroByValAlign();
11551
11552 int FI =
11553 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
11554 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11555 SDValue SizeNode = DAG.getConstant(Size, DL, GRLenVT);
11556
11557 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, Alignment,
11558 /*IsVolatile=*/false,
11559 /*AlwaysInline=*/false, /*CI=*/nullptr, std::nullopt,
11561 ByValArgs.push_back(FIPtr);
11562 }
11563
11564 if (!IsTailCall)
11565 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
11566
11567 // Copy argument values to their designated locations.
11569 SmallVector<SDValue> MemOpChains;
11570 SDValue StackPtr;
11571 for (unsigned i = 0, j = 0, e = ArgLocs.size(), OutIdx = 0; i != e;
11572 ++i, ++OutIdx) {
11573 CCValAssign &VA = ArgLocs[i];
11574 SDValue ArgValue = OutVals[OutIdx];
11575 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
11576
11577 // Handle passing f64 on LA32D with a soft float ABI as a special case.
11578 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11579 assert(VA.isRegLoc() && "Expected register VA assignment");
11580 assert(VA.needsCustom());
11581 SDValue SplitF64 =
11582 DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
11583 DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11584 SDValue Lo = SplitF64.getValue(0);
11585 SDValue Hi = SplitF64.getValue(1);
11586
11587 Register RegLo = VA.getLocReg();
11588 RegsToPass.push_back(std::make_pair(RegLo, Lo));
11589
11590 // Get the CCValAssign for the Hi part.
11591 CCValAssign &HiVA = ArgLocs[++i];
11592
11593 if (HiVA.isMemLoc()) {
11594 // Second half of f64 is passed on the stack.
11595 if (!StackPtr.getNode())
11596 StackPtr = DAG.getCopyFromReg(Chain, DL, LoongArch::R3, PtrVT);
11598 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11599 DAG.getIntPtrConstant(HiVA.getLocMemOffset(), DL));
11600 // Emit the store.
11601 MemOpChains.push_back(DAG.getStore(
11602 Chain, DL, Hi, Address,
11604 } else {
11605 // Second half of f64 is passed in another GPR.
11606 Register RegHigh = HiVA.getLocReg();
11607 RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11608 }
11609 continue;
11610 }
11611
11612 // Promote the value if needed.
11613 // For now, only handle fully promoted and indirect arguments.
11614 if (VA.getLocInfo() == CCValAssign::Indirect) {
11615 // For musttail calls, reuse incoming indirect pointers instead of
11616 // creating new stack temporaries. The incoming pointers point to the
11617 // caller's caller's frame, which remains valid after a tail call.
11618 if (IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
11621 unsigned CallArgIdx = Outs[OutIdx].OrigArgIndex;
11622
11623 // Resolve which formal parameter is being passed at this call
11624 // position.
11625 //
11626 // FIXME: Ins[].OrigArgIndex is Argument::getArgNo() (unfiltered),
11627 // but Outs[].OrigArgIndex is an index into a filtered arg list
11628 // (empty types removed, via CallLoweringInfo in the target-
11629 // independent layer). IncomingIndirectArgs is keyed by the
11630 // caller's unfiltered Argument::getArgNo(), so we have to walk
11631 // the caller's formals (same filter) to translate the index.
11632 // This target-independent asymmetry should be normalized so
11633 // backends do not need to re-derive the mapping.
11634 //
11635 // Steps:
11636 // 1. Find the call operand at filtered position CallArgIdx.
11637 // 2. If it is an Argument, use getArgNo() directly (same filter
11638 // for caller formals and call operands).
11639 // 3. Otherwise (computed value), walk the caller's formals and
11640 // skip empty types to map the filtered index to getArgNo().
11641 const Argument *FormalArg = nullptr;
11642 unsigned FilteredIdx = 0;
11643 for (const auto &CallArg : CLI.CB->args()) {
11644 if (CallArg->getType()->isEmptyTy())
11645 continue;
11646 if (FilteredIdx == CallArgIdx) {
11647 FormalArg = dyn_cast<Argument>(CallArg);
11648 break;
11649 }
11650 ++FilteredIdx;
11651 }
11652
11653 // For forwarded args, getArgNo() gives the unfiltered index directly.
11654 // For computed args, walk the caller's formals to resolve it.
11655 unsigned FormalArgIdx = CallArgIdx;
11656 if (FormalArg) {
11657 FormalArgIdx = FormalArg->getArgNo();
11658 } else {
11659 FilteredIdx = 0;
11660 for (const auto &Arg : MF.getFunction().args()) {
11661 if (Arg.getType()->isEmptyTy())
11662 continue;
11663 if (FilteredIdx == CallArgIdx) {
11664 FormalArgIdx = Arg.getArgNo();
11665 break;
11666 }
11667 ++FilteredIdx;
11668 }
11669 }
11670
11671 Register VReg = LAFI->getIncomingIndirectArg(FormalArgIdx);
11672 SDValue CopyOp = DAG.getCopyFromReg(Chain, DL, VReg, PtrVT);
11673 // Thread the CopyFromReg output chain through MemOpChains so the
11674 // TokenFactor below sequences the copy with any stores we emit
11675 // for this argument.
11676 MemOpChains.push_back(CopyOp.getValue(1));
11677 SDValue IncomingPtr = CopyOp;
11678
11679 if (!FormalArg) {
11680 // Computed value: store into the incoming indirect pointer for the
11681 // same-position formal parameter (musttail guarantees matching
11682 // prototypes, so types match). The pointer survives the tail call
11683 // since it points to the caller's caller's frame.
11684 //
11685 // The data-flow edge through IncomingPtr already prevents the
11686 // store from being scheduled before the CopyFromReg. Threading
11687 // CopyOp.getValue(1) (the copy's output chain) into the store
11688 // makes that ordering explicit on the chain edge as well, which
11689 // is the convention for memory ops chaining off their producers.
11690 MemOpChains.push_back(
11691 DAG.getStore(CopyOp.getValue(1), DL, ArgValue, IncomingPtr,
11693 // Store any split parts at their respective offsets.
11694 unsigned ArgPartOffset = Outs[OutIdx].PartOffset;
11695 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == CallArgIdx) {
11696 SDValue PartValue = OutVals[OutIdx + 1];
11697 unsigned PartOffset = Outs[OutIdx + 1].PartOffset - ArgPartOffset;
11698 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11699 SDValue Addr =
11700 DAG.getNode(ISD::ADD, DL, PtrVT, IncomingPtr, Offset);
11701 MemOpChains.push_back(
11702 DAG.getStore(CopyOp.getValue(1), DL, PartValue, Addr,
11704 ++i;
11705 ++OutIdx;
11706 }
11707 }
11708 ArgValue = IncomingPtr;
11709
11710 // Skip any remaining split parts (for forwarded args, they are
11711 // covered by the forwarded pointer).
11712 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == CallArgIdx) {
11713 ++i;
11714 ++OutIdx;
11715 }
11716 } else {
11717 // Store the argument in a stack slot and pass its address.
11718 Align StackAlign =
11719 std::max(getPrefTypeAlign(Outs[OutIdx].ArgVT, DAG),
11720 getPrefTypeAlign(ArgValue.getValueType(), DAG));
11721 TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11722 // If the original argument was split and passed by reference, we need
11723 // to store the required parts of it here (and pass just one address).
11724 unsigned ArgIndex = Outs[OutIdx].OrigArgIndex;
11725 unsigned ArgPartOffset = Outs[OutIdx].PartOffset;
11726 assert(ArgPartOffset == 0);
11727 // Calculate the total size to store. We don't have access to what we're
11728 // actually storing other than performing the loop and collecting the
11729 // info.
11731 while (i + 1 != e && Outs[OutIdx + 1].OrigArgIndex == ArgIndex) {
11732 SDValue PartValue = OutVals[OutIdx + 1];
11733 unsigned PartOffset = Outs[OutIdx + 1].PartOffset - ArgPartOffset;
11734 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11735 EVT PartVT = PartValue.getValueType();
11736 StoredSize += PartVT.getStoreSize();
11737 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11738 Parts.push_back(std::make_pair(PartValue, Offset));
11739 ++i;
11740 ++OutIdx;
11741 }
11742 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11743 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11744 MemOpChains.push_back(
11745 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11747 for (const auto &Part : Parts) {
11748 SDValue PartValue = Part.first;
11749 SDValue PartOffset = Part.second;
11751 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11752 MemOpChains.push_back(
11753 DAG.getStore(Chain, DL, PartValue, Address,
11755 }
11756 ArgValue = SpillSlot;
11757 }
11758 } else {
11759 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
11760 }
11761
11762 // Use local copy if it is a byval arg.
11763 if (Flags.isByVal())
11764 ArgValue = ByValArgs[j++];
11765
11766 if (VA.isRegLoc()) {
11767 // Queue up the argument copies and emit them at the end.
11768 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11769 } else {
11770 assert(VA.isMemLoc() && "Argument not register or memory");
11771 assert((!IsTailCall || (CLI.CB && CLI.CB->isMustTailCall())) &&
11772 "Tail call not allowed if stack is used for passing parameters");
11773
11774 // Work out the address of the stack slot.
11775 if (!StackPtr.getNode())
11776 StackPtr = DAG.getCopyFromReg(Chain, DL, LoongArch::R3, PtrVT);
11778 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11780
11781 // Emit the store.
11782 MemOpChains.push_back(
11783 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11784 }
11785 }
11786
11787 // Join the stores, which are independent of one another.
11788 if (!MemOpChains.empty())
11789 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11790
11791 SDValue Glue;
11792
11793 // Build a sequence of copy-to-reg nodes, chained and glued together.
11794 for (auto &Reg : RegsToPass) {
11795 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11796 Glue = Chain.getValue(1);
11797 }
11798
11799 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11800 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11801 // split it and then direct call can be matched by PseudoCALL_SMALL.
11803 const GlobalValue *GV = S->getGlobal();
11804 unsigned OpFlags = getTargetMachine().shouldAssumeDSOLocal(GV)
11807 Callee = DAG.getTargetGlobalAddress(S->getGlobal(), DL, PtrVT, 0, OpFlags);
11808 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11809 unsigned OpFlags = getTargetMachine().shouldAssumeDSOLocal(nullptr)
11812 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11813 }
11814
11815 // The first call operand is the chain and the second is the target address.
11817 Ops.push_back(Chain);
11818 Ops.push_back(Callee);
11819
11820 // Add argument registers to the end of the list so that they are
11821 // known live into the call.
11822 for (auto &Reg : RegsToPass)
11823 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11824
11825 if (!IsTailCall) {
11826 // Add a register mask operand representing the call-preserved registers.
11827 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11828 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11829 assert(Mask && "Missing call preserved mask for calling convention");
11830 Ops.push_back(DAG.getRegisterMask(Mask));
11831 }
11832
11833 // Glue the call to the argument copies, if any.
11834 if (Glue.getNode())
11835 Ops.push_back(Glue);
11836
11837 // Emit the call.
11838 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11839 unsigned Op;
11840 switch (DAG.getTarget().getCodeModel()) {
11841 default:
11842 report_fatal_error("Unsupported code model");
11843 case CodeModel::Small:
11844 Op = IsTailCall ? LoongArchISD::TAIL : LoongArchISD::CALL;
11845 break;
11846 case CodeModel::Medium:
11847 Op = IsTailCall ? LoongArchISD::TAIL_MEDIUM : LoongArchISD::CALL_MEDIUM;
11848 break;
11849 case CodeModel::Large:
11850 assert(Subtarget.is64Bit() && "Large code model requires LA64");
11851 Op = IsTailCall ? LoongArchISD::TAIL_LARGE : LoongArchISD::CALL_LARGE;
11852 break;
11853 }
11854
11855 if (IsTailCall) {
11857 SDValue Ret = DAG.getNode(Op, DL, NodeTys, Ops);
11858 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
11859 return Ret;
11860 }
11861
11862 Chain = DAG.getNode(Op, DL, NodeTys, Ops);
11863 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11864 Glue = Chain.getValue(1);
11865
11866 // Mark the end of the call, which is glued to the call itself.
11867 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
11868 Glue = Chain.getValue(1);
11869
11870 // Assign locations to each value returned by this call.
11872 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11873 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_LoongArch);
11874
11875 // Copy all of the result registers out of their specified physreg.
11876 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
11877 auto &VA = RVLocs[i];
11878 // Copy the value out.
11879 SDValue RetValue =
11880 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11881 // Glue the RetValue to the end of the call sequence.
11882 Chain = RetValue.getValue(1);
11883 Glue = RetValue.getValue(2);
11884
11885 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11886 assert(VA.needsCustom());
11887 SDValue RetValue2 = DAG.getCopyFromReg(Chain, DL, RVLocs[++i].getLocReg(),
11888 MVT::i32, Glue);
11889 Chain = RetValue2.getValue(1);
11890 Glue = RetValue2.getValue(2);
11891 RetValue = DAG.getNode(LoongArchISD::BUILD_PAIR_F64, DL, MVT::f64,
11892 RetValue, RetValue2);
11893 } else
11894 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
11895
11896 InVals.push_back(RetValue);
11897 }
11898
11899 return Chain;
11900}
11901
11903 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11905 const Type *RetTy) const {
11907 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11908
11909 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11910 LoongArchABI::ABI ABI =
11911 MF.getSubtarget<LoongArchSubtarget>().getTargetABI();
11912 if (CC_LoongArch(MF.getDataLayout(), ABI, i, Outs[i].VT, CCValAssign::Full,
11913 Outs[i].Flags, CCInfo, /*IsRet=*/true, nullptr))
11914 return false;
11915 }
11916 return true;
11917}
11918
11920 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
11922 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
11923 SelectionDAG &DAG) const {
11924 // Stores the assignment of the return value to a location.
11926
11927 // Info about the registers and stack slot.
11928 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11929 *DAG.getContext());
11930
11931 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11932 nullptr, CC_LoongArch);
11933 if (CallConv == CallingConv::GHC && !RVLocs.empty())
11934 report_fatal_error("GHC functions return void only");
11935 SDValue Glue;
11936 SmallVector<SDValue, 4> RetOps(1, Chain);
11937
11938 // Copy the result values into the output registers.
11939 for (unsigned i = 0, e = RVLocs.size(), OutIdx = 0; i < e; ++i, ++OutIdx) {
11940 SDValue Val = OutVals[OutIdx];
11941 CCValAssign &VA = RVLocs[i];
11942 assert(VA.isRegLoc() && "Can only return in registers!");
11943
11944 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11945 // Handle returning f64 on LA32D with a soft float ABI.
11946 assert(VA.isRegLoc() && "Expected return via registers");
11947 assert(VA.needsCustom());
11948 SDValue SplitF64 = DAG.getNode(LoongArchISD::SPLIT_PAIR_F64, DL,
11949 DAG.getVTList(MVT::i32, MVT::i32), Val);
11950 SDValue Lo = SplitF64.getValue(0);
11951 SDValue Hi = SplitF64.getValue(1);
11952 Register RegLo = VA.getLocReg();
11953 Register RegHi = RVLocs[++i].getLocReg();
11954
11955 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11956 Glue = Chain.getValue(1);
11957 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11958 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11959 Glue = Chain.getValue(1);
11960 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11961 } else {
11962 // Handle a 'normal' return.
11963 Val = convertValVTToLocVT(DAG, Val, VA, DL);
11964 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11965
11966 // Guarantee that all emitted copies are stuck together.
11967 Glue = Chain.getValue(1);
11968 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11969 }
11970 }
11971
11972 RetOps[0] = Chain; // Update chain.
11973
11974 // Add the glue node if we have it.
11975 if (Glue.getNode())
11976 RetOps.push_back(Glue);
11977
11978 return DAG.getNode(LoongArchISD::RET, DL, MVT::Other, RetOps);
11979}
11980
11981// Check if a constant splat can be generated using [x]vldi, where imm[12] == 1.
11982// Note: The following prefixes are excluded:
11983// imm[11:8] == 4'b0000, 4'b0100, 4'b1000
11984// as they can be represented using [x]vrepli.[whb]
11986 const APInt &SplatValue, const unsigned SplatBitSize) const {
11987 uint64_t RequiredImm = 0;
11988 uint64_t V = SplatValue.getZExtValue();
11989 if (SplatBitSize == 16 && !(V & 0x00FF)) {
11990 // 4'b0101
11991 RequiredImm = (0b10101 << 8) | (V >> 8);
11992 return {true, RequiredImm};
11993 } else if (SplatBitSize == 32) {
11994 // 4'b0001
11995 if (!(V & 0xFFFF00FF)) {
11996 RequiredImm = (0b10001 << 8) | (V >> 8);
11997 return {true, RequiredImm};
11998 }
11999 // 4'b0010
12000 if (!(V & 0xFF00FFFF)) {
12001 RequiredImm = (0b10010 << 8) | (V >> 16);
12002 return {true, RequiredImm};
12003 }
12004 // 4'b0011
12005 if (!(V & 0x00FFFFFF)) {
12006 RequiredImm = (0b10011 << 8) | (V >> 24);
12007 return {true, RequiredImm};
12008 }
12009 // 4'b0110
12010 if ((V & 0xFFFF00FF) == 0xFF) {
12011 RequiredImm = (0b10110 << 8) | (V >> 8);
12012 return {true, RequiredImm};
12013 }
12014 // 4'b0111
12015 if ((V & 0xFF00FFFF) == 0xFFFF) {
12016 RequiredImm = (0b10111 << 8) | (V >> 16);
12017 return {true, RequiredImm};
12018 }
12019 // 4'b1010
12020 if ((V & 0x7E07FFFF) == 0x3E000000 || (V & 0x7E07FFFF) == 0x40000000) {
12021 RequiredImm =
12022 (0b11010 << 8) | (((V >> 24) & 0xC0) ^ 0x40) | ((V >> 19) & 0x3F);
12023 return {true, RequiredImm};
12024 }
12025 } else if (SplatBitSize == 64) {
12026 // 4'b1011
12027 if ((V & 0xFFFFFFFF7E07FFFFULL) == 0x3E000000ULL ||
12028 (V & 0xFFFFFFFF7E07FFFFULL) == 0x40000000ULL) {
12029 RequiredImm =
12030 (0b11011 << 8) | (((V >> 24) & 0xC0) ^ 0x40) | ((V >> 19) & 0x3F);
12031 return {true, RequiredImm};
12032 }
12033 // 4'b1100
12034 if ((V & 0x7FC0FFFFFFFFFFFFULL) == 0x4000000000000000ULL ||
12035 (V & 0x7FC0FFFFFFFFFFFFULL) == 0x3FC0000000000000ULL) {
12036 RequiredImm =
12037 (0b11100 << 8) | (((V >> 56) & 0xC0) ^ 0x40) | ((V >> 48) & 0x3F);
12038 return {true, RequiredImm};
12039 }
12040 // 4'b1001
12041 auto sameBitsPreByte = [](uint64_t x) -> std::pair<bool, uint8_t> {
12042 uint8_t res = 0;
12043 for (int i = 0; i < 8; ++i) {
12044 uint8_t byte = x & 0xFF;
12045 if (byte == 0 || byte == 0xFF)
12046 res |= ((byte & 1) << i);
12047 else
12048 return {false, 0};
12049 x >>= 8;
12050 }
12051 return {true, res};
12052 };
12053 auto [IsSame, Suffix] = sameBitsPreByte(V);
12054 if (IsSame) {
12055 RequiredImm = (0b11001 << 8) | Suffix;
12056 return {true, RequiredImm};
12057 }
12058 }
12059 return {false, RequiredImm};
12060}
12061
12063 EVT VT) const {
12064 if (!Subtarget.hasExtLSX())
12065 return false;
12066
12067 if (VT == MVT::f32) {
12068 uint64_t masked = Imm.bitcastToAPInt().getZExtValue() & 0x7e07ffff;
12069 return (masked == 0x3e000000 || masked == 0x40000000);
12070 }
12071
12072 if (VT == MVT::f64) {
12073 uint64_t masked = Imm.bitcastToAPInt().getZExtValue() & 0x7fc0ffffffffffff;
12074 return (masked == 0x3fc0000000000000 || masked == 0x4000000000000000);
12075 }
12076
12077 return false;
12078}
12079
12080// Only form FP_TO_SINT_SAT from clamp/NaN-guard idioms when it will be lowered
12081// to a single [X]VFTINTRZ/FTINTRZ, otherwise the generic expansion is worse
12082// than the original sequence.
12083bool LoongArchTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
12084 EVT VT) const {
12085 if (!isOperationLegalOrCustom(Op, VT))
12086 return false;
12087 if (VT.isVector())
12088 return FPVT.getScalarSizeInBits() == VT.getScalarSizeInBits();
12089 if (FPVT == MVT::f32)
12090 return VT.getSizeInBits() == 32 || Subtarget.hasBasicD();
12091 return FPVT == MVT::f64 && Subtarget.hasBasicD();
12092}
12093
12095LoongArchTargetLowering::getFPImmAction(const APFloat &Imm, EVT VT,
12096 bool ForCodeSize) const {
12097 // TODO: Maybe need more checks here after vector extension is supported.
12098 if (VT == MVT::f32 && !Subtarget.hasBasicF())
12100 if (VT == MVT::f64 && !Subtarget.hasBasicD())
12102 if (Imm.isZero() || isFPImmVLDILegal(Imm, VT))
12103 return FPImmAction::Legal;
12104
12105 // Immediates the size of a GPR are built from their bits. Others are built in
12106 // lowerConstantFP.
12107 if (VT.getSizeInBits() == Subtarget.getGRLen() && isFPImmCheapInGPR(Imm, VT))
12108 return FPImmAction::Bitcast;
12110}
12111
12113 EVT VT) const {
12114 // Count the instructions to generate the bits and move them to a float
12115 // register.
12116 auto Seq =
12117 LoongArchMatInt::generateInstSeq(Imm.bitcastToAPInt().getSExtValue());
12118 int InsNum = Seq.size() + ((VT == MVT::f64 && !Subtarget.is64Bit()) ? 2 : 1);
12119 return InsNum <= MaterializeFPImmInsNum || Imm.isOne();
12120}
12121
12123 return true;
12124}
12125
12127 return true;
12128}
12129
12130bool LoongArchTargetLowering::shouldInsertFencesForAtomic(
12131 const Instruction *I) const {
12132 if (!Subtarget.is64Bit())
12133 return isa<LoadInst>(I) || isa<StoreInst>(I);
12134
12135 if (isa<LoadInst>(I))
12136 return true;
12137
12138 // On LA64, atomic store operations with IntegerBitWidth of 32 and 64 do not
12139 // require fences beacuse we can use amswap_db.[w/d].
12140 Type *Ty = I->getOperand(0)->getType();
12141 if (isa<StoreInst>(I) && Ty->isIntegerTy()) {
12142 unsigned Size = Ty->getIntegerBitWidth();
12143 return (Size == 8 || Size == 16);
12144 }
12145
12146 return false;
12147}
12148
12151 EVT VT) const {
12152 if (!VT.isVector())
12153 return getPointerTy(DL);
12155}
12156
12158 unsigned AddressSpace, EVT MemVT, const MachineFunction &MF) const {
12159 // Do not merge to float value size (128 or 256 bits) if no implicit
12160 // float attribute is set.
12161 bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
12162 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
12163 if (NoFloat)
12164 return MemVT.getSizeInBits() <= MaxIntSize;
12165
12166 // Make sure we don't merge greater than our maximum supported vector width.
12167 if (Subtarget.hasExtLASX())
12168 MaxIntSize = 256;
12169 else if (Subtarget.hasExtLSX())
12170 MaxIntSize = 128;
12171
12172 return MemVT.getSizeInBits() <= MaxIntSize;
12173}
12174
12176 EVT VT = Y.getValueType();
12177
12178 if (VT.isVector())
12179 return Subtarget.hasExtLSX() && VT.isInteger();
12180
12181 return VT.isScalarInteger() && !isa<ConstantSDNode>(Y);
12182}
12183
12186 MachineFunction &MF, unsigned Intrinsic) const {
12187 switch (Intrinsic) {
12188 default:
12189 return;
12190 case Intrinsic::loongarch_masked_atomicrmw_xchg_i32:
12191 case Intrinsic::loongarch_masked_atomicrmw_add_i32:
12192 case Intrinsic::loongarch_masked_atomicrmw_sub_i32:
12193 case Intrinsic::loongarch_masked_atomicrmw_nand_i32: {
12194 IntrinsicInfo Info;
12196 Info.memVT = MVT::i32;
12197 Info.ptrVal = I.getArgOperand(0);
12198 Info.offset = 0;
12199 Info.align = Align(4);
12202 Infos.push_back(Info);
12203 return;
12204 // TODO: Add more Intrinsics later.
12205 }
12206 }
12207}
12208
12209// When -mlamcas is enabled, MinCmpXchgSizeInBits will be set to 8,
12210// atomicrmw and/or/xor operations with operands less than 32 bits cannot be
12211// expanded to am{and/or/xor}[_db].w through AtomicExpandPass. To prevent
12212// regression, we need to implement it manually.
12215
12217 Op == AtomicRMWInst::And) &&
12218 "Unable to expand");
12219 unsigned MinWordSize = 4;
12220
12221 IRBuilder<> Builder(AI);
12222 LLVMContext &Ctx = Builder.getContext();
12223 const DataLayout &DL = AI->getDataLayout();
12224 Type *ValueType = AI->getType();
12225 Type *WordType = Type::getIntNTy(Ctx, MinWordSize * 8);
12226
12227 Value *Addr = AI->getPointerOperand();
12228 PointerType *PtrTy = cast<PointerType>(Addr->getType());
12229 IntegerType *IntTy = DL.getIndexType(Ctx, PtrTy->getAddressSpace());
12230
12231 Value *AlignedAddr = Builder.CreateIntrinsic(
12232 Intrinsic::ptrmask, {PtrTy, IntTy},
12233 {Addr, ConstantInt::get(IntTy, ~(uint64_t)(MinWordSize - 1))}, nullptr,
12234 "AlignedAddr");
12235
12236 Value *AddrInt = Builder.CreatePtrToInt(Addr, IntTy);
12237 Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
12238 Value *ShiftAmt = Builder.CreateShl(PtrLSB, 3);
12239 ShiftAmt = Builder.CreateTrunc(ShiftAmt, WordType, "ShiftAmt");
12240 Value *Mask = Builder.CreateShl(
12241 ConstantInt::get(WordType,
12242 (1 << (DL.getTypeStoreSize(ValueType) * 8)) - 1),
12243 ShiftAmt, "Mask");
12244 Value *Inv_Mask = Builder.CreateNot(Mask, "Inv_Mask");
12245 Value *ValOperand_Shifted =
12246 Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), WordType),
12247 ShiftAmt, "ValOperand_Shifted");
12248 Value *NewOperand;
12249 if (Op == AtomicRMWInst::And)
12250 NewOperand = Builder.CreateOr(ValOperand_Shifted, Inv_Mask, "AndOperand");
12251 else
12252 NewOperand = ValOperand_Shifted;
12253
12254 AtomicRMWInst *NewAI =
12255 Builder.CreateAtomicRMW(Op, AlignedAddr, NewOperand, Align(MinWordSize),
12256 AI->getOrdering(), AI->getSyncScopeID());
12257
12258 Value *Shift = Builder.CreateLShr(NewAI, ShiftAmt, "shifted");
12259 Value *Trunc = Builder.CreateTrunc(Shift, ValueType, "extracted");
12260 Value *FinalOldResult = Builder.CreateBitCast(Trunc, ValueType);
12261 AI->replaceAllUsesWith(FinalOldResult);
12262 AI->eraseFromParent();
12263}
12264
12267 const AtomicRMWInst *AI) const {
12268 // TODO: Add more AtomicRMWInst that needs to be extended.
12269
12270 // Since floating-point operation requires a non-trivial set of data
12271 // operations, use CmpXChg to expand.
12272 if (AI->isFloatingPointOperation() ||
12278
12279 if (Subtarget.hasLAM_BH() && Subtarget.is64Bit() &&
12282 AI->getOperation() == AtomicRMWInst::Sub)) {
12284 }
12285
12286 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12287 if (Subtarget.hasLAMCAS()) {
12288 if (Size < 32 && (AI->getOperation() == AtomicRMWInst::And ||
12292 if (AI->getOperation() == AtomicRMWInst::Nand || Size < 32)
12294 }
12295
12296 if (Size == 8 || Size == 16)
12299}
12300
12301static Intrinsic::ID
12303 AtomicRMWInst::BinOp BinOp) {
12304 if (GRLen == 64) {
12305 switch (BinOp) {
12306 default:
12307 llvm_unreachable("Unexpected AtomicRMW BinOp");
12309 return Intrinsic::loongarch_masked_atomicrmw_xchg_i64;
12310 case AtomicRMWInst::Add:
12311 return Intrinsic::loongarch_masked_atomicrmw_add_i64;
12312 case AtomicRMWInst::Sub:
12313 return Intrinsic::loongarch_masked_atomicrmw_sub_i64;
12315 return Intrinsic::loongarch_masked_atomicrmw_nand_i64;
12317 return Intrinsic::loongarch_masked_atomicrmw_umax_i64;
12319 return Intrinsic::loongarch_masked_atomicrmw_umin_i64;
12320 case AtomicRMWInst::Max:
12321 return Intrinsic::loongarch_masked_atomicrmw_max_i64;
12322 case AtomicRMWInst::Min:
12323 return Intrinsic::loongarch_masked_atomicrmw_min_i64;
12324 // TODO: support other AtomicRMWInst.
12325 }
12326 }
12327
12328 if (GRLen == 32) {
12329 switch (BinOp) {
12330 default:
12331 llvm_unreachable("Unexpected AtomicRMW BinOp");
12333 return Intrinsic::loongarch_masked_atomicrmw_xchg_i32;
12334 case AtomicRMWInst::Add:
12335 return Intrinsic::loongarch_masked_atomicrmw_add_i32;
12336 case AtomicRMWInst::Sub:
12337 return Intrinsic::loongarch_masked_atomicrmw_sub_i32;
12339 return Intrinsic::loongarch_masked_atomicrmw_nand_i32;
12341 return Intrinsic::loongarch_masked_atomicrmw_umax_i32;
12343 return Intrinsic::loongarch_masked_atomicrmw_umin_i32;
12344 case AtomicRMWInst::Max:
12345 return Intrinsic::loongarch_masked_atomicrmw_max_i32;
12346 case AtomicRMWInst::Min:
12347 return Intrinsic::loongarch_masked_atomicrmw_min_i32;
12348 // TODO: support other AtomicRMWInst.
12349 }
12350 }
12351
12352 llvm_unreachable("Unexpected GRLen\n");
12353}
12354
12357 const AtomicCmpXchgInst *CI) const {
12358
12359 if (Subtarget.hasLAMCAS())
12361
12363 if (Size == 8 || Size == 16)
12366}
12367
12369 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
12370 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
12371 unsigned GRLen = Subtarget.getGRLen();
12372 AtomicOrdering FailOrd = CI->getFailureOrdering();
12373 Value *FailureOrdering =
12374 Builder.getIntN(Subtarget.getGRLen(), static_cast<uint64_t>(FailOrd));
12375 Intrinsic::ID CmpXchgIntrID = Intrinsic::loongarch_masked_cmpxchg_i32;
12376 if (GRLen == 64) {
12377 CmpXchgIntrID = Intrinsic::loongarch_masked_cmpxchg_i64;
12378 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
12379 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
12380 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12381 }
12382 Type *Tys[] = {AlignedAddr->getType()};
12383 Value *Result = Builder.CreateIntrinsic(
12384 CmpXchgIntrID, Tys, {AlignedAddr, CmpVal, NewVal, Mask, FailureOrdering});
12385 if (GRLen == 64)
12386 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12387 return Result;
12388}
12389
12391 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
12392 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
12393 // In the case of an atomicrmw xchg with a constant 0/-1 operand, replace
12394 // the atomic instruction with an AtomicRMWInst::And/Or with appropriate
12395 // mask, as this produces better code than the LL/SC loop emitted by
12396 // int_loongarch_masked_atomicrmw_xchg.
12397 if (AI->getOperation() == AtomicRMWInst::Xchg &&
12400 if (CVal->isZero())
12401 return Builder.CreateAtomicRMW(AtomicRMWInst::And, AlignedAddr,
12402 Builder.CreateNot(Mask, "Inv_Mask"),
12403 AI->getAlign(), Ord);
12404 if (CVal->isMinusOne())
12405 return Builder.CreateAtomicRMW(AtomicRMWInst::Or, AlignedAddr, Mask,
12406 AI->getAlign(), Ord);
12407 }
12408
12409 unsigned GRLen = Subtarget.getGRLen();
12410 Value *Ordering =
12411 Builder.getIntN(GRLen, static_cast<uint64_t>(AI->getOrdering()));
12412 Type *Tys[] = {AlignedAddr->getType()};
12414 AI->getModule(),
12416
12417 if (GRLen == 64) {
12418 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
12419 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12420 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
12421 }
12422
12423 Value *Result;
12424
12425 // Must pass the shift amount needed to sign extend the loaded value prior
12426 // to performing a signed comparison for min/max. ShiftAmt is the number of
12427 // bits to shift the value into position. Pass GRLen-ShiftAmt-ValWidth, which
12428 // is the number of bits to left+right shift the value in order to
12429 // sign-extend.
12430 if (AI->getOperation() == AtomicRMWInst::Min ||
12432 const DataLayout &DL = AI->getDataLayout();
12433 unsigned ValWidth =
12434 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
12435 Value *SextShamt =
12436 Builder.CreateSub(Builder.getIntN(GRLen, GRLen - ValWidth), ShiftAmt);
12437 Result = Builder.CreateCall(LlwOpScwLoop,
12438 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
12439 } else {
12440 Result =
12441 Builder.CreateCall(LlwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
12442 }
12443
12444 if (GRLen == 64)
12445 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12446 return Result;
12447}
12448
12450 const MachineFunction &MF, EVT VT) const {
12451 VT = VT.getScalarType();
12452
12453 if (!VT.isSimple())
12454 return false;
12455
12456 switch (VT.getSimpleVT().SimpleTy) {
12457 case MVT::f32:
12458 case MVT::f64:
12459 return true;
12460 default:
12461 break;
12462 }
12463
12464 return false;
12465}
12466
12468 ExceptionHandling EH, const Constant *PersonalityFn) const {
12469 return LoongArch::R4;
12470}
12471
12473 ExceptionHandling EH, const Constant *PersonalityFn) const {
12474 return LoongArch::R5;
12475}
12476
12477//===----------------------------------------------------------------------===//
12478// Target Optimization Hooks
12479//===----------------------------------------------------------------------===//
12480
12483 // Feature FRECIPE instructions relative accuracy is 2^-14.
12484 // IEEE float has 23 digits and double has 52 digits.
12485 int RefinementSteps = VT.getScalarType() == MVT::f64 ? 2 : 1;
12486 return RefinementSteps;
12487}
12488
12489static bool
12491 assert(Subtarget.hasFrecipe() &&
12492 "Reciprocal estimate queried on unsupported target");
12493
12494 if (!VT.isSimple())
12495 return false;
12496
12497 switch (VT.getSimpleVT().SimpleTy) {
12498 case MVT::f32:
12499 // f32 is the base type for reciprocal estimate instructions.
12500 return true;
12501
12502 case MVT::f64:
12503 return Subtarget.hasBasicD();
12504
12505 case MVT::v4f32:
12506 case MVT::v2f64:
12507 return Subtarget.hasExtLSX();
12508
12509 case MVT::v8f32:
12510 case MVT::v4f64:
12511 return Subtarget.hasExtLASX();
12512
12513 default:
12514 return false;
12515 }
12516}
12517
12519 SelectionDAG &DAG, int Enabled,
12520 int &RefinementSteps,
12521 bool &UseOneConstNR,
12522 bool Reciprocal) const {
12524 "Enabled should never be Disabled here");
12525
12526 if (!Subtarget.hasFrecipe())
12527 return SDValue();
12528
12529 SDLoc DL(Operand);
12530 EVT VT = Operand.getValueType();
12531
12532 // Check supported types.
12533 if (!isSupportedReciprocalEstimateType(VT, Subtarget))
12534 return SDValue();
12535
12536 // Handle refinement steps.
12537 if (RefinementSteps == ReciprocalEstimate::Unspecified)
12538 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12539
12540 // LoongArch only has FRSQRTE which is 1.0 / sqrt(x).
12541 UseOneConstNR = false;
12542 SDValue Rsqrt = DAG.getNode(LoongArchISD::FRSQRTE, DL, VT, Operand);
12543
12544 // If the caller wants 1.0 / sqrt(x), or if further refinement steps
12545 // are needed (which rely on the reciprocal form), return the raw reciprocal
12546 // estimate.
12547 if (Reciprocal || RefinementSteps > 0)
12548 return Rsqrt;
12549
12550 // Otherwise, return sqrt(x) by multiplying with the operand.
12551 return DAG.getNode(ISD::FMUL, DL, VT, Operand, Rsqrt);
12552}
12553
12555 SelectionDAG &DAG,
12556 int Enabled,
12557 int &RefinementSteps) const {
12559 "Enabled should never be Disabled here");
12560
12561 if (!Subtarget.hasFrecipe())
12562 return SDValue();
12563
12564 SDLoc DL(Operand);
12565 EVT VT = Operand.getValueType();
12566
12567 // Check supported types.
12568 if (!isSupportedReciprocalEstimateType(VT, Subtarget))
12569 return SDValue();
12570
12571 if (RefinementSteps == ReciprocalEstimate::Unspecified)
12572 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12573
12574 // FRECIPE computes 1.0 / x.
12575 return DAG.getNode(LoongArchISD::FRECIPE, DL, VT, Operand);
12576}
12577
12578//===----------------------------------------------------------------------===//
12579// LoongArch Inline Assembly Support
12580//===----------------------------------------------------------------------===//
12581
12583LoongArchTargetLowering::getConstraintType(StringRef Constraint) const {
12584 // LoongArch specific constraints in GCC: config/loongarch/constraints.md
12585 //
12586 // 'f': A floating-point register (if available).
12587 // 'k': A memory operand whose address is formed by a base register and
12588 // (optionally scaled) index register.
12589 // 'l': A signed 16-bit constant.
12590 // 'm': A memory operand whose address is formed by a base register and
12591 // offset that is suitable for use in instructions with the same
12592 // addressing mode as st.w and ld.w.
12593 // 'q': A general-purpose register except for $r0 and $r1 (for the csrxchg
12594 // instruction)
12595 // 'I': A signed 12-bit constant (for arithmetic instructions).
12596 // 'J': Integer zero.
12597 // 'K': An unsigned 12-bit constant (for logic instructions).
12598 // "ZB": An address that is held in a general-purpose register. The offset is
12599 // zero.
12600 // "ZC": A memory operand whose address is formed by a base register and
12601 // offset that is suitable for use in instructions with the same
12602 // addressing mode as ll.w and sc.w.
12603 if (Constraint.size() == 1) {
12604 switch (Constraint[0]) {
12605 default:
12606 break;
12607 case 'f':
12608 case 'q':
12609 return C_RegisterClass;
12610 case 'l':
12611 case 'I':
12612 case 'J':
12613 case 'K':
12614 return C_Immediate;
12615 case 'k':
12616 return C_Memory;
12617 }
12618 }
12619
12620 if (Constraint == "ZC" || Constraint == "ZB")
12621 return C_Memory;
12622
12623 // 'm' is handled here.
12624 return TargetLowering::getConstraintType(Constraint);
12625}
12626
12627InlineAsm::ConstraintCode LoongArchTargetLowering::getInlineAsmMemConstraint(
12628 StringRef ConstraintCode) const {
12629 return StringSwitch<InlineAsm::ConstraintCode>(ConstraintCode)
12633 .Default(TargetLowering::getInlineAsmMemConstraint(ConstraintCode));
12634}
12635
12636std::pair<unsigned, const TargetRegisterClass *>
12637LoongArchTargetLowering::getRegForInlineAsmConstraint(
12638 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12639 // First, see if this is a constraint that directly corresponds to a LoongArch
12640 // register class.
12641 if (Constraint.size() == 1) {
12642 switch (Constraint[0]) {
12643 case 'r':
12644 // TODO: Support fixed vectors up to GRLen?
12645 if (VT.isVector())
12646 break;
12647 return std::make_pair(0U, &LoongArch::GPRRegClass);
12648 case 'q':
12649 return std::make_pair(0U, &LoongArch::GPRNoR0R1RegClass);
12650 case 'f':
12651 if (Subtarget.hasBasicF() && VT == MVT::f32)
12652 return std::make_pair(0U, &LoongArch::FPR32RegClass);
12653 if (Subtarget.hasBasicD() && VT == MVT::f64)
12654 return std::make_pair(0U, &LoongArch::FPR64RegClass);
12655 if (Subtarget.hasExtLSX() &&
12656 TRI->isTypeLegalForClass(LoongArch::LSX128RegClass, VT))
12657 return std::make_pair(0U, &LoongArch::LSX128RegClass);
12658 if (Subtarget.hasExtLSX() && VT == MVT::i128)
12659 return std::make_pair(0U, &LoongArch::LSX128RegClass);
12660 if (Subtarget.hasExtLASX() &&
12661 TRI->isTypeLegalForClass(LoongArch::LASX256RegClass, VT))
12662 return std::make_pair(0U, &LoongArch::LASX256RegClass);
12663 break;
12664 default:
12665 break;
12666 }
12667 }
12668
12669 // TargetLowering::getRegForInlineAsmConstraint uses the name of the TableGen
12670 // record (e.g. the "R0" in `def R0`) to choose registers for InlineAsm
12671 // constraints while the official register name is prefixed with a '$'. So we
12672 // clip the '$' from the original constraint string (e.g. {$r0} to {r0}.)
12673 // before it being parsed. And TargetLowering::getRegForInlineAsmConstraint is
12674 // case insensitive, so no need to convert the constraint to upper case here.
12675 //
12676 // For now, no need to support ABI names (e.g. `$a0`) as clang will correctly
12677 // decode the usage of register name aliases into their official names. And
12678 // AFAIK, the not yet upstreamed `rustc` for LoongArch will always use
12679 // official register names.
12680 if (Constraint.starts_with("{$r") || Constraint.starts_with("{$f") ||
12681 Constraint.starts_with("{$vr") || Constraint.starts_with("{$xr")) {
12682 bool IsFP = Constraint[2] == 'f';
12683 std::pair<StringRef, StringRef> Temp = Constraint.split('$');
12684 std::pair<unsigned, const TargetRegisterClass *> R;
12686 TRI, join_items("", Temp.first, Temp.second), VT);
12687 // Match those names to the widest floating point register type available.
12688 if (IsFP) {
12689 unsigned RegNo = R.first;
12690 if (LoongArch::F0 <= RegNo && RegNo <= LoongArch::F31) {
12691 if (Subtarget.hasBasicD() && (VT == MVT::f64 || VT == MVT::Other)) {
12692 unsigned DReg = RegNo - LoongArch::F0 + LoongArch::F0_64;
12693 return std::make_pair(DReg, &LoongArch::FPR64RegClass);
12694 }
12695 }
12696 }
12697 return R;
12698 }
12699
12700 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12701}
12702
12703void LoongArchTargetLowering::LowerAsmOperandForConstraint(
12704 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
12705 SelectionDAG &DAG) const {
12706 // Currently only support length 1 constraints.
12707 if (Constraint.size() == 1) {
12708 switch (Constraint[0]) {
12709 case 'l':
12710 // Validate & create a 16-bit signed immediate operand.
12711 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12712 uint64_t CVal = C->getSExtValue();
12713 if (isInt<16>(CVal))
12714 Ops.push_back(DAG.getSignedTargetConstant(CVal, SDLoc(Op),
12715 Subtarget.getGRLenVT()));
12716 }
12717 return;
12718 case 'I':
12719 // Validate & create a 12-bit signed immediate operand.
12720 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12721 uint64_t CVal = C->getSExtValue();
12722 if (isInt<12>(CVal))
12723 Ops.push_back(DAG.getSignedTargetConstant(CVal, SDLoc(Op),
12724 Subtarget.getGRLenVT()));
12725 }
12726 return;
12727 case 'J':
12728 // Validate & create an integer zero operand.
12729 if (auto *C = dyn_cast<ConstantSDNode>(Op))
12730 if (C->getZExtValue() == 0)
12731 Ops.push_back(
12732 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getGRLenVT()));
12733 return;
12734 case 'K':
12735 // Validate & create a 12-bit unsigned immediate operand.
12736 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12737 uint64_t CVal = C->getZExtValue();
12738 if (isUInt<12>(CVal))
12739 Ops.push_back(
12740 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getGRLenVT()));
12741 }
12742 return;
12743 default:
12744 break;
12745 }
12746 }
12748}
12749
12750#define GET_REGISTER_MATCHER
12751#include "LoongArchGenAsmMatcher.inc"
12752
12755 const MachineFunction &MF) const {
12756 std::pair<StringRef, StringRef> Name = StringRef(RegName).split('$');
12757 std::string NewRegName = Name.second.str();
12758 Register Reg = MatchRegisterAltName(NewRegName);
12759 if (!Reg)
12760 Reg = MatchRegisterName(NewRegName);
12761 if (!Reg)
12762 return Reg;
12763 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12764 if (!ReservedRegs.test(Reg))
12765 report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12766 StringRef(RegName) + "\"."));
12767 return Reg;
12768}
12769
12771 EVT VT, SDValue C) const {
12772 // TODO: Support vectors.
12773 if (!VT.isScalarInteger())
12774 return false;
12775
12776 // Omit the optimization if the data size exceeds GRLen.
12777 if (VT.getSizeInBits() > Subtarget.getGRLen())
12778 return false;
12779
12780 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12781 const APInt &Imm = ConstNode->getAPIntValue();
12782 // Break MUL into (SLLI + ADD/SUB) or ALSL.
12783 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12784 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12785 return true;
12786 // Break MUL into (ALSL x, (SLLI x, imm0), imm1).
12787 if (ConstNode->hasOneUse() &&
12788 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12789 (Imm - 8).isPowerOf2() || (Imm - 16).isPowerOf2()))
12790 return true;
12791 // Break (MUL x, imm) into (ADD (SLLI x, s0), (SLLI x, s1)),
12792 // in which the immediate has two set bits. Or Break (MUL x, imm)
12793 // into (SUB (SLLI x, s0), (SLLI x, s1)), in which the immediate
12794 // equals to (1 << s0) - (1 << s1).
12795 if (ConstNode->hasOneUse() && !(Imm.sge(-2048) && Imm.sle(4095))) {
12796 unsigned Shifts = Imm.countr_zero();
12797 // Reject immediates which can be composed via a single LUI.
12798 if (Shifts >= 12)
12799 return false;
12800 // Reject multiplications can be optimized to
12801 // (SLLI (ALSL x, x, 1/2/3/4), s).
12802 APInt ImmPop = Imm.ashr(Shifts);
12803 if (ImmPop == 3 || ImmPop == 5 || ImmPop == 9 || ImmPop == 17)
12804 return false;
12805 // We do not consider the case `(-Imm - ImmSmall).isPowerOf2()`,
12806 // since it needs one more instruction than other 3 cases.
12807 APInt ImmSmall = APInt(Imm.getBitWidth(), 1ULL << Shifts, true);
12808 if ((Imm - ImmSmall).isPowerOf2() || (Imm + ImmSmall).isPowerOf2() ||
12809 (ImmSmall - Imm).isPowerOf2())
12810 return true;
12811 }
12812 }
12813
12814 return false;
12815}
12816
12818 const AddrMode &AM,
12819 Type *Ty, unsigned AS,
12820 Instruction *I) const {
12821 // LoongArch has four basic addressing modes:
12822 // 1. reg
12823 // 2. reg + 12-bit signed offset
12824 // 3. reg + 14-bit signed offset left-shifted by 2
12825 // 4. reg1 + reg2
12826 // TODO: Add more checks after support vector extension.
12827
12828 // No global is ever allowed as a base.
12829 if (AM.BaseGV)
12830 return false;
12831
12832 // Require a 12-bit signed offset or 14-bit signed offset left-shifted by 2
12833 // with `UAL` feature.
12834 if (!isInt<12>(AM.BaseOffs) &&
12835 !(isShiftedInt<14, 2>(AM.BaseOffs) && Subtarget.hasUAL()))
12836 return false;
12837
12838 switch (AM.Scale) {
12839 case 0:
12840 // "r+i" or just "i", depending on HasBaseReg.
12841 break;
12842 case 1:
12843 // "r+r+i" is not allowed.
12844 if (AM.HasBaseReg && AM.BaseOffs)
12845 return false;
12846 // Otherwise we have "r+r" or "r+i".
12847 break;
12848 case 2:
12849 // "2*r+r" or "2*r+i" is not allowed.
12850 if (AM.HasBaseReg || AM.BaseOffs)
12851 return false;
12852 // Allow "2*r" as "r+r".
12853 break;
12854 default:
12855 return false;
12856 }
12857
12858 return true;
12859}
12860
12862 return isInt<12>(Imm);
12863}
12864
12866 return isInt<12>(Imm);
12867}
12868
12870 // Zexts are free if they can be combined with a load.
12871 // Don't advertise i32->i64 zextload as being free for LA64. It interacts
12872 // poorly with type legalization of compares preferring sext.
12873 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
12874 EVT MemVT = LD->getMemoryVT();
12875 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
12876 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12877 LD->getExtensionType() == ISD::ZEXTLOAD))
12878 return true;
12879 }
12880
12881 return TargetLowering::isZExtFree(Val, VT2);
12882}
12883
12885 EVT DstVT) const {
12886 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
12887}
12888
12890 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
12891}
12892
12894 // TODO: Support vectors.
12895 if (Y.getValueType().isVector())
12896 return false;
12897
12898 return true;
12899}
12900
12902 // LAMCAS will use amcas[_DB].{b/h/w/d} which does not require extension.
12903 return Subtarget.hasLAMCAS() ? ISD::ANY_EXTEND : ISD::SIGN_EXTEND;
12904}
12905
12907 Type *Ty, bool IsSigned) const {
12908 if (Subtarget.is64Bit() && Ty->isIntegerTy(32))
12909 return true;
12910
12911 return IsSigned;
12912}
12913
12915 // Return false to suppress the unnecessary extensions if the LibCall
12916 // arguments or return value is a float narrower than GRLEN on a soft FP ABI.
12917 if (Subtarget.isSoftFPABI() && (Type.isFloatingPoint() && !Type.isVector() &&
12918 Type.getSizeInBits() < Subtarget.getGRLen()))
12919 return false;
12920 return true;
12921}
12922
12923// memcpy, and other memory intrinsics, typically tries to use wider load/store
12924// if the source/dest is aligned and the copy size is large enough. We therefore
12925// want to align such objects passed to memory intrinsics.
12927 unsigned &MinSize,
12928 Align &PrefAlign) const {
12929 if (!isa<MemIntrinsic>(CI))
12930 return false;
12931
12932 if (Subtarget.is64Bit()) {
12933 MinSize = 8;
12934 PrefAlign = Align(8);
12935 } else {
12936 MinSize = 4;
12937 PrefAlign = Align(4);
12938 }
12939
12940 return true;
12941}
12942
12945 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
12946 VT.getVectorElementType() != MVT::i1)
12947 return TypeWidenVector;
12948
12950}
12951
12952bool LoongArchTargetLowering::splitValueIntoRegisterParts(
12953 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12954 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
12955 bool IsABIRegCopy = CC.has_value();
12956 EVT ValueVT = Val.getValueType();
12957
12958 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
12959 PartVT == MVT::f32) {
12960 // Cast the [b]f16 to i16, extend to i32, pad with ones to make a float
12961 // nan, and cast to f32.
12962 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12963 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12964 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12965 DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12966 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12967 Parts[0] = Val;
12968 return true;
12969 }
12970
12971 return false;
12972}
12973
12974SDValue LoongArchTargetLowering::joinRegisterPartsIntoValue(
12975 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12976 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
12977 bool IsABIRegCopy = CC.has_value();
12978
12979 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
12980 PartVT == MVT::f32) {
12981 SDValue Val = Parts[0];
12982
12983 // Cast the f32 to i32, truncate to i16, and cast back to [b]f16.
12984 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12985 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12986 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
12987 return Val;
12988 }
12989
12990 return SDValue();
12991}
12992
12993MVT LoongArchTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
12995 EVT VT) const {
12996 // Use f32 to pass f16.
12997 if (VT == MVT::f16 && Subtarget.hasBasicF())
12998 return MVT::f32;
12999
13001}
13002
13003unsigned LoongArchTargetLowering::getNumRegistersForCallingConv(
13005 // Use f32 to pass f16.
13006 if (VT == MVT::f16 && Subtarget.hasBasicF())
13007 return 1;
13008
13010}
13011
13013 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
13014 const SelectionDAG &DAG, unsigned Depth) const {
13015 unsigned Opc = Op.getOpcode();
13016 Known.resetAll();
13017 switch (Opc) {
13018 default:
13019 break;
13020 case LoongArchISD::VANYNONZERO:
13021 case LoongArchISD::VALLZERO:
13022 case LoongArchISD::VALL_ZERO:
13023 case LoongArchISD::VANY_ZERO:
13024 case LoongArchISD::VALL_NONZERO:
13025 case LoongArchISD::VANY_NONZERO: {
13026 // MOVCF2GR zero-extend the i1 cond to GPR.
13027 Known.Zero.setBitsFrom(1);
13028 break;
13029 }
13030 case LoongArchISD::VPICK_ZEXT_ELT: {
13031 assert(isa<VTSDNode>(Op->getOperand(2)) && "Unexpected operand!");
13032 EVT VT = cast<VTSDNode>(Op->getOperand(2))->getVT();
13033 unsigned VTBits = VT.getScalarSizeInBits();
13034 assert(Known.getBitWidth() >= VTBits && "Unexpected width!");
13035 Known.Zero.setBitsFrom(VTBits);
13036 break;
13037 }
13038 case LoongArchISD::BSTRINS: {
13039 // BSTRINS X, Y, msb, lsb: replace X[msb:lsb] with Y[msb-lsb:0].
13040 unsigned Msb = Op.getConstantOperandVal(2);
13041 unsigned Lsb = Op.getConstantOperandVal(3);
13042 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
13043 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
13044 Known.insertBits(Known2.trunc(Msb - Lsb + 1), Lsb);
13045 break;
13046 }
13047 case LoongArchISD::BSTRPICK: {
13048 // BSTRPICK X, msb, lsb: zero-extend X[msb:lsb].
13049 unsigned BitWidth = Known.getBitWidth();
13050 unsigned Msb = Op.getConstantOperandVal(1);
13051 unsigned Lsb = Op.getConstantOperandVal(2);
13052 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
13053 Known = Known.extractBits(Msb - Lsb + 1, Lsb).zext(BitWidth);
13054 break;
13055 }
13056 }
13057}
13058
13060 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
13061 unsigned Depth) const {
13062 switch (Op.getOpcode()) {
13063 default:
13064 break;
13065 case LoongArchISD::BSTRINS: {
13066 unsigned BitWidth = Op.getScalarValueSizeInBits();
13067 unsigned Msb = Op.getConstantOperandVal(2);
13068 unsigned Lsb = Op.getConstantOperandVal(3);
13069 // The bits above msb come from X.
13070 if (Msb != BitWidth - 1) {
13071 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
13072 return std::min(Tmp, BitWidth - 1 - Msb);
13073 }
13074 // The high bits come from Y shifted left by lsb.
13075 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(1), Depth + 1);
13076 return Tmp > Lsb ? Tmp - Lsb : 1;
13077 }
13078 }
13079 return 1;
13080}
13081
13083 SDValue Op, const APInt &OriginalDemandedBits,
13084 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
13085 unsigned Depth) const {
13086 EVT VT = Op.getValueType();
13087 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
13088 unsigned Opc = Op.getOpcode();
13089 switch (Opc) {
13090 default:
13091 break;
13092 case LoongArchISD::CRC_W_B_W:
13093 case LoongArchISD::CRC_W_H_W:
13094 case LoongArchISD::CRCC_W_B_W:
13095 case LoongArchISD::CRCC_W_H_W: {
13096 KnownBits KnownSrc;
13097 APInt DemandedSrcBits =
13098 APInt::getLowBitsSet(BitWidth, (Opc == LoongArchISD::CRC_W_B_W ||
13099 Opc == LoongArchISD::CRCC_W_B_W)
13100 ? 8
13101 : 16);
13102 return SimplifyDemandedBits(Op.getOperand(1), DemandedSrcBits,
13103 OriginalDemandedElts, KnownSrc, TLO, Depth + 1);
13104 }
13105 case LoongArchISD::VMSKLTZ:
13106 case LoongArchISD::XVMSKLTZ: {
13107 SDValue Src = Op.getOperand(0);
13108 MVT SrcVT = Src.getSimpleValueType();
13109 unsigned SrcBits = SrcVT.getScalarSizeInBits();
13110 unsigned NumElts = SrcVT.getVectorNumElements();
13111
13112 // If we don't need the sign bits at all just return zero.
13113 if (OriginalDemandedBits.countr_zero() >= NumElts)
13114 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
13115
13116 // Only demand the vector elements of the sign bits we need.
13117 APInt KnownUndef, KnownZero;
13118 APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
13119 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
13120 TLO, Depth + 1))
13121 return true;
13122
13123 Known.Zero = KnownZero.zext(BitWidth);
13124 Known.Zero.setHighBits(BitWidth - NumElts);
13125
13126 // [X]VMSKLTZ only uses the MSB from each vector element.
13127 KnownBits KnownSrc;
13128 APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
13129 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
13130 Depth + 1))
13131 return true;
13132
13133 if (KnownSrc.One[SrcBits - 1])
13134 Known.One.setLowBits(NumElts);
13135 else if (KnownSrc.Zero[SrcBits - 1])
13136 Known.Zero.setLowBits(NumElts);
13137
13138 // Attempt to avoid multi-use ops if we don't need anything from it.
13140 Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
13141 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
13142 return false;
13143 }
13144 }
13145
13147 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
13148}
13149
13151 unsigned Opc = VecOp.getOpcode();
13152
13153 // Assume target opcodes can't be scalarized.
13154 // TODO - do we have any exceptions?
13155 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opc))
13156 return false;
13157
13158 // If the vector op is not supported, try to convert to scalar.
13159 EVT VecVT = VecOp.getValueType();
13161 return true;
13162
13163 // If the vector op is supported, but the scalar op is not, the transform may
13164 // not be worthwhile.
13165 EVT ScalarVT = VecVT.getScalarType();
13166 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
13167}
13168
13171 unsigned Index) const {
13174
13175 // Extract a 128-bit subvector from index 0 of a 256-bit vector is free.
13176 if (Index == 0)
13179}
13180
13182 unsigned Index) const {
13183 EVT EltVT = VT.getScalarType();
13184
13185 // Extract a scalar FP value from index 0 of a vector is free.
13186 return (EltVT == MVT::f32 || EltVT == MVT::f64) && Index == 0;
13187}
13188
13190 const MachineFunction &MF) const {
13191
13192 // If the function specifically requests inline stack probes, emit them.
13193 if (MF.getFunction().hasFnAttribute("probe-stack"))
13194 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
13195 "inline-asm";
13196
13197 return false;
13198}
13199
13201 Align StackAlign) const {
13202 // The default stack probe size is 4096 if the function has no
13203 // stack-probe-size attribute.
13204 const Function &Fn = MF.getFunction();
13205 unsigned StackProbeSize =
13206 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
13207 // Round down to the stack alignment.
13208 StackProbeSize = alignDown(StackProbeSize, StackAlign.value());
13209 return StackProbeSize ? StackProbeSize : StackAlign.value();
13210}
13211
13212SDValue
13213LoongArchTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
13214 SelectionDAG &DAG) const {
13216 if (!hasInlineStackProbe(MF))
13217 return SDValue();
13218
13219 const MVT GRLenVT = Subtarget.getGRLenVT();
13220 // Get the inputs.
13221 SDValue Chain = Op.getOperand(0);
13222 SDValue Size = Op.getOperand(1);
13223
13224 const MaybeAlign Align =
13225 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
13226 const SDLoc dl(Op);
13227 const EVT VT = Op.getValueType();
13228
13229 // Construct the new SP value in a GPR.
13230 SDValue SP = DAG.getCopyFromReg(Chain, dl, LoongArch::R3, GRLenVT);
13231 Chain = SP.getValue(1);
13232 SP = DAG.getNode(ISD::SUB, dl, GRLenVT, SP, Size);
13233 if (Align)
13234 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13235 DAG.getSignedConstant(-Align->value(), dl, VT));
13236
13237 // Set the real SP to the new value with a probing loop.
13238 Chain = DAG.getNode(LoongArchISD::PROBED_ALLOCA, dl, MVT::Other, Chain, SP);
13239 return DAG.getMergeValues({SP, Chain}, dl);
13240}
13241
13244 MachineBasicBlock *MBB) const {
13245 MachineFunction &MF = *MBB->getParent();
13246 MachineBasicBlock::iterator MBBI = MI.getIterator();
13247 DebugLoc DL = MBB->findDebugLoc(MBBI);
13248 const Register TargetReg = MI.getOperand(0).getReg();
13249
13250 const LoongArchInstrInfo *TII = Subtarget.getInstrInfo();
13251 const bool IsLA64 = Subtarget.is64Bit();
13252 const Align StackAlign = Subtarget.getFrameLowering()->getStackAlign();
13253 const LoongArchTargetLowering *TLI = Subtarget.getTargetLowering();
13254 const uint64_t ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
13255
13256 MachineFunction::iterator MBBInsertPoint = std::next(MBB->getIterator());
13257 MachineBasicBlock *const LoopTestMBB =
13258 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
13259 MF.insert(MBBInsertPoint, LoopTestMBB);
13260 MachineBasicBlock *const ExitMBB =
13261 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
13262 MF.insert(MBBInsertPoint, ExitMBB);
13263 const Register SPReg = LoongArch::R3;
13264 const Register ScratchReg =
13265 MF.getRegInfo().createVirtualRegister(&LoongArch::GPRRegClass);
13266
13267 // ScratchReg = ProbeSize
13268 TII->movImm(*MBB, MBBI, DL, ScratchReg, ProbeSize, MachineInstr::NoFlags);
13269
13270 // LoopTest:
13271 // sub.{w/d} $sp, $sp, ScratchReg
13272 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
13273 TII->get(IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W), SPReg)
13274 .addReg(SPReg)
13275 .addReg(ScratchReg);
13276
13277 // st.{w/d} $zero, $sp, 0
13278 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL,
13279 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
13280 .addReg(LoongArch::R0)
13281 .addReg(SPReg)
13282 .addImm(0);
13283
13284 // bltu TargetReg, $sp, LoopTest
13285 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(LoongArch::BLTU))
13286 .addReg(TargetReg)
13287 .addReg(SPReg)
13288 .addMBB(LoopTestMBB);
13289
13290 // move $sp, TargetReg
13291 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(LoongArch::OR), SPReg)
13292 .addReg(TargetReg)
13293 .addReg(LoongArch::R0);
13294
13295 ExitMBB->splice(ExitMBB->end(), MBB, std::next(MBBI), MBB->end());
13297
13298 LoopTestMBB->addSuccessor(ExitMBB);
13299 LoopTestMBB->addSuccessor(LoopTestMBB);
13300 MBB->addSuccessor(LoopTestMBB);
13301
13302 MI.eraseFromParent();
13303 MF.getInfo<LoongArchMachineFunctionInfo>()->setDynamicAllocation();
13304 return ExitMBB->begin()->getParent();
13305}
13306
13308 // hasFPImpl depends on the max call frame size, so compute it before the
13309 // reserved registers are frozen.
13312}
static MCRegister MatchRegisterName(StringRef Name)
static SDValue performSHLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
If the operand is a bitwise AND with a constant RHS, and the shift has a constant RHS and is the only...
static bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType)
static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
unsigned NumParts
return SDValue()
static SDValue performANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue performSELECT_CCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
static SDValue performSETCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
Function Alias Analysis Results
static uint64_t getConstant(const Value *IndexValue)
static SDValue getTargetNode(ConstantPoolSDNode *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned Flags)
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static MachineBasicBlock * emitSelectPseudo(MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode)
static SDValue unpackFromRegLoc(const CSKYSubtarget &Subtarget, SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static bool isSigned(unsigned Opcode)
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static SDValue performINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
const MCPhysReg ArgFPR32s[]
static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Dispatching routine to lower various 128-bit LoongArch vector shuffles.
static SDValue lowerVECTOR_SHUFFLE_XVSHUF4I(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVSHUF4I (if possible).
const MCPhysReg ArgVRs[]
static SDValue lowerVECTOR_SHUFFLE_VPICKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPICKEV (if possible).
static SDValue combineSelectToBinOp(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVPICKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPICKOD (if possible).
static SDValue unpackF64OnLA32DSoftABI(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const CCValAssign &HiVA, const SDLoc &DL)
static bool fitsRegularPattern(typename SmallVectorImpl< ValType >::const_iterator Begin, unsigned CheckStride, typename SmallVectorImpl< ValType >::const_iterator End, ValType ExpectedIndex, unsigned ExpectedIndexStride)
Determine whether a range fits a regular pattern of values.
static SDValue lowerVECTOR_SHUFFLE_IsReverse(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE whose result is the reversed source vector.
static SDValue lowerVECTOR_SHUFFLE_VREPLVE(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower a VECTOR_SHUFFLE of BUILD_VECTORs to [X]VREPLVE.
static SDValue PromoteMaskArithmetic(SDValue N, const SDLoc &DL, EVT VT, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned Depth)
static SDValue performUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performHorizWideningCombine(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static std::pair< SDValue, EVT > stripSignExtendInReg(SDValue V)
static SDValue emitIntrinsicErrorMessage(SDValue Op, StringRef ErrorMsg, SelectionDAG &DAG)
static SDValue ExtendSrcToDst(SDNode *N, SelectionDAG &DAG, unsigned ExtendOp)
static cl::opt< bool > ZeroDivCheck("loongarch-check-zero-division", cl::Hidden, cl::desc("Trap on integer division by zero."), cl::init(false))
static SDValue lowerVECTOR_SHUFFLE_XVPERMI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERMI (if possible).
static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VSHUF(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VSHUF.
static int getEstimateRefinementSteps(EVT VT, const LoongArchSubtarget &Subtarget)
static bool isSupportedReciprocalEstimateType(EVT VT, const LoongArchSubtarget &Subtarget)
static void emitErrorAndReplaceIntrinsicResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, StringRef ErrorMsg, bool WithChain=true)
static SDValue lowerVECTOR_SHUFFLEAsByteRotate(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE as byte rotate (if possible).
static SDValue matchGuardedDivisor(SDValue D, SDValue A, unsigned Opc)
static SDValue checkIntrinsicImmArg(SDValue Op, unsigned ImmOp, SelectionDAG &DAG, bool IsSigned=false)
static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVINSVE0(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVINSVE0 (if possible).
static SDValue combineVectorBitOpOfBitcastShl(SDNode *N, SelectionDAG &DAG)
static SDValue performMOVFR2GR_SCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VILVH(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VILVH (if possible).
static SDValue performSIGN_EXTEND_INREGCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performDemandedBitsCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI)
static bool CC_LoongArch(const DataLayout &DL, LoongArchABI::ABI ABI, unsigned ValNo, MVT ValVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsRet, Type *OrigTy)
static std::tuple< unsigned, SDValue, EVT > matchBinOpWithSharedOperand(SDValue BinV, SDValue X)
static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
static SDValue performSPLIT_PAIR_F64Combine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performBITCASTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performSRLCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static MachineBasicBlock * emitSplitPairF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorBitSetImm(SDNode *Node, SelectionDAG &DAG)
static SDValue performSETCC_BITCASTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
@ NoMaterializeFPImm
@ MaterializeFPImm2Ins
@ MaterializeFPImm5Ins
@ MaterializeFPImm6Ins
@ MaterializeFPImm3Ins
@ MaterializeFPImm4Ins
static SDValue performEXTENDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_XVPACKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPACKOD (if possible).
static bool buildVPERMIInfo(ArrayRef< int > Mask, SDValue V1, SDValue V2, SmallVectorImpl< SDValue > &SrcVec, unsigned &MaskImm)
static std::optional< bool > matchSetCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDValue Val)
static SDValue combineAndNotIntoVANDN(SDNode *N, const SDLoc &DL, SelectionDAG &DAG)
Try to fold: (and (xor X, -1), Y) -> (vandn X, Y).
static SDValue lowerBUILD_VECTORAsBroadCastLoad(BuildVectorSDNode *BVOp, const SDLoc &DL, SelectionDAG &DAG)
#define CRC_CASE_EXT_BINARYOP(NAME, NODE)
static SDValue lowerVectorBitRevImm(SDNode *Node, SelectionDAG &DAG)
static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size, unsigned Depth)
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
static SDValue lowerVECTOR_SHUFFLEAsShift(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, const APInt &Zeroable)
Lower VECTOR_SHUFFLE as shift (if possible).
static SDValue lowerVECTOR_SHUFFLE_VSHUF4I(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VSHUF4I (if possible).
static SDValue truncateVecElts(SDNode *Node, SelectionDAG &DAG)
static bool CC_LoongArch_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static MachineBasicBlock * insertDivByZeroTrap(MachineInstr &MI, MachineBasicBlock *MBB)
static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG)
static SDValue lowerVECTOR_SHUFFLE_VEXTRINS(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VEXTRINS (if possible).
static SDValue lowerVectorBitClear(SDNode *Node, SelectionDAG &DAG)
static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VPACKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPACKEV (if possible).
static MachineBasicBlock * emitPseudoVMSKCOND(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue performSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performVANDNCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
Do target-specific dag combines on LoongArchISD::VANDN nodes.
static void replaceVPICKVE2GRResults(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned ResOp)
static SDValue lowerVECTOR_SHUFFLEAsZeroOrAnyExtend(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const APInt &Zeroable)
Lower VECTOR_SHUFFLE as ZERO_EXTEND Or ANY_EXTEND (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVPERMIQ(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERMI_Q (if possible).
static SDValue legalizeIntrinsicImmArg(SDNode *Node, unsigned ImmOp, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, bool IsSigned=false)
static bool isRedundantDivisorGuard(SDValue Cond, SDValue A, SDValue B, unsigned Opc, unsigned Depth=0)
static cl::opt< MaterializeFPImm > MaterializeFPImmInsNum("loongarch-materialize-float-imm", cl::Hidden, cl::desc("Maximum number of instructions used (including code sequence " "to generate the value and moving the value to FPR) when " "materializing floating-point immediates (default = 3)"), cl::init(MaterializeFPImm3Ins), cl::values(clEnumValN(NoMaterializeFPImm, "0", "Use constant pool"), clEnumValN(MaterializeFPImm2Ins, "2", "Materialize FP immediate within 2 instructions"), clEnumValN(MaterializeFPImm3Ins, "3", "Materialize FP immediate within 3 instructions"), clEnumValN(MaterializeFPImm4Ins, "4", "Materialize FP immediate within 4 instructions"), clEnumValN(MaterializeFPImm5Ins, "5", "Materialize FP immediate within 5 instructions"), clEnumValN(MaterializeFPImm6Ins, "6", "Materialize FP immediate within 6 instructions " "(behaves same as 5 on loongarch64)")))
static SDValue emitIntrinsicWithChainErrorMessage(SDValue Op, StringRef ErrorMsg, SelectionDAG &DAG)
const MCPhysReg ArgXRs[]
static bool CC_LoongArchAssign2GRLen(unsigned GRLen, CCState &State, CCValAssign VA1, ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, MVT ValVT2, MVT LocVT2, ISD::ArgFlagsTy ArgFlags2)
static unsigned getLoongArchWOpcode(unsigned Opcode)
const MCPhysReg ArgFPR64s[]
static MachineBasicBlock * emitPseudoCTPOP(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue performMOVGR2FR_WCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
#define IOCSRWR_CASE(NAME, NODE)
#define CRC_CASE_EXT_UNARYOP(NAME, NODE)
static SDValue lowerVECTOR_SHUFFLE_VPACKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPACKOD (if possible).
static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT, SDValue Src, const SDLoc &DL)
static SDValue isNOT(SDValue V, SelectionDAG &DAG)
static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Dispatching routine to lower various 256-bit LoongArch vector shuffles.
static SDValue lowerVECTOR_SHUFFLE_VREPLVEI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VREPLVEI (if possible).
static SDValue combineGuardedVectorDiv(SDNode *N, SelectionDAG &DAG)
static MachineBasicBlock * emitPseudoXVINSGR2VR(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
const MCPhysReg PreserveNoneArgGPRs[]
static void fillVector(ArrayRef< SDValue > Ops, SelectionDAG &DAG, SDLoc DL, const LoongArchSubtarget &Subtarget, SDValue &Vector, EVT ResTy)
static SDValue fillSubVectorFromBuildVector(BuildVectorSDNode *Node, SelectionDAG &DAG, SDLoc DL, const LoongArchSubtarget &Subtarget, EVT ResTy, unsigned first)
static bool isSelectPseudo(MachineInstr &MI)
static SDValue foldVMskZeroTest(SDValue LHS, SDValue RHS, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue foldBinOpIntoSelectIfProfitable(SDNode *BO, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorSplatImm(SDNode *Node, unsigned ImmOp, SelectionDAG &DAG, bool IsSigned=false)
const MCPhysReg ArgGPRs[]
static SDValue lowerVECTOR_SHUFFLE_XVPERM(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVPERM (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVILVL(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVILVL (if possible).
static SDValue performVNi128AddSubCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performFP_TO_INTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLE_VPERMI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into VPERMI (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVEXTRINS(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVEXTRINS (if possible).
static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, int NumOp, unsigned ExtOpc=ISD::ANY_EXTEND)
static void replaceVecCondBranchResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget, unsigned ResOp)
#define ASRT_LE_GT_CASE(NAME)
static SDValue lowerVECTOR_SHUFFLE_XVPACKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPACKEV (if possible).
static SDValue matchDeinterleaveBuildVector(SDValue N, unsigned &StartIndex)
static SDValue performBR_CCCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static void computeZeroableShuffleElements(ArrayRef< int > Mask, SDValue V1, SDValue V2, APInt &KnownUndef, APInt &KnownZero)
Compute whether each element of a shuffle is zeroable.
static bool isSetEqSplat(SDValue V, SDValue X, function_ref< bool(const APInt &)> Pred)
static SDValue combineFP_ROUND(SDValue N, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
static bool isCheapVNi128VectorOperand(SDValue V, MVT PartVT, SelectionDAG &DAG)
static SDValue performCONCAT_VECTORSCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue widenShuffleMask(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
static bool canonicalizeShuffleVectorByLane(const SDLoc &DL, MutableArrayRef< int > Mask, MVT VT, SDValue &V1, SDValue &V2, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Shuffle vectors by lane to generate more optimized instructions.
static SDValue performREMCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue combineSubOfBoolean(SDNode *N, SelectionDAG &DAG)
static SDValue lowerVECTOR_SHUFFLE_XVILVH(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVILVH (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVSHUF(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVSHUF (if possible).
static void replaceCMP_XCHG_128Results(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG)
static SDValue lowerVectorPickVE2GR(SDNode *N, SelectionDAG &DAG, unsigned ResOp)
static SDValue performBITREV_WCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static bool isVectorRegisterVT(EVT VT, SelectionDAG &DAG)
static SDValue matchHalfOf128BitLanes(SDValue N, bool isLow)
#define IOCSRRD_CASE(NAME, NODE)
static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2, ArrayRef< int > Mask)
Attempts to match vector shuffle as byte rotation.
static SDValue lowerVECTOR_SHUFFLE_XVREPLVE0(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVREPLVE0 (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVPICKEV(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into XVPICKEV (if possible).
static SDValue lowerVECTOR_SHUFFLE_XVREPLVEI(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower VECTOR_SHUFFLE into XVREPLVEI (if possible).
static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode, unsigned ScalarSizeInBits, ArrayRef< int > Mask, int MaskOffset, const APInt &Zeroable)
Attempts to match a shuffle mask against the VBSLL, VBSRL, VSLLI and VSRLI instruction.
static SDValue lowerVECTOR_SHUFFLE_VILVL(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VILVL (if possible).
static SDValue performVREPLVECombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
Do target-specific dag combines on LoongArchISD::VREPLVE nodes.
static SDValue performMULCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue lowerVectorBitClearImm(SDNode *Node, SelectionDAG &DAG)
static MachineBasicBlock * emitBuildPairF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB, const LoongArchSubtarget &Subtarget)
static SDValue lowerVECTOR_SHUFFLEAsLanePermuteAndShuffle(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE as lane permute and then shuffle (if possible).
static bool hasOnlyVectorUsers(LoadSDNode *Ld, SelectionDAG &DAG)
static void replaceINTRINSIC_WO_CHAINResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
#define CSR_CASE(ID)
static SDValue MergeBlocksConvert(SDNode *N, SelectionDAG &DAG, unsigned Opcode, unsigned BlockBits)
static SDValue lowerVECTOR_SHUFFLE_VPICKOD(const SDLoc &DL, ArrayRef< int > Mask, MVT VT, SDValue V1, SDValue V2, SelectionDAG &DAG)
Lower VECTOR_SHUFFLE into VPICKOD (if possible).
static Intrinsic::ID getIntrinsicForMaskedAtomicRMWBinOp(unsigned GRLen, AtomicRMWInst::BinOp BinOp)
static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, ISD::CondCode &CC, SelectionDAG &DAG)
static Register allocateArgGPR(CCState &State)
static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT, ArrayRef< int > Mask, SmallVectorImpl< int > &RepeatedMask)
Test whether a shuffle mask is equivalent within each sub-lane.
static SDValue lowerSplatOfExtractAsVREPLVE(const SDLoc &DL, MVT VT, ArrayRef< SDValue > Elts, SelectionDAG &DAG, const LoongArchSubtarget &Subtarget)
Lower Elts to [X]VREPLVE Src, Idx if each 128-bit lane L is a splat of (extract_vector_elt Src,...
static SDValue convertRMEncoding(SelectionDAG &DAG, const SDLoc &DL, MVT GRLenVT, SDValue RMValue)
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
static constexpr MCPhysReg SPReg
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool inRange(const MCExpr *Expr, int64_t MinValue, int64_t MaxValue, bool AllowSymbol=false)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static bool isSequentialOrUndefInRange(ArrayRef< int > Mask, unsigned Pos, unsigned Size, int Low, int Step=1)
Return true if every element in Mask, beginning from position Pos and ending in Pos + Size,...
Value * RHS
Value * LHS
bool isZero() const
Definition APFloat.h:1612
APInt bitcastToAPInt() const
Definition APFloat.h:1508
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
An instruction that atomically checks whether a specified value is in a memory location,...
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
an instruction that atomically reads a memory location, combines it with another value,...
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ UMax
*p = old >unsigned v ? old : v
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
Value * getPointerOperand()
bool isFloatingPointOperation() const
BinOp getOperation() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT, LocInfo HTP, unsigned ExtraInfo=0)
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
unsigned getValNo() const
static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
const APFloat & getValueAPF() const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
uint64_t getZExtValue() const
int64_t getSExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:503
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
iterator_range< arg_iterator > args()
Definition Function.h:886
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
Argument * getArg(unsigned i) const
Definition Function.h:880
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
bool isDSOLocal() const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
void setIncomingIndirectArg(unsigned ArgIndex, Register Reg)
Register getIncomingIndirectArg(unsigned ArgIndex) const
bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const override
Return true if result of the specified node is used by a return node only.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const override
Hooks for building estimates in place of slower divisions and square roots.
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
This method can be implemented by targets that want to expose additional information about sign bits ...
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
TargetLowering::AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *CI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
bool isFPImmCheapInGPR(const APFloat &Imm, EVT VT) const
Returns true if building Imm in a GPR and moving it to a float register is cheaper than loading it fr...
Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const override
Perform a masked cmpxchg using a target-specific intrinsic.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
std::pair< bool, uint64_t > isImmVLDILegalForMode1(const APInt &SplatValue, const unsigned SplatBitSize) const
Check if a constant splat can be generated using [x]vldi, where imm[12] is 1.
void finalizeLowering(MachineFunction &MF) const override
Execute target specific actions to finalize target lowering.
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this function.
SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const override
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
bool isExtractVecEltCheap(EVT VT, unsigned Index) const override
Return true if extraction of a scalar element from the given vector type at the given index is cheap.
LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const override
Determine if the target supports unaligned memory accesses.
bool isCheapToSpeculateCtlz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic ctlz.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, Align &PrefAlign) const override
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const override
Perform a masked atomicrmw using a target-specific intrinsic.
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool signExtendConstant(const ConstantInt *CI) const override
Return true if this constant should be sign extended when promoting to a larger type.
ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const override
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
TargetLowering::AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
bool isCheapToSpeculateCttz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic cttz.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
MachineBasicBlock * emitDynamicProbedAlloc(MachineInstr &MI, MachineBasicBlock *MBB) const
bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const override
Returns true if arguments should be sign-extended in lib calls.
bool shouldScalarizeBinop(SDValue VecOp) const override
Try to convert an extract element of a vector binary operation into an extract element followed by a ...
bool isFPImmVLDILegal(const APFloat &Imm, EVT VT) const
bool shouldExtendTypeInLibCall(EVT Type) const override
Returns true if arguments should be extended in lib calls.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const override
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
void emitExpandAtomicRMW(AtomicRMWInst *AI) const override
Perform a atomicrmw expansion using a target-specific way.
ISD::NodeType getExtendForAtomicCmpSwapArg() const override
Returns how the platform's atomic compare and swap expects its comparison value to be extended (ZERO_...
LoongArchTargetLowering(const TargetMachine &TM, const LoongArchSubtarget &STI)
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
bool hasAndNotCompare(SDValue Y) const override
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const override
Return a reciprocal estimate value for the input operand.
bool canMergeStoresTo(unsigned AddressSpace, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
bool hasFeature(unsigned Feature) const
Machine Value Type.
static MVT getFloatingPointVT(unsigned BitWidth)
bool is128BitVector() const
Return true if this is a 128-bit vector type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
bool is256BitVector() const
Return true if this is a 256-bit vector type.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
MVT getDoubleNumVectorElementsVT() const
MVT getHalfNumVectorElementsVT() const
Return a VT for a vector type with the same element type but half the number of elements.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
MVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void push_back(MachineInstr *MI)
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI void computeMaxCallFrameSize(MachineFunction &MF, std::vector< MachineBasicBlock::iterator > *FrameSDOps=nullptr)
Computes the maximum size of a callframe.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI void collectDebugValues(SmallVectorImpl< MachineInstr * > &DbgValues)
Scan instructions immediately following MI and collect any matching DBG_VALUEs.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Align getAlign() const
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
size_t use_size() const
Return the number of uses of this node.
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
uint64_t getScalarValueSizeInBits() const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
bool isSafeToSpeculativelyExecute(unsigned Opcode) const
Some opcodes may create immediate undefined behavior when used with some values (integer division-by-...
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
static LLVM_ABI bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
static LLVM_ABI bool isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
ArrayRef< int > getMask() const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
typename SuperClass::const_iterator const_iterator
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual void finalizeLowering(MachineFunction &MF) const
Execute target specific actions to finalize target lowering.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
void setMaxBytesForAlignment(unsigned MaxBytes)
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of a boolean value from i1 to a wider type.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT, LegalizeAction Action)
Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treate...
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
@ Bitcast
Build the immediate as a bitcast of an integer constant with the same bits.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
std::vector< ArgListEntry > ArgListTy
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Vector Op.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
bool useTLSDESC() const
Returns true if this target uses TLS Descriptors.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent EVT's, which are used to parameterize some operations.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SET_ROUNDING
Set rounding mode.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isExtVecInRegOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0...
LLVM_ABI bool isFreezeUndef(SDValue V)
Return true if the specified value is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
LLVM_ABI bool isBuildVectorAllOnes(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(SDValue V)
Return true if the specified value is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
bool isIntEqualitySetCC(CondCode Code)
Return true if this is a setcc instruction that performs an equality comparison when used with intege...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ABI getTargetABI(StringRef ABIName)
InstSeq generateInstSeq(int64_t Val)
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
Definition PtrState.h:41
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
@ Off
Use window algorithm after SMS algorithm fails.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:262
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
constexpr unsigned BitWidth
std::string join_items(Sep Separator, Args &&... Items)
Joins the strings in the parameter pack Items, adding Separator between the elements....
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool is128BitVector() const
Return true if this is a 128-bit vector type.
Definition ValueTypes.h:245
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isFixedLengthVector() const
Definition ValueTypes.h:214
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
Definition ValueTypes.h:55
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool is256BitVector() const
Return true if this is a 256-bit vector type.
Definition ValueTypes.h:250
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
Align getNonZeroOrigAlign() const
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...