LLVM 24.0.0git
ARMISelLowering.cpp
Go to the documentation of this file.
1//===- ARMISelLowering.cpp - ARM 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 ARM uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMISelLowering.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMCallingConv.h"
20#include "ARMPerfectShuffle.h"
21#include "ARMRegisterInfo.h"
22#include "ARMSelectionDAGInfo.h"
23#include "ARMSubtarget.h"
27#include "Utils/ARMBaseInfo.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/Twine.h"
67#include "llvm/IR/Attributes.h"
68#include "llvm/IR/CallingConv.h"
69#include "llvm/IR/Constant.h"
70#include "llvm/IR/Constants.h"
71#include "llvm/IR/DataLayout.h"
72#include "llvm/IR/DebugLoc.h"
74#include "llvm/IR/Function.h"
75#include "llvm/IR/GlobalAlias.h"
76#include "llvm/IR/GlobalValue.h"
78#include "llvm/IR/IRBuilder.h"
79#include "llvm/IR/InlineAsm.h"
80#include "llvm/IR/Instruction.h"
83#include "llvm/IR/Intrinsics.h"
84#include "llvm/IR/IntrinsicsARM.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
89#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/MC/MCSchedule.h"
98#include "llvm/Support/Debug.h"
106#include <algorithm>
107#include <cassert>
108#include <cstdint>
109#include <iterator>
110#include <limits>
111#include <optional>
112#include <tuple>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117using namespace llvm::SDPatternMatch;
118
119#define DEBUG_TYPE "arm-isel"
120
121STATISTIC(NumTailCalls, "Number of tail calls");
122STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
123STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
124STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
125STATISTIC(NumConstpoolPromoted,
126 "Number of constants with their storage promoted into constant pools");
127
128static cl::opt<bool>
129ARMInterworking("arm-interworking", cl::Hidden,
130 cl::desc("Enable / disable ARM interworking (for debugging only)"),
131 cl::init(true));
132
134 "arm-promote-constant", cl::Hidden,
135 cl::desc("Enable / disable promotion of unnamed_addr constants into "
136 "constant pools"),
137 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
139 "arm-promote-constant-max-size", cl::Hidden,
140 cl::desc("Maximum size of constant to promote into a constant pool"),
141 cl::init(64));
143 "arm-promote-constant-max-total", cl::Hidden,
144 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
145 cl::init(128));
146
148MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
149 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
150 cl::init(2));
151
153 "arm-max-base-updates-to-check", cl::Hidden,
154 cl::desc("Maximum number of base-updates to check generating postindex."),
155 cl::init(64));
156
157/// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
158constexpr MVT FlagsVT = MVT::i32;
159
160// The APCS parameter registers.
161static const MCPhysReg GPRArgRegs[] = {
162 ARM::R0, ARM::R1, ARM::R2, ARM::R3
163};
164
166 SelectionDAG &DAG, const SDLoc &DL) {
168 assert(Arg.ArgVT.bitsLT(MVT::i32));
169 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Arg.ArgVT, Value);
170 SDValue Ext =
172 MVT::i32, Trunc);
173 return Ext;
174}
175
176void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
177 if (VT != PromotedLdStVT) {
179 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
180
182 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
183 }
184
185 MVT ElemTy = VT.getVectorElementType();
186 if (ElemTy != MVT::f64)
190 if (ElemTy == MVT::i32) {
195 } else {
200 }
209 if (VT.isInteger()) {
213 }
214
215 // Neon does not support vector divide/remainder operations.
224
225 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
226 for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
228 setOperationAction(Opcode, VT, Legal);
229 if (!VT.isFloatingPoint())
230 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
231 setOperationAction(Opcode, VT, Legal);
232}
233
234void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
235 addRegisterClass(VT, &ARM::DPRRegClass);
236 addTypeForNEON(VT, MVT::f64);
237}
238
239void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
240 addRegisterClass(VT, &ARM::DPairRegClass);
241 addTypeForNEON(VT, MVT::v2f64);
242}
243
244void ARMTargetLowering::setAllExpand(MVT VT) {
245 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
247
248 // We support these really simple operations even on types where all
249 // the actual arithmetic has to be broken down into simpler
250 // operations or turned into library calls.
255}
256
257void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
258 LegalizeAction Action) {
259 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
260 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
261 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
262}
263
264void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
265 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
266
267 for (auto VT : IntTypes) {
268 addRegisterClass(VT, &ARM::MQPRRegClass);
299
300 // No native support for these.
310
311 // Vector reductions
321
322 if (!HasMVEFP) {
327 } else {
330 }
331
332 // Pre and Post inc are supported on loads and stores
333 for (unsigned im = (unsigned)ISD::PRE_INC;
334 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
339 }
340 }
341
342 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
343 for (auto VT : FloatTypes) {
344 addRegisterClass(VT, &ARM::MQPRRegClass);
345 if (!HasMVEFP)
346 setAllExpand(VT);
347
348 // These are legal or custom whether we have MVE.fp or not
361
362 // Pre and Post inc are supported on loads and stores
363 for (unsigned im = (unsigned)ISD::PRE_INC;
364 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
369 }
370
371 if (HasMVEFP) {
374 for (auto Op :
379 }
384
385 // No native support for these.
400 }
401 }
402
403 // Custom Expand smaller than legal vector reductions to prevent false zero
404 // items being added.
413
414 // We 'support' these types up to bitcast/load/store level, regardless of
415 // MVE integer-only / float support. Only doing FP data processing on the FP
416 // vector types is inhibited at integer-only level.
417 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
418 for (auto VT : LongTypes) {
419 addRegisterClass(VT, &ARM::MQPRRegClass);
420 setAllExpand(VT);
426 }
428
429 // We can do bitwise operations on v2i64 vectors
430 setOperationAction(ISD::AND, MVT::v2i64, Legal);
431 setOperationAction(ISD::OR, MVT::v2i64, Legal);
432 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
433
434 // It is legal to extload from v4i8 to v4i16 or v4i32.
435 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
436 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
437 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
438
439 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
445
446 // Some truncating stores are legal too.
447 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
448 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
449 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
450
451 // Pre and Post inc on these are legal, given the correct extends
452 for (unsigned im = (unsigned)ISD::PRE_INC;
453 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
454 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
459 }
460 }
461
462 // Predicate types
463 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
464 for (auto VT : pTypes) {
465 addRegisterClass(VT, &ARM::VCCRRegClass);
480
481 if (!HasMVEFP) {
486 }
487 }
491 setOperationAction(ISD::OR, MVT::v2i1, Expand);
497
506}
507
509 return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
510}
511
513 const ARMSubtarget &STI)
514 : TargetLowering(TM_, STI), Subtarget(&STI),
515 RegInfo(Subtarget->getRegisterInfo()),
516 Itins(Subtarget->getInstrItineraryData()) {
517 const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
518
521
522 const Triple &TT = TM.getTargetTriple();
523
524 if (Subtarget->isThumb1Only())
525 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
526 else
527 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
528
529 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
530 Subtarget->hasFPRegs()) {
531 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
532 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
533
534 if (!Subtarget->hasVFP2Base()) {
535 setAllExpand(MVT::f32);
536 } else {
539
542 setOperationAction(Op, MVT::f32, Legal);
543 }
544 if (!Subtarget->hasFP64()) {
545 setAllExpand(MVT::f64);
546 } else {
549 setOperationAction(Op, MVT::f64, Legal);
550
552 }
553 }
554
555 if (Subtarget->hasFullFP16()) {
558 setOperationAction(Op, MVT::f16, Legal);
559
560 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
563
568 }
569
570 if (Subtarget->hasBF16()) {
571 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
572 setAllExpand(MVT::bf16);
573 if (!Subtarget->hasFullFP16())
577 } else {
582 }
583
585 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
586 setTruncStoreAction(VT, InnerVT, Expand);
587 addAllExtLoads(VT, InnerVT, Expand);
588 }
589
592
594 }
595
596 if (!Subtarget->isThumb1Only() && !Subtarget->hasV8_1MMainlineOps())
598
599 if (!Subtarget->hasV8_1MMainlineOps())
601
602 if (!Subtarget->isThumb1Only())
604
607
610
611 if (Subtarget->hasMVEIntegerOps())
612 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
613
614 // Combine low-overhead loop intrinsics so that we can lower i1 types.
615 if (Subtarget->hasLOB()) {
617 }
618
619 if (Subtarget->hasNEON()) {
620 addDRTypeForNEON(MVT::v2f32);
621 addDRTypeForNEON(MVT::v8i8);
622 addDRTypeForNEON(MVT::v4i16);
623 addDRTypeForNEON(MVT::v2i32);
624 addDRTypeForNEON(MVT::v1i64);
625
626 addQRTypeForNEON(MVT::v4f32);
627 addQRTypeForNEON(MVT::v2f64);
628 addQRTypeForNEON(MVT::v16i8);
629 addQRTypeForNEON(MVT::v8i16);
630 addQRTypeForNEON(MVT::v4i32);
631 addQRTypeForNEON(MVT::v2i64);
632
633 if (Subtarget->hasFullFP16()) {
634 addQRTypeForNEON(MVT::v8f16);
635 addDRTypeForNEON(MVT::v4f16);
636 }
637
638 if (Subtarget->hasBF16()) {
639 addQRTypeForNEON(MVT::v8bf16);
640 addDRTypeForNEON(MVT::v4bf16);
641 }
642 }
643
644 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
645 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
646 // none of Neon, MVE or VFP supports any arithmetic operations on it.
647 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
648 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
649 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
650 // FIXME: Code duplication: FDIV and FREM are expanded always, see
651 // ARMTargetLowering::addTypeForNEON method for details.
652 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
653 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
654 // FIXME: Create unittest.
655 // In another words, find a way when "copysign" appears in DAG with vector
656 // operands.
658 // FIXME: Code duplication: SETCC has custom operation action, see
659 // ARMTargetLowering::addTypeForNEON method for details.
661 // FIXME: Create unittest for FNEG and for FABS.
662 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
663 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
665 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
666 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
667 setOperationAction(ISD::FTAN, MVT::v2f64, Expand);
668 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
669 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
672 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
681 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
682 }
683
684 if (Subtarget->hasNEON()) {
685 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
686 // supported for v4f32.
688 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
689 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
690 setOperationAction(ISD::FTAN, MVT::v4f32, Expand);
691 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
692 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
695 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
704
705 // Mark v2f32 intrinsics.
707 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
708 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
709 setOperationAction(ISD::FTAN, MVT::v2f32, Expand);
710 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
711 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
714 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
723
726 setOperationAction(Op, MVT::v4f16, Expand);
727 setOperationAction(Op, MVT::v8f16, Expand);
728 }
729
730 // Neon does not support some operations on v1i64 and v2i64 types.
731 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
732 // Custom handling for some quad-vector types to detect VMULL.
733 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
734 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
735 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
736 // Custom handling for some vector types to avoid expensive expansions
737 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
739 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
741 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
742 // a destination type that is wider than the source, and nor does
743 // it have a FP_TO_[SU]INT instruction with a narrower destination than
744 // source.
753
756
757 // NEON does not have single instruction CTPOP for vectors with element
758 // types wider than 8-bits. However, custom lowering can leverage the
759 // v8i8/v16i8 vcnt instruction.
766
767 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
768 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
769
770 // NEON does not have single instruction CTTZ for vectors.
772 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
773 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
774 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
775
776 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
777 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
778 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
779 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
780
785
790
794 }
795
796 // NEON only has FMA instructions as of VFP4.
797 if (!Subtarget->hasVFP4Base()) {
798 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
799 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
800 }
801
804
805 // It is legal to extload from v4i8 to v4i16 or v4i32.
806 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
807 MVT::v2i32}) {
812 }
813 }
814
815 for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
816 MVT::v4i32}) {
821 }
822 }
823
824 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
831 }
832 if (Subtarget->hasMVEIntegerOps()) {
835 ISD::SETCC});
836 }
837 if (Subtarget->hasMVEFloatOps()) {
839 }
840
841 if (!Subtarget->hasFP64()) {
842 // When targeting a floating-point unit with only single-precision
843 // operations, f64 is legal for the few double-precision instructions which
844 // are present However, no double-precision operations other than moves,
845 // loads and stores are provided by the hardware.
882 }
883
884 // STRICT_(U/S)INT_TO_FP specifically use the input MVT to register with
885 // setOperationAction() as opposed to other opcodes that use the output MVT
886 // All inputs should be i32 due to type legalization
889
892
893 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
896 if (Subtarget->hasFullFP16()) {
899 }
900 } else {
902 }
903
904 if (!Subtarget->hasFP16()) {
907 } else {
910 }
911
912 computeRegisterProperties(Subtarget->getRegisterInfo());
913
914 // ARM does not have floating-point extending loads.
915 for (MVT VT : MVT::fp_valuetypes()) {
916 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
917 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
918 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
919 }
920
921 // ... or truncating stores
922 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
923 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
924 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
925 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
926 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
927
928 // ARM does not have i1 sign extending load.
929 for (MVT VT : MVT::integer_valuetypes())
931
932 // ARM supports all 4 flavors of integer indexed load / store.
933 if (!Subtarget->isThumb1Only()) {
934 for (unsigned im = (unsigned)ISD::PRE_INC;
936 setIndexedLoadAction(im, MVT::i1, Legal);
937 setIndexedLoadAction(im, MVT::i8, Legal);
938 setIndexedLoadAction(im, MVT::i16, Legal);
939 setIndexedLoadAction(im, MVT::i32, Legal);
940 setIndexedStoreAction(im, MVT::i1, Legal);
941 setIndexedStoreAction(im, MVT::i8, Legal);
942 setIndexedStoreAction(im, MVT::i16, Legal);
943 setIndexedStoreAction(im, MVT::i32, Legal);
944 }
945 } else {
946 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
949 }
950
951 // Custom loads/stores to possible use __aeabi_uread/write*
952 if (TT.isTargetAEABI() && !Subtarget->allowsUnalignedMem()) {
957 }
958
963
964 if (!Subtarget->isThumb1Only()) {
967 }
968
973 if (Subtarget->hasDSP()) {
982 }
983 if (Subtarget->hasBaseDSP()) {
986 }
987
988 // i64 operation support.
991 if (Subtarget->isThumb1Only()) {
994 }
995 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
996 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
998
1008
1009 // MVE lowers 64 bit shifts to lsll and lsrl
1010 // assuming that ISD::SRL and SRA of i64 are already marked custom
1011 if (Subtarget->hasMVEIntegerOps())
1013
1014 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1015 if (Subtarget->isThumb1Only()) {
1019 }
1020
1021 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1023
1024 // ARM does not have ROTL.
1029 }
1031 // TODO: These two should be set to LibCall, but this currently breaks
1032 // the Linux kernel build. See #101786.
1035 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1038 }
1039
1040 // @llvm.readcyclecounter requires the Performance Monitors extension.
1041 // Default to the 0 expansion on unsupported platforms.
1042 // FIXME: Technically there are older ARM CPUs that have
1043 // implementation-specific ways of obtaining this information.
1044 if (Subtarget->hasPerfMon())
1046
1047 // Only ARMv6 has BSWAP.
1048 if (!Subtarget->hasV6Ops())
1050
1051 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1052 : Subtarget->hasDivideInARMMode();
1053 if (!hasDivide) {
1054 // These are expanded into libcalls if the cpu doesn't have HW divider.
1057 }
1058
1059 if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1062
1065 }
1066
1069
1070 // Register based DivRem for AEABI (RTABI 4.2)
1071 if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1072 TT.isTargetMuslAEABI() || TT.isOSFuchsia() || TT.isOSWindows()) {
1075 HasStandaloneRem = false;
1076
1081 } else {
1084 }
1085
1090
1091 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1093
1094 // Use the default implementation.
1096 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1098 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1101
1102 if (TT.isOSWindows())
1104 else
1106
1107 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1108 // the default expansion.
1109 InsertFencesForAtomic = false;
1110 if (Subtarget->hasAnyDataBarrier() &&
1111 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1112 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1113 // to ldrex/strex loops already.
1115 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1117
1118 // On v8, we have particularly efficient implementations of atomic fences
1119 // if they can be combined with nearby atomic loads and stores.
1120 if (!Subtarget->hasAcquireRelease() ||
1121 getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1122 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1123 InsertFencesForAtomic = true;
1124 }
1125 } else {
1126 // If there's anything we can use as a barrier, go through custom lowering
1127 // for ATOMIC_FENCE.
1128 // If target has DMB in thumb, Fences can be inserted.
1129 if (Subtarget->hasDataBarrier())
1130 InsertFencesForAtomic = true;
1131
1133 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1134
1135 // Set them all for libcall, which will force libcalls.
1141 {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, LibCall);
1142 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1143 // Unordered/Monotonic case.
1144 if (!InsertFencesForAtomic) {
1147 }
1148 }
1149
1150 // Compute supported atomic widths.
1151 if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1152 // For targets where __sync_* routines are reliably available, we use them
1153 // if necessary.
1154 //
1155 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1156 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1157 //
1158 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1159 // such targets should provide __sync_* routines, which use the ARM mode
1160 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1161 // encoding; see ARMISD::MEMBARRIER_MCR.)
1163 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1164 Subtarget->hasForced32BitAtomics()) {
1165 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1167 } else {
1168 // We can't assume anything about other targets; just use libatomic
1169 // routines.
1171 }
1172
1174
1176
1177 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1178 if (!Subtarget->hasV6Ops()) {
1181 }
1183
1184 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1185 !Subtarget->isThumb1Only()) {
1186 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1187 // iff target supports vfp2.
1197 }
1198
1199 // We want to custom lower some of our intrinsics.
1204
1214 if (Subtarget->hasFullFP16()) {
1218 }
1219
1221
1224 if (Subtarget->hasFullFP16())
1228 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1229
1230 // We don't support sin/cos/fmod/copysign/pow
1239 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1240 !Subtarget->isThumb1Only()) {
1243 }
1246
1247 if (!Subtarget->hasVFP4Base()) {
1250 }
1251
1252 // Various VFP goodness
1253 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1254 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1255 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1260 }
1261
1262 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1263 if (!Subtarget->hasFP16()) {
1268 }
1269
1270 // Strict floating-point comparisons need custom lowering.
1277 }
1278
1279 // FP-ARMv8 implements a lot of rounding-like FP operations.
1280 if (Subtarget->hasFPARMv8Base()) {
1281 for (auto Op :
1288 setOperationAction(Op, MVT::f32, Legal);
1289
1290 if (Subtarget->hasFP64())
1291 setOperationAction(Op, MVT::f64, Legal);
1292 }
1293
1294 if (Subtarget->hasNEON()) {
1299 }
1300 }
1301
1302 // FP16 often need to be promoted to call lib functions
1303 // clang-format off
1304 if (Subtarget->hasFullFP16()) {
1308
1309 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
1323 setOperationAction(Op, MVT::f16, Promote);
1324 }
1325
1326 // Round-to-integer need custom lowering for fp16, as Promote doesn't work
1327 // because the result type is integer.
1329 setOperationAction(Op, MVT::f16, Custom);
1330
1336 setOperationAction(Op, MVT::f16, Legal);
1337 }
1338 // clang-format on
1339 }
1340
1341 if (Subtarget->hasNEON()) {
1342 // vmin and vmax aren't available in a scalar form, so we can use
1343 // a NEON instruction with an undef lane instead.
1352
1353 if (Subtarget->hasV8Ops()) {
1354 for (auto Op :
1358 setOperationAction(Op, MVT::v2f32, Legal);
1359 setOperationAction(Op, MVT::v4f32, Legal);
1360 }
1361 }
1362
1363 if (Subtarget->hasFullFP16()) {
1368
1373
1374 for (auto Op :
1378 setOperationAction(Op, MVT::v4f16, Legal);
1379 setOperationAction(Op, MVT::v8f16, Legal);
1380 }
1381 }
1382 }
1383
1384 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
1385 // it, but it's just a wrapper around ldexp.
1386 if (TT.isOSWindows()) {
1388 if (isOperationExpand(Op, MVT::f32))
1389 setOperationAction(Op, MVT::f32, Promote);
1390 }
1391
1392 // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1393 // isn't legal.
1395 if (isOperationExpand(Op, MVT::f16))
1396 setOperationAction(Op, MVT::f16, Promote);
1397
1398 // We have target-specific dag combine patterns for the following nodes:
1399 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1402
1403 if (Subtarget->hasMVEIntegerOps())
1405
1406 if (Subtarget->hasV6Ops())
1408 if (Subtarget->isThumb1Only())
1410 // Attempt to lower smin/smax to ssat/usat
1411 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1412 Subtarget->isThumb2()) {
1414 }
1415
1417
1418 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1419 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1421 else
1423
1424 //// temporary - rewrite interface to use type
1427 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1429 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1431
1432 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1433 // are at least 4 bytes aligned.
1435
1436 // Prefer likely predicted branches to selects on out-of-order cores.
1437 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1438
1440 Align::fromLog2(Subtarget->getPreferBranchLogAlignment()));
1442 Align::fromLog2(Subtarget->getPreferBranchLogAlignment()));
1443
1444 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1445
1446 IsStrictFPEnabled = true;
1447}
1448
1450 return Subtarget->useSoftFloat();
1451}
1452
1454 return !Subtarget->isThumb1Only() && VT.getSizeInBits() <= 32;
1455}
1456
1457// FIXME: It might make sense to define the representative register class as the
1458// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1459// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1460// SPR's representative would be DPR_VFP2. This should work well if register
1461// pressure tracking were modified such that a register use would increment the
1462// pressure of the register class's representative and all of it's super
1463// classes' representatives transitively. We have not implemented this because
1464// of the difficulty prior to coalescing of modeling operand register classes
1465// due to the common occurrence of cross class copies and subregister insertions
1466// and extractions.
1467std::pair<const TargetRegisterClass *, uint8_t>
1469 MVT VT) const {
1470 const TargetRegisterClass *RRC = nullptr;
1471 uint8_t Cost = 1;
1472 switch (VT.SimpleTy) {
1473 default:
1475 // Use DPR as representative register class for all floating point
1476 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1477 // the cost is 1 for both f32 and f64.
1478 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1479 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1480 RRC = &ARM::DPRRegClass;
1481 // When NEON is used for SP, only half of the register file is available
1482 // because operations that define both SP and DP results will be constrained
1483 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1484 // coalescing by double-counting the SP regs. See the FIXME above.
1485 if (Subtarget->useNEONForSinglePrecisionFP())
1486 Cost = 2;
1487 break;
1488 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1489 case MVT::v4f32: case MVT::v2f64:
1490 RRC = &ARM::DPRRegClass;
1491 Cost = 2;
1492 break;
1493 case MVT::v4i64:
1494 RRC = &ARM::DPRRegClass;
1495 Cost = 4;
1496 break;
1497 case MVT::v8i64:
1498 RRC = &ARM::DPRRegClass;
1499 Cost = 8;
1500 break;
1501 }
1502 return std::make_pair(RRC, Cost);
1503}
1504
1506 EVT VT) const {
1507 if (!VT.isVector())
1508 return getPointerTy(DL);
1509
1510 // MVE has a predicate register.
1511 if (Subtarget->hasMVEIntegerOps())
1512 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1513
1515}
1516
1517/// getRegClassFor - Return the register class that should be used for the
1518/// specified value type.
1519const TargetRegisterClass *
1520ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1521 (void)isDivergent;
1522 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1523 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1524 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1525 // MVE Q registers.
1526 if (Subtarget->hasNEON()) {
1527 if (VT == MVT::v4i64)
1528 return &ARM::QQPRRegClass;
1529 if (VT == MVT::v8i64)
1530 return &ARM::QQQQPRRegClass;
1531 }
1532 if (Subtarget->hasMVEIntegerOps()) {
1533 if (VT == MVT::v4i64)
1534 return &ARM::MQQPRRegClass;
1535 if (VT == MVT::v8i64)
1536 return &ARM::MQQQQPRRegClass;
1537 }
1539}
1540
1541// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1542// source/dest is aligned and the copy size is large enough. We therefore want
1543// to align such objects passed to memory intrinsics.
1545 Align &PrefAlign) const {
1546 if (!isa<MemIntrinsic>(CI))
1547 return false;
1548 MinSize = 8;
1549 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1550 // cycle faster than 4-byte aligned LDM.
1551 PrefAlign =
1552 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1553 return true;
1554}
1555
1556// Create a fast isel object.
1558 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
1559 const LibcallLoweringInfo *libcallLowering) const {
1560 return ARM::createFastISel(funcInfo, libInfo, libcallLowering);
1561}
1562
1564 unsigned NumVals = N->getNumValues();
1565 if (!NumVals)
1566 return Sched::RegPressure;
1567
1568 for (unsigned i = 0; i != NumVals; ++i) {
1569 EVT VT = N->getValueType(i);
1570 if (VT == MVT::Glue || VT == MVT::Other)
1571 continue;
1572 if (VT.isFloatingPoint() || VT.isVector())
1573 return Sched::ILP;
1574 }
1575
1576 if (!N->isMachineOpcode())
1577 return Sched::RegPressure;
1578
1579 // Load are scheduled for latency even if there instruction itinerary
1580 // is not available.
1581 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1582 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1583
1584 if (MCID.getNumDefs() == 0)
1585 return Sched::RegPressure;
1586 if (!Itins->isEmpty() &&
1587 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1588 return Sched::ILP;
1589
1590 return Sched::RegPressure;
1591}
1592
1593//===----------------------------------------------------------------------===//
1594// Lowering Code
1595//===----------------------------------------------------------------------===//
1596
1597static bool isSRL16(const SDValue &Op) {
1598 if (Op.getOpcode() != ISD::SRL)
1599 return false;
1600 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1601 return Const->getZExtValue() == 16;
1602 return false;
1603}
1604
1605static bool isSRA16(const SDValue &Op) {
1606 if (Op.getOpcode() != ISD::SRA)
1607 return false;
1608 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1609 return Const->getZExtValue() == 16;
1610 return false;
1611}
1612
1613static bool isSHL16(const SDValue &Op) {
1614 if (Op.getOpcode() != ISD::SHL)
1615 return false;
1616 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1617 return Const->getZExtValue() == 16;
1618 return false;
1619}
1620
1621// Check for a signed 16-bit value. We special case SRA because it makes it
1622// more simple when also looking for SRAs that aren't sign extending a
1623// smaller value. Without the check, we'd need to take extra care with
1624// checking order for some operations.
1625static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1626 if (isSRA16(Op))
1627 return isSHL16(Op.getOperand(0));
1628 return DAG.ComputeNumSignBits(Op) == 17;
1629}
1630
1631/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1633 switch (CC) {
1634 default: llvm_unreachable("Unknown condition code!");
1635 case ISD::SETNE: return ARMCC::NE;
1636 case ISD::SETEQ: return ARMCC::EQ;
1637 case ISD::SETGT: return ARMCC::GT;
1638 case ISD::SETGE: return ARMCC::GE;
1639 case ISD::SETLT: return ARMCC::LT;
1640 case ISD::SETLE: return ARMCC::LE;
1641 case ISD::SETUGT: return ARMCC::HI;
1642 case ISD::SETUGE: return ARMCC::HS;
1643 case ISD::SETULT: return ARMCC::LO;
1644 case ISD::SETULE: return ARMCC::LS;
1645 }
1646}
1647
1648/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1650 ARMCC::CondCodes &CondCode2) {
1651 CondCode2 = ARMCC::AL;
1652 switch (CC) {
1653 default: llvm_unreachable("Unknown FP condition!");
1654 case ISD::SETEQ:
1655 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1656 case ISD::SETGT:
1657 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1658 case ISD::SETGE:
1659 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1660 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1661 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1662 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1663 case ISD::SETO: CondCode = ARMCC::VC; break;
1664 case ISD::SETUO: CondCode = ARMCC::VS; break;
1665 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1666 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1667 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1668 case ISD::SETLT:
1669 case ISD::SETULT: CondCode = ARMCC::LT; break;
1670 case ISD::SETLE:
1671 case ISD::SETULE: CondCode = ARMCC::LE; break;
1672 case ISD::SETNE:
1673 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1674 }
1675}
1676
1677//===----------------------------------------------------------------------===//
1678// Calling Convention Implementation
1679//===----------------------------------------------------------------------===//
1680
1681/// getEffectiveCallingConv - Get the effective calling convention, taking into
1682/// account presence of floating point hardware and calling convention
1683/// limitations, such as support for variadic functions.
1686 bool isVarArg) const {
1687 switch (CC) {
1688 default:
1689 // Unknown CCs are rejected when calling convention lowering is required.
1692 case CallingConv::GHC:
1694 return CC;
1700 case CallingConv::Swift:
1703 case CallingConv::C:
1704 case CallingConv::Tail:
1705 if (!Subtarget->isAAPCS_ABI())
1706 return CallingConv::ARM_APCS;
1707 else if (Subtarget->isTargetHardFloat() && !isVarArg)
1709 else
1711 case CallingConv::Fast:
1713 if (!Subtarget->isAAPCS_ABI()) {
1714 if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() && !isVarArg)
1715 return CallingConv::Fast;
1716 return CallingConv::ARM_APCS;
1717 } else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1718 !Subtarget->useSoftFloat() && !isVarArg)
1720 else
1722 }
1723}
1724
1726 bool isVarArg) const {
1727 return CCAssignFnForNode(CC, false, isVarArg);
1728}
1729
1731 bool isVarArg) const {
1732 return CCAssignFnForNode(CC, true, isVarArg);
1733}
1734
1735/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1736/// CallingConvention.
1737CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1738 bool Return,
1739 bool isVarArg) const {
1740 switch (getEffectiveCallingConv(CC, isVarArg)) {
1741 default:
1742 report_fatal_error("Unsupported calling convention");
1744 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1746 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1748 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1749 case CallingConv::Fast:
1750 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1751 case CallingConv::GHC:
1752 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1754 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1756 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1758 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1759 }
1760}
1761
1762SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
1763 MVT LocVT, MVT ValVT, SDValue Val) const {
1764 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
1765 Val);
1766 if (Subtarget->hasFullFP16()) {
1767 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
1768 } else {
1769 Val = DAG.getNode(ISD::TRUNCATE, dl,
1770 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1771 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
1772 }
1773 return Val;
1774}
1775
1776SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
1777 MVT LocVT, MVT ValVT,
1778 SDValue Val) const {
1779 if (Subtarget->hasFullFP16()) {
1780 Val = DAG.getNode(ARMISD::VMOVrh, dl,
1781 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1782 } else {
1783 Val = DAG.getNode(ISD::BITCAST, dl,
1784 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1785 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
1786 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1787 }
1788 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
1789}
1790
1791/// LowerCallResult - Lower the result values of a call into the
1792/// appropriate copies out of appropriate physical registers.
1793SDValue ARMTargetLowering::LowerCallResult(
1794 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1795 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1796 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1797 SDValue ThisVal, bool isCmseNSCall) const {
1798 // Assign locations to each value returned by this call.
1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1801 *DAG.getContext());
1802 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1803
1804 // Copy all of the result registers out of their specified physreg.
1805 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1806 CCValAssign VA = RVLocs[i];
1807
1808 // Pass 'this' value directly from the argument to return value, to avoid
1809 // reg unit interference
1810 if (i == 0 && isThisReturn) {
1811 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1812 "unexpected return calling convention register assignment");
1813 InVals.push_back(ThisVal);
1814 continue;
1815 }
1816
1817 SDValue Val;
1818 if (VA.needsCustom() &&
1819 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
1820 // Handle f64 or half of a v2f64.
1821 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1822 InGlue);
1823 Chain = Lo.getValue(1);
1824 InGlue = Lo.getValue(2);
1825 VA = RVLocs[++i]; // skip ahead to next loc
1826 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1827 InGlue);
1828 Chain = Hi.getValue(1);
1829 InGlue = Hi.getValue(2);
1830 if (!Subtarget->isLittle())
1831 std::swap (Lo, Hi);
1832 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1833
1834 if (VA.getLocVT() == MVT::v2f64) {
1835 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1836 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1837 DAG.getConstant(0, dl, MVT::i32));
1838
1839 VA = RVLocs[++i]; // skip ahead to next loc
1840 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1841 Chain = Lo.getValue(1);
1842 InGlue = Lo.getValue(2);
1843 VA = RVLocs[++i]; // skip ahead to next loc
1844 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1845 Chain = Hi.getValue(1);
1846 InGlue = Hi.getValue(2);
1847 if (!Subtarget->isLittle())
1848 std::swap (Lo, Hi);
1849 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1850 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1851 DAG.getConstant(1, dl, MVT::i32));
1852 }
1853 } else {
1854 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1855 InGlue);
1856 Chain = Val.getValue(1);
1857 InGlue = Val.getValue(2);
1858 }
1859
1860 switch (VA.getLocInfo()) {
1861 default: llvm_unreachable("Unknown loc info!");
1862 case CCValAssign::Full: break;
1863 case CCValAssign::BCvt:
1864 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1865 break;
1866 }
1867
1868 // f16 arguments have their size extended to 4 bytes and passed as if they
1869 // had been copied to the LSBs of a 32-bit register.
1870 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
1871 if (VA.needsCustom() &&
1872 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
1873 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
1874
1875 // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
1876 // is less than 32 bits must be sign- or zero-extended after the call for
1877 // security reasons. Although the ABI mandates an extension done by the
1878 // callee, the latter cannot be trusted to follow the rules of the ABI.
1879 const ISD::InputArg &Arg = Ins[VA.getValNo()];
1880 if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
1881 VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
1882 Val = handleCMSEValue(Val, Arg, DAG, dl);
1883
1884 InVals.push_back(Val);
1885 }
1886
1887 return Chain;
1888}
1889
1890std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
1891 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
1892 bool IsTailCall, int SPDiff) const {
1893 SDValue DstAddr;
1894 MachinePointerInfo DstInfo;
1895 int32_t Offset = VA.getLocMemOffset();
1897
1898 if (IsTailCall) {
1899 Offset += SPDiff;
1900 auto PtrVT = getPointerTy(DAG.getDataLayout());
1901 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
1902 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
1903 DstAddr = DAG.getFrameIndex(FI, PtrVT);
1904 DstInfo =
1906 } else {
1907 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
1908 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1909 StackPtr, PtrOff);
1910 DstInfo =
1912 }
1913
1914 return std::make_pair(DstAddr, DstInfo);
1915}
1916
1917// Returns the type of copying which is required to set up a byval argument to
1918// a tail-called function. This isn't needed for non-tail calls, because they
1919// always need the equivalent of CopyOnce, but tail-calls sometimes need two to
1920// avoid clobbering another argument (CopyViaTemp), and sometimes can be
1921// optimised to zero copies when forwarding an argument from the caller's
1922// caller (NoCopy).
1923ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
1924 SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
1925 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1926 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1927
1928 // Globals are always safe to copy from.
1930 return CopyOnce;
1931
1932 // Can only analyse frame index nodes, conservatively assume we need a
1933 // temporary.
1934 auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Src);
1935 auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Dst);
1936 if (!SrcFrameIdxNode || !DstFrameIdxNode)
1937 return CopyViaTemp;
1938
1939 int SrcFI = SrcFrameIdxNode->getIndex();
1940 int DstFI = DstFrameIdxNode->getIndex();
1941 assert(MFI.isFixedObjectIndex(DstFI) &&
1942 "byval passed in non-fixed stack slot");
1943
1944 int64_t SrcOffset = MFI.getObjectOffset(SrcFI);
1945 int64_t DstOffset = MFI.getObjectOffset(DstFI);
1946
1947 // If the source is in the local frame, then the copy to the argument memory
1948 // is always valid.
1949 bool FixedSrc = MFI.isFixedObjectIndex(SrcFI);
1950 if (!FixedSrc ||
1951 (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
1952 return CopyOnce;
1953
1954 // In the case of byval arguments split between registers and the stack,
1955 // computeAddrForCallArg returns a FrameIndex which corresponds only to the
1956 // stack portion, but the Src SDValue will refer to the full value, including
1957 // the local stack memory that the register portion gets stored into. We only
1958 // need to compare them for equality, so normalise on the full value version.
1959 uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(DstFI);
1960 DstOffset -= RegSize;
1961
1962 // If the value is already in the correct location, then no copying is
1963 // needed. If not, then we need to copy via a temporary.
1964 if (SrcOffset == DstOffset)
1965 return NoCopy;
1966 else
1967 return CopyViaTemp;
1968}
1969
1970void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1971 SDValue Chain, SDValue &Arg,
1972 RegsToPassVector &RegsToPass,
1973 CCValAssign &VA, CCValAssign &NextVA,
1974 SDValue &StackPtr,
1975 SmallVectorImpl<SDValue> &MemOpChains,
1976 bool IsTailCall,
1977 int SPDiff) const {
1978 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1979 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1980 unsigned id = Subtarget->isLittle() ? 0 : 1;
1981 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1982
1983 if (NextVA.isRegLoc())
1984 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1985 else {
1986 assert(NextVA.isMemLoc());
1987 if (!StackPtr.getNode())
1988 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1990
1991 SDValue DstAddr;
1992 MachinePointerInfo DstInfo;
1993 std::tie(DstAddr, DstInfo) =
1994 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
1995 MemOpChains.push_back(
1996 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
1997 }
1998}
1999
2000static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2001 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2003}
2004
2005/// LowerCall - Lowering a call into a callseq_start <-
2006/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2007/// nodes.
2008SDValue
2009ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2010 SmallVectorImpl<SDValue> &InVals) const {
2011 SelectionDAG &DAG = CLI.DAG;
2012 SDLoc &dl = CLI.DL;
2013 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2014 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2015 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2016 SDValue Chain = CLI.Chain;
2017 SDValue Callee = CLI.Callee;
2018 bool &isTailCall = CLI.IsTailCall;
2019 CallingConv::ID CallConv = CLI.CallConv;
2020 bool doesNotRet = CLI.DoesNotReturn;
2021 bool isVarArg = CLI.IsVarArg;
2022 const CallBase *CB = CLI.CB;
2023
2025 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2026 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2027 MachineFunction::CallSiteInfo CSInfo;
2028 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2029 bool isThisReturn = false;
2030 bool isCmseNSCall = false;
2031 bool isSibCall = false;
2032 bool PreferIndirect = false;
2033 bool GuardWithBTI = false;
2034
2035 // Analyze operands of the call, assigning locations to each operand.
2037 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2038 *DAG.getContext());
2039 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2040
2041 // Lower 'returns_twice' calls to a pseudo-instruction.
2042 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2043 !Subtarget->noBTIAtReturnTwice())
2044 GuardWithBTI = AFI->branchTargetEnforcement();
2045
2046 // Set type id for call site info.
2047 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
2048
2049 // Determine whether this is a non-secure function call.
2050 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2051 isCmseNSCall = true;
2052
2053 // Disable tail calls if they're not supported.
2054 if (!Subtarget->supportsTailCall())
2055 isTailCall = false;
2056
2057 // For both the non-secure calls and the returns from a CMSE entry function,
2058 // the function needs to do some extra work after the call, or before the
2059 // return, respectively, thus it cannot end with a tail call
2060 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2061 isTailCall = false;
2062
2063 if (isa<GlobalAddressSDNode>(Callee)) {
2064 // If we're optimizing for minimum size and the function is called three or
2065 // more times in this block, we can improve codesize by calling indirectly
2066 // as BLXr has a 16-bit encoding.
2067 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2068 if (CLI.CB) {
2069 auto *BB = CLI.CB->getParent();
2070 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2071 count_if(GV->users(), [&BB](const User *U) {
2072 return isa<Instruction>(U) &&
2073 cast<Instruction>(U)->getParent() == BB;
2074 }) > 2;
2075 }
2076 }
2077 if (isTailCall) {
2078 // Check if it's really possible to do a tail call.
2079 isTailCall =
2080 IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, PreferIndirect);
2081
2082 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2083 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2084 isSibCall = true;
2085
2086 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2087 // detected sibcalls.
2088 if (isTailCall)
2089 ++NumTailCalls;
2090 }
2091
2092 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2093 report_fatal_error("failed to perform tail call elimination on a call "
2094 "site marked musttail");
2095
2096 // Get a count of how many bytes are to be pushed on the stack.
2097 unsigned NumBytes = CCInfo.getStackSize();
2098
2099 // SPDiff is the byte offset of the call's argument area from the callee's.
2100 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2101 // by this amount for a tail call. In a sibling call it must be 0 because the
2102 // caller will deallocate the entire stack and the callee still expects its
2103 // arguments to begin at SP+0. Completely unused for non-tail calls.
2104 int SPDiff = 0;
2105
2106 if (isTailCall && !isSibCall) {
2107 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2108 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2109
2110 // Since callee will pop argument stack as a tail call, we must keep the
2111 // popped size 16-byte aligned.
2112 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2113 assert(StackAlign && "data layout string is missing stack alignment");
2114 NumBytes = alignTo(NumBytes, *StackAlign);
2115
2116 // SPDiff will be negative if this tail call requires more space than we
2117 // would automatically have in our incoming argument space. Positive if we
2118 // can actually shrink the stack.
2119 SPDiff = NumReusableBytes - NumBytes;
2120
2121 // If this call requires more stack than we have available from
2122 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2123 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2124 AFI->setArgRegsSaveSize(-SPDiff);
2125 }
2126
2127 if (isSibCall) {
2128 // For sibling tail calls, memory operands are available in our caller's stack.
2129 NumBytes = 0;
2130 } else {
2131 // Adjust the stack pointer for the new arguments...
2132 // These operations are automatically eliminated by the prolog/epilog pass
2133 Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2134 }
2135
2137 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2138
2139 RegsToPassVector RegsToPass;
2140 SmallVector<SDValue, 8> MemOpChains;
2141
2142 // A musttail call in a variadic function must receive the caller's unnamed
2143 // register arguments unchanged. The forwarded set is disjoint from the named
2144 // arguments handled below.
2145 if (isVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
2146 const auto &Forwards = AFI->getForwardedMustTailRegParms();
2147 for (const ForwardedRegister &F : Forwards) {
2148 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2149 RegsToPass.push_back(std::make_pair(F.PReg, Val));
2150 }
2151 }
2152
2153 // If we are doing a tail-call, any byval arguments will be written to stack
2154 // space which was used for incoming arguments. If any the values being used
2155 // are incoming byval arguments to this function, then they might be
2156 // overwritten by the stores of the outgoing arguments. To avoid this, we
2157 // need to make a temporary copy of them in local stack space, then copy back
2158 // to the argument area.
2159 DenseMap<unsigned, SDValue> ByValTemporaries;
2160 SDValue ByValTempChain;
2161 if (isTailCall) {
2162 SmallVector<SDValue, 8> ByValCopyChains;
2163 for (const CCValAssign &VA : ArgLocs) {
2164 unsigned ArgIdx = VA.getValNo();
2165 SDValue Src = OutVals[ArgIdx];
2166 ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2167
2168 if (!Flags.isByVal())
2169 continue;
2170
2171 SDValue Dst;
2172 MachinePointerInfo DstInfo;
2173 std::tie(Dst, DstInfo) =
2174 computeAddrForCallArg(dl, DAG, VA, SDValue(), true, SPDiff);
2175 ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2176
2177 if (Copy == NoCopy) {
2178 // If the argument is already at the correct offset on the stack
2179 // (because we are forwarding a byval argument from our caller), we
2180 // don't need any copying.
2181 continue;
2182 } else if (Copy == CopyOnce) {
2183 // If the argument is in our local stack frame, no other argument
2184 // preparation can clobber it, so we can copy it to the final location
2185 // later.
2186 ByValTemporaries[ArgIdx] = Src;
2187 } else {
2188 assert(Copy == CopyViaTemp && "unexpected enum value");
2189 // If we might be copying this argument from the outgoing argument
2190 // stack area, we need to copy via a temporary in the local stack
2191 // frame.
2192 int TempFrameIdx = MFI.CreateStackObject(
2193 Flags.getByValSize(), Flags.getNonZeroByValAlign(), false);
2194 SDValue Temp =
2195 DAG.getFrameIndex(TempFrameIdx, getPointerTy(DAG.getDataLayout()));
2196
2197 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2198 SDValue AlignNode =
2199 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2200
2201 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2202 SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2203 ByValCopyChains.push_back(
2204 DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, Ops));
2205 ByValTemporaries[ArgIdx] = Temp;
2206 }
2207 }
2208 if (!ByValCopyChains.empty())
2209 ByValTempChain =
2210 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, ByValCopyChains);
2211 }
2212
2213 // During a tail call, stores to the argument area must happen after all of
2214 // the function's incoming arguments have been loaded because they may alias.
2215 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2216 // there's no point in doing so repeatedly so this tracks whether that's
2217 // happened yet.
2218 bool AfterFormalArgLoads = false;
2219
2220 // Walk the register/memloc assignments, inserting copies/loads. In the case
2221 // of tail call optimization, arguments are handled later.
2222 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2223 i != e;
2224 ++i, ++realArgIdx) {
2225 CCValAssign &VA = ArgLocs[i];
2226 SDValue Arg = OutVals[realArgIdx];
2227 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2228 bool isByVal = Flags.isByVal();
2229
2230 // Promote the value if needed.
2231 switch (VA.getLocInfo()) {
2232 default: llvm_unreachable("Unknown loc info!");
2233 case CCValAssign::Full: break;
2234 case CCValAssign::SExt:
2235 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2236 break;
2237 case CCValAssign::ZExt:
2238 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2239 break;
2240 case CCValAssign::AExt:
2241 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2242 break;
2243 case CCValAssign::BCvt:
2244 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2245 break;
2246 }
2247
2248 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2249 Chain = DAG.getStackArgumentTokenFactor(Chain);
2250 if (ByValTempChain) {
2251 // In case of large byval copies, re-using the stackframe for tail-calls
2252 // can lead to overwriting incoming arguments on the stack. Force
2253 // loading these stack arguments before the copy to avoid that.
2254 SmallVector<SDValue, 8> IncomingLoad;
2255 for (unsigned I = 0; I < OutVals.size(); ++I) {
2256 if (Outs[I].Flags.isByVal())
2257 continue;
2258
2259 SDValue OutVal = OutVals[I];
2260 LoadSDNode *OutLN = dyn_cast_or_null<LoadSDNode>(OutVal);
2261 if (!OutLN)
2262 continue;
2263
2264 FrameIndexSDNode *FIN =
2266 if (!FIN)
2267 continue;
2268
2269 if (!MFI.isFixedObjectIndex(FIN->getIndex()))
2270 continue;
2271
2272 for (const CCValAssign &VA : ArgLocs) {
2273 if (VA.isMemLoc())
2274 IncomingLoad.push_back(OutVal.getValue(1));
2275 }
2276 }
2277
2278 // Update the chain to force loads for potentially clobbered argument
2279 // loads to happen before the byval copy.
2280 if (!IncomingLoad.empty()) {
2281 IncomingLoad.push_back(Chain);
2282 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, IncomingLoad);
2283 }
2284
2285 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chain,
2286 ByValTempChain);
2287 }
2288 AfterFormalArgLoads = true;
2289 }
2290
2291 // f16 arguments have their size extended to 4 bytes and passed as if they
2292 // had been copied to the LSBs of a 32-bit register.
2293 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2294 if (VA.needsCustom() &&
2295 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2296 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2297 } else {
2298 // f16 arguments could have been extended prior to argument lowering.
2299 // Mask them arguments if this is a CMSE nonsecure call.
2300 auto ArgVT = Outs[realArgIdx].ArgVT;
2301 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2302 auto LocBits = VA.getLocVT().getSizeInBits();
2303 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2304 SDValue Mask =
2305 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2306 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2307 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2308 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2309 }
2310 }
2311
2312 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2313 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2314 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2315 DAG.getConstant(0, dl, MVT::i32));
2316 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2317 DAG.getConstant(1, dl, MVT::i32));
2318
2319 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2320 StackPtr, MemOpChains, isTailCall, SPDiff);
2321
2322 VA = ArgLocs[++i]; // skip ahead to next loc
2323 if (VA.isRegLoc()) {
2324 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2325 StackPtr, MemOpChains, isTailCall, SPDiff);
2326 } else {
2327 assert(VA.isMemLoc());
2328 SDValue DstAddr;
2329 MachinePointerInfo DstInfo;
2330 std::tie(DstAddr, DstInfo) =
2331 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2332 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2333 }
2334 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2335 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2336 StackPtr, MemOpChains, isTailCall, SPDiff);
2337 } else if (VA.isRegLoc()) {
2338 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2339 Outs[0].VT == MVT::i32) {
2340 assert(VA.getLocVT() == MVT::i32 &&
2341 "unexpected calling convention register assignment");
2342 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2343 "unexpected use of 'returned'");
2344 isThisReturn = true;
2345 }
2346 const TargetOptions &Options = DAG.getTarget().Options;
2347 if (Options.EmitCallSiteInfo)
2348 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
2349 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2350 } else if (isByVal) {
2351 assert(VA.isMemLoc());
2352 unsigned offset = 0;
2353
2354 // True if this byval aggregate will be split between registers
2355 // and memory.
2356 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2357 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2358
2359 SDValue ByValSrc;
2360 bool NeedsStackCopy;
2361 if (auto It = ByValTemporaries.find(realArgIdx);
2362 It != ByValTemporaries.end()) {
2363 ByValSrc = It->second;
2364 NeedsStackCopy = true;
2365 } else {
2366 ByValSrc = Arg;
2367 NeedsStackCopy = !isTailCall;
2368 }
2369
2370 // If part of the argument is in registers, load them.
2371 if (CurByValIdx < ByValArgsCount) {
2372 unsigned RegBegin, RegEnd;
2373 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2374
2375 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2376 unsigned int i, j;
2377 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2378 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2379 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, Const);
2380 SDValue Load =
2381 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2382 DAG.InferPtrAlign(AddArg));
2383 MemOpChains.push_back(Load.getValue(1));
2384 RegsToPass.push_back(std::make_pair(j, Load));
2385 }
2386
2387 // If parameter size outsides register area, "offset" value
2388 // helps us to calculate stack slot for remained part properly.
2389 offset = RegEnd - RegBegin;
2390
2391 CCInfo.nextInRegsParam();
2392 }
2393
2394 // If the memory part of the argument isn't already in the correct place
2395 // (which can happen with tail calls), copy it into the argument area.
2396 if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2397 auto PtrVT = getPointerTy(DAG.getDataLayout());
2398 SDValue Dst;
2399 MachinePointerInfo DstInfo;
2400 std::tie(Dst, DstInfo) =
2401 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2402 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2403 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, SrcOffset);
2404 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2405 MVT::i32);
2406 SDValue AlignNode =
2407 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2408
2409 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2410 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2411 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2412 Ops));
2413 }
2414 } else {
2415 assert(VA.isMemLoc());
2416 SDValue DstAddr;
2417 MachinePointerInfo DstInfo;
2418 std::tie(DstAddr, DstInfo) =
2419 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2420
2421 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2422 MemOpChains.push_back(Store);
2423 }
2424 }
2425
2426 if (!MemOpChains.empty())
2427 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2428
2429 // Build a sequence of copy-to-reg nodes chained together with token chain
2430 // and flag operands which copy the outgoing args into the appropriate regs.
2431 SDValue InGlue;
2432 for (const auto &[Reg, N] : RegsToPass) {
2433 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
2434 InGlue = Chain.getValue(1);
2435 }
2436
2437 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2438 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2439 // node so that legalize doesn't hack it.
2440 bool isDirect = false;
2441
2442 const TargetMachine &TM = getTargetMachine();
2443 const Triple &TT = TM.getTargetTriple();
2444 const GlobalValue *GVal = nullptr;
2445 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2446 GVal = G->getGlobal();
2447 bool isStub = !TM.shouldAssumeDSOLocal(GVal) && TT.isOSBinFormatMachO();
2448
2449 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2450 bool isLocalARMFunc = false;
2451 auto PtrVt = getPointerTy(DAG.getDataLayout());
2452
2453 if (Subtarget->genLongCalls()) {
2454 bool isPIC = isPositionIndependent() && !TT.isOSWindows();
2455 if (isPIC && Subtarget->genExecuteOnly())
2456 reportFatalUsageError("long-calls with execute-only and "
2457 "position-independent code is not supported");
2458 if (Subtarget->isROPI())
2459 reportFatalUsageError("long-calls with ROPI is not currently supported");
2460
2461 // Handle a global address or an external symbol. If it's not one of
2462 // those, the target's already in a register, so we don't need to do
2463 // anything extra.
2464 if (isa<GlobalAddressSDNode>(Callee)) {
2465 if (Subtarget->genExecuteOnly()) {
2466 // Execute-only forbids constant pools in .text, so use movw/movt.
2467 // fPIC is not supported with execute-only.
2468 if (Subtarget->useMovt())
2469 ++NumMovwMovt;
2470 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2471 DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2472 } else if (isPIC) {
2473 // PIC without execute-only: use GOT-based addressing.
2474 // DSO-local symbols use a plain PC-relative WrapperPIC;
2475 // non-DSO-local symbols additionally load the address from the GOT.
2477 GVal, dl, PtrVt, 0, GVal->isDSOLocal() ? 0 : ARMII::MO_GOT);
2478 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVt, G);
2479 if (!GVal->isDSOLocal())
2480 Callee =
2481 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2483 } else {
2484 // Neither execute-only nor PIC: load the address from a constant pool.
2485 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2486 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2487 GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2488
2489 // Get the address of the callee into a register
2490 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2491 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2492 Callee = DAG.getLoad(
2493 PtrVt, dl, DAG.getEntryNode(), Addr,
2495 }
2496 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2497 const char *Sym = S->getSymbol();
2498
2499 if (Subtarget->genExecuteOnly()) {
2500 // Execute-only forbids constant pools in .text, so use movw/movt.
2501 // fPIC is not supported with execute-only.
2502 if (Subtarget->useMovt())
2503 ++NumMovwMovt;
2504 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2505 DAG.getTargetExternalSymbol(Sym, PtrVt, 0));
2506 } else if (isPIC) {
2507 // PIC without execute-only: load the symbol's address from the GOT via
2508 // a GOT_PREL constant pool entry consumed by a PICLDR.
2509 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2510 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2511 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2512 *DAG.getContext(), Sym, ARMPCLabelIndex, PCAdj, ARMCP::GOT_PREL,
2513 /*AddCurrentAddress=*/true);
2514 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2515 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516 SDValue GOTOffset = DAG.getLoad(
2517 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2519 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2520 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, GOTOffset, PICLabel);
2521 Callee =
2522 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
2524 } else {
2525 // Neither execute-only nor PIC: load the address from a constant pool.
2526 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2527 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2528 *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2529
2530 // Get the address of the callee into a register
2531 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2532 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2533 Callee = DAG.getLoad(
2534 PtrVt, dl, DAG.getEntryNode(), Addr,
2536 }
2537 }
2538 } else if (isa<GlobalAddressSDNode>(Callee)) {
2539 if (!PreferIndirect) {
2540 isDirect = true;
2541 bool isDef = GVal->isStrongDefinitionForLinker();
2542
2543 // ARM call to a local ARM function is predicable.
2544 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2545 // tBX takes a register source operand.
2546 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2547 assert(TT.isOSBinFormatMachO() && "WrapperPIC use on non-MachO?");
2548 Callee = DAG.getNode(
2549 ARMISD::WrapperPIC, dl, PtrVt,
2550 DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2551 Callee = DAG.getLoad(
2552 PtrVt, dl, DAG.getEntryNode(), Callee,
2556 } else if (Subtarget->isTargetCOFF()) {
2557 assert(Subtarget->isTargetWindows() &&
2558 "Windows is the only supported COFF target");
2559 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2560 if (GVal->hasDLLImportStorageClass())
2561 TargetFlags = ARMII::MO_DLLIMPORT;
2562 else if (!TM.shouldAssumeDSOLocal(GVal))
2563 TargetFlags = ARMII::MO_COFFSTUB;
2564 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2565 TargetFlags);
2566 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2567 Callee =
2568 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2569 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2571 } else {
2572 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2573 }
2574 }
2575 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2576 isDirect = true;
2577 // tBX takes a register source operand.
2578 const char *Sym = S->getSymbol();
2579 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2580 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2581 ARMConstantPoolValue *CPV =
2583 ARMPCLabelIndex, 4);
2584 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2585 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2586 Callee = DAG.getLoad(
2587 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2589 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2590 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2591 } else {
2592 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2593 }
2594 }
2595
2596 if (isCmseNSCall) {
2597 assert(!isARMFunc && !isDirect &&
2598 "Cannot handle call to ARM function or direct call");
2599 if (NumBytes > 0) {
2600 DAG.getContext()->diagnose(
2601 DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2602 "call to non-secure function would require "
2603 "passing arguments on stack",
2604 dl.getDebugLoc()));
2605 }
2606 if (isStructRet) {
2607 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2609 "call to non-secure function would return value through pointer",
2610 dl.getDebugLoc()));
2611 }
2612 }
2613
2614 // FIXME: handle tail calls differently.
2615 unsigned CallOpc;
2616 if (Subtarget->isThumb()) {
2617 if (GuardWithBTI)
2618 CallOpc = ARMISD::t2CALL_BTI;
2619 else if (isCmseNSCall)
2620 CallOpc = ARMISD::tSECALL;
2621 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2622 CallOpc = ARMISD::CALL_NOLINK;
2623 else
2624 CallOpc = ARMISD::CALL;
2625 } else {
2626 if (!isDirect && !Subtarget->hasV5TOps())
2627 CallOpc = ARMISD::CALL_NOLINK;
2628 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2629 // Emit regular call when code size is the priority
2630 !Subtarget->hasMinSize())
2631 // "mov lr, pc; b _foo" to avoid confusing the RSP
2632 CallOpc = ARMISD::CALL_NOLINK;
2633 else
2634 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2635 }
2636
2637 // We don't usually want to end the call-sequence here because we would tidy
2638 // the frame up *after* the call, however in the ABI-changing tail-call case
2639 // we've carefully laid out the parameters so that when sp is reset they'll be
2640 // in the correct location.
2641 if (isTailCall && !isSibCall) {
2642 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2643 InGlue = Chain.getValue(1);
2644 }
2645
2646 std::vector<SDValue> Ops;
2647 Ops.push_back(Chain);
2648 Ops.push_back(Callee);
2649
2650 if (isTailCall) {
2651 Ops.push_back(DAG.getSignedTargetConstant(SPDiff, dl, MVT::i32));
2652 }
2653
2654 // Add argument registers to the end of the list so that they are known live
2655 // into the call.
2656 for (const auto &[Reg, N] : RegsToPass)
2657 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2658
2659 // Add a register mask operand representing the call-preserved registers.
2660 const uint32_t *Mask;
2661 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2662 if (isThisReturn) {
2663 // For 'this' returns, use the R0-preserving mask if applicable
2664 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2665 if (!Mask) {
2666 // Set isThisReturn to false if the calling convention is not one that
2667 // allows 'returned' to be modeled in this way, so LowerCallResult does
2668 // not try to pass 'this' straight through
2669 isThisReturn = false;
2670 Mask = ARI->getCallPreservedMask(MF, CallConv);
2671 }
2672 } else
2673 Mask = ARI->getCallPreservedMask(MF, CallConv);
2674
2675 assert(Mask && "Missing call preserved mask for calling convention");
2676 Ops.push_back(DAG.getRegisterMask(Mask));
2677
2678 if (InGlue.getNode())
2679 Ops.push_back(InGlue);
2680
2681 if (isTailCall) {
2683 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, MVT::Other, Ops);
2684 if (CLI.CFIType)
2685 Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2686 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2687 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2688 return Ret;
2689 }
2690
2691 // Returns a chain and a flag for retval copy to use.
2692 Chain = DAG.getNode(CallOpc, dl, {MVT::Other, MVT::Glue}, Ops);
2693 if (CLI.CFIType)
2694 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2695 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2696 InGlue = Chain.getValue(1);
2697 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2698
2699 // If we're guaranteeing tail-calls will be honoured, the callee must
2700 // pop its own argument stack on return. But this call is *not* a tail call so
2701 // we need to undo that after it returns to restore the status-quo.
2702 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2703 uint64_t CalleePopBytes =
2704 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1U;
2705
2706 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
2707 if (!Ins.empty())
2708 InGlue = Chain.getValue(1);
2709
2710 // Handle result values, copying them out of physregs into vregs that we
2711 // return.
2712 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2713 InVals, isThisReturn,
2714 isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
2715}
2716
2717/// HandleByVal - Every parameter *after* a byval parameter is passed
2718/// on the stack. Remember the next parameter register to allocate,
2719/// and then confiscate the rest of the parameter registers to insure
2720/// this.
2721void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2722 Align Alignment) const {
2723 // Byval (as with any stack) slots are always at least 4 byte aligned.
2724 Alignment = std::max(Alignment, Align(4));
2725
2726 MCRegister Reg = State->AllocateReg(GPRArgRegs);
2727 if (!Reg)
2728 return;
2729
2730 unsigned AlignInRegs = Alignment.value() / 4;
2731 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2732 for (unsigned i = 0; i < Waste; ++i)
2733 Reg = State->AllocateReg(GPRArgRegs);
2734
2735 if (!Reg)
2736 return;
2737
2738 unsigned Excess = 4 * (ARM::R4 - Reg);
2739
2740 // Special case when NSAA != SP and parameter size greater than size of
2741 // all remained GPR regs. In that case we can't split parameter, we must
2742 // send it to stack. We also must set NCRN to R4, so waste all
2743 // remained registers.
2744 const unsigned NSAAOffset = State->getStackSize();
2745 if (NSAAOffset != 0 && Size > Excess) {
2746 while (State->AllocateReg(GPRArgRegs))
2747 ;
2748 return;
2749 }
2750
2751 // First register for byval parameter is the first register that wasn't
2752 // allocated before this method call, so it would be "reg".
2753 // If parameter is small enough to be saved in range [reg, r4), then
2754 // the end (first after last) register would be reg + param-size-in-regs,
2755 // else parameter would be splitted between registers and stack,
2756 // end register would be r4 in this case.
2757 unsigned ByValRegBegin = Reg;
2758 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2759 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2760 // Note, first register is allocated in the beginning of function already,
2761 // allocate remained amount of registers we need.
2762 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2763 State->AllocateReg(GPRArgRegs);
2764 // A byval parameter that is split between registers and memory needs its
2765 // size truncated here.
2766 // In the case where the entire structure fits in registers, we set the
2767 // size in memory to zero.
2768 Size = std::max<int>(Size - Excess, 0);
2769}
2770
2771/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2772/// for tail call optimization. Targets which want to do tail call
2773/// optimization should implement this function. Note that this function also
2774/// processes musttail calls, so when this function returns false on a valid
2775/// musttail call, a fatal backend error occurs.
2776bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2778 SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
2779 CallingConv::ID CalleeCC = CLI.CallConv;
2780 SDValue Callee = CLI.Callee;
2781 bool isVarArg = CLI.IsVarArg;
2782 const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2783 const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2784 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2785 const SelectionDAG &DAG = CLI.DAG;
2787 const Function &CallerF = MF.getFunction();
2788 CallingConv::ID CallerCC = CallerF.getCallingConv();
2789
2790 assert(Subtarget->supportsTailCall());
2791
2792 // Indirect tail-calls require a register to hold the target address. That
2793 // register must be:
2794 // * Allocatable (i.e. r0-r7 if the target is Thumb1).
2795 // * Not callee-saved, so must be one of r0-r3 or r12.
2796 // * Not used to hold an argument to the tail-called function, which might be
2797 // in r0-r3.
2798 // * Not used to hold the return address authentication code, which is in r12
2799 // if enabled.
2800 // Sometimes, no register matches all of these conditions, so we can't do a
2801 // tail-call.
2802 if (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect) {
2803 SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
2804 ARM::R3};
2805 if (!(Subtarget->isThumb1Only() ||
2806 MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true)))
2807 AddressRegisters.insert(ARM::R12);
2808 for (const CCValAssign &AL : ArgLocs)
2809 if (AL.isRegLoc())
2810 AddressRegisters.erase(AL.getLocReg());
2811 if (AddressRegisters.empty()) {
2812 LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
2813 return false;
2814 }
2815 }
2816
2817 // Look for obvious safe cases to perform tail call optimization that do not
2818 // require ABI changes. This is what gcc calls sibcall.
2819
2820 // Exception-handling functions need a special set of instructions to indicate
2821 // a return to the hardware. Tail-calling another function would probably
2822 // break this.
2823 if (CallerF.hasFnAttribute("interrupt")) {
2824 LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
2825 return false;
2826 }
2827
2828 if (canGuaranteeTCO(CalleeCC,
2829 getTargetMachine().Options.GuaranteedTailCallOpt)) {
2830 LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
2831 << " (guaranteed tail-call CC)\n");
2832 return CalleeCC == CallerCC;
2833 }
2834
2835 // Also avoid sibcall optimization if either caller or callee uses struct
2836 // return semantics.
2837 bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2838 bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
2839 if (isCalleeStructRet != isCallerStructRet) {
2840 LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
2841 return false;
2842 }
2843
2844 // Externally-defined functions with weak linkage should not be
2845 // tail-called on ARM when the OS does not support dynamic
2846 // pre-emption of symbols, as the AAELF spec requires normal calls
2847 // to undefined weak functions to be replaced with a NOP or jump to the
2848 // next instruction. The behaviour of branch instructions in this
2849 // situation (as used for tail calls) is implementation-defined, so we
2850 // cannot rely on the linker replacing the tail call with a return.
2851 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2852 const GlobalValue *GV = G->getGlobal();
2853 const Triple &TT = GV->getParent()->getTargetTriple();
2854 if (GV->hasExternalWeakLinkage() &&
2855 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
2856 TT.isOSBinFormatMachO())) {
2857 LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
2858 return false;
2859 }
2860 }
2861
2862 // Check that the call results are passed in the same way.
2863 LLVMContext &C = *DAG.getContext();
2865 getEffectiveCallingConv(CalleeCC, isVarArg),
2866 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2867 CCAssignFnForReturn(CalleeCC, isVarArg),
2868 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) {
2869 LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
2870 return false;
2871 }
2872 // The callee has to preserve all registers the caller needs to preserve.
2873 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2874 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2875 if (CalleeCC != CallerCC) {
2876 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2877 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) {
2878 LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
2879 return false;
2880 }
2881 }
2882
2883 // If Caller's vararg argument has been split between registers and stack, do
2884 // not perform tail call, since part of the argument is in caller's local
2885 // frame.
2886 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2887 if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
2888 LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
2889 return false;
2890 }
2891
2892 // If the callee takes no arguments then go on to check the results of the
2893 // call.
2894 const MachineRegisterInfo &MRI = MF.getRegInfo();
2895 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) {
2896 LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
2897 return false;
2898 }
2899
2900 // If the stack arguments for this call do not fit into our own save area then
2901 // the call cannot be made tail.
2902 if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
2903 return false;
2904
2905 LLVM_DEBUG(dbgs() << "true\n");
2906 return true;
2907}
2908
2909bool
2910ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2911 MachineFunction &MF, bool isVarArg,
2913 LLVMContext &Context, const Type *RetTy) const {
2915 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2916 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2917}
2918
2920 const SDLoc &DL, SelectionDAG &DAG) {
2921 const MachineFunction &MF = DAG.getMachineFunction();
2922 const Function &F = MF.getFunction();
2923
2924 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2925
2926 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2927 // version of the "preferred return address". These offsets affect the return
2928 // instruction if this is a return from PL1 without hypervisor extensions.
2929 // IRQ/FIQ: +4 "subs pc, lr, #4"
2930 // SWI: 0 "subs pc, lr, #0"
2931 // ABORT: +4 "subs pc, lr, #4"
2932 // UNDEF: +4/+2 "subs pc, lr, #0"
2933 // UNDEF varies depending on where the exception came from ARM or Thumb
2934 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2935
2936 int64_t LROffset;
2937 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2938 IntKind == "ABORT")
2939 LROffset = 4;
2940 else if (IntKind == "SWI" || IntKind == "UNDEF")
2941 LROffset = 0;
2942 else
2943 report_fatal_error("Unsupported interrupt attribute. If present, value "
2944 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2945
2946 RetOps.insert(RetOps.begin() + 1,
2947 DAG.getConstant(LROffset, DL, MVT::i32, false));
2948
2949 return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
2950}
2951
2952SDValue
2953ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2954 bool isVarArg,
2956 const SmallVectorImpl<SDValue> &OutVals,
2957 const SDLoc &dl, SelectionDAG &DAG) const {
2958 // CCValAssign - represent the assignment of the return value to a location.
2960
2961 // CCState - Info about the registers and stack slots.
2962 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2963 *DAG.getContext());
2964
2965 // Analyze outgoing return values.
2966 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2967
2968 SDValue Glue;
2970 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2971 bool isLittleEndian = Subtarget->isLittle();
2972
2974 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2975 AFI->setReturnRegsCount(RVLocs.size());
2976
2977 // Report error if cmse entry function returns structure through first ptr arg.
2978 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2979 // Note: using an empty SDLoc(), as the first line of the function is a
2980 // better place to report than the last line.
2981 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2983 "secure entry function would return value through pointer",
2984 SDLoc().getDebugLoc()));
2985 }
2986
2987 // Copy the result values into the output registers.
2988 for (unsigned i = 0, realRVLocIdx = 0;
2989 i != RVLocs.size();
2990 ++i, ++realRVLocIdx) {
2991 CCValAssign &VA = RVLocs[i];
2992 assert(VA.isRegLoc() && "Can only return in registers!");
2993
2994 SDValue Arg = OutVals[realRVLocIdx];
2995 bool ReturnF16 = false;
2996
2997 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2998 // Half-precision return values can be returned like this:
2999 //
3000 // t11 f16 = fadd ...
3001 // t12: i16 = bitcast t11
3002 // t13: i32 = zero_extend t12
3003 // t14: f32 = bitcast t13 <~~~~~~~ Arg
3004 //
3005 // to avoid code generation for bitcasts, we simply set Arg to the node
3006 // that produces the f16 value, t11 in this case.
3007 //
3008 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3009 SDValue ZE = Arg.getOperand(0);
3010 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3011 SDValue BC = ZE.getOperand(0);
3012 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3013 Arg = BC.getOperand(0);
3014 ReturnF16 = true;
3015 }
3016 }
3017 }
3018 }
3019
3020 switch (VA.getLocInfo()) {
3021 default: llvm_unreachable("Unknown loc info!");
3022 case CCValAssign::Full: break;
3023 case CCValAssign::BCvt:
3024 if (!ReturnF16)
3025 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3026 break;
3027 }
3028
3029 // Mask f16 arguments if this is a CMSE nonsecure entry.
3030 auto RetVT = Outs[realRVLocIdx].ArgVT;
3031 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3032 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3033 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3034 } else {
3035 auto LocBits = VA.getLocVT().getSizeInBits();
3036 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3037 SDValue Mask =
3038 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3039 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3040 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3041 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3042 }
3043 }
3044
3045 if (VA.needsCustom() &&
3046 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3047 if (VA.getLocVT() == MVT::v2f64) {
3048 // Extract the first half and return it in two registers.
3049 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3050 DAG.getConstant(0, dl, MVT::i32));
3051 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3052 DAG.getVTList(MVT::i32, MVT::i32), Half);
3053
3054 Chain =
3055 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3056 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3057 Glue = Chain.getValue(1);
3058 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3059 VA = RVLocs[++i]; // skip ahead to next loc
3060 Chain =
3061 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3062 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3063 Glue = Chain.getValue(1);
3064 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3065 VA = RVLocs[++i]; // skip ahead to next loc
3066
3067 // Extract the 2nd half and fall through to handle it as an f64 value.
3068 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3069 DAG.getConstant(1, dl, MVT::i32));
3070 }
3071 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3072 // available.
3073 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3074 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3075 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3076 fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3077 Glue = Chain.getValue(1);
3078 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3079 VA = RVLocs[++i]; // skip ahead to next loc
3080 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3081 fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3082 } else
3083 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3084
3085 // Guarantee that all emitted copies are
3086 // stuck together, avoiding something bad.
3087 Glue = Chain.getValue(1);
3088 RetOps.push_back(DAG.getRegister(
3089 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3090 }
3091 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3092 const MCPhysReg *I =
3093 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3094 if (I) {
3095 for (; *I; ++I) {
3096 if (ARM::GPRRegClass.contains(*I))
3097 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3098 else if (ARM::DPRRegClass.contains(*I))
3100 else
3101 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3102 }
3103 }
3104
3105 // Update chain and glue.
3106 RetOps[0] = Chain;
3107 if (Glue.getNode())
3108 RetOps.push_back(Glue);
3109
3110 // CPUs which aren't M-class use a special sequence to return from
3111 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3112 // though we use "subs pc, lr, #N").
3113 //
3114 // M-class CPUs actually use a normal return sequence with a special
3115 // (hardware-provided) value in LR, so the normal code path works.
3116 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3117 !Subtarget->isMClass()) {
3118 if (Subtarget->isThumb1Only())
3119 report_fatal_error("interrupt attribute is not supported in Thumb1");
3120 return LowerInterruptReturn(RetOps, dl, DAG);
3121 }
3122
3123 unsigned RetNode =
3124 AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE : ARMISD::RET_GLUE;
3125 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3126}
3127
3128bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3129 if (N->getNumValues() != 1)
3130 return false;
3131 if (!N->hasNUsesOfValue(1, 0))
3132 return false;
3133
3134 SDValue TCChain = Chain;
3135 SDNode *Copy = *N->user_begin();
3136 if (Copy->getOpcode() == ISD::CopyToReg) {
3137 // If the copy has a glue operand, we conservatively assume it isn't safe to
3138 // perform a tail call.
3139 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3140 return false;
3141 TCChain = Copy->getOperand(0);
3142 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3143 SDNode *VMov = Copy;
3144 // f64 returned in a pair of GPRs.
3145 SmallPtrSet<SDNode*, 2> Copies;
3146 for (SDNode *U : VMov->users()) {
3147 if (U->getOpcode() != ISD::CopyToReg)
3148 return false;
3149 Copies.insert(U);
3150 }
3151 if (Copies.size() > 2)
3152 return false;
3153
3154 for (SDNode *U : VMov->users()) {
3155 SDValue UseChain = U->getOperand(0);
3156 if (Copies.count(UseChain.getNode()))
3157 // Second CopyToReg
3158 Copy = U;
3159 else {
3160 // We are at the top of this chain.
3161 // If the copy has a glue operand, we conservatively assume it
3162 // isn't safe to perform a tail call.
3163 if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3164 return false;
3165 // First CopyToReg
3166 TCChain = UseChain;
3167 }
3168 }
3169 } else if (Copy->getOpcode() == ISD::BITCAST) {
3170 // f32 returned in a single GPR.
3171 if (!Copy->hasOneUse())
3172 return false;
3173 Copy = *Copy->user_begin();
3174 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3175 return false;
3176 // If the copy has a glue operand, we conservatively assume it isn't safe to
3177 // perform a tail call.
3178 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3179 return false;
3180 TCChain = Copy->getOperand(0);
3181 } else {
3182 return false;
3183 }
3184
3185 bool HasRet = false;
3186 for (const SDNode *U : Copy->users()) {
3187 if (U->getOpcode() != ARMISD::RET_GLUE &&
3188 U->getOpcode() != ARMISD::INTRET_GLUE)
3189 return false;
3190 HasRet = true;
3191 }
3192
3193 if (!HasRet)
3194 return false;
3195
3196 Chain = TCChain;
3197 return true;
3198}
3199
3200bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3201 if (!Subtarget->supportsTailCall())
3202 return false;
3203
3204 if (!CI->isTailCall())
3205 return false;
3206
3207 return true;
3208}
3209
3210// Trying to write a 64 bit value so need to split into two 32 bit values first,
3211// and pass the lower and high parts through.
3213 SDLoc DL(Op);
3214 SDValue WriteValue = Op->getOperand(2);
3215
3216 // This function is only supposed to be called for i64 type argument.
3217 assert(WriteValue.getValueType() == MVT::i64
3218 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3219
3220 SDValue Lo, Hi;
3221 std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3222 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3223 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3224}
3225
3226// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3227// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3228// one of the above mentioned nodes. It has to be wrapped because otherwise
3229// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3230// be used to form addressing mode. These wrapped nodes will be selected
3231// into MOVi.
3232SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3233 SelectionDAG &DAG) const {
3234 EVT PtrVT = Op.getValueType();
3235 // FIXME there is no actual debug info here
3236 SDLoc dl(Op);
3237 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3238 SDValue Res;
3239
3240 // When generating execute-only code Constant Pools must be promoted to the
3241 // global data section. It's a bit ugly that we can't share them across basic
3242 // blocks, but this way we guarantee that execute-only behaves correct with
3243 // position-independent addressing modes.
3244 if (Subtarget->genExecuteOnly()) {
3245 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3246 auto *T = CP->getType();
3247 auto C = const_cast<Constant*>(CP->getConstVal());
3248 auto M = DAG.getMachineFunction().getFunction().getParent();
3249 auto GV = new GlobalVariable(
3250 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3251 Twine(DAG.getDataLayout().getInternalSymbolPrefix()) + "CP" +
3252 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3253 Twine(AFI->createPICLabelUId()));
3254 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3255 return LowerGlobalAddress(GA, DAG);
3256 }
3257
3258 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3259 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3260 Align CPAlign = CP->getAlign();
3261 if (Subtarget->isThumb1Only())
3262 CPAlign = std::max(CPAlign, Align(4));
3264 Res =
3265 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3266 else
3267 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3268 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3269}
3270
3272 // If we don't have a 32-bit pc-relative branch instruction then the jump
3273 // table consists of block addresses. Usually this is inline, but for
3274 // execute-only it must be placed out-of-line.
3275 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3278}
3279
3280SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3281 SelectionDAG &DAG) const {
3284 unsigned ARMPCLabelIndex = 0;
3285 SDLoc DL(Op);
3286 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3287 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3288 SDValue CPAddr;
3289 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3290 if (!IsPositionIndependent) {
3291 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3292 } else {
3293 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3294 ARMPCLabelIndex = AFI->createPICLabelUId();
3296 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3297 ARMCP::CPBlockAddress, PCAdj);
3298 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3299 }
3300 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3301 SDValue Result = DAG.getLoad(
3302 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3304 if (!IsPositionIndependent)
3305 return Result;
3306 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3307 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3308}
3309
3310/// Convert a TLS address reference into the correct sequence of loads
3311/// and calls to compute the variable's address for Darwin, and return an
3312/// SDValue containing the final node.
3313
3314/// Darwin only has one TLS scheme which must be capable of dealing with the
3315/// fully general situation, in the worst case. This means:
3316/// + "extern __thread" declaration.
3317/// + Defined in a possibly unknown dynamic library.
3318///
3319/// The general system is that each __thread variable has a [3 x i32] descriptor
3320/// which contains information used by the runtime to calculate the address. The
3321/// only part of this the compiler needs to know about is the first word, which
3322/// contains a function pointer that must be called with the address of the
3323/// entire descriptor in "r0".
3324///
3325/// Since this descriptor may be in a different unit, in general access must
3326/// proceed along the usual ARM rules. A common sequence to produce is:
3327///
3328/// movw rT1, :lower16:_var$non_lazy_ptr
3329/// movt rT1, :upper16:_var$non_lazy_ptr
3330/// ldr r0, [rT1]
3331/// ldr rT2, [r0]
3332/// blx rT2
3333/// [...address now in r0...]
3334SDValue
3335ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3336 SelectionDAG &DAG) const {
3337 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3338 "This function expects a Darwin target");
3339 SDLoc DL(Op);
3340
3341 // First step is to get the address of the actua global symbol. This is where
3342 // the TLS descriptor lives.
3343 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3344
3345 // The first entry in the descriptor is a function pointer that we must call
3346 // to obtain the address of the variable.
3347 SDValue Chain = DAG.getEntryNode();
3348 SDValue FuncTLVGet = DAG.getLoad(
3349 MVT::i32, DL, Chain, DescAddr,
3353 Chain = FuncTLVGet.getValue(1);
3354
3356 MachineFrameInfo &MFI = F.getFrameInfo();
3357 MFI.setAdjustsStack(true);
3358
3359 // TLS calls preserve all registers except those that absolutely must be
3360 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3361 // silly).
3362 auto TRI =
3364 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3365 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3366
3367 // Finally, we can make the call. This is just a degenerate version of a
3368 // normal AArch64 call node: r0 takes the address of the descriptor, and
3369 // returns the address of the variable in this thread.
3370 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3371 Chain =
3372 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3373 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3374 DAG.getRegisterMask(Mask), Chain.getValue(1));
3375 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3376}
3377
3378SDValue
3379ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3380 SelectionDAG &DAG) const {
3381 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3382 "Windows specific TLS lowering");
3383
3384 SDValue Chain = DAG.getEntryNode();
3385 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3386 SDLoc DL(Op);
3387
3388 // Load the current TEB (thread environment block)
3389 SDValue Ops[] = {Chain,
3390 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3391 DAG.getTargetConstant(15, DL, MVT::i32),
3392 DAG.getTargetConstant(0, DL, MVT::i32),
3393 DAG.getTargetConstant(13, DL, MVT::i32),
3394 DAG.getTargetConstant(0, DL, MVT::i32),
3395 DAG.getTargetConstant(2, DL, MVT::i32)};
3396 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3397 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3398
3399 SDValue TEB = CurrentTEB.getValue(0);
3400 Chain = CurrentTEB.getValue(1);
3401
3402 // Load the ThreadLocalStoragePointer from the TEB
3403 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3404 SDValue TLSArray =
3405 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3406 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3407
3408 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3409 // offset into the TLSArray.
3410
3411 // Load the TLS index from the C runtime
3412 SDValue TLSIndex =
3413 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3414 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3415 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3416
3417 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3418 DAG.getConstant(2, DL, MVT::i32));
3419 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3420 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3421 MachinePointerInfo());
3422
3423 // Get the offset of the start of the .tls section (section base)
3424 const auto *GA = cast<GlobalAddressSDNode>(Op);
3425 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3426 SDValue Offset = DAG.getLoad(
3427 PtrVT, DL, Chain,
3428 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3429 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3431
3432 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3433}
3434
3435// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3436SDValue
3437ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3438 SelectionDAG &DAG) const {
3439 SDLoc dl(GA);
3440 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3441 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3443 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3444 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3445 ARMConstantPoolValue *CPV =
3446 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3447 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3448 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3449 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3450 Argument = DAG.getLoad(
3451 PtrVT, dl, DAG.getEntryNode(), Argument,
3453 SDValue Chain = Argument.getValue(1);
3454
3455 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3456 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3457
3458 // call __tls_get_addr.
3460 Args.emplace_back(Argument, Type::getInt32Ty(*DAG.getContext()));
3461
3462 // FIXME: is there useful debug info available here?
3463 TargetLowering::CallLoweringInfo CLI(DAG);
3464 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3466 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3467
3468 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3469 return CallResult.first;
3470}
3471
3472// Lower ISD::GlobalTLSAddress using the "initial exec" or
3473// "local exec" model.
3474SDValue
3475ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3476 SelectionDAG &DAG,
3477 TLSModel::Model model) const {
3478 const GlobalValue *GV = GA->getGlobal();
3479 SDLoc dl(GA);
3481 SDValue Chain = DAG.getEntryNode();
3482 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3483 // Get the Thread Pointer
3484 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3485
3486 if (model == TLSModel::InitialExec) {
3488 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3489 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3490 // Initial exec model.
3491 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3492 ARMConstantPoolValue *CPV =
3493 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3495 true);
3496 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3497 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3498 Offset = DAG.getLoad(
3499 PtrVT, dl, Chain, Offset,
3501 Chain = Offset.getValue(1);
3502
3503 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3504 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3505
3506 Offset = DAG.getLoad(
3507 PtrVT, dl, Chain, Offset,
3509 } else {
3510 // local exec model
3511 assert(model == TLSModel::LocalExec);
3512 ARMConstantPoolValue *CPV =
3514 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3515 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3516 Offset = DAG.getLoad(
3517 PtrVT, dl, Chain, Offset,
3519 }
3520
3521 // The address of the thread local variable is the add of the thread
3522 // pointer with the offset of the variable.
3523 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3524}
3525
3526SDValue
3527ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3528 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3529 if (DAG.getTarget().useEmulatedTLS())
3530 return LowerToTLSEmulatedModel(GA, DAG);
3531
3532 const Triple &TT = getTargetMachine().getTargetTriple();
3533 if (TT.isOSDarwin())
3534 return LowerGlobalTLSAddressDarwin(Op, DAG);
3535
3536 if (TT.isOSWindows())
3537 return LowerGlobalTLSAddressWindows(Op, DAG);
3538
3539 // TODO: implement the "local dynamic" model
3540 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3542
3543 switch (model) {
3546 return LowerToTLSGeneralDynamicModel(GA, DAG);
3549 return LowerToTLSExecModels(GA, DAG, model);
3550 }
3551 llvm_unreachable("bogus TLS model");
3552}
3553
3554/// Return true if all users of V are within function F, looking through
3555/// ConstantExprs.
3556static bool allUsersAreInFunction(const Value *V, const Function *F) {
3557 SmallVector<const User*,4> Worklist(V->users());
3558 while (!Worklist.empty()) {
3559 auto *U = Worklist.pop_back_val();
3560 if (isa<ConstantExpr>(U)) {
3561 append_range(Worklist, U->users());
3562 continue;
3563 }
3564
3565 auto *I = dyn_cast<Instruction>(U);
3566 if (!I || I->getParent()->getParent() != F)
3567 return false;
3568 }
3569 return true;
3570}
3571
3573 const GlobalValue *GV, SelectionDAG &DAG,
3574 EVT PtrVT, const SDLoc &dl) {
3575 // If we're creating a pool entry for a constant global with unnamed address,
3576 // and the global is small enough, we can emit it inline into the constant pool
3577 // to save ourselves an indirection.
3578 //
3579 // This is a win if the constant is only used in one function (so it doesn't
3580 // need to be duplicated) or duplicating the constant wouldn't increase code
3581 // size (implying the constant is no larger than 4 bytes).
3582 const Function &F = DAG.getMachineFunction().getFunction();
3583
3584 // We rely on this decision to inline being idempotent and unrelated to the
3585 // use-site. We know that if we inline a variable at one use site, we'll
3586 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3587 // doesn't know about this optimization, so bail out if it's enabled else
3588 // we could decide to inline here (and thus never emit the GV) but require
3589 // the GV from fast-isel generated code.
3592 return SDValue();
3593
3594 auto *GVar = dyn_cast<GlobalVariable>(GV);
3595 if (!GVar || !GVar->hasInitializer() ||
3596 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3597 !GVar->hasLocalLinkage())
3598 return SDValue();
3599
3600 // If we inline a value that contains relocations, we move the relocations
3601 // from .data to .text. This is not allowed in position-independent code.
3602 auto *Init = GVar->getInitializer();
3603 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3604 Init->needsDynamicRelocation())
3605 return SDValue();
3606
3607 // The constant islands pass can only really deal with alignment requests
3608 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3609 // any type wanting greater alignment requirements than 4 bytes. We also
3610 // can only promote constants that are multiples of 4 bytes in size or
3611 // are paddable to a multiple of 4. Currently we only try and pad constants
3612 // that are strings for simplicity.
3613 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3614 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3615 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3616 unsigned RequiredPadding = 4 - (Size % 4);
3617 bool PaddingPossible =
3618 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3619 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3620 Size == 0)
3621 return SDValue();
3622
3623 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3625 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3626
3627 // We can't bloat the constant pool too much, else the ConstantIslands pass
3628 // may fail to converge. If we haven't promoted this global yet (it may have
3629 // multiple uses), and promoting it would increase the constant pool size (Sz
3630 // > 4), ensure we have space to do so up to MaxTotal.
3631 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3632 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3634 return SDValue();
3635
3636 // This is only valid if all users are in a single function; we can't clone
3637 // the constant in general. The LLVM IR unnamed_addr allows merging
3638 // constants, but not cloning them.
3639 //
3640 // We could potentially allow cloning if we could prove all uses of the
3641 // constant in the current function don't care about the address, like
3642 // printf format strings. But that isn't implemented for now.
3643 if (!allUsersAreInFunction(GVar, &F))
3644 return SDValue();
3645
3646 // We're going to inline this global. Pad it out if needed.
3647 if (RequiredPadding != 4) {
3648 StringRef S = CDAInit->getAsString();
3649
3651 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3652 while (RequiredPadding--)
3653 V.push_back(0);
3655 }
3656
3657 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3658 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3659 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3662 PaddedSize - 4);
3663 }
3664 ++NumConstpoolPromoted;
3665 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3666}
3667
3669 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3670 if (!(GV = GA->getAliaseeObject()))
3671 return false;
3672 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3673 return V->isConstant();
3674 return isa<Function>(GV);
3675}
3676
3677SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3678 SelectionDAG &DAG) const {
3679 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3680 default: llvm_unreachable("unknown object format");
3681 case Triple::COFF:
3682 return LowerGlobalAddressWindows(Op, DAG);
3683 case Triple::ELF:
3684 return LowerGlobalAddressELF(Op, DAG);
3685 case Triple::MachO:
3686 return LowerGlobalAddressDarwin(Op, DAG);
3687 }
3688}
3689
3690SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3691 SelectionDAG &DAG) const {
3692 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3693 SDLoc dl(Op);
3694 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3695 bool IsRO = isReadOnly(GV);
3696
3697 // promoteToConstantPool only if not generating XO text section
3698 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3699 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3700 return V;
3701
3702 if (isPositionIndependent()) {
3704 GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3705 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3706 if (!GV->isDSOLocal())
3707 Result =
3708 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3710 return Result;
3711 } else if (Subtarget->isROPI() && IsRO) {
3712 // PC-relative.
3713 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3714 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3715 return Result;
3716 } else if (Subtarget->isRWPI() && !IsRO) {
3717 // SB-relative.
3718 SDValue RelAddr;
3719 if (Subtarget->useMovt()) {
3720 ++NumMovwMovt;
3721 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3722 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3723 } else { // use literal pool for address constant
3724 ARMConstantPoolValue *CPV =
3726 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3727 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3728 RelAddr = DAG.getLoad(
3729 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3731 }
3732 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3733 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3734 return Result;
3735 }
3736
3737 // If we have T2 ops, we can materialize the address directly via movt/movw
3738 // pair. This is always cheaper. If need to generate Execute Only code, and we
3739 // only have Thumb1 available, we can't use a constant pool and are forced to
3740 // use immediate relocations.
3741 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3742 if (Subtarget->useMovt())
3743 ++NumMovwMovt;
3744 // FIXME: Once remat is capable of dealing with instructions with register
3745 // operands, expand this into two nodes.
3746 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3747 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3748 } else {
3749 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3750 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3751 return DAG.getLoad(
3752 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3754 }
3755}
3756
3757SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3758 SelectionDAG &DAG) const {
3759 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3760 "ROPI/RWPI not currently supported for Darwin");
3761 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3762 SDLoc dl(Op);
3763 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3764
3765 if (Subtarget->useMovt())
3766 ++NumMovwMovt;
3767
3768 // FIXME: Once remat is capable of dealing with instructions with register
3769 // operands, expand this into multiple nodes
3770 unsigned Wrapper =
3771 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3772
3773 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3774 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3775
3776 if (Subtarget->isGVIndirectSymbol(GV))
3777 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3779 return Result;
3780}
3781
3782SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3783 SelectionDAG &DAG) const {
3784 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3785 "non-Windows COFF is not supported");
3786 assert(Subtarget->useMovt() &&
3787 "Windows on ARM expects to use movw/movt");
3788 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3789 "ROPI/RWPI not currently supported for Windows");
3790
3791 const TargetMachine &TM = getTargetMachine();
3792 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3793 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3794 if (GV->hasDLLImportStorageClass())
3795 TargetFlags = ARMII::MO_DLLIMPORT;
3796 else if (!TM.shouldAssumeDSOLocal(GV))
3797 TargetFlags = ARMII::MO_COFFSTUB;
3798 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3800 SDLoc DL(Op);
3801
3802 ++NumMovwMovt;
3803
3804 // FIXME: Once remat is capable of dealing with instructions with register
3805 // operands, expand this into two nodes.
3806 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3807 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3808 TargetFlags));
3809 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3810 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3812 return Result;
3813}
3814
3815SDValue
3816ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3817 SDLoc dl(Op);
3818 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3819 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3820 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3821 Op.getOperand(1), Val);
3822}
3823
3824SDValue
3825ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3826 SDLoc dl(Op);
3827 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3828 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3829}
3830
3831SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3832 SelectionDAG &DAG) const {
3833 SDLoc dl(Op);
3834 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3835 Op.getOperand(0));
3836}
3837
3838SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3839 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3840 unsigned IntNo =
3841 Op.getConstantOperandVal(Op.getOperand(0).getValueType() == MVT::Other);
3842 switch (IntNo) {
3843 default:
3844 return SDValue(); // Don't custom lower most intrinsics.
3845 case Intrinsic::arm_gnu_eabi_mcount: {
3847 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3848 SDLoc dl(Op);
3849 SDValue Chain = Op.getOperand(0);
3850 // call "\01__gnu_mcount_nc"
3851 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3852 const uint32_t *Mask =
3854 assert(Mask && "Missing call preserved mask for calling convention");
3855 // Mark LR an implicit live-in.
3856 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3857 SDValue ReturnAddress =
3858 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3859 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3860 SDValue Callee =
3861 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3863 if (Subtarget->isThumb())
3864 return SDValue(
3865 DAG.getMachineNode(
3866 ARM::tBL_PUSHLR, dl, ResultTys,
3867 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3868 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3869 0);
3870 return SDValue(
3871 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3872 {ReturnAddress, Callee, RegisterMask, Chain}),
3873 0);
3874 }
3875 }
3876}
3877
3878SDValue
3879ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3880 const ARMSubtarget *Subtarget) const {
3881 unsigned IntNo = Op.getConstantOperandVal(0);
3882 SDLoc dl(Op);
3883 switch (IntNo) {
3884 default: return SDValue(); // Don't custom lower most intrinsics.
3885 case Intrinsic::localaddress: {
3886 const MachineFunction &MF = DAG.getMachineFunction();
3887 const auto *RegInfo = Subtarget->getRegisterInfo();
3888 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3889 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3890 Op.getSimpleValueType());
3891 }
3892 case Intrinsic::eh_recoverfp: {
3893 SDValue FnOp = Op.getOperand(1);
3894 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3895 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3896 if (!Fn)
3898 "llvm.eh.recoverfp must take a function as the first argument");
3899 const auto *RegInfo = Subtarget->getRegisterInfo();
3900 Register BaseReg = RegInfo->getBaseRegister();
3902 MachineBasicBlock &MBB = *MF.begin();
3903 if (!MBB.isLiveIn(BaseReg))
3904 MBB.addLiveIn(BaseReg);
3905 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3906 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, BaseReg, PtrVT);
3907 }
3908 case Intrinsic::thread_pointer: {
3909 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3910 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3911 }
3912 case Intrinsic::arm_cls: {
3913 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3914 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3915 // instruction.
3916 const SDValue &Operand = Op.getOperand(1);
3917 const EVT VTy = Op.getValueType();
3918 return DAG.getNode(ISD::CTLS, dl, VTy, Operand);
3919 }
3920 case Intrinsic::arm_cls64: {
3921 // arm_cls64 returns i32 but takes i64 input.
3922 // Use ISD::CTLS for i64 and truncate the result.
3923 SDValue CTLS64 = DAG.getNode(ISD::CTLS, dl, MVT::i64, Op.getOperand(1));
3924 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, CTLS64);
3925 }
3926 case Intrinsic::arm_neon_vcls:
3927 case Intrinsic::arm_mve_vcls: {
3928 // Lower vector CLS intrinsics to ISD::CTLS.
3929 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3930 const EVT VTy = Op.getValueType();
3931 return DAG.getNode(ISD::CTLS, dl, VTy, Op.getOperand(1));
3932 }
3933 case Intrinsic::eh_sjlj_lsda: {
3935 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3936 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3937 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3938 SDValue CPAddr;
3939 bool IsPositionIndependent = isPositionIndependent();
3940 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3941 ARMConstantPoolValue *CPV =
3942 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3943 ARMCP::CPLSDA, PCAdj);
3944 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3945 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3946 SDValue Result = DAG.getLoad(
3947 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3949
3950 if (IsPositionIndependent) {
3951 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3952 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3953 }
3954 return Result;
3955 }
3956 case Intrinsic::arm_neon_vabs:
3957 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3958 Op.getOperand(1));
3959 case Intrinsic::arm_neon_vabds:
3960 if (Op.getValueType().isInteger())
3961 return DAG.getNode(ISD::ABDS, SDLoc(Op), Op.getValueType(),
3962 Op.getOperand(1), Op.getOperand(2));
3963 return SDValue();
3964 case Intrinsic::arm_neon_vabdu:
3965 return DAG.getNode(ISD::ABDU, SDLoc(Op), Op.getValueType(),
3966 Op.getOperand(1), Op.getOperand(2));
3967 case Intrinsic::arm_neon_vmulls:
3968 case Intrinsic::arm_neon_vmullu: {
3969 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3970 ? ARMISD::VMULLs : ARMISD::VMULLu;
3971 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3972 Op.getOperand(1), Op.getOperand(2));
3973 }
3974 case Intrinsic::arm_neon_vminnm:
3975 case Intrinsic::arm_neon_vmaxnm: {
3976 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3977 ? ISD::FMINNUM : ISD::FMAXNUM;
3978 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3979 Op.getOperand(1), Op.getOperand(2));
3980 }
3981 case Intrinsic::arm_neon_vminu:
3982 case Intrinsic::arm_neon_vmaxu: {
3983 if (Op.getValueType().isFloatingPoint())
3984 return SDValue();
3985 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3986 ? ISD::UMIN : ISD::UMAX;
3987 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3988 Op.getOperand(1), Op.getOperand(2));
3989 }
3990 case Intrinsic::arm_neon_vmins:
3991 case Intrinsic::arm_neon_vmaxs: {
3992 // v{min,max}s is overloaded between signed integers and floats.
3993 if (!Op.getValueType().isFloatingPoint()) {
3994 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3995 ? ISD::SMIN : ISD::SMAX;
3996 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3997 Op.getOperand(1), Op.getOperand(2));
3998 }
3999 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4000 ? ISD::FMINIMUM : ISD::FMAXIMUM;
4001 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4002 Op.getOperand(1), Op.getOperand(2));
4003 }
4004 case Intrinsic::arm_neon_vtbl1:
4005 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4006 Op.getOperand(1), Op.getOperand(2));
4007 case Intrinsic::arm_neon_vtbl2:
4008 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4009 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4010 case Intrinsic::arm_mve_pred_i2v:
4011 case Intrinsic::arm_mve_pred_v2i:
4012 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4013 Op.getOperand(1));
4014 case Intrinsic::arm_mve_vreinterpretq:
4015 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4016 Op.getOperand(1));
4017 case Intrinsic::arm_mve_lsll:
4018 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4019 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4020 case Intrinsic::arm_mve_asrl:
4021 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4022 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4023 case Intrinsic::arm_mve_vsli:
4024 return DAG.getNode(ARMISD::VSLIIMM, SDLoc(Op), Op->getVTList(),
4025 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4026 case Intrinsic::arm_mve_vsri:
4027 return DAG.getNode(ARMISD::VSRIIMM, SDLoc(Op), Op->getVTList(),
4028 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4029 }
4030}
4031
4033 const ARMSubtarget *Subtarget) {
4034 SDLoc dl(Op);
4035 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4036 if (SSID == SyncScope::SingleThread)
4037 return Op;
4038
4039 if (!Subtarget->hasDataBarrier()) {
4040 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4041 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4042 // here.
4043 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4044 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4045 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4046 DAG.getConstant(0, dl, MVT::i32));
4047 }
4048
4049 AtomicOrdering Ord =
4050 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
4052 if (Subtarget->isMClass()) {
4053 // Only a full system barrier exists in the M-class architectures.
4055 } else if (Subtarget->preferISHSTBarriers() &&
4056 Ord == AtomicOrdering::Release) {
4057 // Swift happens to implement ISHST barriers in a way that's compatible with
4058 // Release semantics but weaker than ISH so we'd be fools not to use
4059 // it. Beware: other processors probably don't!
4061 }
4062
4063 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4064 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4065 DAG.getConstant(Domain, dl, MVT::i32));
4066}
4067
4069 const ARMSubtarget *Subtarget) {
4070 // ARM pre v5TE and Thumb1 does not have preload instructions.
4071 if (!(Subtarget->isThumb2() ||
4072 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4073 // Just preserve the chain.
4074 return Op.getOperand(0);
4075
4076 SDLoc dl(Op);
4077 unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4078 if (!isRead &&
4079 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4080 // ARMv7 with MP extension has PLDW.
4081 return Op.getOperand(0);
4082
4083 unsigned isData = Op.getConstantOperandVal(4);
4084 if (Subtarget->isThumb()) {
4085 // Invert the bits.
4086 isRead = ~isRead & 1;
4087 isData = ~isData & 1;
4088 }
4089
4090 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4091 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4092 DAG.getConstant(isData, dl, MVT::i32));
4093}
4094
4097 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4098
4099 // vastart just stores the address of the VarArgsFrameIndex slot into the
4100 // memory location argument.
4101 SDLoc dl(Op);
4103 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4104 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4105 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4106 MachinePointerInfo(SV));
4107}
4108
4109SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4110 CCValAssign &NextVA,
4111 SDValue &Root,
4112 SelectionDAG &DAG,
4113 const SDLoc &dl) const {
4115 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4116
4117 const TargetRegisterClass *RC;
4118 if (AFI->isThumb1OnlyFunction())
4119 RC = &ARM::tGPRRegClass;
4120 else
4121 RC = &ARM::GPRRegClass;
4122
4123 // Transform the arguments stored in physical registers into virtual ones.
4124 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4125 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4126
4127 SDValue ArgValue2;
4128 if (NextVA.isMemLoc()) {
4129 MachineFrameInfo &MFI = MF.getFrameInfo();
4130 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4131
4132 // Create load node to retrieve arguments from the stack.
4133 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4134 ArgValue2 = DAG.getLoad(
4135 MVT::i32, dl, Root, FIN,
4137 } else {
4138 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4139 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4140 }
4141 if (!Subtarget->isLittle())
4142 std::swap (ArgValue, ArgValue2);
4143 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4144}
4145
4146// The remaining GPRs hold either the beginning of variable-argument
4147// data, or the beginning of an aggregate passed by value (usually
4148// byval). Either way, we allocate stack slots adjacent to the data
4149// provided by our caller, and store the unallocated registers there.
4150// If this is a variadic function, the va_list pointer will begin with
4151// these values; otherwise, this reassembles a (byval) structure that
4152// was split between registers and memory.
4153// Return: The frame index registers were stored into.
4154int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4155 const SDLoc &dl, SDValue &Chain,
4156 const Value *OrigArg,
4157 unsigned InRegsParamRecordIdx,
4158 int ArgOffset, unsigned ArgSize) const {
4159 // Currently, two use-cases possible:
4160 // Case #1. Non-var-args function, and we meet first byval parameter.
4161 // Setup first unallocated register as first byval register;
4162 // eat all remained registers
4163 // (these two actions are performed by HandleByVal method).
4164 // Then, here, we initialize stack frame with
4165 // "store-reg" instructions.
4166 // Case #2. Var-args function, that doesn't contain byval parameters.
4167 // The same: eat all remained unallocated registers,
4168 // initialize stack frame.
4169
4171 MachineFrameInfo &MFI = MF.getFrameInfo();
4172 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4173 unsigned RBegin, REnd;
4174 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4175 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4176 } else {
4177 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4178 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4179 REnd = ARM::R4;
4180 }
4181
4182 if (REnd != RBegin)
4183 ArgOffset = -4 * (ARM::R4 - RBegin);
4184
4185 auto PtrVT = getPointerTy(DAG.getDataLayout());
4186 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4187 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4188
4190 const TargetRegisterClass *RC =
4191 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4192
4193 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4194 Register VReg = MF.addLiveIn(Reg, RC);
4195 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4196 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4197 MachinePointerInfo(OrigArg, 4 * i));
4198 MemOps.push_back(Store);
4199 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4200 }
4201
4202 if (!MemOps.empty())
4203 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4204 return FrameIndex;
4205}
4206
4207// Setup stack frame, the va_list pointer will start from.
4208void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4209 const SDLoc &dl, SDValue &Chain,
4210 unsigned ArgOffset,
4211 unsigned TotalArgRegsSaveSize,
4212 bool ForceMutable) const {
4214 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4215
4216 // Try to store any remaining integer argument regs
4217 // to their spots on the stack so that they may be loaded by dereferencing
4218 // the result of va_next.
4219 // If there is no regs to be stored, just point address after last
4220 // argument passed via stack.
4221 int FrameIndex = StoreByValRegs(
4222 CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4223 CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4224 AFI->setVarArgsFrameIndex(FrameIndex);
4225}
4226
4227bool ARMTargetLowering::splitValueIntoRegisterParts(
4228 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4229 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4230 EVT ValueVT = Val.getValueType();
4231 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4232 unsigned ValueBits = ValueVT.getSizeInBits();
4233 unsigned PartBits = PartVT.getSizeInBits();
4234 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4235 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4236 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4237 Parts[0] = Val;
4238 return true;
4239 }
4240 return false;
4241}
4242
4243SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4244 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4245 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4246 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4247 unsigned ValueBits = ValueVT.getSizeInBits();
4248 unsigned PartBits = PartVT.getSizeInBits();
4249 SDValue Val = Parts[0];
4250
4251 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4252 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4253 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4254 return Val;
4255 }
4256 return SDValue();
4257}
4258
4259SDValue ARMTargetLowering::LowerFormalArguments(
4260 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4261 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4262 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4264 MachineFrameInfo &MFI = MF.getFrameInfo();
4265
4266 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4267
4268 // Assign locations to all of the incoming arguments.
4270 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4271 *DAG.getContext());
4272 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4273
4275 unsigned CurArgIdx = 0;
4276
4277 // Initially ArgRegsSaveSize is zero.
4278 // Then we increase this value each time we meet byval parameter.
4279 // We also increase this value in case of varargs function.
4280 AFI->setArgRegsSaveSize(0);
4281
4282 // Calculate the amount of stack space that we need to allocate to store
4283 // byval and variadic arguments that are passed in registers.
4284 // We need to know this before we allocate the first byval or variadic
4285 // argument, as they will be allocated a stack slot below the CFA (Canonical
4286 // Frame Address, the stack pointer at entry to the function).
4287 unsigned ArgRegBegin = ARM::R4;
4288 for (const CCValAssign &VA : ArgLocs) {
4289 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4290 break;
4291
4292 unsigned Index = VA.getValNo();
4293 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4294 if (!Flags.isByVal())
4295 continue;
4296
4297 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4298 unsigned RBegin, REnd;
4299 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4300 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4301
4302 CCInfo.nextInRegsParam();
4303 }
4304 CCInfo.rewindByValRegsInfo();
4305
4306 int lastInsIndex = -1;
4307 if (isVarArg && MFI.hasVAStart()) {
4308 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4309 if (RegIdx != std::size(GPRArgRegs))
4310 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4311 }
4312
4313 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4314 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4315 auto PtrVT = getPointerTy(DAG.getDataLayout());
4316
4317 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4318 CCValAssign &VA = ArgLocs[i];
4319 if (Ins[VA.getValNo()].isOrigArg()) {
4320 std::advance(CurOrigArg,
4321 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4322 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4323 }
4324 // Arguments stored in registers.
4325 if (VA.isRegLoc()) {
4326 EVT RegVT = VA.getLocVT();
4327 SDValue ArgValue;
4328
4329 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4330 // f64 and vector types are split up into multiple registers or
4331 // combinations of registers and stack slots.
4332 SDValue ArgValue1 =
4333 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4334 VA = ArgLocs[++i]; // skip ahead to next loc
4335 SDValue ArgValue2;
4336 if (VA.isMemLoc()) {
4337 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4338 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4339 ArgValue2 = DAG.getLoad(
4340 MVT::f64, dl, Chain, FIN,
4342 } else {
4343 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4344 }
4345 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4346 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4347 ArgValue1, DAG.getIntPtrConstant(0, dl));
4348 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4349 ArgValue2, DAG.getIntPtrConstant(1, dl));
4350 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4351 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4352 } else {
4353 const TargetRegisterClass *RC;
4354
4355 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4356 RC = &ARM::HPRRegClass;
4357 else if (RegVT == MVT::f32)
4358 RC = &ARM::SPRRegClass;
4359 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4360 RegVT == MVT::v4bf16)
4361 RC = &ARM::DPRRegClass;
4362 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4363 RegVT == MVT::v8bf16)
4364 RC = &ARM::QPRRegClass;
4365 else if (RegVT == MVT::i32)
4366 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4367 : &ARM::GPRRegClass;
4368 else
4369 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4370
4371 // Transform the arguments in physical registers into virtual ones.
4372 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4373 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4374
4375 // If this value is passed in r0 and has the returned attribute (e.g.
4376 // C++ 'structors), record this fact for later use.
4377 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4378 AFI->setPreservesR0();
4379 }
4380 }
4381
4382 // If this is an 8 or 16-bit value, it is really passed promoted
4383 // to 32 bits. Insert an assert[sz]ext to capture this, then
4384 // truncate to the right size.
4385 switch (VA.getLocInfo()) {
4386 default: llvm_unreachable("Unknown loc info!");
4387 case CCValAssign::Full: break;
4388 case CCValAssign::BCvt:
4389 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4390 break;
4391 }
4392
4393 // f16 arguments have their size extended to 4 bytes and passed as if they
4394 // had been copied to the LSBs of a 32-bit register.
4395 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4396 if (VA.needsCustom() &&
4397 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4398 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4399
4400 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4401 // less than 32 bits must be sign- or zero-extended in the callee for
4402 // security reasons. Although the ABI mandates an extension done by the
4403 // caller, the latter cannot be trusted to follow the rules of the ABI.
4404 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4405 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4406 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
4407 ArgValue = handleCMSEValue(ArgValue, Arg, DAG, dl);
4408
4409 InVals.push_back(ArgValue);
4410 } else { // VA.isRegLoc()
4411 // Only arguments passed on the stack should make it here.
4412 assert(VA.isMemLoc());
4413 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4414
4415 int index = VA.getValNo();
4416
4417 // Some Ins[] entries become multiple ArgLoc[] entries.
4418 // Process them only once.
4419 if (index != lastInsIndex)
4420 {
4421 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4422 // FIXME: For now, all byval parameter objects are marked mutable.
4423 // This can be changed with more analysis.
4424 // In case of tail call optimization mark all arguments mutable.
4425 // Since they could be overwritten by lowering of arguments in case of
4426 // a tail call.
4427 if (Flags.isByVal()) {
4428 assert(Ins[index].isOrigArg() &&
4429 "Byval arguments cannot be implicit");
4430 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4431
4432 int FrameIndex = StoreByValRegs(
4433 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4434 VA.getLocMemOffset(), Flags.getByValSize());
4435 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4436 CCInfo.nextInRegsParam();
4437 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4438 VA.getValVT() == MVT::bf16)) {
4439 // f16 and bf16 values are passed in the least-significant half of
4440 // a 4 byte stack slot. This is done as-if the extension was done
4441 // in a 32-bit register, so the actual bytes used for the value
4442 // differ between little and big endian.
4443 assert(VA.getLocVT().getSizeInBits() == 32);
4444 unsigned FIOffset = VA.getLocMemOffset();
4445 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits() / 8,
4446 FIOffset, true);
4447
4448 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
4449 if (DAG.getDataLayout().isBigEndian())
4450 Addr = DAG.getObjectPtrOffset(dl, Addr, TypeSize::getFixed(2));
4451
4452 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, Addr,
4454 DAG.getMachineFunction(), FI)));
4455
4456 } else {
4457 unsigned FIOffset = VA.getLocMemOffset();
4458 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4459 FIOffset, true);
4460
4461 // Create load nodes to retrieve arguments from the stack.
4462 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4463 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4465 DAG.getMachineFunction(), FI)));
4466 }
4467 lastInsIndex = index;
4468 }
4469 }
4470 }
4471
4472 // varargs
4473 if (isVarArg && MFI.hasVAStart()) {
4474 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4475 TotalArgRegsSaveSize);
4476 if (AFI->isCmseNSEntryFunction()) {
4477 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4479 "secure entry function must not be variadic", dl.getDebugLoc()));
4480 }
4481 }
4482
4483 // A variadic function that forwards through a musttail call needs its unnamed
4484 // register arguments modelled as live, so the allocator does not use one as
4485 // scratch. This must run after the va_list save area above, which consumes
4486 // the same registers, and is deliberately *not* predicated on hasVAStart():
4487 // a forwarding thunk never calls va_start.
4488 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
4489 // getRemainingRegParmsForType() walks the assign function until an argument
4490 // lands in memory, so the convention must have a stack fallback. GHC and
4491 // the Windows CFGuard check stub assign to registers only and would run off
4492 // the end of their tables; neither supports variadic arguments anyway.
4493 CallingConv::ID EffCC = getEffectiveCallingConv(CallConv, isVarArg);
4494 if (EffCC != CallingConv::GHC && EffCC != CallingConv::CFGuard_Check) {
4495 // Only the core registers can hold an unnamed argument:
4496 // getEffectiveCallingConv() degrades every VFP convention to ARM_AAPCS
4497 // when isVarArg is set.
4498 SmallVector<MVT, 1> RegParmTypes;
4499 RegParmTypes.push_back(MVT::i32);
4500 SmallVectorImpl<ForwardedRegister> &Forwards =
4503 Forwards, RegParmTypes, CCAssignFnForCall(CallConv, isVarArg));
4504 }
4505 }
4506
4507 unsigned StackArgSize = CCInfo.getStackSize();
4508 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4509 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4510 // The only way to guarantee a tail call is if the callee restores its
4511 // argument area, but it must also keep the stack aligned when doing so.
4512 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4513 assert(StackAlign && "data layout string is missing stack alignment");
4514 StackArgSize = alignTo(StackArgSize, *StackAlign);
4515
4516 AFI->setArgumentStackToRestore(StackArgSize);
4517 }
4518 AFI->setArgumentStackSize(StackArgSize);
4519
4520 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4521 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4523 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4524 }
4525
4526 return Chain;
4527}
4528
4529/// isFloatingPointZero - Return true if this is +0.0.
4532 return CFP->getValueAPF().isPosZero();
4533 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4534 // Maybe this has already been legalized into the constant pool?
4535 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4536 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4538 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4539 return CFP->getValueAPF().isPosZero();
4540 }
4541 } else if (Op->getOpcode() == ISD::BITCAST &&
4542 Op->getValueType(0) == MVT::f64) {
4543 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4544 // created by LowerConstantFP().
4545 SDValue BitcastOp = Op->getOperand(0);
4546 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4547 isNullConstant(BitcastOp->getOperand(0)))
4548 return true;
4549 }
4550 return false;
4551}
4552
4554 // 0 - INT_MIN sign wraps, so no signed wrap means cmn is safe.
4555 if (Op->getFlags().hasNoSignedWrap())
4556 return true;
4557
4558 // We can still figure out if the second operand is safe to use
4559 // in a CMN instruction by checking if it is known to be not the minimum
4560 // signed value. If it is not, then we can safely use CMN.
4561 // Note: We can eventually remove this check and simply rely on
4562 // Op->getFlags().hasNoSignedWrap() once SelectionDAG/ISelLowering
4563 // consistently sets them appropriately when making said nodes.
4564
4565 KnownBits KnownSrc = DAG.computeKnownBits(Op.getOperand(1));
4566 return !KnownSrc.getSignedMinValue().isMinSignedValue();
4567}
4568
4570 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
4571 (isIntEqualitySetCC(CC) ||
4572 (isUnsignedIntSetCC(CC) && DAG.isKnownNeverZero(Op.getOperand(1))) ||
4573 (isSignedIntSetCC(CC) && isSafeSignedCMN(Op, DAG)));
4574}
4575
4576/// Returns how profitable it is to fold a comparison's operand's shift and/or
4577/// extension operations into the comparison instruction's second operand
4578/// (so_reg_imm / so_reg_reg for ARM, t2_so_reg for Thumb-2).
4580 // Thumb-1 CMP does not support shifted second operands.
4581 if (ST.isThumb1Only() || !Op.hasOneUse())
4582 return 0;
4583
4584 unsigned Opc = Op.getOpcode();
4585 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) {
4586 if (auto *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
4587 return ShiftAmt->getZExtValue() <= 31 ? 1 : 0;
4588 // Register-controlled shift: only ARM-mode CMP/CMN (so_reg_reg) supports
4589 // this; Thumb-2 t2_so_reg requires an immediate shift amount.
4590 return ST.isThumb() ? 0 : 1;
4591 }
4592
4593 if (Opc == ISD::ROTR) {
4594 // Rotr constants will be normalized via mod 32, or & 31,
4595 // so we do not have to bounds check.
4596 if (isa<ConstantSDNode>(Op.getOperand(1)))
4597 return 1;
4598 return ST.isThumb() ? 0 : 1;
4599 }
4600
4601 return 0;
4602}
4603
4604// Return a cheaper value with the same zero/nonzero result as a low-mask AND.
4606 const SDLoc &DL) {
4607 if (Value.getValueType() != MVT::i32 || Value.getOpcode() != ISD::AND ||
4608 !Value.hasOneUse())
4609 return SDValue();
4610
4611 auto *Mask = dyn_cast<ConstantSDNode>(Value.getOperand(1));
4612 if (!Mask)
4613 return SDValue();
4614 uint32_t MaskValue = Mask->getZExtValue();
4615 // Keep the existing single-bit lowering and UXTB/UXTH for byte/halfword
4616 // masks, and avoid a zero or no-op shift.
4617 if (!isMask_32(MaskValue) || MaskValue == 1 || MaskValue == 0xff ||
4618 MaskValue == 0xffff || MaskValue == ~0U)
4619 return SDValue();
4620
4621 return DAG.getNode(
4622 ISD::SHL, DL, MVT::i32, Value.getOperand(0),
4623 DAG.getConstant(llvm::countl_zero(MaskValue), DL, MVT::i32));
4624}
4625
4626/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4627/// the given operands.
4628SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4629 SDValue &ARMcc, SelectionDAG &DAG,
4630 const SDLoc &dl) const {
4631 // For a zero test, replace a low-mask AND feeding an OR with a shift. ARM
4632 // and Thumb-2 can fold the shift into the OR. Require single uses to avoid
4633 // duplicating live work.
4634 if (!Subtarget->isThumb1Only() && isIntEqualitySetCC(CC) &&
4635 isNullConstant(RHS) && LHS.getValueType() == MVT::i32 &&
4636 LHS.getOpcode() == ISD::OR && LHS.hasOneUse()) {
4637 for (unsigned I = 0; I != 2; ++I) {
4638 if (SDValue Shift =
4639 getShiftedLowMaskZeroTest(LHS.getOperand(I), DAG, dl)) {
4640 LHS = DAG.getNode(ISD::OR, dl, MVT::i32, LHS.getOperand(I ^ 1), Shift);
4641 break;
4642 }
4643 }
4644 }
4645
4646 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4647 unsigned C = RHSC->getZExtValue();
4648 if (!isLegalICmpImmediate((int32_t)C)) {
4649 // Constant does not fit, try adjusting it by one.
4650 switch (CC) {
4651 default: break;
4652 case ISD::SETLT:
4653 case ISD::SETGE:
4654 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4655 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4656 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4657 }
4658 break;
4659 case ISD::SETULT:
4660 case ISD::SETUGE:
4661 if (C != 0 && isLegalICmpImmediate(C-1)) {
4662 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4663 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4664 }
4665 break;
4666 case ISD::SETLE:
4667 case ISD::SETGT:
4668 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4669 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4670 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4671 }
4672 break;
4673 case ISD::SETULE:
4674 case ISD::SETUGT:
4675 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4676 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4677 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4678 }
4679 break;
4680 }
4681 }
4682 }
4683
4684 // Thumb1 has very limited immediate modes, so turning an "and" into a
4685 // shift can save multiple instructions.
4686 //
4687 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4688 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4689 // own. If it's the operand to an unsigned comparison with an immediate,
4690 // we can eliminate one of the shifts: we transform
4691 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4692 //
4693 // We avoid transforming cases which aren't profitable due to encoding
4694 // details:
4695 //
4696 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4697 // would not; in that case, we're essentially trading one immediate load for
4698 // another.
4699 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4700 // 3. C2 is zero; we have other code for this special case.
4701 //
4702 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4703 // instruction, since the AND is always one instruction anyway, but we could
4704 // use narrow instructions in some cases.
4705 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4706 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4707 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4708 !isSignedIntSetCC(CC)) {
4709 unsigned Mask = LHS.getConstantOperandVal(1);
4710 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4711 uint64_t RHSV = RHSC->getZExtValue();
4712 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4713 unsigned ShiftBits = llvm::countl_zero(Mask);
4714 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4715 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4716 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4717 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4718 }
4719 }
4720 }
4721
4722 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4723 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4724 // way a cmp would.
4725 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4726 // some tweaks to the heuristics for the previous and->shift transform.
4727 // FIXME: Optimize cases where the LHS isn't a shift.
4728 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4729 isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4730 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4731 LHS.getConstantOperandVal(1) < 31) {
4732 unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4733 SDValue Shift =
4734 DAG.getNode(ARMISD::LSLS, dl, DAG.getVTList(MVT::i32, FlagsVT),
4735 LHS.getOperand(0), DAG.getConstant(ShiftAmt, dl, MVT::i32));
4736 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4737 return Shift.getValue(1);
4738 }
4739
4741
4742 unsigned CompareType;
4743 switch (CondCode) {
4744 default:
4745 CompareType = ARMISD::CMP;
4746 break;
4747 case ARMCC::EQ:
4748 case ARMCC::NE:
4749 // Uses only Z Flag
4750 CompareType = ARMISD::CMPZ;
4751 break;
4752 }
4753
4754 // TODO: Remove CMPZ check once we generalize and remove the CMPZ enum from
4755 // the codebase.
4756
4757 // TODO: When we have a solution to the vselect predicate not allowing pl/mi
4758 // all the time, allow those cases to be cmn too no matter what.
4759 if (CompareType != ARMISD::CMPZ && isCMN(RHS, CC, DAG)) {
4760 CompareType = ARMISD::CMN;
4761 RHS = RHS.getOperand(1);
4762 } else if (CompareType != ARMISD::CMPZ && isCMN(LHS, CC, DAG)) {
4763 CompareType = ARMISD::CMN;
4764 LHS = LHS.getOperand(1);
4766 }
4767
4768 // Prefer folding shifts / CMN into the cmp/cmn second operand (so_reg /
4769 // t2_so_reg). When both sides compete, pick the higher
4770 // getCmpOperandFoldingProfit. Only when RHS is not a legal icmp
4771 // immediate: otherwise keep the canonical (reg, imm) form.
4772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getNode());
4773 if (!C || !isLegalICmpImmediate(C->getSExtValue())) {
4774 if (getCmpOperandFoldingProfit(LHS, *Subtarget) >
4775 getCmpOperandFoldingProfit(RHS, *Subtarget)) {
4776 std::swap(LHS, RHS);
4777 if (CompareType == ARMISD::CMP)
4779 }
4780 }
4781
4782 // If the RHS is a constant zero then the V (overflow) flag will never be
4783 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4784 // simpler for other passes (like the peephole optimiser) to deal with.
4785 if (isNullConstant(RHS)) {
4786 switch (CondCode) {
4787 default:
4788 break;
4789 case ARMCC::GE:
4791 break;
4792 case ARMCC::LT:
4794 break;
4795 }
4796 }
4797
4798 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4799 return DAG.getNode(CompareType, dl, FlagsVT, LHS, RHS);
4800}
4801
4802/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4803SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4804 SelectionDAG &DAG, const SDLoc &dl,
4805 bool Signaling) const {
4806 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4807 SDValue Flags;
4809 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, dl, FlagsVT,
4810 LHS, RHS);
4811 else
4812 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, dl,
4813 FlagsVT, LHS);
4814 return DAG.getNode(ARMISD::FMSTAT, dl, FlagsVT, Flags);
4815}
4816
4817// This function returns three things: the arithmetic computation itself
4818// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4819// comparison and the condition code define the case in which the arithmetic
4820// computation *does not* overflow.
4821std::pair<SDValue, SDValue>
4822ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4823 SDValue &ARMcc) const {
4824 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4825
4826 SDValue Value, OverflowCmp;
4827 SDValue LHS = Op.getOperand(0);
4828 SDValue RHS = Op.getOperand(1);
4829 SDLoc dl(Op);
4830
4831 // FIXME: We are currently always generating CMPs because we don't support
4832 // generating CMN through the backend. This is not as good as the natural
4833 // CMP case because it causes a register dependency and cannot be folded
4834 // later.
4835
4836 switch (Op.getOpcode()) {
4837 default:
4838 llvm_unreachable("Unknown overflow instruction!");
4839 case ISD::SADDO:
4840 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4841 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4842 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4843 break;
4844 case ISD::UADDO:
4845 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4846 // We use ADDC here to correspond to its use in LowerALUO.
4847 // We do not use it in the USUBO case as Value may not be used.
4848 Value = DAG.getNode(ARMISD::ADDC, dl,
4849 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4850 .getValue(0);
4851 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4852 break;
4853 case ISD::SSUBO:
4854 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4855 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4856 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4857 break;
4858 case ISD::USUBO:
4859 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4860 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4861 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4862 break;
4863 case ISD::UMULO:
4864 // We generate a UMUL_LOHI and then check if the high word is 0.
4865 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4866 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4867 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4868 LHS, RHS);
4869 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4870 DAG.getConstant(0, dl, MVT::i32));
4871 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4872 break;
4873 case ISD::SMULO:
4874 // We generate a SMUL_LOHI and then check if all the bits of the high word
4875 // are the same as the sign bit of the low word.
4876 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4877 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4878 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4879 LHS, RHS);
4880 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4881 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4882 Value.getValue(0),
4883 DAG.getConstant(31, dl, MVT::i32)));
4884 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4885 break;
4886 } // switch (...)
4887
4888 return std::make_pair(Value, OverflowCmp);
4889}
4890
4892 SDLoc DL(Value);
4893 EVT VT = Value.getValueType();
4894
4895 if (Invert)
4896 Value = DAG.getNode(ISD::SUB, DL, MVT::i32,
4897 DAG.getConstant(1, DL, MVT::i32), Value);
4898
4899 SDValue Cmp = DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(VT, MVT::i32),
4900 Value, DAG.getConstant(1, DL, VT));
4901 return Cmp.getValue(1);
4902}
4903
4905 bool Invert) {
4906 SDLoc DL(Flags);
4907
4908 if (Invert) {
4909 // Convert flags to boolean with ADDE 0,0,Carry then compute 1 - bool.
4910 SDValue BoolCarry = DAG.getNode(
4911 ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4912 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT), Flags);
4913 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(1, DL, VT), BoolCarry);
4914 }
4915
4916 // Now convert the carry flag into a boolean carry. We do this
4917 // using ARMISD::ADDE 0, 0, Carry
4918 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4919 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT),
4920 Flags);
4921}
4922
4923// Value is 1 if 'V' bit is 1, else 0
4925 SDLoc DL(Flags);
4926 SDValue Zero = DAG.getConstant(0, DL, VT);
4927 SDValue One = DAG.getConstant(1, DL, VT);
4928 SDValue ARMcc = DAG.getConstant(ARMCC::VS, DL, MVT::i32);
4929 return DAG.getNode(ARMISD::CMOV, DL, VT, Zero, One, ARMcc, Flags);
4930}
4931
4932SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4933 // Let legalize expand this if it isn't a legal type yet.
4934 if (!isTypeLegal(Op.getValueType()))
4935 return SDValue();
4936
4937 SDValue LHS = Op.getOperand(0);
4938 SDValue RHS = Op.getOperand(1);
4939 SDLoc dl(Op);
4940
4941 EVT VT = Op.getValueType();
4942 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4943 SDValue Value;
4944 SDValue Overflow;
4945 switch (Op.getOpcode()) {
4946 case ISD::UADDO:
4947 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4948 // Convert the carry flag into a boolean value.
4949 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, false);
4950 break;
4951 case ISD::USUBO:
4952 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4953 // Convert the carry flag into a boolean value.
4954 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, true);
4955 break;
4956 default: {
4957 // Handle other operations with getARMXALUOOp
4958 SDValue OverflowCmp, ARMcc;
4959 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4960 // We use 0 and 1 as false and true values.
4961 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4962 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4963 // position to get Overflow=1 when the "no overflow" condition is false.
4964 Overflow =
4965 DAG.getNode(ARMISD::CMOV, dl, MVT::i32,
4966 DAG.getConstant(1, dl, MVT::i32), // FalseVal: overflow
4967 DAG.getConstant(0, dl, MVT::i32), // TrueVal: no overflow
4968 ARMcc, OverflowCmp);
4969 break;
4970 }
4971 }
4972
4973 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4974}
4975
4977 const ARMSubtarget *Subtarget) {
4978 EVT VT = Op.getValueType();
4979 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
4980 return SDValue();
4981 if (!VT.isSimple())
4982 return SDValue();
4983
4984 unsigned NewOpcode;
4985 switch (VT.getSimpleVT().SimpleTy) {
4986 default:
4987 return SDValue();
4988 case MVT::i8:
4989 switch (Op->getOpcode()) {
4990 case ISD::UADDSAT:
4991 NewOpcode = ARMISD::UQADD8b;
4992 break;
4993 case ISD::SADDSAT:
4994 NewOpcode = ARMISD::QADD8b;
4995 break;
4996 case ISD::USUBSAT:
4997 NewOpcode = ARMISD::UQSUB8b;
4998 break;
4999 case ISD::SSUBSAT:
5000 NewOpcode = ARMISD::QSUB8b;
5001 break;
5002 }
5003 break;
5004 case MVT::i16:
5005 switch (Op->getOpcode()) {
5006 case ISD::UADDSAT:
5007 NewOpcode = ARMISD::UQADD16b;
5008 break;
5009 case ISD::SADDSAT:
5010 NewOpcode = ARMISD::QADD16b;
5011 break;
5012 case ISD::USUBSAT:
5013 NewOpcode = ARMISD::UQSUB16b;
5014 break;
5015 case ISD::SSUBSAT:
5016 NewOpcode = ARMISD::QSUB16b;
5017 break;
5018 }
5019 break;
5020 }
5021
5022 SDLoc dl(Op);
5023 SDValue Add =
5024 DAG.getNode(NewOpcode, dl, MVT::i32,
5025 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5026 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5027 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5028}
5029
5030SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5031 SDValue Cond = Op.getOperand(0);
5032 SDValue SelectTrue = Op.getOperand(1);
5033 SDValue SelectFalse = Op.getOperand(2);
5034 SDLoc dl(Op);
5035 unsigned Opc = Cond.getOpcode();
5036
5037 if (Cond.getResNo() == 1 &&
5038 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5039 Opc == ISD::USUBO)) {
5040 if (!isTypeLegal(Cond->getValueType(0)))
5041 return SDValue();
5042
5043 SDValue Value, OverflowCmp;
5044 SDValue ARMcc;
5045 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5046 EVT VT = Op.getValueType();
5047
5048 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, OverflowCmp, DAG);
5049 }
5050
5051 // Convert:
5052 //
5053 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5054 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5055 //
5056 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5057 const ConstantSDNode *CMOVTrue =
5058 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5059 const ConstantSDNode *CMOVFalse =
5060 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5061
5062 if (CMOVTrue && CMOVFalse) {
5063 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5064 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5065
5066 SDValue True;
5067 SDValue False;
5068 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5069 True = SelectTrue;
5070 False = SelectFalse;
5071 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5072 True = SelectFalse;
5073 False = SelectTrue;
5074 }
5075
5076 if (True.getNode() && False.getNode())
5077 return getCMOV(dl, Op.getValueType(), True, False, Cond.getOperand(2),
5078 Cond.getOperand(3), DAG);
5079 }
5080 }
5081
5082 return DAG.getSelectCC(dl, Cond,
5083 DAG.getConstant(0, dl, Cond.getValueType()),
5084 SelectTrue, SelectFalse, ISD::SETNE);
5085}
5086
5088 bool &swpCmpOps, bool &swpVselOps) {
5089 // Start by selecting the GE condition code for opcodes that return true for
5090 // 'equality'
5091 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5092 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5093 CondCode = ARMCC::GE;
5094
5095 // and GT for opcodes that return false for 'equality'.
5096 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5097 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5098 CondCode = ARMCC::GT;
5099
5100 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5101 // to swap the compare operands.
5102 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5103 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5104 swpCmpOps = true;
5105
5106 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5107 // If we have an unordered opcode, we need to swap the operands to the VSEL
5108 // instruction (effectively negating the condition).
5109 //
5110 // This also has the effect of swapping which one of 'less' or 'greater'
5111 // returns true, so we also swap the compare operands. It also switches
5112 // whether we return true for 'equality', so we compensate by picking the
5113 // opposite condition code to our original choice.
5114 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5115 CC == ISD::SETUGT) {
5116 swpCmpOps = !swpCmpOps;
5117 swpVselOps = !swpVselOps;
5118 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5119 }
5120
5121 // 'ordered' is 'anything but unordered', so use the VS condition code and
5122 // swap the VSEL operands.
5123 if (CC == ISD::SETO) {
5124 CondCode = ARMCC::VS;
5125 swpVselOps = true;
5126 }
5127
5128 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5129 // code and swap the VSEL operands. Also do this if we don't care about the
5130 // unordered case.
5131 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5132 CondCode = ARMCC::EQ;
5133 swpVselOps = true;
5134 }
5135}
5136
5137SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5138 SDValue TrueVal, SDValue ARMcc,
5139 SDValue Flags, SelectionDAG &DAG) const {
5140 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5141 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5142 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5143 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5144 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5145
5146 SDValue TrueLow = TrueVal.getValue(0);
5147 SDValue TrueHigh = TrueVal.getValue(1);
5148 SDValue FalseLow = FalseVal.getValue(0);
5149 SDValue FalseHigh = FalseVal.getValue(1);
5150
5151 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5152 ARMcc, Flags);
5153 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5154 ARMcc, Flags);
5155
5156 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5157 }
5158 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, Flags);
5159}
5160
5162 return CC == ISD::SETGT || CC == ISD::SETGE;
5163}
5164
5166 return CC == ISD::SETLT || CC == ISD::SETLE;
5167}
5168
5169// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5170// All of these conditions (and their <= and >= counterparts) will do:
5171// x < k ? k : x
5172// x > k ? x : k
5173// k < x ? x : k
5174// k > x ? k : x
5175static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5176 const SDValue TrueVal, const SDValue FalseVal,
5177 const ISD::CondCode CC, const SDValue K) {
5178 return (isGTorGE(CC) &&
5179 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5180 (isLTorLE(CC) &&
5181 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5182}
5183
5184// Check if two chained conditionals could be converted into SSAT or USAT.
5185//
5186// SSAT can replace a set of two conditional selectors that bound a number to an
5187// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5188//
5189// x < -k ? -k : (x > k ? k : x)
5190// x < -k ? -k : (x < k ? x : k)
5191// x > -k ? (x > k ? k : x) : -k
5192// x < k ? (x < -k ? -k : x) : k
5193// etc.
5194//
5195// LLVM canonicalizes these to either a min(max()) or a max(min())
5196// pattern. This function tries to match one of these and will return a SSAT
5197// node if successful.
5198//
5199// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
5200// is a power of 2.
5202 EVT VT = Op.getValueType();
5203 SDValue V1 = Op.getOperand(0);
5204 SDValue K1 = Op.getOperand(1);
5205 SDValue TrueVal1 = Op.getOperand(2);
5206 SDValue FalseVal1 = Op.getOperand(3);
5207 ISD::CondCode CC1 = Op.getOperandCondCode(4);
5208
5209 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5210 if (Op2.getOpcode() != ISD::SELECT_CC)
5211 return SDValue();
5212
5213 SDValue V2 = Op2.getOperand(0);
5214 SDValue K2 = Op2.getOperand(1);
5215 SDValue TrueVal2 = Op2.getOperand(2);
5216 SDValue FalseVal2 = Op2.getOperand(3);
5217 ISD::CondCode CC2 = Op2.getOperandCondCode(4);
5218
5219 SDValue V1Tmp = V1;
5220 SDValue V2Tmp = V2;
5221
5222 // Check that the registers and the constants match a max(min()) or min(max())
5223 // pattern
5224 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5225 K2 != FalseVal2 ||
5226 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5227 return SDValue();
5228
5229 // Check that the constant in the lower-bound check is
5230 // the opposite of the constant in the upper-bound check
5231 // in 1's complement.
5233 return SDValue();
5234
5235 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5236 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5237 int64_t PosVal = std::max(Val1, Val2);
5238 int64_t NegVal = std::min(Val1, Val2);
5239
5240 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5241 !isPowerOf2_64(PosVal + 1))
5242 return SDValue();
5243
5244 // Handle the difference between USAT (unsigned) and SSAT (signed)
5245 // saturation
5246 // At this point, PosVal is guaranteed to be positive
5247 uint64_t K = PosVal;
5248 SDLoc dl(Op);
5249 if (Val1 == ~Val2)
5250 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5251 DAG.getConstant(llvm::countr_one(K), dl, VT));
5252 if (NegVal == 0)
5253 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5254 DAG.getConstant(llvm::countr_one(K), dl, VT));
5255
5256 return SDValue();
5257}
5258
5259// Check if a condition of the type x < k ? k : x can be converted into a
5260// bit operation instead of conditional moves.
5261// Currently this is allowed given:
5262// - The conditions and values match up
5263// - k is 0 or -1 (all ones)
5264// This function will not check the last condition, thats up to the caller
5265// It returns true if the transformation can be made, and in such case
5266// returns x in V, and k in SatK.
5268 SDValue &SatK)
5269{
5270 SDValue LHS = Op.getOperand(0);
5271 SDValue RHS = Op.getOperand(1);
5272 ISD::CondCode CC = Op.getOperandCondCode(4);
5273 SDValue TrueVal = Op.getOperand(2);
5274 SDValue FalseVal = Op.getOperand(3);
5275
5277 ? &RHS
5278 : nullptr;
5279
5280 // No constant operation in comparison, early out
5281 if (!K)
5282 return false;
5283
5284 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5285 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5286 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5287
5288 // If the constant on left and right side, or variable on left and right,
5289 // does not match, early out
5290 if (*K != KTmp || V != VTmp)
5291 return false;
5292
5293 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5294 SatK = *K;
5295 return true;
5296 }
5297
5298 return false;
5299}
5300
5301bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5302 if (VT == MVT::f32)
5303 return !Subtarget->hasVFP2Base();
5304 if (VT == MVT::f64)
5305 return !Subtarget->hasFP64();
5306 if (VT == MVT::f16)
5307 return !Subtarget->hasFullFP16();
5308 return false;
5309}
5310
5311static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5312 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5313 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5314 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5315 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5316 return SDValue();
5317
5318 unsigned TVal = CTVal->getZExtValue();
5319 unsigned FVal = CFVal->getZExtValue();
5320
5321 Opcode = 0;
5322 InvertCond = false;
5323 if (TVal == ~FVal) {
5324 Opcode = ARMISD::CSINV;
5325 } else if (TVal == ~FVal + 1) {
5326 Opcode = ARMISD::CSNEG;
5327 } else if (TVal + 1 == FVal) {
5328 Opcode = ARMISD::CSINC;
5329 } else if (TVal == FVal + 1) {
5330 Opcode = ARMISD::CSINC;
5331 std::swap(TrueVal, FalseVal);
5332 std::swap(TVal, FVal);
5333 InvertCond = !InvertCond;
5334 } else {
5335 return SDValue();
5336 }
5337
5338 // If one of the constants is cheaper than another, materialise the
5339 // cheaper one and let the csel generate the other.
5340 if (Opcode != ARMISD::CSINC &&
5342 std::swap(TrueVal, FalseVal);
5343 std::swap(TVal, FVal);
5344 InvertCond = !InvertCond;
5345 }
5346
5347 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5348 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5349 // -(-a) == a, but (a+1)+1 != a).
5350 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5351 std::swap(TrueVal, FalseVal);
5352 std::swap(TVal, FVal);
5353 InvertCond = !InvertCond;
5354 }
5355
5356 return TrueVal;
5357}
5358
5359SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5360 EVT VT = Op.getValueType();
5361 SDLoc dl(Op);
5362
5363 // Try to convert two saturating conditional selects into a single SSAT
5364 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5365 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5366 return SatValue;
5367
5368 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5369 // into more efficient bit operations, which is possible when k is 0 or -1
5370 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5371 // single instructions. On Thumb the shift and the bit operation will be two
5372 // instructions.
5373 // Only allow this transformation on full-width (32-bit) operations
5374 SDValue LowerSatConstant;
5375 SDValue SatValue;
5376 if (VT == MVT::i32 &&
5377 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5378 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5379 DAG.getConstant(31, dl, VT));
5380 if (isNullConstant(LowerSatConstant)) {
5381 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5382 DAG.getAllOnesConstant(dl, VT));
5383 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5384 } else if (isAllOnesConstant(LowerSatConstant))
5385 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5386 }
5387
5388 SDValue LHS = Op.getOperand(0);
5389 SDValue RHS = Op.getOperand(1);
5390 ISD::CondCode CC = Op.getOperandCondCode(4);
5391 SDValue TrueVal = Op.getOperand(2);
5392 SDValue FalseVal = Op.getOperand(3);
5393 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5394 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5395 if (Op.getValueType().isInteger()) {
5396
5397 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5398 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5399 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5400 // Both require less instructions than compare and conditional select.
5401 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5402 RHSC->isZero() && CFVal && CFVal->isZero() &&
5403 LHS.getValueType() == RHS.getValueType()) {
5404 EVT VT = LHS.getValueType();
5405 SDValue Shift =
5406 DAG.getNode(ISD::SRA, dl, VT, LHS,
5407 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5408
5409 if (CC == ISD::SETGT)
5410 Shift = DAG.getNOT(dl, Shift, VT);
5411
5412 return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
5413 }
5414
5415 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5416 if (CC == ISD::SETLT && isNullConstant(RHS) && isOneConstant(TrueVal) &&
5417 isNullConstant(FalseVal) && LHS.getValueType() == VT)
5418 return DAG.getNode(ISD::SRL, dl, VT, LHS,
5419 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5420 }
5421
5422 if (LHS.getValueType() == MVT::i32) {
5423 unsigned Opcode;
5424 bool InvertCond;
5425 if (SDValue Op =
5426 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5427 if (InvertCond)
5428 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5429
5430 SDValue ARMcc;
5431 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5432 EVT VT = Op.getValueType();
5433 return DAG.getNode(Opcode, dl, VT, Op, Op, ARMcc, Cmp);
5434 }
5435 }
5436
5437 if (isUnsupportedFloatingType(LHS.getValueType())) {
5438 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5439
5440 // If softenSetCCOperands only returned one value, we should compare it to
5441 // zero.
5442 if (!RHS.getNode()) {
5443 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5444 CC = ISD::SETNE;
5445 }
5446 }
5447
5448 if (LHS.getValueType() == MVT::i32) {
5449 // Try to generate VSEL on ARMv8.
5450 // The VSEL instruction can't use all the usual ARM condition
5451 // codes: it only has two bits to select the condition code, so it's
5452 // constrained to use only GE, GT, VS and EQ.
5453 //
5454 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5455 // swap the operands of the previous compare instruction (effectively
5456 // inverting the compare condition, swapping 'less' and 'greater') and
5457 // sometimes need to swap the operands to the VSEL (which inverts the
5458 // condition in the sense of firing whenever the previous condition didn't)
5459 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5460 TrueVal.getValueType() == MVT::f32 ||
5461 TrueVal.getValueType() == MVT::f64)) {
5463 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5464 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5465 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5466 std::swap(TrueVal, FalseVal);
5467 }
5468 }
5469
5470 SDValue ARMcc;
5471 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5472 // Choose GE over PL, which vsel does now support
5473 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5474 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5475 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5476 }
5477
5478 ARMCC::CondCodes CondCode, CondCode2;
5479 FPCCToARMCC(CC, CondCode, CondCode2);
5480
5481 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5482 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5483 // must use VSEL (limited condition codes), due to not having conditional f16
5484 // moves.
5485 if (Subtarget->hasFPARMv8Base() &&
5486 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5487 (TrueVal.getValueType() == MVT::f16 ||
5488 TrueVal.getValueType() == MVT::f32 ||
5489 TrueVal.getValueType() == MVT::f64)) {
5490 bool swpCmpOps = false;
5491 bool swpVselOps = false;
5492 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5493
5494 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5495 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5496 if (swpCmpOps)
5497 std::swap(LHS, RHS);
5498 if (swpVselOps)
5499 std::swap(TrueVal, FalseVal);
5500 }
5501 }
5502
5503 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5504 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5505 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5506 if (CondCode2 != ARMCC::AL) {
5507 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5508 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, Cmp, DAG);
5509 }
5510 return Result;
5511}
5512
5513/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5514/// to morph to an integer compare sequence.
5515static bool canChangeToInt(SDValue Op, bool &SeenZero,
5516 const ARMSubtarget *Subtarget) {
5517 SDNode *N = Op.getNode();
5518 if (!N->hasOneUse())
5519 // Otherwise it requires moving the value from fp to integer registers.
5520 return false;
5521 if (!N->getNumValues())
5522 return false;
5523 EVT VT = Op.getValueType();
5524 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5525 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5526 // vmrs are very slow, e.g. cortex-a8.
5527 return false;
5528
5529 if (isFloatingPointZero(Op)) {
5530 SeenZero = true;
5531 return true;
5532 }
5533 return ISD::isNormalLoad(N);
5534}
5535
5538 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5539
5541 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5542 Ld->getPointerInfo(), Ld->getAlign(),
5543 Ld->getMemOperand()->getFlags());
5544
5545 llvm_unreachable("Unknown VFP cmp argument!");
5546}
5547
5549 SDValue &RetVal1, SDValue &RetVal2) {
5550 SDLoc dl(Op);
5551
5552 if (isFloatingPointZero(Op)) {
5553 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5554 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5555 return;
5556 }
5557
5558 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5559 SDValue Ptr = Ld->getBasePtr();
5560 RetVal1 =
5561 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5562 Ld->getAlign(), Ld->getMemOperand()->getFlags());
5563
5564 EVT PtrType = Ptr.getValueType();
5565 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5566 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5567 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5568 Ld->getPointerInfo().getWithOffset(4),
5569 commonAlignment(Ld->getAlign(), 4),
5570 Ld->getMemOperand()->getFlags());
5571 return;
5572 }
5573
5574 llvm_unreachable("Unknown VFP cmp argument!");
5575}
5576
5577/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5578/// f32 and even f64 comparisons to integer ones.
5579SDValue
5580ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5581 SDValue Chain = Op.getOperand(0);
5582 ISD::CondCode CC = Op.getOperandCondCode(1);
5583 SDValue LHS = Op.getOperand(2);
5584 SDValue RHS = Op.getOperand(3);
5585 SDValue Dest = Op.getOperand(4);
5586 SDLoc dl(Op);
5587
5588 bool LHSSeenZero = false;
5589 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5590 bool RHSSeenZero = false;
5591 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5592 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5593 // If unsafe fp math optimization is enabled and there are no other uses of
5594 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5595 // to an integer comparison.
5596 if (CC == ISD::SETOEQ)
5597 CC = ISD::SETEQ;
5598 else if (CC == ISD::SETUNE)
5599 CC = ISD::SETNE;
5600
5601 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5602 SDValue ARMcc;
5603 if (LHS.getValueType() == MVT::f32) {
5604 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5605 bitcastf32Toi32(LHS, DAG), Mask);
5606 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5607 bitcastf32Toi32(RHS, DAG), Mask);
5608 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5609 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5610 Cmp);
5611 }
5612
5613 SDValue LHS1, LHS2;
5614 SDValue RHS1, RHS2;
5615 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5616 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5617 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5618 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5620 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5621 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5622 return DAG.getNode(ARMISD::BCC_i64, dl, MVT::Other, Ops);
5623 }
5624
5625 return SDValue();
5626}
5627
5628// Generate CMP + CMOV for integer abs.
5629SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5630 SDLoc DL(Op);
5631
5632 SDValue Neg = DAG.getNegative(Op.getOperand(0), DL, MVT::i32);
5633
5634 // Generate CMP & CMOV.
5635 SDValue Cmp = DAG.getNode(ARMISD::CMP, DL, FlagsVT, Op.getOperand(0),
5636 DAG.getConstant(0, DL, MVT::i32));
5637 return DAG.getNode(ARMISD::CMOV, DL, MVT::i32, Op.getOperand(0), Neg,
5638 DAG.getConstant(ARMCC::MI, DL, MVT::i32), Cmp);
5639}
5640
5642 ARMCC::CondCodes CondCode =
5643 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
5644 CondCode = ARMCC::getOppositeCondition(CondCode);
5645 return DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5646}
5647
5648SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5649 SDValue Chain = Op.getOperand(0);
5650 SDValue Cond = Op.getOperand(1);
5651 SDValue Dest = Op.getOperand(2);
5652 SDLoc dl(Op);
5653
5654 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5655 // instruction.
5656 unsigned Opc = Cond.getOpcode();
5657 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5658 !Subtarget->isThumb1Only();
5659 if (Cond.getResNo() == 1 &&
5660 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5661 Opc == ISD::USUBO || OptimizeMul)) {
5662 // Only lower legal XALUO ops.
5663 if (!isTypeLegal(Cond->getValueType(0)))
5664 return SDValue();
5665
5666 // The actual operation with overflow check.
5667 SDValue Value, OverflowCmp;
5668 SDValue ARMcc;
5669 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5670
5671 // Reverse the condition code.
5672 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5673
5674 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5675 OverflowCmp);
5676 }
5677
5678 return SDValue();
5679}
5680
5681SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5682 SDValue Chain = Op.getOperand(0);
5683 ISD::CondCode CC = Op.getOperandCondCode(1);
5684 SDValue LHS = Op.getOperand(2);
5685 SDValue RHS = Op.getOperand(3);
5686 SDValue Dest = Op.getOperand(4);
5687 SDLoc dl(Op);
5688
5689 if (isUnsupportedFloatingType(LHS.getValueType())) {
5690 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5691
5692 // If softenSetCCOperands only returned one value, we should compare it to
5693 // zero.
5694 if (!RHS.getNode()) {
5695 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5696 CC = ISD::SETNE;
5697 }
5698 }
5699
5700 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5701 // instruction.
5702 unsigned Opc = LHS.getOpcode();
5703 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5704 !Subtarget->isThumb1Only();
5705 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5706 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5707 Opc == ISD::USUBO || OptimizeMul) &&
5708 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5709 // Only lower legal XALUO ops.
5710 if (!isTypeLegal(LHS->getValueType(0)))
5711 return SDValue();
5712
5713 // The actual operation with overflow check.
5714 SDValue Value, OverflowCmp;
5715 SDValue ARMcc;
5716 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5717
5718 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5719 // Reverse the condition code.
5720 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5721 }
5722
5723 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5724 OverflowCmp);
5725 }
5726
5727 if (LHS.getValueType() == MVT::i32) {
5728 SDValue ARMcc;
5729 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5730 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, Cmp);
5731 }
5732
5733 SDNodeFlags Flags = Op->getFlags();
5734 if (Flags.hasNoNaNs() &&
5735 DAG.getDenormalMode(MVT::f32) == DenormalMode::getIEEE() &&
5736 DAG.getDenormalMode(MVT::f64) == DenormalMode::getIEEE() &&
5737 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5738 CC == ISD::SETUNE)) {
5739 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5740 return Result;
5741 }
5742
5743 ARMCC::CondCodes CondCode, CondCode2;
5744 FPCCToARMCC(CC, CondCode, CondCode2);
5745
5746 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5747 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5748 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5749 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5750 if (CondCode2 != ARMCC::AL) {
5751 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5752 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5753 Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5754 }
5755 return Res;
5756}
5757
5758SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5759 SDValue Chain = Op.getOperand(0);
5760 SDValue Table = Op.getOperand(1);
5761 SDValue Index = Op.getOperand(2);
5762 SDLoc dl(Op);
5763
5764 EVT PTy = getPointerTy(DAG.getDataLayout());
5765 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5766 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5767 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5768 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5769 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5770 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5771 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5772 // which does another jump to the destination. This also makes it easier
5773 // to translate it to TBB / TBH later (Thumb2 only).
5774 // FIXME: This might not work if the function is extremely large.
5775 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5776 Addr, Op.getOperand(2), JTI);
5777 }
5778 if (isPositionIndependent() || Subtarget->isROPI()) {
5779 Addr =
5780 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5782 Chain = Addr.getValue(1);
5783 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5784 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5785 } else {
5786 Addr =
5787 DAG.getLoad(PTy, dl, Chain, Addr,
5789 Chain = Addr.getValue(1);
5790 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5791 }
5792}
5793
5795 EVT VT = Op.getValueType();
5796 SDLoc dl(Op);
5797
5798 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5799 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5800 return Op;
5801 return DAG.UnrollVectorOp(Op.getNode());
5802 }
5803
5804 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5805
5806 EVT NewTy;
5807 const EVT OpTy = Op.getOperand(0).getValueType();
5808 if (OpTy == MVT::v4f32)
5809 NewTy = MVT::v4i32;
5810 else if (OpTy == MVT::v4f16 && HasFullFP16)
5811 NewTy = MVT::v4i16;
5812 else if (OpTy == MVT::v8f16 && HasFullFP16)
5813 NewTy = MVT::v8i16;
5814 else
5815 llvm_unreachable("Invalid type for custom lowering!");
5816
5817 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5818 return DAG.UnrollVectorOp(Op.getNode());
5819
5820 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5821 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5822}
5823
5824SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5825 EVT VT = Op.getValueType();
5826 if (VT.isVector())
5827 return LowerVectorFP_TO_INT(Op, DAG);
5828
5829 bool IsStrict = Op->isStrictFPOpcode();
5830 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5831
5832 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5833 RTLIB::Libcall LC;
5834 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5835 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5836 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5837 Op.getValueType());
5838 else
5839 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5840 Op.getValueType());
5841 SDLoc Loc(Op);
5842 MakeLibCallOptions CallOptions;
5843 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5845 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5846 CallOptions, Loc, Chain);
5847 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5848 }
5849
5850 return Op;
5851}
5852
5854 const ARMSubtarget *Subtarget) {
5855 EVT VT = Op.getValueType();
5856 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5857 EVT FromVT = Op.getOperand(0).getValueType();
5858
5859 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5860 return Op;
5861 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5862 Subtarget->hasFP64())
5863 return Op;
5864 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5865 Subtarget->hasFullFP16())
5866 return Op;
5867 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5868 Subtarget->hasMVEFloatOps())
5869 return Op;
5870 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5871 Subtarget->hasMVEFloatOps())
5872 return Op;
5873
5874 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5875 return SDValue();
5876
5877 SDLoc DL(Op);
5878 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5879 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5880 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5881 DAG.getValueType(VT.getScalarType()));
5882 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5883 DAG.getConstant((1 << BW) - 1, DL, VT));
5884 if (IsSigned)
5885 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5886 DAG.getSignedConstant(-(1 << BW), DL, VT));
5887 return Max;
5888}
5889
5891 EVT VT = Op.getValueType();
5892 SDLoc dl(Op);
5893
5894 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5895 if (VT.getVectorElementType() == MVT::f32)
5896 return Op;
5897 return DAG.UnrollVectorOp(Op.getNode());
5898 }
5899
5900 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5901 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5902 "Invalid type for custom lowering!");
5903
5904 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5905
5906 EVT DestVecType;
5907 if (VT == MVT::v4f32)
5908 DestVecType = MVT::v4i32;
5909 else if (VT == MVT::v4f16 && HasFullFP16)
5910 DestVecType = MVT::v4i16;
5911 else if (VT == MVT::v8f16 && HasFullFP16)
5912 DestVecType = MVT::v8i16;
5913 else
5914 return DAG.UnrollVectorOp(Op.getNode());
5915
5916 unsigned CastOpc;
5917 unsigned Opc;
5918 switch (Op.getOpcode()) {
5919 default: llvm_unreachable("Invalid opcode!");
5920 case ISD::SINT_TO_FP:
5921 CastOpc = ISD::SIGN_EXTEND;
5923 break;
5924 case ISD::UINT_TO_FP:
5925 CastOpc = ISD::ZERO_EXTEND;
5927 break;
5928 }
5929
5930 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5931 return DAG.getNode(Opc, dl, VT, Op);
5932}
5933
5934SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5935 EVT VT = Op.getValueType();
5936 if (VT.isVector())
5937 return LowerVectorINT_TO_FP(Op, DAG);
5938
5939 bool IsStrict = Op->isStrictFPOpcode();
5940 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5941
5942 if (isUnsupportedFloatingType(VT)) {
5943 RTLIB::Libcall LC;
5944 if (Op.getOpcode() == ISD::SINT_TO_FP ||
5945 Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
5946 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
5947 else
5948 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
5949 SDLoc Loc(Op);
5950 MakeLibCallOptions CallOptions;
5951 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5953 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5954 CallOptions, Loc, Chain);
5955 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5956 }
5957
5958 return Op;
5959}
5960
5961SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5962 // Implement fcopysign with a fabs and a conditional fneg.
5963 SDValue Tmp0 = Op.getOperand(0);
5964 SDValue Tmp1 = Op.getOperand(1);
5965 SDLoc dl(Op);
5966 EVT VT = Op.getValueType();
5967 EVT SrcVT = Tmp1.getValueType();
5968 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5969 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5970 bool UseNEON = !InGPR && Subtarget->hasNEON();
5971
5972 if (UseNEON) {
5973 // Use VBSL to copy the sign bit.
5974 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5975 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5976 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5977 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5978 if (VT == MVT::f64)
5979 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5980 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5981 DAG.getConstant(32, dl, MVT::i32));
5982 else /*if (VT == MVT::f32)*/
5983 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5984 if (SrcVT == MVT::f32) {
5985 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5986 if (VT == MVT::f64)
5987 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5988 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5989 DAG.getConstant(32, dl, MVT::i32));
5990 } else if (VT == MVT::f32)
5991 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5992 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5993 DAG.getConstant(32, dl, MVT::i32));
5994 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5995 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5996
5998 dl, MVT::i32);
5999 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
6000 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
6001 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
6002
6003 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
6004 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
6005 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
6006 if (VT == MVT::f32) {
6007 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
6008 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
6009 DAG.getConstant(0, dl, MVT::i32));
6010 } else {
6011 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
6012 }
6013
6014 return Res;
6015 }
6016
6017 // Bitcast operand 1 to i32.
6018 if (SrcVT == MVT::f64)
6019 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6020 Tmp1).getValue(1);
6021 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
6022
6023 // Or in the signbit with integer operations.
6024 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
6025 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6026 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6027 if (VT == MVT::f32) {
6028 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6029 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6030 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6031 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6032 }
6033
6034 // f64: Or the high part with signbit and then combine two parts.
6035 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6036 Tmp0);
6037 SDValue Lo = Tmp0.getValue(0);
6038 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6039 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6040 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6041}
6042
6043SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6045 MachineFrameInfo &MFI = MF.getFrameInfo();
6046 MFI.setReturnAddressIsTaken(true);
6047
6048 EVT VT = Op.getValueType();
6049 SDLoc dl(Op);
6050 unsigned Depth = Op.getConstantOperandVal(0);
6051 if (Depth) {
6052 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6053 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6054 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6055 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6056 MachinePointerInfo());
6057 }
6058
6059 // Return LR, which contains the return address. Mark it an implicit live-in.
6060 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6061 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6062}
6063
6064SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6065 const ARMBaseRegisterInfo &ARI =
6066 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6068 MachineFrameInfo &MFI = MF.getFrameInfo();
6069 MFI.setFrameAddressIsTaken(true);
6070
6071 EVT VT = Op.getValueType();
6072 SDLoc dl(Op); // FIXME probably not meaningful
6073 unsigned Depth = Op.getConstantOperandVal(0);
6074 Register FrameReg = ARI.getFrameRegister(MF);
6075 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6076 while (Depth--)
6077 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6078 MachinePointerInfo());
6079 return FrameAddr;
6080}
6081
6082// FIXME? Maybe this could be a TableGen attribute on some registers and
6083// this table could be generated automatically from RegInfo.
6084Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6085 const MachineFunction &MF) const {
6086 return StringSwitch<Register>(RegName)
6087 .Case("sp", ARM::SP)
6088 .Default(Register());
6089}
6090
6091// Result is 64 bit value so split into two 32 bit values and return as a
6092// pair of values.
6094 SelectionDAG &DAG) {
6095 SDLoc DL(N);
6096
6097 // This function is only supposed to be called for i64 type destination.
6098 assert(N->getValueType(0) == MVT::i64
6099 && "ExpandREAD_REGISTER called for non-i64 type result.");
6100
6102 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6103 N->getOperand(0),
6104 N->getOperand(1));
6105
6106 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6107 Read.getValue(1)));
6108 Results.push_back(Read.getValue(2)); // Chain
6109}
6110
6111/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6112/// When \p DstVT, the destination type of \p BC, is on the vector
6113/// register bank and the source of bitcast, \p Op, operates on the same bank,
6114/// it might be possible to combine them, such that everything stays on the
6115/// vector register bank.
6116/// \p return The node that would replace \p BT, if the combine
6117/// is possible.
6119 SelectionDAG &DAG) {
6120 SDValue Op = BC->getOperand(0);
6121 EVT DstVT = BC->getValueType(0);
6122
6123 // The only vector instruction that can produce a scalar (remember,
6124 // since the bitcast was about to be turned into VMOVDRR, the source
6125 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6126 // Moreover, we can do this combine only if there is one use.
6127 // Finally, if the destination type is not a vector, there is not
6128 // much point on forcing everything on the vector bank.
6129 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6130 !Op.hasOneUse())
6131 return SDValue();
6132
6133 // If the index is not constant, we will introduce an additional
6134 // multiply that will stick.
6135 // Give up in that case.
6136 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6137 if (!Index)
6138 return SDValue();
6139 unsigned DstNumElt = DstVT.getVectorNumElements();
6140
6141 // Compute the new index.
6142 const APInt &APIntIndex = Index->getAPIntValue();
6143 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6144 NewIndex *= APIntIndex;
6145 // Check if the new constant index fits into i32.
6146 if (NewIndex.getBitWidth() > 32)
6147 return SDValue();
6148
6149 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6150 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6151 SDLoc dl(Op);
6152 SDValue ExtractSrc = Op.getOperand(0);
6153 EVT VecVT = EVT::getVectorVT(
6154 *DAG.getContext(), DstVT.getScalarType(),
6155 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6156 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6157 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6158 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6159}
6160
6161/// ExpandBITCAST - If the target supports VFP, this function is called to
6162/// expand a bit convert where either the source or destination type is i64 to
6163/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6164/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6165/// vectors), since the legalizer won't know what to do with that.
6166SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6167 const ARMSubtarget *Subtarget) const {
6168 SDLoc dl(N);
6169 SDValue Op = N->getOperand(0);
6170
6171 // This function is only supposed to be called for i16 and i64 types, either
6172 // as the source or destination of the bit convert.
6173 EVT SrcVT = Op.getValueType();
6174 EVT DstVT = N->getValueType(0);
6175
6176 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6177 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6178 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6179 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6180
6181 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6182 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
6183 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
6184 Op = DAG.getBitcast(MVT::f16, Op);
6185 return DAG.getNode(
6186 ISD::TRUNCATE, SDLoc(N), DstVT,
6187 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6188 }
6189
6190 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6191 return SDValue();
6192
6193 // Turn i64->f64 into VMOVDRR.
6194 if (SrcVT == MVT::i64 && isTypeLegal(DstVT)) {
6195 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6196 // if we can combine the bitcast with its source.
6198 return Val;
6199 SDValue Lo, Hi;
6200 std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6201 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6202 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6203 }
6204
6205 // Turn f64->i64 into VMOVRRD.
6206 if (DstVT == MVT::i64 && isTypeLegal(SrcVT)) {
6207 SDValue Cvt;
6208 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6209 SrcVT.getVectorNumElements() > 1)
6210 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6211 DAG.getVTList(MVT::i32, MVT::i32),
6212 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6213 else
6214 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6215 DAG.getVTList(MVT::i32, MVT::i32), Op);
6216 // Merge the pieces into a single i64 value.
6217 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6218 }
6219
6220 return SDValue();
6221}
6222
6223/// getZeroVector - Returns a vector of specified type with all zero elements.
6224/// Zero vectors are used to represent vector negation and in those cases
6225/// will be implemented with the NEON VNEG instruction. However, VNEG does
6226/// not support i64 elements, so sometimes the zero vectors will need to be
6227/// explicitly constructed. Regardless, use a canonical VMOV to create the
6228/// zero vector.
6229static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6230 assert(VT.isVector() && "Expected a vector type");
6231 // The canonical modified immediate encoding of a zero vector is....0!
6232 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6233 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6234 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6235 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6236}
6237
6238/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6239/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6240SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6241 SelectionDAG &DAG) const {
6242 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6243 EVT VT = Op.getValueType();
6244 unsigned VTBits = VT.getSizeInBits();
6245 SDLoc dl(Op);
6246 SDValue ShOpLo = Op.getOperand(0);
6247 SDValue ShOpHi = Op.getOperand(1);
6248 SDValue ShAmt = Op.getOperand(2);
6249 SDValue ARMcc;
6250 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6251
6252 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6253
6254 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6255 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6256 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6257 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6258 DAG.getConstant(VTBits, dl, MVT::i32));
6259 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6260 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6261 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6262 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6263 ISD::SETGE, ARMcc, DAG, dl);
6264 SDValue Lo =
6265 DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, ARMcc, CmpLo);
6266
6267 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6268 SDValue HiBigShift = Opc == ISD::SRA
6269 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6270 DAG.getConstant(VTBits - 1, dl, VT))
6271 : DAG.getConstant(0, dl, VT);
6272 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6273 ISD::SETGE, ARMcc, DAG, dl);
6274 SDValue Hi =
6275 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6276
6277 SDValue Ops[2] = { Lo, Hi };
6278 return DAG.getMergeValues(Ops, dl);
6279}
6280
6281/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6282/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6283SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6284 SelectionDAG &DAG) const {
6285 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6286 EVT VT = Op.getValueType();
6287 unsigned VTBits = VT.getSizeInBits();
6288 SDLoc dl(Op);
6289 SDValue ShOpLo = Op.getOperand(0);
6290 SDValue ShOpHi = Op.getOperand(1);
6291 SDValue ShAmt = Op.getOperand(2);
6292 SDValue ARMcc;
6293
6294 assert(Op.getOpcode() == ISD::SHL_PARTS);
6295 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6296 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6297 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6298 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6299 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6300
6301 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6302 DAG.getConstant(VTBits, dl, MVT::i32));
6303 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6304 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6305 ISD::SETGE, ARMcc, DAG, dl);
6306 SDValue Hi =
6307 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6308
6309 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6310 ISD::SETGE, ARMcc, DAG, dl);
6311 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6312 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6313 DAG.getConstant(0, dl, VT), ARMcc, CmpLo);
6314
6315 SDValue Ops[2] = { Lo, Hi };
6316 return DAG.getMergeValues(Ops, dl);
6317}
6318
6319SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6320 SelectionDAG &DAG) const {
6321 // The rounding mode is in bits 23:22 of the FPSCR.
6322 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6323 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6324 // so that the shift + and get folded into a bitfield extract.
6325 SDLoc dl(Op);
6326 SDValue Chain = Op.getOperand(0);
6327 SDValue Ops[] = {Chain,
6328 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6329
6330 SDValue FPSCR =
6331 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6332 Chain = FPSCR.getValue(1);
6333 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6334 DAG.getConstant(1U << 22, dl, MVT::i32));
6335 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6336 DAG.getConstant(22, dl, MVT::i32));
6337 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6338 DAG.getConstant(3, dl, MVT::i32));
6339 return DAG.getMergeValues({And, Chain}, dl);
6340}
6341
6342SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6343 SelectionDAG &DAG) const {
6344 SDLoc DL(Op);
6345 SDValue Chain = Op->getOperand(0);
6346 SDValue RMValue = Op->getOperand(1);
6347
6348 // The rounding mode is in bits 23:22 of the FPSCR.
6349 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6350 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6351 // ((arg - 1) & 3) << 22).
6352 //
6353 // It is expected that the argument of llvm.set.rounding is within the
6354 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6355 // responsibility of the code generated llvm.set.rounding to ensure this
6356 // condition.
6357
6358 // Calculate new value of FPSCR[23:22].
6359 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6360 DAG.getConstant(1, DL, MVT::i32));
6361 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6362 DAG.getConstant(0x3, DL, MVT::i32));
6363 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6364 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6365
6366 // Get current value of FPSCR.
6367 SDValue Ops[] = {Chain,
6368 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6369 SDValue FPSCR =
6370 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6371 Chain = FPSCR.getValue(1);
6372 FPSCR = FPSCR.getValue(0);
6373
6374 // Put new rounding mode into FPSCR[23:22].
6375 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6376 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6377 DAG.getConstant(RMMask, DL, MVT::i32));
6378 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6379 SDValue Ops2[] = {
6380 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6381 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6382}
6383
6384SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6385 SelectionDAG &DAG) const {
6386 SDLoc DL(Op);
6387 SDValue Chain = Op->getOperand(0);
6388 SDValue Mode = Op->getOperand(1);
6389
6390 // Generate nodes to build:
6391 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6392 SDValue Ops[] = {Chain,
6393 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6394 SDValue FPSCR =
6395 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6396 Chain = FPSCR.getValue(1);
6397 FPSCR = FPSCR.getValue(0);
6398
6399 SDValue FPSCRMasked =
6400 DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6401 DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6402 SDValue InputMasked =
6403 DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6404 DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6405 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6406
6407 SDValue Ops2[] = {
6408 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6409 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6410}
6411
6412SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6413 SelectionDAG &DAG) const {
6414 SDLoc DL(Op);
6415 SDValue Chain = Op->getOperand(0);
6416
6417 // To get the default FP mode all control bits are cleared:
6418 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6419 SDValue Ops[] = {Chain,
6420 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6421 SDValue FPSCR =
6422 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6423 Chain = FPSCR.getValue(1);
6424 FPSCR = FPSCR.getValue(0);
6425
6426 SDValue FPSCRMasked = DAG.getNode(
6427 ISD::AND, DL, MVT::i32, FPSCR,
6429 SDValue Ops2[] = {Chain,
6430 DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6431 FPSCRMasked};
6432 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6433}
6434
6436 const ARMSubtarget *ST) {
6437 SDLoc dl(N);
6438 EVT VT = N->getValueType(0);
6439 if (VT.isVector() && ST->hasNEON()) {
6440
6441 // Compute the least significant set bit: LSB = X & -X
6442 SDValue X = N->getOperand(0);
6443 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6444 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6445
6447
6448 if (ElemTy == MVT::i8) {
6449 // Compute with: cttz(x) = ctpop(lsb - 1)
6450 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6451 DAG.getTargetConstant(1, dl, ElemTy));
6452 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6453 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6454 }
6455
6456 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6457 (N->getOpcode() == ISD::CTTZ_ZERO_POISON)) {
6458 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6459 unsigned NumBits = ElemTy.getSizeInBits();
6460 SDValue WidthMinus1 =
6461 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6462 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6463 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6464 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6465 }
6466
6467 // Compute with: cttz(x) = ctpop(lsb - 1)
6468
6469 // Compute LSB - 1.
6470 SDValue Bits;
6471 if (ElemTy == MVT::i64) {
6472 // Load constant 0xffff'ffff'ffff'ffff to register.
6473 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6474 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6475 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6476 } else {
6477 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6478 DAG.getTargetConstant(1, dl, ElemTy));
6479 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6480 }
6481 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6482 }
6483
6484 if (!ST->hasV6T2Ops())
6485 return SDValue();
6486
6487 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6488 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6489}
6490
6492 const ARMSubtarget *ST) {
6493 EVT VT = N->getValueType(0);
6494 SDLoc DL(N);
6495
6496 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6497 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6498 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6499 "Unexpected type for custom ctpop lowering");
6500
6502 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6503 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6504 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6505
6506 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6507 unsigned EltSize = 8;
6508 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6509 while (EltSize != VT.getScalarSizeInBits()) {
6511 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6512 TLI.getPointerTy(DAG.getDataLayout())));
6513 Ops.push_back(Res);
6514
6515 EltSize *= 2;
6516 NumElts /= 2;
6517 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6518 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6519 }
6520
6521 return Res;
6522}
6523
6524/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6525/// operand of a vector shift operation, where all the elements of the
6526/// build_vector must have the same constant integer value.
6527static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6528 // Ignore bit_converts.
6529 while (Op.getOpcode() == ISD::BITCAST)
6530 Op = Op.getOperand(0);
6532 APInt SplatBits, SplatUndef;
6533 unsigned SplatBitSize;
6534 bool HasAnyUndefs;
6535 if (!BVN ||
6536 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6537 ElementBits) ||
6538 SplatBitSize > ElementBits)
6539 return false;
6540 Cnt = SplatBits.getSExtValue();
6541 return true;
6542}
6543
6544/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6545/// operand of a vector shift left operation. That value must be in the range:
6546/// 0 <= Value < ElementBits for a left shift; or
6547/// 0 <= Value <= ElementBits for a long left shift.
6548static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6549 assert(VT.isVector() && "vector shift count is not a vector type");
6550 int64_t ElementBits = VT.getScalarSizeInBits();
6551 if (!getVShiftImm(Op, ElementBits, Cnt))
6552 return false;
6553 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6554}
6555
6556/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6557/// operand of a vector shift right operation. For a shift opcode, the value
6558/// is positive, but for an intrinsic the value count must be negative. The
6559/// absolute value must be in the range:
6560/// 1 <= |Value| <= ElementBits for a right shift; or
6561/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6562static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6563 int64_t &Cnt) {
6564 assert(VT.isVector() && "vector shift count is not a vector type");
6565 int64_t ElementBits = VT.getScalarSizeInBits();
6566 if (!getVShiftImm(Op, ElementBits, Cnt))
6567 return false;
6568 if (!isIntrinsic)
6569 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6570 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6571 Cnt = -Cnt;
6572 return true;
6573 }
6574 return false;
6575}
6576
6578 const ARMSubtarget *ST) {
6579 EVT VT = N->getValueType(0);
6580 SDLoc dl(N);
6581 int64_t Cnt;
6582
6583 if (!VT.isVector())
6584 return SDValue();
6585
6586 // We essentially have two forms here. Shift by an immediate and shift by a
6587 // vector register (there are also shift by a gpr, but that is just handled
6588 // with a tablegen pattern). We cannot easily match shift by an immediate in
6589 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6590 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6591 // signed or unsigned, and a negative shift indicates a shift right).
6592 if (N->getOpcode() == ISD::SHL) {
6593 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6594 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6595 DAG.getConstant(Cnt, dl, MVT::i32));
6596 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6597 N->getOperand(1));
6598 }
6599
6600 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6601 "unexpected vector shift opcode");
6602
6603 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6604 unsigned VShiftOpc =
6605 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6606 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6607 DAG.getConstant(Cnt, dl, MVT::i32));
6608 }
6609
6610 // Other right shifts we don't have operations for (we use a shift left by a
6611 // negative number).
6612 EVT ShiftVT = N->getOperand(1).getValueType();
6613 SDValue NegatedCount = DAG.getNode(
6614 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6615 unsigned VShiftOpc =
6616 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6617 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6618}
6619
6621 const ARMSubtarget *ST) {
6622 EVT VT = N->getValueType(0);
6623 SDLoc dl(N);
6624
6625 // We can get here for a node like i32 = ISD::SHL i32, i64
6626 if (VT != MVT::i64)
6627 return SDValue();
6628
6629 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6630 N->getOpcode() == ISD::SHL) &&
6631 "Unknown shift to lower!");
6632
6633 unsigned ShOpc = N->getOpcode();
6634 if (ST->hasMVEIntegerOps()) {
6635 SDValue ShAmt = N->getOperand(1);
6636 unsigned ShPartsOpc = ARMISD::LSLL;
6638
6639 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6640 // then do the default optimisation
6641 if ((!Con && ShAmt->getValueType(0).getSizeInBits() > 64) ||
6642 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(32))))
6643 return SDValue();
6644
6645 // Extract the lower 32 bits of the shift amount if it's not an i32
6646 if (ShAmt->getValueType(0) != MVT::i32)
6647 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6648
6649 if (ShOpc == ISD::SRL) {
6650 if (!Con)
6651 // There is no t2LSRLr instruction so negate and perform an lsll if the
6652 // shift amount is in a register, emulating a right shift.
6653 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6654 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6655 else
6656 // Else generate an lsrl on the immediate shift amount
6657 ShPartsOpc = ARMISD::LSRL;
6658 } else if (ShOpc == ISD::SRA)
6659 ShPartsOpc = ARMISD::ASRL;
6660
6661 // Split Lower/Upper 32 bits of the destination/source
6662 SDValue Lo, Hi;
6663 std::tie(Lo, Hi) =
6664 DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6665 // Generate the shift operation as computed above
6666 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6667 ShAmt);
6668 // The upper 32 bits come from the second return value of lsll
6669 Hi = SDValue(Lo.getNode(), 1);
6670 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6671 }
6672
6673 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6674 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6675 return SDValue();
6676
6677 // If we are in thumb mode, we don't have RRX.
6678 if (ST->isThumb1Only())
6679 return SDValue();
6680
6681 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6682 SDValue Lo, Hi;
6683 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6684
6685 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6686 // captures the shifted out bit into a carry flag.
6687 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6688 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, FlagsVT), Hi);
6689
6690 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6691 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6692
6693 // Merge the pieces into a single i64 value.
6694 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6695}
6696
6698 const ARMSubtarget *ST) {
6699 bool Invert = false;
6700 bool Swap = false;
6701 unsigned Opc = ARMCC::AL;
6702
6703 SDValue Op0 = Op.getOperand(0);
6704 SDValue Op1 = Op.getOperand(1);
6705 SDValue CC = Op.getOperand(2);
6706 EVT VT = Op.getValueType();
6707 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6708 SDLoc dl(Op);
6709
6710 EVT CmpVT;
6711 if (ST->hasNEON())
6713 else {
6714 assert(ST->hasMVEIntegerOps() &&
6715 "No hardware support for integer vector comparison!");
6716
6717 if (Op.getValueType().getVectorElementType() != MVT::i1)
6718 return SDValue();
6719
6720 // Make sure we expand floating point setcc to scalar if we do not have
6721 // mve.fp, so that we can handle them from there.
6722 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6723 return SDValue();
6724
6725 CmpVT = VT;
6726 }
6727
6728 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6729 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6730 // Special-case integer 64-bit equality comparisons. They aren't legal,
6731 // but they can be lowered with a few vector instructions.
6732 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6733 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6734 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6735 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6736 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6737 DAG.getCondCode(ISD::SETEQ));
6738 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6739 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6740 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6741 if (SetCCOpcode == ISD::SETNE)
6742 Merged = DAG.getNOT(dl, Merged, CmpVT);
6743 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6744 return Merged;
6745 }
6746
6747 if (CmpVT.getVectorElementType() == MVT::i64)
6748 // 64-bit comparisons are not legal in general.
6749 return SDValue();
6750
6751 if (Op1.getValueType().isFloatingPoint()) {
6752 switch (SetCCOpcode) {
6753 default: llvm_unreachable("Illegal FP comparison");
6754 case ISD::SETUNE:
6755 case ISD::SETNE:
6756 if (ST->hasMVEFloatOps()) {
6757 Opc = ARMCC::NE; break;
6758 } else {
6759 Invert = true; [[fallthrough]];
6760 }
6761 case ISD::SETOEQ:
6762 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6763 case ISD::SETOLT:
6764 case ISD::SETLT: Swap = true; [[fallthrough]];
6765 case ISD::SETOGT:
6766 case ISD::SETGT: Opc = ARMCC::GT; break;
6767 case ISD::SETOLE:
6768 case ISD::SETLE: Swap = true; [[fallthrough]];
6769 case ISD::SETOGE:
6770 case ISD::SETGE: Opc = ARMCC::GE; break;
6771 case ISD::SETUGE: Swap = true; [[fallthrough]];
6772 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6773 case ISD::SETUGT: Swap = true; [[fallthrough]];
6774 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6775 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6776 case ISD::SETONE: {
6777 // Expand this to (OLT | OGT).
6778 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6779 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6780 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6781 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6782 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6783 if (Invert)
6784 Result = DAG.getNOT(dl, Result, VT);
6785 return Result;
6786 }
6787 case ISD::SETUO: Invert = true; [[fallthrough]];
6788 case ISD::SETO: {
6789 // Expand this to (OLT | OGE).
6790 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6791 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6792 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6793 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6794 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6795 if (Invert)
6796 Result = DAG.getNOT(dl, Result, VT);
6797 return Result;
6798 }
6799 }
6800 } else {
6801 // Integer comparisons.
6802 switch (SetCCOpcode) {
6803 default: llvm_unreachable("Illegal integer comparison");
6804 case ISD::SETNE:
6805 if (ST->hasMVEIntegerOps()) {
6806 Opc = ARMCC::NE; break;
6807 } else {
6808 Invert = true; [[fallthrough]];
6809 }
6810 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6811 case ISD::SETLT: Swap = true; [[fallthrough]];
6812 case ISD::SETGT: Opc = ARMCC::GT; break;
6813 case ISD::SETLE: Swap = true; [[fallthrough]];
6814 case ISD::SETGE: Opc = ARMCC::GE; break;
6815 case ISD::SETULT: Swap = true; [[fallthrough]];
6816 case ISD::SETUGT: Opc = ARMCC::HI; break;
6817 case ISD::SETULE: Swap = true; [[fallthrough]];
6818 case ISD::SETUGE: Opc = ARMCC::HS; break;
6819 }
6820
6821 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6822 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6823 SDValue AndOp;
6825 AndOp = Op0;
6826 else if (ISD::isBuildVectorAllZeros(Op0))
6827 AndOp = Op1;
6828
6829 // Ignore bitconvert.
6830 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6831 AndOp = AndOp.getOperand(0);
6832
6833 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6834 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6835 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6836 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6837 if (!Invert)
6838 Result = DAG.getNOT(dl, Result, VT);
6839 return Result;
6840 }
6841 }
6842 }
6843
6844 if (Swap)
6845 std::swap(Op0, Op1);
6846
6847 // If one of the operands is a constant vector zero, attempt to fold the
6848 // comparison to a specialized compare-against-zero form.
6849 if (ISD::isBuildVectorAllZeros(Op0) &&
6850 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6851 Opc == ARMCC::NE)) {
6852 if (Opc == ARMCC::GE)
6853 Opc = ARMCC::LE;
6854 else if (Opc == ARMCC::GT)
6855 Opc = ARMCC::LT;
6856 std::swap(Op0, Op1);
6857 }
6858
6859 SDValue Result;
6860 if (ISD::isBuildVectorAllZeros(Op1) &&
6861 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6862 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6863 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
6864 DAG.getConstant(Opc, dl, MVT::i32));
6865 else
6866 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6867 DAG.getConstant(Opc, dl, MVT::i32));
6868
6869 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6870
6871 if (Invert)
6872 Result = DAG.getNOT(dl, Result, VT);
6873
6874 return Result;
6875}
6876
6878 SDValue LHS = Op.getOperand(0);
6879 SDValue RHS = Op.getOperand(1);
6880
6881 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6882
6883 SDValue Carry = Op.getOperand(2);
6884 SDValue Cond = Op.getOperand(3);
6885 SDLoc DL(Op);
6886
6887 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6888 // have to invert the carry first.
6889 SDValue InvCarry = valueToCarryFlag(Carry, DAG, true);
6890
6891 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6892 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, InvCarry);
6893
6894 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6895 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6896 SDValue ARMcc = DAG.getConstant(
6897 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6898 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6899 Cmp.getValue(1));
6900}
6901
6902/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6903/// valid vector constant for a NEON or MVE instruction with a "modified
6904/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6905static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6906 unsigned SplatBitSize, SelectionDAG &DAG,
6907 const SDLoc &dl, EVT &VT, EVT VectorVT,
6908 VMOVModImmType type) {
6909 unsigned OpCmode, Imm;
6910 bool is128Bits = VectorVT.is128BitVector();
6911
6912 // SplatBitSize is set to the smallest size that splats the vector, so a
6913 // zero vector will always have SplatBitSize == 8. However, NEON modified
6914 // immediate instructions others than VMOV do not support the 8-bit encoding
6915 // of a zero vector, and the default encoding of zero is supposed to be the
6916 // 32-bit version.
6917 if (SplatBits == 0)
6918 SplatBitSize = 32;
6919
6920 switch (SplatBitSize) {
6921 case 8:
6922 if (type != VMOVModImm)
6923 return SDValue();
6924 // Any 1-byte value is OK. Op=0, Cmode=1110.
6925 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6926 OpCmode = 0xe;
6927 Imm = SplatBits;
6928 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6929 break;
6930
6931 case 16:
6932 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6933 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6934 if ((SplatBits & ~0xff) == 0) {
6935 // Value = 0x00nn: Op=x, Cmode=100x.
6936 OpCmode = 0x8;
6937 Imm = SplatBits;
6938 break;
6939 }
6940 if ((SplatBits & ~0xff00) == 0) {
6941 // Value = 0xnn00: Op=x, Cmode=101x.
6942 OpCmode = 0xa;
6943 Imm = SplatBits >> 8;
6944 break;
6945 }
6946 return SDValue();
6947
6948 case 32:
6949 // NEON's 32-bit VMOV supports splat values where:
6950 // * only one byte is nonzero, or
6951 // * the least significant byte is 0xff and the second byte is nonzero, or
6952 // * the least significant 2 bytes are 0xff and the third is nonzero.
6953 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6954 if ((SplatBits & ~0xff) == 0) {
6955 // Value = 0x000000nn: Op=x, Cmode=000x.
6956 OpCmode = 0;
6957 Imm = SplatBits;
6958 break;
6959 }
6960 if ((SplatBits & ~0xff00) == 0) {
6961 // Value = 0x0000nn00: Op=x, Cmode=001x.
6962 OpCmode = 0x2;
6963 Imm = SplatBits >> 8;
6964 break;
6965 }
6966 if ((SplatBits & ~0xff0000) == 0) {
6967 // Value = 0x00nn0000: Op=x, Cmode=010x.
6968 OpCmode = 0x4;
6969 Imm = SplatBits >> 16;
6970 break;
6971 }
6972 if ((SplatBits & ~0xff000000) == 0) {
6973 // Value = 0xnn000000: Op=x, Cmode=011x.
6974 OpCmode = 0x6;
6975 Imm = SplatBits >> 24;
6976 break;
6977 }
6978
6979 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6980 if (type == OtherModImm) return SDValue();
6981
6982 if ((SplatBits & ~0xffff) == 0 &&
6983 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6984 // Value = 0x0000nnff: Op=x, Cmode=1100.
6985 OpCmode = 0xc;
6986 Imm = SplatBits >> 8;
6987 break;
6988 }
6989
6990 // cmode == 0b1101 is not supported for MVE VMVN
6991 if (type == MVEVMVNModImm)
6992 return SDValue();
6993
6994 if ((SplatBits & ~0xffffff) == 0 &&
6995 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6996 // Value = 0x00nnffff: Op=x, Cmode=1101.
6997 OpCmode = 0xd;
6998 Imm = SplatBits >> 16;
6999 break;
7000 }
7001
7002 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
7003 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
7004 // VMOV.I32. A (very) minor optimization would be to replicate the value
7005 // and fall through here to test for a valid 64-bit splat. But, then the
7006 // caller would also need to check and handle the change in size.
7007 return SDValue();
7008
7009 case 64: {
7010 if (type != VMOVModImm)
7011 return SDValue();
7012 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
7013 uint64_t BitMask = 0xff;
7014 unsigned ImmMask = 1;
7015 Imm = 0;
7016 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
7017 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
7018 Imm |= ImmMask;
7019 } else if ((SplatBits & BitMask) != 0) {
7020 return SDValue();
7021 }
7022 BitMask <<= 8;
7023 ImmMask <<= 1;
7024 }
7025
7026 // Op=1, Cmode=1110.
7027 OpCmode = 0x1e;
7028 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
7029 break;
7030 }
7031
7032 default:
7033 llvm_unreachable("unexpected size for isVMOVModifiedImm");
7034 }
7035
7036 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
7037 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
7038}
7039
7040SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
7041 const ARMSubtarget *ST) const {
7042 EVT VT = Op.getValueType();
7043 bool IsDouble = (VT == MVT::f64);
7044 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7045 const APFloat &FPVal = CFP->getValueAPF();
7046
7047 // Prevent floating-point constants from using literal loads
7048 // when execute-only is enabled.
7049 if (ST->genExecuteOnly()) {
7050 // We shouldn't trigger this for v6m execute-only
7051 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
7052 "Unexpected architecture");
7053
7054 // If we can represent the constant as an immediate, don't lower it
7055 if (isFPImmLegal(FPVal, VT))
7056 return Op;
7057 // Otherwise, construct as integer, and move to float register
7058 APInt INTVal = FPVal.bitcastToAPInt();
7059 SDLoc DL(CFP);
7060 switch (VT.getSimpleVT().SimpleTy) {
7061 default:
7062 llvm_unreachable("Unknown floating point type!");
7063 break;
7064 case MVT::f64: {
7065 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7066 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7067 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7068 }
7069 case MVT::f32:
7070 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7071 DAG.getConstant(INTVal, DL, MVT::i32));
7072 }
7073 }
7074
7075 if (!ST->hasVFP3Base())
7076 return SDValue();
7077
7078 // Use the default (constant pool) lowering for double constants when we have
7079 // an SP-only FPU
7080 if (IsDouble && !Subtarget->hasFP64())
7081 return SDValue();
7082
7083 // Try splatting with a VMOV.f32...
7084 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7085
7086 if (ImmVal != -1) {
7087 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7088 // We have code in place to select a valid ConstantFP already, no need to
7089 // do any mangling.
7090 return Op;
7091 }
7092
7093 // It's a float and we are trying to use NEON operations where
7094 // possible. Lower it to a splat followed by an extract.
7095 SDLoc DL(Op);
7096 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7097 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7098 NewVal);
7099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7100 DAG.getConstant(0, DL, MVT::i32));
7101 }
7102
7103 // The rest of our options are NEON only, make sure that's allowed before
7104 // proceeding..
7105 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7106 return SDValue();
7107
7108 EVT VMovVT;
7109 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7110
7111 // It wouldn't really be worth bothering for doubles except for one very
7112 // important value, which does happen to match: 0.0. So make sure we don't do
7113 // anything stupid.
7114 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7115 return SDValue();
7116
7117 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7118 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7119 VMovVT, VT, VMOVModImm);
7120 if (NewVal != SDValue()) {
7121 SDLoc DL(Op);
7122 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7123 NewVal);
7124 if (IsDouble)
7125 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7126
7127 // It's a float: cast and extract a vector element.
7128 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7129 VecConstant);
7130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7131 DAG.getConstant(0, DL, MVT::i32));
7132 }
7133
7134 // Finally, try a VMVN.i32
7135 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7136 VT, VMVNModImm);
7137 if (NewVal != SDValue()) {
7138 SDLoc DL(Op);
7139 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7140
7141 if (IsDouble)
7142 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7143
7144 // It's a float: cast and extract a vector element.
7145 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7146 VecConstant);
7147 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7148 DAG.getConstant(0, DL, MVT::i32));
7149 }
7150
7151 return SDValue();
7152}
7153
7154// check if an VEXT instruction can handle the shuffle mask when the
7155// vector sources of the shuffle are the same.
7156static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7157 unsigned NumElts = VT.getVectorNumElements();
7158
7159 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7160 if (M[0] < 0)
7161 return false;
7162
7163 Imm = M[0];
7164
7165 // If this is a VEXT shuffle, the immediate value is the index of the first
7166 // element. The other shuffle indices must be the successive elements after
7167 // the first one.
7168 unsigned ExpectedElt = Imm;
7169 for (unsigned i = 1; i < NumElts; ++i) {
7170 // Increment the expected index. If it wraps around, just follow it
7171 // back to index zero and keep going.
7172 ++ExpectedElt;
7173 if (ExpectedElt == NumElts)
7174 ExpectedElt = 0;
7175
7176 if (M[i] < 0) continue; // ignore UNDEF indices
7177 if (ExpectedElt != static_cast<unsigned>(M[i]))
7178 return false;
7179 }
7180
7181 return true;
7182}
7183
7184static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7185 bool &ReverseVEXT, unsigned &Imm) {
7186 unsigned NumElts = VT.getVectorNumElements();
7187 ReverseVEXT = false;
7188
7189 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7190 if (M[0] < 0)
7191 return false;
7192
7193 Imm = M[0];
7194
7195 // If this is a VEXT shuffle, the immediate value is the index of the first
7196 // element. The other shuffle indices must be the successive elements after
7197 // the first one.
7198 unsigned ExpectedElt = Imm;
7199 for (unsigned i = 1; i < NumElts; ++i) {
7200 // Increment the expected index. If it wraps around, it may still be
7201 // a VEXT but the source vectors must be swapped.
7202 ExpectedElt += 1;
7203 if (ExpectedElt == NumElts * 2) {
7204 ExpectedElt = 0;
7205 ReverseVEXT = true;
7206 }
7207
7208 if (M[i] < 0) continue; // ignore UNDEF indices
7209 if (ExpectedElt != static_cast<unsigned>(M[i]))
7210 return false;
7211 }
7212
7213 // Adjust the index value if the source operands will be swapped.
7214 if (ReverseVEXT)
7215 Imm -= NumElts;
7216
7217 return true;
7218}
7219
7220static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7221 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7222 // range, then 0 is placed into the resulting vector. So pretty much any mask
7223 // of 8 elements can work here.
7224 return VT == MVT::v8i8 && M.size() == 8;
7225}
7226
7227/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7228/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7229static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7230 unsigned &WhichResult,
7231 bool &isV_UNDEF) {
7232 isV_UNDEF = false;
7233 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7234 return ARMISD::VTRN;
7235 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7236 return ARMISD::VUZP;
7237 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7238 return ARMISD::VZIP;
7239
7240 isV_UNDEF = true;
7241 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7242 return ARMISD::VTRN;
7243 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7244 return ARMISD::VUZP;
7245 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7246 return ARMISD::VZIP;
7247
7248 return 0;
7249}
7250
7251/// \return true if this is a reverse operation on an vector.
7252static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7253 unsigned NumElts = VT.getVectorNumElements();
7254 // Make sure the mask has the right size.
7255 if (NumElts != M.size())
7256 return false;
7257
7258 // Look for <15, ..., 3, -1, 1, 0>.
7259 for (unsigned i = 0; i != NumElts; ++i)
7260 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7261 return false;
7262
7263 return true;
7264}
7265
7266static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7267 unsigned NumElts = VT.getVectorNumElements();
7268 // Make sure the mask has the right size.
7269 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7270 return false;
7271
7272 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7273 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7274 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7275 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7276 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7277 int Ofs = Top ? 1 : 0;
7278 int Upper = SingleSource ? 0 : NumElts;
7279 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7280 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7281 return false;
7282 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7283 return false;
7284 }
7285 return true;
7286}
7287
7288static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7289 unsigned NumElts = VT.getVectorNumElements();
7290 // Make sure the mask has the right size.
7291 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7292 return false;
7293
7294 // If Top
7295 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7296 // This inserts Input2 into Input1
7297 // else if not Top
7298 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7299 // This inserts Input1 into Input2
7300 unsigned Offset = Top ? 0 : 1;
7301 unsigned N = SingleSource ? 0 : NumElts;
7302 for (unsigned i = 0; i < NumElts; i += 2) {
7303 if (M[i] >= 0 && M[i] != (int)i)
7304 return false;
7305 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7306 return false;
7307 }
7308
7309 return true;
7310}
7311
7312static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7313 unsigned NumElts = ToVT.getVectorNumElements();
7314 if (NumElts != M.size())
7315 return false;
7316
7317 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7318 // looking for patterns of:
7319 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7320 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7321
7322 unsigned Off0 = rev ? NumElts / 2 : 0;
7323 unsigned Off1 = rev ? 0 : NumElts / 2;
7324 for (unsigned i = 0; i < NumElts; i += 2) {
7325 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7326 return false;
7327 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7328 return false;
7329 }
7330
7331 return true;
7332}
7333
7334// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7335// from a pair of inputs. For example:
7336// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7337// FP_ROUND(EXTRACT_ELT(Y, 0),
7338// FP_ROUND(EXTRACT_ELT(X, 1),
7339// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7341 const ARMSubtarget *ST) {
7342 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7343 if (!ST->hasMVEFloatOps())
7344 return SDValue();
7345
7346 SDLoc dl(BV);
7347 EVT VT = BV.getValueType();
7348 if (VT != MVT::v8f16)
7349 return SDValue();
7350
7351 // We are looking for a buildvector of fptrunc elements, where all the
7352 // elements are interleavingly extracted from two sources. Check the first two
7353 // items are valid enough and extract some info from them (they are checked
7354 // properly in the loop below).
7355 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7358 return SDValue();
7359 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7362 return SDValue();
7363 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7364 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7365 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7366 return SDValue();
7367
7368 // Check all the values in the BuildVector line up with our expectations.
7369 for (unsigned i = 1; i < 4; i++) {
7370 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7371 return Trunc.getOpcode() == ISD::FP_ROUND &&
7373 Trunc.getOperand(0).getOperand(0) == Op &&
7374 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7375 };
7376 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7377 return SDValue();
7378 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7379 return SDValue();
7380 }
7381
7382 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7383 DAG.getConstant(0, dl, MVT::i32));
7384 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7385 DAG.getConstant(1, dl, MVT::i32));
7386}
7387
7388// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7389// from a single input on alternating lanes. For example:
7390// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7391// FP_ROUND(EXTRACT_ELT(X, 2),
7392// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7394 const ARMSubtarget *ST) {
7395 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7396 if (!ST->hasMVEFloatOps())
7397 return SDValue();
7398
7399 SDLoc dl(BV);
7400 EVT VT = BV.getValueType();
7401 if (VT != MVT::v4f32)
7402 return SDValue();
7403
7404 // We are looking for a buildvector of fptext elements, where all the
7405 // elements are alternating lanes from a single source. For example <0,2,4,6>
7406 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7407 // info from them (they are checked properly in the loop below).
7408 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7410 return SDValue();
7411 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7413 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7414 return SDValue();
7415
7416 // Check all the values in the BuildVector line up with our expectations.
7417 for (unsigned i = 1; i < 4; i++) {
7418 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7419 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7421 Trunc.getOperand(0).getOperand(0) == Op &&
7422 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7423 };
7424 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7425 return SDValue();
7426 }
7427
7428 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7429 DAG.getConstant(Offset, dl, MVT::i32));
7430}
7431
7432// If N is an integer constant that can be moved into a register in one
7433// instruction, return an SDValue of such a constant (will become a MOV
7434// instruction). Otherwise return null.
7436 const ARMSubtarget *ST, const SDLoc &dl) {
7437 uint64_t Val;
7438 if (!isa<ConstantSDNode>(N))
7439 return SDValue();
7440 Val = N->getAsZExtVal();
7441
7442 if (ST->isThumb1Only()) {
7443 if (Val <= 255 || ~Val <= 255)
7444 return DAG.getConstant(Val, dl, MVT::i32);
7445 } else {
7446 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7447 return DAG.getConstant(Val, dl, MVT::i32);
7448 }
7449 return SDValue();
7450}
7451
7453 const ARMSubtarget *ST) {
7454 SDLoc dl(Op);
7455 EVT VT = Op.getValueType();
7456
7457 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7458
7459 unsigned NumElts = VT.getVectorNumElements();
7460 unsigned BoolMask;
7461 unsigned BitsPerBool;
7462 if (NumElts == 2) {
7463 BitsPerBool = 8;
7464 BoolMask = 0xff;
7465 } else if (NumElts == 4) {
7466 BitsPerBool = 4;
7467 BoolMask = 0xf;
7468 } else if (NumElts == 8) {
7469 BitsPerBool = 2;
7470 BoolMask = 0x3;
7471 } else if (NumElts == 16) {
7472 BitsPerBool = 1;
7473 BoolMask = 0x1;
7474 } else
7475 return SDValue();
7476
7477 // If this is a single value copied into all lanes (a splat), we can just sign
7478 // extend that single value
7479 SDValue FirstOp = Op.getOperand(0);
7480 if (!isa<ConstantSDNode>(FirstOp) &&
7481 llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7482 return U.get().isUndef() || U.get() == FirstOp;
7483 })) {
7484 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7485 DAG.getValueType(MVT::i1));
7486 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7487 }
7488
7489 // First create base with bits set where known
7490 unsigned Bits32 = 0;
7491 for (unsigned i = 0; i < NumElts; ++i) {
7492 SDValue V = Op.getOperand(i);
7493 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7494 continue;
7495 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7496 if (BitSet)
7497 Bits32 |= BoolMask << (i * BitsPerBool);
7498 }
7499
7500 // Add in unknown nodes
7501 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7502 DAG.getConstant(Bits32, dl, MVT::i32));
7503 for (unsigned i = 0; i < NumElts; ++i) {
7504 SDValue V = Op.getOperand(i);
7505 if (isa<ConstantSDNode>(V) || V.isUndef())
7506 continue;
7507 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7508 DAG.getConstant(i, dl, MVT::i32));
7509 }
7510
7511 return Base;
7512}
7513
7515 const ARMSubtarget *ST) {
7516 if (!ST->hasMVEIntegerOps())
7517 return SDValue();
7518
7519 // We are looking for a buildvector where each element is Op[0] + i*N
7520 EVT VT = Op.getValueType();
7521 SDValue Op0 = Op.getOperand(0);
7522 unsigned NumElts = VT.getVectorNumElements();
7523
7524 // Get the increment value from operand 1
7525 SDValue Op1 = Op.getOperand(1);
7526 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7528 return SDValue();
7529 unsigned N = Op1.getConstantOperandVal(1);
7530 if (N != 1 && N != 2 && N != 4 && N != 8)
7531 return SDValue();
7532
7533 // Check that each other operand matches
7534 for (unsigned I = 2; I < NumElts; I++) {
7535 SDValue OpI = Op.getOperand(I);
7536 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7538 OpI.getConstantOperandVal(1) != I * N)
7539 return SDValue();
7540 }
7541
7542 SDLoc DL(Op);
7543 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7544 DAG.getConstant(N, DL, MVT::i32));
7545}
7546
7547// Returns true if the operation N can be treated as qr instruction variant at
7548// operand Op.
7549static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7550 switch (N->getOpcode()) {
7551 case ISD::ADD:
7552 case ISD::MUL:
7553 case ISD::SADDSAT:
7554 case ISD::UADDSAT:
7555 case ISD::AVGFLOORS:
7556 case ISD::AVGFLOORU:
7557 return true;
7558 case ISD::SUB:
7559 case ISD::SSUBSAT:
7560 case ISD::USUBSAT:
7561 return N->getOperand(1).getNode() == Op;
7563 switch (N->getConstantOperandVal(0)) {
7564 case Intrinsic::arm_mve_add_predicated:
7565 case Intrinsic::arm_mve_mul_predicated:
7566 case Intrinsic::arm_mve_qadd_predicated:
7567 case Intrinsic::arm_mve_vhadd:
7568 case Intrinsic::arm_mve_hadd_predicated:
7569 case Intrinsic::arm_mve_vqdmulh:
7570 case Intrinsic::arm_mve_qdmulh_predicated:
7571 case Intrinsic::arm_mve_vqrdmulh:
7572 case Intrinsic::arm_mve_qrdmulh_predicated:
7573 case Intrinsic::arm_mve_vqdmull:
7574 case Intrinsic::arm_mve_vqdmull_predicated:
7575 return true;
7576 case Intrinsic::arm_mve_sub_predicated:
7577 case Intrinsic::arm_mve_qsub_predicated:
7578 case Intrinsic::arm_mve_vhsub:
7579 case Intrinsic::arm_mve_hsub_predicated:
7580 return N->getOperand(2).getNode() == Op;
7581 default:
7582 return false;
7583 }
7584 default:
7585 return false;
7586 }
7587}
7588
7589// If this is a case we can't handle, return null and let the default
7590// expansion code take care of it.
7591SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7592 const ARMSubtarget *ST) const {
7593 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7594 SDLoc dl(Op);
7595 EVT VT = Op.getValueType();
7596
7597 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7598 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7599
7600 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7601 return R;
7602
7603 APInt SplatBits, SplatUndef;
7604 unsigned SplatBitSize;
7605 bool HasAnyUndefs;
7606 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7607 if (SplatUndef.isAllOnes())
7608 return DAG.getUNDEF(VT);
7609
7610 // If all the users of this constant splat are qr instruction variants,
7611 // generate a vdup of the constant.
7612 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7613 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7614 all_of(BVN->users(),
7615 [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7616 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7617 : SplatBitSize == 16 ? MVT::v8i16
7618 : MVT::v16i8;
7619 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7620 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7621 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7622 }
7623
7624 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7625 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7626 // Check if an immediate VMOV works.
7627 EVT VmovVT;
7628 SDValue Val =
7629 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7630 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7631
7632 if (Val.getNode()) {
7633 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7634 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7635 }
7636
7637 // Try an immediate VMVN.
7638 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7639 Val = isVMOVModifiedImm(
7640 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7641 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7642 if (Val.getNode()) {
7643 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7644 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7645 }
7646
7647 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7648 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7649 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7650 if (ImmVal != -1) {
7651 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7652 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7653 }
7654 }
7655
7656 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7657 // type.
7658 if (ST->hasMVEIntegerOps() &&
7659 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7660 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7661 : SplatBitSize == 16 ? MVT::v8i16
7662 : MVT::v16i8;
7663 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7664 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7665 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7666 }
7667 }
7668 }
7669
7670 // Scan through the operands to see if only one value is used.
7671 //
7672 // As an optimisation, even if more than one value is used it may be more
7673 // profitable to splat with one value then change some lanes.
7674 //
7675 // Heuristically we decide to do this if the vector has a "dominant" value,
7676 // defined as splatted to more than half of the lanes.
7677 unsigned NumElts = VT.getVectorNumElements();
7678 bool isOnlyLowElement = true;
7679 bool usesOnlyOneValue = true;
7680 bool hasDominantValue = false;
7681 bool isConstant = true;
7682
7683 // Map of the number of times a particular SDValue appears in the
7684 // element list.
7685 DenseMap<SDValue, unsigned> ValueCounts;
7686 SDValue Value;
7687 for (unsigned i = 0; i < NumElts; ++i) {
7688 SDValue V = Op.getOperand(i);
7689 if (V.isUndef())
7690 continue;
7691 if (i > 0)
7692 isOnlyLowElement = false;
7694 isConstant = false;
7695
7696 unsigned &Count = ValueCounts[V];
7697
7698 // Is this value dominant? (takes up more than half of the lanes)
7699 if (++Count > (NumElts / 2)) {
7700 hasDominantValue = true;
7701 Value = V;
7702 }
7703 }
7704 if (ValueCounts.size() != 1)
7705 usesOnlyOneValue = false;
7706 if (!Value.getNode() && !ValueCounts.empty())
7707 Value = ValueCounts.begin()->first;
7708
7709 if (ValueCounts.empty())
7710 return DAG.getUNDEF(VT);
7711
7712 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7713 // Keep going if we are hitting this case.
7714 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()) &&
7715 (VT != MVT::v8f16 || ST->hasFullFP16()))
7716 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7717
7718 unsigned EltSize = VT.getScalarSizeInBits();
7719
7720 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7721 // i32 and try again.
7722 if (hasDominantValue && EltSize <= 32) {
7723 if (!isConstant) {
7724 SDValue N;
7725
7726 // If we are VDUPing a value that comes directly from a vector, that will
7727 // cause an unnecessary move to and from a GPR, where instead we could
7728 // just use VDUPLANE. We can only do this if the lane being extracted
7729 // is at a constant index, as the VDUP from lane instructions only have
7730 // constant-index forms.
7731 ConstantSDNode *constIndex;
7732 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7733 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7734 // We need to create a new undef vector to use for the VDUPLANE if the
7735 // size of the vector from which we get the value is different than the
7736 // size of the vector that we need to create. We will insert the element
7737 // such that the register coalescer will remove unnecessary copies.
7738 if (VT != Value->getOperand(0).getValueType()) {
7739 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7741 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7742 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7743 Value, DAG.getConstant(index, dl, MVT::i32)),
7744 DAG.getConstant(index, dl, MVT::i32));
7745 } else
7746 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7747 Value->getOperand(0), Value->getOperand(1));
7748 } else
7749 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7750
7751 if (!usesOnlyOneValue) {
7752 // The dominant value was splatted as 'N', but we now have to insert
7753 // all differing elements.
7754 for (unsigned I = 0; I < NumElts; ++I) {
7755 if (Op.getOperand(I) == Value)
7756 continue;
7758 Ops.push_back(N);
7759 Ops.push_back(Op.getOperand(I));
7760 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7761 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7762 }
7763 }
7764 return N;
7765 }
7768 MVT FVT = VT.getVectorElementType().getSimpleVT();
7769 assert(FVT == MVT::f32 || FVT == MVT::f16);
7770 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7771 for (unsigned i = 0; i < NumElts; ++i)
7772 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7773 Op.getOperand(i)));
7774 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7775 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7776 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7777 if (Val.getNode())
7778 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7779 }
7780 if (usesOnlyOneValue) {
7781 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7782 if (isConstant && Val.getNode())
7783 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7784 }
7785 }
7786
7787 // If all elements are constants and the case above didn't get hit, fall back
7788 // to the default expansion, which will generate a load from the constant
7789 // pool.
7790 if (isConstant)
7791 return SDValue();
7792
7793 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7794 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7795 // length <= 2.
7796 if (NumElts >= 4)
7797 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7798 return shuffle;
7799
7800 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7801 // VCVT's
7802 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7803 return VCVT;
7804 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7805 return VCVT;
7806
7807 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7808 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7809 // into two 64-bit vectors; we might discover a better way to lower it.
7810 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7811 EVT ExtVT = VT.getVectorElementType();
7812 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7813 SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
7814 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7815 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7816 SDValue Upper =
7817 DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7818 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7819 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7820 if (Lower && Upper)
7821 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7822 }
7823
7824 // Vectors with 32- or 64-bit elements can be built by directly assigning
7825 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7826 // will be legalized.
7827 if (EltSize >= 32) {
7828 // Do the expansion with floating-point types, since that is what the VFP
7829 // registers are defined to use, and since i64 is not legal.
7830 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7831 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7833 for (unsigned i = 0; i < NumElts; ++i)
7834 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7835 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7836 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7837 }
7838
7839 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7840 // know the default expansion would otherwise fall back on something even
7841 // worse. For a vector with one or two non-undef values, that's
7842 // scalar_to_vector for the elements followed by a shuffle (provided the
7843 // shuffle is valid for the target) and materialization element by element
7844 // on the stack followed by a load for everything else.
7845 if ((!isConstant && !usesOnlyOneValue) ||
7846 (VT == MVT::v8f16 && !ST->hasFullFP16())) {
7847 SDValue Vec = DAG.getUNDEF(VT);
7848 for (unsigned i = 0 ; i < NumElts; ++i) {
7849 SDValue V = Op.getOperand(i);
7850 if (V.isUndef())
7851 continue;
7852 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7853 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7854 }
7855 return Vec;
7856 }
7857
7858 return SDValue();
7859}
7860
7861// Gather data to see if the operation can be modelled as a
7862// shuffle in combination with VEXTs.
7863SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7864 SelectionDAG &DAG) const {
7865 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7866 SDLoc dl(Op);
7867 EVT VT = Op.getValueType();
7868 unsigned NumElts = VT.getVectorNumElements();
7869
7870 struct ShuffleSourceInfo {
7871 SDValue Vec;
7872 unsigned MinElt = std::numeric_limits<unsigned>::max();
7873 unsigned MaxElt = 0;
7874
7875 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7876 // be compatible with the shuffle we intend to construct. As a result
7877 // ShuffleVec will be some sliding window into the original Vec.
7878 SDValue ShuffleVec;
7879
7880 // Code should guarantee that element i in Vec starts at element "WindowBase
7881 // + i * WindowScale in ShuffleVec".
7882 int WindowBase = 0;
7883 int WindowScale = 1;
7884
7885 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7886
7887 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7888 };
7889
7890 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7891 // node.
7893 for (unsigned i = 0; i < NumElts; ++i) {
7894 SDValue V = Op.getOperand(i);
7895 if (V.isUndef())
7896 continue;
7897 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7898 // A shuffle can only come from building a vector from various
7899 // elements of other vectors.
7900 return SDValue();
7901 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7902 // Furthermore, shuffles require a constant mask, whereas extractelts
7903 // accept variable indices.
7904 return SDValue();
7905 }
7906
7907 // Add this element source to the list if it's not already there.
7908 SDValue SourceVec = V.getOperand(0);
7909 auto Source = llvm::find(Sources, SourceVec);
7910 if (Source == Sources.end())
7911 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7912
7913 // Update the minimum and maximum lane number seen.
7914 unsigned EltNo = V.getConstantOperandVal(1);
7915 Source->MinElt = std::min(Source->MinElt, EltNo);
7916 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7917 }
7918
7919 // Currently only do something sane when at most two source vectors
7920 // are involved.
7921 if (Sources.size() > 2)
7922 return SDValue();
7923
7924 // Find out the smallest element size among result and two sources, and use
7925 // it as element size to build the shuffle_vector.
7926 EVT SmallestEltTy = VT.getVectorElementType();
7927 for (auto &Source : Sources) {
7928 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7929 if (SrcEltTy.bitsLT(SmallestEltTy))
7930 SmallestEltTy = SrcEltTy;
7931 }
7932 unsigned ResMultiplier =
7933 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7934 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7935 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7936
7937 // If the source vector is too wide or too narrow, we may nevertheless be able
7938 // to construct a compatible shuffle either by concatenating it with UNDEF or
7939 // extracting a suitable range of elements.
7940 for (auto &Src : Sources) {
7941 EVT SrcVT = Src.ShuffleVec.getValueType();
7942
7943 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7944 uint64_t VTSize = VT.getFixedSizeInBits();
7945 if (SrcVTSize == VTSize)
7946 continue;
7947
7948 // This stage of the search produces a source with the same element type as
7949 // the original, but with a total width matching the BUILD_VECTOR output.
7950 EVT EltVT = SrcVT.getVectorElementType();
7951 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7952 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7953
7954 if (SrcVTSize < VTSize) {
7955 if (2 * SrcVTSize != VTSize)
7956 return SDValue();
7957 // We can pad out the smaller vector for free, so if it's part of a
7958 // shuffle...
7959 Src.ShuffleVec =
7960 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7961 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7962 continue;
7963 }
7964
7965 if (SrcVTSize != 2 * VTSize)
7966 return SDValue();
7967
7968 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7969 // Span too large for a VEXT to cope
7970 return SDValue();
7971 }
7972
7973 if (Src.MinElt >= NumSrcElts) {
7974 // The extraction can just take the second half
7975 Src.ShuffleVec =
7976 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7977 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7978 Src.WindowBase = -NumSrcElts;
7979 } else if (Src.MaxElt < NumSrcElts) {
7980 // The extraction can just take the first half
7981 Src.ShuffleVec =
7982 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7983 DAG.getConstant(0, dl, MVT::i32));
7984 } else {
7985 // An actual VEXT is needed
7986 SDValue VEXTSrc1 =
7987 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7988 DAG.getConstant(0, dl, MVT::i32));
7989 SDValue VEXTSrc2 =
7990 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7991 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7992
7993 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7994 VEXTSrc2,
7995 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7996 Src.WindowBase = -Src.MinElt;
7997 }
7998 }
7999
8000 // Another possible incompatibility occurs from the vector element types. We
8001 // can fix this by bitcasting the source vectors to the same type we intend
8002 // for the shuffle.
8003 for (auto &Src : Sources) {
8004 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8005 if (SrcEltTy == SmallestEltTy)
8006 continue;
8007 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8008 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8009 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8010 Src.WindowBase *= Src.WindowScale;
8011 }
8012
8013 // Final check before we try to actually produce a shuffle.
8014 LLVM_DEBUG({
8015 for (auto Src : Sources)
8016 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8017 });
8018
8019 // The stars all align, our next step is to produce the mask for the shuffle.
8020 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8021 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8022 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8023 SDValue Entry = Op.getOperand(i);
8024 if (Entry.isUndef())
8025 continue;
8026
8027 auto Src = llvm::find(Sources, Entry.getOperand(0));
8028 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8029
8030 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8031 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8032 // segment.
8033 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8034 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8035 VT.getScalarSizeInBits());
8036 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8037
8038 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8039 // starting at the appropriate offset.
8040 int *LaneMask = &Mask[i * ResMultiplier];
8041
8042 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8043 ExtractBase += NumElts * (Src - Sources.begin());
8044 for (int j = 0; j < LanesDefined; ++j)
8045 LaneMask[j] = ExtractBase + j;
8046 }
8047
8048
8049 // We can't handle more than two sources. This should have already
8050 // been checked before this point.
8051 assert(Sources.size() <= 2 && "Too many sources!");
8052
8053 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8054 for (unsigned i = 0; i < Sources.size(); ++i)
8055 ShuffleOps[i] = Sources[i].ShuffleVec;
8056
8057 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8058 ShuffleOps[1], Mask, DAG);
8059 if (!Shuffle)
8060 return SDValue();
8061 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8062}
8063
8065 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8074 OP_VUZPL, // VUZP, left result
8075 OP_VUZPR, // VUZP, right result
8076 OP_VZIPL, // VZIP, left result
8077 OP_VZIPR, // VZIP, right result
8078 OP_VTRNL, // VTRN, left result
8079 OP_VTRNR // VTRN, right result
8080};
8081
8082static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8083 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8084 switch (OpNum) {
8085 case OP_COPY:
8086 case OP_VREV:
8087 case OP_VDUP0:
8088 case OP_VDUP1:
8089 case OP_VDUP2:
8090 case OP_VDUP3:
8091 return true;
8092 }
8093 return false;
8094}
8095
8096/// isShuffleMaskLegal - Targets can use this to indicate that they only
8097/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8098/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8099/// are assumed to be legal.
8101 if (VT.getVectorNumElements() == 4 &&
8102 (VT.is128BitVector() || VT.is64BitVector())) {
8103 unsigned PFIndexes[4];
8104 for (unsigned i = 0; i != 4; ++i) {
8105 if (M[i] < 0)
8106 PFIndexes[i] = 8;
8107 else
8108 PFIndexes[i] = M[i];
8109 }
8110
8111 // Compute the index in the perfect shuffle table.
8112 unsigned PFTableIndex =
8113 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8114 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8115 unsigned Cost = (PFEntry >> 30);
8116
8117 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8118 return true;
8119 }
8120
8121 bool ReverseVEXT, isV_UNDEF;
8122 unsigned Imm, WhichResult;
8123
8124 unsigned EltSize = VT.getScalarSizeInBits();
8125 if (EltSize >= 32 ||
8127 ShuffleVectorInst::isIdentityMask(M, M.size()) ||
8128 isVREVMask(M, VT, 64) ||
8129 isVREVMask(M, VT, 32) ||
8130 isVREVMask(M, VT, 16))
8131 return true;
8132 else if (Subtarget->hasNEON() &&
8133 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8134 isVTBLMask(M, VT) ||
8135 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8136 return true;
8137 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8138 isReverseMask(M, VT))
8139 return true;
8140 else if (Subtarget->hasMVEIntegerOps() &&
8141 (isVMOVNMask(M, VT, true, false) ||
8142 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8143 return true;
8144 else if (Subtarget->hasMVEIntegerOps() &&
8145 (isTruncMask(M, VT, false, false) ||
8146 isTruncMask(M, VT, false, true) ||
8147 isTruncMask(M, VT, true, false) || isTruncMask(M, VT, true, true)))
8148 return true;
8149 else
8150 return false;
8151}
8152
8153/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8154/// the specified operations to build the shuffle.
8156 SDValue RHS, SelectionDAG &DAG,
8157 const SDLoc &dl) {
8158 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8159 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8160 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8161
8162 if (OpNum == OP_COPY) {
8163 if (LHSID == (1*9+2)*9+3) return LHS;
8164 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8165 return RHS;
8166 }
8167
8168 SDValue OpLHS, OpRHS;
8169 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8170 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8171 EVT VT = OpLHS.getValueType();
8172
8173 switch (OpNum) {
8174 default: llvm_unreachable("Unknown shuffle opcode!");
8175 case OP_VREV:
8176 // VREV divides the vector in half and swaps within the half.
8177 if (VT.getScalarSizeInBits() == 32)
8178 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8179 // vrev <4 x i16> -> VREV32
8180 if (VT.getScalarSizeInBits() == 16)
8181 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8182 // vrev <4 x i8> -> VREV16
8183 assert(VT.getScalarSizeInBits() == 8);
8184 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8185 case OP_VDUP0:
8186 case OP_VDUP1:
8187 case OP_VDUP2:
8188 case OP_VDUP3:
8189 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8190 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8191 case OP_VEXT1:
8192 case OP_VEXT2:
8193 case OP_VEXT3:
8194 return DAG.getNode(ARMISD::VEXT, dl, VT,
8195 OpLHS, OpRHS,
8196 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8197 case OP_VUZPL:
8198 case OP_VUZPR:
8199 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8200 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8201 case OP_VZIPL:
8202 case OP_VZIPR:
8203 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8204 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8205 case OP_VTRNL:
8206 case OP_VTRNR:
8207 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8208 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8209 }
8210}
8211
8213 ArrayRef<int> ShuffleMask,
8214 SelectionDAG &DAG) {
8215 // Check to see if we can use the VTBL instruction.
8216 SDValue V1 = Op.getOperand(0);
8217 SDValue V2 = Op.getOperand(1);
8218 SDLoc DL(Op);
8219
8220 SmallVector<SDValue, 8> VTBLMask;
8221 for (int I : ShuffleMask)
8222 VTBLMask.push_back(DAG.getSignedConstant(I, DL, MVT::i32));
8223
8224 if (V2.getNode()->isUndef())
8225 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8226 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8227
8228 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8229 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8230}
8231
8233 SDLoc DL(Op);
8234 EVT VT = Op.getValueType();
8235
8236 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8237 "Expect an v8i16/v16i8 type");
8238 SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8239 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8240 // extract the first 8 bytes into the top double word and the last 8 bytes
8241 // into the bottom double word, through a new vector shuffle that will be
8242 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8243 std::vector<int> NewMask;
8244 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8245 NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8246 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8247 NewMask.push_back(i);
8248 return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8249}
8250
8252 switch (VT.getSimpleVT().SimpleTy) {
8253 case MVT::v2i1:
8254 return MVT::v2f64;
8255 case MVT::v4i1:
8256 return MVT::v4i32;
8257 case MVT::v8i1:
8258 return MVT::v8i16;
8259 case MVT::v16i1:
8260 return MVT::v16i8;
8261 default:
8262 llvm_unreachable("Unexpected vector predicate type");
8263 }
8264}
8265
8267 SelectionDAG &DAG) {
8268 // Converting from boolean predicates to integers involves creating a vector
8269 // of all ones or all zeroes and selecting the lanes based upon the real
8270 // predicate.
8272 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8273 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8274
8275 SDValue AllZeroes =
8276 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8277 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8278
8279 // Get full vector type from predicate type
8281
8282 SDValue RecastV1;
8283 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8284 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8285 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8286 // since we know in hardware the sizes are really the same.
8287 if (VT != MVT::v16i1)
8288 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8289 else
8290 RecastV1 = Pred;
8291
8292 // Select either all ones or zeroes depending upon the real predicate bits.
8293 SDValue PredAsVector =
8294 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8295
8296 // Recast our new predicate-as-integer v16i8 vector into something
8297 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8298 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8299}
8300
8302 const ARMSubtarget *ST) {
8303 EVT VT = Op.getValueType();
8305 ArrayRef<int> ShuffleMask = SVN->getMask();
8306
8307 assert(ST->hasMVEIntegerOps() &&
8308 "No support for vector shuffle of boolean predicates");
8309
8310 SDValue V1 = Op.getOperand(0);
8311 SDValue V2 = Op.getOperand(1);
8312 SDLoc dl(Op);
8313 if (isReverseMask(ShuffleMask, VT)) {
8314 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8315 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8316 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8317 DAG.getConstant(16, dl, MVT::i32));
8318 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8319 }
8320
8321 // Until we can come up with optimised cases for every single vector
8322 // shuffle in existence we have chosen the least painful strategy. This is
8323 // to essentially promote the boolean predicate to a 8-bit integer, where
8324 // each predicate represents a byte. Then we fall back on a normal integer
8325 // vector shuffle and convert the result back into a predicate vector. In
8326 // many cases the generated code might be even better than scalar code
8327 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8328 // fields in a register into 8 other arbitrary 2-bit fields!
8329 SDValue PredAsVector1 = PromoteMVEPredVector(dl, V1, VT, DAG);
8330 EVT NewVT = PredAsVector1.getValueType();
8331 SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(NewVT)
8332 : PromoteMVEPredVector(dl, V2, VT, DAG);
8333 assert(PredAsVector2.getValueType() == NewVT &&
8334 "Expected identical vector type in expanded i1 shuffle!");
8335
8336 // Do the shuffle!
8337 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector1,
8338 PredAsVector2, ShuffleMask);
8339
8340 // Now return the result of comparing the shuffled vector with zero,
8341 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8342 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8343 if (VT == MVT::v2i1) {
8344 SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8345 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8346 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8347 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8348 }
8349 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8350 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8351}
8352
8354 ArrayRef<int> ShuffleMask,
8355 SelectionDAG &DAG) {
8356 // Attempt to lower the vector shuffle using as many whole register movs as
8357 // possible. This is useful for types smaller than 32bits, which would
8358 // often otherwise become a series for grp movs.
8359 SDLoc dl(Op);
8360 EVT VT = Op.getValueType();
8361 if (VT.getScalarSizeInBits() >= 32)
8362 return SDValue();
8363
8364 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8365 "Unexpected vector type");
8366 int NumElts = VT.getVectorNumElements();
8367 int QuarterSize = NumElts / 4;
8368 // The four final parts of the vector, as i32's
8369 SDValue Parts[4];
8370
8371 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8372 // <u,u,u,u>), returning the vmov lane index
8373 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8374 // Detect which mov lane this would be from the first non-undef element.
8375 int MovIdx = -1;
8376 for (int i = 0; i < Length; i++) {
8377 if (ShuffleMask[Start + i] >= 0) {
8378 if (ShuffleMask[Start + i] % Length != i)
8379 return -1;
8380 MovIdx = ShuffleMask[Start + i] / Length;
8381 break;
8382 }
8383 }
8384 // If all items are undef, leave this for other combines
8385 if (MovIdx == -1)
8386 return -1;
8387 // Check the remaining values are the correct part of the same mov
8388 for (int i = 1; i < Length; i++) {
8389 if (ShuffleMask[Start + i] >= 0 &&
8390 (ShuffleMask[Start + i] / Length != MovIdx ||
8391 ShuffleMask[Start + i] % Length != i))
8392 return -1;
8393 }
8394 return MovIdx;
8395 };
8396
8397 for (int Part = 0; Part < 4; ++Part) {
8398 // Does this part look like a mov
8399 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8400 if (Elt != -1) {
8401 SDValue Input = Op->getOperand(0);
8402 if (Elt >= 4) {
8403 Input = Op->getOperand(1);
8404 Elt -= 4;
8405 }
8406 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8407 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8408 DAG.getConstant(Elt, dl, MVT::i32));
8409 }
8410 }
8411
8412 // Nothing interesting found, just return
8413 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8414 return SDValue();
8415
8416 // The other parts need to be built with the old shuffle vector, cast to a
8417 // v4i32 and extract_vector_elts
8418 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8419 SmallVector<int, 16> NewShuffleMask;
8420 for (int Part = 0; Part < 4; ++Part)
8421 for (int i = 0; i < QuarterSize; i++)
8422 NewShuffleMask.push_back(
8423 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8424 SDValue NewShuffle = DAG.getVectorShuffle(
8425 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8426 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8427
8428 for (int Part = 0; Part < 4; ++Part)
8429 if (!Parts[Part])
8430 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8431 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8432 }
8433 // Build a vector out of the various parts and bitcast it back to the original
8434 // type.
8435 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8436 return DAG.getBitcast(VT, NewVec);
8437}
8438
8440 ArrayRef<int> ShuffleMask,
8441 SelectionDAG &DAG) {
8442 SDValue V1 = Op.getOperand(0);
8443 SDValue V2 = Op.getOperand(1);
8444 EVT VT = Op.getValueType();
8445 unsigned NumElts = VT.getVectorNumElements();
8446
8447 // An One-Off Identity mask is one that is mostly an identity mask from as
8448 // single source but contains a single element out-of-place, either from a
8449 // different vector or from another position in the same vector. As opposed to
8450 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8451 // pair directly.
8452 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8453 int &OffElement) {
8454 OffElement = -1;
8455 int NonUndef = 0;
8456 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8457 if (Mask[i] == -1)
8458 continue;
8459 NonUndef++;
8460 if (Mask[i] != i + BaseOffset) {
8461 if (OffElement == -1)
8462 OffElement = i;
8463 else
8464 return false;
8465 }
8466 }
8467 return NonUndef > 2 && OffElement != -1;
8468 };
8469 int OffElement;
8470 SDValue VInput;
8471 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8472 VInput = V1;
8473 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8474 VInput = V2;
8475 else
8476 return SDValue();
8477
8478 SDLoc dl(Op);
8479 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8480 ? MVT::i32
8481 : VT.getScalarType();
8482 SDValue Elt = DAG.getNode(
8483 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8484 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8485 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8486 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8487 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8488}
8489
8491 const ARMSubtarget *ST) {
8492 SDValue V1 = Op.getOperand(0);
8493 SDValue V2 = Op.getOperand(1);
8494 SDLoc dl(Op);
8495 EVT VT = Op.getValueType();
8497 unsigned EltSize = VT.getScalarSizeInBits();
8498
8499 if (ST->hasMVEIntegerOps() && EltSize == 1)
8500 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8501
8502 // Convert shuffles that are directly supported on NEON to target-specific
8503 // DAG nodes, instead of keeping them as shuffles and matching them again
8504 // during code selection. This is more efficient and avoids the possibility
8505 // of inconsistencies between legalization and selection.
8506 // FIXME: floating-point vectors should be canonicalized to integer vectors
8507 // of the same time so that they get CSEd properly.
8508 ArrayRef<int> ShuffleMask = SVN->getMask();
8509
8510 if (EltSize <= 32) {
8511 if (SVN->isSplat()) {
8512 int Lane = SVN->getSplatIndex();
8513 // If this is undef splat, generate it via "just" vdup, if possible.
8514 if (Lane == -1) Lane = 0;
8515
8516 // Test if V1 is a SCALAR_TO_VECTOR.
8517 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8518 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8519 }
8520 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8521 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8522 // reaches it).
8523 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8524 !isa<ConstantSDNode>(V1.getOperand(0))) {
8525 bool IsScalarToVector = true;
8526 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8527 if (!V1.getOperand(i).isUndef()) {
8528 IsScalarToVector = false;
8529 break;
8530 }
8531 if (IsScalarToVector)
8532 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8533 }
8534 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8535 DAG.getConstant(Lane, dl, MVT::i32));
8536 }
8537
8538 bool ReverseVEXT = false;
8539 unsigned Imm = 0;
8540 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8541 if (ReverseVEXT)
8542 std::swap(V1, V2);
8543 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8544 DAG.getConstant(Imm, dl, MVT::i32));
8545 }
8546
8547 if (isVREVMask(ShuffleMask, VT, 64))
8548 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8549 if (isVREVMask(ShuffleMask, VT, 32))
8550 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8551 if (isVREVMask(ShuffleMask, VT, 16))
8552 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8553
8554 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8555 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8556 DAG.getConstant(Imm, dl, MVT::i32));
8557 }
8558
8559 // Check for Neon shuffles that modify both input vectors in place.
8560 // If both results are used, i.e., if there are two shuffles with the same
8561 // source operands and with masks corresponding to both results of one of
8562 // these operations, DAG memoization will ensure that a single node is
8563 // used for both shuffles.
8564 unsigned WhichResult = 0;
8565 bool isV_UNDEF = false;
8566 if (ST->hasNEON()) {
8567 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8568 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8569 if (isV_UNDEF)
8570 V2 = V1;
8571 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8572 .getValue(WhichResult);
8573 }
8574 }
8575 if (ST->hasMVEIntegerOps()) {
8576 if (isVMOVNMask(ShuffleMask, VT, false, false))
8577 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8578 DAG.getConstant(0, dl, MVT::i32));
8579 if (isVMOVNMask(ShuffleMask, VT, true, false))
8580 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8581 DAG.getConstant(1, dl, MVT::i32));
8582 if (isVMOVNMask(ShuffleMask, VT, true, true))
8583 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8584 DAG.getConstant(1, dl, MVT::i32));
8585 }
8586
8587 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8588 // shuffles that produce a result larger than their operands with:
8589 // shuffle(concat(v1, undef), concat(v2, undef))
8590 // ->
8591 // shuffle(concat(v1, v2), undef)
8592 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8593 //
8594 // This is useful in the general case, but there are special cases where
8595 // native shuffles produce larger results: the two-result ops.
8596 //
8597 // Look through the concat when lowering them:
8598 // shuffle(concat(v1, v2), undef)
8599 // ->
8600 // concat(VZIP(v1, v2):0, :1)
8601 //
8602 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8603 SDValue SubV1 = V1->getOperand(0);
8604 SDValue SubV2 = V1->getOperand(1);
8605 EVT SubVT = SubV1.getValueType();
8606
8607 // We expect these to have been canonicalized to -1.
8608 assert(llvm::all_of(ShuffleMask, [&](int i) {
8609 return i < (int)VT.getVectorNumElements();
8610 }) && "Unexpected shuffle index into UNDEF operand!");
8611
8612 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8613 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8614 if (isV_UNDEF)
8615 SubV2 = SubV1;
8616 assert((WhichResult == 0) &&
8617 "In-place shuffle of concat can only have one result!");
8618 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8619 SubV1, SubV2);
8620 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8621 Res.getValue(1));
8622 }
8623 }
8624 }
8625
8626 if (ST->hasMVEIntegerOps() && EltSize <= 32 &&
8627 (ST->hasFullFP16() || VT != MVT::v8f16)) {
8628 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8629 return V;
8630
8631 for (bool Top : {false, true}) {
8632 for (bool SingleSource : {false, true}) {
8633 if (isTruncMask(ShuffleMask, VT, Top, SingleSource)) {
8634 MVT FromSVT = MVT::getIntegerVT(EltSize * 2);
8635 MVT FromVT = MVT::getVectorVT(FromSVT, ShuffleMask.size() / 2);
8636 SDValue Lo = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT, V1);
8637 SDValue Hi = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT,
8638 SingleSource ? V1 : V2);
8639 if (Top) {
8640 SDValue Amt = DAG.getConstant(EltSize, dl, FromVT);
8641 Lo = DAG.getNode(ISD::SRL, dl, FromVT, Lo, Amt);
8642 Hi = DAG.getNode(ISD::SRL, dl, FromVT, Hi, Amt);
8643 }
8644 return DAG.getNode(ARMISD::MVETRUNC, dl, VT, Lo, Hi);
8645 }
8646 }
8647 }
8648 }
8649
8650 // If the shuffle is not directly supported and it has 4 elements, use
8651 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8652 unsigned NumElts = VT.getVectorNumElements();
8653 if (NumElts == 4) {
8654 unsigned PFIndexes[4];
8655 for (unsigned i = 0; i != 4; ++i) {
8656 if (ShuffleMask[i] < 0)
8657 PFIndexes[i] = 8;
8658 else
8659 PFIndexes[i] = ShuffleMask[i];
8660 }
8661
8662 // Compute the index in the perfect shuffle table.
8663 unsigned PFTableIndex =
8664 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8665 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8666 unsigned Cost = (PFEntry >> 30);
8667
8668 if (Cost <= 4) {
8669 if (ST->hasNEON())
8670 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8671 else if (isLegalMVEShuffleOp(PFEntry)) {
8672 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8673 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8674 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8675 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8676 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8677 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8678 }
8679 }
8680 }
8681
8682 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8683 if (EltSize >= 32) {
8684 // Do the expansion with floating-point types, since that is what the VFP
8685 // registers are defined to use, and since i64 is not legal.
8686 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8687 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8688 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8689 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8691 for (unsigned i = 0; i < NumElts; ++i) {
8692 if (ShuffleMask[i] < 0)
8693 Ops.push_back(DAG.getUNDEF(EltVT));
8694 else
8695 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8696 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8697 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8698 dl, MVT::i32)));
8699 }
8700 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8701 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8702 }
8703
8704 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8705 isReverseMask(ShuffleMask, VT))
8706 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8707
8708 if (ST->hasNEON() && VT == MVT::v8i8)
8709 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8710 return NewOp;
8711
8712 if (ST->hasMVEIntegerOps())
8713 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8714 return NewOp;
8715
8716 // Lower v8f16 via v8i16 to avoid invalid f16 nodes.
8717 if (VT == MVT::v8f16 && !ST->hasFullFP16()) {
8718 SDValue BC0 =
8719 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v8i16, Op.getOperand(0));
8720 SDValue BC1 =
8721 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v8i16, Op.getOperand(1));
8722 SDValue Shuf = DAG.getVectorShuffle(MVT::v8i16, dl, BC0, BC1, ShuffleMask);
8723 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuf);
8724 }
8725
8726 return SDValue();
8727}
8728
8730 const ARMSubtarget *ST) {
8731 EVT VecVT = Op.getOperand(0).getValueType();
8732 SDLoc dl(Op);
8733
8734 assert(ST->hasMVEIntegerOps() &&
8735 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8736
8737 SDValue Conv =
8738 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8739 unsigned Lane = Op.getConstantOperandVal(2);
8740 unsigned LaneWidth =
8742 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8743 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8744 Op.getOperand(1), DAG.getValueType(MVT::i1));
8745 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8746 DAG.getConstant(~Mask, dl, MVT::i32));
8747 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8748}
8749
8750SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8751 SelectionDAG &DAG) const {
8752 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8753 SDValue Lane = Op.getOperand(2);
8754 if (!isa<ConstantSDNode>(Lane))
8755 return SDValue();
8756
8757 SDValue Elt = Op.getOperand(1);
8758 EVT EltVT = Elt.getValueType();
8759
8760 if (Subtarget->hasMVEIntegerOps() &&
8761 Op.getValueType().getScalarSizeInBits() == 1)
8762 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8763
8764 if (getTypeAction(*DAG.getContext(), EltVT) ==
8766 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8767 // but the type system will try to do that if we don't intervene.
8768 // Reinterpret any such vector-element insertion as one with the
8769 // corresponding integer types.
8770
8771 SDLoc dl(Op);
8772
8773 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8774 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8776
8777 SDValue VecIn = Op.getOperand(0);
8778 EVT VecVT = VecIn.getValueType();
8779 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8780 VecVT.getVectorNumElements());
8781
8782 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8783 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8784 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8785 IVecIn, IElt, Lane);
8786 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8787 }
8788
8789 return Op;
8790}
8791
8793 const ARMSubtarget *ST) {
8794 EVT VecVT = Op.getOperand(0).getValueType();
8795 SDLoc dl(Op);
8796
8797 assert(ST->hasMVEIntegerOps() &&
8798 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8799
8800 SDValue Conv =
8801 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8802 unsigned Lane = Op.getConstantOperandVal(1);
8803 unsigned LaneWidth =
8805 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8806 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8807 return Shift;
8808}
8809
8811 const ARMSubtarget *ST) {
8812 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8813 SDValue Lane = Op.getOperand(1);
8814 if (!isa<ConstantSDNode>(Lane))
8815 return SDValue();
8816
8817 SDValue Vec = Op.getOperand(0);
8818 EVT VT = Vec.getValueType();
8819
8820 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8821 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8822
8823 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8824 SDLoc dl(Op);
8825 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8826 }
8827
8828 return Op;
8829}
8830
8832 const ARMSubtarget *ST) {
8833 SDLoc dl(Op);
8834 assert(Op.getValueType().getScalarSizeInBits() == 1 &&
8835 "Unexpected custom CONCAT_VECTORS lowering");
8836 assert(isPowerOf2_32(Op.getNumOperands()) &&
8837 "Unexpected custom CONCAT_VECTORS lowering");
8838 assert(ST->hasMVEIntegerOps() &&
8839 "CONCAT_VECTORS lowering only supported for MVE");
8840
8841 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8842 EVT Op1VT = V1.getValueType();
8843 EVT Op2VT = V2.getValueType();
8844 assert(Op1VT == Op2VT && "Operand types don't match!");
8845 assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
8846 "Unexpected i1 concat operations!");
8847 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
8848
8849 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8850 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8851
8852 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8853 // promoted to v8i16, etc.
8854 MVT ElType =
8856 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8857
8858 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8859 if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
8860 // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
8861 // ConcatVT.
8862 SDValue ConVec =
8863 DAG.getNode(ARMISD::MVETRUNC, dl, ConcatVT, NewV1, NewV2);
8864 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8865 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8866 }
8867
8868 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8869 // to be the right size for the destination. For example, if Op1 is v4i1
8870 // then the promoted vector is v4i32. The result of concatenation gives a
8871 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8872 // needs truncating to i16 and inserting in the result.
8873 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8874 EVT NewVT = NewV.getValueType();
8875 EVT ConcatVT = ConVec.getValueType();
8876 unsigned ExtScale = 1;
8877 if (NewVT == MVT::v2f64) {
8878 NewV = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, NewV);
8879 ExtScale = 2;
8880 }
8881 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8882 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8883 DAG.getIntPtrConstant(i * ExtScale, dl));
8884 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8885 DAG.getConstant(j, dl, MVT::i32));
8886 }
8887 return ConVec;
8888 };
8889 unsigned j = 0;
8890 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8891 ConVec = ExtractInto(NewV1, ConVec, j);
8892 ConVec = ExtractInto(NewV2, ConVec, j);
8893
8894 // Now return the result of comparing the subvector with zero, which will
8895 // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8896 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8897 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8898 };
8899
8900 // Concat each pair of subvectors and pack into the lower half of the array.
8901 SmallVector<SDValue> ConcatOps(Op->ops());
8902 while (ConcatOps.size() > 1) {
8903 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8904 SDValue V1 = ConcatOps[I];
8905 SDValue V2 = ConcatOps[I + 1];
8906 ConcatOps[I / 2] = ConcatPair(V1, V2);
8907 }
8908 ConcatOps.resize(ConcatOps.size() / 2);
8909 }
8910 return ConcatOps[0];
8911}
8912
8914 const ARMSubtarget *ST) {
8915 EVT VT = Op->getValueType(0);
8916 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8917 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8918
8919 // The only time a CONCAT_VECTORS operation can have legal types is when
8920 // two 64-bit vectors are concatenated to a 128-bit vector.
8921 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8922 "unexpected CONCAT_VECTORS");
8923 SDLoc dl(Op);
8924 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8925 SDValue Op0 = Op.getOperand(0);
8926 SDValue Op1 = Op.getOperand(1);
8927 if (!Op0.isUndef())
8928 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8929 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8930 DAG.getIntPtrConstant(0, dl));
8931 if (!Op1.isUndef())
8932 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8933 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8934 DAG.getIntPtrConstant(1, dl));
8935 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8936}
8937
8939 const ARMSubtarget *ST) {
8940 SDValue V1 = Op.getOperand(0);
8941 SDValue V2 = Op.getOperand(1);
8942 SDLoc dl(Op);
8943 EVT VT = Op.getValueType();
8944 EVT Op1VT = V1.getValueType();
8945 unsigned NumElts = VT.getVectorNumElements();
8946 unsigned Index = V2->getAsZExtVal();
8947
8948 assert(VT.getScalarSizeInBits() == 1 &&
8949 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8950 assert(ST->hasMVEIntegerOps() &&
8951 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8952
8953 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8954
8955 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8956 // promoted to v8i16, etc.
8957
8959
8960 if (NumElts == 2) {
8961 EVT SubVT = MVT::v4i32;
8962 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8963 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
8964 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8965 DAG.getIntPtrConstant(i, dl));
8966 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8967 DAG.getConstant(j, dl, MVT::i32));
8968 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8969 DAG.getConstant(j + 1, dl, MVT::i32));
8970 }
8971 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
8972 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8973 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8974 }
8975
8976 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8977 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8978 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8979 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8980 DAG.getIntPtrConstant(i, dl));
8981 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8982 DAG.getConstant(j, dl, MVT::i32));
8983 }
8984
8985 // Now return the result of comparing the subvector with zero,
8986 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8987 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8988 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8989}
8990
8991// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
8993 const ARMSubtarget *ST) {
8994 assert(ST->hasMVEIntegerOps() && "Expected MVE!");
8995 EVT VT = N->getValueType(0);
8996 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
8997 "Expected a vector i1 type!");
8998 SDValue Op = N->getOperand(0);
8999 EVT FromVT = Op.getValueType();
9000 SDLoc DL(N);
9001
9002 SDValue And =
9003 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9004 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9005 DAG.getCondCode(ISD::SETNE));
9006}
9007
9009 const ARMSubtarget *Subtarget) {
9010 if (!Subtarget->hasMVEIntegerOps())
9011 return SDValue();
9012
9013 EVT ToVT = N->getValueType(0);
9014 if (ToVT.getScalarType() == MVT::i1)
9015 return LowerTruncatei1(N, DAG, Subtarget);
9016
9017 // MVE does not have a single instruction to perform the truncation of a v4i32
9018 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9019 // Most of the instructions in MVE follow the 'Beats' system, where moving
9020 // values from different lanes is usually something that the instructions
9021 // avoid.
9022 //
9023 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9024 // which take a the top/bottom half of a larger lane and extend it (or do the
9025 // opposite, truncating into the top/bottom lane from a larger lane). Note
9026 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9027 // bottom 16bits from each vector lane. This works really well with T/B
9028 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9029 // to move order.
9030 //
9031 // But truncates and sext/zext are always going to be fairly common from llvm.
9032 // We have several options for how to deal with them:
9033 // - Wherever possible combine them into an instruction that makes them
9034 // "free". This includes loads/stores, which can perform the trunc as part
9035 // of the memory operation. Or certain shuffles that can be turned into
9036 // VMOVN/VMOVL.
9037 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9038 // trunc(mul(sext(a), sext(b))) may become
9039 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9040 // this case can use VMULL). This is performed in the
9041 // MVELaneInterleavingPass.
9042 // - Otherwise we have an option. By default we would expand the
9043 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9044 // registers. One for each vector lane in the vector. This can obviously be
9045 // very expensive.
9046 // - The other option is to use the fact that loads/store can extend/truncate
9047 // to turn a trunc into two truncating stack stores and a stack reload. This
9048 // becomes 3 back-to-back memory operations, but at least that is less than
9049 // all the insert/extracts.
9050 //
9051 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9052 // are either optimized where they can be, or eventually lowered into stack
9053 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9054 // two early, where other instructions would be better, and stops us from
9055 // having to reconstruct multiple buildvector shuffles into loads/stores.
9056 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9057 return SDValue();
9058 EVT FromVT = N->getOperand(0).getValueType();
9059 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9060 return SDValue();
9061
9062 SDValue Lo, Hi;
9063 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9064 SDLoc DL(N);
9065 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9066}
9067
9069 const ARMSubtarget *Subtarget) {
9070 if (!Subtarget->hasMVEIntegerOps())
9071 return SDValue();
9072
9073 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9074
9075 EVT ToVT = N->getValueType(0);
9076 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9077 return SDValue();
9078 SDValue Op = N->getOperand(0);
9079 EVT FromVT = Op.getValueType();
9080 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9081 return SDValue();
9082
9083 SDLoc DL(N);
9084 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9085 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9086 ExtVT = MVT::v8i16;
9087
9088 unsigned Opcode =
9090 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9091 SDValue Ext1 = Ext.getValue(1);
9092
9093 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9094 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9095 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9096 }
9097
9098 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9099}
9100
9101/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9102/// element has been zero/sign-extended, depending on the isSigned parameter,
9103/// from an integer type half its size.
9105 bool isSigned) {
9106 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9107 EVT VT = N->getValueType(0);
9108 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9109 SDNode *BVN = N->getOperand(0).getNode();
9110 if (BVN->getValueType(0) != MVT::v4i32 ||
9111 BVN->getOpcode() != ISD::BUILD_VECTOR)
9112 return false;
9113 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9114 unsigned HiElt = 1 - LoElt;
9119 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9120 return false;
9121 if (isSigned) {
9122 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9123 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9124 return true;
9125 } else {
9126 if (Hi0->isZero() && Hi1->isZero())
9127 return true;
9128 }
9129 return false;
9130 }
9131
9132 if (N->getOpcode() != ISD::BUILD_VECTOR)
9133 return false;
9134
9135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9136 SDNode *Elt = N->getOperand(i).getNode();
9138 unsigned EltSize = VT.getScalarSizeInBits();
9139 unsigned HalfSize = EltSize / 2;
9140 if (isSigned) {
9141 if (!isIntN(HalfSize, C->getSExtValue()))
9142 return false;
9143 } else {
9144 if (!isUIntN(HalfSize, C->getZExtValue()))
9145 return false;
9146 }
9147 continue;
9148 }
9149 return false;
9150 }
9151
9152 return true;
9153}
9154
9155/// isSignExtended - Check if a node is a vector value that is sign-extended
9156/// or a constant BUILD_VECTOR with sign-extended elements.
9158 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9159 return true;
9160 if (isExtendedBUILD_VECTOR(N, DAG, true))
9161 return true;
9162 return false;
9163}
9164
9165/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9166/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9168 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9170 return true;
9171 if (isExtendedBUILD_VECTOR(N, DAG, false))
9172 return true;
9173 return false;
9174}
9175
9176static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9177 if (OrigVT.getSizeInBits() >= 64)
9178 return OrigVT;
9179
9180 assert(OrigVT.isSimple() && "Expecting a simple value type");
9181
9182 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9183 switch (OrigSimpleTy) {
9184 default: llvm_unreachable("Unexpected Vector Type");
9185 case MVT::v2i8:
9186 case MVT::v2i16:
9187 return MVT::v2i32;
9188 case MVT::v4i8:
9189 return MVT::v4i16;
9190 }
9191}
9192
9193/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9194/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9195/// We insert the required extension here to get the vector to fill a D register.
9197 const EVT &OrigTy,
9198 const EVT &ExtTy,
9199 unsigned ExtOpcode) {
9200 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9201 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9202 // 64-bits we need to insert a new extension so that it will be 64-bits.
9203 assert(ExtTy.is128BitVector() && "Unexpected extension size");
9204 if (OrigTy.getSizeInBits() >= 64)
9205 return N;
9206
9207 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9208 EVT NewVT = getExtensionTo64Bits(OrigTy);
9209
9210 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9211}
9212
9213/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9214/// does not do any sign/zero extension. If the original vector is less
9215/// than 64 bits, an appropriate extension will be added after the load to
9216/// reach a total size of 64 bits. We have to add the extension separately
9217/// because ARM does not have a sign/zero extending load for vectors.
9219 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9220
9221 // The load already has the right type.
9222 if (ExtendedTy == LD->getMemoryVT())
9223 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9224 LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9225 LD->getMemOperand()->getFlags());
9226
9227 // We need to create a zextload/sextload. We cannot just create a load
9228 // followed by a zext/zext node because LowerMUL is also run during normal
9229 // operation legalization where we can't create illegal types.
9230 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9231 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9232 LD->getMemoryVT(), LD->getAlign(),
9233 LD->getMemOperand()->getFlags());
9234}
9235
9236/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9237/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9238/// the unextended value. The unextended vector should be 64 bits so that it can
9239/// be used as an operand to a VMULL instruction. If the original vector size
9240/// before extension is less than 64 bits we add a an extension to resize
9241/// the vector to 64 bits.
9243 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9244 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9245 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9246 N->getOperand(0)->getValueType(0),
9247 N->getValueType(0),
9248 N->getOpcode());
9249
9250 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9251 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9252 "Expected extending load");
9253
9254 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9255 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9256 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9257 SDValue extLoad =
9258 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9259 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9260
9261 return newLoad;
9262 }
9263
9264 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9265 // have been legalized as a BITCAST from v4i32.
9266 if (N->getOpcode() == ISD::BITCAST) {
9267 SDNode *BVN = N->getOperand(0).getNode();
9269 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9270 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9271 return DAG.getBuildVector(
9272 MVT::v2i32, SDLoc(N),
9273 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9274 }
9275 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9276 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9277 EVT VT = N->getValueType(0);
9278 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9279 unsigned NumElts = VT.getVectorNumElements();
9280 MVT TruncVT = MVT::getIntegerVT(EltSize);
9282 SDLoc dl(N);
9283 for (unsigned i = 0; i != NumElts; ++i) {
9284 const APInt &CInt = N->getConstantOperandAPInt(i);
9285 // Element types smaller than 32 bits are not legal, so use i32 elements.
9286 // The values are implicitly truncated so sext vs. zext doesn't matter.
9287 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9288 }
9289 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9290}
9291
9292static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9293 unsigned Opcode = N->getOpcode();
9294 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9295 SDNode *N0 = N->getOperand(0).getNode();
9296 SDNode *N1 = N->getOperand(1).getNode();
9297 return N0->hasOneUse() && N1->hasOneUse() &&
9298 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9299 }
9300 return false;
9301}
9302
9303static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9304 unsigned Opcode = N->getOpcode();
9305 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9306 SDNode *N0 = N->getOperand(0).getNode();
9307 SDNode *N1 = N->getOperand(1).getNode();
9308 return N0->hasOneUse() && N1->hasOneUse() &&
9309 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9310 }
9311 return false;
9312}
9313
9315 // Multiplications are only custom-lowered for 128-bit vectors so that
9316 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9317 EVT VT = Op.getValueType();
9318 assert(VT.is128BitVector() && VT.isInteger() &&
9319 "unexpected type for custom-lowering ISD::MUL");
9320 SDNode *N0 = Op.getOperand(0).getNode();
9321 SDNode *N1 = Op.getOperand(1).getNode();
9322 unsigned NewOpc = 0;
9323 bool isMLA = false;
9324 bool isN0SExt = isSignExtended(N0, DAG);
9325 bool isN1SExt = isSignExtended(N1, DAG);
9326 if (isN0SExt && isN1SExt)
9327 NewOpc = ARMISD::VMULLs;
9328 else {
9329 bool isN0ZExt = isZeroExtended(N0, DAG);
9330 bool isN1ZExt = isZeroExtended(N1, DAG);
9331 if (isN0ZExt && isN1ZExt)
9332 NewOpc = ARMISD::VMULLu;
9333 else if (isN1SExt || isN1ZExt) {
9334 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9335 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9336 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9337 NewOpc = ARMISD::VMULLs;
9338 isMLA = true;
9339 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9340 NewOpc = ARMISD::VMULLu;
9341 isMLA = true;
9342 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9343 std::swap(N0, N1);
9344 NewOpc = ARMISD::VMULLu;
9345 isMLA = true;
9346 }
9347 }
9348
9349 if (!NewOpc) {
9350 if (VT == MVT::v2i64)
9351 // Fall through to expand this. It is not legal.
9352 return SDValue();
9353 else
9354 // Other vector multiplications are legal.
9355 return Op;
9356 }
9357 }
9358
9359 // Legalize to a VMULL instruction.
9360 SDLoc DL(Op);
9361 SDValue Op0;
9362 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9363 if (!isMLA) {
9364 Op0 = SkipExtensionForVMULL(N0, DAG);
9366 Op1.getValueType().is64BitVector() &&
9367 "unexpected types for extended operands to VMULL");
9368 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9369 }
9370
9371 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9372 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9373 // vmull q0, d4, d6
9374 // vmlal q0, d5, d6
9375 // is faster than
9376 // vaddl q0, d4, d5
9377 // vmovl q1, d6
9378 // vmul q0, q0, q1
9379 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9380 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9381 EVT Op1VT = Op1.getValueType();
9382 return DAG.getNode(N0->getOpcode(), DL, VT,
9383 DAG.getNode(NewOpc, DL, VT,
9384 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9385 DAG.getNode(NewOpc, DL, VT,
9386 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9387}
9388
9390 SelectionDAG &DAG) {
9391 // TODO: Should this propagate fast-math-flags?
9392
9393 // Convert to float
9394 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9395 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9396 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9397 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9398 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9399 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9400 // Get reciprocal estimate.
9401 // float4 recip = vrecpeq_f32(yf);
9402 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9403 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9404 Y);
9405 // Because char has a smaller range than uchar, we can actually get away
9406 // without any newton steps. This requires that we use a weird bias
9407 // of 0xb000, however (again, this has been exhaustively tested).
9408 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9409 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9410 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9411 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9412 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9413 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9414 // Convert back to short.
9415 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9416 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9417 return X;
9418}
9419
9421 SelectionDAG &DAG) {
9422 // TODO: Should this propagate fast-math-flags?
9423
9424 SDValue N2;
9425 // Convert to float.
9426 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9427 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9428 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9429 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9430 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9431 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9432
9433 // Use reciprocal estimate and one refinement step.
9434 // float4 recip = vrecpeq_f32(yf);
9435 // recip *= vrecpsq_f32(yf, recip);
9436 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9437 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9438 N1);
9439 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9440 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9441 N1, N2);
9442 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9443 // Because short has a smaller range than ushort, we can actually get away
9444 // with only a single newton step. This requires that we use a weird bias
9445 // of 89, however (again, this has been exhaustively tested).
9446 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9447 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9448 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9449 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9450 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9451 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9452 // Convert back to integer and return.
9453 // return vmovn_s32(vcvt_s32_f32(result));
9454 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9455 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9456 return N0;
9457}
9458
9460 const ARMSubtarget *ST) {
9461 EVT VT = Op.getValueType();
9462 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9463 "unexpected type for custom-lowering ISD::SDIV");
9464
9465 SDLoc dl(Op);
9466 SDValue N0 = Op.getOperand(0);
9467 SDValue N1 = Op.getOperand(1);
9468 SDValue N2, N3;
9469
9470 if (VT == MVT::v8i8) {
9471 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9472 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9473
9474 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9475 DAG.getIntPtrConstant(4, dl));
9476 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9477 DAG.getIntPtrConstant(4, dl));
9478 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9479 DAG.getIntPtrConstant(0, dl));
9480 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9481 DAG.getIntPtrConstant(0, dl));
9482
9483 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9484 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9485
9486 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9487 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9488
9489 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9490 return N0;
9491 }
9492 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9493}
9494
9496 const ARMSubtarget *ST) {
9497 // TODO: Should this propagate fast-math-flags?
9498 EVT VT = Op.getValueType();
9499 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9500 "unexpected type for custom-lowering ISD::UDIV");
9501
9502 SDLoc dl(Op);
9503 SDValue N0 = Op.getOperand(0);
9504 SDValue N1 = Op.getOperand(1);
9505 SDValue N2, N3;
9506
9507 if (VT == MVT::v8i8) {
9508 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9509 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9510
9511 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9512 DAG.getIntPtrConstant(4, dl));
9513 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9514 DAG.getIntPtrConstant(4, dl));
9515 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9516 DAG.getIntPtrConstant(0, dl));
9517 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9518 DAG.getIntPtrConstant(0, dl));
9519
9520 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9521 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9522
9523 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9524 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9525
9526 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9527 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9528 MVT::i32),
9529 N0);
9530 return N0;
9531 }
9532
9533 // v4i16 sdiv ... Convert to float.
9534 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9535 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9536 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9537 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9538 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9539 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9540
9541 // Use reciprocal estimate and two refinement steps.
9542 // float4 recip = vrecpeq_f32(yf);
9543 // recip *= vrecpsq_f32(yf, recip);
9544 // recip *= vrecpsq_f32(yf, recip);
9545 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9546 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9547 BN1);
9548 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9549 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9550 BN1, N2);
9551 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9552 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9553 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9554 BN1, N2);
9555 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9556 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9557 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9558 // and that it will never cause us to return an answer too large).
9559 // float4 result = as_float4(as_int4(xf*recip) + 2);
9560 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9561 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9562 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9563 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9564 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9565 // Convert back to integer and return.
9566 // return vmovn_u32(vcvt_s32_f32(result));
9567 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9568 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9569 return N0;
9570}
9571
9573 unsigned Opcode, bool IsSigned) {
9574 EVT VT0 = Op.getValue(0).getValueType();
9575 EVT VT1 = Op.getValue(1).getValueType();
9576
9577 bool InvertCarry = Opcode == ARMISD::SUBE;
9578 SDValue OpLHS = Op.getOperand(0);
9579 SDValue OpRHS = Op.getOperand(1);
9580 SDValue OpCarryIn = valueToCarryFlag(Op.getOperand(2), DAG, InvertCarry);
9581
9582 SDLoc DL(Op);
9583
9584 SDValue Result = DAG.getNode(Opcode, DL, DAG.getVTList(VT0, MVT::i32), OpLHS,
9585 OpRHS, OpCarryIn);
9586
9587 SDValue OutFlag =
9588 IsSigned ? overflowFlagToValue(Result.getValue(1), VT1, DAG)
9589 : carryFlagToValue(Result.getValue(1), VT1, DAG, InvertCarry);
9590
9591 return DAG.getMergeValues({Result, OutFlag}, DL);
9592}
9593
9594SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9595 bool Signed,
9596 SDValue &Chain) const {
9597 EVT VT = Op.getValueType();
9598 assert((VT == MVT::i32 || VT == MVT::i64) &&
9599 "unexpected type for custom lowering DIV");
9600 SDLoc dl(Op);
9601
9602 const auto &DL = DAG.getDataLayout();
9603 RTLIB::Libcall LC;
9604 if (Signed)
9605 LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
9606 else
9607 LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
9608
9609 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
9610 SDValue ES = DAG.getExternalSymbol(LCImpl, getPointerTy(DL));
9611
9613
9614 for (auto AI : {1, 0}) {
9615 SDValue Operand = Op.getOperand(AI);
9616 Args.emplace_back(Operand,
9617 Operand.getValueType().getTypeForEVT(*DAG.getContext()));
9618 }
9619
9620 CallLoweringInfo CLI(DAG);
9621 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
9623 VT.getTypeForEVT(*DAG.getContext()), ES, std::move(Args));
9624
9625 return LowerCallTo(CLI).first;
9626}
9627
9628// This is a code size optimisation: return the original SDIV node to
9629// DAGCombiner when we don't want to expand SDIV into a sequence of
9630// instructions, and an empty node otherwise which will cause the
9631// SDIV to be expanded in DAGCombine.
9632SDValue
9633ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9634 SelectionDAG &DAG,
9635 SmallVectorImpl<SDNode *> &Created) const {
9636 // TODO: Support SREM
9637 if (N->getOpcode() != ISD::SDIV)
9638 return SDValue();
9639
9640 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9641 const bool MinSize = ST.hasMinSize();
9642 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9643 : ST.hasDivideInARMMode();
9644
9645 // Don't touch vector types; rewriting this may lead to scalarizing
9646 // the int divs.
9647 if (N->getOperand(0).getValueType().isVector())
9648 return SDValue();
9649
9650 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9651 // hwdiv support for this to be really profitable.
9652 if (!(MinSize && HasDivide))
9653 return SDValue();
9654
9655 // ARM mode is a bit simpler than Thumb: we can handle large power
9656 // of 2 immediates with 1 mov instruction; no further checks required,
9657 // just return the sdiv node.
9658 if (!ST.isThumb())
9659 return SDValue(N, 0);
9660
9661 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9662 // and thus lose the code size benefits of a MOVS that requires only 2.
9663 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9664 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9665 if (Divisor.sgt(128))
9666 return SDValue();
9667
9668 return SDValue(N, 0);
9669}
9670
9671SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9672 bool Signed) const {
9673 assert(Op.getValueType() == MVT::i32 &&
9674 "unexpected type for custom lowering DIV");
9675 SDLoc dl(Op);
9676
9677 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9678 DAG.getEntryNode(), Op.getOperand(1));
9679
9680 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9681}
9682
9684 SDLoc DL(N);
9685 SDValue Op = N->getOperand(1);
9686 if (N->getValueType(0) == MVT::i32)
9687 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9688 SDValue Lo, Hi;
9689 std::tie(Lo, Hi) = DAG.SplitScalar(Op, DL, MVT::i32, MVT::i32);
9690 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9691 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9692}
9693
9694void ARMTargetLowering::ExpandDIV_Windows(
9695 SDValue Op, SelectionDAG &DAG, bool Signed,
9697 const auto &DL = DAG.getDataLayout();
9698
9699 assert(Op.getValueType() == MVT::i64 &&
9700 "unexpected type for custom lowering DIV");
9701 SDLoc dl(Op);
9702
9703 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9704
9705 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9706
9707 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9708 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9709 DAG.getConstant(32, dl, getPointerTy(DL)));
9710 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9711
9712 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9713}
9714
9715std::pair<SDValue, SDValue>
9716ARMTargetLowering::LowerAEABIUnalignedLoad(SDValue Op,
9717 SelectionDAG &DAG) const {
9718 // If we have an unaligned load from a i32 or i64 that would normally be
9719 // split into separate ldrb's, we can use the __aeabi_uread4/__aeabi_uread8
9720 // functions instead.
9721 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9722 EVT MemVT = LD->getMemoryVT();
9723 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9724 return std::make_pair(SDValue(), SDValue());
9725
9726 const auto &MF = DAG.getMachineFunction();
9727 unsigned AS = LD->getAddressSpace();
9728 Align Alignment = LD->getAlign();
9729 const DataLayout &DL = DAG.getDataLayout();
9730 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9731 RTLIB::Libcall LC =
9732 (MemVT == MVT::i32) ? RTLIB::AEABI_UREAD4 : RTLIB::AEABI_UREAD8;
9733
9734 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9735 Alignment <= llvm::Align(2) && DAG.getLibcalls().getLibcallImpl(LC)) {
9736 MakeLibCallOptions Opts;
9737 SDLoc dl(Op);
9738
9739 auto Pair = makeLibCall(DAG, LC, MemVT.getSimpleVT(), LD->getBasePtr(),
9740 Opts, dl, LD->getChain());
9741
9742 // If necessary, extend the node to 64bit
9743 if (LD->getExtensionType() != ISD::NON_EXTLOAD) {
9744 unsigned ExtType = LD->getExtensionType() == ISD::SEXTLOAD
9747 SDValue EN = DAG.getNode(ExtType, dl, LD->getValueType(0), Pair.first);
9748 Pair.first = EN;
9749 }
9750 return Pair;
9751 }
9752
9753 // Default expand to individual loads
9754 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9755 return expandUnalignedLoad(LD, DAG);
9756 return std::make_pair(SDValue(), SDValue());
9757}
9758
9759SDValue ARMTargetLowering::LowerAEABIUnalignedStore(SDValue Op,
9760 SelectionDAG &DAG) const {
9761 // If we have an unaligned store to a i32 or i64 that would normally be
9762 // split into separate ldrb's, we can use the __aeabi_uwrite4/__aeabi_uwrite8
9763 // functions instead.
9764 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9765 EVT MemVT = ST->getMemoryVT();
9766 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9767 return SDValue();
9768
9769 const auto &MF = DAG.getMachineFunction();
9770 unsigned AS = ST->getAddressSpace();
9771 Align Alignment = ST->getAlign();
9772 const DataLayout &DL = DAG.getDataLayout();
9773 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9774 RTLIB::Libcall LC =
9775 (MemVT == MVT::i32) ? RTLIB::AEABI_UWRITE4 : RTLIB::AEABI_UWRITE8;
9776
9777 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9778 Alignment <= llvm::Align(2) && DAG.getLibcalls().getLibcallImpl(LC)) {
9779
9780 SDLoc dl(Op);
9781
9782 // If necessary, trunc the value to 32bit
9783 SDValue StoreVal = ST->getOperand(1);
9784 if (ST->isTruncatingStore())
9785 StoreVal = DAG.getNode(ISD::TRUNCATE, dl, MemVT, ST->getOperand(1));
9786
9787 MakeLibCallOptions Opts;
9788 auto CallResult =
9789 makeLibCall(DAG, LC, MVT::isVoid, {StoreVal, ST->getBasePtr()}, Opts,
9790 dl, ST->getChain());
9791
9792 return CallResult.second;
9793 }
9794
9795 // Default expand to individual stores
9796 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9797 return expandUnalignedStore(ST, DAG);
9798 return SDValue();
9799}
9800
9802 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9803 EVT MemVT = LD->getMemoryVT();
9804 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9805 MemVT == MVT::v16i1) &&
9806 "Expected a predicate type!");
9807 assert(MemVT == Op.getValueType());
9808 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9809 "Expected a non-extending load");
9810 assert(LD->isUnindexed() && "Expected a unindexed load");
9811
9812 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9813 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9814 // need to make sure that 8/4/2 bits are actually loaded into the correct
9815 // place, which means loading the value and then shuffling the values into
9816 // the bottom bits of the predicate.
9817 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9818 // for BE).
9819 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9820 // a natural VMSR(load), so needs to be reversed.
9821
9822 SDLoc dl(Op);
9823 SDValue Load = DAG.getExtLoad(
9824 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9826 LD->getMemOperand());
9827 SDValue Val = Load;
9828 if (DAG.getDataLayout().isBigEndian())
9829 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
9830 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
9831 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
9832 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
9833 if (MemVT != MVT::v16i1)
9834 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9835 DAG.getConstant(0, dl, MVT::i32));
9836 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9837}
9838
9839void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9840 SelectionDAG &DAG) const {
9841 LoadSDNode *LD = cast<LoadSDNode>(N);
9842 EVT MemVT = LD->getMemoryVT();
9843
9844 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9845 !Subtarget->isThumb1Only() && LD->isVolatile() &&
9846 LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9847 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9848 SDLoc dl(N);
9850 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9851 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9852 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9853 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9854 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9855 Results.append({Pair, Result.getValue(2)});
9856 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9857 auto Pair = LowerAEABIUnalignedLoad(SDValue(N, 0), DAG);
9858 if (Pair.first) {
9859 Results.push_back(Pair.first);
9860 Results.push_back(Pair.second);
9861 }
9862 }
9863}
9864
9866 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9867 EVT MemVT = ST->getMemoryVT();
9868 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9869 MemVT == MVT::v16i1) &&
9870 "Expected a predicate type!");
9871 assert(MemVT == ST->getValue().getValueType());
9872 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9873 assert(ST->isUnindexed() && "Expected a unindexed store");
9874
9875 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
9876 // top bits unset and a scalar store.
9877 SDLoc dl(Op);
9878 SDValue Build = ST->getValue();
9879 if (MemVT != MVT::v16i1) {
9881 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9882 unsigned Elt = DAG.getDataLayout().isBigEndian()
9883 ? MemVT.getVectorNumElements() - I - 1
9884 : I;
9885 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9886 DAG.getConstant(Elt, dl, MVT::i32)));
9887 }
9888 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9889 Ops.push_back(DAG.getUNDEF(MVT::i32));
9890 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9891 }
9892 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9893 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9894 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
9895 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
9896 DAG.getConstant(16, dl, MVT::i32));
9897 return DAG.getTruncStore(
9898 ST->getChain(), dl, GRP, ST->getBasePtr(),
9900 ST->getMemOperand());
9901}
9902
9903SDValue ARMTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG,
9904 const ARMSubtarget *Subtarget) const {
9905 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9906 EVT MemVT = ST->getMemoryVT();
9907
9908 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9909 !Subtarget->isThumb1Only() && ST->isVolatile() &&
9910 ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9911 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9912 SDNode *N = Op.getNode();
9913 SDLoc dl(N);
9914
9915 SDValue Lo = DAG.getNode(
9916 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9917 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9918 MVT::i32));
9919 SDValue Hi = DAG.getNode(
9920 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9921 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9922 MVT::i32));
9923
9924 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9925 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9926 MemVT, ST->getMemOperand());
9927 } else if (Subtarget->hasMVEIntegerOps() &&
9928 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9929 MemVT == MVT::v16i1))) {
9930 return LowerPredicateStore(Op, DAG);
9931 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9932 return LowerAEABIUnalignedStore(Op, DAG);
9933 }
9934 return SDValue();
9935}
9936
9937static bool isZeroVector(SDValue N) {
9938 return (ISD::isBuildVectorAllZeros(N) || (N->getOpcode() == ARMISD::VMOVIMM &&
9939 isNullConstant(N->getOperand(0))));
9940}
9941
9944 MVT VT = Op.getSimpleValueType();
9945 SDValue Mask = N->getMask();
9946 SDValue PassThru = N->getPassThru();
9947 SDLoc dl(Op);
9948
9949 if (isZeroVector(PassThru))
9950 return Op;
9951
9952 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9953 // zero too, and other values are lowered to a select.
9954 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9955 DAG.getTargetConstant(0, dl, MVT::i32));
9956 SDValue NewLoad = DAG.getMaskedLoad(
9957 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9958 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9959 N->getExtensionType(), N->isExpandingLoad());
9960 SDValue Combo = NewLoad;
9961 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9962 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9963 isZeroVector(PassThru->getOperand(0));
9964 if (!PassThru.isUndef() && !PassThruIsCastZero)
9965 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9966 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9967}
9968
9970 const ARMSubtarget *ST) {
9971 if (!ST->hasMVEIntegerOps())
9972 return SDValue();
9973
9974 SDLoc dl(Op);
9975 unsigned BaseOpcode = 0;
9976 switch (Op->getOpcode()) {
9977 default: llvm_unreachable("Expected VECREDUCE opcode");
9978 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9979 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9980 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
9981 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
9982 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
9983 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
9984 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9985 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9986 }
9987
9988 SDValue Op0 = Op->getOperand(0);
9989 EVT VT = Op0.getValueType();
9990 EVT EltVT = VT.getVectorElementType();
9991 unsigned NumElts = VT.getVectorNumElements();
9992 unsigned NumActiveLanes = NumElts;
9993
9994 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
9995 NumActiveLanes == 2) &&
9996 "Only expected a power 2 vector size");
9997
9998 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9999 // allows us to easily extract vector elements from the lanes.
10000 while (NumActiveLanes > 4) {
10001 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10002 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10003 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10004 NumActiveLanes /= 2;
10005 }
10006
10007 SDValue Res;
10008 if (NumActiveLanes == 4) {
10009 // The remaining 4 elements are summed sequentially
10010 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10011 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10012 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10013 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10014 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10015 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10016 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10017 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10018 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10019 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10020 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10021 } else {
10022 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10023 DAG.getConstant(0, dl, MVT::i32));
10024 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10025 DAG.getConstant(1, dl, MVT::i32));
10026 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10027 }
10028
10029 // Result type may be wider than element type.
10030 if (EltVT != Op->getValueType(0))
10031 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10032 return Res;
10033}
10034
10036 const ARMSubtarget *ST) {
10037 if (!ST->hasMVEFloatOps())
10038 return SDValue();
10039 return LowerVecReduce(Op, DAG, ST);
10040}
10041
10043 const ARMSubtarget *ST) {
10044 if (!ST->hasNEON())
10045 return SDValue();
10046
10047 SDLoc dl(Op);
10048 SDValue Op0 = Op->getOperand(0);
10049 EVT VT = Op0.getValueType();
10050 EVT EltVT = VT.getVectorElementType();
10051
10052 unsigned PairwiseIntrinsic = 0;
10053 switch (Op->getOpcode()) {
10054 default:
10055 llvm_unreachable("Expected VECREDUCE opcode");
10057 PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10058 break;
10060 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10061 break;
10063 PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10064 break;
10066 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10067 break;
10068 }
10069 SDValue PairwiseOp = DAG.getConstant(PairwiseIntrinsic, dl, MVT::i32);
10070
10071 unsigned NumElts = VT.getVectorNumElements();
10072 unsigned NumActiveLanes = NumElts;
10073
10074 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10075 NumActiveLanes == 2) &&
10076 "Only expected a power 2 vector size");
10077
10078 // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10079 if (VT.is128BitVector()) {
10080 SDValue Lo, Hi;
10081 std::tie(Lo, Hi) = DAG.SplitVector(Op0, dl);
10082 VT = Lo.getValueType();
10083 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Lo, Hi});
10084 NumActiveLanes /= 2;
10085 }
10086
10087 // Use pairwise reductions until one lane remains
10088 while (NumActiveLanes > 1) {
10089 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Op0, Op0});
10090 NumActiveLanes /= 2;
10091 }
10092
10093 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10094 DAG.getConstant(0, dl, MVT::i32));
10095
10096 // Result type may be wider than element type.
10097 if (EltVT != Op.getValueType()) {
10098 unsigned Extend = 0;
10099 switch (Op->getOpcode()) {
10100 default:
10101 llvm_unreachable("Expected VECREDUCE opcode");
10104 Extend = ISD::ZERO_EXTEND;
10105 break;
10108 Extend = ISD::SIGN_EXTEND;
10109 break;
10110 }
10111 Res = DAG.getNode(Extend, dl, Op.getValueType(), Res);
10112 }
10113 return Res;
10114}
10115
10117 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10118 // Acquire/Release load/store is not legal for targets without a dmb or
10119 // equivalent available.
10120 return SDValue();
10121
10122 // Monotonic load/store is legal for all targets.
10123 return Op;
10124}
10125
10128 SelectionDAG &DAG,
10129 const ARMSubtarget *Subtarget) {
10130 SDLoc DL(N);
10131 // Under Power Management extensions, the cycle-count is:
10132 // mrc p15, #0, <Rt>, c9, c13, #0
10133 SDValue Ops[] = { N->getOperand(0), // Chain
10134 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10135 DAG.getTargetConstant(15, DL, MVT::i32),
10136 DAG.getTargetConstant(0, DL, MVT::i32),
10137 DAG.getTargetConstant(9, DL, MVT::i32),
10138 DAG.getTargetConstant(13, DL, MVT::i32),
10139 DAG.getTargetConstant(0, DL, MVT::i32)
10140 };
10141
10142 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10143 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10144 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10145 DAG.getConstant(0, DL, MVT::i32)));
10146 Results.push_back(Cycles32.getValue(1));
10147}
10148
10150 SDValue V1) {
10151 SDLoc dl(V0.getNode());
10152 SDValue RegClass =
10153 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10154 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10155 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10156 const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10157 return SDValue(
10158 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10159}
10160
10162 SDLoc dl(V.getNode());
10163 auto [VLo, VHi] = DAG.SplitScalar(V, dl, MVT::i32, MVT::i32);
10164 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10165 if (isBigEndian)
10166 std::swap(VLo, VHi);
10167 return createGPRPairNode2xi32(DAG, VLo, VHi);
10168}
10169
10172 SelectionDAG &DAG) {
10173 assert(N->getValueType(0) == MVT::i64 &&
10174 "AtomicCmpSwap on types less than 64 should be legal");
10175 SDValue Ops[] = {
10176 createGPRPairNode2xi32(DAG, N->getOperand(1),
10177 DAG.getUNDEF(MVT::i32)), // pointer, temp
10178 createGPRPairNodei64(DAG, N->getOperand(2)), // expected
10179 createGPRPairNodei64(DAG, N->getOperand(3)), // new
10180 N->getOperand(0), // chain in
10181 };
10182 SDNode *CmpSwap = DAG.getMachineNode(
10183 ARM::CMP_SWAP_64, SDLoc(N),
10184 DAG.getVTList(MVT::Untyped, MVT::Untyped, MVT::Other), Ops);
10185
10186 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10187 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10188
10189 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10190
10191 SDValue Lo =
10192 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10193 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10194 SDValue Hi =
10195 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10196 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10197 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10198 Results.push_back(SDValue(CmpSwap, 2));
10199}
10200
10201SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10202 SDLoc dl(Op);
10203 EVT VT = Op.getValueType();
10204 SDValue Chain = Op.getOperand(0);
10205 SDValue LHS = Op.getOperand(1);
10206 SDValue RHS = Op.getOperand(2);
10207 ISD::CondCode CC = Op.getOperandCondCode(3);
10208 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10209
10210 // If we don't have instructions of this float type then soften to a libcall
10211 // and use SETCC instead.
10212 if (isUnsupportedFloatingType(LHS.getValueType())) {
10213 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS,
10214 Chain, IsSignaling);
10215 if (!RHS.getNode()) {
10216 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10217 CC = ISD::SETNE;
10218 }
10219 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10220 DAG.getCondCode(CC));
10221 return DAG.getMergeValues({Result, Chain}, dl);
10222 }
10223
10224 ARMCC::CondCodes CondCode, CondCode2;
10225 FPCCToARMCC(CC, CondCode, CondCode2);
10226
10227 SDValue True = DAG.getConstant(1, dl, VT);
10228 SDValue False = DAG.getConstant(0, dl, VT);
10229 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10230 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10231 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, Cmp, DAG);
10232 if (CondCode2 != ARMCC::AL) {
10233 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10234 Result = getCMOV(dl, VT, Result, True, ARMcc, Cmp, DAG);
10235 }
10236 return DAG.getMergeValues({Result, Chain}, dl);
10237}
10238
10239SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10240 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10241
10242 EVT VT = getPointerTy(DAG.getDataLayout());
10243 int FI = MFI.CreateFixedObject(4, 0, false);
10244 return DAG.getFrameIndex(FI, VT);
10245}
10246
10247SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10248 SelectionDAG &DAG) const {
10249 SDLoc DL(Op);
10250 MakeLibCallOptions CallOptions;
10251 MVT SVT = Op.getOperand(0).getSimpleValueType();
10252 RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
10253 SDValue Res =
10254 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
10255 return DAG.getBitcast(MVT::i32, Res);
10256}
10257
10258SDValue ARMTargetLowering::LowerCMP(SDValue Op, SelectionDAG &DAG) const {
10259 SDLoc dl(Op);
10260 SDValue LHS = Op.getOperand(0);
10261 SDValue RHS = Op.getOperand(1);
10262
10263 // Determine if this is signed or unsigned comparison
10264 bool IsSigned = (Op.getOpcode() == ISD::SCMP);
10265
10266 // Special case for Thumb1 UCMP only
10267 if (!IsSigned && Subtarget->isThumb1Only()) {
10268 // For Thumb unsigned comparison, use this sequence:
10269 // subs r2, r0, r1 ; r2 = LHS - RHS, sets flags
10270 // sbc r2, r2 ; r2 = r2 - r2 - !carry
10271 // cmp r1, r0 ; compare RHS with LHS
10272 // sbc r1, r1 ; r1 = r1 - r1 - !carry
10273 // subs r0, r2, r1 ; r0 = r2 - r1 (final result)
10274
10275 // First subtraction: LHS - RHS
10276 SDValue Sub1WithFlags = DAG.getNode(
10277 ARMISD::SUBC, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10278 SDValue Sub1Result = Sub1WithFlags.getValue(0);
10279 SDValue Flags1 = Sub1WithFlags.getValue(1);
10280
10281 // SUBE: Sub1Result - Sub1Result - !carry
10282 // This gives 0 if LHS >= RHS (unsigned), -1 if LHS < RHS (unsigned)
10283 SDValue Sbc1 =
10284 DAG.getNode(ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT),
10285 Sub1Result, Sub1Result, Flags1);
10286 SDValue Sbc1Result = Sbc1.getValue(0);
10287
10288 // Second comparison: RHS vs LHS (reverse comparison)
10289 SDValue CmpFlags = DAG.getNode(ARMISD::CMP, dl, FlagsVT, RHS, LHS);
10290
10291 // SUBE: RHS - RHS - !carry
10292 // This gives 0 if RHS <= LHS (unsigned), -1 if RHS > LHS (unsigned)
10293 SDValue Sbc2 = DAG.getNode(
10294 ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT), RHS, RHS, CmpFlags);
10295 SDValue Sbc2Result = Sbc2.getValue(0);
10296
10297 // Final subtraction: Sbc1Result - Sbc2Result (no flags needed)
10298 SDValue Result =
10299 DAG.getNode(ISD::SUB, dl, MVT::i32, Sbc1Result, Sbc2Result);
10300 if (Op.getValueType() != MVT::i32)
10301 Result = DAG.getSExtOrTrunc(Result, dl, Op.getValueType());
10302
10303 return Result;
10304 }
10305
10306 // For the ARM assembly pattern:
10307 // subs r0, r0, r1 ; subtract RHS from LHS and set flags
10308 // movgt r0, #1 ; if LHS > RHS, set result to 1 (GT for signed, HI for
10309 // unsigned) mvnlt r0, #0 ; if LHS < RHS, set result to -1 (LT for
10310 // signed, LO for unsigned)
10311 // ; if LHS == RHS, result remains 0 from the subs
10312
10313 // Optimization: if RHS is a subtraction against 0, use ADDC instead of SUBC
10314 unsigned Opcode = ARMISD::SUBC;
10315
10316 // Check if RHS is a subtraction against 0: (0 - X)
10317 if (RHS.getOpcode() == ISD::SUB) {
10318 SDValue SubLHS = RHS.getOperand(0);
10319 SDValue SubRHS = RHS.getOperand(1);
10320
10321 // Check if it's 0 - X
10322 if (isNullConstant(SubLHS)) {
10323 bool CanUseAdd = false;
10324 if (IsSigned) {
10325 // For SCMP: only if X is known to never be INT_MIN (to avoid overflow)
10326 if (RHS->getFlags().hasNoSignedWrap() || !DAG.computeKnownBits(SubRHS)
10328 .isMinSignedValue()) {
10329 CanUseAdd = true;
10330 }
10331 } else {
10332 // For UCMP: only if X is known to never be zero
10333 if (DAG.isKnownNeverZero(SubRHS)) {
10334 CanUseAdd = true;
10335 }
10336 }
10337
10338 if (CanUseAdd) {
10339 Opcode = ARMISD::ADDC;
10340 RHS = SubRHS; // Replace RHS with X, so we do LHS + X instead of
10341 // LHS - (0 - X)
10342 }
10343 }
10344 }
10345
10346 // Generate the operation with flags
10347 SDValue OpWithFlags =
10348 DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10349
10350 SDValue OpResult = OpWithFlags.getValue(0);
10351 SDValue Flags = OpWithFlags.getValue(1);
10352
10353 // Constants for conditional moves
10354 SDValue One = DAG.getConstant(1, dl, MVT::i32);
10355 SDValue MinusOne = DAG.getAllOnesConstant(dl, MVT::i32);
10356
10357 // Select condition codes based on signed vs unsigned
10358 ARMCC::CondCodes GTCond = IsSigned ? ARMCC::GT : ARMCC::HI;
10359 ARMCC::CondCodes LTCond = IsSigned ? ARMCC::LT : ARMCC::LO;
10360
10361 // First conditional move: if greater than, set to 1
10362 SDValue GTCondValue = DAG.getConstant(GTCond, dl, MVT::i32);
10363 SDValue Result1 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, OpResult, One,
10364 GTCondValue, Flags);
10365
10366 // Second conditional move: if less than, set to -1
10367 SDValue LTCondValue = DAG.getConstant(LTCond, dl, MVT::i32);
10368 SDValue Result2 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, Result1, MinusOne,
10369 LTCondValue, Flags);
10370
10371 if (Op.getValueType() != MVT::i32)
10372 Result2 = DAG.getSExtOrTrunc(Result2, dl, Op.getValueType());
10373
10374 return Result2;
10375}
10376
10378 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10379 switch (Op.getOpcode()) {
10380 default: llvm_unreachable("Don't know how to custom lower this!");
10381 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10382 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10383 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10384 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10385 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10386 case ISD::SELECT: return LowerSELECT(Op, DAG);
10387 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10388 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10389 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10390 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10391 case ISD::VASTART: return LowerVASTART(Op, DAG);
10392 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10393 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10396 case ISD::SINT_TO_FP:
10397 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10400 case ISD::FP_TO_SINT:
10401 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10403 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10404 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10405 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10406 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10407 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10408 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10409 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10410 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10411 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10412 Subtarget);
10413 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10414 case ISD::SHL:
10415 case ISD::SRL:
10416 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10417 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10418 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10419 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10420 case ISD::SRL_PARTS:
10421 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10422 case ISD::CTTZ:
10423 case ISD::CTTZ_ZERO_POISON: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10424 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10425 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10426 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10427 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10428 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10429 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10430 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10431 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10432 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10433 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10434 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10435 case ISD::SIGN_EXTEND:
10436 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10437 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
10438 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10439 case ISD::SET_FPMODE:
10440 return LowerSET_FPMODE(Op, DAG);
10441 case ISD::RESET_FPMODE:
10442 return LowerRESET_FPMODE(Op, DAG);
10443 case ISD::MUL: return LowerMUL(Op, DAG);
10444 case ISD::SDIV:
10445 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10446 !Op.getValueType().isVector())
10447 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10448 return LowerSDIV(Op, DAG, Subtarget);
10449 case ISD::UDIV:
10450 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10451 !Op.getValueType().isVector())
10452 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10453 return LowerUDIV(Op, DAG, Subtarget);
10454 case ISD::UADDO_CARRY:
10455 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, false /*unsigned*/);
10456 case ISD::USUBO_CARRY:
10457 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, false /*unsigned*/);
10458 case ISD::SADDO_CARRY:
10459 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, true /*signed*/);
10460 case ISD::SSUBO_CARRY:
10461 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, true /*signed*/);
10462 case ISD::UADDO:
10463 case ISD::USUBO:
10464 case ISD::UMULO:
10465 case ISD::SADDO:
10466 case ISD::SSUBO:
10467 case ISD::SMULO:
10468 return LowerALUO(Op, DAG);
10469 case ISD::SADDSAT:
10470 case ISD::SSUBSAT:
10471 case ISD::UADDSAT:
10472 case ISD::USUBSAT:
10473 return LowerADDSUBSAT(Op, DAG, Subtarget);
10474 case ISD::LOAD: {
10475 auto *LD = cast<LoadSDNode>(Op);
10476 EVT MemVT = LD->getMemoryVT();
10477 if (Subtarget->hasMVEIntegerOps() &&
10478 (MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10479 MemVT == MVT::v16i1))
10480 return LowerPredicateLoad(Op, DAG);
10481
10482 auto Pair = LowerAEABIUnalignedLoad(Op, DAG);
10483 if (Pair.first)
10484 return DAG.getMergeValues({Pair.first, Pair.second}, SDLoc(Pair.first));
10485 return SDValue();
10486 }
10487 case ISD::STORE:
10488 return LowerSTORE(Op, DAG, Subtarget);
10489 case ISD::MLOAD:
10490 return LowerMLOAD(Op, DAG);
10491 case ISD::VECREDUCE_MUL:
10492 case ISD::VECREDUCE_AND:
10493 case ISD::VECREDUCE_OR:
10494 case ISD::VECREDUCE_XOR:
10495 return LowerVecReduce(Op, DAG, Subtarget);
10500 return LowerVecReduceF(Op, DAG, Subtarget);
10505 return LowerVecReduceMinMax(Op, DAG, Subtarget);
10506 case ISD::ATOMIC_LOAD:
10507 case ISD::ATOMIC_STORE:
10508 return LowerAtomicLoadStore(Op, DAG);
10509 case ISD::SDIVREM:
10510 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10512 if (getTargetMachine().getTargetTriple().isOSWindows())
10513 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10514 llvm_unreachable("Don't know how to custom lower this!");
10516 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10518 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10519 case ISD::STRICT_FSETCC:
10520 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10521 case ISD::SPONENTRY:
10522 return LowerSPONENTRY(Op, DAG);
10523 case ISD::FP_TO_BF16:
10524 return LowerFP_TO_BF16(Op, DAG);
10525 case ARMISD::WIN__DBZCHK: return SDValue();
10526 case ISD::UCMP:
10527 case ISD::SCMP:
10528 return LowerCMP(Op, DAG);
10529 case ISD::ABS:
10530 return LowerABS(Op, DAG);
10531 case ISD::STRICT_LROUND:
10533 case ISD::STRICT_LRINT:
10534 case ISD::STRICT_LLRINT: {
10535 assert((Op.getOperand(1).getValueType() == MVT::f16 ||
10536 Op.getOperand(1).getValueType() == MVT::bf16) &&
10537 "Expected custom lowering of rounding operations only for f16");
10538 SDLoc DL(Op);
10539 SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
10540 {Op.getOperand(0), Op.getOperand(1)});
10541 return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
10542 {Ext.getValue(1), Ext.getValue(0)});
10543 }
10544 }
10545}
10546
10548 SelectionDAG &DAG) {
10549 unsigned IntNo = N->getConstantOperandVal(0);
10550 unsigned Opc = 0;
10551 if (IntNo == Intrinsic::arm_smlald)
10552 Opc = ARMISD::SMLALD;
10553 else if (IntNo == Intrinsic::arm_smlaldx)
10554 Opc = ARMISD::SMLALDX;
10555 else if (IntNo == Intrinsic::arm_smlsld)
10556 Opc = ARMISD::SMLSLD;
10557 else if (IntNo == Intrinsic::arm_smlsldx)
10558 Opc = ARMISD::SMLSLDX;
10559 else
10560 return;
10561
10562 SDLoc dl(N);
10563 SDValue Lo, Hi;
10564 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(3), dl, MVT::i32, MVT::i32);
10565
10566 SDValue LongMul = DAG.getNode(Opc, dl,
10567 DAG.getVTList(MVT::i32, MVT::i32),
10568 N->getOperand(1), N->getOperand(2),
10569 Lo, Hi);
10570 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10571 LongMul.getValue(0), LongMul.getValue(1)));
10572}
10573
10574/// ReplaceNodeResults - Replace the results of node with an illegal result
10575/// type with new values built out of custom code.
10578 SelectionDAG &DAG) const {
10579 SDValue Res;
10580 switch (N->getOpcode()) {
10581 default:
10582 llvm_unreachable("Don't know how to custom expand this!");
10583 case ISD::READ_REGISTER:
10585 break;
10586 case ISD::BITCAST:
10587 Res = ExpandBITCAST(N, DAG, Subtarget);
10588 break;
10589 case ISD::SRL:
10590 case ISD::SRA:
10591 case ISD::SHL:
10592 Res = Expand64BitShift(N, DAG, Subtarget);
10593 break;
10594 case ISD::SREM:
10595 case ISD::UREM:
10596 Res = LowerREM(N, DAG);
10597 break;
10598 case ISD::SDIVREM:
10599 case ISD::UDIVREM:
10600 Res = LowerDivRem(SDValue(N, 0), DAG);
10601 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10602 Results.push_back(Res.getValue(0));
10603 Results.push_back(Res.getValue(1));
10604 return;
10605 case ISD::SADDSAT:
10606 case ISD::SSUBSAT:
10607 case ISD::UADDSAT:
10608 case ISD::USUBSAT:
10609 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10610 break;
10612 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10613 return;
10614 case ISD::UDIV:
10615 case ISD::SDIV:
10616 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
10617 "can only expand DIV on Windows");
10618 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10619 Results);
10622 return;
10624 return ReplaceLongIntrinsic(N, Results, DAG);
10625 case ISD::LOAD:
10626 LowerLOAD(N, Results, DAG);
10627 break;
10628 case ISD::STORE:
10629 Res = LowerAEABIUnalignedStore(SDValue(N, 0), DAG);
10630 break;
10631 case ISD::TRUNCATE:
10632 Res = LowerTruncate(N, DAG, Subtarget);
10633 break;
10634 case ISD::SIGN_EXTEND:
10635 case ISD::ZERO_EXTEND:
10636 Res = LowerVectorExtend(N, DAG, Subtarget);
10637 break;
10640 Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10641 break;
10642 }
10643 if (Res.getNode())
10644 Results.push_back(Res);
10645}
10646
10647//===----------------------------------------------------------------------===//
10648// ARM Scheduler Hooks
10649//===----------------------------------------------------------------------===//
10650
10651/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10652/// registers the function context.
10653void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10655 MachineBasicBlock *DispatchBB,
10656 int FI) const {
10657 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10658 "ROPI/RWPI not currently supported with SjLj");
10659 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10660 DebugLoc dl = MI.getDebugLoc();
10661 MachineFunction *MF = MBB->getParent();
10665 const Function &F = MF->getFunction();
10666
10667 bool isThumb = Subtarget->isThumb();
10668 bool isThumb2 = Subtarget->isThumb2();
10669
10670 unsigned PCLabelId = AFI->createPICLabelUId();
10671 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10673 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10674 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10675
10676 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10677 : &ARM::GPRRegClass;
10678
10679 // Grab constant pool and fixed stack memory operands.
10680 MachineMemOperand *CPMMO =
10683
10684 MachineMemOperand *FIMMOSt =
10687
10688 // Load the address of the dispatch MBB into the jump buffer.
10689 if (isThumb2) {
10690 // Incoming value: jbuf
10691 // ldr.n r5, LCPI1_1
10692 // orr r5, r5, #1
10693 // add r5, pc
10694 // str r5, [$jbuf, #+4] ; &jbuf[1]
10695 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10696 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10698 .addMemOperand(CPMMO)
10700 // Set the low bit because of thumb mode.
10701 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10702 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10703 .addReg(NewVReg1)
10704 .addImm(0x01)
10706 .add(condCodeOp());
10707 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10708 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10709 .addReg(NewVReg2)
10710 .addImm(PCLabelId);
10711 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10712 .addReg(NewVReg3)
10713 .addFrameIndex(FI)
10714 .addImm(36) // &jbuf[1] :: pc
10715 .addMemOperand(FIMMOSt)
10717 } else if (isThumb) {
10718 // Incoming value: jbuf
10719 // ldr.n r1, LCPI1_4
10720 // add r1, pc
10721 // mov r2, #1
10722 // orrs r1, r2
10723 // add r2, $jbuf, #+4 ; &jbuf[1]
10724 // str r1, [r2]
10725 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10726 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10728 .addMemOperand(CPMMO)
10730 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10731 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10732 .addReg(NewVReg1)
10733 .addImm(PCLabelId);
10734 // Set the low bit because of thumb mode.
10735 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10736 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10737 .addReg(ARM::CPSR, RegState::Define)
10738 .addImm(1)
10740 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10741 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10742 .addReg(ARM::CPSR, RegState::Define)
10743 .addReg(NewVReg2)
10744 .addReg(NewVReg3)
10746 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10747 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10748 .addFrameIndex(FI)
10749 .addImm(36); // &jbuf[1] :: pc
10750 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10751 .addReg(NewVReg4)
10752 .addReg(NewVReg5)
10753 .addImm(0)
10754 .addMemOperand(FIMMOSt)
10756 } else {
10757 // Incoming value: jbuf
10758 // ldr r1, LCPI1_1
10759 // add r1, pc, r1
10760 // str r1, [$jbuf, #+4] ; &jbuf[1]
10761 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10762 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10764 .addImm(0)
10765 .addMemOperand(CPMMO)
10767 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10768 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10769 .addReg(NewVReg1)
10770 .addImm(PCLabelId)
10772 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10773 .addReg(NewVReg2)
10774 .addFrameIndex(FI)
10775 .addImm(36) // &jbuf[1] :: pc
10776 .addMemOperand(FIMMOSt)
10778 }
10779}
10780
10781void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10782 MachineBasicBlock *MBB) const {
10783 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10784 DebugLoc dl = MI.getDebugLoc();
10785 MachineFunction *MF = MBB->getParent();
10786 MachineRegisterInfo *MRI = &MF->getRegInfo();
10787 MachineFrameInfo &MFI = MF->getFrameInfo();
10788 int FI = MFI.getFunctionContextIndex();
10789
10790 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10791 : &ARM::GPRnopcRegClass;
10792
10793 // Get a mapping of the call site numbers to all of the landing pads they're
10794 // associated with.
10795 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10796 unsigned MaxCSNum = 0;
10797 for (MachineBasicBlock &BB : *MF) {
10798 if (!BB.isEHPad())
10799 continue;
10800
10801 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10802 // pad.
10803 for (MachineInstr &II : BB) {
10804 if (!II.isEHLabel())
10805 continue;
10806
10807 MCSymbol *Sym = II.getOperand(0).getMCSymbol();
10808 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10809
10810 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10811 for (unsigned Idx : CallSiteIdxs) {
10812 CallSiteNumToLPad[Idx].push_back(&BB);
10813 MaxCSNum = std::max(MaxCSNum, Idx);
10814 }
10815 break;
10816 }
10817 }
10818
10819 // Get an ordered list of the machine basic blocks for the jump table.
10820 std::vector<MachineBasicBlock*> LPadList;
10821 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10822 LPadList.reserve(CallSiteNumToLPad.size());
10823 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10824 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10825 for (MachineBasicBlock *MBB : MBBList) {
10826 LPadList.push_back(MBB);
10827 InvokeBBs.insert_range(MBB->predecessors());
10828 }
10829 }
10830
10831 assert(!LPadList.empty() &&
10832 "No landing pad destinations for the dispatch jump table!");
10833
10834 // Create the jump table and associated information.
10835 MachineJumpTableInfo *JTI =
10836 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10837 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10838
10839 // Create the MBBs for the dispatch code.
10840
10841 // Shove the dispatch's address into the return slot in the function context.
10842 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10843 DispatchBB->setIsEHPad();
10844
10845 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10846
10847 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
10848 DispatchBB->addSuccessor(TrapBB);
10849
10850 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10851 DispatchBB->addSuccessor(DispContBB);
10852
10853 // Insert and MBBs.
10854 MF->insert(MF->end(), DispatchBB);
10855 MF->insert(MF->end(), DispContBB);
10856 MF->insert(MF->end(), TrapBB);
10857
10858 // Insert code into the entry block that creates and registers the function
10859 // context.
10860 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10861
10862 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10865
10866 MachineInstrBuilder MIB;
10867 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10868
10869 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10870 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10871
10872 // Add a register mask with no preserved registers. This results in all
10873 // registers being marked as clobbered. This can't work if the dispatch block
10874 // is in a Thumb1 function and is linked with ARM code which uses the FP
10875 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10877
10878 bool IsPositionIndependent = isPositionIndependent();
10879 unsigned NumLPads = LPadList.size();
10880 if (Subtarget->isThumb2()) {
10881 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10882 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10883 .addFrameIndex(FI)
10884 .addImm(4)
10885 .addMemOperand(FIMMOLd)
10887
10888 if (NumLPads < 256) {
10889 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10890 .addReg(NewVReg1)
10891 .addImm(LPadList.size())
10893 } else {
10894 Register VReg1 = MRI->createVirtualRegister(TRC);
10895 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10896 .addImm(NumLPads & 0xFFFF)
10898
10899 unsigned VReg2 = VReg1;
10900 if ((NumLPads & 0xFFFF0000) != 0) {
10901 VReg2 = MRI->createVirtualRegister(TRC);
10902 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10903 .addReg(VReg1)
10904 .addImm(NumLPads >> 16)
10906 }
10907
10908 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10909 .addReg(NewVReg1)
10910 .addReg(VReg2)
10912 }
10913
10914 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10915 .addMBB(TrapBB)
10917 .addReg(ARM::CPSR);
10918
10919 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10920 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10921 .addJumpTableIndex(MJTI)
10923
10924 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10925 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10926 .addReg(NewVReg3)
10927 .addReg(NewVReg1)
10930 .add(condCodeOp());
10931
10932 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10933 .addReg(NewVReg4)
10934 .addReg(NewVReg1)
10935 .addJumpTableIndex(MJTI);
10936 } else if (Subtarget->isThumb()) {
10937 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10938 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10939 .addFrameIndex(FI)
10940 .addImm(1)
10941 .addMemOperand(FIMMOLd)
10943
10944 if (NumLPads < 256) {
10945 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10946 .addReg(NewVReg1)
10947 .addImm(NumLPads)
10949 } else {
10950 MachineConstantPool *ConstantPool = MF->getConstantPool();
10951 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10952 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10953
10954 // MachineConstantPool wants an explicit alignment.
10955 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10956 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10957
10958 Register VReg1 = MRI->createVirtualRegister(TRC);
10959 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10960 .addReg(VReg1, RegState::Define)
10963 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10964 .addReg(NewVReg1)
10965 .addReg(VReg1)
10967 }
10968
10969 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10970 .addMBB(TrapBB)
10972 .addReg(ARM::CPSR);
10973
10974 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10975 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10976 .addReg(ARM::CPSR, RegState::Define)
10977 .addReg(NewVReg1)
10978 .addImm(2)
10980
10981 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10982 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10983 .addJumpTableIndex(MJTI)
10985
10986 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10987 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10988 .addReg(ARM::CPSR, RegState::Define)
10989 .addReg(NewVReg2)
10990 .addReg(NewVReg3)
10992
10993 MachineMemOperand *JTMMOLd =
10994 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10996
10997 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10998 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10999 .addReg(NewVReg4)
11000 .addImm(0)
11001 .addMemOperand(JTMMOLd)
11003
11004 unsigned NewVReg6 = NewVReg5;
11005 if (IsPositionIndependent) {
11006 NewVReg6 = MRI->createVirtualRegister(TRC);
11007 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
11008 .addReg(ARM::CPSR, RegState::Define)
11009 .addReg(NewVReg5)
11010 .addReg(NewVReg3)
11012 }
11013
11014 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
11015 .addReg(NewVReg6)
11016 .addJumpTableIndex(MJTI);
11017 } else {
11018 Register NewVReg1 = MRI->createVirtualRegister(TRC);
11019 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
11020 .addFrameIndex(FI)
11021 .addImm(4)
11022 .addMemOperand(FIMMOLd)
11024
11025 if (NumLPads < 256) {
11026 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
11027 .addReg(NewVReg1)
11028 .addImm(NumLPads)
11030 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
11031 Register VReg1 = MRI->createVirtualRegister(TRC);
11032 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
11033 .addImm(NumLPads & 0xFFFF)
11035
11036 unsigned VReg2 = VReg1;
11037 if ((NumLPads & 0xFFFF0000) != 0) {
11038 VReg2 = MRI->createVirtualRegister(TRC);
11039 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
11040 .addReg(VReg1)
11041 .addImm(NumLPads >> 16)
11043 }
11044
11045 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11046 .addReg(NewVReg1)
11047 .addReg(VReg2)
11049 } else {
11050 MachineConstantPool *ConstantPool = MF->getConstantPool();
11051 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11052 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11053
11054 // MachineConstantPool wants an explicit alignment.
11055 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11056 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11057
11058 Register VReg1 = MRI->createVirtualRegister(TRC);
11059 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
11060 .addReg(VReg1, RegState::Define)
11062 .addImm(0)
11064 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11065 .addReg(NewVReg1)
11066 .addReg(VReg1)
11068 }
11069
11070 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
11071 .addMBB(TrapBB)
11073 .addReg(ARM::CPSR);
11074
11075 Register NewVReg3 = MRI->createVirtualRegister(TRC);
11076 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
11077 .addReg(NewVReg1)
11080 .add(condCodeOp());
11081 Register NewVReg4 = MRI->createVirtualRegister(TRC);
11082 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
11083 .addJumpTableIndex(MJTI)
11085
11086 MachineMemOperand *JTMMOLd =
11087 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11089 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11090 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11091 .addReg(NewVReg3)
11092 .addReg(NewVReg4)
11093 .addImm(0)
11094 .addMemOperand(JTMMOLd)
11096
11097 if (IsPositionIndependent) {
11098 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11099 .addReg(NewVReg5)
11100 .addReg(NewVReg4)
11101 .addJumpTableIndex(MJTI);
11102 } else {
11103 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11104 .addReg(NewVReg5)
11105 .addJumpTableIndex(MJTI);
11106 }
11107 }
11108
11109 // Add the jump table entries as successors to the MBB.
11110 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11111 for (MachineBasicBlock *CurMBB : LPadList) {
11112 if (SeenMBBs.insert(CurMBB).second)
11113 DispContBB->addSuccessor(CurMBB);
11114 }
11115
11116 // N.B. the order the invoke BBs are processed in doesn't matter here.
11117 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11119 for (MachineBasicBlock *BB : InvokeBBs) {
11120
11121 // Remove the landing pad successor from the invoke block and replace it
11122 // with the new dispatch block.
11123 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11124 while (!Successors.empty()) {
11125 MachineBasicBlock *SMBB = Successors.pop_back_val();
11126 if (SMBB->isEHPad()) {
11127 BB->removeSuccessor(SMBB);
11128 MBBLPads.push_back(SMBB);
11129 }
11130 }
11131
11132 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11133 BB->normalizeSuccProbs();
11134
11135 // Find the invoke call and mark all of the callee-saved registers as
11136 // 'implicit defined' so that they're spilled. This prevents code from
11137 // moving instructions to before the EH block, where they will never be
11138 // executed.
11140 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11141 if (!II->isCall()) continue;
11142
11143 DenseSet<unsigned> DefRegs;
11145 OI = II->operands_begin(), OE = II->operands_end();
11146 OI != OE; ++OI) {
11147 if (!OI->isReg()) continue;
11148 DefRegs.insert(OI->getReg());
11149 }
11150
11151 MachineInstrBuilder MIB(*MF, &*II);
11152
11153 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11154 unsigned Reg = SavedRegs[i];
11155 if (Subtarget->isThumb2() &&
11156 !ARM::tGPRRegClass.contains(Reg) &&
11157 !ARM::hGPRRegClass.contains(Reg))
11158 continue;
11159 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11160 continue;
11161 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11162 continue;
11163 if (!DefRegs.contains(Reg))
11165 }
11166
11167 break;
11168 }
11169 }
11170
11171 // Mark all former landing pads as non-landing pads. The dispatch is the only
11172 // landing pad now.
11173 for (MachineBasicBlock *MBBLPad : MBBLPads)
11174 MBBLPad->setIsEHPad(false);
11175
11176 // The instruction is gone now.
11177 MI.eraseFromParent();
11178}
11179
11180static
11182 for (MachineBasicBlock *S : MBB->successors())
11183 if (S != Succ)
11184 return S;
11185 llvm_unreachable("Expecting a BB with two successors!");
11186}
11187
11188/// Return the load opcode for a given load size. If load size >= 8,
11189/// neon opcode will be returned.
11190static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11191 if (LdSize >= 8)
11192 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11193 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11194 if (IsThumb1)
11195 return LdSize == 4 ? ARM::tLDRi
11196 : LdSize == 2 ? ARM::tLDRHi
11197 : LdSize == 1 ? ARM::tLDRBi : 0;
11198 if (IsThumb2)
11199 return LdSize == 4 ? ARM::t2LDR_POST
11200 : LdSize == 2 ? ARM::t2LDRH_POST
11201 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11202 return LdSize == 4 ? ARM::LDR_POST_IMM
11203 : LdSize == 2 ? ARM::LDRH_POST
11204 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11205}
11206
11207/// Return the store opcode for a given store size. If store size >= 8,
11208/// neon opcode will be returned.
11209static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11210 if (StSize >= 8)
11211 return StSize == 16 ? ARM::VST1q32wb_fixed
11212 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11213 if (IsThumb1)
11214 return StSize == 4 ? ARM::tSTRi
11215 : StSize == 2 ? ARM::tSTRHi
11216 : StSize == 1 ? ARM::tSTRBi : 0;
11217 if (IsThumb2)
11218 return StSize == 4 ? ARM::t2STR_POST
11219 : StSize == 2 ? ARM::t2STRH_POST
11220 : StSize == 1 ? ARM::t2STRB_POST : 0;
11221 return StSize == 4 ? ARM::STR_POST_IMM
11222 : StSize == 2 ? ARM::STRH_POST
11223 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11224}
11225
11226/// Emit a post-increment load operation with given size. The instructions
11227/// will be added to BB at Pos.
11229 const TargetInstrInfo *TII, const DebugLoc &dl,
11230 unsigned LdSize, unsigned Data, unsigned AddrIn,
11231 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11232 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11233 assert(LdOpc != 0 && "Should have a load opcode");
11234 if (LdSize >= 8) {
11235 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11236 .addReg(AddrOut, RegState::Define)
11237 .addReg(AddrIn)
11238 .addImm(0)
11240 } else if (IsThumb1) {
11241 // load + update AddrIn
11242 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11243 .addReg(AddrIn)
11244 .addImm(0)
11246 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11247 .add(t1CondCodeOp())
11248 .addReg(AddrIn)
11249 .addImm(LdSize)
11251 } else if (IsThumb2) {
11252 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11253 .addReg(AddrOut, RegState::Define)
11254 .addReg(AddrIn)
11255 .addImm(LdSize)
11257 } else { // arm
11258 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11259 .addReg(AddrOut, RegState::Define)
11260 .addReg(AddrIn)
11261 .addReg(0)
11262 .addImm(LdSize)
11264 }
11265}
11266
11267/// Emit a post-increment store operation with given size. The instructions
11268/// will be added to BB at Pos.
11270 const TargetInstrInfo *TII, const DebugLoc &dl,
11271 unsigned StSize, unsigned Data, unsigned AddrIn,
11272 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11273 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11274 assert(StOpc != 0 && "Should have a store opcode");
11275 if (StSize >= 8) {
11276 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11277 .addReg(AddrIn)
11278 .addImm(0)
11279 .addReg(Data)
11281 } else if (IsThumb1) {
11282 // store + update AddrIn
11283 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11284 .addReg(Data)
11285 .addReg(AddrIn)
11286 .addImm(0)
11288 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11289 .add(t1CondCodeOp())
11290 .addReg(AddrIn)
11291 .addImm(StSize)
11293 } else if (IsThumb2) {
11294 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11295 .addReg(Data)
11296 .addReg(AddrIn)
11297 .addImm(StSize)
11299 } else { // arm
11300 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11301 .addReg(Data)
11302 .addReg(AddrIn)
11303 .addReg(0)
11304 .addImm(StSize)
11306 }
11307}
11308
11310ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11311 MachineBasicBlock *BB) const {
11312 // This pseudo instruction has 3 operands: dst, src, size
11313 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11314 // Otherwise, we will generate unrolled scalar copies.
11315 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11316 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11318
11319 Register dest = MI.getOperand(0).getReg();
11320 Register src = MI.getOperand(1).getReg();
11321 unsigned SizeVal = MI.getOperand(2).getImm();
11322 unsigned Alignment = MI.getOperand(3).getImm();
11323 DebugLoc dl = MI.getDebugLoc();
11324
11325 MachineFunction *MF = BB->getParent();
11326 MachineRegisterInfo &MRI = MF->getRegInfo();
11327 unsigned UnitSize = 0;
11328 const TargetRegisterClass *TRC = nullptr;
11329 const TargetRegisterClass *VecTRC = nullptr;
11330
11331 bool IsThumb1 = Subtarget->isThumb1Only();
11332 bool IsThumb2 = Subtarget->isThumb2();
11333 bool IsThumb = Subtarget->isThumb();
11334
11335 if (Alignment & 1) {
11336 UnitSize = 1;
11337 } else if (Alignment & 2) {
11338 UnitSize = 2;
11339 } else {
11340 // Check whether we can use NEON instructions.
11341 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11342 Subtarget->hasNEON()) {
11343 if ((Alignment % 16 == 0) && SizeVal >= 16)
11344 UnitSize = 16;
11345 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11346 UnitSize = 8;
11347 }
11348 // Can't use NEON instructions.
11349 if (UnitSize == 0)
11350 UnitSize = 4;
11351 }
11352
11353 // Select the correct opcode and register class for unit size load/store
11354 bool IsNeon = UnitSize >= 8;
11355 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11356 if (IsNeon)
11357 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11358 : UnitSize == 8 ? &ARM::DPRRegClass
11359 : nullptr;
11360
11361 unsigned BytesLeft = SizeVal % UnitSize;
11362 unsigned LoopSize = SizeVal - BytesLeft;
11363
11364 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11365 // Use LDR and STR to copy.
11366 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11367 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11368 unsigned srcIn = src;
11369 unsigned destIn = dest;
11370 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11371 Register srcOut = MRI.createVirtualRegister(TRC);
11372 Register destOut = MRI.createVirtualRegister(TRC);
11373 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11374 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11375 IsThumb1, IsThumb2);
11376 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11377 IsThumb1, IsThumb2);
11378 srcIn = srcOut;
11379 destIn = destOut;
11380 }
11381
11382 // Handle the leftover bytes with LDRB and STRB.
11383 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11384 // [destOut] = STRB_POST(scratch, destIn, 1)
11385 for (unsigned i = 0; i < BytesLeft; i++) {
11386 Register srcOut = MRI.createVirtualRegister(TRC);
11387 Register destOut = MRI.createVirtualRegister(TRC);
11388 Register scratch = MRI.createVirtualRegister(TRC);
11389 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11390 IsThumb1, IsThumb2);
11391 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11392 IsThumb1, IsThumb2);
11393 srcIn = srcOut;
11394 destIn = destOut;
11395 }
11396 MI.eraseFromParent(); // The instruction is gone now.
11397 return BB;
11398 }
11399
11400 // Expand the pseudo op to a loop.
11401 // thisMBB:
11402 // ...
11403 // movw varEnd, # --> with thumb2
11404 // movt varEnd, #
11405 // ldrcp varEnd, idx --> without thumb2
11406 // fallthrough --> loopMBB
11407 // loopMBB:
11408 // PHI varPhi, varEnd, varLoop
11409 // PHI srcPhi, src, srcLoop
11410 // PHI destPhi, dst, destLoop
11411 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11412 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11413 // subs varLoop, varPhi, #UnitSize
11414 // bne loopMBB
11415 // fallthrough --> exitMBB
11416 // exitMBB:
11417 // epilogue to handle left-over bytes
11418 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11419 // [destOut] = STRB_POST(scratch, destLoop, 1)
11420 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11421 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11422 MF->insert(It, loopMBB);
11423 MF->insert(It, exitMBB);
11424
11425 // Set the call frame size on entry to the new basic blocks.
11426 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11427 loopMBB->setCallFrameSize(CallFrameSize);
11428 exitMBB->setCallFrameSize(CallFrameSize);
11429
11430 // Transfer the remainder of BB and its successor edges to exitMBB.
11431 exitMBB->splice(exitMBB->begin(), BB,
11432 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11434
11435 // Load an immediate to varEnd.
11436 Register varEnd = MRI.createVirtualRegister(TRC);
11437 if (Subtarget->useMovt()) {
11438 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11439 varEnd)
11440 .addImm(LoopSize);
11441 } else if (Subtarget->genExecuteOnly()) {
11442 assert(IsThumb && "Non-thumb expected to have used movt");
11443 BuildMI(BB, dl, TII->get(ARM::tMOVi32imm), varEnd).addImm(LoopSize);
11444 } else {
11445 MachineConstantPool *ConstantPool = MF->getConstantPool();
11446 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11447 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11448
11449 // MachineConstantPool wants an explicit alignment.
11451 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11452 MachineMemOperand *CPMMO =
11455
11456 if (IsThumb)
11457 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11458 .addReg(varEnd, RegState::Define)
11461 .addMemOperand(CPMMO);
11462 else
11463 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11464 .addReg(varEnd, RegState::Define)
11466 .addImm(0)
11468 .addMemOperand(CPMMO);
11469 }
11470 BB->addSuccessor(loopMBB);
11471
11472 // Generate the loop body:
11473 // varPhi = PHI(varLoop, varEnd)
11474 // srcPhi = PHI(srcLoop, src)
11475 // destPhi = PHI(destLoop, dst)
11476 MachineBasicBlock *entryBB = BB;
11477 BB = loopMBB;
11478 Register varLoop = MRI.createVirtualRegister(TRC);
11479 Register varPhi = MRI.createVirtualRegister(TRC);
11480 Register srcLoop = MRI.createVirtualRegister(TRC);
11481 Register srcPhi = MRI.createVirtualRegister(TRC);
11482 Register destLoop = MRI.createVirtualRegister(TRC);
11483 Register destPhi = MRI.createVirtualRegister(TRC);
11484
11485 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11486 .addReg(varLoop).addMBB(loopMBB)
11487 .addReg(varEnd).addMBB(entryBB);
11488 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11489 .addReg(srcLoop).addMBB(loopMBB)
11490 .addReg(src).addMBB(entryBB);
11491 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11492 .addReg(destLoop).addMBB(loopMBB)
11493 .addReg(dest).addMBB(entryBB);
11494
11495 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11496 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11497 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11498 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11499 IsThumb1, IsThumb2);
11500 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11501 IsThumb1, IsThumb2);
11502
11503 // Decrement loop variable by UnitSize.
11504 if (IsThumb1) {
11505 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11506 .add(t1CondCodeOp())
11507 .addReg(varPhi)
11508 .addImm(UnitSize)
11510 } else {
11511 MachineInstrBuilder MIB =
11512 BuildMI(*BB, BB->end(), dl,
11513 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11514 MIB.addReg(varPhi)
11515 .addImm(UnitSize)
11517 .add(condCodeOp());
11518 MIB->getOperand(5).setReg(ARM::CPSR);
11519 MIB->getOperand(5).setIsDef(true);
11520 }
11521 BuildMI(*BB, BB->end(), dl,
11522 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11523 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11524
11525 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11526 BB->addSuccessor(loopMBB);
11527 BB->addSuccessor(exitMBB);
11528
11529 // Add epilogue to handle BytesLeft.
11530 BB = exitMBB;
11531 auto StartOfExit = exitMBB->begin();
11532
11533 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11534 // [destOut] = STRB_POST(scratch, destLoop, 1)
11535 unsigned srcIn = srcLoop;
11536 unsigned destIn = destLoop;
11537 for (unsigned i = 0; i < BytesLeft; i++) {
11538 Register srcOut = MRI.createVirtualRegister(TRC);
11539 Register destOut = MRI.createVirtualRegister(TRC);
11540 Register scratch = MRI.createVirtualRegister(TRC);
11541 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11542 IsThumb1, IsThumb2);
11543 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11544 IsThumb1, IsThumb2);
11545 srcIn = srcOut;
11546 destIn = destOut;
11547 }
11548
11549 MI.eraseFromParent(); // The instruction is gone now.
11550 return BB;
11551}
11552
11554ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11555 MachineBasicBlock *MBB) const {
11556 const TargetMachine &TM = getTargetMachine();
11557 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11558 DebugLoc DL = MI.getDebugLoc();
11559
11560 assert(TM.getTargetTriple().isOSWindows() &&
11561 "__chkstk is only supported on Windows");
11562 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11563
11564 // __chkstk takes the number of words to allocate on the stack in R4, and
11565 // returns the stack adjustment in number of bytes in R4. This will not
11566 // clober any other registers (other than the obvious lr).
11567 //
11568 // Although, technically, IP should be considered a register which may be
11569 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11570 // thumb-2 environment, so there is no interworking required. As a result, we
11571 // do not expect a veneer to be emitted by the linker, clobbering IP.
11572 //
11573 // Each module receives its own copy of __chkstk, so no import thunk is
11574 // required, again, ensuring that IP is not clobbered.
11575 //
11576 // Finally, although some linkers may theoretically provide a trampoline for
11577 // out of range calls (which is quite common due to a 32M range limitation of
11578 // branches for Thumb), we can generate the long-call version via
11579 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11580 // IP.
11581
11582 RTLIB::LibcallImpl ChkStkLibcall = getLibcallImpl(RTLIB::STACK_PROBE);
11583 if (ChkStkLibcall == RTLIB::Unsupported)
11584 reportFatalUsageError("no available implementation of __chkstk");
11585
11586 const char *ChkStk = getLibcallImplName(ChkStkLibcall).data();
11587 switch (TM.getCodeModel()) {
11588 case CodeModel::Tiny:
11589 llvm_unreachable("Tiny code model not available on ARM.");
11590 case CodeModel::Small:
11591 case CodeModel::Medium:
11592 case CodeModel::Kernel:
11593 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11595 .addExternalSymbol(ChkStk)
11596 .setOperandDead(3) // implicit-def $lr
11599 .addReg(ARM::R12,
11601 .addReg(ARM::CPSR,
11603 break;
11604 case CodeModel::Large: {
11605 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11606 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11607
11608 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11609 .addExternalSymbol(ChkStk);
11612 .addReg(Reg)
11613 .setOperandDead(3) // implicit-def $lr
11616 .addReg(ARM::R12,
11618 .addReg(ARM::CPSR,
11620 break;
11621 }
11622 }
11623
11624 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11625 .addReg(ARM::SP, RegState::Kill)
11626 .addReg(ARM::R4, RegState::Kill)
11629 .add(condCodeOp());
11630
11631 MI.eraseFromParent();
11632 return MBB;
11633}
11634
11636ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11637 MachineBasicBlock *MBB) const {
11638 DebugLoc DL = MI.getDebugLoc();
11639 MachineFunction *MF = MBB->getParent();
11640 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11641
11642 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11643 MF->insert(++MBB->getIterator(), ContBB);
11644 ContBB->splice(ContBB->begin(), MBB,
11645 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11647 MBB->addSuccessor(ContBB);
11648
11649 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11650 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11651 MF->push_back(TrapBB);
11652 MBB->addSuccessor(TrapBB);
11653
11654 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11655 .addReg(MI.getOperand(0).getReg())
11656 .addImm(0)
11658 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11659 .addMBB(TrapBB)
11661 .addReg(ARM::CPSR);
11662
11663 MI.eraseFromParent();
11664 return ContBB;
11665}
11666
11667// The CPSR operand of SelectItr might be missing a kill marker
11668// because there were multiple uses of CPSR, and ISel didn't know
11669// which to mark. Figure out whether SelectItr should have had a
11670// kill marker, and set it if it should. Returns the correct kill
11671// marker value.
11674 const TargetRegisterInfo* TRI) {
11675 // Scan forward through BB for a use/def of CPSR.
11676 MachineBasicBlock::iterator miI(std::next(SelectItr));
11677 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11678 const MachineInstr& mi = *miI;
11679 if (mi.readsRegister(ARM::CPSR, /*TRI=*/nullptr))
11680 return false;
11681 if (mi.definesRegister(ARM::CPSR, /*TRI=*/nullptr))
11682 break; // Should have kill-flag - update below.
11683 }
11684
11685 // If we hit the end of the block, check whether CPSR is live into a
11686 // successor.
11687 if (miI == BB->end()) {
11688 for (MachineBasicBlock *Succ : BB->successors())
11689 if (Succ->isLiveIn(ARM::CPSR))
11690 return false;
11691 }
11692
11693 // We found a def, or hit the end of the basic block and CPSR wasn't live
11694 // out. SelectMI should have a kill flag on CPSR.
11695 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11696 return true;
11697}
11698
11699/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11700/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11702 MachineBasicBlock *TpLoopBody,
11703 MachineBasicBlock *TpExit, Register OpSizeReg,
11704 const TargetInstrInfo *TII, DebugLoc Dl,
11706 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11707 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11708 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11709 .addUse(OpSizeReg)
11710 .addImm(15)
11712 .addReg(0);
11713
11714 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11715 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11716 .addUse(AddDestReg)
11717 .addImm(4)
11719 .addReg(0);
11720
11721 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11722 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11723 .addUse(LsrDestReg);
11724
11725 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11726 .addUse(TotalIterationsReg)
11727 .addMBB(TpExit);
11728
11729 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11730 .addMBB(TpLoopBody)
11732
11733 return TotalIterationsReg;
11734}
11735
11736/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11737/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11738/// loops.
11739static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11740 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11741 const TargetInstrInfo *TII, DebugLoc Dl,
11742 MachineRegisterInfo &MRI, Register OpSrcReg,
11743 Register OpDestReg, Register ElementCountReg,
11744 Register TotalIterationsReg, bool IsMemcpy) {
11745 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11746 // array, loop iteration counter, predication counter.
11747
11748 Register SrcPhiReg, CurrSrcReg;
11749 if (IsMemcpy) {
11750 // Current position in the src array
11751 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11752 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11753 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11754 .addUse(OpSrcReg)
11755 .addMBB(TpEntry)
11756 .addUse(CurrSrcReg)
11757 .addMBB(TpLoopBody);
11758 }
11759
11760 // Current position in the dest array
11761 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11762 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11763 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11764 .addUse(OpDestReg)
11765 .addMBB(TpEntry)
11766 .addUse(CurrDestReg)
11767 .addMBB(TpLoopBody);
11768
11769 // Current loop counter
11770 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11771 Register RemainingLoopIterationsReg =
11772 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11773 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11774 .addUse(TotalIterationsReg)
11775 .addMBB(TpEntry)
11776 .addUse(RemainingLoopIterationsReg)
11777 .addMBB(TpLoopBody);
11778
11779 // Predication counter
11780 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11781 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11782 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11783 .addUse(ElementCountReg)
11784 .addMBB(TpEntry)
11785 .addUse(RemainingElementsReg)
11786 .addMBB(TpLoopBody);
11787
11788 // Pass predication counter to VCTP
11789 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11790 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11791 .addUse(PredCounterPhiReg)
11793 .addReg(0)
11794 .addReg(0);
11795
11796 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11797 .addUse(PredCounterPhiReg)
11798 .addImm(16)
11800 .addReg(0);
11801
11802 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11803 Register SrcValueReg;
11804 if (IsMemcpy) {
11805 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11806 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11807 .addDef(CurrSrcReg)
11808 .addDef(SrcValueReg)
11809 .addReg(SrcPhiReg)
11810 .addImm(16)
11812 .addUse(VccrReg)
11813 .addReg(0);
11814 } else
11815 SrcValueReg = OpSrcReg;
11816
11817 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11818 .addDef(CurrDestReg)
11819 .addUse(SrcValueReg)
11820 .addReg(DestPhiReg)
11821 .addImm(16)
11823 .addUse(VccrReg)
11824 .addReg(0);
11825
11826 // Add the pseudoInstrs for decrementing the loop counter and marking the
11827 // end:t2DoLoopDec and t2DoLoopEnd
11828 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11829 .addUse(LoopCounterPhiReg)
11830 .addImm(1);
11831
11832 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11833 .addUse(RemainingLoopIterationsReg)
11834 .addMBB(TpLoopBody);
11835
11836 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11837 .addMBB(TpExit)
11839}
11840
11842 // KCFI is supported in all ARM/Thumb modes
11843 return true;
11844}
11845
11849 const TargetInstrInfo *TII) const {
11850 assert(MBBI->isCall() && MBBI->getCFIType() &&
11851 "Invalid call instruction for a KCFI check");
11852
11853 MachineOperand *TargetOp = nullptr;
11854 switch (MBBI->getOpcode()) {
11855 // ARM mode opcodes
11856 case ARM::BLX:
11857 case ARM::BLX_pred:
11858 case ARM::BLX_noip:
11859 case ARM::BLX_pred_noip:
11860 case ARM::BX_CALL:
11861 TargetOp = &MBBI->getOperand(0);
11862 break;
11863 case ARM::TCRETURNri:
11864 case ARM::TCRETURNrinotr12:
11865 case ARM::TAILJMPr:
11866 case ARM::TAILJMPr4:
11867 TargetOp = &MBBI->getOperand(0);
11868 break;
11869 // Thumb mode opcodes (Thumb1 and Thumb2)
11870 // Note: Most Thumb call instructions have predicate operands before the
11871 // target register Format: tBLXr pred, predreg, target_register, ...
11872 case ARM::tBLXr: // Thumb1/Thumb2: BLX register (requires V5T)
11873 case ARM::tBLXr_noip: // Thumb1/Thumb2: BLX register, no IP clobber
11874 case ARM::tBX_CALL: // Thumb1 only: BX call (push LR, BX)
11875 TargetOp = &MBBI->getOperand(2);
11876 break;
11877 // Tail call instructions don't have predicates, target is operand 0
11878 case ARM::tTAILJMPr: // Thumb1/Thumb2: Tail call via register
11879 TargetOp = &MBBI->getOperand(0);
11880 break;
11881 default:
11882 llvm_unreachable("Unexpected CFI call opcode");
11883 }
11884
11885 assert(TargetOp && TargetOp->isReg() && "Invalid target operand");
11886 TargetOp->setIsRenamable(false);
11887
11888 // Select the appropriate KCFI_CHECK variant based on the instruction set
11889 unsigned KCFICheckOpcode;
11890 if (Subtarget->isThumb()) {
11891 if (Subtarget->isThumb2()) {
11892 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb2;
11893 } else {
11894 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb1;
11895 }
11896 } else {
11897 KCFICheckOpcode = ARM::KCFI_CHECK_ARM;
11898 }
11899
11900 return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(KCFICheckOpcode))
11901 .addReg(TargetOp->getReg())
11902 .addImm(MBBI->getCFIType())
11903 .getInstr();
11904}
11905
11908 MachineBasicBlock *BB) const {
11909 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11910 DebugLoc dl = MI.getDebugLoc();
11911 bool isThumb2 = Subtarget->isThumb2();
11912 switch (MI.getOpcode()) {
11913 default: {
11914 MI.print(errs());
11915 llvm_unreachable("Unexpected instr type to insert");
11916 }
11917
11918 // Thumb1 post-indexed loads are really just single-register LDMs.
11919 case ARM::tLDR_postidx: {
11920 MachineOperand Def(MI.getOperand(1));
11921 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11922 .add(Def) // Rn_wb
11923 .add(MI.getOperand(2)) // Rn
11924 .add(MI.getOperand(3)) // PredImm
11925 .add(MI.getOperand(4)) // PredReg
11926 .add(MI.getOperand(0)) // Rt
11927 .cloneMemRefs(MI);
11928 MI.eraseFromParent();
11929 return BB;
11930 }
11931
11932 case ARM::MVE_MEMCPYLOOPINST:
11933 case ARM::MVE_MEMSETLOOPINST: {
11934
11935 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11936 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11937 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11938 // adds the relevant instructions in the TP loop Body for generation of a
11939 // WLSTP loop.
11940
11941 // Below is relevant portion of the CFG after the transformation.
11942 // The Machine Basic Blocks are shown along with branch conditions (in
11943 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11944 // portion of the CFG and may not necessarily be the entry/exit of the
11945 // function.
11946
11947 // (Relevant) CFG after transformation:
11948 // TP entry MBB
11949 // |
11950 // |-----------------|
11951 // (n <= 0) (n > 0)
11952 // | |
11953 // | TP loop Body MBB<--|
11954 // | | |
11955 // \ |___________|
11956 // \ /
11957 // TP exit MBB
11958
11959 MachineFunction *MF = BB->getParent();
11960 MachineFunctionProperties &Properties = MF->getProperties();
11962
11963 Register OpDestReg = MI.getOperand(0).getReg();
11964 Register OpSrcReg = MI.getOperand(1).getReg();
11965 Register OpSizeReg = MI.getOperand(2).getReg();
11966
11967 // Allocate the required MBBs and add to parent function.
11968 MachineBasicBlock *TpEntry = BB;
11969 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11970 MachineBasicBlock *TpExit;
11971
11972 MF->push_back(TpLoopBody);
11973
11974 // If any instructions are present in the current block after
11975 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11976 // move the instructions into the newly created exit block. If there are no
11977 // instructions add an explicit branch to the FallThrough block and then
11978 // split.
11979 //
11980 // The split is required for two reasons:
11981 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
11982 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
11983 // need to be updated. splitAt() already handles this.
11984 TpExit = BB->splitAt(MI, false);
11985 if (TpExit == BB) {
11986 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
11987 "block containing memcpy/memset Pseudo");
11988 TpExit = BB->getFallThrough();
11989 BuildMI(BB, dl, TII->get(ARM::t2B))
11990 .addMBB(TpExit)
11992 TpExit = BB->splitAt(MI, false);
11993 }
11994
11995 // Add logic for iteration count
11996 Register TotalIterationsReg =
11997 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
11998
11999 // Add the vectorized (and predicated) loads/store instructions
12000 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12001 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
12002 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
12003
12004 // Required to avoid conflict with the MachineVerifier during testing.
12005 Properties.resetNoPHIs();
12006
12007 // Connect the blocks
12008 TpEntry->addSuccessor(TpLoopBody);
12009 TpLoopBody->addSuccessor(TpLoopBody);
12010 TpLoopBody->addSuccessor(TpExit);
12011
12012 // Reorder for a more natural layout
12013 TpLoopBody->moveAfter(TpEntry);
12014 TpExit->moveAfter(TpLoopBody);
12015
12016 // Finally, remove the memcpy Pseudo Instruction
12017 MI.eraseFromParent();
12018
12019 // Return the exit block as it may contain other instructions requiring a
12020 // custom inserter
12021 return TpExit;
12022 }
12023
12024 // The Thumb2 pre-indexed stores have the same MI operands, they just
12025 // define them differently in the .td files from the isel patterns, so
12026 // they need pseudos.
12027 case ARM::t2STR_preidx:
12028 MI.setDesc(TII->get(ARM::t2STR_PRE));
12029 return BB;
12030 case ARM::t2STRB_preidx:
12031 MI.setDesc(TII->get(ARM::t2STRB_PRE));
12032 return BB;
12033 case ARM::t2STRH_preidx:
12034 MI.setDesc(TII->get(ARM::t2STRH_PRE));
12035 return BB;
12036
12037 case ARM::STRi_preidx:
12038 case ARM::STRBi_preidx: {
12039 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12040 : ARM::STRB_PRE_IMM;
12041 // Decode the offset.
12042 unsigned Offset = MI.getOperand(4).getImm();
12043 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
12045 if (isSub)
12046 Offset = -Offset;
12047
12048 MachineMemOperand *MMO = *MI.memoperands_begin();
12049 BuildMI(*BB, MI, dl, TII->get(NewOpc))
12050 .add(MI.getOperand(0)) // Rn_wb
12051 .add(MI.getOperand(1)) // Rt
12052 .add(MI.getOperand(2)) // Rn
12053 .addImm(Offset) // offset (skip GPR==zero_reg)
12054 .add(MI.getOperand(5)) // pred
12055 .add(MI.getOperand(6))
12056 .addMemOperand(MMO);
12057 MI.eraseFromParent();
12058 return BB;
12059 }
12060 case ARM::STRr_preidx:
12061 case ARM::STRBr_preidx:
12062 case ARM::STRH_preidx: {
12063 unsigned NewOpc;
12064 switch (MI.getOpcode()) {
12065 default: llvm_unreachable("unexpected opcode!");
12066 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12067 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12068 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12069 }
12070 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
12071 for (const MachineOperand &MO : MI.operands())
12072 MIB.add(MO);
12073 MI.eraseFromParent();
12074 return BB;
12075 }
12076
12077 case ARM::tMOVCCr_pseudo: {
12078 // To "insert" a SELECT_CC instruction, we actually have to insert the
12079 // diamond control-flow pattern. The incoming instruction knows the
12080 // destination vreg to set, the condition code register to branch on, the
12081 // true/false values to select between, and a branch opcode to use.
12082 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12084
12085 // thisMBB:
12086 // ...
12087 // TrueVal = ...
12088 // cmpTY ccX, r1, r2
12089 // bCC copy1MBB
12090 // fallthrough --> copy0MBB
12091 MachineBasicBlock *thisMBB = BB;
12092 MachineFunction *F = BB->getParent();
12093 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12094 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12095 F->insert(It, copy0MBB);
12096 F->insert(It, sinkMBB);
12097
12098 // Set the call frame size on entry to the new basic blocks.
12099 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12100 copy0MBB->setCallFrameSize(CallFrameSize);
12101 sinkMBB->setCallFrameSize(CallFrameSize);
12102
12103 // Check whether CPSR is live past the tMOVCCr_pseudo.
12104 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12105 if (!MI.killsRegister(ARM::CPSR, /*TRI=*/nullptr) &&
12106 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
12107 copy0MBB->addLiveIn(ARM::CPSR);
12108 sinkMBB->addLiveIn(ARM::CPSR);
12109 }
12110
12111 // Transfer the remainder of BB and its successor edges to sinkMBB.
12112 sinkMBB->splice(sinkMBB->begin(), BB,
12113 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12115
12116 BB->addSuccessor(copy0MBB);
12117 BB->addSuccessor(sinkMBB);
12118
12119 BuildMI(BB, dl, TII->get(ARM::tBcc))
12120 .addMBB(sinkMBB)
12121 .addImm(MI.getOperand(3).getImm())
12122 .addReg(MI.getOperand(4).getReg());
12123
12124 // copy0MBB:
12125 // %FalseValue = ...
12126 // # fallthrough to sinkMBB
12127 BB = copy0MBB;
12128
12129 // Update machine-CFG edges
12130 BB->addSuccessor(sinkMBB);
12131
12132 // sinkMBB:
12133 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12134 // ...
12135 BB = sinkMBB;
12136 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
12137 .addReg(MI.getOperand(1).getReg())
12138 .addMBB(copy0MBB)
12139 .addReg(MI.getOperand(2).getReg())
12140 .addMBB(thisMBB);
12141
12142 MI.eraseFromParent(); // The pseudo instruction is gone now.
12143 return BB;
12144 }
12145
12146 case ARM::BCCi64:
12147 case ARM::BCCZi64: {
12148 // If there is an unconditional branch to the other successor, remove it.
12149 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
12150
12151 // Compare both parts that make up the double comparison separately for
12152 // equality.
12153 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12154
12155 Register LHS1 = MI.getOperand(1).getReg();
12156 Register LHS2 = MI.getOperand(2).getReg();
12157 if (RHSisZero) {
12158 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12159 .addReg(LHS1)
12160 .addImm(0)
12162 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12163 .addReg(LHS2).addImm(0)
12164 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12165 } else {
12166 Register RHS1 = MI.getOperand(3).getReg();
12167 Register RHS2 = MI.getOperand(4).getReg();
12168 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12169 .addReg(LHS1)
12170 .addReg(RHS1)
12172 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12173 .addReg(LHS2).addReg(RHS2)
12174 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12175 }
12176
12177 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12178 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12179 if (MI.getOperand(0).getImm() == ARMCC::NE)
12180 std::swap(destMBB, exitMBB);
12181
12182 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12183 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12184 if (isThumb2)
12185 BuildMI(BB, dl, TII->get(ARM::t2B))
12186 .addMBB(exitMBB)
12188 else
12189 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12190
12191 MI.eraseFromParent(); // The pseudo instruction is gone now.
12192 return BB;
12193 }
12194
12195 case ARM::Int_eh_sjlj_setjmp:
12196 case ARM::Int_eh_sjlj_setjmp_nofp:
12197 case ARM::tInt_eh_sjlj_setjmp:
12198 case ARM::t2Int_eh_sjlj_setjmp:
12199 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12200 return BB;
12201
12202 case ARM::Int_eh_sjlj_setup_dispatch:
12203 EmitSjLjDispatchBlock(MI, BB);
12204 return BB;
12205 case ARM::COPY_STRUCT_BYVAL_I32:
12206 ++NumLoopByVals;
12207 return EmitStructByval(MI, BB);
12208 case ARM::WIN__CHKSTK:
12209 return EmitLowered__chkstk(MI, BB);
12210 case ARM::WIN__DBZCHK:
12211 return EmitLowered__dbzchk(MI, BB);
12212 }
12213}
12214
12215/// Attaches vregs to MEMCPY that it will use as scratch registers
12216/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12217/// instead of as a custom inserter because we need the use list from the SDNode.
12219 MachineInstr &MI, const SDNode *Node) {
12220 bool isThumb1 = Subtarget->isThumb1Only();
12221
12222 MachineFunction *MF = MI.getParent()->getParent();
12224 MachineInstrBuilder MIB(*MF, MI);
12225
12226 // If the new dst/src is unused mark it as dead.
12227 if (!Node->hasAnyUseOfValue(0)) {
12228 MI.getOperand(0).setIsDead(true);
12229 }
12230 if (!Node->hasAnyUseOfValue(1)) {
12231 MI.getOperand(1).setIsDead(true);
12232 }
12233
12234 // The MEMCPY both defines and kills the scratch registers.
12235 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12236 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12237 : &ARM::GPRRegClass);
12239 }
12240}
12241
12243 SDNode *Node) const {
12244 if (MI.getOpcode() == ARM::MEMCPY) {
12245 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12246 return;
12247 }
12248
12249 const MCInstrDesc *MCID = &MI.getDesc();
12250 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12251 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12252 // operand is still set to noreg. If needed, set the optional operand's
12253 // register to CPSR, and remove the redundant implicit def.
12254 //
12255 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12256
12257 // Rename pseudo opcodes.
12258 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12259 unsigned ccOutIdx;
12260 if (NewOpc) {
12261 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12262 MCID = &TII->get(NewOpc);
12263
12264 assert(MCID->getNumOperands() ==
12265 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12266 && "converted opcode should be the same except for cc_out"
12267 " (and, on Thumb1, pred)");
12268
12269 MI.setDesc(*MCID);
12270
12271 // Add the optional cc_out operand
12272 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12273
12274 // On Thumb1, move all input operands to the end, then add the predicate
12275 if (Subtarget->isThumb1Only()) {
12276 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12277 MI.addOperand(MI.getOperand(1));
12278 MI.removeOperand(1);
12279 }
12280
12281 // Restore the ties
12282 for (unsigned i = MI.getNumOperands(); i--;) {
12283 const MachineOperand& op = MI.getOperand(i);
12284 if (op.isReg() && op.isUse()) {
12285 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12286 if (DefIdx != -1)
12287 MI.tieOperands(DefIdx, i);
12288 }
12289 }
12290
12292 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12293 ccOutIdx = 1;
12294 } else
12295 ccOutIdx = MCID->getNumOperands() - 1;
12296 } else
12297 ccOutIdx = MCID->getNumOperands() - 1;
12298
12299 // Any ARM instruction that sets the 's' bit should specify an optional
12300 // "cc_out" operand in the last operand position.
12301 if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12302 assert(!NewOpc && "Optional cc_out operand required");
12303 return;
12304 }
12305 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12306 // since we already have an optional CPSR def.
12307 bool definesCPSR = false;
12308 bool deadCPSR = false;
12309 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12310 ++i) {
12311 const MachineOperand &MO = MI.getOperand(i);
12312 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12313 definesCPSR = true;
12314 if (MO.isDead())
12315 deadCPSR = true;
12316 MI.removeOperand(i);
12317 break;
12318 }
12319 }
12320 if (!definesCPSR) {
12321 assert(!NewOpc && "Optional cc_out operand required");
12322 return;
12323 }
12324 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12325 if (deadCPSR) {
12326 assert(!MI.getOperand(ccOutIdx).getReg() &&
12327 "expect uninitialized optional cc_out operand");
12328 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12329 if (!Subtarget->isThumb1Only())
12330 return;
12331 }
12332
12333 // If this instruction was defined with an optional CPSR def and its dag node
12334 // had a live implicit CPSR def, then activate the optional CPSR def.
12335 MachineOperand &MO = MI.getOperand(ccOutIdx);
12336 MO.setReg(ARM::CPSR);
12337 MO.setIsDef(true);
12338 MO.setIsDead(deadCPSR);
12339}
12340
12341//===----------------------------------------------------------------------===//
12342// ARM Optimization Hooks
12343//===----------------------------------------------------------------------===//
12344
12345// Helper function that checks if N is a null or all ones constant.
12346static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12348}
12349
12350// Return true if N is conditionally 0 or all ones.
12351// Detects these expressions where cc is an i1 value:
12352//
12353// (select cc 0, y) [AllOnes=0]
12354// (select cc y, 0) [AllOnes=0]
12355// (zext cc) [AllOnes=0]
12356// (sext cc) [AllOnes=0/1]
12357// (select cc -1, y) [AllOnes=1]
12358// (select cc y, -1) [AllOnes=1]
12359//
12360// Invert is set when N is the null/all ones constant when CC is false.
12361// OtherOp is set to the alternative value of N.
12363 SDValue &CC, bool &Invert,
12364 SDValue &OtherOp,
12365 SelectionDAG &DAG) {
12366 switch (N->getOpcode()) {
12367 default: return false;
12368 case ISD::SELECT: {
12369 CC = N->getOperand(0);
12370 SDValue N1 = N->getOperand(1);
12371 SDValue N2 = N->getOperand(2);
12372 if (isZeroOrAllOnes(N1, AllOnes)) {
12373 Invert = false;
12374 OtherOp = N2;
12375 return true;
12376 }
12377 if (isZeroOrAllOnes(N2, AllOnes)) {
12378 Invert = true;
12379 OtherOp = N1;
12380 return true;
12381 }
12382 return false;
12383 }
12384 case ISD::ZERO_EXTEND:
12385 // (zext cc) can never be the all ones value.
12386 if (AllOnes)
12387 return false;
12388 [[fallthrough]];
12389 case ISD::SIGN_EXTEND: {
12390 SDLoc dl(N);
12391 EVT VT = N->getValueType(0);
12392 CC = N->getOperand(0);
12393 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12394 return false;
12395 Invert = !AllOnes;
12396 if (AllOnes)
12397 // When looking for an AllOnes constant, N is an sext, and the 'other'
12398 // value is 0.
12399 OtherOp = DAG.getConstant(0, dl, VT);
12400 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12401 // When looking for a 0 constant, N can be zext or sext.
12402 OtherOp = DAG.getConstant(1, dl, VT);
12403 else
12404 OtherOp = DAG.getAllOnesConstant(dl, VT);
12405 return true;
12406 }
12407 }
12408}
12409
12410// Combine a constant select operand into its use:
12411//
12412// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12413// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12414// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12415// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12416// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12417//
12418// The transform is rejected if the select doesn't have a constant operand that
12419// is null, or all ones when AllOnes is set.
12420//
12421// Also recognize sext/zext from i1:
12422//
12423// (add (zext cc), x) -> (select cc (add x, 1), x)
12424// (add (sext cc), x) -> (select cc (add x, -1), x)
12425//
12426// These transformations eventually create predicated instructions.
12427//
12428// @param N The node to transform.
12429// @param Slct The N operand that is a select.
12430// @param OtherOp The other N operand (x above).
12431// @param DCI Context.
12432// @param AllOnes Require the select constant to be all ones instead of null.
12433// @returns The new node, or SDValue() on failure.
12434static
12437 bool AllOnes = false) {
12438 SelectionDAG &DAG = DCI.DAG;
12439 EVT VT = N->getValueType(0);
12440 SDValue NonConstantVal;
12441 SDValue CCOp;
12442 bool SwapSelectOps;
12443 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12444 NonConstantVal, DAG))
12445 return SDValue();
12446
12447 // Slct is now know to be the desired identity constant when CC is true.
12448 SDValue TrueVal = OtherOp;
12449 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12450 OtherOp, NonConstantVal);
12451 // Unless SwapSelectOps says CC should be false.
12452 if (SwapSelectOps)
12453 std::swap(TrueVal, FalseVal);
12454
12455 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12456 CCOp, TrueVal, FalseVal);
12457}
12458
12459// Attempt combineSelectAndUse on each operand of a commutative operator N.
12460static
12463 SDValue N0 = N->getOperand(0);
12464 SDValue N1 = N->getOperand(1);
12465 if (N0.getNode()->hasOneUse())
12466 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12467 return Result;
12468 if (N1.getNode()->hasOneUse())
12469 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12470 return Result;
12471 return SDValue();
12472}
12473
12475 // VUZP shuffle node.
12476 if (N->getOpcode() == ARMISD::VUZP)
12477 return true;
12478
12479 // "VUZP" on i32 is an alias for VTRN.
12480 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12481 return true;
12482
12483 return false;
12484}
12485
12488 const ARMSubtarget *Subtarget) {
12489 // Look for ADD(VUZP.0, VUZP.1).
12490 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12491 N0 == N1)
12492 return SDValue();
12493
12494 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12495 if (!N->getValueType(0).is64BitVector())
12496 return SDValue();
12497
12498 // Generate vpadd.
12499 SelectionDAG &DAG = DCI.DAG;
12501 SDLoc dl(N);
12502 SDNode *Unzip = N0.getNode();
12503 EVT VT = N->getValueType(0);
12504
12506 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12507 TLI.getPointerTy(DAG.getDataLayout())));
12508 Ops.push_back(Unzip->getOperand(0));
12509 Ops.push_back(Unzip->getOperand(1));
12510
12511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12512}
12513
12516 const ARMSubtarget *Subtarget) {
12517 // Check for two extended operands.
12518 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12519 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12520 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12521 N1.getOpcode() == ISD::ZERO_EXTEND))
12522 return SDValue();
12523
12524 SDValue N00 = N0.getOperand(0);
12525 SDValue N10 = N1.getOperand(0);
12526
12527 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12528 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12529 N00 == N10)
12530 return SDValue();
12531
12532 // We only recognize Q register paddl here; this can't be reached until
12533 // after type legalization.
12534 if (!N00.getValueType().is64BitVector() ||
12536 return SDValue();
12537
12538 // Generate vpaddl.
12539 SelectionDAG &DAG = DCI.DAG;
12541 SDLoc dl(N);
12542 EVT VT = N->getValueType(0);
12543
12545 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12546 unsigned Opcode;
12547 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12548 Opcode = Intrinsic::arm_neon_vpaddls;
12549 else
12550 Opcode = Intrinsic::arm_neon_vpaddlu;
12551 Ops.push_back(DAG.getConstant(Opcode, dl,
12552 TLI.getPointerTy(DAG.getDataLayout())));
12554 unsigned NumElts = VT.getVectorNumElements();
12555 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12556 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12557 N00.getOperand(0), N00.getOperand(1));
12558 Ops.push_back(Concat);
12559
12560 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12561}
12562
12563// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12564// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12565// much easier to match.
12566static SDValue
12569 const ARMSubtarget *Subtarget) {
12570 // Only perform optimization if after legalize, and if NEON is available. We
12571 // also expected both operands to be BUILD_VECTORs.
12572 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12573 || N0.getOpcode() != ISD::BUILD_VECTOR
12574 || N1.getOpcode() != ISD::BUILD_VECTOR)
12575 return SDValue();
12576
12577 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12578 EVT VT = N->getValueType(0);
12579 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12580 return SDValue();
12581
12582 // Check that the vector operands are of the right form.
12583 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12584 // operands, where N is the size of the formed vector.
12585 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12586 // index such that we have a pair wise add pattern.
12587
12588 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12590 return SDValue();
12591 SDValue Vec = N0->getOperand(0)->getOperand(0);
12592 SDNode *V = Vec.getNode();
12593 unsigned nextIndex = 0;
12594
12595 // For each operands to the ADD which are BUILD_VECTORs,
12596 // check to see if each of their operands are an EXTRACT_VECTOR with
12597 // the same vector and appropriate index.
12598 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12601
12602 SDValue ExtVec0 = N0->getOperand(i);
12603 SDValue ExtVec1 = N1->getOperand(i);
12604
12605 // First operand is the vector, verify its the same.
12606 if (V != ExtVec0->getOperand(0).getNode() ||
12607 V != ExtVec1->getOperand(0).getNode())
12608 return SDValue();
12609
12610 // Second is the constant, verify its correct.
12613
12614 // For the constant, we want to see all the even or all the odd.
12615 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12616 || C1->getZExtValue() != nextIndex+1)
12617 return SDValue();
12618
12619 // Increment index.
12620 nextIndex+=2;
12621 } else
12622 return SDValue();
12623 }
12624
12625 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12626 // we're using the entire input vector, otherwise there's a size/legality
12627 // mismatch somewhere.
12628 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12630 return SDValue();
12631
12632 // Create VPADDL node.
12633 SelectionDAG &DAG = DCI.DAG;
12635
12636 SDLoc dl(N);
12637
12638 // Build operand list.
12640 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12641 TLI.getPointerTy(DAG.getDataLayout())));
12642
12643 // Input is the vector.
12644 Ops.push_back(Vec);
12645
12646 // Get widened type and narrowed type.
12647 MVT widenType;
12648 unsigned numElem = VT.getVectorNumElements();
12649
12650 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12651 switch (inputLaneType.getSimpleVT().SimpleTy) {
12652 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12653 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12654 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12655 default:
12656 llvm_unreachable("Invalid vector element type for padd optimization.");
12657 }
12658
12659 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12660 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12661 return DAG.getNode(ExtOp, dl, VT, tmp);
12662}
12663
12665 if (V->getOpcode() == ISD::UMUL_LOHI ||
12666 V->getOpcode() == ISD::SMUL_LOHI)
12667 return V;
12668 return SDValue();
12669}
12670
12671static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12673 const ARMSubtarget *Subtarget) {
12674 if (!Subtarget->hasBaseDSP())
12675 return SDValue();
12676
12677 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12678 // accumulates the product into a 64-bit value. The 16-bit values will
12679 // be sign extended somehow or SRA'd into 32-bit values
12680 // (addc (adde (mul 16bit, 16bit), lo), hi)
12681 SDValue Mul = AddcNode->getOperand(0);
12682 SDValue Lo = AddcNode->getOperand(1);
12683 if (Mul.getOpcode() != ISD::MUL) {
12684 Lo = AddcNode->getOperand(0);
12685 Mul = AddcNode->getOperand(1);
12686 if (Mul.getOpcode() != ISD::MUL)
12687 return SDValue();
12688 }
12689
12690 SDValue SRA = AddeNode->getOperand(0);
12691 SDValue Hi = AddeNode->getOperand(1);
12692 if (SRA.getOpcode() != ISD::SRA) {
12693 SRA = AddeNode->getOperand(1);
12694 Hi = AddeNode->getOperand(0);
12695 if (SRA.getOpcode() != ISD::SRA)
12696 return SDValue();
12697 }
12698 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12699 if (Const->getZExtValue() != 31)
12700 return SDValue();
12701 } else
12702 return SDValue();
12703
12704 if (SRA.getOperand(0) != Mul)
12705 return SDValue();
12706
12707 SelectionDAG &DAG = DCI.DAG;
12708 SDLoc dl(AddcNode);
12709 unsigned Opcode = 0;
12710 SDValue Op0;
12711 SDValue Op1;
12712
12713 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12714 Opcode = ARMISD::SMLALBB;
12715 Op0 = Mul.getOperand(0);
12716 Op1 = Mul.getOperand(1);
12717 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12718 Opcode = ARMISD::SMLALBT;
12719 Op0 = Mul.getOperand(0);
12720 Op1 = Mul.getOperand(1).getOperand(0);
12721 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12722 Opcode = ARMISD::SMLALTB;
12723 Op0 = Mul.getOperand(0).getOperand(0);
12724 Op1 = Mul.getOperand(1);
12725 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12726 Opcode = ARMISD::SMLALTT;
12727 Op0 = Mul->getOperand(0).getOperand(0);
12728 Op1 = Mul->getOperand(1).getOperand(0);
12729 }
12730
12731 if (!Op0 || !Op1)
12732 return SDValue();
12733
12734 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12735 Op0, Op1, Lo, Hi);
12736 // Replace the ADDs' nodes uses by the MLA node's values.
12737 SDValue HiMLALResult(SMLAL.getNode(), 1);
12738 SDValue LoMLALResult(SMLAL.getNode(), 0);
12739
12740 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12741 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12742 DCI.recursivelyDeleteUnusedNodes(AddeNode);
12743
12744 // Return original node to notify the driver to stop replacing.
12745 return SDValue(AddeNode, 0);
12746}
12747
12750 const ARMSubtarget *Subtarget) {
12751 // Look for multiply add opportunities.
12752 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12753 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12754 // a glue link from the first add to the second add.
12755 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12756 // a S/UMLAL instruction.
12757 // UMUL_LOHI
12758 // / :lo \ :hi
12759 // V \ [no multiline comment]
12760 // loAdd -> ADDC |
12761 // \ :carry /
12762 // V V
12763 // ADDE <- hiAdd
12764 //
12765 // In the special case where only the higher part of a signed result is used
12766 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12767 // a constant with the exact value of 0x80000000, we recognize we are dealing
12768 // with a "rounded multiply and add" (or subtract) and transform it into
12769 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12770
12771 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12772 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12773 "Expect an ADDE or SUBE");
12774
12775 assert(AddeSubeNode->getNumOperands() == 3 &&
12776 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12777 "ADDE node has the wrong inputs");
12778
12779 if (AddeSubeNode->hasAnyUseOfValue(1))
12780 return SDValue();
12781
12782 // Check that we are chained to the right ADDC or SUBC node.
12783 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12784 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12785 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12786 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12787 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12788 return SDValue();
12789
12790 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12791 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12792
12793 // Check if the two operands are from the same mul_lohi node.
12794 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12795 return SDValue();
12796
12797 assert(AddcSubcNode->getNumValues() == 2 &&
12798 AddcSubcNode->getValueType(0) == MVT::i32 &&
12799 "Expect ADDC with two result values. First: i32");
12800
12801 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12802 // maybe a SMLAL which multiplies two 16-bit values.
12803 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12804 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12805 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12806 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12807 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12808 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12809
12810 // Check for the triangle shape.
12811 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12812 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12813
12814 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12815 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12816 return SDValue();
12817
12818 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12819 bool IsLeftOperandMUL = false;
12820 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12821 if (MULOp == SDValue())
12822 MULOp = findMUL_LOHI(AddeSubeOp1);
12823 else
12824 IsLeftOperandMUL = true;
12825 if (MULOp == SDValue())
12826 return SDValue();
12827
12828 // Figure out the right opcode.
12829 unsigned Opc = MULOp->getOpcode();
12830 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12831
12832 // Figure out the high and low input values to the MLAL node.
12833 SDValue *HiAddSub = nullptr;
12834 SDValue *LoMul = nullptr;
12835 SDValue *LowAddSub = nullptr;
12836
12837 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12838 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12839 return SDValue();
12840
12841 if (IsLeftOperandMUL)
12842 HiAddSub = &AddeSubeOp1;
12843 else
12844 HiAddSub = &AddeSubeOp0;
12845
12846 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12847 // whose low result is fed to the ADDC/SUBC we are checking.
12848
12849 if (AddcSubcOp0 == MULOp.getValue(0)) {
12850 LoMul = &AddcSubcOp0;
12851 LowAddSub = &AddcSubcOp1;
12852 }
12853 if (AddcSubcOp1 == MULOp.getValue(0)) {
12854 LoMul = &AddcSubcOp1;
12855 LowAddSub = &AddcSubcOp0;
12856 }
12857
12858 if (!LoMul)
12859 return SDValue();
12860
12861 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12862 // the replacement below will create a cycle.
12863 if (AddcSubcNode == HiAddSub->getNode() ||
12864 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12865 return SDValue();
12866
12867 // Create the merged node.
12868 SelectionDAG &DAG = DCI.DAG;
12869
12870 // Start building operand list.
12872 Ops.push_back(LoMul->getOperand(0));
12873 Ops.push_back(LoMul->getOperand(1));
12874
12875 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12876 // the case, we must be doing signed multiplication and only use the higher
12877 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12878 // addition or subtraction with the value of 0x800000.
12879 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12880 FinalOpc == ARMISD::SMLAL &&
12881 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12882 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12883 0x80000000) {
12884 Ops.push_back(*HiAddSub);
12885 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12886 FinalOpc = ARMISD::SMMLSR;
12887 } else {
12888 FinalOpc = ARMISD::SMMLAR;
12889 }
12890 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12891 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12892
12893 return SDValue(AddeSubeNode, 0);
12894 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12895 // SMMLS is generated during instruction selection and the rest of this
12896 // function can not handle the case where AddcSubcNode is a SUBC.
12897 return SDValue();
12898
12899 // Finish building the operand list for {U/S}MLAL
12900 Ops.push_back(*LowAddSub);
12901 Ops.push_back(*HiAddSub);
12902
12903 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12904 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12905
12906 // Replace the ADDs' nodes uses by the MLA node's values.
12907 SDValue HiMLALResult(MLALNode.getNode(), 1);
12908 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12909
12910 SDValue LoMLALResult(MLALNode.getNode(), 0);
12911 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12912
12913 // Return original node to notify the driver to stop replacing.
12914 return SDValue(AddeSubeNode, 0);
12915}
12916
12919 const ARMSubtarget *Subtarget) {
12920 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12921 // While trying to combine for the other MLAL nodes, first search for the
12922 // chance to use UMAAL. Check if Addc uses a node which has already
12923 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12924 // as the addend, and it's handled in PerformUMLALCombine.
12925
12926 if (AddeNode->hasAnyUseOfValue(1))
12927 return SDValue();
12928
12929 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12930 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12931
12932 // Check that we have a glued ADDC node.
12933 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12934 if (AddcNode->getOpcode() != ARMISD::ADDC)
12935 return SDValue();
12936
12937 // Find the converted UMAAL or quit if it doesn't exist.
12938 SDNode *UmlalNode = nullptr;
12939 SDValue AddHi;
12940 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12941 UmlalNode = AddcNode->getOperand(0).getNode();
12942 AddHi = AddcNode->getOperand(1);
12943 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12944 UmlalNode = AddcNode->getOperand(1).getNode();
12945 AddHi = AddcNode->getOperand(0);
12946 } else {
12947 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12948 }
12949
12950 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12951 // the ADDC as well as Zero.
12952 if (!isNullConstant(UmlalNode->getOperand(3)))
12953 return SDValue();
12954
12955 if ((isNullConstant(AddeNode->getOperand(0)) &&
12956 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12957 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12958 isNullConstant(AddeNode->getOperand(1)))) {
12959 SelectionDAG &DAG = DCI.DAG;
12960 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12961 UmlalNode->getOperand(2), AddHi };
12962 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12963 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12964
12965 // Replace the ADDs' nodes uses by the UMAAL node's values.
12966 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12967 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12968
12969 // Return original node to notify the driver to stop replacing.
12970 return SDValue(AddeNode, 0);
12971 }
12972 return SDValue();
12973}
12974
12976 const ARMSubtarget *Subtarget) {
12977 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12978 return SDValue();
12979
12980 // Check that we have a pair of ADDC and ADDE as operands.
12981 // Both addends of the ADDE must be zero.
12982 SDNode* AddcNode = N->getOperand(2).getNode();
12983 SDNode* AddeNode = N->getOperand(3).getNode();
12984 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12985 (AddeNode->getOpcode() == ARMISD::ADDE) &&
12986 isNullConstant(AddeNode->getOperand(0)) &&
12987 isNullConstant(AddeNode->getOperand(1)) &&
12988 (AddeNode->getOperand(2).getNode() == AddcNode))
12989 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12990 DAG.getVTList(MVT::i32, MVT::i32),
12991 {N->getOperand(0), N->getOperand(1),
12992 AddcNode->getOperand(0), AddcNode->getOperand(1)});
12993 else
12994 return SDValue();
12995}
12996
12999 const ARMSubtarget *Subtarget) {
13000 SelectionDAG &DAG(DCI.DAG);
13001
13002 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
13003 // (SUBC (ADDE 0, 0, C), 1) -> C
13004 SDValue LHS = N->getOperand(0);
13005 SDValue RHS = N->getOperand(1);
13006 if (LHS->getOpcode() == ARMISD::ADDE &&
13007 isNullConstant(LHS->getOperand(0)) &&
13008 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
13009 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
13010 }
13011 }
13012
13013 if (Subtarget->isThumb1Only()) {
13014 SDValue RHS = N->getOperand(1);
13016 int32_t imm = C->getSExtValue();
13017 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13018 SDLoc DL(N);
13019 RHS = DAG.getConstant(-imm, DL, MVT::i32);
13020 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13021 : ARMISD::ADDC;
13022 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
13023 }
13024 }
13025 }
13026
13027 return SDValue();
13028}
13029
13032 const ARMSubtarget *Subtarget) {
13033 if (Subtarget->isThumb1Only()) {
13034 SelectionDAG &DAG = DCI.DAG;
13035 SDValue RHS = N->getOperand(1);
13037 int64_t imm = C->getSExtValue();
13038 if (imm < 0) {
13039 SDLoc DL(N);
13040
13041 // The with-carry-in form matches bitwise not instead of the negation.
13042 // Effectively, the inverse interpretation of the carry flag already
13043 // accounts for part of the negation.
13044 RHS = DAG.getConstant(~imm, DL, MVT::i32);
13045
13046 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13047 : ARMISD::ADDE;
13048 return DAG.getNode(Opcode, DL, N->getVTList(),
13049 N->getOperand(0), RHS, N->getOperand(2));
13050 }
13051 }
13052 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
13053 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
13054 }
13055 return SDValue();
13056}
13057
13060 const ARMSubtarget *Subtarget) {
13061 if (!Subtarget->hasMVEIntegerOps())
13062 return SDValue();
13063
13064 SDLoc dl(N);
13065 SDValue SetCC;
13066 SDValue LHS;
13067 SDValue RHS;
13069 SDValue TrueVal;
13070 SDValue FalseVal;
13071
13072 if (N->getOpcode() == ISD::SELECT &&
13073 N->getOperand(0)->getOpcode() == ISD::SETCC) {
13074 SetCC = N->getOperand(0);
13075 LHS = SetCC->getOperand(0);
13076 RHS = SetCC->getOperand(1);
13077 CC = SetCC->getOperandCondCode(2);
13078 TrueVal = N->getOperand(1);
13079 FalseVal = N->getOperand(2);
13080 } else if (N->getOpcode() == ISD::SELECT_CC) {
13081 LHS = N->getOperand(0);
13082 RHS = N->getOperand(1);
13083 CC = N->getOperandCondCode(4);
13084 TrueVal = N->getOperand(2);
13085 FalseVal = N->getOperand(3);
13086 } else {
13087 return SDValue();
13088 }
13089
13090 unsigned int Opcode = 0;
13091 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13092 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13093 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13094 Opcode = ARMISD::VMINVu;
13095 if (CC == ISD::SETUGT)
13096 std::swap(TrueVal, FalseVal);
13097 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13098 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13099 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13100 Opcode = ARMISD::VMINVs;
13101 if (CC == ISD::SETGT)
13102 std::swap(TrueVal, FalseVal);
13103 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13104 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13105 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13106 Opcode = ARMISD::VMAXVu;
13107 if (CC == ISD::SETULT)
13108 std::swap(TrueVal, FalseVal);
13109 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13110 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13111 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13112 Opcode = ARMISD::VMAXVs;
13113 if (CC == ISD::SETLT)
13114 std::swap(TrueVal, FalseVal);
13115 } else
13116 return SDValue();
13117
13118 // Normalise to the right hand side being the vector reduction
13119 switch (TrueVal->getOpcode()) {
13124 std::swap(LHS, RHS);
13125 std::swap(TrueVal, FalseVal);
13126 break;
13127 }
13128
13129 EVT VectorType = FalseVal->getOperand(0).getValueType();
13130
13131 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13132 VectorType != MVT::v4i32)
13133 return SDValue();
13134
13135 EVT VectorScalarType = VectorType.getVectorElementType();
13136
13137 // The values being selected must also be the ones being compared
13138 if (TrueVal != LHS || FalseVal != RHS)
13139 return SDValue();
13140
13141 EVT LeftType = LHS->getValueType(0);
13142 EVT RightType = RHS->getValueType(0);
13143
13144 // The types must match the reduced type too
13145 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13146 return SDValue();
13147
13148 // Legalise the scalar to an i32
13149 if (VectorScalarType != MVT::i32)
13150 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13151
13152 // Generate the reduction as an i32 for legalisation purposes
13153 auto Reduction =
13154 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13155
13156 // The result isn't actually an i32 so truncate it back to its original type
13157 if (VectorScalarType != MVT::i32)
13158 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13159
13160 return Reduction;
13161}
13162
13163// A special combine for the vqdmulh family of instructions. This is one of the
13164// potential set of patterns that could patch this instruction. The base pattern
13165// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13166// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13167// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13168// the max is unnecessary.
13170 EVT VT = N->getValueType(0);
13171 SDValue Shft;
13172 ConstantSDNode *Clamp;
13173
13174 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13175 return SDValue();
13176
13177 if (N->getOpcode() == ISD::SMIN) {
13178 Shft = N->getOperand(0);
13179 Clamp = isConstOrConstSplat(N->getOperand(1));
13180 } else if (N->getOpcode() == ISD::VSELECT) {
13181 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13182 SDValue Cmp = N->getOperand(0);
13183 if (Cmp.getOpcode() != ISD::SETCC ||
13184 Cmp.getOperandCondCode(2) != ISD::SETLT ||
13185 Cmp.getOperand(0) != N->getOperand(1) ||
13186 Cmp.getOperand(1) != N->getOperand(2))
13187 return SDValue();
13188 Shft = N->getOperand(1);
13189 Clamp = isConstOrConstSplat(N->getOperand(2));
13190 } else
13191 return SDValue();
13192
13193 if (!Clamp)
13194 return SDValue();
13195
13196 MVT ScalarType;
13197 int ShftAmt = 0;
13198 switch (Clamp->getSExtValue()) {
13199 case (1 << 7) - 1:
13200 ScalarType = MVT::i8;
13201 ShftAmt = 7;
13202 break;
13203 case (1 << 15) - 1:
13204 ScalarType = MVT::i16;
13205 ShftAmt = 15;
13206 break;
13207 case (1ULL << 31) - 1:
13208 ScalarType = MVT::i32;
13209 ShftAmt = 31;
13210 break;
13211 default:
13212 return SDValue();
13213 }
13214
13215 if (Shft.getOpcode() != ISD::SRA)
13216 return SDValue();
13218 if (!N1 || N1->getSExtValue() != ShftAmt)
13219 return SDValue();
13220
13221 SDValue Mul = Shft.getOperand(0);
13222 if (Mul.getOpcode() != ISD::MUL)
13223 return SDValue();
13224
13225 SDValue Ext0 = Mul.getOperand(0);
13226 SDValue Ext1 = Mul.getOperand(1);
13227 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13228 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13229 return SDValue();
13230 EVT VecVT = Ext0.getOperand(0).getValueType();
13231 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13232 return SDValue();
13233 if (Ext1.getOperand(0).getValueType() != VecVT ||
13234 VecVT.getScalarType() != ScalarType ||
13235 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13236 return SDValue();
13237
13238 SDLoc DL(Mul);
13239 unsigned LegalLanes = 128 / (ShftAmt + 1);
13240 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13241 // For types smaller than legal vectors extend to be legal and only use needed
13242 // lanes.
13243 if (VecVT.getSizeInBits() < 128) {
13244 EVT ExtVecVT =
13246 VecVT.getVectorNumElements());
13247 SDValue Inp0 =
13248 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13249 SDValue Inp1 =
13250 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13251 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13252 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13253 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13254 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13255 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13256 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13257 }
13258
13259 // For larger types, split into legal sized chunks.
13260 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13261 unsigned NumParts = VecVT.getSizeInBits() / 128;
13263 for (unsigned I = 0; I < NumParts; ++I) {
13264 SDValue Inp0 =
13265 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13266 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13267 SDValue Inp1 =
13268 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13269 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13270 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13271 Parts.push_back(VQDMULH);
13272 }
13273 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13274 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13275}
13276
13279 const ARMSubtarget *Subtarget) {
13280 if (!Subtarget->hasMVEIntegerOps())
13281 return SDValue();
13282
13283 // Constant fold vselect 0, A, B -> B
13284 // and vselect 0xffff, A, B -> A
13285 if (N->getOperand(0).getOpcode() == ARMISD::PREDICATE_CAST &&
13286 isa<ConstantSDNode>(N->getOperand(0).getOperand(0))) {
13287 unsigned C = N->getOperand(0).getConstantOperandVal(0);
13288 if (C == 0)
13289 return N->getOperand(2);
13290 if (C == 0xffff)
13291 return N->getOperand(1);
13292 }
13293
13294 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13295 return V;
13296
13297 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13298 //
13299 // We need to re-implement this optimization here as the implementation in the
13300 // Target-Independent DAGCombiner does not handle the kind of constant we make
13301 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13302 // good reason, allowing truncation there would break other targets).
13303 //
13304 // Currently, this is only done for MVE, as it's the only target that benefits
13305 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13306 if (N->getOperand(0).getOpcode() != ISD::XOR)
13307 return SDValue();
13308 SDValue XOR = N->getOperand(0);
13309
13310 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13311 // It is important to check with truncation allowed as the BUILD_VECTORs we
13312 // generate in those situations will truncate their operands.
13313 ConstantSDNode *Const =
13314 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13315 /*AllowTruncation*/ true);
13316 if (!Const || !Const->isOne())
13317 return SDValue();
13318
13319 // Rewrite into vselect(cond, rhs, lhs).
13320 SDValue Cond = XOR->getOperand(0);
13321 SDValue LHS = N->getOperand(1);
13322 SDValue RHS = N->getOperand(2);
13323 EVT Type = N->getValueType(0);
13324 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13325}
13326
13327// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13330 const ARMSubtarget *Subtarget) {
13331 SDValue Op0 = N->getOperand(0);
13332 SDValue Op1 = N->getOperand(1);
13333 ISD::CondCode CC = N->getOperandCondCode(2);
13334 EVT VT = N->getValueType(0);
13335
13336 if (!Subtarget->hasMVEIntegerOps() ||
13338 return SDValue();
13339
13340 if (CC == ISD::SETUGT) {
13341 std::swap(Op0, Op1);
13342 CC = ISD::SETULT;
13343 }
13344
13345 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13347 return SDValue();
13348
13349 // Check first operand is BuildVector of 0,1,2,...
13350 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13351 if (!Op0.getOperand(I).isUndef() &&
13353 Op0.getConstantOperandVal(I) == I))
13354 return SDValue();
13355 }
13356
13357 // The second is a Splat of Op1S
13358 SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13359 if (!Op1S)
13360 return SDValue();
13361
13362 unsigned Opc;
13363 switch (VT.getVectorNumElements()) {
13364 case 4:
13365 Opc = Intrinsic::arm_mve_vctp32;
13366 break;
13367 case 8:
13368 Opc = Intrinsic::arm_mve_vctp16;
13369 break;
13370 case 16:
13371 Opc = Intrinsic::arm_mve_vctp8;
13372 break;
13373 default:
13374 return SDValue();
13375 }
13376
13377 SDLoc DL(N);
13378 return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13379 DCI.DAG.getConstant(Opc, DL, MVT::i32),
13380 DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13381}
13382
13383/// PerformADDECombine - Target-specific dag combine transform from
13384/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13385/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13388 const ARMSubtarget *Subtarget) {
13389 // Only ARM and Thumb2 support UMLAL/SMLAL.
13390 if (Subtarget->isThumb1Only())
13391 return PerformAddeSubeCombine(N, DCI, Subtarget);
13392
13393 // Only perform the checks after legalize when the pattern is available.
13394 if (DCI.isBeforeLegalize()) return SDValue();
13395
13396 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13397}
13398
13399/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13400/// operands N0 and N1. This is a helper for PerformADDCombine that is
13401/// called with the default operands, and if that fails, with commuted
13402/// operands.
13405 const ARMSubtarget *Subtarget){
13406 // Attempt to create vpadd for this add.
13407 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13408 return Result;
13409
13410 // Attempt to create vpaddl for this add.
13411 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13412 return Result;
13413 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13414 Subtarget))
13415 return Result;
13416
13417 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13418 if (N0.getNode()->hasOneUse())
13419 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13420 return Result;
13421 return SDValue();
13422}
13423
13425 EVT VT = N->getValueType(0);
13426 SDValue N0 = N->getOperand(0);
13427 SDValue N1 = N->getOperand(1);
13428 SDLoc dl(N);
13429
13430 auto IsVecReduce = [](SDValue Op) {
13431 switch (Op.getOpcode()) {
13432 case ISD::VECREDUCE_ADD:
13433 case ARMISD::VADDVs:
13434 case ARMISD::VADDVu:
13435 case ARMISD::VMLAVs:
13436 case ARMISD::VMLAVu:
13437 return true;
13438 }
13439 return false;
13440 };
13441
13442 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13443 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13444 // add(add(X, vecreduce(Y)), vecreduce(Z))
13445 // to make better use of vaddva style instructions.
13446 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13447 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13448 !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13449 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13450 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13451 }
13452 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13453 // add(add(add(A, C), reduce(B)), reduce(D))
13454 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13455 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13456 unsigned N0RedOp = 0;
13457 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13458 N0RedOp = 1;
13459 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13460 return SDValue();
13461 }
13462
13463 unsigned N1RedOp = 0;
13464 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13465 N1RedOp = 1;
13466 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13467 return SDValue();
13468
13469 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13470 N1.getOperand(1 - N1RedOp));
13471 SDValue Add1 =
13472 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13473 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13474 }
13475 return SDValue();
13476 };
13477 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13478 return R;
13479 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13480 return R;
13481
13482 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13483 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13484 // by ascending load offsets. This can help cores prefetch if the order of
13485 // loads is more predictable.
13486 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13487 // Check if two reductions are known to load data where one is before/after
13488 // another. Return negative if N0 loads data before N1, positive if N1 is
13489 // before N0 and 0 otherwise if nothing is known.
13490 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13491 // Look through to the first operand of a MUL, for the VMLA case.
13492 // Currently only looks at the first operand, in the hope they are equal.
13493 if (N0.getOpcode() == ISD::MUL)
13494 N0 = N0.getOperand(0);
13495 if (N1.getOpcode() == ISD::MUL)
13496 N1 = N1.getOperand(0);
13497
13498 // Return true if the two operands are loads to the same object and the
13499 // offset of the first is known to be less than the offset of the second.
13500 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13501 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13502 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13503 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13504 Load1->isIndexed())
13505 return 0;
13506
13507 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13508 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13509
13510 if (!BaseLocDecomp0.getBase() ||
13511 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13512 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13513 return 0;
13514 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13515 return -1;
13516 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13517 return 1;
13518 return 0;
13519 };
13520
13521 SDValue X;
13522 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13523 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13524 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13525 N0.getOperand(1).getOperand(0));
13526 if (IsBefore < 0) {
13527 X = N0.getOperand(0);
13528 N0 = N0.getOperand(1);
13529 } else if (IsBefore > 0) {
13530 X = N0.getOperand(1);
13531 N0 = N0.getOperand(0);
13532 } else
13533 return SDValue();
13534 } else if (IsVecReduce(N0.getOperand(0))) {
13535 X = N0.getOperand(1);
13536 N0 = N0.getOperand(0);
13537 } else if (IsVecReduce(N0.getOperand(1))) {
13538 X = N0.getOperand(0);
13539 N0 = N0.getOperand(1);
13540 } else
13541 return SDValue();
13542 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13543 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13544 // Note this is backward to how you would expect. We create
13545 // add(reduce(load + 16), reduce(load + 0)) so that the
13546 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13547 // the X as VADDV(load + 0)
13548 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13549 } else
13550 return SDValue();
13551
13552 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13553 return SDValue();
13554
13555 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13556 return SDValue();
13557
13558 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13559 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13560 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13561 };
13562 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13563 return R;
13564 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13565 return R;
13566 return SDValue();
13567}
13568
13570 const ARMSubtarget *Subtarget) {
13571 if (!Subtarget->hasMVEIntegerOps())
13572 return SDValue();
13573
13575 return R;
13576
13577 EVT VT = N->getValueType(0);
13578 SDValue N0 = N->getOperand(0);
13579 SDValue N1 = N->getOperand(1);
13580 SDLoc dl(N);
13581
13582 if (VT != MVT::i64)
13583 return SDValue();
13584
13585 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13586 // will look like:
13587 // t1: i32,i32 = ARMISD::VADDLVs x
13588 // t2: i64 = build_pair t1, t1:1
13589 // t3: i64 = add t2, y
13590 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13591 // the add to be simplified separately.
13592 // We also need to check for sext / zext and commutitive adds.
13593 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13594 SDValue NB) {
13595 if (NB->getOpcode() != ISD::BUILD_PAIR)
13596 return SDValue();
13597 SDValue VecRed = NB->getOperand(0);
13598 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13599 VecRed.getResNo() != 0 ||
13600 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13601 return SDValue();
13602
13603 if (VecRed->getOpcode() == OpcodeA) {
13604 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13605 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13606 VecRed.getOperand(0), VecRed.getOperand(1));
13607 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13608 }
13609
13611 std::tie(Ops[0], Ops[1]) = DAG.SplitScalar(NA, dl, MVT::i32, MVT::i32);
13612
13613 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13614 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13615 Ops.push_back(VecRed->getOperand(I));
13616 SDValue Red =
13617 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13618 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13619 SDValue(Red.getNode(), 1));
13620 };
13621
13622 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13623 return M;
13624 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13625 return M;
13626 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13627 return M;
13628 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13629 return M;
13630 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13631 return M;
13632 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13633 return M;
13634 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13635 return M;
13636 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13637 return M;
13638 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13639 return M;
13640 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13641 return M;
13642 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13643 return M;
13644 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13645 return M;
13646 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13647 return M;
13648 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13649 return M;
13650 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13651 return M;
13652 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13653 return M;
13654 return SDValue();
13655}
13656
13657bool
13659 CombineLevel Level) const {
13660 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13661 N->getOpcode() == ISD::SRL) &&
13662 "Expected shift op");
13663
13664 SDValue ShiftLHS = N->getOperand(0);
13665 if (!ShiftLHS->hasOneUse())
13666 return false;
13667
13668 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13669 !ShiftLHS.getOperand(0)->hasOneUse())
13670 return false;
13671
13672 if (Level == BeforeLegalizeTypes)
13673 return true;
13674
13675 if (N->getOpcode() != ISD::SHL)
13676 return true;
13677
13678 if (Subtarget->isThumb1Only()) {
13679 // Avoid making expensive immediates by commuting shifts. (This logic
13680 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13681 // for free.)
13682 if (N->getOpcode() != ISD::SHL)
13683 return true;
13684 SDValue N1 = N->getOperand(0);
13685 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13686 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13687 return true;
13688 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13689 if (Const->getAPIntValue().ult(256))
13690 return false;
13691 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13692 Const->getAPIntValue().sgt(-256))
13693 return false;
13694 }
13695 return true;
13696 }
13697
13698 // Turn off commute-with-shift transform after legalization, so it doesn't
13699 // conflict with PerformSHLSimplify. (We could try to detect when
13700 // PerformSHLSimplify would trigger more precisely, but it isn't
13701 // really necessary.)
13702 return false;
13703}
13704
13706 const SDNode *N) const {
13707 assert(N->getOpcode() == ISD::XOR &&
13708 (N->getOperand(0).getOpcode() == ISD::SHL ||
13709 N->getOperand(0).getOpcode() == ISD::SRL) &&
13710 "Expected XOR(SHIFT) pattern");
13711
13712 // Only commute if the entire NOT mask is a hidden shifted mask.
13713 auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13714 auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13715 if (XorC && ShiftC) {
13716 unsigned MaskIdx, MaskLen;
13717 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13718 unsigned ShiftAmt = ShiftC->getZExtValue();
13719 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13720 if (N->getOperand(0).getOpcode() == ISD::SHL)
13721 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13722 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13723 }
13724 }
13725
13726 return false;
13727}
13728
13730 const SDNode *N) const {
13731 assert(((N->getOpcode() == ISD::SHL &&
13732 N->getOperand(0).getOpcode() == ISD::SRL) ||
13733 (N->getOpcode() == ISD::SRL &&
13734 N->getOperand(0).getOpcode() == ISD::SHL)) &&
13735 "Expected shift-shift mask");
13736
13737 if (!Subtarget->isThumb1Only())
13738 return true;
13739
13740 EVT VT = N->getValueType(0);
13741 if (VT.getScalarSizeInBits() > 32)
13742 return true;
13743
13744 return false;
13745}
13746
13748 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13749 SDValue Y) const {
13750 return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13751 SelectOpcode == ISD::VSELECT;
13752}
13753
13755 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) {
13756 if (Subtarget->isThumb1Only())
13757 return VT.getScalarSizeInBits() <= 32;
13758 return true;
13759 }
13760 return VT.isScalarInteger();
13761}
13762
13764 EVT VT) const {
13765 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13766 return false;
13767
13768 switch (FPVT.getSimpleVT().SimpleTy) {
13769 case MVT::f16:
13770 return Subtarget->hasVFP2Base();
13771 case MVT::f32:
13772 return Subtarget->hasVFP2Base();
13773 case MVT::f64:
13774 return Subtarget->hasFP64();
13775 case MVT::v4f32:
13776 case MVT::v8f16:
13777 return Subtarget->hasMVEFloatOps();
13778 default:
13779 return false;
13780 }
13781}
13782
13785 const ARMSubtarget *ST) {
13786 // Allow the generic combiner to identify potential bswaps.
13787 if (DCI.isBeforeLegalize())
13788 return SDValue();
13789
13790 // DAG combiner will fold:
13791 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13792 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13793 // Other code patterns that can be also be modified have the following form:
13794 // b + ((a << 1) | 510)
13795 // b + ((a << 1) & 510)
13796 // b + ((a << 1) ^ 510)
13797 // b + ((a << 1) + 510)
13798
13799 // Many instructions can perform the shift for free, but it requires both
13800 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13801 // instruction will needed. So, unfold back to the original pattern if:
13802 // - if c1 and c2 are small enough that they don't require mov imms.
13803 // - the user(s) of the node can perform an shl
13804
13805 // No shifted operands for 16-bit instructions.
13806 if (ST->isThumb1Only())
13807 return SDValue();
13808
13809 // Check that all the users could perform the shl themselves.
13810 for (auto *U : N->users()) {
13811 switch(U->getOpcode()) {
13812 default:
13813 return SDValue();
13814 case ISD::SUB:
13815 case ISD::ADD:
13816 case ISD::AND:
13817 case ISD::OR:
13818 case ISD::XOR:
13819 case ISD::SETCC:
13820 case ARMISD::CMP:
13821 // Check that the user isn't already using a constant because there
13822 // aren't any instructions that support an immediate operand and a
13823 // shifted operand.
13824 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13825 isa<ConstantSDNode>(U->getOperand(1)))
13826 return SDValue();
13827
13828 // Check that it's not already using a shift.
13829 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13830 U->getOperand(1).getOpcode() == ISD::SHL)
13831 return SDValue();
13832 break;
13833 }
13834 }
13835
13836 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13837 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13838 return SDValue();
13839
13840 if (N->getOperand(0).getOpcode() != ISD::SHL)
13841 return SDValue();
13842
13843 SDValue SHL = N->getOperand(0);
13844
13845 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13846 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13847 if (!C1ShlC2 || !C2)
13848 return SDValue();
13849
13850 APInt C2Int = C2->getAPIntValue();
13851 APInt C1Int = C1ShlC2->getAPIntValue();
13852 unsigned C2Width = C2Int.getBitWidth();
13853 if (C2Int.uge(C2Width))
13854 return SDValue();
13855 uint64_t C2Value = C2Int.getZExtValue();
13856
13857 // Check that performing a lshr will not lose any information.
13858 APInt Mask = APInt::getHighBitsSet(C2Width, C2Width - C2Value);
13859 if ((C1Int & Mask) != C1Int)
13860 return SDValue();
13861
13862 // Shift the first constant.
13863 C1Int.lshrInPlace(C2Int);
13864
13865 // The immediates are encoded as an 8-bit value that can be rotated.
13866 auto LargeImm = [](const APInt &Imm) {
13867 unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13868 return Imm.getBitWidth() - Zeros > 8;
13869 };
13870
13871 if (LargeImm(C1Int) || LargeImm(C2Int))
13872 return SDValue();
13873
13874 SelectionDAG &DAG = DCI.DAG;
13875 SDLoc dl(N);
13876 SDValue X = SHL.getOperand(0);
13877 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13878 DAG.getConstant(C1Int, dl, MVT::i32));
13879 // Shift left to compensate for the lshr of C1Int.
13880 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13881
13882 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
13883 SHL.dump(); N->dump());
13884 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
13885 return Res;
13886}
13887
13888
13889/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13890///
13893 const ARMSubtarget *Subtarget) {
13894 SDValue N0 = N->getOperand(0);
13895 SDValue N1 = N->getOperand(1);
13896
13897 // Only works one way, because it needs an immediate operand.
13898 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13899 return Result;
13900
13901 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13902 return Result;
13903
13904 // First try with the default operand order.
13905 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13906 return Result;
13907
13908 // If that didn't work, try again with the operands commuted.
13909 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13910}
13911
13912// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13913// providing -X is as cheap as X (currently, just a constant).
13915 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13916 return SDValue();
13917 SDValue CSINC = N->getOperand(1);
13918 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13919 return SDValue();
13920
13922 if (!X)
13923 return SDValue();
13924
13925 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13926 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13927 CSINC.getOperand(0)),
13928 CSINC.getOperand(1), CSINC.getOperand(2),
13929 CSINC.getOperand(3));
13930}
13931
13933 // Free to negate.
13935 return 0;
13936
13937 // Will save one instruction.
13938 if (Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)))
13939 return -1;
13940
13941 // Can freely negate by converting sra <-> srl.
13942 if (Op.getOpcode() == ISD::SRA || Op.getOpcode() == ISD::SRL) {
13943 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13944 if (Op.hasOneUse() && ShiftAmt &&
13945 ShiftAmt->getZExtValue() == Op.getValueType().getScalarSizeInBits() - 1)
13946 return 0;
13947 }
13948
13949 // Will have to create sub.
13950 return 1;
13951}
13952
13953// Try to fold
13954//
13955// (neg (cmov X, Y)) -> (cmov (neg X), (neg Y))
13956//
13957// The folding helps cmov to be matched with csneg without generating
13958// redundant neg instruction.
13960 assert(N->getOpcode() == ISD::SUB);
13961 if (!isNullConstant(N->getOperand(0)))
13962 return SDValue();
13963
13964 SDValue CMov = N->getOperand(1);
13965 if (CMov.getOpcode() != ARMISD::CMOV || !CMov->hasOneUse())
13966 return SDValue();
13967
13968 SDValue N0 = CMov.getOperand(0);
13969 SDValue N1 = CMov.getOperand(1);
13970
13971 // Only perform the fold if we actually save something.
13972 if (getNegationCost(N0) + getNegationCost(N1) > 0)
13973 return SDValue();
13974
13975 SDLoc DL(N);
13976 EVT VT = CMov.getValueType();
13977
13978 SDValue N0N = DAG.getNegative(N0, DL, VT);
13979 SDValue N1N = DAG.getNegative(N1, DL, VT);
13980 return DAG.getNode(ARMISD::CMOV, DL, VT, N0N, N1N, CMov.getOperand(2),
13981 CMov.getOperand(3));
13982}
13983
13984/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13985///
13988 const ARMSubtarget *Subtarget) {
13989 SDValue N0 = N->getOperand(0);
13990 SDValue N1 = N->getOperand(1);
13991
13992 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
13993 if (N1.getNode()->hasOneUse())
13994 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
13995 return Result;
13996
13997 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
13998 return R;
13999
14000 if (SDValue Val = performNegCMovCombine(N, DCI.DAG))
14001 return Val;
14002
14003 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
14004 return SDValue();
14005
14006 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14007 // so that we can readily pattern match more mve instructions which can use
14008 // a scalar operand.
14009 SDValue VDup = N->getOperand(1);
14010 if (VDup->getOpcode() != ARMISD::VDUP)
14011 return SDValue();
14012
14013 SDValue VMov = N->getOperand(0);
14014 if (VMov->getOpcode() == ISD::BITCAST)
14015 VMov = VMov->getOperand(0);
14016
14017 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
14018 return SDValue();
14019
14020 SDLoc dl(N);
14021 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
14022 DCI.DAG.getConstant(0, dl, MVT::i32),
14023 VDup->getOperand(0));
14024 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
14025}
14026
14027/// PerformVMULCombine
14028/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14029/// special multiplier accumulator forwarding.
14030/// vmul d3, d0, d2
14031/// vmla d3, d1, d2
14032/// is faster than
14033/// vadd d3, d0, d1
14034/// vmul d3, d3, d2
14035// However, for (A + B) * (A + B),
14036// vadd d2, d0, d1
14037// vmul d3, d0, d2
14038// vmla d3, d1, d2
14039// is slower than
14040// vadd d2, d0, d1
14041// vmul d3, d2, d2
14044 const ARMSubtarget *Subtarget) {
14045 if (!Subtarget->hasVMLxForwarding())
14046 return SDValue();
14047
14048 SelectionDAG &DAG = DCI.DAG;
14049 SDValue N0 = N->getOperand(0);
14050 SDValue N1 = N->getOperand(1);
14051 unsigned Opcode = N0.getOpcode();
14052 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14053 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14054 Opcode = N1.getOpcode();
14055 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14056 Opcode != ISD::FADD && Opcode != ISD::FSUB)
14057 return SDValue();
14058 std::swap(N0, N1);
14059 }
14060
14061 if (N0 == N1)
14062 return SDValue();
14063
14064 EVT VT = N->getValueType(0);
14065 SDLoc DL(N);
14066 SDValue N00 = N0->getOperand(0);
14067 SDValue N01 = N0->getOperand(1);
14068 return DAG.getNode(Opcode, DL, VT,
14069 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
14070 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
14071}
14072
14074 const ARMSubtarget *Subtarget) {
14075 EVT VT = N->getValueType(0);
14076 if (VT != MVT::v2i64)
14077 return SDValue();
14078
14079 SDValue N0 = N->getOperand(0);
14080 SDValue N1 = N->getOperand(1);
14081
14082 auto IsSignExt = [&](SDValue Op) {
14083 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14084 return SDValue();
14085 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
14086 if (VT.getScalarSizeInBits() == 32)
14087 return Op->getOperand(0);
14088 return SDValue();
14089 };
14090 auto IsZeroExt = [&](SDValue Op) {
14091 // Zero extends are a little more awkward. At the point we are matching
14092 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14093 // That might be before of after a bitcast depending on how the and is
14094 // placed. Because this has to look through bitcasts, it is currently only
14095 // supported on LE.
14096 if (!Subtarget->isLittle())
14097 return SDValue();
14098
14099 SDValue And = Op;
14100 if (And->getOpcode() == ISD::BITCAST)
14101 And = And->getOperand(0);
14102 if (And->getOpcode() != ISD::AND)
14103 return SDValue();
14104 SDValue Mask = And->getOperand(1);
14105 if (Mask->getOpcode() == ISD::BITCAST)
14106 Mask = Mask->getOperand(0);
14107
14108 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14109 Mask.getValueType() != MVT::v4i32)
14110 return SDValue();
14111 if (isAllOnesConstant(Mask->getOperand(0)) &&
14112 isNullConstant(Mask->getOperand(1)) &&
14113 isAllOnesConstant(Mask->getOperand(2)) &&
14114 isNullConstant(Mask->getOperand(3)))
14115 return And->getOperand(0);
14116 return SDValue();
14117 };
14118
14119 SDLoc dl(N);
14120 if (SDValue Op0 = IsSignExt(N0)) {
14121 if (SDValue Op1 = IsSignExt(N1)) {
14122 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14123 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14124 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
14125 }
14126 }
14127 if (SDValue Op0 = IsZeroExt(N0)) {
14128 if (SDValue Op1 = IsZeroExt(N1)) {
14129 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14130 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14131 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
14132 }
14133 }
14134
14135 return SDValue();
14136}
14137
14140 const ARMSubtarget *Subtarget) {
14141 SelectionDAG &DAG = DCI.DAG;
14142
14143 EVT VT = N->getValueType(0);
14144 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14145 return PerformMVEVMULLCombine(N, DAG, Subtarget);
14146
14147 if (Subtarget->isThumb1Only())
14148 return SDValue();
14149
14150 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14151 return SDValue();
14152
14153 if (VT.is64BitVector() || VT.is128BitVector())
14154 return PerformVMULCombine(N, DCI, Subtarget);
14155 if (VT != MVT::i32)
14156 return SDValue();
14157
14158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14159 if (!C)
14160 return SDValue();
14161
14162 int64_t MulAmt = C->getSExtValue();
14163 unsigned ShiftAmt = llvm::countr_zero<uint64_t>(MulAmt);
14164
14165 ShiftAmt = ShiftAmt & (32 - 1);
14166 SDValue V = N->getOperand(0);
14167 SDLoc DL(N);
14168
14169 SDValue Res;
14170 MulAmt >>= ShiftAmt;
14171
14172 if (MulAmt >= 0) {
14173 if (llvm::has_single_bit<uint32_t>(MulAmt - 1)) {
14174 // (mul x, 2^N + 1) => (add (shl x, N), x)
14175 Res = DAG.getNode(ISD::ADD, DL, VT,
14176 V,
14177 DAG.getNode(ISD::SHL, DL, VT,
14178 V,
14179 DAG.getConstant(Log2_32(MulAmt - 1), DL,
14180 MVT::i32)));
14181 } else if (llvm::has_single_bit<uint32_t>(MulAmt + 1)) {
14182 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14183 Res = DAG.getNode(ISD::SUB, DL, VT,
14184 DAG.getNode(ISD::SHL, DL, VT,
14185 V,
14186 DAG.getConstant(Log2_32(MulAmt + 1), DL,
14187 MVT::i32)),
14188 V);
14189 } else
14190 return SDValue();
14191 } else {
14192 uint64_t MulAmtAbs = -MulAmt;
14193 if (llvm::has_single_bit<uint32_t>(MulAmtAbs + 1)) {
14194 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14195 Res = DAG.getNode(ISD::SUB, DL, VT,
14196 V,
14197 DAG.getNode(ISD::SHL, DL, VT,
14198 V,
14199 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14200 MVT::i32)));
14201 } else if (llvm::has_single_bit<uint32_t>(MulAmtAbs - 1)) {
14202 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14203 Res = DAG.getNode(ISD::ADD, DL, VT,
14204 V,
14205 DAG.getNode(ISD::SHL, DL, VT,
14206 V,
14207 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14208 MVT::i32)));
14209 Res = DAG.getNode(ISD::SUB, DL, VT,
14210 DAG.getConstant(0, DL, MVT::i32), Res);
14211 } else
14212 return SDValue();
14213 }
14214
14215 if (ShiftAmt != 0)
14216 Res = DAG.getNode(ISD::SHL, DL, VT,
14217 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14218
14219 // Do not add new nodes to DAG combiner worklist.
14220 DCI.CombineTo(N, Res, false);
14221 return SDValue();
14222}
14223
14226 const ARMSubtarget *Subtarget) {
14227 // Allow DAGCombine to pattern-match before we touch the canonical form.
14228 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14229 return SDValue();
14230
14231 if (N->getValueType(0) != MVT::i32)
14232 return SDValue();
14233
14234 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14235 if (!N1C)
14236 return SDValue();
14237
14238 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14239 // Don't transform uxtb/uxth.
14240 if (C1 == 255 || C1 == 65535)
14241 return SDValue();
14242
14243 SDNode *N0 = N->getOperand(0).getNode();
14244 if (!N0->hasOneUse())
14245 return SDValue();
14246
14247 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14248 return SDValue();
14249
14250 bool LeftShift = N0->getOpcode() == ISD::SHL;
14251
14253 if (!N01C)
14254 return SDValue();
14255
14256 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14257 if (!C2 || C2 >= 32)
14258 return SDValue();
14259
14260 // Clear irrelevant bits in the mask.
14261 if (LeftShift)
14262 C1 &= (-1U << C2);
14263 else
14264 C1 &= (-1U >> C2);
14265
14266 SelectionDAG &DAG = DCI.DAG;
14267 SDLoc DL(N);
14268
14269 // We have a pattern of the form "(and (shl x, c2) c1)" or
14270 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14271 // transform to a pair of shifts, to save materializing c1.
14272
14273 // First pattern: right shift, then mask off leading bits.
14274 // FIXME: Use demanded bits?
14275 if (!LeftShift && isMask_32(C1)) {
14277 if (C2 < C3) {
14278 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14279 DAG.getConstant(C3 - C2, DL, MVT::i32));
14280 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14281 DAG.getConstant(C3, DL, MVT::i32));
14282 }
14283 }
14284
14285 // First pattern, reversed: left shift, then mask off trailing bits.
14286 if (LeftShift && isMask_32(~C1)) {
14288 if (C2 < C3) {
14289 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14290 DAG.getConstant(C3 - C2, DL, MVT::i32));
14291 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14292 DAG.getConstant(C3, DL, MVT::i32));
14293 }
14294 }
14295
14296 // Second pattern: left shift, then mask off leading bits.
14297 // FIXME: Use demanded bits?
14298 if (LeftShift && isShiftedMask_32(C1)) {
14299 uint32_t Trailing = llvm::countr_zero(C1);
14301 if (Trailing == C2 && C2 + C3 < 32) {
14302 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14303 DAG.getConstant(C2 + C3, DL, MVT::i32));
14304 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14305 DAG.getConstant(C3, DL, MVT::i32));
14306 }
14307 }
14308
14309 // Second pattern, reversed: right shift, then mask off trailing bits.
14310 // FIXME: Handle other patterns of known/demanded bits.
14311 if (!LeftShift && isShiftedMask_32(C1)) {
14312 uint32_t Leading = llvm::countl_zero(C1);
14314 if (Leading == C2 && C2 + C3 < 32) {
14315 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14316 DAG.getConstant(C2 + C3, DL, MVT::i32));
14317 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14318 DAG.getConstant(C3, DL, MVT::i32));
14319 }
14320 }
14321
14322 // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14323 // if "c1 >> c2" is a cheaper immediate than "c1"
14324 if (LeftShift &&
14326
14327 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i32, N0->getOperand(0),
14328 DAG.getConstant(C1 >> C2, DL, MVT::i32));
14329 return DAG.getNode(ISD::SHL, DL, MVT::i32, And,
14330 DAG.getConstant(C2, DL, MVT::i32));
14331 }
14332
14333 return SDValue();
14334}
14335
14338 const ARMSubtarget *Subtarget) {
14339 // Attempt to use immediate-form VBIC
14340 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14341 SDLoc dl(N);
14342 EVT VT = N->getValueType(0);
14343 SelectionDAG &DAG = DCI.DAG;
14344
14345 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14346 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14347 return SDValue();
14348
14349 APInt SplatBits, SplatUndef;
14350 unsigned SplatBitSize;
14351 bool HasAnyUndefs;
14352 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14353 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14354 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14355 SplatBitSize == 64) {
14356 EVT VbicVT;
14357 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14358 SplatUndef.getZExtValue(), SplatBitSize,
14359 DAG, dl, VbicVT, VT, OtherModImm);
14360 if (Val.getNode()) {
14361 SDValue Input =
14362 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VbicVT, N->getOperand(0));
14363 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14364 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vbic);
14365 }
14366 }
14367 }
14368
14369 if (!Subtarget->isThumb1Only()) {
14370 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14371 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14372 return Result;
14373
14374 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14375 return Result;
14376 }
14377
14378 if (Subtarget->isThumb1Only())
14379 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14380 return Result;
14381
14382 return SDValue();
14383}
14384
14385// Try combining OR nodes to SMULWB, SMULWT.
14388 const ARMSubtarget *Subtarget) {
14389 if (!Subtarget->hasV6Ops() ||
14390 (Subtarget->isThumb() &&
14391 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14392 return SDValue();
14393
14394 SDValue SRL = OR->getOperand(0);
14395 SDValue SHL = OR->getOperand(1);
14396
14397 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14398 SRL = OR->getOperand(1);
14399 SHL = OR->getOperand(0);
14400 }
14401 if (!isSRL16(SRL) || !isSHL16(SHL))
14402 return SDValue();
14403
14404 // The first operands to the shifts need to be the two results from the
14405 // same smul_lohi node.
14406 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14407 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14408 return SDValue();
14409
14410 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14411 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14412 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14413 return SDValue();
14414
14415 // Now we have:
14416 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14417 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14418 // For SMUWB the 16-bit value will signed extended somehow.
14419 // For SMULWT only the SRA is required.
14420 // Check both sides of SMUL_LOHI
14421 SDValue OpS16 = SMULLOHI->getOperand(0);
14422 SDValue OpS32 = SMULLOHI->getOperand(1);
14423
14424 SelectionDAG &DAG = DCI.DAG;
14425 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14426 OpS16 = OpS32;
14427 OpS32 = SMULLOHI->getOperand(0);
14428 }
14429
14430 SDLoc dl(OR);
14431 unsigned Opcode = 0;
14432 if (isS16(OpS16, DAG))
14433 Opcode = ARMISD::SMULWB;
14434 else if (isSRA16(OpS16)) {
14435 Opcode = ARMISD::SMULWT;
14436 OpS16 = OpS16->getOperand(0);
14437 }
14438 else
14439 return SDValue();
14440
14441 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14442 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14443 return SDValue(OR, 0);
14444}
14445
14448 const ARMSubtarget *Subtarget) {
14449 // BFI is only available on V6T2+
14450 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14451 return SDValue();
14452
14453 EVT VT = N->getValueType(0);
14454 SDValue N0 = N->getOperand(0);
14455 SDValue N1 = N->getOperand(1);
14456 SelectionDAG &DAG = DCI.DAG;
14457 SDLoc DL(N);
14458 // 1) or (and A, mask), val => ARMbfi A, val, mask
14459 // iff (val & mask) == val
14460 //
14461 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14462 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14463 // && mask == ~mask2
14464 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14465 // && ~mask == mask2
14466 // (i.e., copy a bitfield value into another bitfield of the same width)
14467
14468 if (VT != MVT::i32)
14469 return SDValue();
14470
14471 SDValue N00 = N0.getOperand(0);
14472
14473 // The value and the mask need to be constants so we can verify this is
14474 // actually a bitfield set. If the mask is 0xffff, we can do better
14475 // via a movt instruction, so don't use BFI in that case.
14476 SDValue MaskOp = N0.getOperand(1);
14478 if (!MaskC)
14479 return SDValue();
14480 unsigned Mask = MaskC->getZExtValue();
14481 if (Mask == 0xffff)
14482 return SDValue();
14483 SDValue Res;
14484 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14486 if (N1C) {
14487 unsigned Val = N1C->getZExtValue();
14488 if ((Val & ~Mask) != Val)
14489 return SDValue();
14490
14491 if (ARM::isBitFieldInvertedMask(Mask)) {
14492 Val >>= llvm::countr_zero(~Mask);
14493
14494 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14495 DAG.getConstant(Val, DL, MVT::i32),
14496 DAG.getConstant(Mask, DL, MVT::i32));
14497
14498 DCI.CombineTo(N, Res, false);
14499 // Return value from the original node to inform the combiner than N is
14500 // now dead.
14501 return SDValue(N, 0);
14502 }
14503 } else if (N1.getOpcode() == ISD::AND) {
14504 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14506 if (!N11C)
14507 return SDValue();
14508 unsigned Mask2 = N11C->getZExtValue();
14509
14510 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14511 // as is to match.
14512 if (ARM::isBitFieldInvertedMask(Mask) &&
14513 (Mask == ~Mask2)) {
14514 // The pack halfword instruction works better for masks that fit it,
14515 // so use that when it's available.
14516 if (Subtarget->hasDSP() &&
14517 (Mask == 0xffff || Mask == 0xffff0000))
14518 return SDValue();
14519 // 2a
14520 unsigned amt = llvm::countr_zero(Mask2);
14521 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14522 DAG.getConstant(amt, DL, MVT::i32));
14523 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14524 DAG.getConstant(Mask, DL, MVT::i32));
14525 DCI.CombineTo(N, Res, false);
14526 // Return value from the original node to inform the combiner than N is
14527 // now dead.
14528 return SDValue(N, 0);
14529 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14530 (~Mask == Mask2)) {
14531 // The pack halfword instruction works better for masks that fit it,
14532 // so use that when it's available.
14533 if (Subtarget->hasDSP() &&
14534 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14535 return SDValue();
14536 // 2b
14537 unsigned lsb = llvm::countr_zero(Mask);
14538 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14539 DAG.getConstant(lsb, DL, MVT::i32));
14540 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14541 DAG.getConstant(Mask2, DL, MVT::i32));
14542 DCI.CombineTo(N, Res, false);
14543 // Return value from the original node to inform the combiner than N is
14544 // now dead.
14545 return SDValue(N, 0);
14546 }
14547 }
14548
14549 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14550 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14552 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14553 // where lsb(mask) == #shamt and masked bits of B are known zero.
14554 SDValue ShAmt = N00.getOperand(1);
14555 unsigned ShAmtC = ShAmt->getAsZExtVal();
14556 unsigned LSB = llvm::countr_zero(Mask);
14557 if (ShAmtC != LSB)
14558 return SDValue();
14559
14560 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14561 DAG.getConstant(~Mask, DL, MVT::i32));
14562
14563 DCI.CombineTo(N, Res, false);
14564 // Return value from the original node to inform the combiner than N is
14565 // now dead.
14566 return SDValue(N, 0);
14567 }
14568
14569 return SDValue();
14570}
14571
14572static bool isValidMVECond(unsigned CC, bool IsFloat) {
14573 switch (CC) {
14574 case ARMCC::EQ:
14575 case ARMCC::NE:
14576 case ARMCC::LE:
14577 case ARMCC::GT:
14578 case ARMCC::GE:
14579 case ARMCC::LT:
14580 return true;
14581 case ARMCC::HS:
14582 case ARMCC::HI:
14583 return !IsFloat;
14584 default:
14585 return false;
14586 };
14587}
14588
14590 if (N->getOpcode() == ARMISD::VCMP)
14591 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14592 else if (N->getOpcode() == ARMISD::VCMPZ)
14593 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14594 else
14595 llvm_unreachable("Not a VCMP/VCMPZ!");
14596}
14597
14600 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14601}
14602
14604 const ARMSubtarget *Subtarget) {
14605 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14606 // together with predicates
14607 EVT VT = N->getValueType(0);
14608 SDLoc DL(N);
14609 SDValue N0 = N->getOperand(0);
14610 SDValue N1 = N->getOperand(1);
14611
14612 auto IsFreelyInvertable = [&](SDValue V) {
14613 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14614 return CanInvertMVEVCMP(V);
14615 return false;
14616 };
14617
14618 // At least one operand must be freely invertable.
14619 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14620 return SDValue();
14621
14622 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14623 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14624 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14625 return DAG.getLogicalNOT(DL, And, VT);
14626}
14627
14628// Try to form a NEON shift-{right, left}-and-insert (VSRI/VSLI) from:
14629// (or (and X, splat (i32 C1)), (srl Y, splat (i32 C2))) -> VSRI X, Y, #C2
14630// (or (and X, splat (i32 C1)), (shl Y, splat (i32 C2))) -> VSLI X, Y, #C2
14631// where C1 is a mask that preserves the bits not written by the shift/insert,
14632// i.e. `C1 == (1 << C2) - 1`.
14634 SDValue ShiftOp, EVT VT,
14635 SDLoc dl) {
14636 // Match (and X, Mask)
14637 if (AndOp.getOpcode() != ISD::AND)
14638 return SDValue();
14639
14640 SDValue X = AndOp.getOperand(0);
14641 SDValue Mask = AndOp.getOperand(1);
14642
14643 ConstantSDNode *MaskC = isConstOrConstSplat(Mask, false, true);
14644 if (!MaskC)
14645 return SDValue();
14646 APInt MaskBits =
14647 MaskC->getAPIntValue().trunc(Mask.getScalarValueSizeInBits());
14648
14649 // Match shift (srl/shl Y, CntVec)
14650 int64_t Cnt = 0;
14651 bool IsShiftRight = false;
14652 SDValue Y;
14653
14654 if (ShiftOp.getOpcode() == ARMISD::VSHRuIMM) {
14655 IsShiftRight = true;
14656 Y = ShiftOp.getOperand(0);
14657 Cnt = ShiftOp.getConstantOperandVal(1);
14658 } else if (ShiftOp.getOpcode() == ARMISD::VSHLIMM) {
14659 Y = ShiftOp.getOperand(0);
14660 Cnt = ShiftOp.getConstantOperandVal(1);
14661 } else {
14662 return SDValue();
14663 }
14664
14665 unsigned ElemBits = VT.getScalarSizeInBits();
14666 APInt RequiredMask = IsShiftRight
14667 ? APInt::getHighBitsSet(ElemBits, (unsigned)Cnt)
14668 : APInt::getLowBitsSet(ElemBits, (unsigned)Cnt);
14669 if (MaskBits != RequiredMask)
14670 return SDValue();
14671
14672 unsigned Opc = IsShiftRight ? ARMISD::VSRIIMM : ARMISD::VSLIIMM;
14673 return DAG.getNode(Opc, dl, VT, X, Y, DAG.getConstant(Cnt, dl, MVT::i32));
14674}
14675
14676/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14678 const ARMSubtarget *Subtarget) {
14679 // Attempt to use immediate-form VORR
14680 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14681 SDLoc dl(N);
14682 EVT VT = N->getValueType(0);
14683 SelectionDAG &DAG = DCI.DAG;
14684
14685 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14686 return SDValue();
14687
14688 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14689 VT == MVT::v8i1 || VT == MVT::v16i1))
14690 return PerformORCombine_i1(N, DAG, Subtarget);
14691
14692 APInt SplatBits, SplatUndef;
14693 unsigned SplatBitSize;
14694 bool HasAnyUndefs;
14695 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14696 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14697 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14698 SplatBitSize == 64) {
14699 EVT VorrVT;
14700 SDValue Val =
14701 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14702 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14703 if (Val.getNode()) {
14704 SDValue Input =
14705 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VorrVT, N->getOperand(0));
14706 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14707 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vorr);
14708 }
14709 }
14710 }
14711
14712 if (!Subtarget->isThumb1Only()) {
14713 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14714 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14715 return Result;
14716 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14717 return Result;
14718 }
14719
14720 SDValue N0 = N->getOperand(0);
14721 SDValue N1 = N->getOperand(1);
14722
14723 // (or (and X, C1), (srl Y, C2)) -> VSRI X, Y, #C2
14724 // (or (and X, C1), (shl Y, C2)) -> VSLI X, Y, #C2
14725 if (VT.isVector() &&
14726 ((Subtarget->hasNEON() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) ||
14727 (Subtarget->hasMVEIntegerOps() &&
14728 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32)))) {
14729 if (SDValue ShiftInsert =
14730 PerformORCombineToShiftInsert(DAG, N0, N1, VT, dl))
14731 return ShiftInsert;
14732
14733 if (SDValue ShiftInsert =
14734 PerformORCombineToShiftInsert(DAG, N1, N0, VT, dl))
14735 return ShiftInsert;
14736 }
14737
14738 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14739 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14741
14742 // The code below optimizes (or (and X, Y), Z).
14743 // The AND operand needs to have a single user to make these optimizations
14744 // profitable.
14745 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14746 return SDValue();
14747
14748 APInt SplatUndef;
14749 unsigned SplatBitSize;
14750 bool HasAnyUndefs;
14751
14752 APInt SplatBits0, SplatBits1;
14755 // Ensure that the second operand of both ands are constants
14756 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14757 HasAnyUndefs) && !HasAnyUndefs) {
14758 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14759 HasAnyUndefs) && !HasAnyUndefs) {
14760 // Ensure that the bit width of the constants are the same and that
14761 // the splat arguments are logical inverses as per the pattern we
14762 // are trying to simplify.
14763 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14764 SplatBits0 == ~SplatBits1) {
14765 // Canonicalize the vector type to make instruction selection
14766 // simpler.
14767 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14768 SDValue Mask = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14769 CanonicalVT, N0->getOperand(1));
14770 SDValue LHS = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14771 CanonicalVT, N0->getOperand(0));
14772 SDValue RHS = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl,
14773 CanonicalVT, N1->getOperand(0));
14774 SDValue Result =
14775 DAG.getNode(ARMISD::VBSP, dl, CanonicalVT, Mask, LHS, RHS);
14776 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Result);
14777 }
14778 }
14779 }
14780 }
14781
14782 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14783 // reasonable.
14784 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14785 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14786 return Res;
14787 }
14788
14789 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14790 return Result;
14791
14792 // (or x, (csinc 0, 0, cc)) -> (csinc x, 0, cc)
14793 // providing that the x is 0 or 1.
14794 SDValue CSINC = N1;
14795 SDValue Other = N0;
14796 if (CSINC.getOpcode() != ARMISD::CSINC)
14797 std::swap(CSINC, Other);
14798 if (CSINC.getOpcode() == ARMISD::CSINC &&
14799 isNullConstant(CSINC.getOperand(0)) &&
14800 isNullConstant(CSINC.getOperand(1)) &&
14802 return DAG.getNode(ARMISD::CSINC, dl, VT, Other, CSINC.getOperand(1),
14803 CSINC.getOperand(2), CSINC.getOperand(3));
14804
14805 return SDValue();
14806}
14807
14810 const ARMSubtarget *Subtarget) {
14811 EVT VT = N->getValueType(0);
14812 SelectionDAG &DAG = DCI.DAG;
14813
14814 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14815 return SDValue();
14816
14817 if (!Subtarget->isThumb1Only()) {
14818 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14819 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14820 return Result;
14821
14822 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14823 return Result;
14824 }
14825
14826 if (Subtarget->hasMVEIntegerOps()) {
14827 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14828 SDValue N0 = N->getOperand(0);
14829 SDValue N1 = N->getOperand(1);
14830 const TargetLowering *TLI = Subtarget->getTargetLowering();
14831 if (TLI->isConstTrueVal(N1) &&
14832 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14833 if (CanInvertMVEVCMP(N0)) {
14834 SDLoc DL(N0);
14836
14838 Ops.push_back(N0->getOperand(0));
14839 if (N0->getOpcode() == ARMISD::VCMP)
14840 Ops.push_back(N0->getOperand(1));
14841 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14842 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14843 }
14844 }
14845 }
14846
14847 return SDValue();
14848}
14849
14850// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14851// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14852// their position in "to" (Rd).
14853static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14854 assert(N->getOpcode() == ARMISD::BFI);
14855
14856 SDValue From = N->getOperand(1);
14857 ToMask = ~N->getConstantOperandAPInt(2);
14858 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.popcount());
14859
14860 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14861 // #C in the base of the SHR.
14862 if (From->getOpcode() == ISD::SRL &&
14863 isa<ConstantSDNode>(From->getOperand(1))) {
14864 APInt Shift = From->getConstantOperandAPInt(1);
14865 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14866 FromMask <<= Shift.getLimitedValue(31);
14867 From = From->getOperand(0);
14868 }
14869
14870 return From;
14871}
14872
14873// If A and B contain one contiguous set of bits, does A | B == A . B?
14874//
14875// Neither A nor B must be zero.
14876static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14877 unsigned LastActiveBitInA = A.countr_zero();
14878 unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14879 return LastActiveBitInA - 1 == FirstActiveBitInB;
14880}
14881
14883 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14884 APInt ToMask, FromMask;
14885 SDValue From = ParseBFI(N, ToMask, FromMask);
14886 SDValue To = N->getOperand(0);
14887
14888 SDValue V = To;
14889 if (V.getOpcode() != ARMISD::BFI)
14890 return SDValue();
14891
14892 APInt NewToMask, NewFromMask;
14893 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14894 if (NewFrom != From)
14895 return SDValue();
14896
14897 // Do the written bits conflict with any we've seen so far?
14898 if ((NewToMask & ToMask).getBoolValue())
14899 // Conflicting bits.
14900 return SDValue();
14901
14902 // Are the new bits contiguous when combined with the old bits?
14903 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14904 BitsProperlyConcatenate(FromMask, NewFromMask))
14905 return V;
14906 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14907 BitsProperlyConcatenate(NewFromMask, FromMask))
14908 return V;
14909
14910 return SDValue();
14911}
14912
14914 SDValue N0 = N->getOperand(0);
14915 SDValue N1 = N->getOperand(1);
14916
14917 if (N1.getOpcode() == ISD::AND) {
14918 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14919 // the bits being cleared by the AND are not demanded by the BFI.
14921 if (!N11C)
14922 return SDValue();
14923 unsigned InvMask = N->getConstantOperandVal(2);
14924 unsigned LSB = llvm::countr_zero(~InvMask);
14925 unsigned Width = llvm::bit_width<unsigned>(~InvMask) - LSB;
14926 assert(Width <
14927 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14928 "undefined behavior");
14929 unsigned Mask = (1u << Width) - 1;
14930 unsigned Mask2 = N11C->getZExtValue();
14931 if ((Mask & (~Mask2)) == 0)
14932 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14933 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14934 return SDValue();
14935 }
14936
14937 // Look for another BFI to combine with.
14938 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14939 // We've found a BFI.
14940 APInt ToMask1, FromMask1;
14941 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14942
14943 APInt ToMask2, FromMask2;
14944 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14945 assert(From1 == From2);
14946 (void)From2;
14947
14948 // Create a new BFI, combining the two together.
14949 APInt NewFromMask = FromMask1 | FromMask2;
14950 APInt NewToMask = ToMask1 | ToMask2;
14951
14952 EVT VT = N->getValueType(0);
14953 SDLoc dl(N);
14954
14955 if (NewFromMask[0] == 0)
14956 From1 = DAG.getNode(ISD::SRL, dl, VT, From1,
14957 DAG.getConstant(NewFromMask.countr_zero(), dl, VT));
14958 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14959 DAG.getConstant(~NewToMask, dl, VT));
14960 }
14961
14962 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14963 // that lower bit insertions are performed first, providing that M1 and M2
14964 // do no overlap. This can allow multiple BFI instructions to be combined
14965 // together by the other folds above.
14966 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14967 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14968 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14969
14970 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14971 ToMask1.countl_zero() < ToMask2.countl_zero())
14972 return SDValue();
14973
14974 EVT VT = N->getValueType(0);
14975 SDLoc dl(N);
14976 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14977 N->getOperand(1), N->getOperand(2));
14978 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14979 N0.getOperand(2));
14980 }
14981
14982 return SDValue();
14983}
14984
14985// Check that N is CMPZ(CSINC(0, 0, CC, X)),
14986// or CMPZ(CMOV(1, 0, CC, X))
14987// return X if valid.
14989 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
14990 return SDValue();
14991 SDValue CSInc = Cmp->getOperand(0);
14992
14993 // Ignore any `And 1` nodes that may not yet have been removed. We are
14994 // looking for a value that produces 1/0, so these have no effect on the
14995 // code.
14996 while (CSInc.getOpcode() == ISD::AND &&
14997 isa<ConstantSDNode>(CSInc.getOperand(1)) &&
14998 CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
14999 CSInc = CSInc.getOperand(0);
15000
15001 if (CSInc.getOpcode() == ARMISD::CSINC &&
15002 isNullConstant(CSInc.getOperand(0)) &&
15003 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15005 return CSInc.getOperand(3);
15006 }
15007 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
15008 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15010 return CSInc.getOperand(3);
15011 }
15012 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
15013 isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
15016 return CSInc.getOperand(3);
15017 }
15018 return SDValue();
15019}
15020
15022 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15023 // t92: flags = ARMISD::CMPZ t74, 0
15024 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15025 // t96: flags = ARMISD::CMPZ t93, 0
15026 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15028 if (SDValue C = IsCMPZCSINC(N, Cond))
15029 if (Cond == ARMCC::EQ)
15030 return C;
15031 return SDValue();
15032}
15033
15035 // Fold away an unnecessary CMPZ/CSINC
15036 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15037 // if C1==EQ -> CSXYZ A, B, C2, D
15038 // if C1==NE -> CSXYZ A, B, NOT(C2), D
15040 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
15041 if (N->getConstantOperandVal(2) == ARMCC::EQ)
15042 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15043 N->getOperand(1),
15044 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
15045 if (N->getConstantOperandVal(2) == ARMCC::NE)
15046 return DAG.getNode(
15047 N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15048 N->getOperand(1),
15050 }
15051 return SDValue();
15052}
15053
15054/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15055/// ARMISD::VMOVRRD.
15058 const ARMSubtarget *Subtarget) {
15059 // vmovrrd(vmovdrr x, y) -> x,y
15060 SDValue InDouble = N->getOperand(0);
15061 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15062 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
15063
15064 // vmovrrd(load f64) -> (load i32), (load i32)
15065 SDNode *InNode = InDouble.getNode();
15066 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
15067 InNode->getValueType(0) == MVT::f64 &&
15068 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
15069 !cast<LoadSDNode>(InNode)->isVolatile()) {
15070 // TODO: Should this be done for non-FrameIndex operands?
15071 LoadSDNode *LD = cast<LoadSDNode>(InNode);
15072
15073 SelectionDAG &DAG = DCI.DAG;
15074 SDLoc DL(LD);
15075 SDValue BasePtr = LD->getBasePtr();
15076 SDValue NewLD1 =
15077 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
15078 LD->getAlign(), LD->getMemOperand()->getFlags());
15079
15080 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
15081 DAG.getConstant(4, DL, MVT::i32));
15082
15083 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
15084 LD->getPointerInfo().getWithOffset(4),
15085 commonAlignment(LD->getAlign(), 4),
15086 LD->getMemOperand()->getFlags());
15087
15088 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
15089 if (DCI.DAG.getDataLayout().isBigEndian())
15090 std::swap (NewLD1, NewLD2);
15091 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
15092 return Result;
15093 }
15094
15095 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15096 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15097 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15098 isa<ConstantSDNode>(InDouble.getOperand(1))) {
15099 SDValue BV = InDouble.getOperand(0);
15100 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15101 // change lane order under big endian.
15102 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15103 while (
15104 (BV.getOpcode() == ISD::BITCAST ||
15105 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15106 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15107 BVSwap = BV.getOpcode() == ISD::BITCAST;
15108 BV = BV.getOperand(0);
15109 }
15110 if (BV.getValueType() != MVT::v4i32)
15111 return SDValue();
15112
15113 // Handle buildvectors, pulling out the correct lane depending on
15114 // endianness.
15115 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
15116 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15117 SDValue Op0 = BV.getOperand(Offset);
15118 SDValue Op1 = BV.getOperand(Offset + 1);
15119 if (!Subtarget->isLittle() && BVSwap)
15120 std::swap(Op0, Op1);
15121
15122 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15123 }
15124
15125 // A chain of insert_vectors, grabbing the correct value of the chain of
15126 // inserts.
15127 SDValue Op0, Op1;
15128 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15129 if (isa<ConstantSDNode>(BV.getOperand(2))) {
15130 if (BV.getConstantOperandVal(2) == Offset && !Op0)
15131 Op0 = BV.getOperand(1);
15132 if (BV.getConstantOperandVal(2) == Offset + 1 && !Op1)
15133 Op1 = BV.getOperand(1);
15134 }
15135 BV = BV.getOperand(0);
15136 }
15137 if (!Subtarget->isLittle() && BVSwap)
15138 std::swap(Op0, Op1);
15139 if (Op0 && Op1)
15140 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15141 }
15142
15143 return SDValue();
15144}
15145
15146/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15147/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
15149 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15150 SDValue Op0 = N->getOperand(0);
15151 SDValue Op1 = N->getOperand(1);
15152 if (Op0.getOpcode() == ISD::BITCAST)
15153 Op0 = Op0.getOperand(0);
15154 if (Op1.getOpcode() == ISD::BITCAST)
15155 Op1 = Op1.getOperand(0);
15156 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15157 Op0.getNode() == Op1.getNode() &&
15158 Op0.getResNo() == 0 && Op1.getResNo() == 1)
15159 return DAG.getNode(ISD::BITCAST, SDLoc(N),
15160 N->getValueType(0), Op0.getOperand(0));
15161 return SDValue();
15162}
15163
15166 SDValue Op0 = N->getOperand(0);
15167
15168 // VMOVhr (VMOVrh (X)) -> X
15169 if (Op0->getOpcode() == ARMISD::VMOVrh)
15170 return Op0->getOperand(0);
15171
15172 // FullFP16: half values are passed in S-registers, and we don't
15173 // need any of the bitcast and moves:
15174 //
15175 // t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15176 // t5: i32 = bitcast t2
15177 // t18: f16 = ARMISD::VMOVhr t5
15178 // =>
15179 // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15180 if (Op0->getOpcode() == ISD::BITCAST) {
15181 SDValue Copy = Op0->getOperand(0);
15182 if (Copy.getValueType() == MVT::f32 &&
15183 Copy->getOpcode() == ISD::CopyFromReg) {
15184 bool HasGlue = Copy->getNumOperands() == 3;
15185 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1),
15186 HasGlue ? Copy->getOperand(2) : SDValue()};
15187 EVT OutTys[] = {N->getValueType(0), MVT::Other, MVT::Glue};
15188 SDValue NewCopy =
15190 DCI.DAG.getVTList(ArrayRef(OutTys, HasGlue ? 3 : 2)),
15191 ArrayRef(Ops, HasGlue ? 3 : 2));
15192
15193 // Update Users, Chains, and Potential Glue.
15194 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), NewCopy.getValue(0));
15195 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(1), NewCopy.getValue(1));
15196 if (HasGlue)
15197 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(2),
15198 NewCopy.getValue(2));
15199
15200 return NewCopy;
15201 }
15202 }
15203
15204 // fold (VMOVhr (load x)) -> (load (f16*)x)
15205 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
15206 if (LN0->hasOneUse() && LN0->isUnindexed() &&
15207 LN0->getMemoryVT() == MVT::i16) {
15208 SDValue Load =
15209 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
15210 LN0->getBasePtr(), LN0->getMemOperand());
15211 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15212 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
15213 return Load;
15214 }
15215 }
15216
15217 // Only the bottom 16 bits of the source register are used.
15218 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15220 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
15221 return SDValue(N, 0);
15222
15223 return SDValue();
15224}
15225
15227 SDValue N0 = N->getOperand(0);
15228 EVT VT = N->getValueType(0);
15229
15230 // fold (VMOVrh (fpconst x)) -> const x
15232 APFloat V = C->getValueAPF();
15233 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
15234 }
15235
15236 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15237 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
15238 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15239
15240 SDValue Load =
15241 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
15242 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
15243 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15244 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
15245 return Load;
15246 }
15247
15248 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15249 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15251 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
15252 N0->getOperand(1));
15253
15254 return SDValue();
15255}
15256
15257/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15258/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15259/// i64 vector to have f64 elements, since the value can then be loaded
15260/// directly into a VFP register.
15262 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15263 for (unsigned i = 0; i < NumElts; ++i) {
15264 SDNode *Elt = N->getOperand(i).getNode();
15265 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15266 return true;
15267 }
15268 return false;
15269}
15270
15271/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15272/// ISD::BUILD_VECTOR.
15275 const ARMSubtarget *Subtarget) {
15276 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15277 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15278 // into a pair of GPRs, which is fine when the value is used as a scalar,
15279 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15280 SelectionDAG &DAG = DCI.DAG;
15281 if (N->getNumOperands() == 2)
15282 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15283 return RV;
15284
15285 // Load i64 elements as f64 values so that type legalization does not split
15286 // them up into i32 values.
15287 EVT VT = N->getValueType(0);
15288 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15289 return SDValue();
15290 SDLoc dl(N);
15292 unsigned NumElts = VT.getVectorNumElements();
15293 for (unsigned i = 0; i < NumElts; ++i) {
15294 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15295 Ops.push_back(V);
15296 // Make the DAGCombiner fold the bitcast.
15297 DCI.AddToWorklist(V.getNode());
15298 }
15299 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15300 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15301 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15302}
15303
15306 const ARMSubtarget *Subtarget) {
15307 // Type legalization splits a wide load into consecutive legal loads. Combine
15308 // each group used by a legal VECTOR_DEINTERLEAVE into a structured load.
15310 return SDValue();
15311
15312 unsigned NumParts = N->getNumOperands();
15314 return SDValue();
15315
15316 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
15317 return SDValue();
15318
15319 EVT SubVecTy = N->getValueType(0);
15320 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
15321 !SubVecTy.is128BitVector())
15322 return SDValue();
15323 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
15324 return SDValue();
15325 unsigned EltBits = SubVecTy.getScalarSizeInBits();
15326 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
15327 return SDValue();
15328
15330 for (const SDValue &Operand : N->op_values()) {
15331 auto *Load = dyn_cast<LoadSDNode>(Operand);
15332 if (!Load || !Operand.hasOneUse())
15333 return SDValue();
15334 Loads.push_back(Load);
15335 }
15336
15337 LoadSDNode *BaseLoad = Loads[0];
15338 if (Subtarget->hasMVEIntegerOps() && BaseLoad->getAlign() < EltBits / 8)
15339 return SDValue();
15340 unsigned Bytes = SubVecTy.getStoreSize().getFixedValue();
15341 for (auto [Idx, Load] : enumerate(Loads)) {
15342 if (!DAG.areNonVolatileConsecutiveLoads(Load, BaseLoad, Bytes, Idx))
15343 return SDValue();
15344 }
15345
15346 SDLoc DL(N);
15347 EVT MemVT =
15348 EVT::getVectorVT(*DAG.getContext(), SubVecTy.getVectorElementType(),
15349 SubVecTy.getVectorElementCount() * NumParts);
15351 MachineMemOperand *MMO =
15352 MF.getMachineMemOperand(BaseLoad->getMemOperand(), 0, NumParts * Bytes);
15353
15355 ResVTs.push_back(MVT::Other);
15356
15357 SmallVector<SDValue> NewLdOps;
15358 NewLdOps.push_back(BaseLoad->getChain());
15359 Intrinsic::ID IID = 0;
15360 static constexpr Intrinsic::ID NEONLoads[] = {Intrinsic::arm_neon_vld2,
15361 Intrinsic::arm_neon_vld3,
15362 Intrinsic::arm_neon_vld4};
15363 if (Subtarget->hasNEON())
15364 IID = NEONLoads[NumParts - 2];
15365 else
15366 IID = NumParts == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
15367
15368 NewLdOps.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
15369 NewLdOps.push_back(BaseLoad->getBasePtr());
15370 // We can now generate a structured load!
15371 SDValue NewLoad = DAG.getMemIntrinsicNode(
15372 ISD::INTRINSIC_W_CHAIN, DL, DAG.getVTList(ResVTs), NewLdOps, MemVT, MMO);
15373
15375 for (unsigned I = 0; I != NumParts; ++I)
15376 ResOps.push_back(NewLoad.getValue(I));
15377
15378 // Preserve the memory ordering of each original load with the new load.
15379 for (LoadSDNode *Load : Loads)
15381 NewLoad.getValue(NumParts));
15382 return DCI.CombineTo(N, ResOps, false);
15383}
15384
15385// Combine a deinterleave of adjacent subvectors from one load into a
15386// structured NEON load.
15387static SDValue
15390 const ARMSubtarget *Subtarget) {
15391 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
15392 return SDValue();
15393
15395 Subtarget))
15396 return Res;
15397
15398 if (!DCI.isBeforeLegalize())
15399 return SDValue();
15400
15401 SelectionDAG &DAG = DCI.DAG;
15402 unsigned NumParts = N->getNumOperands();
15403 if (NumParts != 2 && NumParts != 3 && NumParts != 4)
15404 return SDValue();
15405
15406 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
15407 return SDValue();
15408
15409 EVT SubVecTy = N->getValueType(0);
15410
15411 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
15412 !SubVecTy.is128BitVector())
15413 return SDValue();
15414 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
15415 return SDValue();
15416 unsigned EltBits = SubVecTy.getScalarSizeInBits();
15417 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
15418 return SDValue();
15419
15420 // Make sure each input operand is the correct extract_subvector of the same
15421 // wider vector.
15422 unsigned MinNumElements = SubVecTy.getVectorMinNumElements();
15423 SDValue Op0 = N->getOperand(0);
15424 for (unsigned I = 0; I < NumParts; I++) {
15425 SDValue OpI = N->getOperand(I);
15426 if (!OpI.hasOneUse() || OpI.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
15427 OpI.getOperand(0) != Op0.getOperand(0))
15428 return SDValue();
15429 if (OpI.getConstantOperandVal(1) != (I * MinNumElements))
15430 return SDValue();
15431 }
15432
15433 SDValue WideVec = Op0.getOperand(0);
15434 SDLoc DL(N);
15435
15437 ResVTs.push_back(MVT::Other);
15438 SDVTList ResVTList = DAG.getVTList(ResVTs);
15439 auto *Load = dyn_cast<LoadSDNode>(WideVec);
15440 if (!Load || !Load->hasNUsesOfValue(NumParts, 0) || !Load->isSimple() ||
15441 !ISD::isNormalLoad(Load) || !Load->getOffset().isUndef())
15442 return SDValue();
15443 if (Subtarget->hasMVEIntegerOps() && Load->getAlign() < EltBits / 8)
15444 return SDValue();
15445
15446 static constexpr Intrinsic::ID NEONLoads[] = {Intrinsic::arm_neon_vld2,
15447 Intrinsic::arm_neon_vld3,
15448 Intrinsic::arm_neon_vld4};
15449 SmallVector<SDValue> NewLdOps;
15450 Intrinsic::ID IID = 0;
15451 NewLdOps.push_back(Load->getChain());
15452 if (Subtarget->hasNEON())
15453 IID = NEONLoads[NumParts - 2];
15454 else
15455 IID = NumParts == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
15456 NewLdOps.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
15457
15458 NewLdOps.push_back(Load->getBasePtr());
15459
15460 // We can now generate a structured load!
15461 SDValue Res =
15462 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, ResVTList, NewLdOps,
15463 Load->getMemoryVT(), Load->getMemOperand());
15464
15466 for (unsigned Idx = 0; Idx < NumParts; Idx++)
15467 ResOps[Idx] = Res.getValue(Idx);
15468
15469 // Preserve the original load's memory ordering with the new load.
15471 return DCI.CombineTo(N, ResOps, false);
15472}
15473
15474/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15475static SDValue
15477 SelectionDAG &DAG = DCI.DAG;
15478 EVT VT = N->getValueType(0);
15479
15480 // Fold buildvector(extractelt(bitcast(build_vector(a,b,_,_))),
15481 // extractelt(bitcast(build_vector(_,_,c,d))))
15482 // -> bitcast(build_vector(a,b,c,d))
15483 if (VT.getScalarSizeInBits() == 64 && N->getNumOperands() == 2) {
15484 auto IsExtractFromBuildVec = [](SDValue V, SDValue &BV, int64_t &Lane) {
15485 if (!sd_match(V, m_ExtractElt(m_Value(BV), m_ConstInt(Lane))))
15486 return false;
15487 while (BV.getOpcode() == ISD::BITCAST)
15488 BV = BV.getOperand(0);
15489 return BV.getOpcode() == ARMISD::BUILD_VECTOR &&
15490 BV.getNumOperands() == 4 &&
15491 BV.getValueType().getScalarSizeInBits() == 32;
15492 };
15493 SDValue BV1, BV2;
15494 int64_t Lane1, Lane2;
15495 if (IsExtractFromBuildVec(N->getOperand(0), BV1, Lane1) &&
15496 IsExtractFromBuildVec(N->getOperand(1), BV2, Lane2))
15497 return DAG.getBitcast(
15498 VT, DAG.getNode(
15499 ARMISD::BUILD_VECTOR, N, MVT::v4f32,
15500 DAG.getBitcast(MVT::f32, BV1->getOperand(Lane1 * 2 + 0)),
15501 DAG.getBitcast(MVT::f32, BV1->getOperand(Lane1 * 2 + 1)),
15502 DAG.getBitcast(MVT::f32, BV2->getOperand(Lane2 * 2 + 0)),
15503 DAG.getBitcast(MVT::f32, BV2->getOperand(Lane2 * 2 + 1))));
15504 }
15505
15506 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15507 // At that time, we may have inserted bitcasts from integer to float.
15508 // If these bitcasts have survived DAGCombine, change the lowering of this
15509 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15510 // force to use floating point types.
15511
15512 // Make sure we can change the type of the vector.
15513 // This is possible iff:
15514 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15515 // 1.1. Vector is used only once.
15516 // 1.2. Use is a bit convert to an integer type.
15517 // 2. The size of its operands are 32-bits (64-bits are not legal).
15518 EVT EltVT = VT.getVectorElementType();
15519
15520 // Check 1.1. and 2.
15521 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15522 return SDValue();
15523
15524 // By construction, the input type must be float.
15525 assert(EltVT == MVT::f32 && "Unexpected type!");
15526
15527 // Check 1.2.
15528 SDNode *Use = *N->user_begin();
15529 if (Use->getOpcode() != ISD::BITCAST ||
15530 Use->getValueType(0).isFloatingPoint())
15531 return SDValue();
15532
15533 // Check profitability.
15534 // Model is, if more than half of the relevant operands are bitcast from
15535 // i32, turn the build_vector into a sequence of insert_vector_elt.
15536 // Relevant operands are everything that is not statically
15537 // (i.e., at compile time) bitcasted.
15538 unsigned NumOfBitCastedElts = 0;
15539 unsigned NumElts = VT.getVectorNumElements();
15540 unsigned NumOfRelevantElts = NumElts;
15541 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15542 SDValue Elt = N->getOperand(Idx);
15543 if (Elt->getOpcode() == ISD::BITCAST) {
15544 // Assume only bit cast to i32 will go away.
15545 if (Elt->getOperand(0).getValueType() == MVT::i32)
15546 ++NumOfBitCastedElts;
15547 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15548 // Constants are statically casted, thus do not count them as
15549 // relevant operands.
15550 --NumOfRelevantElts;
15551 }
15552
15553 // Check if more than half of the elements require a non-free bitcast.
15554 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15555 return SDValue();
15556
15557 // Create the new vector type.
15558 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15559 // Check if the type is legal.
15561 if (!TLI.isTypeLegal(VecVT))
15562 return SDValue();
15563
15564 // Combine:
15565 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15566 // => BITCAST INSERT_VECTOR_ELT
15567 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15568 // (BITCAST EN), N.
15569 SDValue Vec = DAG.getUNDEF(VecVT);
15570 SDLoc dl(N);
15571 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15572 SDValue V = N->getOperand(Idx);
15573 if (V.isUndef())
15574 continue;
15575 if (V.getOpcode() == ISD::BITCAST &&
15576 V->getOperand(0).getValueType() == MVT::i32)
15577 // Fold obvious case.
15578 V = V.getOperand(0);
15579 else {
15580 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15581 // Make the DAGCombiner fold the bitcasts.
15582 DCI.AddToWorklist(V.getNode());
15583 }
15584 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15585 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15586 }
15587 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15588 // Make the DAGCombiner fold the bitcasts.
15589 DCI.AddToWorklist(Vec.getNode());
15590 return Vec;
15591}
15592
15593static SDValue
15595 EVT VT = N->getValueType(0);
15596 SDValue Op = N->getOperand(0);
15597 SDLoc dl(N);
15598
15599 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15600 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15601 // If the valuetypes are the same, we can remove the cast entirely.
15602 if (Op->getOperand(0).getValueType() == VT)
15603 return Op->getOperand(0);
15604 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15605 }
15606
15607 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15608 // more VPNOT which might get folded as else predicates.
15609 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15610 SDValue X =
15611 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15612 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15613 DCI.DAG.getConstant(65535, dl, MVT::i32));
15614 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15615 }
15616
15617 // Only the bottom 16 bits of the source register are used.
15618 if (Op.getValueType() == MVT::i32) {
15619 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15621 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15622 return SDValue(N, 0);
15623 }
15624 return SDValue();
15625}
15626
15628 const ARMSubtarget *ST) {
15629 EVT VT = N->getValueType(0);
15630 SDValue Op = N->getOperand(0);
15631 SDLoc dl(N);
15632
15633 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15634 if (ST->isLittle())
15635 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15636
15637 // VT VECTOR_REG_CAST (VT Op) -> Op
15638 if (Op.getValueType() == VT)
15639 return Op;
15640 // VECTOR_REG_CAST undef -> undef
15641 if (Op.isUndef())
15642 return DAG.getUNDEF(VT);
15643
15644 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15645 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15646 // If the valuetypes are the same, we can remove the cast entirely.
15647 if (Op->getOperand(0).getValueType() == VT)
15648 return Op->getOperand(0);
15649 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15650 }
15651
15652 return SDValue();
15653}
15654
15656 const ARMSubtarget *Subtarget) {
15657 if (!Subtarget->hasMVEIntegerOps())
15658 return SDValue();
15659
15660 EVT VT = N->getValueType(0);
15661 SDValue Op0 = N->getOperand(0);
15662 SDValue Op1 = N->getOperand(1);
15663 ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(2);
15664 SDLoc dl(N);
15665
15666 // vcmp X, 0, cc -> vcmpz X, cc
15667 if (isZeroVector(Op1))
15668 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15669
15670 unsigned SwappedCond = getSwappedCondition(Cond);
15671 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15672 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15673 if (isZeroVector(Op0))
15674 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15675 DAG.getConstant(SwappedCond, dl, MVT::i32));
15676 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15677 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15678 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15679 DAG.getConstant(SwappedCond, dl, MVT::i32));
15680 }
15681
15682 return SDValue();
15683}
15684
15685/// PerformInsertEltCombine - Target-specific dag combine xforms for
15686/// ISD::INSERT_VECTOR_ELT.
15689 // Bitcast an i64 load inserted into a vector to f64.
15690 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15691 EVT VT = N->getValueType(0);
15692 SDNode *Elt = N->getOperand(1).getNode();
15693 if (VT.getVectorElementType() != MVT::i64 ||
15694 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15695 return SDValue();
15696
15697 SelectionDAG &DAG = DCI.DAG;
15698 SDLoc dl(N);
15699 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15701 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15702 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15703 // Make the DAGCombiner fold the bitcasts.
15704 DCI.AddToWorklist(Vec.getNode());
15705 DCI.AddToWorklist(V.getNode());
15706 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15707 Vec, V, N->getOperand(2));
15708 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15709}
15710
15711// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15712// directly or bitcast to an integer if the original is a float vector.
15713// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15714// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15715static SDValue
15717 EVT VT = N->getValueType(0);
15718 SDLoc dl(N);
15719
15720 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15721 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15722 return SDValue();
15723
15724 SDValue Ext = SDValue(N, 0);
15725 if (Ext.getOpcode() == ISD::BITCAST &&
15726 Ext.getOperand(0).getValueType() == MVT::f32)
15727 Ext = Ext.getOperand(0);
15728 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15730 Ext.getConstantOperandVal(1) % 2 != 0)
15731 return SDValue();
15732 if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15733 Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15734 return SDValue();
15735
15736 SDValue Op0 = Ext.getOperand(0);
15737 EVT VecVT = Op0.getValueType();
15738 unsigned ResNo = Op0.getResNo();
15739 unsigned Lane = Ext.getConstantOperandVal(1);
15740 if (VecVT.getVectorNumElements() != 4)
15741 return SDValue();
15742
15743 // Find another extract, of Lane + 1
15744 auto OtherIt = find_if(Op0->users(), [&](SDNode *V) {
15745 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15746 isa<ConstantSDNode>(V->getOperand(1)) &&
15747 V->getConstantOperandVal(1) == Lane + 1 &&
15748 V->getOperand(0).getResNo() == ResNo;
15749 });
15750 if (OtherIt == Op0->users().end())
15751 return SDValue();
15752
15753 // For float extracts, we need to be converting to a i32 for both vector
15754 // lanes.
15755 SDValue OtherExt(*OtherIt, 0);
15756 if (OtherExt.getValueType() != MVT::i32) {
15757 if (!OtherExt->hasOneUse() ||
15758 OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15759 OtherExt->user_begin()->getValueType(0) != MVT::i32)
15760 return SDValue();
15761 OtherExt = SDValue(*OtherExt->user_begin(), 0);
15762 }
15763
15764 // Convert the type to a f64 and extract with a VMOVRRD.
15765 SDValue F64 = DCI.DAG.getNode(
15766 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15767 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15768 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15769 SDValue VMOVRRD =
15770 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15771
15772 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15773 return VMOVRRD;
15774}
15775
15778 const ARMSubtarget *ST) {
15779 SDValue Op0 = N->getOperand(0);
15780 EVT VT = N->getValueType(0);
15781 SDLoc dl(N);
15782
15783 // extract (vdup x) -> x
15784 if (Op0->getOpcode() == ARMISD::VDUP) {
15785 SDValue X = Op0->getOperand(0);
15786 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15787 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15788 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15789 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15790 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15791 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15792
15793 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15794 X = X->getOperand(0);
15795 if (X.getValueType() == VT)
15796 return X;
15797 }
15798
15799 // extract ARM_BUILD_VECTOR -> x
15800 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15801 isa<ConstantSDNode>(N->getOperand(1)) &&
15802 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15803 return Op0.getOperand(N->getConstantOperandVal(1));
15804 }
15805
15806 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15807 if (Op0.getValueType() == MVT::v4i32 &&
15808 isa<ConstantSDNode>(N->getOperand(1)) &&
15809 Op0.getOpcode() == ISD::BITCAST &&
15811 Op0.getOperand(0).getValueType() == MVT::v2f64) {
15812 SDValue BV = Op0.getOperand(0);
15813 unsigned Offset = N->getConstantOperandVal(1);
15814 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15815 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15816 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15817 }
15818
15819 // extract x, n; extract x, n+1 -> VMOVRRD x
15820 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15821 return R;
15822
15823 // extract (MVETrunc(x)) -> extract x
15824 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15825 unsigned Idx = N->getConstantOperandVal(1);
15826 unsigned Vec =
15828 unsigned SubIdx =
15830 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15831 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15832 }
15833
15834 // extract(bitcast(BUILD_VECTOR(extract(bitcast(a)), ..))) -> extract(a)
15835 if (ST->isLittle() && Op0.getOpcode() == ISD::BITCAST &&
15837 isa<ConstantSDNode>(N->getOperand(1)) &&
15840 unsigned Lane = N->getConstantOperandVal(1);
15841 EVT ExtVT = Op0.getValueType();
15842 EVT BVVT = Op0.getOperand(0).getValueType();
15843 unsigned BVLane =
15844 (Lane * BVVT.getVectorNumElements()) / ExtVT.getVectorNumElements();
15845 assert(BVLane < Op0.getOperand(0).getNumOperands());
15846 SDValue Ext = Op0.getOperand(0).getOperand(BVLane);
15847 if (Ext.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15848 Ext.getOperand(0).getOpcode() == ISD::BITCAST &&
15850 Ext.getOperand(0).getOperand(0).getValueType() == ExtVT) {
15851 unsigned InnerLane = Ext.getConstantOperandVal(1);
15852 unsigned BVSubLane = Lane - (BVLane * ExtVT.getVectorNumElements()) /
15853 BVVT.getVectorNumElements();
15854 unsigned FinalLane = (InnerLane * ExtVT.getVectorNumElements()) /
15855 BVVT.getVectorNumElements() +
15856 BVSubLane;
15857 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT,
15858 Ext.getOperand(0).getOperand(0),
15859 DCI.DAG.getConstant(FinalLane, dl, MVT::i32));
15860 }
15861 }
15862
15863 return SDValue();
15864}
15865
15867 SDValue Op = N->getOperand(0);
15868 EVT VT = N->getValueType(0);
15869
15870 // sext_inreg(VGETLANEu) -> VGETLANEs
15871 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15872 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15873 Op.getOperand(0).getValueType().getScalarType())
15874 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15875 Op.getOperand(1));
15876
15877 return SDValue();
15878}
15879
15880static SDValue
15882 SDValue Vec = N->getOperand(0);
15883 SDValue SubVec = N->getOperand(1);
15884 uint64_t IdxVal = N->getConstantOperandVal(2);
15885 EVT VecVT = Vec.getValueType();
15886 EVT SubVT = SubVec.getValueType();
15887
15888 // Only do this for legal fixed vector types.
15889 if (!VecVT.isFixedLengthVector() ||
15890 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15892 return SDValue();
15893
15894 // Ignore widening patterns.
15895 if (IdxVal == 0 && Vec.isUndef())
15896 return SDValue();
15897
15898 // Subvector must be half the width and an "aligned" insertion.
15899 unsigned NumSubElts = SubVT.getVectorNumElements();
15900 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15901 (IdxVal != 0 && IdxVal != NumSubElts))
15902 return SDValue();
15903
15904 // Fold insert_subvector -> concat_vectors
15905 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15906 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15907 SDLoc DL(N);
15908 SDValue Lo, Hi;
15909 if (IdxVal == 0) {
15910 Lo = SubVec;
15911 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15912 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15913 } else {
15914 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15915 DCI.DAG.getVectorIdxConstant(0, DL));
15916 Hi = SubVec;
15917 }
15918 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15919}
15920
15921// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15923 SelectionDAG &DAG) {
15924 SDValue Trunc = N->getOperand(0);
15925 EVT VT = Trunc.getValueType();
15926 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15927 return SDValue();
15928
15929 SDLoc DL(Trunc);
15930 if (isVMOVNTruncMask(N->getMask(), VT, false))
15931 return DAG.getNode(
15932 ARMISD::VMOVN, DL, VT,
15933 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15934 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15935 DAG.getConstant(1, DL, MVT::i32));
15936 else if (isVMOVNTruncMask(N->getMask(), VT, true))
15937 return DAG.getNode(
15938 ARMISD::VMOVN, DL, VT,
15939 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15940 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15941 DAG.getConstant(1, DL, MVT::i32));
15942 return SDValue();
15943}
15944
15945/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15946/// ISD::VECTOR_SHUFFLE.
15949 return R;
15950
15951 // The LLVM shufflevector instruction does not require the shuffle mask
15952 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15953 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15954 // operands do not match the mask length, they are extended by concatenating
15955 // them with undef vectors. That is probably the right thing for other
15956 // targets, but for NEON it is better to concatenate two double-register
15957 // size vector operands into a single quad-register size vector. Do that
15958 // transformation here:
15959 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15960 // shuffle(concat(v1, v2), undef)
15961 SDValue Op0 = N->getOperand(0);
15962 SDValue Op1 = N->getOperand(1);
15963 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15964 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15965 Op0.getNumOperands() != 2 ||
15966 Op1.getNumOperands() != 2)
15967 return SDValue();
15968 SDValue Concat0Op1 = Op0.getOperand(1);
15969 SDValue Concat1Op1 = Op1.getOperand(1);
15970 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15971 return SDValue();
15972 // Skip the transformation if any of the types are illegal.
15974 EVT VT = N->getValueType(0);
15975 if (!TLI.isTypeLegal(VT) ||
15976 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15977 !TLI.isTypeLegal(Concat1Op1.getValueType()))
15978 return SDValue();
15979
15980 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15981 Op0.getOperand(0), Op1.getOperand(0));
15982 // Translate the shuffle mask.
15983 SmallVector<int, 16> NewMask;
15984 unsigned NumElts = VT.getVectorNumElements();
15985 unsigned HalfElts = NumElts/2;
15987 for (unsigned n = 0; n < NumElts; ++n) {
15988 int MaskElt = SVN->getMaskElt(n);
15989 int NewElt = -1;
15990 if (MaskElt < (int)HalfElts)
15991 NewElt = MaskElt;
15992 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15993 NewElt = HalfElts + MaskElt - NumElts;
15994 NewMask.push_back(NewElt);
15995 }
15996 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15997 DAG.getUNDEF(VT), NewMask);
15998}
15999
16000/// Load/store instruction that can be merged with a base address
16001/// update
16006 unsigned AddrOpIdx;
16007};
16008
16010 /// Instruction that updates a pointer
16012 /// Pointer increment operand
16014 /// Pointer increment value if it is a constant, or 0 otherwise
16015 unsigned ConstInc;
16016};
16017
16019 // Check that the add is independent of the load/store.
16020 // Otherwise, folding it would create a cycle. Search through Addr
16021 // as well, since the User may not be a direct user of Addr and
16022 // only share a base pointer.
16025 Worklist.push_back(N);
16026 Worklist.push_back(User);
16027 const unsigned MaxSteps = 1024;
16028 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16029 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16030 return false;
16031 return true;
16032}
16033
16035 struct BaseUpdateUser &User,
16036 bool SimpleConstIncOnly,
16038 SelectionDAG &DAG = DCI.DAG;
16039 SDNode *N = Target.N;
16041 SDLoc dl(N);
16042
16043 // Find the new opcode for the updating load/store.
16044 bool isLoadOp = true;
16045 bool isLaneOp = false;
16046 // Workaround for vst1x and vld1x intrinsics which do not have alignment
16047 // as an operand.
16048 bool hasAlignment = true;
16049 unsigned NewOpc = 0;
16050 unsigned NumVecs = 0;
16051 if (Target.isIntrinsic) {
16052 unsigned IntNo = N->getConstantOperandVal(1);
16053 switch (IntNo) {
16054 default:
16055 llvm_unreachable("unexpected intrinsic for Neon base update");
16056 case Intrinsic::arm_neon_vld1:
16057 NewOpc = ARMISD::VLD1_UPD;
16058 NumVecs = 1;
16059 break;
16060 case Intrinsic::arm_neon_vld2:
16061 NewOpc = ARMISD::VLD2_UPD;
16062 NumVecs = 2;
16063 break;
16064 case Intrinsic::arm_neon_vld3:
16065 NewOpc = ARMISD::VLD3_UPD;
16066 NumVecs = 3;
16067 break;
16068 case Intrinsic::arm_neon_vld4:
16069 NewOpc = ARMISD::VLD4_UPD;
16070 NumVecs = 4;
16071 break;
16072 case Intrinsic::arm_neon_vld1x2:
16073 NewOpc = ARMISD::VLD1x2_UPD;
16074 NumVecs = 2;
16075 hasAlignment = false;
16076 break;
16077 case Intrinsic::arm_neon_vld1x3:
16078 NewOpc = ARMISD::VLD1x3_UPD;
16079 NumVecs = 3;
16080 hasAlignment = false;
16081 break;
16082 case Intrinsic::arm_neon_vld1x4:
16083 NewOpc = ARMISD::VLD1x4_UPD;
16084 NumVecs = 4;
16085 hasAlignment = false;
16086 break;
16087 case Intrinsic::arm_neon_vld2dup:
16088 NewOpc = ARMISD::VLD2DUP_UPD;
16089 NumVecs = 2;
16090 break;
16091 case Intrinsic::arm_neon_vld3dup:
16092 NewOpc = ARMISD::VLD3DUP_UPD;
16093 NumVecs = 3;
16094 break;
16095 case Intrinsic::arm_neon_vld4dup:
16096 NewOpc = ARMISD::VLD4DUP_UPD;
16097 NumVecs = 4;
16098 break;
16099 case Intrinsic::arm_neon_vld2lane:
16100 NewOpc = ARMISD::VLD2LN_UPD;
16101 NumVecs = 2;
16102 isLaneOp = true;
16103 break;
16104 case Intrinsic::arm_neon_vld3lane:
16105 NewOpc = ARMISD::VLD3LN_UPD;
16106 NumVecs = 3;
16107 isLaneOp = true;
16108 break;
16109 case Intrinsic::arm_neon_vld4lane:
16110 NewOpc = ARMISD::VLD4LN_UPD;
16111 NumVecs = 4;
16112 isLaneOp = true;
16113 break;
16114 case Intrinsic::arm_neon_vst1:
16115 NewOpc = ARMISD::VST1_UPD;
16116 NumVecs = 1;
16117 isLoadOp = false;
16118 break;
16119 case Intrinsic::arm_neon_vst2:
16120 NewOpc = ARMISD::VST2_UPD;
16121 NumVecs = 2;
16122 isLoadOp = false;
16123 break;
16124 case Intrinsic::arm_neon_vst3:
16125 NewOpc = ARMISD::VST3_UPD;
16126 NumVecs = 3;
16127 isLoadOp = false;
16128 break;
16129 case Intrinsic::arm_neon_vst4:
16130 NewOpc = ARMISD::VST4_UPD;
16131 NumVecs = 4;
16132 isLoadOp = false;
16133 break;
16134 case Intrinsic::arm_neon_vst2lane:
16135 NewOpc = ARMISD::VST2LN_UPD;
16136 NumVecs = 2;
16137 isLoadOp = false;
16138 isLaneOp = true;
16139 break;
16140 case Intrinsic::arm_neon_vst3lane:
16141 NewOpc = ARMISD::VST3LN_UPD;
16142 NumVecs = 3;
16143 isLoadOp = false;
16144 isLaneOp = true;
16145 break;
16146 case Intrinsic::arm_neon_vst4lane:
16147 NewOpc = ARMISD::VST4LN_UPD;
16148 NumVecs = 4;
16149 isLoadOp = false;
16150 isLaneOp = true;
16151 break;
16152 case Intrinsic::arm_neon_vst1x2:
16153 NewOpc = ARMISD::VST1x2_UPD;
16154 NumVecs = 2;
16155 isLoadOp = false;
16156 hasAlignment = false;
16157 break;
16158 case Intrinsic::arm_neon_vst1x3:
16159 NewOpc = ARMISD::VST1x3_UPD;
16160 NumVecs = 3;
16161 isLoadOp = false;
16162 hasAlignment = false;
16163 break;
16164 case Intrinsic::arm_neon_vst1x4:
16165 NewOpc = ARMISD::VST1x4_UPD;
16166 NumVecs = 4;
16167 isLoadOp = false;
16168 hasAlignment = false;
16169 break;
16170 }
16171 } else {
16172 isLaneOp = true;
16173 switch (N->getOpcode()) {
16174 default:
16175 llvm_unreachable("unexpected opcode for Neon base update");
16176 case ARMISD::VLD1DUP:
16177 NewOpc = ARMISD::VLD1DUP_UPD;
16178 NumVecs = 1;
16179 break;
16180 case ARMISD::VLD2DUP:
16181 NewOpc = ARMISD::VLD2DUP_UPD;
16182 NumVecs = 2;
16183 break;
16184 case ARMISD::VLD3DUP:
16185 NewOpc = ARMISD::VLD3DUP_UPD;
16186 NumVecs = 3;
16187 break;
16188 case ARMISD::VLD4DUP:
16189 NewOpc = ARMISD::VLD4DUP_UPD;
16190 NumVecs = 4;
16191 break;
16192 case ISD::LOAD:
16193 NewOpc = ARMISD::VLD1_UPD;
16194 NumVecs = 1;
16195 isLaneOp = false;
16196 break;
16197 case ISD::STORE:
16198 NewOpc = ARMISD::VST1_UPD;
16199 NumVecs = 1;
16200 isLaneOp = false;
16201 isLoadOp = false;
16202 break;
16203 }
16204 }
16205
16206 // Find the size of memory referenced by the load/store.
16207 EVT VecTy;
16208 if (isLoadOp) {
16209 VecTy = N->getValueType(0);
16210 } else if (Target.isIntrinsic) {
16211 VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
16212 } else {
16213 assert(Target.isStore &&
16214 "Node has to be a load, a store, or an intrinsic!");
16215 VecTy = N->getOperand(1).getValueType();
16216 }
16217
16218 bool isVLDDUPOp =
16219 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
16220 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
16221
16222 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16223 if (isLaneOp || isVLDDUPOp)
16224 NumBytes /= VecTy.getVectorNumElements();
16225
16226 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
16227 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
16228 // separate instructions that make it harder to use a non-constant update.
16229 return false;
16230 }
16231
16232 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
16233 return false;
16234
16235 if (!isValidBaseUpdate(N, User.N))
16236 return false;
16237
16238 // OK, we found an ADD we can fold into the base update.
16239 // Now, create a _UPD node, taking care of not breaking alignment.
16240
16241 EVT AlignedVecTy = VecTy;
16242 Align Alignment = MemN->getAlign();
16243
16244 // If this is a less-than-standard-aligned load/store, change the type to
16245 // match the standard alignment.
16246 // The alignment is overlooked when selecting _UPD variants; and it's
16247 // easier to introduce bitcasts here than fix that.
16248 // There are 3 ways to get to this base-update combine:
16249 // - intrinsics: they are assumed to be properly aligned (to the standard
16250 // alignment of the memory type), so we don't need to do anything.
16251 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16252 // intrinsics, so, likewise, there's nothing to do.
16253 // - generic load/store instructions: the alignment is specified as an
16254 // explicit operand, rather than implicitly as the standard alignment
16255 // of the memory type (like the intrinsics). We need to change the
16256 // memory type to match the explicit alignment. That way, we don't
16257 // generate non-standard-aligned ARMISD::VLDx nodes.
16258 if (isa<LSBaseSDNode>(N)) {
16259 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16260 MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
16261 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16262 assert(!isLaneOp && "Unexpected generic load/store lane.");
16263 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16264 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
16265 }
16266 // Don't set an explicit alignment on regular load/stores that we want
16267 // to transform to VLD/VST 1_UPD nodes.
16268 // This matches the behavior of regular load/stores, which only get an
16269 // explicit alignment if the MMO alignment is larger than the standard
16270 // alignment of the memory type.
16271 // Intrinsics, however, always get an explicit alignment, set to the
16272 // alignment of the MMO.
16273 Alignment = Align(1);
16274 }
16275
16276 // Create the new updating load/store node.
16277 // First, create an SDVTList for the new updating node's results.
16278 EVT Tys[6];
16279 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16280 unsigned n;
16281 for (n = 0; n < NumResultVecs; ++n)
16282 Tys[n] = AlignedVecTy;
16283 Tys[n++] = MVT::i32;
16284 Tys[n] = MVT::Other;
16285 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16286
16287 // Then, gather the new node's operands.
16289 Ops.push_back(N->getOperand(0)); // incoming chain
16290 Ops.push_back(N->getOperand(Target.AddrOpIdx));
16291 Ops.push_back(User.Inc);
16292
16293 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
16294 // Try to match the intrinsic's signature
16295 Ops.push_back(StN->getValue());
16296 } else {
16297 // Loads (and of course intrinsics) match the intrinsics' signature,
16298 // so just add all but the alignment operand.
16299 unsigned LastOperand =
16300 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16301 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16302 Ops.push_back(N->getOperand(i));
16303 }
16304
16305 // For all node types, the alignment operand is always the last one.
16306 Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
16307
16308 // If this is a non-standard-aligned STORE, the penultimate operand is the
16309 // stored value. Bitcast it to the aligned type.
16310 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16311 SDValue &StVal = Ops[Ops.size() - 2];
16312 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
16313 }
16314
16315 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16316 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
16317 MemN->getMemOperand());
16318
16319 // Update the uses.
16320 SmallVector<SDValue, 5> NewResults;
16321 for (unsigned i = 0; i < NumResultVecs; ++i)
16322 NewResults.push_back(SDValue(UpdN.getNode(), i));
16323
16324 // If this is an non-standard-aligned LOAD, the first result is the loaded
16325 // value. Bitcast it to the expected result type.
16326 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16327 SDValue &LdVal = NewResults[0];
16328 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
16329 }
16330
16331 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16332 DCI.CombineTo(N, NewResults);
16333 DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
16334
16335 return true;
16336}
16337
16338// If (opcode ptr inc) is and ADD-like instruction, return the
16339// increment value. Otherwise return 0.
16340static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16341 SDValue Inc, const SelectionDAG &DAG) {
16343 if (!CInc)
16344 return 0;
16345
16346 switch (Opcode) {
16347 case ARMISD::VLD1_UPD:
16348 case ISD::ADD:
16349 return CInc->getZExtValue();
16350 case ISD::OR: {
16351 if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
16352 // (OR ptr inc) is the same as (ADD ptr inc)
16353 return CInc->getZExtValue();
16354 }
16355 return 0;
16356 }
16357 default:
16358 return 0;
16359 }
16360}
16361
16363 switch (N->getOpcode()) {
16364 case ISD::ADD:
16365 case ISD::OR: {
16366 if (isa<ConstantSDNode>(N->getOperand(1))) {
16367 *Ptr = N->getOperand(0);
16368 *CInc = N->getOperand(1);
16369 return true;
16370 }
16371 return false;
16372 }
16373 case ARMISD::VLD1_UPD: {
16374 if (isa<ConstantSDNode>(N->getOperand(2))) {
16375 *Ptr = N->getOperand(1);
16376 *CInc = N->getOperand(2);
16377 return true;
16378 }
16379 return false;
16380 }
16381 default:
16382 return false;
16383 }
16384}
16385
16386/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16387/// NEON load/store intrinsics, and generic vector load/stores, to merge
16388/// base address updates.
16389/// For generic load/stores, the memory type is assumed to be a vector.
16390/// The caller is assumed to have checked legality.
16393 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16394 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16395 const bool isStore = N->getOpcode() == ISD::STORE;
16396 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16397 BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
16398
16399 // Limit the number of possible base-updates we look at to prevent degenerate
16400 // cases.
16401 unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16402
16403 SDValue Addr = N->getOperand(AddrOpIdx);
16404
16406
16407 // Search for a use of the address operand that is an increment.
16408 for (SDUse &Use : Addr->uses()) {
16409 SDNode *User = Use.getUser();
16410 if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16411 continue;
16412
16413 SDValue Inc = User->getOperand(Use.getOperandNo() == 1 ? 0 : 1);
16414 unsigned ConstInc =
16415 getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
16416
16417 if (ConstInc || User->getOpcode() == ISD::ADD) {
16418 BaseUpdates.push_back({User, Inc, ConstInc});
16419 if (BaseUpdates.size() >= MaxBaseUpdates)
16420 break;
16421 }
16422 }
16423
16424 // If the address is a constant pointer increment itself, find
16425 // another constant increment that has the same base operand
16426 SDValue Base;
16427 SDValue CInc;
16428 if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
16429 unsigned Offset =
16430 getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
16431 if (Offset) {
16432 for (SDUse &Use : Base->uses()) {
16433
16434 SDNode *User = Use.getUser();
16435 if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16436 User->getNumOperands() != 2)
16437 continue;
16438
16439 SDValue UserInc = User->getOperand(Use.getOperandNo() == 0 ? 1 : 0);
16440 unsigned UserOffset =
16441 getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
16442
16443 if (!UserOffset || UserOffset <= Offset)
16444 continue;
16445
16446 unsigned NewConstInc = UserOffset - Offset;
16447 SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16448 BaseUpdates.push_back({User, NewInc, NewConstInc});
16449 if (BaseUpdates.size() >= MaxBaseUpdates)
16450 break;
16451 }
16452 }
16453 }
16454
16455 // Try to fold the load/store with an update that matches memory
16456 // access size. This should work well for sequential loads.
16457 unsigned NumValidUpd = BaseUpdates.size();
16458 for (unsigned I = 0; I < NumValidUpd; I++) {
16459 BaseUpdateUser &User = BaseUpdates[I];
16460 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16461 return SDValue();
16462 }
16463
16464 // Try to fold with other users. Non-constant updates are considered
16465 // first, and constant updates are sorted to not break a sequence of
16466 // strided accesses (if there is any).
16467 llvm::stable_sort(BaseUpdates,
16468 [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16469 return LHS.ConstInc < RHS.ConstInc;
16470 });
16471 for (BaseUpdateUser &User : BaseUpdates) {
16472 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16473 return SDValue();
16474 }
16475 return SDValue();
16476}
16477
16480 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16481 return SDValue();
16482
16483 return CombineBaseUpdate(N, DCI);
16484}
16485
16488 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16489 return SDValue();
16490
16491 SelectionDAG &DAG = DCI.DAG;
16492 SDValue Addr = N->getOperand(2);
16494 SDLoc dl(N);
16495
16496 // For the stores, where there are multiple intrinsics we only actually want
16497 // to post-inc the last of the them.
16498 unsigned IntNo = N->getConstantOperandVal(1);
16499 if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(5) != 1)
16500 return SDValue();
16501 if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(7) != 3)
16502 return SDValue();
16503
16504 // Search for a use of the address operand that is an increment.
16505 for (SDUse &Use : Addr->uses()) {
16506 SDNode *User = Use.getUser();
16507 if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16508 continue;
16509
16510 // Check that the add is independent of the load/store. Otherwise, folding
16511 // it would create a cycle. We can avoid searching through Addr as it's a
16512 // predecessor to both.
16515 Visited.insert(Addr.getNode());
16516 Worklist.push_back(N);
16517 Worklist.push_back(User);
16518 const unsigned MaxSteps = 1024;
16519 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16520 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16521 continue;
16522
16523 // Find the new opcode for the updating load/store.
16524 bool isLoadOp = true;
16525 unsigned NewOpc = 0;
16526 unsigned NumVecs = 0;
16527 switch (IntNo) {
16528 default:
16529 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16530 case Intrinsic::arm_mve_vld2q:
16531 NewOpc = ARMISD::VLD2_UPD;
16532 NumVecs = 2;
16533 break;
16534 case Intrinsic::arm_mve_vld4q:
16535 NewOpc = ARMISD::VLD4_UPD;
16536 NumVecs = 4;
16537 break;
16538 case Intrinsic::arm_mve_vst2q:
16539 NewOpc = ARMISD::VST2_UPD;
16540 NumVecs = 2;
16541 isLoadOp = false;
16542 break;
16543 case Intrinsic::arm_mve_vst4q:
16544 NewOpc = ARMISD::VST4_UPD;
16545 NumVecs = 4;
16546 isLoadOp = false;
16547 break;
16548 }
16549
16550 // Find the size of memory referenced by the load/store.
16551 EVT VecTy;
16552 if (isLoadOp) {
16553 VecTy = N->getValueType(0);
16554 } else {
16555 VecTy = N->getOperand(3).getValueType();
16556 }
16557
16558 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16559
16560 // If the increment is a constant, it must match the memory ref size.
16561 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16563 if (!CInc || CInc->getZExtValue() != NumBytes)
16564 continue;
16565
16566 // Create the new updating load/store node.
16567 // First, create an SDVTList for the new updating node's results.
16568 EVT Tys[6];
16569 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16570 unsigned n;
16571 for (n = 0; n < NumResultVecs; ++n)
16572 Tys[n] = VecTy;
16573 Tys[n++] = MVT::i32;
16574 Tys[n] = MVT::Other;
16575 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16576
16577 // Then, gather the new node's operands.
16579 Ops.push_back(N->getOperand(0)); // incoming chain
16580 Ops.push_back(N->getOperand(2)); // ptr
16581 Ops.push_back(Inc);
16582
16583 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16584 Ops.push_back(N->getOperand(i));
16585
16586 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16587 MemN->getMemOperand());
16588
16589 // Update the uses.
16590 SmallVector<SDValue, 5> NewResults;
16591 for (unsigned i = 0; i < NumResultVecs; ++i)
16592 NewResults.push_back(SDValue(UpdN.getNode(), i));
16593
16594 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16595 DCI.CombineTo(N, NewResults);
16596 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16597
16598 break;
16599 }
16600
16601 return SDValue();
16602}
16603
16604/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16605/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16606/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16607/// return true.
16609 SelectionDAG &DAG = DCI.DAG;
16610 EVT VT = N->getValueType(0);
16611 // vldN-dup instructions only support 64-bit vectors for N > 1.
16612 if (!VT.is64BitVector())
16613 return false;
16614
16615 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16616 SDNode *VLD = N->getOperand(0).getNode();
16617 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16618 return false;
16619 unsigned NumVecs = 0;
16620 unsigned NewOpc = 0;
16621 unsigned IntNo = VLD->getConstantOperandVal(1);
16622 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16623 NumVecs = 2;
16624 NewOpc = ARMISD::VLD2DUP;
16625 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16626 NumVecs = 3;
16627 NewOpc = ARMISD::VLD3DUP;
16628 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16629 NumVecs = 4;
16630 NewOpc = ARMISD::VLD4DUP;
16631 } else {
16632 return false;
16633 }
16634
16635 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16636 // numbers match the load.
16637 unsigned VLDLaneNo = VLD->getConstantOperandVal(NumVecs + 3);
16638 for (SDUse &Use : VLD->uses()) {
16639 // Ignore uses of the chain result.
16640 if (Use.getResNo() == NumVecs)
16641 continue;
16642 SDNode *User = Use.getUser();
16643 if (User->getOpcode() != ARMISD::VDUPLANE ||
16644 VLDLaneNo != User->getConstantOperandVal(1))
16645 return false;
16646 }
16647
16648 // Create the vldN-dup node.
16649 EVT Tys[5];
16650 unsigned n;
16651 for (n = 0; n < NumVecs; ++n)
16652 Tys[n] = VT;
16653 Tys[n] = MVT::Other;
16654 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumVecs + 1));
16655 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16657 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16658 Ops, VLDMemInt->getMemoryVT(),
16659 VLDMemInt->getMemOperand());
16660
16661 // Update the uses.
16662 for (SDUse &Use : VLD->uses()) {
16663 unsigned ResNo = Use.getResNo();
16664 // Ignore uses of the chain result.
16665 if (ResNo == NumVecs)
16666 continue;
16667 DCI.CombineTo(Use.getUser(), SDValue(VLDDup.getNode(), ResNo));
16668 }
16669
16670 // Now the vldN-lane intrinsic is dead except for its chain result.
16671 // Update uses of the chain.
16672 std::vector<SDValue> VLDDupResults;
16673 for (unsigned n = 0; n < NumVecs; ++n)
16674 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16675 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16676 DCI.CombineTo(VLD, VLDDupResults);
16677
16678 return true;
16679}
16680
16681/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16682/// ARMISD::VDUPLANE.
16685 const ARMSubtarget *Subtarget) {
16686 SDValue Op = N->getOperand(0);
16687 EVT VT = N->getValueType(0);
16688
16689 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16690 if (Subtarget->hasMVEIntegerOps()) {
16691 EVT ExtractVT = VT.getVectorElementType();
16692 // We need to ensure we are creating a legal type.
16693 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16694 ExtractVT = MVT::i32;
16695 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16696 N->getOperand(0), N->getOperand(1));
16697 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16698 }
16699
16700 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16701 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16702 if (CombineVLDDUP(N, DCI))
16703 return SDValue(N, 0);
16704
16705 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16706 // redundant. Ignore bit_converts for now; element sizes are checked below.
16707 while (Op.getOpcode() == ISD::BITCAST)
16708 Op = Op.getOperand(0);
16709 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16710 return SDValue();
16711
16712 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16713 unsigned EltSize = Op.getScalarValueSizeInBits();
16714 // The canonical VMOV for a zero vector uses a 32-bit element size.
16715 unsigned Imm = Op.getConstantOperandVal(0);
16716 unsigned EltBits;
16717 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16718 EltSize = 8;
16719 if (EltSize > VT.getScalarSizeInBits())
16720 return SDValue();
16721
16722 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16723}
16724
16725/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16727 const ARMSubtarget *Subtarget) {
16728 SDValue Op = N->getOperand(0);
16729 SDLoc dl(N);
16730
16731 if (Subtarget->hasMVEIntegerOps()) {
16732 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16733 // need to come from a GPR.
16734 if (Op.getValueType() == MVT::f32)
16735 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16736 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16737 else if (Op.getValueType() == MVT::f16)
16738 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16739 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16740 }
16741
16742 if (!Subtarget->hasNEON())
16743 return SDValue();
16744
16745 // Match VDUP(LOAD) -> VLD1DUP.
16746 // We match this pattern here rather than waiting for isel because the
16747 // transform is only legal for unindexed loads.
16748 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16749 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16750 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16751 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16752 DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16753 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16754 SDValue VLDDup =
16756 LD->getMemoryVT(), LD->getMemOperand());
16757 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16758 return VLDDup;
16759 }
16760
16761 return SDValue();
16762}
16763
16766 const ARMSubtarget *Subtarget) {
16767 EVT VT = N->getValueType(0);
16768 // Let the deinterleave combine form a structured load first.
16770 for (SDUse &Use : N->uses())
16771 if (Use.getUser()->getOpcode() == ISD::VECTOR_DEINTERLEAVE)
16772 return SDValue();
16773 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16774 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16776 return CombineBaseUpdate(N, DCI);
16777
16778 return SDValue();
16779}
16780
16781// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16782// pack all of the elements in one place. Next, store to memory in fewer
16783// chunks.
16785 SelectionDAG &DAG) {
16786 SDValue StVal = St->getValue();
16787 EVT VT = StVal.getValueType();
16788 if (!St->isTruncatingStore() || !VT.isVector())
16789 return SDValue();
16791 EVT StVT = St->getMemoryVT();
16792 unsigned NumElems = VT.getVectorNumElements();
16793 assert(StVT != VT && "Cannot truncate to the same type");
16794 unsigned FromEltSz = VT.getScalarSizeInBits();
16795 unsigned ToEltSz = StVT.getScalarSizeInBits();
16796
16797 // From, To sizes and ElemCount must be pow of two
16798 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16799 return SDValue();
16800
16801 // We are going to use the original vector elt for storing.
16802 // Accumulated smaller vector elements must be a multiple of the store size.
16803 if (0 != (NumElems * FromEltSz) % ToEltSz)
16804 return SDValue();
16805
16806 unsigned SizeRatio = FromEltSz / ToEltSz;
16807 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16808
16809 // Create a type on which we perform the shuffle.
16810 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16811 NumElems * SizeRatio);
16812 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16813
16814 SDLoc DL(St);
16815 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16816 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16817 for (unsigned i = 0; i < NumElems; ++i)
16818 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16819 : i * SizeRatio;
16820
16821 // Can't shuffle using an illegal type.
16822 if (!TLI.isTypeLegal(WideVecVT))
16823 return SDValue();
16824
16825 SDValue Shuff = DAG.getVectorShuffle(
16826 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16827 // At this point all of the data is stored at the bottom of the
16828 // register. We now need to save it to mem.
16829
16830 // Find the largest store unit
16831 MVT StoreType = MVT::i8;
16832 for (MVT Tp : MVT::integer_valuetypes()) {
16833 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16834 StoreType = Tp;
16835 }
16836 // Didn't find a legal store type.
16837 if (!TLI.isTypeLegal(StoreType))
16838 return SDValue();
16839
16840 // Bitcast the original vector into a vector of store-size units
16841 EVT StoreVecVT =
16842 EVT::getVectorVT(*DAG.getContext(), StoreType,
16843 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16844 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16845 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16847 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16848 TLI.getPointerTy(DAG.getDataLayout()));
16849 SDValue BasePtr = St->getBasePtr();
16850
16851 // Perform one or more big stores into memory.
16852 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16853 for (unsigned I = 0; I < E; I++) {
16854 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16855 ShuffWide, DAG.getIntPtrConstant(I, DL));
16856 SDValue Ch =
16857 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16858 St->getAlign(), St->getMemOperand()->getFlags());
16859 BasePtr =
16860 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16861 Chains.push_back(Ch);
16862 }
16863 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16864}
16865
16866// Try taking a single vector store from an fpround (which would otherwise turn
16867// into an expensive buildvector) and splitting it into a series of narrowing
16868// stores.
16870 SelectionDAG &DAG) {
16871 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16872 return SDValue();
16873 SDValue Trunc = St->getValue();
16874 if (Trunc->getOpcode() != ISD::FP_ROUND)
16875 return SDValue();
16876 EVT FromVT = Trunc->getOperand(0).getValueType();
16877 EVT ToVT = Trunc.getValueType();
16878 if (!ToVT.isVector())
16879 return SDValue();
16881 EVT ToEltVT = ToVT.getVectorElementType();
16882 EVT FromEltVT = FromVT.getVectorElementType();
16883
16884 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16885 return SDValue();
16886
16887 unsigned NumElements = 4;
16888 if (FromVT.getVectorNumElements() % NumElements != 0)
16889 return SDValue();
16890
16891 // Test if the Trunc will be convertible to a VMOVN with a shuffle, and if so
16892 // use the VMOVN over splitting the store. We are looking for patterns of:
16893 // !rev: 0 N 1 N+1 2 N+2 ...
16894 // rev: N 0 N+1 1 N+2 2 ...
16895 // The shuffle may either be a single source (in which case N = NumElts/2) or
16896 // two inputs extended with concat to the same size (in which case N =
16897 // NumElts).
16898 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16899 ArrayRef<int> M = SVN->getMask();
16900 unsigned NumElts = ToVT.getVectorNumElements();
16901 if (SVN->getOperand(1).isUndef())
16902 NumElts /= 2;
16903
16904 unsigned Off0 = Rev ? NumElts : 0;
16905 unsigned Off1 = Rev ? 0 : NumElts;
16906
16907 for (unsigned I = 0; I < NumElts; I += 2) {
16908 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16909 return false;
16910 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16911 return false;
16912 }
16913
16914 return true;
16915 };
16916
16917 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16918 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16919 return SDValue();
16920
16921 LLVMContext &C = *DAG.getContext();
16922 SDLoc DL(St);
16923 // Details about the old store
16924 SDValue Ch = St->getChain();
16925 SDValue BasePtr = St->getBasePtr();
16926 Align Alignment = St->getBaseAlign();
16927 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16928 AAMDNodes AAInfo = St->getAAInfo();
16929
16930 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16931 // and then stored as truncating integer stores.
16932 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16933 EVT NewToVT = EVT::getVectorVT(
16934 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16935
16937 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16938 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16939 SDValue NewPtr =
16940 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16941
16942 SDValue Extract =
16943 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16944 DAG.getConstant(i * NumElements, DL, MVT::i32));
16945
16946 SDValue FPTrunc =
16947 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16948 Extract, DAG.getConstant(0, DL, MVT::i32));
16949 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16950
16952 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16953 NewToVT, Alignment, MMOFlags, AAInfo);
16954 Stores.push_back(Store);
16955 }
16956 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16957}
16958
16959// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16960// into an expensive buildvector) and splitting it into a series of narrowing
16961// stores.
16963 SelectionDAG &DAG) {
16964 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16965 return SDValue();
16966 SDValue Trunc = St->getValue();
16967 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16968 return SDValue();
16969 EVT FromVT = Trunc->getOperand(0).getValueType();
16970 EVT ToVT = Trunc.getValueType();
16971
16972 LLVMContext &C = *DAG.getContext();
16973 SDLoc DL(St);
16974 // Details about the old store
16975 SDValue Ch = St->getChain();
16976 SDValue BasePtr = St->getBasePtr();
16977 Align Alignment = St->getBaseAlign();
16978 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16979 AAMDNodes AAInfo = St->getAAInfo();
16980
16981 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16982 FromVT.getVectorNumElements());
16983
16985 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16986 unsigned NewOffset =
16987 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16988 SDValue NewPtr =
16989 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16990
16991 SDValue Extract = Trunc.getOperand(i);
16993 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16994 NewToVT, Alignment, MMOFlags, AAInfo);
16995 Stores.push_back(Store);
16996 }
16997 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16998}
16999
17000// Given a floating point store from an extracted vector, with an integer
17001// VGETLANE that already exists, store the existing VGETLANEu directly. This can
17002// help reduce fp register pressure, doesn't require the fp extract and allows
17003// use of more integer post-inc stores not available with vstr.
17005 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
17006 return SDValue();
17007 SDValue Extract = St->getValue();
17008 EVT VT = Extract.getValueType();
17009 // For now only uses f16. This may be useful for f32 too, but that will
17010 // be bitcast(extract), not the VGETLANEu we currently check here.
17011 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17012 return SDValue();
17013
17014 SDNode *GetLane =
17015 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
17016 {Extract.getOperand(0), Extract.getOperand(1)});
17017 if (!GetLane)
17018 return SDValue();
17019
17020 LLVMContext &C = *DAG.getContext();
17021 SDLoc DL(St);
17022 // Create a new integer store to replace the existing floating point version.
17023 SDValue Ch = St->getChain();
17024 SDValue BasePtr = St->getBasePtr();
17025 Align Alignment = St->getBaseAlign();
17026 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
17027 AAMDNodes AAInfo = St->getAAInfo();
17028 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
17029 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
17030 St->getPointerInfo(), NewToVT, Alignment,
17031 MMOFlags, AAInfo);
17032
17033 return Store;
17034}
17035
17036// Combine stores of all VECTOR_INTERLEAVE results into a structured store
17037// (vstN) when they access consecutive memory. Running this after type
17038// legalization let wider vector types to be split into legal types, so each
17039// split can form a structured store.
17042 const ARMSubtarget *Subtarget) {
17044 return SDValue();
17045
17046 if (!ISD::isNormalStore(ST) || !ST->isSimple() || !ST->getOffset().isUndef())
17047 return SDValue();
17048
17049 SDValue StoredValue = ST->getValue();
17050 SDNode *Interleave = StoredValue.getNode();
17051 if (Interleave->getOpcode() != ISD::VECTOR_INTERLEAVE)
17052 return SDValue();
17053
17054 unsigned NumParts = Interleave->getNumOperands();
17056 return SDValue();
17057
17058 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
17059 return SDValue();
17060
17061 EVT SubVecTy = Interleave->getValueType(0);
17062 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
17063 !SubVecTy.is128BitVector())
17064 return SDValue();
17065 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
17066 return SDValue();
17067 unsigned EltBits = SubVecTy.getScalarSizeInBits();
17068 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
17069 return SDValue();
17070
17071 SmallVector<StoreSDNode *, 4> Stores(NumParts, nullptr);
17072 for (SDUse &Use : Interleave->uses()) {
17073 unsigned ResNo = Use.getResNo();
17075 if (Stores[ResNo] || !Store)
17076 return SDValue();
17077 Stores[ResNo] = Store;
17078 }
17079
17080 if (llvm::is_contained(Stores, nullptr))
17081 return SDValue();
17082
17083 StoreSDNode *BaseStore = Stores[0];
17084 if (Subtarget->hasMVEIntegerOps() && BaseStore->getAlign() < EltBits / 8)
17085 return SDValue();
17086 unsigned Bytes = SubVecTy.getStoreSize().getFixedValue();
17087 for (auto [Idx, Store] : enumerate(Stores)) {
17088 if (!DAG.areNonVolatileConsecutiveStores(Store, BaseStore, Bytes, Idx))
17089 return SDValue();
17090 }
17091
17092 static constexpr Intrinsic::ID NEONStores[] = {Intrinsic::arm_neon_vst2,
17093 Intrinsic::arm_neon_vst3,
17094 Intrinsic::arm_neon_vst4};
17095 SDLoc DL(Interleave);
17097
17098 Ops.push_back(BaseStore->getChain());
17099 Intrinsic::ID IID = 0;
17100 if (Subtarget->hasNEON())
17101 IID = NEONStores[NumParts - 2];
17102 else
17103 IID = NumParts == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17104
17105 Ops.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
17106
17107 Ops.push_back(BaseStore->getBasePtr());
17108 Ops.append(Interleave->op_begin(), Interleave->op_end());
17109 Ops.push_back(DAG.getConstant(BaseStore->getAlign().value(), DL, MVT::i32));
17110
17111 EVT MemVT =
17112 EVT::getVectorVT(*DAG.getContext(), SubVecTy.getVectorElementType(),
17113 SubVecTy.getVectorElementCount() * NumParts);
17115 MachineMemOperand *MMO =
17116 MF.getMachineMemOperand(BaseStore->getMemOperand(), 0, NumParts * Bytes);
17117 SDValue NewStore;
17118 if (Subtarget->hasNEON()) {
17119 NewStore = DAG.getMemIntrinsicNode(
17120 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
17121 } else {
17122 // MVE
17123 for (unsigned Stage = 0; Stage < NumParts; Stage++) {
17124 Ops.back() = DAG.getConstant(Stage, DL, MVT::i32);
17125 NewStore = DAG.getMemIntrinsicNode(
17126 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
17127 Ops.front() = NewStore;
17128 }
17129 }
17130 for (StoreSDNode *Store : Stores) {
17131 DAG.makeEquivalentMemoryOrdering(SDValue(Store, 0), NewStore);
17132 if (Store != ST)
17133 DCI.CombineTo(Store, NewStore);
17134 }
17135 return NewStore;
17136}
17137
17138static bool
17140 if (N->getOpcode() != ISD::CONCAT_VECTORS)
17141 return false;
17142
17143 unsigned NumParts = N->getNumOperands();
17144
17145 // We should be concatenating each sequential result from a
17146 // VECTOR_INTERLEAVE.
17147 SDNode *InterleaveOp = N->getOperand(0).getNode();
17148 if (InterleaveOp->getOpcode() != ISD::VECTOR_INTERLEAVE ||
17149 InterleaveOp->getNumOperands() != NumParts)
17150 return false;
17151
17152 for (unsigned I = 0; I < NumParts; I++)
17153 if (N->getOperand(I) != SDValue(InterleaveOp, I))
17154 return false;
17155
17156 Ops.append(InterleaveOp->op_begin(), InterleaveOp->op_end());
17157 return true;
17158}
17159
17162 const ARMSubtarget *Subtarget) {
17163 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
17164 return SDValue();
17165 if (SDValue Res =
17167 return Res;
17168
17169 if (!DCI.isBeforeLegalize())
17170 return SDValue();
17171
17172 if (!ISD::isNormalStore(ST) || !ST->isSimple() || !ST->getOffset().isUndef())
17173 return SDValue();
17174
17175 SDValue WideValue = ST->getValue();
17176 SmallVector<SDValue, 4> ValueInterleaveOps;
17178 ValueInterleaveOps))
17179 return SDValue();
17180
17181 if (!WideValue.hasOneUse())
17182 return SDValue();
17183
17184 unsigned NumParts = ValueInterleaveOps.size();
17185 if (NumParts != 2 && NumParts != 3 && NumParts != 4)
17186 return SDValue();
17187
17188 if (NumParts == 3 && Subtarget->hasMVEIntegerOps())
17189 return SDValue();
17190
17191 EVT SubVecTy = ValueInterleaveOps[0].getValueType();
17192 if (Subtarget->hasNEON() && !SubVecTy.is64BitVector() &&
17193 !SubVecTy.is128BitVector())
17194 return SDValue();
17195 if (Subtarget->hasMVEIntegerOps() && !SubVecTy.is128BitVector())
17196 return SDValue();
17197 unsigned EltBits = SubVecTy.getScalarSizeInBits();
17198 if (EltBits != 8 && EltBits != 16 && EltBits != 32)
17199 return SDValue();
17200 if (Subtarget->hasMVEIntegerOps() && ST->getAlign() < EltBits / 8)
17201 return SDValue();
17202 static constexpr Intrinsic::ID NEONStores[] = {Intrinsic::arm_neon_vst2,
17203 Intrinsic::arm_neon_vst3,
17204 Intrinsic::arm_neon_vst4};
17205 SDLoc DL(ST);
17207 Ops.push_back(ST->getChain());
17208 Intrinsic::ID IID = 0;
17209 if (Subtarget->hasNEON())
17210 IID = NEONStores[NumParts - 2];
17211 else
17212 IID = NumParts == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17213
17214 Ops.push_back(DAG.getTargetConstant(IID, DL, MVT::i64));
17215
17216 Ops.push_back(ST->getBasePtr());
17217 Ops.append(ValueInterleaveOps);
17218
17219 Ops.push_back(DAG.getConstant(ST->getAlign().value(), DL, MVT::i32));
17220 if (Subtarget->hasNEON())
17222 DAG.getVTList(MVT::Other), Ops,
17223 ST->getMemoryVT(), ST->getMemOperand());
17224 // MVE
17225 SDValue NewStore;
17226 for (unsigned Stage = 0; Stage < NumParts; Stage++) {
17227 Ops.back() = DAG.getConstant(Stage, DL, MVT::i32);
17229 DAG.getVTList(MVT::Other), Ops,
17230 ST->getMemoryVT(), ST->getMemOperand());
17231 Ops.front() = NewStore;
17232 }
17233 return NewStore;
17234}
17235
17236/// PerformSTORECombine - Target-specific dag combine xforms for
17237/// ISD::STORE.
17240 const ARMSubtarget *Subtarget) {
17242 if (St->isVolatile())
17243 return SDValue();
17244 SDValue StVal = St->getValue();
17245 EVT VT = StVal.getValueType();
17246 if (SDValue Store =
17248 return Store;
17249
17250 if (Subtarget->hasNEON())
17252 return Store;
17253
17254 if (Subtarget->hasMVEFloatOps())
17255 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
17256 return NewToken;
17257
17258 if (Subtarget->hasMVEIntegerOps()) {
17259 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
17260 return NewChain;
17261 if (SDValue NewToken =
17263 return NewToken;
17264 }
17265
17266 if (!ISD::isNormalStore(St))
17267 return SDValue();
17268
17269 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
17270 // ARM stores of arguments in the same cache line.
17271 if (StVal.getOpcode() == ARMISD::VMOVDRR && StVal->hasOneUse()) {
17272 SelectionDAG &DAG = DCI.DAG;
17273 bool isBigEndian = DAG.getDataLayout().isBigEndian();
17274 SDLoc DL(St);
17275 SDValue BasePtr = St->getBasePtr();
17276 SDValue NewST1 =
17277 DAG.getStore(St->getChain(), DL, StVal.getOperand(isBigEndian ? 1 : 0),
17278 BasePtr, St->getPointerInfo(), St->getBaseAlign(),
17279 St->getMemOperand()->getFlags());
17280
17281 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
17282 DAG.getConstant(4, DL, MVT::i32));
17283 return DAG.getStore(NewST1.getValue(0), DL,
17284 StVal.getOperand(isBigEndian ? 0 : 1), OffsetPtr,
17285 St->getPointerInfo().getWithOffset(4),
17286 St->getBaseAlign(), St->getMemOperand()->getFlags());
17287 }
17288
17289 if (StVal.getValueType() == MVT::i64 &&
17291 // Bitcast an i64 store extracted from a vector to f64.
17292 // Otherwise, the i64 value will be legalized to a pair of i32 values.
17293 SelectionDAG &DAG = DCI.DAG;
17294 SDLoc dl(StVal);
17295 SDValue IntVec = StVal.getOperand(0);
17296 EVT FloatVT =
17297 EVT::getVectorVT(*DAG.getContext(), MVT::f64,
17299 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
17300 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Vec,
17301 StVal.getOperand(1));
17302 dl = SDLoc(N);
17303 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
17304 // Make the DAGCombiner fold the bitcasts.
17305 DCI.AddToWorklist(Vec.getNode());
17306 DCI.AddToWorklist(ExtElt.getNode());
17307 DCI.AddToWorklist(V.getNode());
17308 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
17309 St->getPointerInfo(), St->getAlign(),
17310 St->getMemOperand()->getFlags(), St->getAAInfo());
17311 }
17312
17313 // If this is a legal vector store, try to combine it into a VST1_UPD.
17314 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
17316 return CombineBaseUpdate(N, DCI);
17317
17318 return SDValue();
17319}
17320
17321/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
17322/// can replace combinations of VMUL and VCVT (floating-point to integer)
17323/// when the VMUL has a constant operand that is a power of 2.
17324///
17325/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
17326/// vmul.f32 d16, d17, d16
17327/// vcvt.s32.f32 d16, d16
17328/// becomes:
17329/// vcvt.s32.f32 d16, d16, #3
17331 const ARMSubtarget *Subtarget) {
17332 if (!Subtarget->hasNEON())
17333 return SDValue();
17334
17335 SDValue Op = N->getOperand(0);
17336 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
17337 Op.getOpcode() != ISD::FMUL)
17338 return SDValue();
17339
17340 SDValue ConstVec = Op->getOperand(1);
17341 if (!isa<BuildVectorSDNode>(ConstVec))
17342 return SDValue();
17343
17344 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
17345 uint32_t FloatBits = FloatTy.getSizeInBits();
17346 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
17347 uint32_t IntBits = IntTy.getSizeInBits();
17348 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17349 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17350 // These instructions only exist converting from f32 to i32. We can handle
17351 // smaller integers by generating an extra truncate, but larger ones would
17352 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17353 // these instructions only support v2i32/v4i32 types.
17354 return SDValue();
17355 }
17356
17357 BitVector UndefElements;
17359 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
17360 if (C == -1 || C == 0 || C > 32)
17361 return SDValue();
17362
17363 SDLoc dl(N);
17364 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
17365 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
17366 Intrinsic::arm_neon_vcvtfp2fxu;
17367 SDValue FixConv = DAG.getNode(
17368 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
17369 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
17370 DAG.getConstant(C, dl, MVT::i32));
17371
17372 if (IntBits < FloatBits)
17373 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
17374
17375 return FixConv;
17376}
17377
17379 const ARMSubtarget *Subtarget) {
17380 if (!Subtarget->hasMVEFloatOps())
17381 return SDValue();
17382
17383 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
17384 // The second form can be more easily turned into a predicated vadd, and
17385 // possibly combined into a fma to become a predicated vfma.
17386 SDValue Op0 = N->getOperand(0);
17387 SDValue Op1 = N->getOperand(1);
17388 EVT VT = N->getValueType(0);
17389 SDLoc DL(N);
17390
17391 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
17392 // which these VMOV's represent.
17393 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
17394 if (Op.getOpcode() != ISD::BITCAST ||
17395 Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
17396 return false;
17397 uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
17398 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
17399 return true;
17400 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
17401 return true;
17402 return false;
17403 };
17404
17405 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
17406 std::swap(Op0, Op1);
17407
17408 if (Op1.getOpcode() != ISD::VSELECT)
17409 return SDValue();
17410
17411 SDNodeFlags FaddFlags = N->getFlags();
17412 bool NSZ = FaddFlags.hasNoSignedZeros();
17413 if (!isIdentitySplat(Op1.getOperand(2), NSZ))
17414 return SDValue();
17415
17416 SDValue FAdd =
17417 DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
17418 return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
17419}
17420
17422 SDValue LHS = N->getOperand(0);
17423 SDValue RHS = N->getOperand(1);
17424 EVT VT = N->getValueType(0);
17425 SDLoc DL(N);
17426
17427 if (!N->getFlags().hasAllowReassociation())
17428 return SDValue();
17429
17430 // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
17431 auto ReassocComplex = [&](SDValue A, SDValue B) {
17432 if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
17433 return SDValue();
17434 unsigned Opc = A.getConstantOperandVal(0);
17435 if (Opc != Intrinsic::arm_mve_vcmlaq)
17436 return SDValue();
17437 SDValue VCMLA = DAG.getNode(
17438 ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0), A.getOperand(1),
17439 DAG.getNode(ISD::FADD, DL, VT, A.getOperand(2), B, N->getFlags()),
17440 A.getOperand(3), A.getOperand(4));
17441 VCMLA->setFlags(A->getFlags());
17442 return VCMLA;
17443 };
17444 if (SDValue R = ReassocComplex(LHS, RHS))
17445 return R;
17446 if (SDValue R = ReassocComplex(RHS, LHS))
17447 return R;
17448
17449 return SDValue();
17450}
17451
17453 const ARMSubtarget *Subtarget) {
17455 return S;
17456 if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17457 return S;
17458 return SDValue();
17459}
17460
17461/// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17462/// can replace combinations of VCVT (integer to floating-point) and VMUL
17463/// when the VMUL has a constant operand that is a power of 2.
17464///
17465/// Example (assume d17 = <float 0.125, float 0.125>):
17466/// vcvt.f32.s32 d16, d16
17467/// vmul.f32 d16, d16, d17
17468/// becomes:
17469/// vcvt.f32.s32 d16, d16, #3
17471 const ARMSubtarget *Subtarget) {
17472 if (!Subtarget->hasNEON())
17473 return SDValue();
17474
17475 SDValue Op = N->getOperand(0);
17476 unsigned OpOpcode = Op.getNode()->getOpcode();
17477 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
17478 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17479 return SDValue();
17480
17481 SDValue ConstVec = N->getOperand(1);
17482 if (!isa<BuildVectorSDNode>(ConstVec))
17483 return SDValue();
17484
17485 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
17486 uint32_t FloatBits = FloatTy.getSizeInBits();
17487 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
17488 uint32_t IntBits = IntTy.getSizeInBits();
17489 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17490 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17491 // These instructions only exist converting from i32 to f32. We can handle
17492 // smaller integers by generating an extra extend, but larger ones would
17493 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17494 // these instructions only support v2i32/v4i32 types.
17495 return SDValue();
17496 }
17497
17498 ConstantFPSDNode *CN = isConstOrConstSplatFP(ConstVec, true);
17499 APFloat Recip(0.0f);
17500 if (!CN || !CN->getValueAPF().getExactInverse(&Recip))
17501 return SDValue();
17502
17503 bool IsExact;
17504 APSInt IntVal(33);
17505 if (Recip.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
17506 APFloat::opOK ||
17507 !IsExact)
17508 return SDValue();
17509
17510 int32_t C = IntVal.exactLogBase2();
17511 if (C == -1 || C == 0 || C > 32)
17512 return SDValue();
17513
17514 SDLoc DL(N);
17515 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17516 SDValue ConvInput = Op.getOperand(0);
17517 if (IntBits < FloatBits)
17519 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, ConvInput);
17520
17521 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17522 : Intrinsic::arm_neon_vcvtfxu2fp;
17523 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
17524 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
17525 DAG.getConstant(C, DL, MVT::i32));
17526}
17527
17529 const ARMSubtarget *ST) {
17530 if (!ST->hasMVEIntegerOps())
17531 return SDValue();
17532
17533 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17534 EVT ResVT = N->getValueType(0);
17535 SDValue N0 = N->getOperand(0);
17536 SDLoc dl(N);
17537
17538 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17539 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17540 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17541 N0.getValueType() == MVT::v16i8)) {
17542 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
17543 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
17544 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
17545 }
17546
17547 // We are looking for something that will have illegal types if left alone,
17548 // but that we can convert to a single instruction under MVE. For example
17549 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17550 // or
17551 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17552
17553 // The legal cases are:
17554 // VADDV u/s 8/16/32
17555 // VMLAV u/s 8/16/32
17556 // VADDLV u/s 32
17557 // VMLALV u/s 16/32
17558
17559 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17560 // extend it and use v4i32 instead.
17561 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17562 EVT AVT = A.getValueType();
17563 return any_of(ExtTypes, [&](MVT Ty) {
17564 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17565 AVT.bitsLE(Ty);
17566 });
17567 };
17568 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17569 EVT AVT = A.getValueType();
17570 if (!AVT.is128BitVector())
17571 A = DAG.getNode(
17572 ExtendCode, dl,
17574 *DAG.getContext(),
17576 A);
17577 return A;
17578 };
17579 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17580 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17581 return SDValue();
17582 SDValue A = N0->getOperand(0);
17583 if (ExtTypeMatches(A, ExtTypes))
17584 return ExtendIfNeeded(A, ExtendCode);
17585 return SDValue();
17586 };
17587 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17588 SDValue &Mask) {
17589 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17591 return SDValue();
17592 Mask = N0->getOperand(0);
17593 SDValue Ext = N0->getOperand(1);
17594 if (Ext->getOpcode() != ExtendCode)
17595 return SDValue();
17596 SDValue A = Ext->getOperand(0);
17597 if (ExtTypeMatches(A, ExtTypes))
17598 return ExtendIfNeeded(A, ExtendCode);
17599 return SDValue();
17600 };
17601 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17602 SDValue &A, SDValue &B) {
17603 // For a vmla we are trying to match a larger pattern:
17604 // ExtA = sext/zext A
17605 // ExtB = sext/zext B
17606 // Mul = mul ExtA, ExtB
17607 // vecreduce.add Mul
17608 // There might also be en extra extend between the mul and the addreduce, so
17609 // long as the bitwidth is high enough to make them equivalent (for example
17610 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17611 if (ResVT != RetTy)
17612 return false;
17613 SDValue Mul = N0;
17614 if (Mul->getOpcode() == ExtendCode &&
17615 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17616 ResVT.getScalarSizeInBits())
17617 Mul = Mul->getOperand(0);
17618 if (Mul->getOpcode() != ISD::MUL)
17619 return false;
17620 SDValue ExtA = Mul->getOperand(0);
17621 SDValue ExtB = Mul->getOperand(1);
17622 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17623 return false;
17624 A = ExtA->getOperand(0);
17625 B = ExtB->getOperand(0);
17626 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17627 A = ExtendIfNeeded(A, ExtendCode);
17628 B = ExtendIfNeeded(B, ExtendCode);
17629 return true;
17630 }
17631 return false;
17632 };
17633 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17634 SDValue &A, SDValue &B, SDValue &Mask) {
17635 // Same as the pattern above with a select for the zero predicated lanes
17636 // ExtA = sext/zext A
17637 // ExtB = sext/zext B
17638 // Mul = mul ExtA, ExtB
17639 // N0 = select Mask, Mul, 0
17640 // vecreduce.add N0
17641 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17643 return false;
17644 Mask = N0->getOperand(0);
17645 SDValue Mul = N0->getOperand(1);
17646 if (Mul->getOpcode() == ExtendCode &&
17647 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17648 ResVT.getScalarSizeInBits())
17649 Mul = Mul->getOperand(0);
17650 if (Mul->getOpcode() != ISD::MUL)
17651 return false;
17652 SDValue ExtA = Mul->getOperand(0);
17653 SDValue ExtB = Mul->getOperand(1);
17654 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17655 return false;
17656 A = ExtA->getOperand(0);
17657 B = ExtB->getOperand(0);
17658 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17659 A = ExtendIfNeeded(A, ExtendCode);
17660 B = ExtendIfNeeded(B, ExtendCode);
17661 return true;
17662 }
17663 return false;
17664 };
17665 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17666 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17667 // reductions. The operands are extended with MVEEXT, but as they are
17668 // reductions the lane orders do not matter. MVEEXT may be combined with
17669 // loads to produce two extending loads, or else they will be expanded to
17670 // VREV/VMOVL.
17671 EVT VT = Ops[0].getValueType();
17672 if (VT == MVT::v16i8) {
17673 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17674 "Unexpected illegal long reduction opcode");
17675 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17676
17677 SDValue Ext0 =
17678 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17679 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
17680 SDValue Ext1 =
17681 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17682 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
17683
17684 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
17685 Ext0, Ext1);
17686 SDValue MLA1 =
17687 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
17688 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17689 Ext0.getValue(1), Ext1.getValue(1));
17690 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17691 }
17692 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17693 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17694 SDValue(Node.getNode(), 1));
17695 };
17696
17697 SDValue A, B;
17698 SDValue Mask;
17699 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17700 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17701 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17702 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17703 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17704 A, B))
17705 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17706 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17707 A, B))
17708 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17709 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17710 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17711 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17712 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17713 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17714 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17715
17716 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17717 Mask))
17718 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17719 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17720 Mask))
17721 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17722 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17723 Mask))
17724 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17725 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17726 Mask))
17727 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17728 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17729 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17730 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17731 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17732 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17733 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17734
17735 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17736 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17737 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17738 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17739 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17740 return Create64bitNode(ARMISD::VADDLVs, {A});
17741 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17742 return Create64bitNode(ARMISD::VADDLVu, {A});
17743 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17744 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17745 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17746 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17747 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17748 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17749
17750 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17751 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17752 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17753 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17754 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17755 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17756 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17757 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17758 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17759 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17760 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17761 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17762 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17763 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17764
17765 // Some complications. We can get a case where the two inputs of the mul are
17766 // the same, then the output sext will have been helpfully converted to a
17767 // zext. Turn it back.
17768 SDValue Op = N0;
17769 if (Op->getOpcode() == ISD::VSELECT)
17770 Op = Op->getOperand(1);
17771 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17772 Op->getOperand(0)->getOpcode() == ISD::MUL) {
17773 SDValue Mul = Op->getOperand(0);
17774 if (Mul->getOperand(0) == Mul->getOperand(1) &&
17775 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17776 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17777 if (Op != N0)
17778 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17779 N0->getOperand(0), Ext, N0->getOperand(2));
17780 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17781 }
17782 }
17783
17784 return SDValue();
17785}
17786
17787// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17788// the lanes are used. Due to the reduction being commutative the shuffle can be
17789// removed.
17791 unsigned VecOp = N->getOperand(0).getValueType().isVector() ? 0 : 2;
17792 auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp));
17793 if (!Shuf || !Shuf->getOperand(1).isUndef())
17794 return SDValue();
17795
17796 // Check all elements are used once in the mask.
17797 ArrayRef<int> Mask = Shuf->getMask();
17798 APInt SetElts(Mask.size(), 0);
17799 for (int E : Mask) {
17800 if (E < 0 || E >= (int)Mask.size())
17801 return SDValue();
17802 SetElts.setBit(E);
17803 }
17804 if (!SetElts.isAllOnes())
17805 return SDValue();
17806
17807 if (N->getNumOperands() != VecOp + 1) {
17808 auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp + 1));
17809 if (!Shuf2 || !Shuf2->getOperand(1).isUndef() || Shuf2->getMask() != Mask)
17810 return SDValue();
17811 }
17812
17814 for (SDValue Op : N->ops()) {
17815 if (Op.getValueType().isVector())
17816 Ops.push_back(Op.getOperand(0));
17817 else
17818 Ops.push_back(Op);
17819 }
17820 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops);
17821}
17822
17825 SDValue Op0 = N->getOperand(0);
17826 SDValue Op1 = N->getOperand(1);
17827 unsigned IsTop = N->getConstantOperandVal(2);
17828
17829 // VMOVNT a undef -> a
17830 // VMOVNB a undef -> a
17831 // VMOVNB undef a -> a
17832 if (Op1->isUndef())
17833 return Op0;
17834 if (Op0->isUndef() && !IsTop)
17835 return Op1;
17836
17837 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17838 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17839 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17840 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17841 Op1->getConstantOperandVal(2) == 0)
17842 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17843 Op0, Op1->getOperand(1), N->getOperand(2));
17844
17845 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17846 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17847 // into the top or bottom lanes.
17848 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17849 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17850 APInt Op0DemandedElts =
17851 IsTop ? Op1DemandedElts
17852 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17853
17855 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17856 return SDValue(N, 0);
17857 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17858 return SDValue(N, 0);
17859
17860 return SDValue();
17861}
17862
17865 SDValue Op0 = N->getOperand(0);
17866 unsigned IsTop = N->getConstantOperandVal(2);
17867
17868 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17869 APInt Op0DemandedElts =
17870 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17871 : APInt::getHighBitsSet(2, 1));
17872
17874 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17875 return SDValue(N, 0);
17876 return SDValue();
17877}
17878
17881 EVT VT = N->getValueType(0);
17882 SDValue LHS = N->getOperand(0);
17883 SDValue RHS = N->getOperand(1);
17884
17885 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
17886 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
17887 // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17888 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
17889 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
17890 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17891 SDLoc DL(N);
17892 SDValue NewBinOp = DCI.DAG.getNode(N->getOpcode(), DL, VT,
17893 LHS.getOperand(0), RHS.getOperand(0));
17894 SDValue UndefV = LHS.getOperand(1);
17895 return DCI.DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
17896 }
17897 return SDValue();
17898}
17899
17901 SDLoc DL(N);
17902 SDValue Op0 = N->getOperand(0);
17903 SDValue Op1 = N->getOperand(1);
17904
17905 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17906 // uses of the intrinsics.
17907 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17908 int ShiftAmt = C->getSExtValue();
17909 if (ShiftAmt == 0) {
17910 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17911 DAG.ReplaceAllUsesWith(N, Merge.getNode());
17912 return SDValue();
17913 }
17914
17915 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17916 unsigned NewOpcode =
17917 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17918 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17919 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17920 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17921 return NewShift;
17922 }
17923 }
17924
17925 return SDValue();
17926}
17927
17928/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17930 DAGCombinerInfo &DCI) const {
17931 SelectionDAG &DAG = DCI.DAG;
17932 unsigned IntNo = N->getConstantOperandVal(0);
17933 switch (IntNo) {
17934 default:
17935 // Don't do anything for most intrinsics.
17936 break;
17937
17938 // Vector shifts: check for immediate versions and lower them.
17939 // Note: This is done during DAG combining instead of DAG legalizing because
17940 // the build_vectors for 64-bit vector element shift counts are generally
17941 // not legal, and it is hard to see their values after they get legalized to
17942 // loads from a constant pool.
17943 case Intrinsic::arm_neon_vshifts:
17944 case Intrinsic::arm_neon_vshiftu:
17945 case Intrinsic::arm_neon_vrshifts:
17946 case Intrinsic::arm_neon_vrshiftu:
17947 case Intrinsic::arm_neon_vrshiftn:
17948 case Intrinsic::arm_neon_vqshifts:
17949 case Intrinsic::arm_neon_vqshiftu:
17950 case Intrinsic::arm_neon_vqshiftsu:
17951 case Intrinsic::arm_neon_vqshiftns:
17952 case Intrinsic::arm_neon_vqshiftnu:
17953 case Intrinsic::arm_neon_vqshiftnsu:
17954 case Intrinsic::arm_neon_vqrshiftns:
17955 case Intrinsic::arm_neon_vqrshiftnu:
17956 case Intrinsic::arm_neon_vqrshiftnsu: {
17957 EVT VT = N->getOperand(1).getValueType();
17958 int64_t Cnt;
17959 unsigned VShiftOpc = 0;
17960
17961 switch (IntNo) {
17962 case Intrinsic::arm_neon_vshifts:
17963 case Intrinsic::arm_neon_vshiftu:
17964 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
17965 VShiftOpc = ARMISD::VSHLIMM;
17966 break;
17967 }
17968 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
17969 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17970 : ARMISD::VSHRuIMM);
17971 break;
17972 }
17973 return SDValue();
17974
17975 case Intrinsic::arm_neon_vrshifts:
17976 case Intrinsic::arm_neon_vrshiftu:
17977 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
17978 break;
17979 return SDValue();
17980
17981 case Intrinsic::arm_neon_vqshifts:
17982 case Intrinsic::arm_neon_vqshiftu:
17983 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17984 break;
17985 return SDValue();
17986
17987 case Intrinsic::arm_neon_vqshiftsu:
17988 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17989 break;
17990 llvm_unreachable("invalid shift count for vqshlu intrinsic");
17991
17992 case Intrinsic::arm_neon_vrshiftn:
17993 case Intrinsic::arm_neon_vqshiftns:
17994 case Intrinsic::arm_neon_vqshiftnu:
17995 case Intrinsic::arm_neon_vqshiftnsu:
17996 case Intrinsic::arm_neon_vqrshiftns:
17997 case Intrinsic::arm_neon_vqrshiftnu:
17998 case Intrinsic::arm_neon_vqrshiftnsu:
17999 // Narrowing shifts require an immediate right shift.
18000 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
18001 break;
18002 llvm_unreachable("invalid shift count for narrowing vector shift "
18003 "intrinsic");
18004
18005 default:
18006 llvm_unreachable("unhandled vector shift");
18007 }
18008
18009 switch (IntNo) {
18010 case Intrinsic::arm_neon_vshifts:
18011 case Intrinsic::arm_neon_vshiftu:
18012 // Opcode already set above.
18013 break;
18014 case Intrinsic::arm_neon_vrshifts:
18015 VShiftOpc = ARMISD::VRSHRsIMM;
18016 break;
18017 case Intrinsic::arm_neon_vrshiftu:
18018 VShiftOpc = ARMISD::VRSHRuIMM;
18019 break;
18020 case Intrinsic::arm_neon_vrshiftn:
18021 VShiftOpc = ARMISD::VRSHRNIMM;
18022 break;
18023 case Intrinsic::arm_neon_vqshifts:
18024 VShiftOpc = ARMISD::VQSHLsIMM;
18025 break;
18026 case Intrinsic::arm_neon_vqshiftu:
18027 VShiftOpc = ARMISD::VQSHLuIMM;
18028 break;
18029 case Intrinsic::arm_neon_vqshiftsu:
18030 VShiftOpc = ARMISD::VQSHLsuIMM;
18031 break;
18032 case Intrinsic::arm_neon_vqshiftns:
18033 VShiftOpc = ARMISD::VQSHRNsIMM;
18034 break;
18035 case Intrinsic::arm_neon_vqshiftnu:
18036 VShiftOpc = ARMISD::VQSHRNuIMM;
18037 break;
18038 case Intrinsic::arm_neon_vqshiftnsu:
18039 VShiftOpc = ARMISD::VQSHRNsuIMM;
18040 break;
18041 case Intrinsic::arm_neon_vqrshiftns:
18042 VShiftOpc = ARMISD::VQRSHRNsIMM;
18043 break;
18044 case Intrinsic::arm_neon_vqrshiftnu:
18045 VShiftOpc = ARMISD::VQRSHRNuIMM;
18046 break;
18047 case Intrinsic::arm_neon_vqrshiftnsu:
18048 VShiftOpc = ARMISD::VQRSHRNsuIMM;
18049 break;
18050 }
18051
18052 SDLoc dl(N);
18053 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
18054 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
18055 }
18056
18057 case Intrinsic::arm_neon_vshiftins: {
18058 EVT VT = N->getOperand(1).getValueType();
18059 int64_t Cnt;
18060 unsigned VShiftOpc = 0;
18061
18062 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
18063 VShiftOpc = ARMISD::VSLIIMM;
18064 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
18065 VShiftOpc = ARMISD::VSRIIMM;
18066 else {
18067 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
18068 }
18069
18070 SDLoc dl(N);
18071 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
18072 N->getOperand(1), N->getOperand(2),
18073 DAG.getConstant(Cnt, dl, MVT::i32));
18074 }
18075
18076 case Intrinsic::arm_neon_vqrshifts:
18077 case Intrinsic::arm_neon_vqrshiftu:
18078 // No immediate versions of these to check for.
18079 break;
18080
18081 case Intrinsic::arm_neon_vbsl: {
18082 SDLoc dl(N);
18083 return DAG.getNode(ARMISD::VBSP, dl, N->getValueType(0), N->getOperand(1),
18084 N->getOperand(2), N->getOperand(3));
18085 }
18086 case Intrinsic::arm_mve_vqdmlah:
18087 case Intrinsic::arm_mve_vqdmlash:
18088 case Intrinsic::arm_mve_vqrdmlah:
18089 case Intrinsic::arm_mve_vqrdmlash:
18090 case Intrinsic::arm_mve_vmla_n_predicated:
18091 case Intrinsic::arm_mve_vmlas_n_predicated:
18092 case Intrinsic::arm_mve_vqdmlah_predicated:
18093 case Intrinsic::arm_mve_vqdmlash_predicated:
18094 case Intrinsic::arm_mve_vqrdmlah_predicated:
18095 case Intrinsic::arm_mve_vqrdmlash_predicated: {
18096 // These intrinsics all take an i32 scalar operand which is narrowed to the
18097 // size of a single lane of the vector type they return. So we don't need
18098 // any bits of that operand above that point, which allows us to eliminate
18099 // uxth/sxth.
18100 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
18101 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
18102 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
18103 return SDValue();
18104 break;
18105 }
18106
18107 case Intrinsic::arm_mve_minv:
18108 case Intrinsic::arm_mve_maxv:
18109 case Intrinsic::arm_mve_minav:
18110 case Intrinsic::arm_mve_maxav:
18111 case Intrinsic::arm_mve_minv_predicated:
18112 case Intrinsic::arm_mve_maxv_predicated:
18113 case Intrinsic::arm_mve_minav_predicated:
18114 case Intrinsic::arm_mve_maxav_predicated: {
18115 // These intrinsics all take an i32 scalar operand which is narrowed to the
18116 // size of a single lane of the vector type they take as the other input.
18117 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
18118 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
18119 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18120 return SDValue();
18121 break;
18122 }
18123
18124 case Intrinsic::arm_mve_addv: {
18125 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
18126 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
18127 bool Unsigned = N->getConstantOperandVal(2);
18128 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
18129 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
18130 }
18131
18132 case Intrinsic::arm_mve_addlv:
18133 case Intrinsic::arm_mve_addlv_predicated: {
18134 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
18135 // which recombines the two outputs into an i64
18136 bool Unsigned = N->getConstantOperandVal(2);
18137 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
18138 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
18139 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
18140
18142 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
18143 if (i != 2) // skip the unsigned flag
18144 Ops.push_back(N->getOperand(i));
18145
18146 SDLoc dl(N);
18147 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
18148 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
18149 val.getValue(1));
18150 }
18151 }
18152
18153 return SDValue();
18154}
18155
18157 EVT VT = Y.getValueType();
18158 if (!VT.isVector())
18159 return hasAndNotCompare(Y);
18160 if (Subtarget->hasMVEIntegerOps())
18161 return VT.is128BitVector();
18162 if (Subtarget->hasNEON())
18163 return VT.is64BitVector() || VT.is128BitVector();
18164 return false;
18165}
18166
18167/// PerformShiftCombine - Checks for immediate versions of vector shifts and
18168/// lowers them. As with the vector shift intrinsics, this is done during DAG
18169/// combining instead of DAG legalizing because the build_vectors for 64-bit
18170/// vector element shift counts are generally not legal, and it is hard to see
18171/// their values after they get legalized to loads from a constant pool.
18174 const ARMSubtarget *ST) {
18175 SelectionDAG &DAG = DCI.DAG;
18176 EVT VT = N->getValueType(0);
18177
18178 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
18179 N->getOperand(0)->getOpcode() == ISD::AND &&
18180 N->getOperand(0)->hasOneUse()) {
18181 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18182 return SDValue();
18183 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
18184 // usually show up because instcombine prefers to canonicalize it to
18185 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
18186 // out of GEP lowering in some cases.
18187 SDValue N0 = N->getOperand(0);
18188 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
18189 if (!ShiftAmtNode)
18190 return SDValue();
18191 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
18192 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
18193 if (!AndMaskNode)
18194 return SDValue();
18195 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
18196 // Don't transform uxtb/uxth.
18197 if (AndMask == 255 || AndMask == 65535)
18198 return SDValue();
18199 if (isMask_32(AndMask)) {
18200 uint32_t MaskedBits = llvm::countl_zero(AndMask);
18201 if (MaskedBits > ShiftAmt) {
18202 SDLoc DL(N);
18203 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
18204 DAG.getConstant(MaskedBits, DL, MVT::i32));
18205 return DAG.getNode(
18206 ISD::SRL, DL, MVT::i32, SHL,
18207 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
18208 }
18209 }
18210 }
18211
18212 // Nothing to be done for scalar shifts.
18214 if (!VT.isVector() || !TLI.isTypeLegal(VT))
18215 return SDValue();
18216 if (ST->hasMVEIntegerOps())
18217 return SDValue();
18218
18219 int64_t Cnt;
18220
18221 switch (N->getOpcode()) {
18222 default: llvm_unreachable("unexpected shift opcode");
18223
18224 case ISD::SHL:
18225 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
18226 SDLoc dl(N);
18227 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
18228 DAG.getConstant(Cnt, dl, MVT::i32));
18229 }
18230 break;
18231
18232 case ISD::SRA:
18233 case ISD::SRL:
18234 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
18235 unsigned VShiftOpc =
18236 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
18237 SDLoc dl(N);
18238 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
18239 DAG.getConstant(Cnt, dl, MVT::i32));
18240 }
18241 }
18242 return SDValue();
18243}
18244
18245// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
18246// split into multiple extending loads, which are simpler to deal with than an
18247// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
18248// to convert the type to an f32.
18250 SDValue N0 = N->getOperand(0);
18251 if (N0.getOpcode() != ISD::LOAD)
18252 return SDValue();
18254 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
18255 LD->getExtensionType() != ISD::NON_EXTLOAD)
18256 return SDValue();
18257 EVT FromVT = LD->getValueType(0);
18258 EVT ToVT = N->getValueType(0);
18259 if (!ToVT.isVector())
18260 return SDValue();
18262 EVT ToEltVT = ToVT.getVectorElementType();
18263 EVT FromEltVT = FromVT.getVectorElementType();
18264
18265 unsigned NumElements = 0;
18266 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
18267 NumElements = 4;
18268 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
18269 NumElements = 4;
18270 if (NumElements == 0 ||
18271 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
18272 FromVT.getVectorNumElements() % NumElements != 0 ||
18273 !isPowerOf2_32(NumElements))
18274 return SDValue();
18275
18276 LLVMContext &C = *DAG.getContext();
18277 SDLoc DL(LD);
18278 // Details about the old load
18279 SDValue Ch = LD->getChain();
18280 SDValue BasePtr = LD->getBasePtr();
18281 Align Alignment = LD->getBaseAlign();
18282 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18283 AAMDNodes AAInfo = LD->getAAInfo();
18284
18285 ISD::LoadExtType NewExtType =
18286 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18287 SDValue Offset = DAG.getPOISON(BasePtr.getValueType());
18288 EVT NewFromVT = EVT::getVectorVT(
18289 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18290 EVT NewToVT = EVT::getVectorVT(
18291 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18292
18295 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18296 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18297 SDValue NewPtr =
18298 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
18299
18300 SDValue NewLoad =
18301 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18302 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18303 Alignment, MMOFlags, AAInfo);
18304 Loads.push_back(NewLoad);
18305 Chains.push_back(SDValue(NewLoad.getNode(), 1));
18306 }
18307
18308 // Float truncs need to extended with VCVTB's into their floating point types.
18309 if (FromEltVT == MVT::f16) {
18311
18312 for (unsigned i = 0; i < Loads.size(); i++) {
18313 SDValue LoadBC =
18314 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
18315 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
18316 DAG.getConstant(0, DL, MVT::i32));
18317 Extends.push_back(FPExt);
18318 }
18319
18320 Loads = Extends;
18321 }
18322
18323 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18324 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18325 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
18326}
18327
18328/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
18329/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
18331 const ARMSubtarget *ST) {
18332 SDValue N0 = N->getOperand(0);
18333 EVT VT = N->getValueType(0);
18334 SDLoc DL(N);
18335
18336 // Check for sign- and zero-extensions of vector extract operations of 8- and
18337 // 16-bit vector elements. NEON and MVE support these directly. They are
18338 // handled during DAG combining because type legalization will promote them
18339 // to 32-bit types and it is messy to recognize the operations after that.
18340 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
18342 SDValue Vec = N0.getOperand(0);
18343 SDValue Lane = N0.getOperand(1);
18344 EVT EltVT = N0.getValueType();
18346
18347 if (VT == MVT::i32 &&
18348 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
18349 TLI.isTypeLegal(Vec.getValueType()) &&
18350 isa<ConstantSDNode>(Lane)) {
18351
18352 unsigned Opc = 0;
18353 switch (N->getOpcode()) {
18354 default: llvm_unreachable("unexpected opcode");
18355 case ISD::SIGN_EXTEND:
18356 Opc = ARMISD::VGETLANEs;
18357 break;
18358 case ISD::ZERO_EXTEND:
18359 case ISD::ANY_EXTEND:
18360 Opc = ARMISD::VGETLANEu;
18361 break;
18362 }
18363 return DAG.getNode(Opc, DL, VT, Vec, Lane);
18364 }
18365 }
18366
18367 if (ST->hasMVEIntegerOps())
18368 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18369 return NewLoad;
18370
18371 // Combine sext(buildvector(..)) to buildvector(sext(..)) to help avoid
18372 // difficult to lower i1 buildvector.
18373 if (ST->hasMVEIntegerOps() && N0.getValueType().getScalarSizeInBits() == 1 &&
18374 N0.getOpcode() == ISD::BUILD_VECTOR && VT.getScalarSizeInBits() <= 32) {
18376 for (unsigned I = 0; I < N0.getNumOperands(); I++) {
18377 SDValue InReg = N0.getOperand(I);
18378 if (N->getOpcode() == ISD::ZERO_EXTEND)
18379 InReg = DAG.getNode(ISD::AND, DL, InReg.getValueType(), InReg,
18380 DAG.getConstant(1, DL, InReg.getValueType()));
18381 else if (N->getOpcode() == ISD::SIGN_EXTEND)
18382 InReg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InReg.getValueType(),
18383 InReg, DAG.getValueType(MVT::i1));
18384 SDValue Ext = DAG.getNode(N->getOpcode(), DL, MVT::i32, InReg);
18385 Ops.push_back(Ext);
18386 }
18387 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
18388 }
18389
18390 return SDValue();
18391}
18392
18394 const ARMSubtarget *ST) {
18395 if (ST->hasMVEFloatOps())
18396 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18397 return NewLoad;
18398
18399 return SDValue();
18400}
18401
18402// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
18403// constant bounds.
18405 const ARMSubtarget *Subtarget) {
18406 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
18407 !Subtarget->isThumb2())
18408 return SDValue();
18409
18410 EVT VT = Op.getValueType();
18411 SDValue Op0 = Op.getOperand(0);
18412
18413 if (VT != MVT::i32 ||
18414 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
18415 !isa<ConstantSDNode>(Op.getOperand(1)) ||
18417 return SDValue();
18418
18419 SDValue Min = Op;
18420 SDValue Max = Op0;
18421 SDValue Input = Op0.getOperand(0);
18422 if (Min.getOpcode() == ISD::SMAX)
18423 std::swap(Min, Max);
18424
18425 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX)
18426 return SDValue();
18427
18428 APInt MinC = Min.getConstantOperandAPInt(1);
18429 APInt MaxC = Max.getConstantOperandAPInt(1);
18430 if (MaxC.sgt(MinC))
18431 return SDValue();
18432
18433 SDLoc DL(Op);
18434
18435 // A clamp whose bounds are already a saturation range maps to a single
18436 // SSAT / USAT.
18437 if ((MinC + 1).isPowerOf2()) {
18438 if (MinC == ~MaxC)
18439 return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
18440 DAG.getConstant(MinC.countr_one(), DL, VT));
18441 if (MaxC == 0)
18442 return DAG.getNode(ARMISD::USAT, DL, VT, Input,
18443 DAG.getConstant(MinC.countr_one(), DL, VT));
18444 }
18445
18446 // For power-of-two clamp widths, convert the range to be zero-centered,
18447 // apply SSAT, and convert the result back.
18448 //
18449 // Width = Hi - Lo + 1
18450 // Center = Lo + Width / 2
18451 // Result = ssat(X - Center) + Center
18452 //
18453 // The idea is to shift the input so that the clamp range is centered
18454 // around zero, apply ssat, and then shift the result back.
18455 //
18456 // For example clamp(X, -118, 137) -> Width = 256, Center = 10, so it becomes
18457 // ssat(X - 10, 8) + 10
18458
18459 APInt Width = MinC - MaxC + 1;
18460 if (!Width.isPowerOf2() || Width.isOne())
18461 return SDValue();
18462 unsigned SatBit = Width.logBase2() - 1; // ssat to SatBit + 1 signed bits
18463 APInt Center = MaxC + Width.lshr(1);
18464
18465 // The rewrite is only valid when X - Center does not overflow;
18466 SDValue NegC = DAG.getConstant(-Center, DL, VT);
18468 return SDValue();
18469
18470 SDValue Shifted = DAG.getNode(ISD::ADD, DL, VT, Input, NegC);
18471 SDValue Sat = DAG.getNode(ARMISD::SSAT, DL, VT, Shifted,
18472 DAG.getConstant(SatBit, DL, VT));
18473 return DAG.getNode(ISD::ADD, DL, VT, Sat, DAG.getConstant(Center, DL, VT));
18474}
18475
18476/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
18477/// saturates.
18479 const ARMSubtarget *ST) {
18480 EVT VT = N->getValueType(0);
18481 SDValue N0 = N->getOperand(0);
18482
18483 if (VT == MVT::i32)
18484 return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
18485
18486 if (!ST->hasMVEIntegerOps())
18487 return SDValue();
18488
18489 if (SDValue V = PerformVQDMULHCombine(N, DAG))
18490 return V;
18491
18492 if (VT != MVT::v4i32 && VT != MVT::v8i16)
18493 return SDValue();
18494
18495 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
18496 // Check one is a smin and the other is a smax
18497 if (Min->getOpcode() != ISD::SMIN)
18498 std::swap(Min, Max);
18499 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
18500 return false;
18501
18502 APInt SaturateC;
18503 if (VT == MVT::v4i32)
18504 SaturateC = APInt(32, (1 << 15) - 1, true);
18505 else //if (VT == MVT::v8i16)
18506 SaturateC = APInt(16, (1 << 7) - 1, true);
18507
18508 APInt MinC, MaxC;
18509 if (!ISD::isConstantSplatVector(Min->getOperand(1), MinC) ||
18510 MinC != SaturateC)
18511 return false;
18512 if (!ISD::isConstantSplatVector(Max->getOperand(1), MaxC) ||
18513 MaxC != ~SaturateC)
18514 return false;
18515 return true;
18516 };
18517
18518 if (IsSignedSaturate(N, N0.getNode())) {
18519 SDLoc DL(N);
18520 MVT ExtVT, HalfVT;
18521 if (VT == MVT::v4i32) {
18522 HalfVT = MVT::v8i16;
18523 ExtVT = MVT::v4i16;
18524 } else { // if (VT == MVT::v8i16)
18525 HalfVT = MVT::v16i8;
18526 ExtVT = MVT::v8i8;
18527 }
18528
18529 // Create a VQMOVNB with undef top lanes, then signed extended into the top
18530 // half. That extend will hopefully be removed if only the bottom bits are
18531 // demanded (though a truncating store, for example).
18532 SDValue VQMOVN =
18533 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
18534 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
18535 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
18537 DAG.getValueType(ExtVT));
18538 }
18539
18540 auto IsUnsignedSaturate = [&](SDNode *Min) {
18541 // For unsigned, we just need to check for <= 0xffff
18542 if (Min->getOpcode() != ISD::UMIN)
18543 return false;
18544
18545 APInt SaturateC;
18546 if (VT == MVT::v4i32)
18547 SaturateC = APInt(32, (1 << 16) - 1, true);
18548 else //if (VT == MVT::v8i16)
18549 SaturateC = APInt(16, (1 << 8) - 1, true);
18550
18551 APInt MinC;
18552 if (!ISD::isConstantSplatVector(Min->getOperand(1), MinC) ||
18553 MinC != SaturateC)
18554 return false;
18555 return true;
18556 };
18557
18558 if (IsUnsignedSaturate(N)) {
18559 SDLoc DL(N);
18560 MVT HalfVT;
18561 unsigned ExtConst;
18562 if (VT == MVT::v4i32) {
18563 HalfVT = MVT::v8i16;
18564 ExtConst = 0x0000FFFF;
18565 } else { //if (VT == MVT::v8i16)
18566 HalfVT = MVT::v16i8;
18567 ExtConst = 0x00FF;
18568 }
18569
18570 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18571 // an AND. That extend will hopefully be removed if only the bottom bits are
18572 // demanded (though a truncating store, for example).
18573 SDValue VQMOVN =
18574 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
18575 DAG.getConstant(0, DL, MVT::i32));
18576 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18577 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
18578 DAG.getConstant(ExtConst, DL, VT));
18579 }
18580
18581 return SDValue();
18582}
18583
18586 if (!C)
18587 return nullptr;
18588 const APInt *CV = &C->getAPIntValue();
18589 return CV->isPowerOf2() ? CV : nullptr;
18590}
18591
18593 // If we have a CMOV, OR and AND combination such as:
18594 // if (x & CN)
18595 // y |= CM;
18596 //
18597 // And:
18598 // * CN is a single bit;
18599 // * All bits covered by CM are known zero in y
18600 //
18601 // Then we can convert this into a sequence of BFI instructions. This will
18602 // always be a win if CM is a single bit, will always be no worse than the
18603 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18604 // three bits (due to the extra IT instruction).
18605
18606 SDValue Op0 = CMOV->getOperand(0);
18607 SDValue Op1 = CMOV->getOperand(1);
18608 auto CC = CMOV->getConstantOperandAPInt(2).getLimitedValue();
18609 SDValue CmpZ = CMOV->getOperand(3);
18610
18611 // The compare must be against zero.
18612 if (!isNullConstant(CmpZ->getOperand(1)))
18613 return SDValue();
18614
18615 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18616 SDValue And = CmpZ->getOperand(0);
18617 if (And->getOpcode() != ISD::AND)
18618 return SDValue();
18619 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
18620 if (!AndC)
18621 return SDValue();
18622 SDValue X = And->getOperand(0);
18623
18624 if (CC == ARMCC::EQ) {
18625 // We're performing an "equal to zero" compare. Swap the operands so we
18626 // canonicalize on a "not equal to zero" compare.
18627 std::swap(Op0, Op1);
18628 } else {
18629 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18630 }
18631
18632 if (Op1->getOpcode() != ISD::OR)
18633 return SDValue();
18634
18636 if (!OrC)
18637 return SDValue();
18638 SDValue Y = Op1->getOperand(0);
18639
18640 if (Op0 != Y)
18641 return SDValue();
18642
18643 // Now, is it profitable to continue?
18644 APInt OrCI = OrC->getAPIntValue();
18645 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18646 if (OrCI.popcount() > Heuristic)
18647 return SDValue();
18648
18649 // Lastly, can we determine that the bits defined by OrCI
18650 // are zero in Y?
18652 if ((OrCI & Known.Zero) != OrCI)
18653 return SDValue();
18654
18655 // OK, we can do the combine.
18656 SDValue V = Y;
18657 SDLoc dl(X);
18658 EVT VT = X.getValueType();
18659 unsigned BitInX = AndC->logBase2();
18660
18661 if (BitInX != 0) {
18662 // We must shift X first.
18663 X = DAG.getNode(ISD::SRL, dl, VT, X,
18664 DAG.getConstant(BitInX, dl, VT));
18665 }
18666
18667 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18668 BitInY < NumActiveBits; ++BitInY) {
18669 if (OrCI[BitInY] == 0)
18670 continue;
18671 APInt Mask(VT.getSizeInBits(), 0);
18672 Mask.setBit(BitInY);
18673 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
18674 // Confusingly, the operand is an *inverted* mask.
18675 DAG.getConstant(~Mask, dl, VT));
18676 }
18677
18678 return V;
18679}
18680
18681// Given N, the value controlling the conditional branch, search for the loop
18682// intrinsic, returning it, along with how the value is used. We need to handle
18683// patterns such as the following:
18684// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18685// (brcond (setcc (loop.decrement), 0, eq), exit)
18686// (brcond (setcc (loop.decrement), 0, ne), header)
18688 bool &Negate) {
18689 switch (N->getOpcode()) {
18690 default:
18691 break;
18692 case ISD::XOR: {
18693 if (!isa<ConstantSDNode>(N.getOperand(1)))
18694 return SDValue();
18695 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
18696 return SDValue();
18697 Negate = !Negate;
18698 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
18699 }
18700 case ISD::SETCC: {
18701 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
18702 if (!Const)
18703 return SDValue();
18704 if (Const->isZero())
18705 Imm = 0;
18706 else if (Const->isOne())
18707 Imm = 1;
18708 else
18709 return SDValue();
18710 CC = N.getOperandCondCode(2);
18711 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
18712 }
18714 unsigned IntOp = N.getConstantOperandVal(1);
18715 if (IntOp != Intrinsic::test_start_loop_iterations &&
18716 IntOp != Intrinsic::loop_decrement_reg)
18717 return SDValue();
18718 return N;
18719 }
18720 }
18721 return SDValue();
18722}
18723
18726 const ARMSubtarget *ST) {
18727
18728 // The hwloop intrinsics that we're interested are used for control-flow,
18729 // either for entering or exiting the loop:
18730 // - test.start.loop.iterations will test whether its operand is zero. If it
18731 // is zero, the proceeding branch should not enter the loop.
18732 // - loop.decrement.reg also tests whether its operand is zero. If it is
18733 // zero, the proceeding branch should not branch back to the beginning of
18734 // the loop.
18735 // So here, we need to check that how the brcond is using the result of each
18736 // of the intrinsics to ensure that we're branching to the right place at the
18737 // right time.
18738
18740 SDValue Cond;
18741 int Imm = 1;
18742 bool Negate = false;
18743 SDValue Chain = N->getOperand(0);
18744 SDValue Dest;
18745
18746 if (N->getOpcode() == ISD::BRCOND) {
18747 CC = ISD::SETEQ;
18748 Cond = N->getOperand(1);
18749 Dest = N->getOperand(2);
18750 } else {
18751 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18752 CC = N->getOperandCondCode(1);
18753 Cond = N->getOperand(2);
18754 Dest = N->getOperand(4);
18755 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
18756 if (!Const->isOne() && !Const->isZero())
18757 return SDValue();
18758 Imm = Const->getZExtValue();
18759 } else
18760 return SDValue();
18761 }
18762
18764 if (!Int)
18765 return SDValue();
18766
18767 if (Negate)
18768 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
18769
18770 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18771 return (CC == ISD::SETEQ && Imm == 0) ||
18772 (CC == ISD::SETNE && Imm == 1) ||
18773 (CC == ISD::SETLT && Imm == 1) ||
18774 (CC == ISD::SETULT && Imm == 1);
18775 };
18776
18777 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18778 return (CC == ISD::SETEQ && Imm == 1) ||
18779 (CC == ISD::SETNE && Imm == 0) ||
18780 (CC == ISD::SETGT && Imm == 0) ||
18781 (CC == ISD::SETUGT && Imm == 0) ||
18782 (CC == ISD::SETGE && Imm == 1) ||
18783 (CC == ISD::SETUGE && Imm == 1);
18784 };
18785
18786 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18787 "unsupported condition");
18788
18789 SDLoc dl(Int);
18790 SelectionDAG &DAG = DCI.DAG;
18791 SDValue Elements = Int.getOperand(2);
18792 unsigned IntOp = Int->getConstantOperandVal(1);
18793 assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18794 "expected single br user");
18795 SDNode *Br = *N->user_begin();
18796 SDValue OtherTarget = Br->getOperand(1);
18797
18798 // Update the unconditional branch to branch to the given Dest.
18799 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18800 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
18801 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
18802 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
18803 };
18804
18805 if (IntOp == Intrinsic::test_start_loop_iterations) {
18806 SDValue Res;
18807 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
18808 // We expect this 'instruction' to branch when the counter is zero.
18809 if (IsTrueIfZero(CC, Imm)) {
18810 SDValue Ops[] = {Chain, Setup, Dest};
18811 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18812 } else {
18813 // The logic is the reverse of what we need for WLS, so find the other
18814 // basic block target: the target of the proceeding br.
18815 UpdateUncondBr(Br, Dest, DAG);
18816
18817 SDValue Ops[] = {Chain, Setup, OtherTarget};
18818 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18819 }
18820 // Update LR count to the new value
18821 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18822 // Update chain
18823 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18824 return Res;
18825 } else {
18826 SDValue Size =
18827 DAG.getTargetConstant(Int.getConstantOperandVal(3), dl, MVT::i32);
18828 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18829 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18830 DAG.getVTList(MVT::i32, MVT::Other), Args);
18831 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18832
18833 // We expect this instruction to branch when the count is not zero.
18834 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18835
18836 // Update the unconditional branch to target the loop preheader if we've
18837 // found the condition has been reversed.
18838 if (Target == OtherTarget)
18839 UpdateUncondBr(Br, Dest, DAG);
18840
18841 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18842 SDValue(LoopDec.getNode(), 1), Chain);
18843
18844 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18845 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18846 }
18847 return SDValue();
18848}
18849
18850/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18851SDValue
18853 SDValue Cmp = N->getOperand(3);
18854 if (Cmp.getOpcode() != ARMISD::CMPZ)
18855 // Only looking at NE cases.
18856 return SDValue();
18857
18858 SDLoc dl(N);
18859 SDValue LHS = Cmp.getOperand(0);
18860 SDValue RHS = Cmp.getOperand(1);
18861 SDValue Chain = N->getOperand(0);
18862 SDValue BB = N->getOperand(1);
18863 SDValue ARMcc = N->getOperand(2);
18865
18866 // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18867 // -> (brcond Chain BB CC Flags)
18868 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18869 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18870 LHS->getOperand(0)->hasOneUse() &&
18871 isNullConstant(LHS->getOperand(0)->getOperand(0)) &&
18872 isOneConstant(LHS->getOperand(0)->getOperand(1)) &&
18873 isOneConstant(LHS->getOperand(1)) && isNullConstant(RHS)) {
18874 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, BB,
18875 LHS->getOperand(0)->getOperand(2),
18876 LHS->getOperand(0)->getOperand(3));
18877 }
18878
18879 return SDValue();
18880}
18881
18882/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18883SDValue
18885 SDLoc dl(N);
18886 EVT VT = N->getValueType(0);
18887 SDValue FalseVal = N->getOperand(0);
18888 SDValue TrueVal = N->getOperand(1);
18889 SDValue ARMcc = N->getOperand(2);
18890 SDValue Cmp = N->getOperand(3);
18891
18892 // Try to form CSINV etc.
18893 unsigned Opcode;
18894 bool InvertCond;
18895 if (SDValue CSetOp =
18896 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
18897 if (InvertCond) {
18898 ARMCC::CondCodes CondCode =
18899 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
18900 CondCode = ARMCC::getOppositeCondition(CondCode);
18901 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
18902 }
18903 return DAG.getNode(Opcode, dl, VT, CSetOp, CSetOp, ARMcc, Cmp);
18904 }
18905
18906 if (Cmp.getOpcode() != ARMISD::CMPZ)
18907 // Only looking at EQ and NE cases.
18908 return SDValue();
18909
18910 SDValue LHS = Cmp.getOperand(0);
18911 SDValue RHS = Cmp.getOperand(1);
18913
18914 // BFI is only available on V6T2+.
18915 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18917 if (R)
18918 return R;
18919 }
18920
18921 // Simplify
18922 // mov r1, r0
18923 // cmp r1, x
18924 // mov r0, y
18925 // moveq r0, x
18926 // to
18927 // cmp r0, x
18928 // movne r0, y
18929 //
18930 // mov r1, r0
18931 // cmp r1, x
18932 // mov r0, x
18933 // movne r0, y
18934 // to
18935 // cmp r0, x
18936 // movne r0, y
18937 /// FIXME: Turn this into a target neutral optimization?
18938 SDValue Res;
18939 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18940 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, Cmp);
18941 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18942 SDValue ARMcc;
18943 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
18944 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, NewCmp);
18945 }
18946
18947 // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
18948 // -> (cmov F T CC Flags)
18949 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18950 isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
18951 isNullConstant(RHS)) {
18952 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
18953 LHS->getOperand(2), LHS->getOperand(3));
18954 }
18955
18956 if (!VT.isInteger())
18957 return SDValue();
18958
18959 // Fold away an unnecessary CMPZ/CMOV
18960 // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18961 // if C1==EQ -> CMOV A, B, C2, D
18962 // if C1==NE -> CMOV A, B, NOT(C2), D
18963 if (N->getConstantOperandVal(2) == ARMCC::EQ ||
18964 N->getConstantOperandVal(2) == ARMCC::NE) {
18966 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
18967 if (N->getConstantOperandVal(2) == ARMCC::NE)
18969 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
18970 N->getOperand(1),
18971 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
18972 }
18973 }
18974
18975 // Materialize a boolean comparison for integers so we can avoid branching.
18976 if (isNullConstant(FalseVal)) {
18977 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
18978 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18979 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18980 // right 5 bits will make that 32 be 1, otherwise it will be 0.
18981 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18982 SDValue Value;
18983 if (VT == MVT::i32 && Subtarget->isThumb2() && isNullConstant(RHS) &&
18984 Cmp.hasOneUse())
18985 Value = getShiftedLowMaskZeroTest(LHS, DAG, dl);
18986 if (!Value)
18987 Value = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18988 Res =
18989 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Value),
18990 DAG.getConstant(5, dl, MVT::i32));
18991 } else {
18992 // CMOV 0, 1, ==, (CMPZ x, y) ->
18993 // (UADDO_CARRY (SUB x, y), t:0, t:1)
18994 // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18995 //
18996 // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18997 // x != y. In other words, a carry C == 1 when x == y, C == 0
18998 // otherwise.
18999 // The final UADDO_CARRY computes
19000 // x - y + (0 - (x - y)) + C == C
19001 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
19002 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19003 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
19004 // ISD::USUBO_CARRY returns a borrow but we want the carry here
19005 // actually.
19006 SDValue Carry =
19007 DAG.getNode(ISD::SUB, dl, MVT::i32,
19008 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
19009 Res = DAG.getNode(ISD::UADDO_CARRY, dl, VTs, Sub, Neg, Carry);
19010 }
19011 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
19012 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
19013 // This seems pointless but will allow us to combine it further below.
19014 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
19015 SDValue Sub =
19016 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
19017 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
19018 Sub.getValue(1));
19019 FalseVal = Sub;
19020 }
19021 } else if (isNullConstant(TrueVal)) {
19022 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
19023 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
19024 // This seems pointless but will allow us to combine it further below
19025 // Note that we change == for != as this is the dual for the case above.
19026 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
19027 SDValue Sub =
19028 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
19029 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
19030 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
19031 Sub.getValue(1));
19032 FalseVal = Sub;
19033 }
19034 }
19035
19036 // On Thumb1, the DAG above may be further combined if z is a power of 2
19037 // (z == 2 ^ K).
19038 // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
19039 // t1 = (USUBO (SUB x, y), 1)
19040 // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
19041 // Result = if K != 0 then (SHL t2:0, K) else t2:0
19042 //
19043 // This also handles the special case of comparing against zero; it's
19044 // essentially, the same pattern, except there's no SUBC:
19045 // CMOV x, z, !=, (CMPZ x, 0) ->
19046 // t1 = (USUBO x, 1)
19047 // t2 = (USUBO_CARRY x, t1:0, t1:1)
19048 // Result = if K != 0 then (SHL t2:0, K) else t2:0
19049 const APInt *TrueConst;
19050 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
19051 ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(0) == LHS &&
19052 FalseVal.getOperand(1) == RHS) ||
19053 (FalseVal == LHS && isNullConstant(RHS))) &&
19054 (TrueConst = isPowerOf2Constant(TrueVal))) {
19055 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19056 unsigned ShiftAmount = TrueConst->logBase2();
19057 if (ShiftAmount)
19058 TrueVal = DAG.getConstant(1, dl, VT);
19059 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
19060 Res = DAG.getNode(ISD::USUBO_CARRY, dl, VTs, FalseVal, Subc,
19061 Subc.getValue(1));
19062
19063 if (ShiftAmount)
19064 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
19065 DAG.getConstant(ShiftAmount, dl, MVT::i32));
19066 }
19067
19068 if (Res.getNode()) {
19070 // Capture demanded bits information that would be otherwise lost.
19071 if (Known.Zero == 0xfffffffe)
19072 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19073 DAG.getValueType(MVT::i1));
19074 else if (Known.Zero == 0xffffff00)
19075 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19076 DAG.getValueType(MVT::i8));
19077 else if (Known.Zero == 0xffff0000)
19078 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
19079 DAG.getValueType(MVT::i16));
19080 }
19081
19082 return Res;
19083}
19084
19087 const ARMSubtarget *ST) {
19088 SelectionDAG &DAG = DCI.DAG;
19089 SDValue Src = N->getOperand(0);
19090 EVT DstVT = N->getValueType(0);
19091
19092 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
19093 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
19094 EVT SrcVT = Src.getValueType();
19095 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
19096 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
19097 }
19098
19099 // We may have a bitcast of something that has already had this bitcast
19100 // combine performed on it, so skip past any VECTOR_REG_CASTs.
19101 if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
19102 Src.getOperand(0).getValueType().getScalarSizeInBits() <=
19103 Src.getValueType().getScalarSizeInBits())
19104 Src = Src.getOperand(0);
19105
19106 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
19107 // would be generated is at least the width of the element type.
19108 EVT SrcVT = Src.getValueType();
19109 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
19110 Src.getOpcode() == ARMISD::VMVNIMM ||
19111 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
19112 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
19113 DAG.getDataLayout().isBigEndian())
19114 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
19115
19116 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
19117 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
19118 return R;
19119
19120 return SDValue();
19121}
19122
19123// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
19124// node into stack operations after legalizeOps.
19127 SelectionDAG &DAG = DCI.DAG;
19128 EVT VT = N->getValueType(0);
19129 SDLoc DL(N);
19130
19131 // MVETrunc(Undef, Undef) -> Undef
19132 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
19133 return DAG.getUNDEF(VT);
19134
19135 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
19136 if (N->getNumOperands() == 2 &&
19137 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
19138 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
19139 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
19140 N->getOperand(0).getOperand(1),
19141 N->getOperand(1).getOperand(0),
19142 N->getOperand(1).getOperand(1));
19143
19144 // MVETrunc(shuffle, shuffle) -> VMOVN
19145 if (N->getNumOperands() == 2 &&
19146 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
19147 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
19148 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
19149 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
19150
19151 if (S0->getOperand(0) == S1->getOperand(0) &&
19152 S0->getOperand(1) == S1->getOperand(1)) {
19153 // Construct complete shuffle mask
19154 SmallVector<int, 8> Mask(S0->getMask());
19155 Mask.append(S1->getMask().begin(), S1->getMask().end());
19156
19157 if (isVMOVNTruncMask(Mask, VT, false))
19158 return DAG.getNode(
19159 ARMISD::VMOVN, DL, VT,
19160 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
19161 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
19162 DAG.getConstant(1, DL, MVT::i32));
19163 if (isVMOVNTruncMask(Mask, VT, true))
19164 return DAG.getNode(
19165 ARMISD::VMOVN, DL, VT,
19166 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
19167 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
19168 DAG.getConstant(1, DL, MVT::i32));
19169 }
19170 }
19171
19172 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
19173 // truncate to a buildvector to allow the generic optimisations to kick in.
19174 if (all_of(N->ops(), [](SDValue Op) {
19175 return Op.getOpcode() == ISD::BUILD_VECTOR ||
19176 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
19177 (Op.getOpcode() == ISD::BITCAST &&
19178 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
19179 })) {
19180 SmallVector<SDValue, 8> Extracts;
19181 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
19182 SDValue O = N->getOperand(Op);
19183 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
19184 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
19185 DAG.getConstant(i, DL, MVT::i32));
19186 Extracts.push_back(Ext);
19187 }
19188 }
19189 return DAG.getBuildVector(VT, DL, Extracts);
19190 }
19191
19192 // If we are late in the legalization process and nothing has optimised
19193 // the trunc to anything better, lower it to a stack store and reload,
19194 // performing the truncation whilst keeping the lanes in the correct order:
19195 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
19196 if (!DCI.isAfterLegalizeDAG())
19197 return SDValue();
19198
19199 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
19200 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
19201 int NumIns = N->getNumOperands();
19202 assert((NumIns == 2 || NumIns == 4) &&
19203 "Expected 2 or 4 inputs to an MVETrunc");
19204 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
19205 if (N->getNumOperands() == 4)
19206 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
19207
19208 SmallVector<SDValue> Chains;
19209 for (int I = 0; I < NumIns; I++) {
19210 SDValue Ptr = DAG.getNode(
19211 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
19212 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
19214 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
19215 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
19216 Ptr, MPI, StoreVT, Align(4));
19217 Chains.push_back(Ch);
19218 }
19219
19220 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19221 MachinePointerInfo MPI =
19223 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
19224}
19225
19226// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
19228 SelectionDAG &DAG) {
19229 SDValue N0 = N->getOperand(0);
19231 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
19232 return SDValue();
19233
19234 EVT FromVT = LD->getMemoryVT();
19235 EVT ToVT = N->getValueType(0);
19236 if (!ToVT.isVector())
19237 return SDValue();
19238 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
19239 EVT ToEltVT = ToVT.getVectorElementType();
19240 EVT FromEltVT = FromVT.getVectorElementType();
19241
19242 unsigned NumElements = 0;
19243 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
19244 NumElements = 4;
19245 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
19246 NumElements = 8;
19247 assert(NumElements != 0);
19248
19249 ISD::LoadExtType NewExtType =
19250 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
19251 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
19252 LD->getExtensionType() != ISD::EXTLOAD &&
19253 LD->getExtensionType() != NewExtType)
19254 return SDValue();
19255
19256 LLVMContext &C = *DAG.getContext();
19257 SDLoc DL(LD);
19258 // Details about the old load
19259 SDValue Ch = LD->getChain();
19260 SDValue BasePtr = LD->getBasePtr();
19261 Align Alignment = LD->getBaseAlign();
19262 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
19263 AAMDNodes AAInfo = LD->getAAInfo();
19264
19265 SDValue Offset = DAG.getPOISON(BasePtr.getValueType());
19266 EVT NewFromVT = EVT::getVectorVT(
19267 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
19268 EVT NewToVT = EVT::getVectorVT(
19269 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
19270
19273 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
19274 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
19275 SDValue NewPtr =
19276 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
19277
19278 SDValue NewLoad =
19279 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
19280 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
19281 Alignment, MMOFlags, AAInfo);
19282 Loads.push_back(NewLoad);
19283 Chains.push_back(SDValue(NewLoad.getNode(), 1));
19284 }
19285
19286 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19287 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
19288 return DAG.getMergeValues(Loads, DL);
19289}
19290
19291// Perform combines for MVEEXT. If it has not be optimized to anything better
19292// before lowering, it gets converted to stack store and extloads performing the
19293// extend whilst still keeping the same lane ordering.
19296 SelectionDAG &DAG = DCI.DAG;
19297 EVT VT = N->getValueType(0);
19298 SDLoc DL(N);
19299 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
19300 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
19301
19302 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
19303 *DAG.getContext());
19304 auto Extend = [&](SDValue V) {
19305 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
19306 return N->getOpcode() == ARMISD::MVESEXT
19307 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
19308 DAG.getValueType(ExtVT))
19309 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
19310 };
19311
19312 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
19313 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
19314 SDValue Ext = Extend(N->getOperand(0));
19315 return DAG.getMergeValues({Ext, Ext}, DL);
19316 }
19317
19318 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
19319 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
19320 ArrayRef<int> Mask = SVN->getMask();
19321 assert(Mask.size() == 2 * VT.getVectorNumElements());
19322 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
19323 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
19324 SDValue Op0 = SVN->getOperand(0);
19325 SDValue Op1 = SVN->getOperand(1);
19326
19327 auto CheckInregMask = [&](int Start, int Offset) {
19328 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
19329 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
19330 return false;
19331 return true;
19332 };
19333 SDValue V0 = SDValue(N, 0);
19334 SDValue V1 = SDValue(N, 1);
19335 if (CheckInregMask(0, 0))
19336 V0 = Extend(Op0);
19337 else if (CheckInregMask(0, 1))
19338 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
19339 else if (CheckInregMask(0, Mask.size()))
19340 V0 = Extend(Op1);
19341 else if (CheckInregMask(0, Mask.size() + 1))
19342 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
19343
19344 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
19345 V1 = Extend(Op1);
19346 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
19347 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
19348 else if (CheckInregMask(VT.getVectorNumElements(), 0))
19349 V1 = Extend(Op0);
19350 else if (CheckInregMask(VT.getVectorNumElements(), 1))
19351 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
19352
19353 if (V0.getNode() != N || V1.getNode() != N)
19354 return DAG.getMergeValues({V0, V1}, DL);
19355 }
19356
19357 // MVEEXT(load) -> extload, extload
19358 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
19360 return L;
19361
19362 if (!DCI.isAfterLegalizeDAG())
19363 return SDValue();
19364
19365 // Lower to a stack store and reload:
19366 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
19367 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
19368 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
19369 int NumOuts = N->getNumValues();
19370 assert((NumOuts == 2 || NumOuts == 4) &&
19371 "Expected 2 or 4 outputs to an MVEEXT");
19372 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
19373 *DAG.getContext());
19374 if (N->getNumOperands() == 4)
19375 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
19376
19377 MachinePointerInfo MPI =
19379 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
19380 StackPtr, MPI, Align(4));
19381
19383 for (int I = 0; I < NumOuts; I++) {
19384 SDValue Ptr = DAG.getNode(
19385 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
19386 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
19388 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
19389 SDValue Load = DAG.getExtLoad(
19390 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
19391 VT, Chain, Ptr, MPI, LoadVT, Align(4));
19392 Loads.push_back(Load);
19393 }
19394
19395 return DAG.getMergeValues(Loads, DL);
19396}
19397
19399 DAGCombinerInfo &DCI) const {
19400 switch (N->getOpcode()) {
19401 default: break;
19402 case ISD::SELECT_CC:
19403 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
19404 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
19405 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
19406 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
19407 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
19408 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
19409 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
19410 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
19411 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
19412 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
19413 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
19414 case ISD::BRCOND:
19415 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
19416 case ARMISD::ADDC:
19417 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
19418 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
19419 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
19420 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
19421 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
19422 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
19423 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
19424 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
19425 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
19428 return PerformExtractEltCombine(N, DCI, Subtarget);
19432 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
19433 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
19434 case ISD::FP_TO_SINT:
19435 case ISD::FP_TO_UINT:
19436 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
19437 case ISD::FADD:
19438 return PerformFADDCombine(N, DCI.DAG, Subtarget);
19439 case ISD::FMUL:
19440 return PerformVMulVCTPCombine(N, DCI.DAG, Subtarget);
19442 return PerformIntrinsicCombine(N, DCI);
19443 case ISD::SHL:
19444 case ISD::SRA:
19445 case ISD::SRL:
19446 return PerformShiftCombine(N, DCI, Subtarget);
19447 case ISD::SIGN_EXTEND:
19448 case ISD::ZERO_EXTEND:
19449 case ISD::ANY_EXTEND:
19450 return PerformExtendCombine(N, DCI.DAG, Subtarget);
19451 case ISD::FP_EXTEND:
19452 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
19453 case ISD::SMIN:
19454 case ISD::UMIN:
19455 case ISD::SMAX:
19456 case ISD::UMAX:
19457 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
19458 case ARMISD::CMOV:
19459 return PerformCMOVCombine(N, DCI.DAG);
19460 case ARMISD::BRCOND:
19461 return PerformBRCONDCombine(N, DCI.DAG);
19462 case ARMISD::CMPZ:
19463 return PerformCMPZCombine(N, DCI.DAG);
19464 case ARMISD::CSINC:
19465 case ARMISD::CSINV:
19466 case ARMISD::CSNEG:
19467 return PerformCSETCombine(N, DCI.DAG);
19468 case ISD::LOAD:
19469 return PerformLOADCombine(N, DCI, Subtarget);
19471 return PerformVECTOR_DEINTERLEAVECombine(N, DCI, Subtarget);
19472 case ARMISD::VLD1DUP:
19473 case ARMISD::VLD2DUP:
19474 case ARMISD::VLD3DUP:
19475 case ARMISD::VLD4DUP:
19476 return PerformVLDCombine(N, DCI);
19478 return PerformARMBUILD_VECTORCombine(N, DCI);
19479 case ISD::BITCAST:
19480 return PerformBITCASTCombine(N, DCI, Subtarget);
19481 case ARMISD::PREDICATE_CAST:
19482 return PerformPREDICATE_CASTCombine(N, DCI);
19483 case ARMISD::VECTOR_REG_CAST:
19484 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
19485 case ARMISD::MVETRUNC:
19486 return PerformMVETruncCombine(N, DCI);
19487 case ARMISD::MVESEXT:
19488 case ARMISD::MVEZEXT:
19489 return PerformMVEExtCombine(N, DCI);
19490 case ARMISD::VCMP:
19491 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
19492 case ISD::VECREDUCE_ADD:
19493 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
19494 case ARMISD::VADDVs:
19495 case ARMISD::VADDVu:
19496 case ARMISD::VADDLVs:
19497 case ARMISD::VADDLVu:
19498 case ARMISD::VADDLVAs:
19499 case ARMISD::VADDLVAu:
19500 case ARMISD::VMLAVs:
19501 case ARMISD::VMLAVu:
19502 case ARMISD::VMLALVs:
19503 case ARMISD::VMLALVu:
19504 case ARMISD::VMLALVAs:
19505 case ARMISD::VMLALVAu:
19506 return PerformReduceShuffleCombine(N, DCI.DAG);
19507 case ARMISD::VMOVN:
19508 return PerformVMOVNCombine(N, DCI);
19509 case ARMISD::VQMOVNs:
19510 case ARMISD::VQMOVNu:
19511 return PerformVQMOVNCombine(N, DCI);
19512 case ARMISD::VQDMULH:
19513 return PerformVQDMULHCombine(N, DCI);
19514 case ARMISD::ASRL:
19515 case ARMISD::LSRL:
19516 case ARMISD::LSLL:
19517 return PerformLongShiftCombine(N, DCI.DAG);
19518 case ARMISD::SMULWB: {
19519 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19520 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19521 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19522 return SDValue();
19523 break;
19524 }
19525 case ARMISD::SMULWT: {
19526 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19527 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19528 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19529 return SDValue();
19530 break;
19531 }
19532 case ARMISD::SMLALBB:
19533 case ARMISD::QADD16b:
19534 case ARMISD::QSUB16b:
19535 case ARMISD::UQADD16b:
19536 case ARMISD::UQSUB16b: {
19537 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19538 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19539 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19540 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19541 return SDValue();
19542 break;
19543 }
19544 case ARMISD::SMLALBT: {
19545 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
19546 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19547 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
19548 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19549 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
19550 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
19551 return SDValue();
19552 break;
19553 }
19554 case ARMISD::SMLALTB: {
19555 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
19556 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19557 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
19558 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19559 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
19560 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
19561 return SDValue();
19562 break;
19563 }
19564 case ARMISD::SMLALTT: {
19565 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19566 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19567 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19568 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19569 return SDValue();
19570 break;
19571 }
19572 case ARMISD::QADD8b:
19573 case ARMISD::QSUB8b:
19574 case ARMISD::UQADD8b:
19575 case ARMISD::UQSUB8b: {
19576 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19577 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
19578 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19579 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19580 return SDValue();
19581 break;
19582 }
19583 case ARMISD::VBSP:
19584 if (N->getOperand(1) == N->getOperand(2))
19585 return N->getOperand(1);
19586 return SDValue();
19589 switch (N->getConstantOperandVal(1)) {
19590 case Intrinsic::arm_neon_vld1:
19591 case Intrinsic::arm_neon_vld1x2:
19592 case Intrinsic::arm_neon_vld1x3:
19593 case Intrinsic::arm_neon_vld1x4:
19594 case Intrinsic::arm_neon_vld2:
19595 case Intrinsic::arm_neon_vld3:
19596 case Intrinsic::arm_neon_vld4:
19597 case Intrinsic::arm_neon_vld2lane:
19598 case Intrinsic::arm_neon_vld3lane:
19599 case Intrinsic::arm_neon_vld4lane:
19600 case Intrinsic::arm_neon_vld2dup:
19601 case Intrinsic::arm_neon_vld3dup:
19602 case Intrinsic::arm_neon_vld4dup:
19603 case Intrinsic::arm_neon_vst1:
19604 case Intrinsic::arm_neon_vst1x2:
19605 case Intrinsic::arm_neon_vst1x3:
19606 case Intrinsic::arm_neon_vst1x4:
19607 case Intrinsic::arm_neon_vst2:
19608 case Intrinsic::arm_neon_vst3:
19609 case Intrinsic::arm_neon_vst4:
19610 case Intrinsic::arm_neon_vst2lane:
19611 case Intrinsic::arm_neon_vst3lane:
19612 case Intrinsic::arm_neon_vst4lane:
19613 return PerformVLDCombine(N, DCI);
19614 case Intrinsic::arm_mve_vld2q:
19615 case Intrinsic::arm_mve_vld4q:
19616 case Intrinsic::arm_mve_vst2q:
19617 case Intrinsic::arm_mve_vst4q:
19618 return PerformMVEVLDCombine(N, DCI);
19619 default: break;
19620 }
19621 break;
19622 }
19623 return SDValue();
19624}
19625
19627 EVT VT) const {
19628 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19629}
19630
19632 Align Alignment,
19634 unsigned *Fast) const {
19635 // Depends what it gets converted into if the type is weird.
19636 if (!VT.isSimple())
19637 return false;
19638
19639 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19640 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19641 auto Ty = VT.getSimpleVT().SimpleTy;
19642
19643 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19644 // Unaligned access can use (for example) LRDB, LRDH, LDR
19645 if (AllowsUnaligned) {
19646 if (Fast)
19647 *Fast = Subtarget->hasV7Ops();
19648 return true;
19649 }
19650 }
19651
19652 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19653 // For any little-endian targets with neon, we can support unaligned ld/st
19654 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19655 // A big-endian target may also explicitly support unaligned accesses
19656 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19657 if (Fast)
19658 *Fast = 1;
19659 return true;
19660 }
19661 }
19662
19663 if (!Subtarget->hasMVEIntegerOps())
19664 return false;
19665
19666 // These are for predicates
19667 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19668 Ty == MVT::v2i1)) {
19669 if (Fast)
19670 *Fast = 1;
19671 return true;
19672 }
19673
19674 // These are for truncated stores/narrowing loads. They are fine so long as
19675 // the alignment is at least the size of the item being loaded
19676 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19677 Alignment >= VT.getScalarSizeInBits() / 8) {
19678 if (Fast)
19679 *Fast = true;
19680 return true;
19681 }
19682
19683 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19684 // VSTRW.U32 all store the vector register in exactly the same format, and
19685 // differ only in the range of their immediate offset field and the required
19686 // alignment. So there is always a store that can be used, regardless of
19687 // actual type.
19688 //
19689 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19690 // VREV64.8) pair and get the same effect. This will likely be better than
19691 // aligning the vector through the stack.
19692 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19693 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19694 Ty == MVT::v2f64) {
19695 if (Fast)
19696 *Fast = 1;
19697 return true;
19698 }
19699
19700 return false;
19701}
19702
19704 LLVMContext &Context, const MemOp &Op,
19705 const AttributeList &FuncAttributes) const {
19706 // See if we can use NEON instructions for this...
19707 if ((Op.isMemcpyOrMemmove() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19708 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
19709 unsigned Fast;
19710 if (Op.size() >= 16 &&
19711 (Op.isAligned(Align(16)) ||
19712 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
19714 Fast))) {
19715 return MVT::v2f64;
19716 } else if (Op.size() >= 8 &&
19717 (Op.isAligned(Align(8)) ||
19719 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
19720 Fast))) {
19721 return MVT::f64;
19722 }
19723 }
19724
19725 // Let the target-independent logic figure it out.
19726 return MVT::Other;
19727}
19728
19729// 64-bit integers are split into their high and low parts and held in two
19730// different registers, so the trunc is free since the low register can just
19731// be used.
19732bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19733 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19734 return false;
19735 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19736 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19737 return (SrcBits == 64 && DestBits == 32);
19738}
19739
19741 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19742 !DstVT.isInteger())
19743 return false;
19744 unsigned SrcBits = SrcVT.getSizeInBits();
19745 unsigned DestBits = DstVT.getSizeInBits();
19746 return (SrcBits == 64 && DestBits == 32);
19747}
19748
19750 if (Val.getOpcode() != ISD::LOAD)
19751 return false;
19752
19753 EVT VT1 = Val.getValueType();
19754 if (!VT1.isSimple() || !VT1.isInteger() ||
19755 !VT2.isSimple() || !VT2.isInteger())
19756 return false;
19757
19758 switch (VT1.getSimpleVT().SimpleTy) {
19759 default: break;
19760 case MVT::i1:
19761 case MVT::i8:
19762 case MVT::i16:
19763 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19764 return true;
19765 }
19766
19767 return false;
19768}
19769
19771 if (!VT.isSimple())
19772 return false;
19773
19774 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19775 // negate values directly (fneg is free). So, we don't want to let the DAG
19776 // combiner rewrite fneg into xors and some other instructions. For f16 and
19777 // FullFP16 argument passing, some bitcast nodes may be introduced,
19778 // triggering this DAG combine rewrite, so we are avoiding that with this.
19779 switch (VT.getSimpleVT().SimpleTy) {
19780 default: break;
19781 case MVT::f16:
19782 return Subtarget->hasFullFP16();
19783 }
19784
19785 return false;
19786}
19787
19789 if (!Subtarget->hasMVEIntegerOps())
19790 return nullptr;
19791 Type *SVIType = SVI->getType();
19792 Type *ScalarType = SVIType->getScalarType();
19793
19794 if (ScalarType->isFloatTy())
19795 return Type::getInt32Ty(SVIType->getContext());
19796 if (ScalarType->isHalfTy())
19797 return Type::getInt16Ty(SVIType->getContext());
19798 return nullptr;
19799}
19800
19802 EVT VT = ExtVal.getValueType();
19803
19804 if (!isTypeLegal(VT))
19805 return false;
19806
19807 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19808 if (Ld->isExpandingLoad())
19809 return false;
19810 }
19811
19812 if (Subtarget->hasMVEIntegerOps())
19813 return true;
19814
19815 // Don't create a loadext if we can fold the extension into a wide/long
19816 // instruction.
19817 // If there's more than one user instruction, the loadext is desirable no
19818 // matter what. There can be two uses by the same instruction.
19819 if (ExtVal->use_empty() ||
19820 !ExtVal->user_begin()->isOnlyUserOf(ExtVal.getNode()))
19821 return true;
19822
19823 SDNode *U = *ExtVal->user_begin();
19824 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19825 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19826 return false;
19827
19828 return true;
19829}
19830
19832 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19833 return false;
19834
19835 if (!isTypeLegal(EVT::getEVT(Ty1)))
19836 return false;
19837
19838 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19839
19840 // Assuming the caller doesn't have a zeroext or signext return parameter,
19841 // truncation all the way down to i1 is valid.
19842 return true;
19843}
19844
19845/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19846/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19847/// expanded to FMAs when this method returns true, otherwise fmuladd is
19848/// expanded to fmul + fadd.
19849///
19850/// ARM supports both fused and unfused multiply-add operations; we already
19851/// lower a pair of fmul and fadd to the latter so it's not clear that there
19852/// would be a gain or that the gain would be worthwhile enough to risk
19853/// correctness bugs.
19854///
19855/// For MVE, we set this to true as it helps simplify the need for some
19856/// patterns (and we don't have the non-fused floating point instruction).
19857bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19858 EVT VT) const {
19859 if (Subtarget->useSoftFloat())
19860 return false;
19861
19862 if (!VT.isSimple())
19863 return false;
19864
19865 switch (VT.getSimpleVT().SimpleTy) {
19866 case MVT::v4f32:
19867 case MVT::v8f16:
19868 return Subtarget->hasMVEFloatOps();
19869 case MVT::f16:
19870 return Subtarget->useFPVFMx16();
19871 case MVT::f32:
19872 return Subtarget->useFPVFMx();
19873 case MVT::f64:
19874 return Subtarget->useFPVFMx64();
19875 default:
19876 break;
19877 }
19878
19879 return false;
19880}
19881
19882static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19883 if (V < 0)
19884 return false;
19885
19886 unsigned Scale = 1;
19887 switch (VT.getSimpleVT().SimpleTy) {
19888 case MVT::i1:
19889 case MVT::i8:
19890 // Scale == 1;
19891 break;
19892 case MVT::i16:
19893 // Scale == 2;
19894 Scale = 2;
19895 break;
19896 default:
19897 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19898 // Scale == 4;
19899 Scale = 4;
19900 break;
19901 }
19902
19903 if ((V & (Scale - 1)) != 0)
19904 return false;
19905 return isUInt<5>(V / Scale);
19906}
19907
19908static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19909 const ARMSubtarget *Subtarget) {
19910 if (!VT.isInteger() && !VT.isFloatingPoint())
19911 return false;
19912 if (VT.isVector() && Subtarget->hasNEON())
19913 return false;
19914 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19915 !Subtarget->hasMVEFloatOps())
19916 return false;
19917
19918 bool IsNeg = false;
19919 if (V < 0) {
19920 IsNeg = true;
19921 V = -V;
19922 }
19923
19924 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
19925
19926 // MVE: size * imm7
19927 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19928 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19929 case MVT::i32:
19930 case MVT::f32:
19931 return isShiftedUInt<7,2>(V);
19932 case MVT::i16:
19933 case MVT::f16:
19934 return isShiftedUInt<7,1>(V);
19935 case MVT::i8:
19936 return isUInt<7>(V);
19937 default:
19938 return false;
19939 }
19940 }
19941
19942 // half VLDR: 2 * imm8
19943 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19944 return isShiftedUInt<8, 1>(V);
19945 // VLDR and LDRD: 4 * imm8
19946 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19947 return isShiftedUInt<8, 2>(V);
19948
19949 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19950 // + imm12 or - imm8
19951 if (IsNeg)
19952 return isUInt<8>(V);
19953 return isUInt<12>(V);
19954 }
19955
19956 return false;
19957}
19958
19959/// isLegalAddressImmediate - Return true if the integer value can be used
19960/// as the offset of the target addressing mode for load / store of the
19961/// given type.
19962static bool isLegalAddressImmediate(int64_t V, EVT VT,
19963 const ARMSubtarget *Subtarget) {
19964 if (V == 0)
19965 return true;
19966
19967 if (!VT.isSimple())
19968 return false;
19969
19970 if (Subtarget->isThumb1Only())
19971 return isLegalT1AddressImmediate(V, VT);
19972 else if (Subtarget->isThumb2())
19974
19975 // ARM mode.
19976 if (V < 0)
19977 V = - V;
19978 switch (VT.getSimpleVT().SimpleTy) {
19979 default: return false;
19980 case MVT::i1:
19981 case MVT::i8:
19982 case MVT::i32:
19983 // +- imm12
19984 return isUInt<12>(V);
19985 case MVT::i16:
19986 // +- imm8
19987 return isUInt<8>(V);
19988 case MVT::f32:
19989 case MVT::f64:
19990 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19991 return false;
19992 return isShiftedUInt<8, 2>(V);
19993 }
19994}
19995
19997 EVT VT) const {
19998 int Scale = AM.Scale;
19999 if (Scale < 0)
20000 return false;
20001
20002 switch (VT.getSimpleVT().SimpleTy) {
20003 default: return false;
20004 case MVT::i1:
20005 case MVT::i8:
20006 case MVT::i16:
20007 case MVT::i32:
20008 if (Scale == 1)
20009 return true;
20010 // r + r << imm
20011 Scale = Scale & ~1;
20012 return Scale == 2 || Scale == 4 || Scale == 8;
20013 case MVT::i64:
20014 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
20015 // version in Thumb mode.
20016 // r + r
20017 if (Scale == 1)
20018 return true;
20019 // r * 2 (this can be lowered to r + r).
20020 if (!AM.HasBaseReg && Scale == 2)
20021 return true;
20022 return false;
20023 case MVT::isVoid:
20024 // Note, we allow "void" uses (basically, uses that aren't loads or
20025 // stores), because arm allows folding a scale into many arithmetic
20026 // operations. This should be made more precise and revisited later.
20027
20028 // Allow r << imm, but the imm has to be a multiple of two.
20029 if (Scale & 1) return false;
20030 return isPowerOf2_32(Scale);
20031 }
20032}
20033
20035 EVT VT) const {
20036 const int Scale = AM.Scale;
20037
20038 // Negative scales are not supported in Thumb1.
20039 if (Scale < 0)
20040 return false;
20041
20042 // Thumb1 addressing modes do not support register scaling excepting the
20043 // following cases:
20044 // 1. Scale == 1 means no scaling.
20045 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
20046 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
20047}
20048
20049/// isLegalAddressingMode - Return true if the addressing mode represented
20050/// by AM is legal for this target, for a load/store of the specified type.
20052 const AddrMode &AM, Type *Ty,
20053 unsigned AS, Instruction *I) const {
20054 EVT VT = getValueType(DL, Ty, true);
20055 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
20056 return false;
20057
20058 // Can never fold addr of global into load/store.
20059 if (AM.BaseGV)
20060 return false;
20061
20062 switch (AM.Scale) {
20063 case 0: // no scale reg, must be "r+i" or "r", or "i".
20064 break;
20065 default:
20066 // ARM doesn't support any R+R*scale+imm addr modes.
20067 if (AM.BaseOffs)
20068 return false;
20069
20070 if (!VT.isSimple())
20071 return false;
20072
20073 if (Subtarget->isThumb1Only())
20074 return isLegalT1ScaledAddressingMode(AM, VT);
20075
20076 if (Subtarget->isThumb2())
20077 return isLegalT2ScaledAddressingMode(AM, VT);
20078
20079 int Scale = AM.Scale;
20080 switch (VT.getSimpleVT().SimpleTy) {
20081 default: return false;
20082 case MVT::i1:
20083 case MVT::i8:
20084 case MVT::i32:
20085 if (Scale < 0) Scale = -Scale;
20086 if (Scale == 1)
20087 return true;
20088 // r + r << imm
20089 return isPowerOf2_32(Scale & ~1);
20090 case MVT::i16:
20091 case MVT::i64:
20092 // r +/- r
20093 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
20094 return true;
20095 // r * 2 (this can be lowered to r + r).
20096 if (!AM.HasBaseReg && Scale == 2)
20097 return true;
20098 return false;
20099
20100 case MVT::isVoid:
20101 // Note, we allow "void" uses (basically, uses that aren't loads or
20102 // stores), because arm allows folding a scale into many arithmetic
20103 // operations. This should be made more precise and revisited later.
20104
20105 // Allow r << imm, but the imm has to be a multiple of two.
20106 if (Scale & 1) return false;
20107 return isPowerOf2_32(Scale);
20108 }
20109 }
20110 return true;
20111}
20112
20113/// isLegalICmpImmediate - Return true if the specified immediate is legal
20114/// icmp immediate, that is the target has icmp instructions which can compare
20115/// a register against the immediate without having to materialize the
20116/// immediate into a register.
20118 // Thumb2 and ARM modes can use cmn for negative immediates.
20119 if (!Subtarget->isThumb())
20120 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
20122 if (Subtarget->isThumb2())
20123 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
20125 // Thumb1 doesn't have cmn, and only 8-bit immediates.
20126 return Imm >= 0 && Imm <= 255;
20127}
20128
20129/// isLegalAddImmediate - Return true if the specified immediate is a legal add
20130/// *or sub* immediate, that is the target has add or sub instructions which can
20131/// add a register with the immediate without having to materialize the
20132/// immediate into a register.
20134 // Same encoding for add/sub, just flip the sign.
20135 uint64_t AbsImm = AbsoluteValue(Imm);
20136 if (!Subtarget->isThumb())
20137 return ARM_AM::getSOImmVal(AbsImm) != -1;
20138 if (Subtarget->isThumb2())
20139 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
20140 // Thumb1 only has 8-bit unsigned immediate.
20141 return AbsImm <= 255;
20142}
20143
20144// Return false to prevent folding
20145// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
20146// if the folding leads to worse code.
20148 SDValue ConstNode) const {
20149 // Let the DAGCombiner decide for vector types and large types.
20150 const EVT VT = AddNode.getValueType();
20151 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
20152 return true;
20153
20154 // It is worse if c0 is legal add immediate, while c1*c0 is not
20155 // and has to be composed by at least two instructions.
20156 const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
20157 const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
20158 const int64_t C0 = C0Node->getSExtValue();
20159 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
20161 return true;
20162 if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
20163 return false;
20164
20165 // Default to true and let the DAGCombiner decide.
20166 return true;
20167}
20168
20170 bool isSEXTLoad, SDValue &Base,
20171 SDValue &Offset, bool &isInc,
20172 SelectionDAG &DAG) {
20173 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20174 return false;
20175
20176 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
20177 // AddressingMode 3
20178 Base = Ptr->getOperand(0);
20180 int RHSC = (int)RHS->getZExtValue();
20181 if (RHSC < 0 && RHSC > -256) {
20182 assert(Ptr->getOpcode() == ISD::ADD);
20183 isInc = false;
20184 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20185 return true;
20186 }
20187 }
20188 isInc = (Ptr->getOpcode() == ISD::ADD);
20189 Offset = Ptr->getOperand(1);
20190 return true;
20191 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
20192 // AddressingMode 2
20194 int RHSC = (int)RHS->getZExtValue();
20195 if (RHSC < 0 && RHSC > -0x1000) {
20196 assert(Ptr->getOpcode() == ISD::ADD);
20197 isInc = false;
20198 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20199 Base = Ptr->getOperand(0);
20200 return true;
20201 }
20202 }
20203
20204 if (Ptr->getOpcode() == ISD::ADD) {
20205 isInc = true;
20206 ARM_AM::ShiftOpc ShOpcVal=
20208 if (ShOpcVal != ARM_AM::no_shift) {
20209 Base = Ptr->getOperand(1);
20210 Offset = Ptr->getOperand(0);
20211 } else {
20212 Base = Ptr->getOperand(0);
20213 Offset = Ptr->getOperand(1);
20214 }
20215 return true;
20216 }
20217
20218 isInc = (Ptr->getOpcode() == ISD::ADD);
20219 Base = Ptr->getOperand(0);
20220 Offset = Ptr->getOperand(1);
20221 return true;
20222 }
20223
20224 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
20225 return false;
20226}
20227
20229 bool isSEXTLoad, SDValue &Base,
20230 SDValue &Offset, bool &isInc,
20231 SelectionDAG &DAG) {
20232 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20233 return false;
20234
20235 Base = Ptr->getOperand(0);
20237 int RHSC = (int)RHS->getZExtValue();
20238 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
20239 assert(Ptr->getOpcode() == ISD::ADD);
20240 isInc = false;
20241 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20242 return true;
20243 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
20244 isInc = Ptr->getOpcode() == ISD::ADD;
20245 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
20246 return true;
20247 }
20248 }
20249
20250 return false;
20251}
20252
20253static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
20254 bool isSEXTLoad, bool IsMasked, bool isLE,
20256 bool &isInc, SelectionDAG &DAG) {
20257 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
20258 return false;
20259 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
20260 return false;
20261
20262 // We allow LE non-masked loads to change the type (for example use a vldrb.8
20263 // as opposed to a vldrw.32). This can allow extra addressing modes or
20264 // alignments for what is otherwise an equivalent instruction.
20265 bool CanChangeType = isLE && !IsMasked;
20266
20268 int RHSC = (int)RHS->getZExtValue();
20269
20270 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
20271 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
20272 assert(Ptr->getOpcode() == ISD::ADD);
20273 isInc = false;
20274 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
20275 return true;
20276 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
20277 isInc = Ptr->getOpcode() == ISD::ADD;
20278 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
20279 return true;
20280 }
20281 return false;
20282 };
20283
20284 // Try to find a matching instruction based on s/zext, Alignment, Offset and
20285 // (in BE/masked) type.
20286 Base = Ptr->getOperand(0);
20287 if (VT == MVT::v4i16) {
20288 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
20289 return true;
20290 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
20291 if (IsInRange(RHSC, 0x80, 1))
20292 return true;
20293 } else if (Alignment >= 4 &&
20294 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
20295 IsInRange(RHSC, 0x80, 4))
20296 return true;
20297 else if (Alignment >= 2 &&
20298 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
20299 IsInRange(RHSC, 0x80, 2))
20300 return true;
20301 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
20302 return true;
20303 return false;
20304}
20305
20306/// getPreIndexedAddressParts - returns true by value, base pointer and
20307/// offset pointer and addressing mode by reference if the node's address
20308/// can be legally represented as pre-indexed load / store address.
20309bool
20311 SDValue &Offset,
20313 SelectionDAG &DAG) const {
20314 if (Subtarget->isThumb1Only())
20315 return false;
20316
20317 EVT VT;
20318 SDValue Ptr;
20319 Align Alignment;
20320 unsigned AS = 0;
20321 bool isSEXTLoad = false;
20322 bool IsMasked = false;
20323 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
20324 Ptr = LD->getBasePtr();
20325 VT = LD->getMemoryVT();
20326 Alignment = LD->getAlign();
20327 AS = LD->getAddressSpace();
20328 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20329 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
20330 Ptr = ST->getBasePtr();
20331 VT = ST->getMemoryVT();
20332 Alignment = ST->getAlign();
20333 AS = ST->getAddressSpace();
20334 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
20335 Ptr = LD->getBasePtr();
20336 VT = LD->getMemoryVT();
20337 Alignment = LD->getAlign();
20338 AS = LD->getAddressSpace();
20339 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20340 IsMasked = true;
20342 Ptr = ST->getBasePtr();
20343 VT = ST->getMemoryVT();
20344 Alignment = ST->getAlign();
20345 AS = ST->getAddressSpace();
20346 IsMasked = true;
20347 } else
20348 return false;
20349
20350 unsigned Fast = 0;
20351 if (!allowsMisalignedMemoryAccesses(VT, AS, Alignment,
20353 // Only generate post-increment or pre-increment forms when a real
20354 // hardware instruction exists for them. Do not emit postinc/preinc
20355 // if the operation will end up as a libcall.
20356 return false;
20357 }
20358
20359 bool isInc;
20360 bool isLegal = false;
20361 if (VT.isVector())
20362 isLegal = Subtarget->hasMVEIntegerOps() &&
20364 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
20365 Subtarget->isLittle(), Base, Offset, isInc, DAG);
20366 else {
20367 if (Subtarget->isThumb2())
20368 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
20369 Offset, isInc, DAG);
20370 else
20371 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
20372 Offset, isInc, DAG);
20373 }
20374 if (!isLegal)
20375 return false;
20376
20377 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
20378 return true;
20379}
20380
20381/// getPostIndexedAddressParts - returns true by value, base pointer and
20382/// offset pointer and addressing mode by reference if this node can be
20383/// combined with a load / store to form a post-indexed load / store.
20385 SDValue &Base,
20386 SDValue &Offset,
20388 SelectionDAG &DAG) const {
20389 EVT VT;
20390 SDValue Ptr;
20391 Align Alignment;
20392 bool isSEXTLoad = false, isNonExt;
20393 bool IsMasked = false;
20394 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
20395 VT = LD->getMemoryVT();
20396 Ptr = LD->getBasePtr();
20397 Alignment = LD->getAlign();
20398 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20399 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
20400 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
20401 VT = ST->getMemoryVT();
20402 Ptr = ST->getBasePtr();
20403 Alignment = ST->getAlign();
20404 isNonExt = !ST->isTruncatingStore();
20405 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
20406 VT = LD->getMemoryVT();
20407 Ptr = LD->getBasePtr();
20408 Alignment = LD->getAlign();
20409 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20410 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
20411 IsMasked = true;
20413 VT = ST->getMemoryVT();
20414 Ptr = ST->getBasePtr();
20415 Alignment = ST->getAlign();
20416 isNonExt = !ST->isTruncatingStore();
20417 IsMasked = true;
20418 } else
20419 return false;
20420
20421 if (Subtarget->isThumb1Only()) {
20422 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
20423 // must be non-extending/truncating, i32, with an offset of 4.
20424 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
20425 if (Op->getOpcode() != ISD::ADD || !isNonExt)
20426 return false;
20427 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
20428 if (!RHS || RHS->getZExtValue() != 4)
20429 return false;
20430 if (Alignment < Align(4))
20431 return false;
20432
20433 Offset = Op->getOperand(1);
20434 Base = Op->getOperand(0);
20435 AM = ISD::POST_INC;
20436 return true;
20437 }
20438
20439 bool isInc;
20440 bool isLegal = false;
20441 if (VT.isVector())
20442 isLegal = Subtarget->hasMVEIntegerOps() &&
20443 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
20444 Subtarget->isLittle(), Base, Offset,
20445 isInc, DAG);
20446 else {
20447 if (Subtarget->isThumb2())
20448 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20449 isInc, DAG);
20450 else
20451 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20452 isInc, DAG);
20453 }
20454 if (!isLegal)
20455 return false;
20456
20457 if (Ptr != Base) {
20458 // Swap base ptr and offset to catch more post-index load / store when
20459 // it's legal. In Thumb2 mode, offset must be an immediate.
20460 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
20461 !Subtarget->isThumb2())
20463
20464 // Post-indexed load / store update the base pointer.
20465 if (Ptr != Base)
20466 return false;
20467 }
20468
20469 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
20470 return true;
20471}
20472
20475 const APInt &DemandedElts,
20476 const SelectionDAG &DAG,
20477 unsigned Depth) const {
20478 unsigned BitWidth = Known.getBitWidth();
20479 Known.resetAll();
20480 switch (Op.getOpcode()) {
20481 default: break;
20482 case ARMISD::ADDC:
20483 case ARMISD::ADDE:
20484 case ARMISD::SUBC:
20485 case ARMISD::SUBE:
20486 // Special cases when we convert a carry to a boolean.
20487 if (Op.getResNo() == 0) {
20488 SDValue LHS = Op.getOperand(0);
20489 SDValue RHS = Op.getOperand(1);
20490 // (ADDE 0, 0, C) will give us a single bit.
20491 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
20492 isNullConstant(RHS)) {
20494 return;
20495 }
20496 }
20497 break;
20498 case ARMISD::CMOV: {
20499 // Bits are known zero/one if known on the LHS and RHS.
20500 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
20501 if (Known.isUnknown())
20502 return;
20503
20504 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
20505 Known = Known.intersectWith(KnownRHS);
20506 return;
20507 }
20509 Intrinsic::ID IntID =
20510 static_cast<Intrinsic::ID>(Op->getConstantOperandVal(1));
20511 switch (IntID) {
20512 default: return;
20513 case Intrinsic::arm_ldaex:
20514 case Intrinsic::arm_ldrex: {
20515 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
20516 unsigned MemBits = VT.getScalarSizeInBits();
20517 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
20518 return;
20519 }
20520 }
20521 }
20522 case ARMISD::BFI: {
20523 // Conservatively, we can recurse down the first operand
20524 // and just mask out all affected bits.
20525 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20526
20527 // The operand to BFI is already a mask suitable for removing the bits it
20528 // sets.
20529 const APInt &Mask = Op.getConstantOperandAPInt(2);
20530 Known.Zero &= Mask;
20531 Known.One &= Mask;
20532 return;
20533 }
20534 case ARMISD::VGETLANEs:
20535 case ARMISD::VGETLANEu: {
20536 const SDValue &SrcSV = Op.getOperand(0);
20537 EVT VecVT = SrcSV.getValueType();
20538 assert(VecVT.isVector() && "VGETLANE expected a vector type");
20539 const unsigned NumSrcElts = VecVT.getVectorNumElements();
20540 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
20541 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20542 "VGETLANE index out of bounds");
20543 unsigned Idx = Pos->getZExtValue();
20544 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
20545 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
20546
20547 EVT VT = Op.getValueType();
20548 const unsigned DstSz = VT.getScalarSizeInBits();
20549 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20550 (void)SrcSz;
20551 assert(SrcSz == Known.getBitWidth());
20552 assert(DstSz > SrcSz);
20553 if (Op.getOpcode() == ARMISD::VGETLANEs)
20554 Known = Known.sext(DstSz);
20555 else {
20556 Known = Known.zext(DstSz);
20557 }
20558 assert(DstSz == Known.getBitWidth());
20559 break;
20560 }
20561 case ARMISD::VMOVrh: {
20562 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20563 assert(KnownOp.getBitWidth() == 16);
20564 Known = KnownOp.zext(32);
20565 break;
20566 }
20567 case ARMISD::CSINC:
20568 case ARMISD::CSINV:
20569 case ARMISD::CSNEG: {
20570 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20571 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
20572
20573 // The result is either:
20574 // CSINC: KnownOp0 or KnownOp1 + 1
20575 // CSINV: KnownOp0 or ~KnownOp1
20576 // CSNEG: KnownOp0 or KnownOp1 * -1
20577 if (Op.getOpcode() == ARMISD::CSINC)
20578 KnownOp1 =
20579 KnownBits::add(KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
20580 else if (Op.getOpcode() == ARMISD::CSINV)
20581 std::swap(KnownOp1.Zero, KnownOp1.One);
20582 else if (Op.getOpcode() == ARMISD::CSNEG)
20583 KnownOp1 = KnownBits::mul(KnownOp1,
20585
20586 Known = KnownOp0.intersectWith(KnownOp1);
20587 break;
20588 }
20589 case ARMISD::VORRIMM:
20590 case ARMISD::VBICIMM: {
20591 unsigned Encoded = Op.getConstantOperandVal(1);
20592 unsigned DecEltBits = 0;
20593 uint64_t DecodedVal = ARM_AM::decodeVMOVModImm(Encoded, DecEltBits);
20594
20595 unsigned EltBits = Op.getScalarValueSizeInBits();
20596 if (EltBits != DecEltBits) {
20597 // Be conservative: only update Known when EltBits == DecEltBits.
20598 // This is believed to always be true for VORRIMM/VBICIMM today, but if
20599 // that changes in the future, doing nothing here is safer than risking
20600 // subtle bugs.
20601 break;
20602 }
20603
20604 KnownBits KnownLHS = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20605 bool IsVORR = Op.getOpcode() == ARMISD::VORRIMM;
20606 APInt Imm(DecEltBits, DecodedVal);
20607
20608 Known.One = IsVORR ? (KnownLHS.One | Imm) : (KnownLHS.One & ~Imm);
20609 Known.Zero = IsVORR ? (KnownLHS.Zero & ~Imm) : (KnownLHS.Zero | Imm);
20610 break;
20611 }
20612 }
20613}
20614
20615static bool isLegalLogicalImmediate(unsigned Imm,
20616 const ARMSubtarget *Subtarget) {
20617 if (!Subtarget->isThumb())
20618 return ARM_AM::getSOImmVal(Imm) != -1;
20619 if (Subtarget->isThumb2())
20620<