LLVM 23.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"
66#include "llvm/IR/Attributes.h"
67#include "llvm/IR/CallingConv.h"
68#include "llvm/IR/Constant.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DebugLoc.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalValue.h"
77#include "llvm/IR/IRBuilder.h"
78#include "llvm/IR/InlineAsm.h"
79#include "llvm/IR/Instruction.h"
82#include "llvm/IR/Intrinsics.h"
83#include "llvm/IR/IntrinsicsARM.h"
84#include "llvm/IR/Module.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
88#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/MC/MCSchedule.h"
97#include "llvm/Support/Debug.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <cstdlib>
109#include <iterator>
110#include <limits>
111#include <optional>
112#include <tuple>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE "arm-isel"
119
120STATISTIC(NumTailCalls, "Number of tail calls");
121STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
122STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124STATISTIC(NumConstpoolPromoted,
125 "Number of constants with their storage promoted into constant pools");
126
127static cl::opt<bool>
128ARMInterworking("arm-interworking", cl::Hidden,
129 cl::desc("Enable / disable ARM interworking (for debugging only)"),
130 cl::init(true));
131
133 "arm-promote-constant", cl::Hidden,
134 cl::desc("Enable / disable promotion of unnamed_addr constants into "
135 "constant pools"),
136 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
138 "arm-promote-constant-max-size", cl::Hidden,
139 cl::desc("Maximum size of constant to promote into a constant pool"),
140 cl::init(64));
142 "arm-promote-constant-max-total", cl::Hidden,
143 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144 cl::init(128));
145
147MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149 cl::init(2));
150
152 "arm-max-base-updates-to-check", cl::Hidden,
153 cl::desc("Maximum number of base-updates to check generating postindex."),
154 cl::init(64));
155
156/// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
157constexpr MVT FlagsVT = MVT::i32;
158
159// The APCS parameter registers.
160static const MCPhysReg GPRArgRegs[] = {
161 ARM::R0, ARM::R1, ARM::R2, ARM::R3
162};
163
165 SelectionDAG &DAG, const SDLoc &DL) {
167 assert(Arg.ArgVT.bitsLT(MVT::i32));
168 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Arg.ArgVT, Value);
169 SDValue Ext =
171 MVT::i32, Trunc);
172 return Ext;
173}
174
175void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
176 if (VT != PromotedLdStVT) {
178 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
179
181 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
182 }
183
184 MVT ElemTy = VT.getVectorElementType();
185 if (ElemTy != MVT::f64)
189 if (ElemTy == MVT::i32) {
194 } else {
199 }
208 if (VT.isInteger()) {
212 }
213
214 // Neon does not support vector divide/remainder operations.
223
224 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
225 for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
227 setOperationAction(Opcode, VT, Legal);
228 if (!VT.isFloatingPoint())
229 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
230 setOperationAction(Opcode, VT, Legal);
231}
232
233void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
234 addRegisterClass(VT, &ARM::DPRRegClass);
235 addTypeForNEON(VT, MVT::f64);
236}
237
238void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
239 addRegisterClass(VT, &ARM::DPairRegClass);
240 addTypeForNEON(VT, MVT::v2f64);
241}
242
243void ARMTargetLowering::setAllExpand(MVT VT) {
244 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
246
247 // We support these really simple operations even on types where all
248 // the actual arithmetic has to be broken down into simpler
249 // operations or turned into library calls.
254}
255
256void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
257 LegalizeAction Action) {
258 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
259 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
260 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
261}
262
263void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
264 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
265
266 for (auto VT : IntTypes) {
267 addRegisterClass(VT, &ARM::MQPRRegClass);
298
299 // No native support for these.
309
310 // Vector reductions
320
321 if (!HasMVEFP) {
326 } else {
329 }
330
331 // Pre and Post inc are supported on loads and stores
332 for (unsigned im = (unsigned)ISD::PRE_INC;
333 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
338 }
339 }
340
341 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
342 for (auto VT : FloatTypes) {
343 addRegisterClass(VT, &ARM::MQPRRegClass);
344 if (!HasMVEFP)
345 setAllExpand(VT);
346
347 // These are legal or custom whether we have MVE.fp or not
360
361 // Pre and Post inc are supported on loads and stores
362 for (unsigned im = (unsigned)ISD::PRE_INC;
363 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
368 }
369
370 if (HasMVEFP) {
378 }
383
384 // No native support for these.
399 }
400 }
401
402 // Custom Expand smaller than legal vector reductions to prevent false zero
403 // items being added.
412
413 // We 'support' these types up to bitcast/load/store level, regardless of
414 // MVE integer-only / float support. Only doing FP data processing on the FP
415 // vector types is inhibited at integer-only level.
416 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
417 for (auto VT : LongTypes) {
418 addRegisterClass(VT, &ARM::MQPRRegClass);
419 setAllExpand(VT);
425 }
427
428 // We can do bitwise operations on v2i64 vectors
429 setOperationAction(ISD::AND, MVT::v2i64, Legal);
430 setOperationAction(ISD::OR, MVT::v2i64, Legal);
431 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
432
433 // It is legal to extload from v4i8 to v4i16 or v4i32.
434 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
435 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
436 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
437
438 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
444
445 // Some truncating stores are legal too.
446 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
447 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
448 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
449
450 // Pre and Post inc on these are legal, given the correct extends
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
458 }
459 }
460
461 // Predicate types
462 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
463 for (auto VT : pTypes) {
464 addRegisterClass(VT, &ARM::VCCRRegClass);
479
480 if (!HasMVEFP) {
485 }
486 }
490 setOperationAction(ISD::OR, MVT::v2i1, Expand);
496
505}
506
508 return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
509}
510
512 const ARMSubtarget &STI)
513 : TargetLowering(TM_, STI), Subtarget(&STI),
514 RegInfo(Subtarget->getRegisterInfo()),
515 Itins(Subtarget->getInstrItineraryData()) {
516 const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
517
520
521 const Triple &TT = TM.getTargetTriple();
522
523 if (Subtarget->isThumb1Only())
524 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
525 else
526 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
527
528 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
529 Subtarget->hasFPRegs()) {
530 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
531 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
532
533 if (!Subtarget->hasVFP2Base()) {
534 setAllExpand(MVT::f32);
535 } else {
538
541 setOperationAction(Op, MVT::f32, Legal);
542 }
543 if (!Subtarget->hasFP64()) {
544 setAllExpand(MVT::f64);
545 } else {
548 setOperationAction(Op, MVT::f64, Legal);
549
551 }
552 }
553
554 if (Subtarget->hasFullFP16()) {
557 setOperationAction(Op, MVT::f16, Legal);
558
559 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
562
567 }
568
569 if (Subtarget->hasBF16()) {
570 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
571 setAllExpand(MVT::bf16);
572 if (!Subtarget->hasFullFP16())
574 } else {
579 }
580
582 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
583 setTruncStoreAction(VT, InnerVT, Expand);
584 addAllExtLoads(VT, InnerVT, Expand);
585 }
586
589
591 }
592
593 if (!Subtarget->isThumb1Only() && !Subtarget->hasV8_1MMainlineOps())
595
596 if (!Subtarget->hasV8_1MMainlineOps())
598
599 if (!Subtarget->isThumb1Only())
601
604
607
608 if (Subtarget->hasMVEIntegerOps())
609 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
610
611 // Combine low-overhead loop intrinsics so that we can lower i1 types.
612 if (Subtarget->hasLOB()) {
614 }
615
616 if (Subtarget->hasNEON()) {
617 addDRTypeForNEON(MVT::v2f32);
618 addDRTypeForNEON(MVT::v8i8);
619 addDRTypeForNEON(MVT::v4i16);
620 addDRTypeForNEON(MVT::v2i32);
621 addDRTypeForNEON(MVT::v1i64);
622
623 addQRTypeForNEON(MVT::v4f32);
624 addQRTypeForNEON(MVT::v2f64);
625 addQRTypeForNEON(MVT::v16i8);
626 addQRTypeForNEON(MVT::v8i16);
627 addQRTypeForNEON(MVT::v4i32);
628 addQRTypeForNEON(MVT::v2i64);
629
630 if (Subtarget->hasFullFP16()) {
631 addQRTypeForNEON(MVT::v8f16);
632 addDRTypeForNEON(MVT::v4f16);
633 }
634
635 if (Subtarget->hasBF16()) {
636 addQRTypeForNEON(MVT::v8bf16);
637 addDRTypeForNEON(MVT::v4bf16);
638 }
639 }
640
641 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
642 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
643 // none of Neon, MVE or VFP supports any arithmetic operations on it.
644 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
645 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
646 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
647 // FIXME: Code duplication: FDIV and FREM are expanded always, see
648 // ARMTargetLowering::addTypeForNEON method for details.
649 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
650 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
651 // FIXME: Create unittest.
652 // In another words, find a way when "copysign" appears in DAG with vector
653 // operands.
655 // FIXME: Code duplication: SETCC has custom operation action, see
656 // ARMTargetLowering::addTypeForNEON method for details.
658 // FIXME: Create unittest for FNEG and for FABS.
659 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
660 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
662 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
663 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
664 setOperationAction(ISD::FTAN, MVT::v2f64, Expand);
665 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
666 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
669 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
678 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
679 }
680
681 if (Subtarget->hasNEON()) {
682 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
683 // supported for v4f32.
685 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
686 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
687 setOperationAction(ISD::FTAN, MVT::v4f32, Expand);
688 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
689 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
692 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
701
702 // Mark v2f32 intrinsics.
704 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
705 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
706 setOperationAction(ISD::FTAN, MVT::v2f32, Expand);
707 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
708 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
711 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
720
723 setOperationAction(Op, MVT::v4f16, Expand);
724 setOperationAction(Op, MVT::v8f16, Expand);
725 }
726
727 // Neon does not support some operations on v1i64 and v2i64 types.
728 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
729 // Custom handling for some quad-vector types to detect VMULL.
730 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
731 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
732 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
733 // Custom handling for some vector types to avoid expensive expansions
734 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
736 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
738 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
739 // a destination type that is wider than the source, and nor does
740 // it have a FP_TO_[SU]INT instruction with a narrower destination than
741 // source.
750
753
754 // NEON does not have single instruction CTPOP for vectors with element
755 // types wider than 8-bits. However, custom lowering can leverage the
756 // v8i8/v16i8 vcnt instruction.
763
764 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
765 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
766
767 // NEON does not have single instruction CTTZ for vectors.
769 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
770 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
771 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
772
773 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
774 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
775 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
776 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
777
782
787
791 }
792
793 // NEON only has FMA instructions as of VFP4.
794 if (!Subtarget->hasVFP4Base()) {
795 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
796 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
797 }
798
801
802 // It is legal to extload from v4i8 to v4i16 or v4i32.
803 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
804 MVT::v2i32}) {
809 }
810 }
811
812 for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
813 MVT::v4i32}) {
818 }
819 }
820
821 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
828 }
829 if (Subtarget->hasMVEIntegerOps()) {
832 ISD::SETCC});
833 }
834 if (Subtarget->hasMVEFloatOps()) {
836 }
837
838 if (!Subtarget->hasFP64()) {
839 // When targeting a floating-point unit with only single-precision
840 // operations, f64 is legal for the few double-precision instructions which
841 // are present However, no double-precision operations other than moves,
842 // loads and stores are provided by the hardware.
879 }
880
883
884 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
887 if (Subtarget->hasFullFP16()) {
890 }
891 } else {
893 }
894
895 if (!Subtarget->hasFP16()) {
898 } else {
901 }
902
903 computeRegisterProperties(Subtarget->getRegisterInfo());
904
905 // ARM does not have floating-point extending loads.
906 for (MVT VT : MVT::fp_valuetypes()) {
907 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
908 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
909 setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
910 }
911
912 // ... or truncating stores
913 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
914 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
915 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
916 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
917 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
918
919 // ARM does not have i1 sign extending load.
920 for (MVT VT : MVT::integer_valuetypes())
922
923 // ARM supports all 4 flavors of integer indexed load / store.
924 if (!Subtarget->isThumb1Only()) {
925 for (unsigned im = (unsigned)ISD::PRE_INC;
927 setIndexedLoadAction(im, MVT::i1, Legal);
928 setIndexedLoadAction(im, MVT::i8, Legal);
929 setIndexedLoadAction(im, MVT::i16, Legal);
930 setIndexedLoadAction(im, MVT::i32, Legal);
931 setIndexedStoreAction(im, MVT::i1, Legal);
932 setIndexedStoreAction(im, MVT::i8, Legal);
933 setIndexedStoreAction(im, MVT::i16, Legal);
934 setIndexedStoreAction(im, MVT::i32, Legal);
935 }
936 } else {
937 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
940 }
941
942 // Custom loads/stores to possible use __aeabi_uread/write*
943 if (TT.isTargetAEABI() && !Subtarget->allowsUnalignedMem()) {
948 }
949
954
955 if (!Subtarget->isThumb1Only()) {
958 }
959
964 if (Subtarget->hasDSP()) {
973 }
974 if (Subtarget->hasBaseDSP()) {
977 }
978
979 // i64 operation support.
982 if (Subtarget->isThumb1Only()) {
985 }
986 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
987 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
989
999
1000 // MVE lowers 64 bit shifts to lsll and lsrl
1001 // assuming that ISD::SRL and SRA of i64 are already marked custom
1002 if (Subtarget->hasMVEIntegerOps())
1004
1005 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1006 if (Subtarget->isThumb1Only()) {
1010 }
1011
1012 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1014
1015 // ARM does not have ROTL.
1020 }
1022 // TODO: These two should be set to LibCall, but this currently breaks
1023 // the Linux kernel build. See #101786.
1026 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1029 }
1030
1031 // @llvm.readcyclecounter requires the Performance Monitors extension.
1032 // Default to the 0 expansion on unsupported platforms.
1033 // FIXME: Technically there are older ARM CPUs that have
1034 // implementation-specific ways of obtaining this information.
1035 if (Subtarget->hasPerfMon())
1037
1038 // Only ARMv6 has BSWAP.
1039 if (!Subtarget->hasV6Ops())
1041
1042 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1043 : Subtarget->hasDivideInARMMode();
1044 if (!hasDivide) {
1045 // These are expanded into libcalls if the cpu doesn't have HW divider.
1048 }
1049
1050 if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1053
1056 }
1057
1060
1061 // Register based DivRem for AEABI (RTABI 4.2)
1062 if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1063 TT.isTargetMuslAEABI() || TT.isOSFuchsia() || TT.isOSWindows()) {
1066 HasStandaloneRem = false;
1067
1072 } else {
1075 }
1076
1081
1082 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1084
1085 // Use the default implementation.
1087 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1089 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1092
1093 if (TT.isOSWindows())
1095 else
1097
1098 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1099 // the default expansion.
1100 InsertFencesForAtomic = false;
1101 if (Subtarget->hasAnyDataBarrier() &&
1102 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1103 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1104 // to ldrex/strex loops already.
1106 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1108
1109 // On v8, we have particularly efficient implementations of atomic fences
1110 // if they can be combined with nearby atomic loads and stores.
1111 if (!Subtarget->hasAcquireRelease() ||
1112 getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1113 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1114 InsertFencesForAtomic = true;
1115 }
1116 } else {
1117 // If there's anything we can use as a barrier, go through custom lowering
1118 // for ATOMIC_FENCE.
1119 // If target has DMB in thumb, Fences can be inserted.
1120 if (Subtarget->hasDataBarrier())
1121 InsertFencesForAtomic = true;
1122
1124 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1125
1126 // Set them all for libcall, which will force libcalls.
1139 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1140 // Unordered/Monotonic case.
1141 if (!InsertFencesForAtomic) {
1144 }
1145 }
1146
1147 // Compute supported atomic widths.
1148 if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1149 // For targets where __sync_* routines are reliably available, we use them
1150 // if necessary.
1151 //
1152 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1153 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1154 //
1155 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1156 // such targets should provide __sync_* routines, which use the ARM mode
1157 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1158 // encoding; see ARMISD::MEMBARRIER_MCR.)
1160 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1161 Subtarget->hasForced32BitAtomics()) {
1162 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1164 } else {
1165 // We can't assume anything about other targets; just use libatomic
1166 // routines.
1168 }
1169
1171
1173
1174 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1175 if (!Subtarget->hasV6Ops()) {
1178 }
1180
1181 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1182 !Subtarget->isThumb1Only()) {
1183 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1184 // iff target supports vfp2.
1194 }
1195
1196 // We want to custom lower some of our intrinsics.
1201
1211 if (Subtarget->hasFullFP16()) {
1215 }
1216
1218
1221 if (Subtarget->hasFullFP16())
1225 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1226
1227 // We don't support sin/cos/fmod/copysign/pow
1236 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1237 !Subtarget->isThumb1Only()) {
1240 }
1243
1244 if (!Subtarget->hasVFP4Base()) {
1247 }
1248
1249 // Various VFP goodness
1250 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1251 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1252 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1257 }
1258
1259 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1260 if (!Subtarget->hasFP16()) {
1265 }
1266
1267 // Strict floating-point comparisons need custom lowering.
1274 }
1275
1276 // FP-ARMv8 implements a lot of rounding-like FP operations.
1277 if (Subtarget->hasFPARMv8Base()) {
1278 for (auto Op :
1285 setOperationAction(Op, MVT::f32, Legal);
1286
1287 if (Subtarget->hasFP64())
1288 setOperationAction(Op, MVT::f64, Legal);
1289 }
1290
1291 if (Subtarget->hasNEON()) {
1296 }
1297 }
1298
1299 // FP16 often need to be promoted to call lib functions
1300 // clang-format off
1301 if (Subtarget->hasFullFP16()) {
1305
1306 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
1320 setOperationAction(Op, MVT::f16, Promote);
1321 }
1322
1323 // Round-to-integer need custom lowering for fp16, as Promote doesn't work
1324 // because the result type is integer.
1326 setOperationAction(Op, MVT::f16, Custom);
1327
1333 setOperationAction(Op, MVT::f16, Legal);
1334 }
1335 // clang-format on
1336 }
1337
1338 if (Subtarget->hasNEON()) {
1339 // vmin and vmax aren't available in a scalar form, so we can use
1340 // a NEON instruction with an undef lane instead.
1349
1350 if (Subtarget->hasV8Ops()) {
1355 setOperationAction(Op, MVT::v2f32, Legal);
1356 setOperationAction(Op, MVT::v4f32, Legal);
1357 }
1358 }
1359
1360 if (Subtarget->hasFullFP16()) {
1365
1370
1375 setOperationAction(Op, MVT::v4f16, Legal);
1376 setOperationAction(Op, MVT::v8f16, Legal);
1377 }
1378 }
1379 }
1380
1381 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
1382 // it, but it's just a wrapper around ldexp.
1383 if (TT.isOSWindows()) {
1385 if (isOperationExpand(Op, MVT::f32))
1386 setOperationAction(Op, MVT::f32, Promote);
1387 }
1388
1389 // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1390 // isn't legal.
1392 if (isOperationExpand(Op, MVT::f16))
1393 setOperationAction(Op, MVT::f16, Promote);
1394
1395 // We have target-specific dag combine patterns for the following nodes:
1396 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1399
1400 if (Subtarget->hasMVEIntegerOps())
1402
1403 if (Subtarget->hasV6Ops())
1405 if (Subtarget->isThumb1Only())
1407 // Attempt to lower smin/smax to ssat/usat
1408 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1409 Subtarget->isThumb2()) {
1411 }
1412
1414
1415 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1416 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1418 else
1420
1421 //// temporary - rewrite interface to use type
1424 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1426 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1428
1429 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1430 // are at least 4 bytes aligned.
1432
1433 // Prefer likely predicted branches to selects on out-of-order cores.
1434 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1435
1436 setPrefLoopAlignment(Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1438 Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1439
1440 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1441
1442 IsStrictFPEnabled = true;
1443}
1444
1446 return Subtarget->useSoftFloat();
1447}
1448
1450 return !Subtarget->isThumb1Only() && VT.getSizeInBits() <= 32;
1451}
1452
1453// FIXME: It might make sense to define the representative register class as the
1454// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1455// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1456// SPR's representative would be DPR_VFP2. This should work well if register
1457// pressure tracking were modified such that a register use would increment the
1458// pressure of the register class's representative and all of it's super
1459// classes' representatives transitively. We have not implemented this because
1460// of the difficulty prior to coalescing of modeling operand register classes
1461// due to the common occurrence of cross class copies and subregister insertions
1462// and extractions.
1463std::pair<const TargetRegisterClass *, uint8_t>
1465 MVT VT) const {
1466 const TargetRegisterClass *RRC = nullptr;
1467 uint8_t Cost = 1;
1468 switch (VT.SimpleTy) {
1469 default:
1471 // Use DPR as representative register class for all floating point
1472 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1473 // the cost is 1 for both f32 and f64.
1474 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1475 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1476 RRC = &ARM::DPRRegClass;
1477 // When NEON is used for SP, only half of the register file is available
1478 // because operations that define both SP and DP results will be constrained
1479 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1480 // coalescing by double-counting the SP regs. See the FIXME above.
1481 if (Subtarget->useNEONForSinglePrecisionFP())
1482 Cost = 2;
1483 break;
1484 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1485 case MVT::v4f32: case MVT::v2f64:
1486 RRC = &ARM::DPRRegClass;
1487 Cost = 2;
1488 break;
1489 case MVT::v4i64:
1490 RRC = &ARM::DPRRegClass;
1491 Cost = 4;
1492 break;
1493 case MVT::v8i64:
1494 RRC = &ARM::DPRRegClass;
1495 Cost = 8;
1496 break;
1497 }
1498 return std::make_pair(RRC, Cost);
1499}
1500
1502 EVT VT) const {
1503 if (!VT.isVector())
1504 return getPointerTy(DL);
1505
1506 // MVE has a predicate register.
1507 if (Subtarget->hasMVEIntegerOps())
1508 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1509
1511}
1512
1513/// getRegClassFor - Return the register class that should be used for the
1514/// specified value type.
1515const TargetRegisterClass *
1516ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1517 (void)isDivergent;
1518 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1519 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1520 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1521 // MVE Q registers.
1522 if (Subtarget->hasNEON()) {
1523 if (VT == MVT::v4i64)
1524 return &ARM::QQPRRegClass;
1525 if (VT == MVT::v8i64)
1526 return &ARM::QQQQPRRegClass;
1527 }
1528 if (Subtarget->hasMVEIntegerOps()) {
1529 if (VT == MVT::v4i64)
1530 return &ARM::MQQPRRegClass;
1531 if (VT == MVT::v8i64)
1532 return &ARM::MQQQQPRRegClass;
1533 }
1535}
1536
1537// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1538// source/dest is aligned and the copy size is large enough. We therefore want
1539// to align such objects passed to memory intrinsics.
1541 Align &PrefAlign) const {
1542 if (!isa<MemIntrinsic>(CI))
1543 return false;
1544 MinSize = 8;
1545 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1546 // cycle faster than 4-byte aligned LDM.
1547 PrefAlign =
1548 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1549 return true;
1550}
1551
1552// Create a fast isel object.
1554 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
1555 const LibcallLoweringInfo *libcallLowering) const {
1556 return ARM::createFastISel(funcInfo, libInfo, libcallLowering);
1557}
1558
1560 unsigned NumVals = N->getNumValues();
1561 if (!NumVals)
1562 return Sched::RegPressure;
1563
1564 for (unsigned i = 0; i != NumVals; ++i) {
1565 EVT VT = N->getValueType(i);
1566 if (VT == MVT::Glue || VT == MVT::Other)
1567 continue;
1568 if (VT.isFloatingPoint() || VT.isVector())
1569 return Sched::ILP;
1570 }
1571
1572 if (!N->isMachineOpcode())
1573 return Sched::RegPressure;
1574
1575 // Load are scheduled for latency even if there instruction itinerary
1576 // is not available.
1577 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1578 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1579
1580 if (MCID.getNumDefs() == 0)
1581 return Sched::RegPressure;
1582 if (!Itins->isEmpty() &&
1583 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1584 return Sched::ILP;
1585
1586 return Sched::RegPressure;
1587}
1588
1589//===----------------------------------------------------------------------===//
1590// Lowering Code
1591//===----------------------------------------------------------------------===//
1592
1593static bool isSRL16(const SDValue &Op) {
1594 if (Op.getOpcode() != ISD::SRL)
1595 return false;
1596 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1597 return Const->getZExtValue() == 16;
1598 return false;
1599}
1600
1601static bool isSRA16(const SDValue &Op) {
1602 if (Op.getOpcode() != ISD::SRA)
1603 return false;
1604 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1605 return Const->getZExtValue() == 16;
1606 return false;
1607}
1608
1609static bool isSHL16(const SDValue &Op) {
1610 if (Op.getOpcode() != ISD::SHL)
1611 return false;
1612 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1613 return Const->getZExtValue() == 16;
1614 return false;
1615}
1616
1617// Check for a signed 16-bit value. We special case SRA because it makes it
1618// more simple when also looking for SRAs that aren't sign extending a
1619// smaller value. Without the check, we'd need to take extra care with
1620// checking order for some operations.
1621static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1622 if (isSRA16(Op))
1623 return isSHL16(Op.getOperand(0));
1624 return DAG.ComputeNumSignBits(Op) == 17;
1625}
1626
1627/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1629 switch (CC) {
1630 default: llvm_unreachable("Unknown condition code!");
1631 case ISD::SETNE: return ARMCC::NE;
1632 case ISD::SETEQ: return ARMCC::EQ;
1633 case ISD::SETGT: return ARMCC::GT;
1634 case ISD::SETGE: return ARMCC::GE;
1635 case ISD::SETLT: return ARMCC::LT;
1636 case ISD::SETLE: return ARMCC::LE;
1637 case ISD::SETUGT: return ARMCC::HI;
1638 case ISD::SETUGE: return ARMCC::HS;
1639 case ISD::SETULT: return ARMCC::LO;
1640 case ISD::SETULE: return ARMCC::LS;
1641 }
1642}
1643
1644/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1646 ARMCC::CondCodes &CondCode2) {
1647 CondCode2 = ARMCC::AL;
1648 switch (CC) {
1649 default: llvm_unreachable("Unknown FP condition!");
1650 case ISD::SETEQ:
1651 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1652 case ISD::SETGT:
1653 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1654 case ISD::SETGE:
1655 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1656 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1657 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1658 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1659 case ISD::SETO: CondCode = ARMCC::VC; break;
1660 case ISD::SETUO: CondCode = ARMCC::VS; break;
1661 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1662 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1663 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1664 case ISD::SETLT:
1665 case ISD::SETULT: CondCode = ARMCC::LT; break;
1666 case ISD::SETLE:
1667 case ISD::SETULE: CondCode = ARMCC::LE; break;
1668 case ISD::SETNE:
1669 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1670 }
1671}
1672
1673//===----------------------------------------------------------------------===//
1674// Calling Convention Implementation
1675//===----------------------------------------------------------------------===//
1676
1677/// getEffectiveCallingConv - Get the effective calling convention, taking into
1678/// account presence of floating point hardware and calling convention
1679/// limitations, such as support for variadic functions.
1681ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1682 bool isVarArg) const {
1683 switch (CC) {
1684 default:
1685 report_fatal_error("Unsupported calling convention");
1688 case CallingConv::GHC:
1690 return CC;
1696 case CallingConv::Swift:
1699 case CallingConv::C:
1700 case CallingConv::Tail:
1701 if (!getTM().isAAPCS_ABI())
1702 return CallingConv::ARM_APCS;
1703 else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1704 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1705 !isVarArg)
1707 else
1709 case CallingConv::Fast:
1711 if (!getTM().isAAPCS_ABI()) {
1712 if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() && !isVarArg)
1713 return CallingConv::Fast;
1714 return CallingConv::ARM_APCS;
1715 } else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1716 !isVarArg)
1718 else
1720 }
1721}
1722
1724 bool isVarArg) const {
1725 return CCAssignFnForNode(CC, false, isVarArg);
1726}
1727
1729 bool isVarArg) const {
1730 return CCAssignFnForNode(CC, true, isVarArg);
1731}
1732
1733/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1734/// CallingConvention.
1735CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1736 bool Return,
1737 bool isVarArg) const {
1738 switch (getEffectiveCallingConv(CC, isVarArg)) {
1739 default:
1740 report_fatal_error("Unsupported calling convention");
1742 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1744 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1746 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1747 case CallingConv::Fast:
1748 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1749 case CallingConv::GHC:
1750 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1752 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1754 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1756 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1757 }
1758}
1759
1760SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
1761 MVT LocVT, MVT ValVT, SDValue Val) const {
1762 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
1763 Val);
1764 if (Subtarget->hasFullFP16()) {
1765 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
1766 } else {
1767 Val = DAG.getNode(ISD::TRUNCATE, dl,
1768 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1769 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
1770 }
1771 return Val;
1772}
1773
1774SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
1775 MVT LocVT, MVT ValVT,
1776 SDValue Val) const {
1777 if (Subtarget->hasFullFP16()) {
1778 Val = DAG.getNode(ARMISD::VMOVrh, dl,
1779 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1780 } else {
1781 Val = DAG.getNode(ISD::BITCAST, dl,
1782 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
1783 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
1784 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
1785 }
1786 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
1787}
1788
1789/// LowerCallResult - Lower the result values of a call into the
1790/// appropriate copies out of appropriate physical registers.
1791SDValue ARMTargetLowering::LowerCallResult(
1792 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1793 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1794 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1795 SDValue ThisVal, bool isCmseNSCall) const {
1796 // Assign locations to each value returned by this call.
1798 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1799 *DAG.getContext());
1800 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1801
1802 // Copy all of the result registers out of their specified physreg.
1803 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1804 CCValAssign VA = RVLocs[i];
1805
1806 // Pass 'this' value directly from the argument to return value, to avoid
1807 // reg unit interference
1808 if (i == 0 && isThisReturn) {
1809 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1810 "unexpected return calling convention register assignment");
1811 InVals.push_back(ThisVal);
1812 continue;
1813 }
1814
1815 SDValue Val;
1816 if (VA.needsCustom() &&
1817 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
1818 // Handle f64 or half of a v2f64.
1819 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1820 InGlue);
1821 Chain = Lo.getValue(1);
1822 InGlue = Lo.getValue(2);
1823 VA = RVLocs[++i]; // skip ahead to next loc
1824 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1825 InGlue);
1826 Chain = Hi.getValue(1);
1827 InGlue = Hi.getValue(2);
1828 if (!Subtarget->isLittle())
1829 std::swap (Lo, Hi);
1830 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1831
1832 if (VA.getLocVT() == MVT::v2f64) {
1833 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1834 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1835 DAG.getConstant(0, dl, MVT::i32));
1836
1837 VA = RVLocs[++i]; // skip ahead to next loc
1838 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1839 Chain = Lo.getValue(1);
1840 InGlue = Lo.getValue(2);
1841 VA = RVLocs[++i]; // skip ahead to next loc
1842 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
1843 Chain = Hi.getValue(1);
1844 InGlue = Hi.getValue(2);
1845 if (!Subtarget->isLittle())
1846 std::swap (Lo, Hi);
1847 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1848 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1849 DAG.getConstant(1, dl, MVT::i32));
1850 }
1851 } else {
1852 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1853 InGlue);
1854 Chain = Val.getValue(1);
1855 InGlue = Val.getValue(2);
1856 }
1857
1858 switch (VA.getLocInfo()) {
1859 default: llvm_unreachable("Unknown loc info!");
1860 case CCValAssign::Full: break;
1861 case CCValAssign::BCvt:
1862 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1863 break;
1864 }
1865
1866 // f16 arguments have their size extended to 4 bytes and passed as if they
1867 // had been copied to the LSBs of a 32-bit register.
1868 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
1869 if (VA.needsCustom() &&
1870 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
1871 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
1872
1873 // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
1874 // is less than 32 bits must be sign- or zero-extended after the call for
1875 // security reasons. Although the ABI mandates an extension done by the
1876 // callee, the latter cannot be trusted to follow the rules of the ABI.
1877 const ISD::InputArg &Arg = Ins[VA.getValNo()];
1878 if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
1879 VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
1880 Val = handleCMSEValue(Val, Arg, DAG, dl);
1881
1882 InVals.push_back(Val);
1883 }
1884
1885 return Chain;
1886}
1887
1888std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
1889 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
1890 bool IsTailCall, int SPDiff) const {
1891 SDValue DstAddr;
1892 MachinePointerInfo DstInfo;
1893 int32_t Offset = VA.getLocMemOffset();
1894 MachineFunction &MF = DAG.getMachineFunction();
1895
1896 if (IsTailCall) {
1897 Offset += SPDiff;
1898 auto PtrVT = getPointerTy(DAG.getDataLayout());
1899 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
1900 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
1901 DstAddr = DAG.getFrameIndex(FI, PtrVT);
1902 DstInfo =
1904 } else {
1905 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
1906 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1907 StackPtr, PtrOff);
1908 DstInfo =
1910 }
1911
1912 return std::make_pair(DstAddr, DstInfo);
1913}
1914
1915// Returns the type of copying which is required to set up a byval argument to
1916// a tail-called function. This isn't needed for non-tail calls, because they
1917// always need the equivalent of CopyOnce, but tail-calls sometimes need two to
1918// avoid clobbering another argument (CopyViaTemp), and sometimes can be
1919// optimised to zero copies when forwarding an argument from the caller's
1920// caller (NoCopy).
1921ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
1922 SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
1923 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1924 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1925
1926 // Globals are always safe to copy from.
1928 return CopyOnce;
1929
1930 // Can only analyse frame index nodes, conservatively assume we need a
1931 // temporary.
1932 auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Src);
1933 auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Dst);
1934 if (!SrcFrameIdxNode || !DstFrameIdxNode)
1935 return CopyViaTemp;
1936
1937 int SrcFI = SrcFrameIdxNode->getIndex();
1938 int DstFI = DstFrameIdxNode->getIndex();
1939 assert(MFI.isFixedObjectIndex(DstFI) &&
1940 "byval passed in non-fixed stack slot");
1941
1942 int64_t SrcOffset = MFI.getObjectOffset(SrcFI);
1943 int64_t DstOffset = MFI.getObjectOffset(DstFI);
1944
1945 // If the source is in the local frame, then the copy to the argument memory
1946 // is always valid.
1947 bool FixedSrc = MFI.isFixedObjectIndex(SrcFI);
1948 if (!FixedSrc ||
1949 (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
1950 return CopyOnce;
1951
1952 // In the case of byval arguments split between registers and the stack,
1953 // computeAddrForCallArg returns a FrameIndex which corresponds only to the
1954 // stack portion, but the Src SDValue will refer to the full value, including
1955 // the local stack memory that the register portion gets stored into. We only
1956 // need to compare them for equality, so normalise on the full value version.
1957 uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(DstFI);
1958 DstOffset -= RegSize;
1959
1960 // If the value is already in the correct location, then no copying is
1961 // needed. If not, then we need to copy via a temporary.
1962 if (SrcOffset == DstOffset)
1963 return NoCopy;
1964 else
1965 return CopyViaTemp;
1966}
1967
1968void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1969 SDValue Chain, SDValue &Arg,
1970 RegsToPassVector &RegsToPass,
1971 CCValAssign &VA, CCValAssign &NextVA,
1972 SDValue &StackPtr,
1973 SmallVectorImpl<SDValue> &MemOpChains,
1974 bool IsTailCall,
1975 int SPDiff) const {
1976 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1977 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1978 unsigned id = Subtarget->isLittle() ? 0 : 1;
1979 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1980
1981 if (NextVA.isRegLoc())
1982 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1983 else {
1984 assert(NextVA.isMemLoc());
1985 if (!StackPtr.getNode())
1986 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1988
1989 SDValue DstAddr;
1990 MachinePointerInfo DstInfo;
1991 std::tie(DstAddr, DstInfo) =
1992 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
1993 MemOpChains.push_back(
1994 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
1995 }
1996}
1997
1998static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
1999 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2001}
2002
2003/// LowerCall - Lowering a call into a callseq_start <-
2004/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2005/// nodes.
2006SDValue
2007ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2008 SmallVectorImpl<SDValue> &InVals) const {
2009 SelectionDAG &DAG = CLI.DAG;
2010 SDLoc &dl = CLI.DL;
2011 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2012 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2013 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2014 SDValue Chain = CLI.Chain;
2015 SDValue Callee = CLI.Callee;
2016 bool &isTailCall = CLI.IsTailCall;
2017 CallingConv::ID CallConv = CLI.CallConv;
2018 bool doesNotRet = CLI.DoesNotReturn;
2019 bool isVarArg = CLI.IsVarArg;
2020 const CallBase *CB = CLI.CB;
2021
2022 MachineFunction &MF = DAG.getMachineFunction();
2023 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2024 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2025 MachineFunction::CallSiteInfo CSInfo;
2026 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2027 bool isThisReturn = false;
2028 bool isCmseNSCall = false;
2029 bool isSibCall = false;
2030 bool PreferIndirect = false;
2031 bool GuardWithBTI = false;
2032
2033 // Analyze operands of the call, assigning locations to each operand.
2035 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2036 *DAG.getContext());
2037 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2038
2039 // Lower 'returns_twice' calls to a pseudo-instruction.
2040 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2041 !Subtarget->noBTIAtReturnTwice())
2042 GuardWithBTI = AFI->branchTargetEnforcement();
2043
2044 // Set type id for call site info.
2045 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
2046
2047 // Determine whether this is a non-secure function call.
2048 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2049 isCmseNSCall = true;
2050
2051 // Disable tail calls if they're not supported.
2052 if (!Subtarget->supportsTailCall())
2053 isTailCall = false;
2054
2055 // For both the non-secure calls and the returns from a CMSE entry function,
2056 // the function needs to do some extra work after the call, or before the
2057 // return, respectively, thus it cannot end with a tail call
2058 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2059 isTailCall = false;
2060
2061 if (isa<GlobalAddressSDNode>(Callee)) {
2062 // If we're optimizing for minimum size and the function is called three or
2063 // more times in this block, we can improve codesize by calling indirectly
2064 // as BLXr has a 16-bit encoding.
2065 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2066 if (CLI.CB) {
2067 auto *BB = CLI.CB->getParent();
2068 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2069 count_if(GV->users(), [&BB](const User *U) {
2070 return isa<Instruction>(U) &&
2071 cast<Instruction>(U)->getParent() == BB;
2072 }) > 2;
2073 }
2074 }
2075 if (isTailCall) {
2076 // Check if it's really possible to do a tail call.
2077 isTailCall =
2078 IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, PreferIndirect);
2079
2080 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2081 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2082 isSibCall = true;
2083
2084 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2085 // detected sibcalls.
2086 if (isTailCall)
2087 ++NumTailCalls;
2088 }
2089
2090 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2091 report_fatal_error("failed to perform tail call elimination on a call "
2092 "site marked musttail");
2093
2094 // Get a count of how many bytes are to be pushed on the stack.
2095 unsigned NumBytes = CCInfo.getStackSize();
2096
2097 // SPDiff is the byte offset of the call's argument area from the callee's.
2098 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2099 // by this amount for a tail call. In a sibling call it must be 0 because the
2100 // caller will deallocate the entire stack and the callee still expects its
2101 // arguments to begin at SP+0. Completely unused for non-tail calls.
2102 int SPDiff = 0;
2103
2104 if (isTailCall && !isSibCall) {
2105 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2106 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2107
2108 // Since callee will pop argument stack as a tail call, we must keep the
2109 // popped size 16-byte aligned.
2110 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2111 assert(StackAlign && "data layout string is missing stack alignment");
2112 NumBytes = alignTo(NumBytes, *StackAlign);
2113
2114 // SPDiff will be negative if this tail call requires more space than we
2115 // would automatically have in our incoming argument space. Positive if we
2116 // can actually shrink the stack.
2117 SPDiff = NumReusableBytes - NumBytes;
2118
2119 // If this call requires more stack than we have available from
2120 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2121 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2122 AFI->setArgRegsSaveSize(-SPDiff);
2123 }
2124
2125 if (isSibCall) {
2126 // For sibling tail calls, memory operands are available in our caller's stack.
2127 NumBytes = 0;
2128 } else {
2129 // Adjust the stack pointer for the new arguments...
2130 // These operations are automatically eliminated by the prolog/epilog pass
2131 Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2132 }
2133
2135 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2136
2137 RegsToPassVector RegsToPass;
2138 SmallVector<SDValue, 8> MemOpChains;
2139
2140 // If we are doing a tail-call, any byval arguments will be written to stack
2141 // space which was used for incoming arguments. If any the values being used
2142 // are incoming byval arguments to this function, then they might be
2143 // overwritten by the stores of the outgoing arguments. To avoid this, we
2144 // need to make a temporary copy of them in local stack space, then copy back
2145 // to the argument area.
2146 DenseMap<unsigned, SDValue> ByValTemporaries;
2147 SDValue ByValTempChain;
2148 if (isTailCall) {
2149 SmallVector<SDValue, 8> ByValCopyChains;
2150 for (const CCValAssign &VA : ArgLocs) {
2151 unsigned ArgIdx = VA.getValNo();
2152 SDValue Src = OutVals[ArgIdx];
2153 ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2154
2155 if (!Flags.isByVal())
2156 continue;
2157
2158 SDValue Dst;
2159 MachinePointerInfo DstInfo;
2160 std::tie(Dst, DstInfo) =
2161 computeAddrForCallArg(dl, DAG, VA, SDValue(), true, SPDiff);
2162 ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2163
2164 if (Copy == NoCopy) {
2165 // If the argument is already at the correct offset on the stack
2166 // (because we are forwarding a byval argument from our caller), we
2167 // don't need any copying.
2168 continue;
2169 } else if (Copy == CopyOnce) {
2170 // If the argument is in our local stack frame, no other argument
2171 // preparation can clobber it, so we can copy it to the final location
2172 // later.
2173 ByValTemporaries[ArgIdx] = Src;
2174 } else {
2175 assert(Copy == CopyViaTemp && "unexpected enum value");
2176 // If we might be copying this argument from the outgoing argument
2177 // stack area, we need to copy via a temporary in the local stack
2178 // frame.
2179 int TempFrameIdx = MFI.CreateStackObject(
2180 Flags.getByValSize(), Flags.getNonZeroByValAlign(), false);
2181 SDValue Temp =
2182 DAG.getFrameIndex(TempFrameIdx, getPointerTy(DAG.getDataLayout()));
2183
2184 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2185 SDValue AlignNode =
2186 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2187
2188 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2189 SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2190 ByValCopyChains.push_back(
2191 DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, Ops));
2192 ByValTemporaries[ArgIdx] = Temp;
2193 }
2194 }
2195 if (!ByValCopyChains.empty())
2196 ByValTempChain =
2197 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, ByValCopyChains);
2198 }
2199
2200 // During a tail call, stores to the argument area must happen after all of
2201 // the function's incoming arguments have been loaded because they may alias.
2202 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2203 // there's no point in doing so repeatedly so this tracks whether that's
2204 // happened yet.
2205 bool AfterFormalArgLoads = false;
2206
2207 // Walk the register/memloc assignments, inserting copies/loads. In the case
2208 // of tail call optimization, arguments are handled later.
2209 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2210 i != e;
2211 ++i, ++realArgIdx) {
2212 CCValAssign &VA = ArgLocs[i];
2213 SDValue Arg = OutVals[realArgIdx];
2214 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2215 bool isByVal = Flags.isByVal();
2216
2217 // Promote the value if needed.
2218 switch (VA.getLocInfo()) {
2219 default: llvm_unreachable("Unknown loc info!");
2220 case CCValAssign::Full: break;
2221 case CCValAssign::SExt:
2222 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2223 break;
2224 case CCValAssign::ZExt:
2225 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2226 break;
2227 case CCValAssign::AExt:
2228 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2229 break;
2230 case CCValAssign::BCvt:
2231 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2232 break;
2233 }
2234
2235 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2236 Chain = DAG.getStackArgumentTokenFactor(Chain);
2237 if (ByValTempChain) {
2238 // In case of large byval copies, re-using the stackframe for tail-calls
2239 // can lead to overwriting incoming arguments on the stack. Force
2240 // loading these stack arguments before the copy to avoid that.
2241 SmallVector<SDValue, 8> IncomingLoad;
2242 for (unsigned I = 0; I < OutVals.size(); ++I) {
2243 if (Outs[I].Flags.isByVal())
2244 continue;
2245
2246 SDValue OutVal = OutVals[I];
2247 LoadSDNode *OutLN = dyn_cast_or_null<LoadSDNode>(OutVal);
2248 if (!OutLN)
2249 continue;
2250
2251 FrameIndexSDNode *FIN =
2253 if (!FIN)
2254 continue;
2255
2256 if (!MFI.isFixedObjectIndex(FIN->getIndex()))
2257 continue;
2258
2259 for (const CCValAssign &VA : ArgLocs) {
2260 if (VA.isMemLoc())
2261 IncomingLoad.push_back(OutVal.getValue(1));
2262 }
2263 }
2264
2265 // Update the chain to force loads for potentially clobbered argument
2266 // loads to happen before the byval copy.
2267 if (!IncomingLoad.empty()) {
2268 IncomingLoad.push_back(Chain);
2269 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, IncomingLoad);
2270 }
2271
2272 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chain,
2273 ByValTempChain);
2274 }
2275 AfterFormalArgLoads = true;
2276 }
2277
2278 // f16 arguments have their size extended to 4 bytes and passed as if they
2279 // had been copied to the LSBs of a 32-bit register.
2280 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2281 if (VA.needsCustom() &&
2282 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2283 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2284 } else {
2285 // f16 arguments could have been extended prior to argument lowering.
2286 // Mask them arguments if this is a CMSE nonsecure call.
2287 auto ArgVT = Outs[realArgIdx].ArgVT;
2288 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2289 auto LocBits = VA.getLocVT().getSizeInBits();
2290 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2291 SDValue Mask =
2292 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2293 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2294 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2295 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2296 }
2297 }
2298
2299 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2300 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2301 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2302 DAG.getConstant(0, dl, MVT::i32));
2303 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2304 DAG.getConstant(1, dl, MVT::i32));
2305
2306 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2307 StackPtr, MemOpChains, isTailCall, SPDiff);
2308
2309 VA = ArgLocs[++i]; // skip ahead to next loc
2310 if (VA.isRegLoc()) {
2311 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2312 StackPtr, MemOpChains, isTailCall, SPDiff);
2313 } else {
2314 assert(VA.isMemLoc());
2315 SDValue DstAddr;
2316 MachinePointerInfo DstInfo;
2317 std::tie(DstAddr, DstInfo) =
2318 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2319 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2320 }
2321 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2322 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2323 StackPtr, MemOpChains, isTailCall, SPDiff);
2324 } else if (VA.isRegLoc()) {
2325 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2326 Outs[0].VT == MVT::i32) {
2327 assert(VA.getLocVT() == MVT::i32 &&
2328 "unexpected calling convention register assignment");
2329 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2330 "unexpected use of 'returned'");
2331 isThisReturn = true;
2332 }
2333 const TargetOptions &Options = DAG.getTarget().Options;
2334 if (Options.EmitCallSiteInfo)
2335 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
2336 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2337 } else if (isByVal) {
2338 assert(VA.isMemLoc());
2339 unsigned offset = 0;
2340
2341 // True if this byval aggregate will be split between registers
2342 // and memory.
2343 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2344 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2345
2346 SDValue ByValSrc;
2347 bool NeedsStackCopy;
2348 if (auto It = ByValTemporaries.find(realArgIdx);
2349 It != ByValTemporaries.end()) {
2350 ByValSrc = It->second;
2351 NeedsStackCopy = true;
2352 } else {
2353 ByValSrc = Arg;
2354 NeedsStackCopy = !isTailCall;
2355 }
2356
2357 // If part of the argument is in registers, load them.
2358 if (CurByValIdx < ByValArgsCount) {
2359 unsigned RegBegin, RegEnd;
2360 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2361
2362 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2363 unsigned int i, j;
2364 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2365 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2366 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, Const);
2367 SDValue Load =
2368 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2369 DAG.InferPtrAlign(AddArg));
2370 MemOpChains.push_back(Load.getValue(1));
2371 RegsToPass.push_back(std::make_pair(j, Load));
2372 }
2373
2374 // If parameter size outsides register area, "offset" value
2375 // helps us to calculate stack slot for remained part properly.
2376 offset = RegEnd - RegBegin;
2377
2378 CCInfo.nextInRegsParam();
2379 }
2380
2381 // If the memory part of the argument isn't already in the correct place
2382 // (which can happen with tail calls), copy it into the argument area.
2383 if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2384 auto PtrVT = getPointerTy(DAG.getDataLayout());
2385 SDValue Dst;
2386 MachinePointerInfo DstInfo;
2387 std::tie(Dst, DstInfo) =
2388 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2389 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2390 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, SrcOffset);
2391 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2392 MVT::i32);
2393 SDValue AlignNode =
2394 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2395
2396 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2397 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2398 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2399 Ops));
2400 }
2401 } else {
2402 assert(VA.isMemLoc());
2403 SDValue DstAddr;
2404 MachinePointerInfo DstInfo;
2405 std::tie(DstAddr, DstInfo) =
2406 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2407
2408 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2409 MemOpChains.push_back(Store);
2410 }
2411 }
2412
2413 if (!MemOpChains.empty())
2414 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2415
2416 // Build a sequence of copy-to-reg nodes chained together with token chain
2417 // and flag operands which copy the outgoing args into the appropriate regs.
2418 SDValue InGlue;
2419 for (const auto &[Reg, N] : RegsToPass) {
2420 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
2421 InGlue = Chain.getValue(1);
2422 }
2423
2424 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2425 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2426 // node so that legalize doesn't hack it.
2427 bool isDirect = false;
2428
2429 const TargetMachine &TM = getTargetMachine();
2430 const Triple &TT = TM.getTargetTriple();
2431 const GlobalValue *GVal = nullptr;
2432 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2433 GVal = G->getGlobal();
2434 bool isStub = !TM.shouldAssumeDSOLocal(GVal) && TT.isOSBinFormatMachO();
2435
2436 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2437 bool isLocalARMFunc = false;
2438 auto PtrVt = getPointerTy(DAG.getDataLayout());
2439
2440 if (Subtarget->genLongCalls()) {
2441 assert((!isPositionIndependent() || TT.isOSWindows()) &&
2442 "long-calls codegen is not position independent!");
2443 // Handle a global address or an external symbol. If it's not one of
2444 // those, the target's already in a register, so we don't need to do
2445 // anything extra.
2446 if (isa<GlobalAddressSDNode>(Callee)) {
2447 if (Subtarget->genExecuteOnly()) {
2448 if (Subtarget->useMovt())
2449 ++NumMovwMovt;
2450 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2451 DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2452 } else {
2453 // Create a constant pool entry for the callee address
2454 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2455 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2456 GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2457
2458 // Get the address of the callee into a register
2459 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2460 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2461 Callee = DAG.getLoad(
2462 PtrVt, dl, DAG.getEntryNode(), Addr,
2464 }
2465 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2466 const char *Sym = S->getSymbol();
2467
2468 if (Subtarget->genExecuteOnly()) {
2469 if (Subtarget->useMovt())
2470 ++NumMovwMovt;
2471 Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2472 DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2473 } else {
2474 // Create a constant pool entry for the callee address
2475 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2476 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2477 *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2478
2479 // Get the address of the callee into a register
2480 SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2481 Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2482 Callee = DAG.getLoad(
2483 PtrVt, dl, DAG.getEntryNode(), Addr,
2485 }
2486 }
2487 } else if (isa<GlobalAddressSDNode>(Callee)) {
2488 if (!PreferIndirect) {
2489 isDirect = true;
2490 bool isDef = GVal->isStrongDefinitionForLinker();
2491
2492 // ARM call to a local ARM function is predicable.
2493 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2494 // tBX takes a register source operand.
2495 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2496 assert(TT.isOSBinFormatMachO() && "WrapperPIC use on non-MachO?");
2497 Callee = DAG.getNode(
2498 ARMISD::WrapperPIC, dl, PtrVt,
2499 DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2500 Callee = DAG.getLoad(
2501 PtrVt, dl, DAG.getEntryNode(), Callee,
2505 } else if (Subtarget->isTargetCOFF()) {
2506 assert(Subtarget->isTargetWindows() &&
2507 "Windows is the only supported COFF target");
2508 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2509 if (GVal->hasDLLImportStorageClass())
2510 TargetFlags = ARMII::MO_DLLIMPORT;
2511 else if (!TM.shouldAssumeDSOLocal(GVal))
2512 TargetFlags = ARMII::MO_COFFSTUB;
2513 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2514 TargetFlags);
2515 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2516 Callee =
2517 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2518 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2520 } else {
2521 Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2522 }
2523 }
2524 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2525 isDirect = true;
2526 // tBX takes a register source operand.
2527 const char *Sym = S->getSymbol();
2528 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2529 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2530 ARMConstantPoolValue *CPV =
2532 ARMPCLabelIndex, 4);
2533 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2534 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2535 Callee = DAG.getLoad(
2536 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2538 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2539 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2540 } else {
2541 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2542 }
2543 }
2544
2545 if (isCmseNSCall) {
2546 assert(!isARMFunc && !isDirect &&
2547 "Cannot handle call to ARM function or direct call");
2548 if (NumBytes > 0) {
2549 DAG.getContext()->diagnose(
2550 DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2551 "call to non-secure function would require "
2552 "passing arguments on stack",
2553 dl.getDebugLoc()));
2554 }
2555 if (isStructRet) {
2556 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2558 "call to non-secure function would return value through pointer",
2559 dl.getDebugLoc()));
2560 }
2561 }
2562
2563 // FIXME: handle tail calls differently.
2564 unsigned CallOpc;
2565 if (Subtarget->isThumb()) {
2566 if (GuardWithBTI)
2567 CallOpc = ARMISD::t2CALL_BTI;
2568 else if (isCmseNSCall)
2569 CallOpc = ARMISD::tSECALL;
2570 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2571 CallOpc = ARMISD::CALL_NOLINK;
2572 else
2573 CallOpc = ARMISD::CALL;
2574 } else {
2575 if (!isDirect && !Subtarget->hasV5TOps())
2576 CallOpc = ARMISD::CALL_NOLINK;
2577 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2578 // Emit regular call when code size is the priority
2579 !Subtarget->hasMinSize())
2580 // "mov lr, pc; b _foo" to avoid confusing the RSP
2581 CallOpc = ARMISD::CALL_NOLINK;
2582 else
2583 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2584 }
2585
2586 // We don't usually want to end the call-sequence here because we would tidy
2587 // the frame up *after* the call, however in the ABI-changing tail-call case
2588 // we've carefully laid out the parameters so that when sp is reset they'll be
2589 // in the correct location.
2590 if (isTailCall && !isSibCall) {
2591 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2592 InGlue = Chain.getValue(1);
2593 }
2594
2595 std::vector<SDValue> Ops;
2596 Ops.push_back(Chain);
2597 Ops.push_back(Callee);
2598
2599 if (isTailCall) {
2600 Ops.push_back(DAG.getSignedTargetConstant(SPDiff, dl, MVT::i32));
2601 }
2602
2603 // Add argument registers to the end of the list so that they are known live
2604 // into the call.
2605 for (const auto &[Reg, N] : RegsToPass)
2606 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2607
2608 // Add a register mask operand representing the call-preserved registers.
2609 const uint32_t *Mask;
2610 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2611 if (isThisReturn) {
2612 // For 'this' returns, use the R0-preserving mask if applicable
2613 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2614 if (!Mask) {
2615 // Set isThisReturn to false if the calling convention is not one that
2616 // allows 'returned' to be modeled in this way, so LowerCallResult does
2617 // not try to pass 'this' straight through
2618 isThisReturn = false;
2619 Mask = ARI->getCallPreservedMask(MF, CallConv);
2620 }
2621 } else
2622 Mask = ARI->getCallPreservedMask(MF, CallConv);
2623
2624 assert(Mask && "Missing call preserved mask for calling convention");
2625 Ops.push_back(DAG.getRegisterMask(Mask));
2626
2627 if (InGlue.getNode())
2628 Ops.push_back(InGlue);
2629
2630 if (isTailCall) {
2632 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, MVT::Other, Ops);
2633 if (CLI.CFIType)
2634 Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2635 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2636 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2637 return Ret;
2638 }
2639
2640 // Returns a chain and a flag for retval copy to use.
2641 Chain = DAG.getNode(CallOpc, dl, {MVT::Other, MVT::Glue}, Ops);
2642 if (CLI.CFIType)
2643 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2644 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2645 InGlue = Chain.getValue(1);
2646 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2647
2648 // If we're guaranteeing tail-calls will be honoured, the callee must
2649 // pop its own argument stack on return. But this call is *not* a tail call so
2650 // we need to undo that after it returns to restore the status-quo.
2651 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2652 uint64_t CalleePopBytes =
2653 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1U;
2654
2655 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
2656 if (!Ins.empty())
2657 InGlue = Chain.getValue(1);
2658
2659 // Handle result values, copying them out of physregs into vregs that we
2660 // return.
2661 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2662 InVals, isThisReturn,
2663 isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
2664}
2665
2666/// HandleByVal - Every parameter *after* a byval parameter is passed
2667/// on the stack. Remember the next parameter register to allocate,
2668/// and then confiscate the rest of the parameter registers to insure
2669/// this.
2670void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2671 Align Alignment) const {
2672 // Byval (as with any stack) slots are always at least 4 byte aligned.
2673 Alignment = std::max(Alignment, Align(4));
2674
2675 MCRegister Reg = State->AllocateReg(GPRArgRegs);
2676 if (!Reg)
2677 return;
2678
2679 unsigned AlignInRegs = Alignment.value() / 4;
2680 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2681 for (unsigned i = 0; i < Waste; ++i)
2682 Reg = State->AllocateReg(GPRArgRegs);
2683
2684 if (!Reg)
2685 return;
2686
2687 unsigned Excess = 4 * (ARM::R4 - Reg);
2688
2689 // Special case when NSAA != SP and parameter size greater than size of
2690 // all remained GPR regs. In that case we can't split parameter, we must
2691 // send it to stack. We also must set NCRN to R4, so waste all
2692 // remained registers.
2693 const unsigned NSAAOffset = State->getStackSize();
2694 if (NSAAOffset != 0 && Size > Excess) {
2695 while (State->AllocateReg(GPRArgRegs))
2696 ;
2697 return;
2698 }
2699
2700 // First register for byval parameter is the first register that wasn't
2701 // allocated before this method call, so it would be "reg".
2702 // If parameter is small enough to be saved in range [reg, r4), then
2703 // the end (first after last) register would be reg + param-size-in-regs,
2704 // else parameter would be splitted between registers and stack,
2705 // end register would be r4 in this case.
2706 unsigned ByValRegBegin = Reg;
2707 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2708 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2709 // Note, first register is allocated in the beginning of function already,
2710 // allocate remained amount of registers we need.
2711 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2712 State->AllocateReg(GPRArgRegs);
2713 // A byval parameter that is split between registers and memory needs its
2714 // size truncated here.
2715 // In the case where the entire structure fits in registers, we set the
2716 // size in memory to zero.
2717 Size = std::max<int>(Size - Excess, 0);
2718}
2719
2720/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2721/// for tail call optimization. Targets which want to do tail call
2722/// optimization should implement this function. Note that this function also
2723/// processes musttail calls, so when this function returns false on a valid
2724/// musttail call, a fatal backend error occurs.
2725bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2727 SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
2728 CallingConv::ID CalleeCC = CLI.CallConv;
2729 SDValue Callee = CLI.Callee;
2730 bool isVarArg = CLI.IsVarArg;
2731 const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2732 const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2733 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2734 const SelectionDAG &DAG = CLI.DAG;
2735 MachineFunction &MF = DAG.getMachineFunction();
2736 const Function &CallerF = MF.getFunction();
2737 CallingConv::ID CallerCC = CallerF.getCallingConv();
2738
2739 assert(Subtarget->supportsTailCall());
2740
2741 // Indirect tail-calls require a register to hold the target address. That
2742 // register must be:
2743 // * Allocatable (i.e. r0-r7 if the target is Thumb1).
2744 // * Not callee-saved, so must be one of r0-r3 or r12.
2745 // * Not used to hold an argument to the tail-called function, which might be
2746 // in r0-r3.
2747 // * Not used to hold the return address authentication code, which is in r12
2748 // if enabled.
2749 // Sometimes, no register matches all of these conditions, so we can't do a
2750 // tail-call.
2751 if (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect) {
2752 SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
2753 ARM::R3};
2754 if (!(Subtarget->isThumb1Only() ||
2755 MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true)))
2756 AddressRegisters.insert(ARM::R12);
2757 for (const CCValAssign &AL : ArgLocs)
2758 if (AL.isRegLoc())
2759 AddressRegisters.erase(AL.getLocReg());
2760 if (AddressRegisters.empty()) {
2761 LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
2762 return false;
2763 }
2764 }
2765
2766 // Look for obvious safe cases to perform tail call optimization that do not
2767 // require ABI changes. This is what gcc calls sibcall.
2768
2769 // Exception-handling functions need a special set of instructions to indicate
2770 // a return to the hardware. Tail-calling another function would probably
2771 // break this.
2772 if (CallerF.hasFnAttribute("interrupt")) {
2773 LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
2774 return false;
2775 }
2776
2777 if (canGuaranteeTCO(CalleeCC,
2778 getTargetMachine().Options.GuaranteedTailCallOpt)) {
2779 LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
2780 << " (guaranteed tail-call CC)\n");
2781 return CalleeCC == CallerCC;
2782 }
2783
2784 // Also avoid sibcall optimization if either caller or callee uses struct
2785 // return semantics.
2786 bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2787 bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
2788 if (isCalleeStructRet != isCallerStructRet) {
2789 LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
2790 return false;
2791 }
2792
2793 // Externally-defined functions with weak linkage should not be
2794 // tail-called on ARM when the OS does not support dynamic
2795 // pre-emption of symbols, as the AAELF spec requires normal calls
2796 // to undefined weak functions to be replaced with a NOP or jump to the
2797 // next instruction. The behaviour of branch instructions in this
2798 // situation (as used for tail calls) is implementation-defined, so we
2799 // cannot rely on the linker replacing the tail call with a return.
2800 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2801 const GlobalValue *GV = G->getGlobal();
2802 const Triple &TT = getTargetMachine().getTargetTriple();
2803 if (GV->hasExternalWeakLinkage() &&
2804 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
2805 TT.isOSBinFormatMachO())) {
2806 LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
2807 return false;
2808 }
2809 }
2810
2811 // Check that the call results are passed in the same way.
2812 LLVMContext &C = *DAG.getContext();
2814 getEffectiveCallingConv(CalleeCC, isVarArg),
2815 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2816 CCAssignFnForReturn(CalleeCC, isVarArg),
2817 CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) {
2818 LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
2819 return false;
2820 }
2821 // The callee has to preserve all registers the caller needs to preserve.
2822 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2823 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2824 if (CalleeCC != CallerCC) {
2825 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2826 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) {
2827 LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
2828 return false;
2829 }
2830 }
2831
2832 // If Caller's vararg argument has been split between registers and stack, do
2833 // not perform tail call, since part of the argument is in caller's local
2834 // frame.
2835 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2836 if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
2837 LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
2838 return false;
2839 }
2840
2841 // If the callee takes no arguments then go on to check the results of the
2842 // call.
2843 const MachineRegisterInfo &MRI = MF.getRegInfo();
2844 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) {
2845 LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
2846 return false;
2847 }
2848
2849 // If the stack arguments for this call do not fit into our own save area then
2850 // the call cannot be made tail.
2851 if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
2852 return false;
2853
2854 LLVM_DEBUG(dbgs() << "true\n");
2855 return true;
2856}
2857
2858bool
2859ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2860 MachineFunction &MF, bool isVarArg,
2862 LLVMContext &Context, const Type *RetTy) const {
2864 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2865 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2866}
2867
2869 const SDLoc &DL, SelectionDAG &DAG) {
2870 const MachineFunction &MF = DAG.getMachineFunction();
2871 const Function &F = MF.getFunction();
2872
2873 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2874
2875 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2876 // version of the "preferred return address". These offsets affect the return
2877 // instruction if this is a return from PL1 without hypervisor extensions.
2878 // IRQ/FIQ: +4 "subs pc, lr, #4"
2879 // SWI: 0 "subs pc, lr, #0"
2880 // ABORT: +4 "subs pc, lr, #4"
2881 // UNDEF: +4/+2 "subs pc, lr, #0"
2882 // UNDEF varies depending on where the exception came from ARM or Thumb
2883 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2884
2885 int64_t LROffset;
2886 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2887 IntKind == "ABORT")
2888 LROffset = 4;
2889 else if (IntKind == "SWI" || IntKind == "UNDEF")
2890 LROffset = 0;
2891 else
2892 report_fatal_error("Unsupported interrupt attribute. If present, value "
2893 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2894
2895 RetOps.insert(RetOps.begin() + 1,
2896 DAG.getConstant(LROffset, DL, MVT::i32, false));
2897
2898 return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
2899}
2900
2901SDValue
2902ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2903 bool isVarArg,
2905 const SmallVectorImpl<SDValue> &OutVals,
2906 const SDLoc &dl, SelectionDAG &DAG) const {
2907 // CCValAssign - represent the assignment of the return value to a location.
2909
2910 // CCState - Info about the registers and stack slots.
2911 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2912 *DAG.getContext());
2913
2914 // Analyze outgoing return values.
2915 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2916
2917 SDValue Glue;
2919 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2920 bool isLittleEndian = Subtarget->isLittle();
2921
2922 MachineFunction &MF = DAG.getMachineFunction();
2923 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2924 AFI->setReturnRegsCount(RVLocs.size());
2925
2926 // Report error if cmse entry function returns structure through first ptr arg.
2927 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2928 // Note: using an empty SDLoc(), as the first line of the function is a
2929 // better place to report than the last line.
2930 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2932 "secure entry function would return value through pointer",
2933 SDLoc().getDebugLoc()));
2934 }
2935
2936 // Copy the result values into the output registers.
2937 for (unsigned i = 0, realRVLocIdx = 0;
2938 i != RVLocs.size();
2939 ++i, ++realRVLocIdx) {
2940 CCValAssign &VA = RVLocs[i];
2941 assert(VA.isRegLoc() && "Can only return in registers!");
2942
2943 SDValue Arg = OutVals[realRVLocIdx];
2944 bool ReturnF16 = false;
2945
2946 if (Subtarget->hasFullFP16() && getTM().isTargetHardFloat()) {
2947 // Half-precision return values can be returned like this:
2948 //
2949 // t11 f16 = fadd ...
2950 // t12: i16 = bitcast t11
2951 // t13: i32 = zero_extend t12
2952 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2953 //
2954 // to avoid code generation for bitcasts, we simply set Arg to the node
2955 // that produces the f16 value, t11 in this case.
2956 //
2957 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2958 SDValue ZE = Arg.getOperand(0);
2959 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2960 SDValue BC = ZE.getOperand(0);
2961 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2962 Arg = BC.getOperand(0);
2963 ReturnF16 = true;
2964 }
2965 }
2966 }
2967 }
2968
2969 switch (VA.getLocInfo()) {
2970 default: llvm_unreachable("Unknown loc info!");
2971 case CCValAssign::Full: break;
2972 case CCValAssign::BCvt:
2973 if (!ReturnF16)
2974 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2975 break;
2976 }
2977
2978 // Mask f16 arguments if this is a CMSE nonsecure entry.
2979 auto RetVT = Outs[realRVLocIdx].ArgVT;
2980 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
2981 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
2982 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2983 } else {
2984 auto LocBits = VA.getLocVT().getSizeInBits();
2985 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
2986 SDValue Mask =
2987 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2988 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2989 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2990 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2991 }
2992 }
2993
2994 if (VA.needsCustom() &&
2995 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
2996 if (VA.getLocVT() == MVT::v2f64) {
2997 // Extract the first half and return it in two registers.
2998 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2999 DAG.getConstant(0, dl, MVT::i32));
3000 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3001 DAG.getVTList(MVT::i32, MVT::i32), Half);
3002
3003 Chain =
3004 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3005 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3006 Glue = Chain.getValue(1);
3007 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3008 VA = RVLocs[++i]; // skip ahead to next loc
3009 Chain =
3010 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3011 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3012 Glue = Chain.getValue(1);
3013 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3014 VA = RVLocs[++i]; // skip ahead to next loc
3015
3016 // Extract the 2nd half and fall through to handle it as an f64 value.
3017 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3018 DAG.getConstant(1, dl, MVT::i32));
3019 }
3020 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3021 // available.
3022 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3023 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3024 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3025 fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3026 Glue = Chain.getValue(1);
3027 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3028 VA = RVLocs[++i]; // skip ahead to next loc
3029 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3030 fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3031 } else
3032 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3033
3034 // Guarantee that all emitted copies are
3035 // stuck together, avoiding something bad.
3036 Glue = Chain.getValue(1);
3037 RetOps.push_back(DAG.getRegister(
3038 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3039 }
3040 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3041 const MCPhysReg *I =
3042 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3043 if (I) {
3044 for (; *I; ++I) {
3045 if (ARM::GPRRegClass.contains(*I))
3046 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3047 else if (ARM::DPRRegClass.contains(*I))
3049 else
3050 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3051 }
3052 }
3053
3054 // Update chain and glue.
3055 RetOps[0] = Chain;
3056 if (Glue.getNode())
3057 RetOps.push_back(Glue);
3058
3059 // CPUs which aren't M-class use a special sequence to return from
3060 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3061 // though we use "subs pc, lr, #N").
3062 //
3063 // M-class CPUs actually use a normal return sequence with a special
3064 // (hardware-provided) value in LR, so the normal code path works.
3065 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3066 !Subtarget->isMClass()) {
3067 if (Subtarget->isThumb1Only())
3068 report_fatal_error("interrupt attribute is not supported in Thumb1");
3069 return LowerInterruptReturn(RetOps, dl, DAG);
3070 }
3071
3072 unsigned RetNode =
3073 AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE : ARMISD::RET_GLUE;
3074 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3075}
3076
3077bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3078 if (N->getNumValues() != 1)
3079 return false;
3080 if (!N->hasNUsesOfValue(1, 0))
3081 return false;
3082
3083 SDValue TCChain = Chain;
3084 SDNode *Copy = *N->user_begin();
3085 if (Copy->getOpcode() == ISD::CopyToReg) {
3086 // If the copy has a glue operand, we conservatively assume it isn't safe to
3087 // perform a tail call.
3088 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3089 return false;
3090 TCChain = Copy->getOperand(0);
3091 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3092 SDNode *VMov = Copy;
3093 // f64 returned in a pair of GPRs.
3094 SmallPtrSet<SDNode*, 2> Copies;
3095 for (SDNode *U : VMov->users()) {
3096 if (U->getOpcode() != ISD::CopyToReg)
3097 return false;
3098 Copies.insert(U);
3099 }
3100 if (Copies.size() > 2)
3101 return false;
3102
3103 for (SDNode *U : VMov->users()) {
3104 SDValue UseChain = U->getOperand(0);
3105 if (Copies.count(UseChain.getNode()))
3106 // Second CopyToReg
3107 Copy = U;
3108 else {
3109 // We are at the top of this chain.
3110 // If the copy has a glue operand, we conservatively assume it
3111 // isn't safe to perform a tail call.
3112 if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3113 return false;
3114 // First CopyToReg
3115 TCChain = UseChain;
3116 }
3117 }
3118 } else if (Copy->getOpcode() == ISD::BITCAST) {
3119 // f32 returned in a single GPR.
3120 if (!Copy->hasOneUse())
3121 return false;
3122 Copy = *Copy->user_begin();
3123 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3124 return false;
3125 // If the copy has a glue operand, we conservatively assume it isn't safe to
3126 // perform a tail call.
3127 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3128 return false;
3129 TCChain = Copy->getOperand(0);
3130 } else {
3131 return false;
3132 }
3133
3134 bool HasRet = false;
3135 for (const SDNode *U : Copy->users()) {
3136 if (U->getOpcode() != ARMISD::RET_GLUE &&
3137 U->getOpcode() != ARMISD::INTRET_GLUE)
3138 return false;
3139 HasRet = true;
3140 }
3141
3142 if (!HasRet)
3143 return false;
3144
3145 Chain = TCChain;
3146 return true;
3147}
3148
3149bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3150 if (!Subtarget->supportsTailCall())
3151 return false;
3152
3153 if (!CI->isTailCall())
3154 return false;
3155
3156 return true;
3157}
3158
3159// Trying to write a 64 bit value so need to split into two 32 bit values first,
3160// and pass the lower and high parts through.
3162 SDLoc DL(Op);
3163 SDValue WriteValue = Op->getOperand(2);
3164
3165 // This function is only supposed to be called for i64 type argument.
3166 assert(WriteValue.getValueType() == MVT::i64
3167 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3168
3169 SDValue Lo, Hi;
3170 std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3171 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3172 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3173}
3174
3175// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3176// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3177// one of the above mentioned nodes. It has to be wrapped because otherwise
3178// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3179// be used to form addressing mode. These wrapped nodes will be selected
3180// into MOVi.
3181SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3182 SelectionDAG &DAG) const {
3183 EVT PtrVT = Op.getValueType();
3184 // FIXME there is no actual debug info here
3185 SDLoc dl(Op);
3186 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3187 SDValue Res;
3188
3189 // When generating execute-only code Constant Pools must be promoted to the
3190 // global data section. It's a bit ugly that we can't share them across basic
3191 // blocks, but this way we guarantee that execute-only behaves correct with
3192 // position-independent addressing modes.
3193 if (Subtarget->genExecuteOnly()) {
3194 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3195 auto *T = CP->getType();
3196 auto C = const_cast<Constant*>(CP->getConstVal());
3197 auto M = DAG.getMachineFunction().getFunction().getParent();
3198 auto GV = new GlobalVariable(
3199 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3200 Twine(DAG.getDataLayout().getInternalSymbolPrefix()) + "CP" +
3201 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3202 Twine(AFI->createPICLabelUId()));
3203 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3204 return LowerGlobalAddress(GA, DAG);
3205 }
3206
3207 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3208 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3209 Align CPAlign = CP->getAlign();
3210 if (Subtarget->isThumb1Only())
3211 CPAlign = std::max(CPAlign, Align(4));
3213 Res =
3214 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3215 else
3216 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3217 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3218}
3219
3221 // If we don't have a 32-bit pc-relative branch instruction then the jump
3222 // table consists of block addresses. Usually this is inline, but for
3223 // execute-only it must be placed out-of-line.
3224 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3227}
3228
3229SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3230 SelectionDAG &DAG) const {
3233 unsigned ARMPCLabelIndex = 0;
3234 SDLoc DL(Op);
3235 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3236 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3237 SDValue CPAddr;
3238 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3239 if (!IsPositionIndependent) {
3240 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3241 } else {
3242 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3243 ARMPCLabelIndex = AFI->createPICLabelUId();
3245 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3246 ARMCP::CPBlockAddress, PCAdj);
3247 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3248 }
3249 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3250 SDValue Result = DAG.getLoad(
3251 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3253 if (!IsPositionIndependent)
3254 return Result;
3255 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3256 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3257}
3258
3259/// Convert a TLS address reference into the correct sequence of loads
3260/// and calls to compute the variable's address for Darwin, and return an
3261/// SDValue containing the final node.
3262
3263/// Darwin only has one TLS scheme which must be capable of dealing with the
3264/// fully general situation, in the worst case. This means:
3265/// + "extern __thread" declaration.
3266/// + Defined in a possibly unknown dynamic library.
3267///
3268/// The general system is that each __thread variable has a [3 x i32] descriptor
3269/// which contains information used by the runtime to calculate the address. The
3270/// only part of this the compiler needs to know about is the first word, which
3271/// contains a function pointer that must be called with the address of the
3272/// entire descriptor in "r0".
3273///
3274/// Since this descriptor may be in a different unit, in general access must
3275/// proceed along the usual ARM rules. A common sequence to produce is:
3276///
3277/// movw rT1, :lower16:_var$non_lazy_ptr
3278/// movt rT1, :upper16:_var$non_lazy_ptr
3279/// ldr r0, [rT1]
3280/// ldr rT2, [r0]
3281/// blx rT2
3282/// [...address now in r0...]
3283SDValue
3284ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3285 SelectionDAG &DAG) const {
3286 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3287 "This function expects a Darwin target");
3288 SDLoc DL(Op);
3289
3290 // First step is to get the address of the actua global symbol. This is where
3291 // the TLS descriptor lives.
3292 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3293
3294 // The first entry in the descriptor is a function pointer that we must call
3295 // to obtain the address of the variable.
3296 SDValue Chain = DAG.getEntryNode();
3297 SDValue FuncTLVGet = DAG.getLoad(
3298 MVT::i32, DL, Chain, DescAddr,
3302 Chain = FuncTLVGet.getValue(1);
3303
3304 MachineFunction &F = DAG.getMachineFunction();
3305 MachineFrameInfo &MFI = F.getFrameInfo();
3306 MFI.setAdjustsStack(true);
3307
3308 // TLS calls preserve all registers except those that absolutely must be
3309 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3310 // silly).
3311 auto TRI =
3313 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3314 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3315
3316 // Finally, we can make the call. This is just a degenerate version of a
3317 // normal AArch64 call node: r0 takes the address of the descriptor, and
3318 // returns the address of the variable in this thread.
3319 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3320 Chain =
3321 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3322 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3323 DAG.getRegisterMask(Mask), Chain.getValue(1));
3324 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3325}
3326
3327SDValue
3328ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3329 SelectionDAG &DAG) const {
3330 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3331 "Windows specific TLS lowering");
3332
3333 SDValue Chain = DAG.getEntryNode();
3334 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3335 SDLoc DL(Op);
3336
3337 // Load the current TEB (thread environment block)
3338 SDValue Ops[] = {Chain,
3339 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3340 DAG.getTargetConstant(15, DL, MVT::i32),
3341 DAG.getTargetConstant(0, DL, MVT::i32),
3342 DAG.getTargetConstant(13, DL, MVT::i32),
3343 DAG.getTargetConstant(0, DL, MVT::i32),
3344 DAG.getTargetConstant(2, DL, MVT::i32)};
3345 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3346 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3347
3348 SDValue TEB = CurrentTEB.getValue(0);
3349 Chain = CurrentTEB.getValue(1);
3350
3351 // Load the ThreadLocalStoragePointer from the TEB
3352 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3353 SDValue TLSArray =
3354 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3355 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3356
3357 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3358 // offset into the TLSArray.
3359
3360 // Load the TLS index from the C runtime
3361 SDValue TLSIndex =
3362 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3363 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3364 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3365
3366 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3367 DAG.getConstant(2, DL, MVT::i32));
3368 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3369 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3370 MachinePointerInfo());
3371
3372 // Get the offset of the start of the .tls section (section base)
3373 const auto *GA = cast<GlobalAddressSDNode>(Op);
3374 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3375 SDValue Offset = DAG.getLoad(
3376 PtrVT, DL, Chain,
3377 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3378 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3380
3381 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3382}
3383
3384// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3385SDValue
3386ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3387 SelectionDAG &DAG) const {
3388 SDLoc dl(GA);
3389 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3390 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3391 MachineFunction &MF = DAG.getMachineFunction();
3392 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3393 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3394 ARMConstantPoolValue *CPV =
3395 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3396 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3397 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3398 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3399 Argument = DAG.getLoad(
3400 PtrVT, dl, DAG.getEntryNode(), Argument,
3402 SDValue Chain = Argument.getValue(1);
3403
3404 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3405 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3406
3407 // call __tls_get_addr.
3409 Args.emplace_back(Argument, Type::getInt32Ty(*DAG.getContext()));
3410
3411 // FIXME: is there useful debug info available here?
3412 TargetLowering::CallLoweringInfo CLI(DAG);
3413 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3415 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3416
3417 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3418 return CallResult.first;
3419}
3420
3421// Lower ISD::GlobalTLSAddress using the "initial exec" or
3422// "local exec" model.
3423SDValue
3424ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3425 SelectionDAG &DAG,
3426 TLSModel::Model model) const {
3427 const GlobalValue *GV = GA->getGlobal();
3428 SDLoc dl(GA);
3430 SDValue Chain = DAG.getEntryNode();
3431 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3432 // Get the Thread Pointer
3433 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3434
3435 if (model == TLSModel::InitialExec) {
3436 MachineFunction &MF = DAG.getMachineFunction();
3437 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3438 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3439 // Initial exec model.
3440 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3441 ARMConstantPoolValue *CPV =
3442 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3444 true);
3445 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3446 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3447 Offset = DAG.getLoad(
3448 PtrVT, dl, Chain, Offset,
3450 Chain = Offset.getValue(1);
3451
3452 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3453 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3454
3455 Offset = DAG.getLoad(
3456 PtrVT, dl, Chain, Offset,
3458 } else {
3459 // local exec model
3460 assert(model == TLSModel::LocalExec);
3461 ARMConstantPoolValue *CPV =
3463 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3464 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3465 Offset = DAG.getLoad(
3466 PtrVT, dl, Chain, Offset,
3468 }
3469
3470 // The address of the thread local variable is the add of the thread
3471 // pointer with the offset of the variable.
3472 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3473}
3474
3475SDValue
3476ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3477 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3478 if (DAG.getTarget().useEmulatedTLS())
3479 return LowerToTLSEmulatedModel(GA, DAG);
3480
3481 const Triple &TT = getTargetMachine().getTargetTriple();
3482 if (TT.isOSDarwin())
3483 return LowerGlobalTLSAddressDarwin(Op, DAG);
3484
3485 if (TT.isOSWindows())
3486 return LowerGlobalTLSAddressWindows(Op, DAG);
3487
3488 // TODO: implement the "local dynamic" model
3489 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3491
3492 switch (model) {
3495 return LowerToTLSGeneralDynamicModel(GA, DAG);
3498 return LowerToTLSExecModels(GA, DAG, model);
3499 }
3500 llvm_unreachable("bogus TLS model");
3501}
3502
3503/// Return true if all users of V are within function F, looking through
3504/// ConstantExprs.
3505static bool allUsersAreInFunction(const Value *V, const Function *F) {
3506 SmallVector<const User*,4> Worklist(V->users());
3507 while (!Worklist.empty()) {
3508 auto *U = Worklist.pop_back_val();
3509 if (isa<ConstantExpr>(U)) {
3510 append_range(Worklist, U->users());
3511 continue;
3512 }
3513
3514 auto *I = dyn_cast<Instruction>(U);
3515 if (!I || I->getParent()->getParent() != F)
3516 return false;
3517 }
3518 return true;
3519}
3520
3522 const GlobalValue *GV, SelectionDAG &DAG,
3523 EVT PtrVT, const SDLoc &dl) {
3524 // If we're creating a pool entry for a constant global with unnamed address,
3525 // and the global is small enough, we can emit it inline into the constant pool
3526 // to save ourselves an indirection.
3527 //
3528 // This is a win if the constant is only used in one function (so it doesn't
3529 // need to be duplicated) or duplicating the constant wouldn't increase code
3530 // size (implying the constant is no larger than 4 bytes).
3531 const Function &F = DAG.getMachineFunction().getFunction();
3532
3533 // We rely on this decision to inline being idempotent and unrelated to the
3534 // use-site. We know that if we inline a variable at one use site, we'll
3535 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3536 // doesn't know about this optimization, so bail out if it's enabled else
3537 // we could decide to inline here (and thus never emit the GV) but require
3538 // the GV from fast-isel generated code.
3541 return SDValue();
3542
3543 auto *GVar = dyn_cast<GlobalVariable>(GV);
3544 if (!GVar || !GVar->hasInitializer() ||
3545 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3546 !GVar->hasLocalLinkage())
3547 return SDValue();
3548
3549 // If we inline a value that contains relocations, we move the relocations
3550 // from .data to .text. This is not allowed in position-independent code.
3551 auto *Init = GVar->getInitializer();
3552 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3553 Init->needsDynamicRelocation())
3554 return SDValue();
3555
3556 // The constant islands pass can only really deal with alignment requests
3557 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3558 // any type wanting greater alignment requirements than 4 bytes. We also
3559 // can only promote constants that are multiples of 4 bytes in size or
3560 // are paddable to a multiple of 4. Currently we only try and pad constants
3561 // that are strings for simplicity.
3562 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3563 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3564 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3565 unsigned RequiredPadding = 4 - (Size % 4);
3566 bool PaddingPossible =
3567 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3568 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3569 Size == 0)
3570 return SDValue();
3571
3572 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3574 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3575
3576 // We can't bloat the constant pool too much, else the ConstantIslands pass
3577 // may fail to converge. If we haven't promoted this global yet (it may have
3578 // multiple uses), and promoting it would increase the constant pool size (Sz
3579 // > 4), ensure we have space to do so up to MaxTotal.
3580 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3581 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3583 return SDValue();
3584
3585 // This is only valid if all users are in a single function; we can't clone
3586 // the constant in general. The LLVM IR unnamed_addr allows merging
3587 // constants, but not cloning them.
3588 //
3589 // We could potentially allow cloning if we could prove all uses of the
3590 // constant in the current function don't care about the address, like
3591 // printf format strings. But that isn't implemented for now.
3592 if (!allUsersAreInFunction(GVar, &F))
3593 return SDValue();
3594
3595 // We're going to inline this global. Pad it out if needed.
3596 if (RequiredPadding != 4) {
3597 StringRef S = CDAInit->getAsString();
3598
3600 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3601 while (RequiredPadding--)
3602 V.push_back(0);
3604 }
3605
3606 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3607 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3608 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3611 PaddedSize - 4);
3612 }
3613 ++NumConstpoolPromoted;
3614 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3615}
3616
3618 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3619 if (!(GV = GA->getAliaseeObject()))
3620 return false;
3621 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3622 return V->isConstant();
3623 return isa<Function>(GV);
3624}
3625
3626SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3627 SelectionDAG &DAG) const {
3628 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3629 default: llvm_unreachable("unknown object format");
3630 case Triple::COFF:
3631 return LowerGlobalAddressWindows(Op, DAG);
3632 case Triple::ELF:
3633 return LowerGlobalAddressELF(Op, DAG);
3634 case Triple::MachO:
3635 return LowerGlobalAddressDarwin(Op, DAG);
3636 }
3637}
3638
3639SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3640 SelectionDAG &DAG) const {
3641 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3642 SDLoc dl(Op);
3643 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3644 bool IsRO = isReadOnly(GV);
3645
3646 // promoteToConstantPool only if not generating XO text section
3647 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3648 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3649 return V;
3650
3651 if (isPositionIndependent()) {
3653 GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3654 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3655 if (!GV->isDSOLocal())
3656 Result =
3657 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3659 return Result;
3660 } else if (Subtarget->isROPI() && IsRO) {
3661 // PC-relative.
3662 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3663 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3664 return Result;
3665 } else if (Subtarget->isRWPI() && !IsRO) {
3666 // SB-relative.
3667 SDValue RelAddr;
3668 if (Subtarget->useMovt()) {
3669 ++NumMovwMovt;
3670 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3671 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3672 } else { // use literal pool for address constant
3673 ARMConstantPoolValue *CPV =
3675 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3676 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3677 RelAddr = DAG.getLoad(
3678 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3680 }
3681 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3682 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3683 return Result;
3684 }
3685
3686 // If we have T2 ops, we can materialize the address directly via movt/movw
3687 // pair. This is always cheaper. If need to generate Execute Only code, and we
3688 // only have Thumb1 available, we can't use a constant pool and are forced to
3689 // use immediate relocations.
3690 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3691 if (Subtarget->useMovt())
3692 ++NumMovwMovt;
3693 // FIXME: Once remat is capable of dealing with instructions with register
3694 // operands, expand this into two nodes.
3695 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3696 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3697 } else {
3698 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3699 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3700 return DAG.getLoad(
3701 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3703 }
3704}
3705
3706SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3707 SelectionDAG &DAG) const {
3708 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3709 "ROPI/RWPI not currently supported for Darwin");
3710 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3711 SDLoc dl(Op);
3712 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3713
3714 if (Subtarget->useMovt())
3715 ++NumMovwMovt;
3716
3717 // FIXME: Once remat is capable of dealing with instructions with register
3718 // operands, expand this into multiple nodes
3719 unsigned Wrapper =
3720 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3721
3722 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3723 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3724
3725 if (Subtarget->isGVIndirectSymbol(GV))
3726 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3728 return Result;
3729}
3730
3731SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3732 SelectionDAG &DAG) const {
3733 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3734 "non-Windows COFF is not supported");
3735 assert(Subtarget->useMovt() &&
3736 "Windows on ARM expects to use movw/movt");
3737 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3738 "ROPI/RWPI not currently supported for Windows");
3739
3740 const TargetMachine &TM = getTargetMachine();
3741 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3742 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3743 if (GV->hasDLLImportStorageClass())
3744 TargetFlags = ARMII::MO_DLLIMPORT;
3745 else if (!TM.shouldAssumeDSOLocal(GV))
3746 TargetFlags = ARMII::MO_COFFSTUB;
3747 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3749 SDLoc DL(Op);
3750
3751 ++NumMovwMovt;
3752
3753 // FIXME: Once remat is capable of dealing with instructions with register
3754 // operands, expand this into two nodes.
3755 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3756 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3757 TargetFlags));
3758 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3759 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3761 return Result;
3762}
3763
3764SDValue
3765ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3766 SDLoc dl(Op);
3767 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3768 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3769 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3770 Op.getOperand(1), Val);
3771}
3772
3773SDValue
3774ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3775 SDLoc dl(Op);
3776 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3777 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3778}
3779
3780SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3781 SelectionDAG &DAG) const {
3782 SDLoc dl(Op);
3783 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3784 Op.getOperand(0));
3785}
3786
3787SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3788 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3789 unsigned IntNo =
3790 Op.getConstantOperandVal(Op.getOperand(0).getValueType() == MVT::Other);
3791 switch (IntNo) {
3792 default:
3793 return SDValue(); // Don't custom lower most intrinsics.
3794 case Intrinsic::arm_gnu_eabi_mcount: {
3795 MachineFunction &MF = DAG.getMachineFunction();
3796 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3797 SDLoc dl(Op);
3798 SDValue Chain = Op.getOperand(0);
3799 // call "\01__gnu_mcount_nc"
3800 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3801 const uint32_t *Mask =
3803 assert(Mask && "Missing call preserved mask for calling convention");
3804 // Mark LR an implicit live-in.
3805 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3806 SDValue ReturnAddress =
3807 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3808 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3809 SDValue Callee =
3810 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3812 if (Subtarget->isThumb())
3813 return SDValue(
3814 DAG.getMachineNode(
3815 ARM::tBL_PUSHLR, dl, ResultTys,
3816 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3817 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3818 0);
3819 return SDValue(
3820 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3821 {ReturnAddress, Callee, RegisterMask, Chain}),
3822 0);
3823 }
3824 }
3825}
3826
3827SDValue
3828ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3829 const ARMSubtarget *Subtarget) const {
3830 unsigned IntNo = Op.getConstantOperandVal(0);
3831 SDLoc dl(Op);
3832 switch (IntNo) {
3833 default: return SDValue(); // Don't custom lower most intrinsics.
3834 case Intrinsic::thread_pointer: {
3835 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3836 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3837 }
3838 case Intrinsic::arm_cls: {
3839 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3840 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3841 // instruction.
3842 const SDValue &Operand = Op.getOperand(1);
3843 const EVT VTy = Op.getValueType();
3844 return DAG.getNode(ISD::CTLS, dl, VTy, Operand);
3845 }
3846 case Intrinsic::arm_cls64: {
3847 // arm_cls64 returns i32 but takes i64 input.
3848 // Use ISD::CTLS for i64 and truncate the result.
3849 SDValue CTLS64 = DAG.getNode(ISD::CTLS, dl, MVT::i64, Op.getOperand(1));
3850 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, CTLS64);
3851 }
3852 case Intrinsic::arm_neon_vcls:
3853 case Intrinsic::arm_mve_vcls: {
3854 // Lower vector CLS intrinsics to ISD::CTLS.
3855 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3856 const EVT VTy = Op.getValueType();
3857 return DAG.getNode(ISD::CTLS, dl, VTy, Op.getOperand(1));
3858 }
3859 case Intrinsic::eh_sjlj_lsda: {
3860 MachineFunction &MF = DAG.getMachineFunction();
3861 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3862 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3863 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3864 SDValue CPAddr;
3865 bool IsPositionIndependent = isPositionIndependent();
3866 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3867 ARMConstantPoolValue *CPV =
3868 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3869 ARMCP::CPLSDA, PCAdj);
3870 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3871 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3872 SDValue Result = DAG.getLoad(
3873 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3875
3876 if (IsPositionIndependent) {
3877 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3878 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3879 }
3880 return Result;
3881 }
3882 case Intrinsic::arm_neon_vabs:
3883 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3884 Op.getOperand(1));
3885 case Intrinsic::arm_neon_vabds:
3886 if (Op.getValueType().isInteger())
3887 return DAG.getNode(ISD::ABDS, SDLoc(Op), Op.getValueType(),
3888 Op.getOperand(1), Op.getOperand(2));
3889 return SDValue();
3890 case Intrinsic::arm_neon_vabdu:
3891 return DAG.getNode(ISD::ABDU, SDLoc(Op), Op.getValueType(),
3892 Op.getOperand(1), Op.getOperand(2));
3893 case Intrinsic::arm_neon_vmulls:
3894 case Intrinsic::arm_neon_vmullu: {
3895 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3896 ? ARMISD::VMULLs : ARMISD::VMULLu;
3897 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3898 Op.getOperand(1), Op.getOperand(2));
3899 }
3900 case Intrinsic::arm_neon_vminnm:
3901 case Intrinsic::arm_neon_vmaxnm: {
3902 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3903 ? ISD::FMINNUM : ISD::FMAXNUM;
3904 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3905 Op.getOperand(1), Op.getOperand(2));
3906 }
3907 case Intrinsic::arm_neon_vminu:
3908 case Intrinsic::arm_neon_vmaxu: {
3909 if (Op.getValueType().isFloatingPoint())
3910 return SDValue();
3911 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3912 ? ISD::UMIN : ISD::UMAX;
3913 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3914 Op.getOperand(1), Op.getOperand(2));
3915 }
3916 case Intrinsic::arm_neon_vmins:
3917 case Intrinsic::arm_neon_vmaxs: {
3918 // v{min,max}s is overloaded between signed integers and floats.
3919 if (!Op.getValueType().isFloatingPoint()) {
3920 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3921 ? ISD::SMIN : ISD::SMAX;
3922 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3923 Op.getOperand(1), Op.getOperand(2));
3924 }
3925 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3926 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3927 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3928 Op.getOperand(1), Op.getOperand(2));
3929 }
3930 case Intrinsic::arm_neon_vtbl1:
3931 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3932 Op.getOperand(1), Op.getOperand(2));
3933 case Intrinsic::arm_neon_vtbl2:
3934 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3935 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3936 case Intrinsic::arm_mve_pred_i2v:
3937 case Intrinsic::arm_mve_pred_v2i:
3938 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3939 Op.getOperand(1));
3940 case Intrinsic::arm_mve_vreinterpretq:
3941 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3942 Op.getOperand(1));
3943 case Intrinsic::arm_mve_lsll:
3944 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
3945 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3946 case Intrinsic::arm_mve_asrl:
3947 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
3948 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3949 case Intrinsic::arm_mve_vsli:
3950 return DAG.getNode(ARMISD::VSLIIMM, SDLoc(Op), Op->getVTList(),
3951 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3952 case Intrinsic::arm_mve_vsri:
3953 return DAG.getNode(ARMISD::VSRIIMM, SDLoc(Op), Op->getVTList(),
3954 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3955 }
3956}
3957
3959 const ARMSubtarget *Subtarget) {
3960 SDLoc dl(Op);
3961 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
3962 if (SSID == SyncScope::SingleThread)
3963 return Op;
3964
3965 if (!Subtarget->hasDataBarrier()) {
3966 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3967 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3968 // here.
3969 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3970 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3971 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3972 DAG.getConstant(0, dl, MVT::i32));
3973 }
3974
3975 AtomicOrdering Ord =
3976 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
3978 if (Subtarget->isMClass()) {
3979 // Only a full system barrier exists in the M-class architectures.
3981 } else if (Subtarget->preferISHSTBarriers() &&
3982 Ord == AtomicOrdering::Release) {
3983 // Swift happens to implement ISHST barriers in a way that's compatible with
3984 // Release semantics but weaker than ISH so we'd be fools not to use
3985 // it. Beware: other processors probably don't!
3987 }
3988
3989 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3990 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3991 DAG.getConstant(Domain, dl, MVT::i32));
3992}
3993
3995 const ARMSubtarget *Subtarget) {
3996 // ARM pre v5TE and Thumb1 does not have preload instructions.
3997 if (!(Subtarget->isThumb2() ||
3998 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3999 // Just preserve the chain.
4000 return Op.getOperand(0);
4001
4002 SDLoc dl(Op);
4003 unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4004 if (!isRead &&
4005 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4006 // ARMv7 with MP extension has PLDW.
4007 return Op.getOperand(0);
4008
4009 unsigned isData = Op.getConstantOperandVal(4);
4010 if (Subtarget->isThumb()) {
4011 // Invert the bits.
4012 isRead = ~isRead & 1;
4013 isData = ~isData & 1;
4014 }
4015
4016 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4017 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4018 DAG.getConstant(isData, dl, MVT::i32));
4019}
4020
4023 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4024
4025 // vastart just stores the address of the VarArgsFrameIndex slot into the
4026 // memory location argument.
4027 SDLoc dl(Op);
4029 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4030 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4031 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4032 MachinePointerInfo(SV));
4033}
4034
4035SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4036 CCValAssign &NextVA,
4037 SDValue &Root,
4038 SelectionDAG &DAG,
4039 const SDLoc &dl) const {
4040 MachineFunction &MF = DAG.getMachineFunction();
4041 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4042
4043 const TargetRegisterClass *RC;
4044 if (AFI->isThumb1OnlyFunction())
4045 RC = &ARM::tGPRRegClass;
4046 else
4047 RC = &ARM::GPRRegClass;
4048
4049 // Transform the arguments stored in physical registers into virtual ones.
4050 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4051 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4052
4053 SDValue ArgValue2;
4054 if (NextVA.isMemLoc()) {
4055 MachineFrameInfo &MFI = MF.getFrameInfo();
4056 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4057
4058 // Create load node to retrieve arguments from the stack.
4059 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4060 ArgValue2 = DAG.getLoad(
4061 MVT::i32, dl, Root, FIN,
4063 } else {
4064 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4065 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4066 }
4067 if (!Subtarget->isLittle())
4068 std::swap (ArgValue, ArgValue2);
4069 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4070}
4071
4072// The remaining GPRs hold either the beginning of variable-argument
4073// data, or the beginning of an aggregate passed by value (usually
4074// byval). Either way, we allocate stack slots adjacent to the data
4075// provided by our caller, and store the unallocated registers there.
4076// If this is a variadic function, the va_list pointer will begin with
4077// these values; otherwise, this reassembles a (byval) structure that
4078// was split between registers and memory.
4079// Return: The frame index registers were stored into.
4080int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4081 const SDLoc &dl, SDValue &Chain,
4082 const Value *OrigArg,
4083 unsigned InRegsParamRecordIdx,
4084 int ArgOffset, unsigned ArgSize) const {
4085 // Currently, two use-cases possible:
4086 // Case #1. Non-var-args function, and we meet first byval parameter.
4087 // Setup first unallocated register as first byval register;
4088 // eat all remained registers
4089 // (these two actions are performed by HandleByVal method).
4090 // Then, here, we initialize stack frame with
4091 // "store-reg" instructions.
4092 // Case #2. Var-args function, that doesn't contain byval parameters.
4093 // The same: eat all remained unallocated registers,
4094 // initialize stack frame.
4095
4096 MachineFunction &MF = DAG.getMachineFunction();
4097 MachineFrameInfo &MFI = MF.getFrameInfo();
4098 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4099 unsigned RBegin, REnd;
4100 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4101 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4102 } else {
4103 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4104 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4105 REnd = ARM::R4;
4106 }
4107
4108 if (REnd != RBegin)
4109 ArgOffset = -4 * (ARM::R4 - RBegin);
4110
4111 auto PtrVT = getPointerTy(DAG.getDataLayout());
4112 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4113 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4114
4116 const TargetRegisterClass *RC =
4117 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4118
4119 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4120 Register VReg = MF.addLiveIn(Reg, RC);
4121 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4122 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4123 MachinePointerInfo(OrigArg, 4 * i));
4124 MemOps.push_back(Store);
4125 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4126 }
4127
4128 if (!MemOps.empty())
4129 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4130 return FrameIndex;
4131}
4132
4133// Setup stack frame, the va_list pointer will start from.
4134void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4135 const SDLoc &dl, SDValue &Chain,
4136 unsigned ArgOffset,
4137 unsigned TotalArgRegsSaveSize,
4138 bool ForceMutable) const {
4139 MachineFunction &MF = DAG.getMachineFunction();
4140 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4141
4142 // Try to store any remaining integer argument regs
4143 // to their spots on the stack so that they may be loaded by dereferencing
4144 // the result of va_next.
4145 // If there is no regs to be stored, just point address after last
4146 // argument passed via stack.
4147 int FrameIndex = StoreByValRegs(
4148 CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4149 CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4150 AFI->setVarArgsFrameIndex(FrameIndex);
4151}
4152
4153bool ARMTargetLowering::splitValueIntoRegisterParts(
4154 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4155 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4156 EVT ValueVT = Val.getValueType();
4157 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4158 unsigned ValueBits = ValueVT.getSizeInBits();
4159 unsigned PartBits = PartVT.getSizeInBits();
4160 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4161 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4162 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4163 Parts[0] = Val;
4164 return true;
4165 }
4166 return false;
4167}
4168
4169SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4170 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4171 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4172 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4173 unsigned ValueBits = ValueVT.getSizeInBits();
4174 unsigned PartBits = PartVT.getSizeInBits();
4175 SDValue Val = Parts[0];
4176
4177 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4178 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4179 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4180 return Val;
4181 }
4182 return SDValue();
4183}
4184
4185SDValue ARMTargetLowering::LowerFormalArguments(
4186 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4187 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4188 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4189 MachineFunction &MF = DAG.getMachineFunction();
4190 MachineFrameInfo &MFI = MF.getFrameInfo();
4191
4192 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4193
4194 // Assign locations to all of the incoming arguments.
4196 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4197 *DAG.getContext());
4198 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4199
4201 unsigned CurArgIdx = 0;
4202
4203 // Initially ArgRegsSaveSize is zero.
4204 // Then we increase this value each time we meet byval parameter.
4205 // We also increase this value in case of varargs function.
4206 AFI->setArgRegsSaveSize(0);
4207
4208 // Calculate the amount of stack space that we need to allocate to store
4209 // byval and variadic arguments that are passed in registers.
4210 // We need to know this before we allocate the first byval or variadic
4211 // argument, as they will be allocated a stack slot below the CFA (Canonical
4212 // Frame Address, the stack pointer at entry to the function).
4213 unsigned ArgRegBegin = ARM::R4;
4214 for (const CCValAssign &VA : ArgLocs) {
4215 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4216 break;
4217
4218 unsigned Index = VA.getValNo();
4219 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4220 if (!Flags.isByVal())
4221 continue;
4222
4223 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4224 unsigned RBegin, REnd;
4225 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4226 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4227
4228 CCInfo.nextInRegsParam();
4229 }
4230 CCInfo.rewindByValRegsInfo();
4231
4232 int lastInsIndex = -1;
4233 if (isVarArg && MFI.hasVAStart()) {
4234 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4235 if (RegIdx != std::size(GPRArgRegs))
4236 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4237 }
4238
4239 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4240 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4241 auto PtrVT = getPointerTy(DAG.getDataLayout());
4242
4243 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4244 CCValAssign &VA = ArgLocs[i];
4245 if (Ins[VA.getValNo()].isOrigArg()) {
4246 std::advance(CurOrigArg,
4247 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4248 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4249 }
4250 // Arguments stored in registers.
4251 if (VA.isRegLoc()) {
4252 EVT RegVT = VA.getLocVT();
4253 SDValue ArgValue;
4254
4255 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4256 // f64 and vector types are split up into multiple registers or
4257 // combinations of registers and stack slots.
4258 SDValue ArgValue1 =
4259 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4260 VA = ArgLocs[++i]; // skip ahead to next loc
4261 SDValue ArgValue2;
4262 if (VA.isMemLoc()) {
4263 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4264 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4265 ArgValue2 = DAG.getLoad(
4266 MVT::f64, dl, Chain, FIN,
4268 } else {
4269 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4270 }
4271 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4272 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4273 ArgValue1, DAG.getIntPtrConstant(0, dl));
4274 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4275 ArgValue2, DAG.getIntPtrConstant(1, dl));
4276 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4277 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4278 } else {
4279 const TargetRegisterClass *RC;
4280
4281 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4282 RC = &ARM::HPRRegClass;
4283 else if (RegVT == MVT::f32)
4284 RC = &ARM::SPRRegClass;
4285 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4286 RegVT == MVT::v4bf16)
4287 RC = &ARM::DPRRegClass;
4288 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4289 RegVT == MVT::v8bf16)
4290 RC = &ARM::QPRRegClass;
4291 else if (RegVT == MVT::i32)
4292 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4293 : &ARM::GPRRegClass;
4294 else
4295 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4296
4297 // Transform the arguments in physical registers into virtual ones.
4298 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4299 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4300
4301 // If this value is passed in r0 and has the returned attribute (e.g.
4302 // C++ 'structors), record this fact for later use.
4303 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4304 AFI->setPreservesR0();
4305 }
4306 }
4307
4308 // If this is an 8 or 16-bit value, it is really passed promoted
4309 // to 32 bits. Insert an assert[sz]ext to capture this, then
4310 // truncate to the right size.
4311 switch (VA.getLocInfo()) {
4312 default: llvm_unreachable("Unknown loc info!");
4313 case CCValAssign::Full: break;
4314 case CCValAssign::BCvt:
4315 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4316 break;
4317 }
4318
4319 // f16 arguments have their size extended to 4 bytes and passed as if they
4320 // had been copied to the LSBs of a 32-bit register.
4321 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4322 if (VA.needsCustom() &&
4323 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4324 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4325
4326 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4327 // less than 32 bits must be sign- or zero-extended in the callee for
4328 // security reasons. Although the ABI mandates an extension done by the
4329 // caller, the latter cannot be trusted to follow the rules of the ABI.
4330 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4331 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4332 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
4333 ArgValue = handleCMSEValue(ArgValue, Arg, DAG, dl);
4334
4335 InVals.push_back(ArgValue);
4336 } else { // VA.isRegLoc()
4337 // Only arguments passed on the stack should make it here.
4338 assert(VA.isMemLoc());
4339 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4340
4341 int index = VA.getValNo();
4342
4343 // Some Ins[] entries become multiple ArgLoc[] entries.
4344 // Process them only once.
4345 if (index != lastInsIndex)
4346 {
4347 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4348 // FIXME: For now, all byval parameter objects are marked mutable.
4349 // This can be changed with more analysis.
4350 // In case of tail call optimization mark all arguments mutable.
4351 // Since they could be overwritten by lowering of arguments in case of
4352 // a tail call.
4353 if (Flags.isByVal()) {
4354 assert(Ins[index].isOrigArg() &&
4355 "Byval arguments cannot be implicit");
4356 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4357
4358 int FrameIndex = StoreByValRegs(
4359 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4360 VA.getLocMemOffset(), Flags.getByValSize());
4361 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4362 CCInfo.nextInRegsParam();
4363 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4364 VA.getValVT() == MVT::bf16)) {
4365 // f16 and bf16 values are passed in the least-significant half of
4366 // a 4 byte stack slot. This is done as-if the extension was done
4367 // in a 32-bit register, so the actual bytes used for the value
4368 // differ between little and big endian.
4369 assert(VA.getLocVT().getSizeInBits() == 32);
4370 unsigned FIOffset = VA.getLocMemOffset();
4371 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits() / 8,
4372 FIOffset, true);
4373
4374 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
4375 if (DAG.getDataLayout().isBigEndian())
4376 Addr = DAG.getObjectPtrOffset(dl, Addr, TypeSize::getFixed(2));
4377
4378 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, Addr,
4380 DAG.getMachineFunction(), FI)));
4381
4382 } else {
4383 unsigned FIOffset = VA.getLocMemOffset();
4384 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4385 FIOffset, true);
4386
4387 // Create load nodes to retrieve arguments from the stack.
4388 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4389 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4391 DAG.getMachineFunction(), FI)));
4392 }
4393 lastInsIndex = index;
4394 }
4395 }
4396 }
4397
4398 // varargs
4399 if (isVarArg && MFI.hasVAStart()) {
4400 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4401 TotalArgRegsSaveSize);
4402 if (AFI->isCmseNSEntryFunction()) {
4403 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4405 "secure entry function must not be variadic", dl.getDebugLoc()));
4406 }
4407 }
4408
4409 unsigned StackArgSize = CCInfo.getStackSize();
4410 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4411 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4412 // The only way to guarantee a tail call is if the callee restores its
4413 // argument area, but it must also keep the stack aligned when doing so.
4414 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4415 assert(StackAlign && "data layout string is missing stack alignment");
4416 StackArgSize = alignTo(StackArgSize, *StackAlign);
4417
4418 AFI->setArgumentStackToRestore(StackArgSize);
4419 }
4420 AFI->setArgumentStackSize(StackArgSize);
4421
4422 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4423 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4425 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4426 }
4427
4428 return Chain;
4429}
4430
4431/// isFloatingPointZero - Return true if this is +0.0.
4434 return CFP->getValueAPF().isPosZero();
4435 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4436 // Maybe this has already been legalized into the constant pool?
4437 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4438 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4440 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4441 return CFP->getValueAPF().isPosZero();
4442 }
4443 } else if (Op->getOpcode() == ISD::BITCAST &&
4444 Op->getValueType(0) == MVT::f64) {
4445 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4446 // created by LowerConstantFP().
4447 SDValue BitcastOp = Op->getOperand(0);
4448 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4449 isNullConstant(BitcastOp->getOperand(0)))
4450 return true;
4451 }
4452 return false;
4453}
4454
4456 // 0 - INT_MIN sign wraps, so no signed wrap means cmn is safe.
4457 if (Op->getFlags().hasNoSignedWrap())
4458 return true;
4459
4460 // We can still figure out if the second operand is safe to use
4461 // in a CMN instruction by checking if it is known to be not the minimum
4462 // signed value. If it is not, then we can safely use CMN.
4463 // Note: We can eventually remove this check and simply rely on
4464 // Op->getFlags().hasNoSignedWrap() once SelectionDAG/ISelLowering
4465 // consistently sets them appropriately when making said nodes.
4466
4467 KnownBits KnownSrc = DAG.computeKnownBits(Op.getOperand(1));
4468 return !KnownSrc.getSignedMinValue().isMinSignedValue();
4469}
4470
4472 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
4473 (isIntEqualitySetCC(CC) ||
4474 (isUnsignedIntSetCC(CC) && DAG.isKnownNeverZero(Op.getOperand(1))) ||
4475 (isSignedIntSetCC(CC) && isSafeSignedCMN(Op, DAG)));
4476}
4477
4478/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4479/// the given operands.
4480SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4481 SDValue &ARMcc, SelectionDAG &DAG,
4482 const SDLoc &dl) const {
4483 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4484 unsigned C = RHSC->getZExtValue();
4485 if (!isLegalICmpImmediate((int32_t)C)) {
4486 // Constant does not fit, try adjusting it by one.
4487 switch (CC) {
4488 default: break;
4489 case ISD::SETLT:
4490 case ISD::SETGE:
4491 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4492 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4493 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4494 }
4495 break;
4496 case ISD::SETULT:
4497 case ISD::SETUGE:
4498 if (C != 0 && isLegalICmpImmediate(C-1)) {
4499 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4500 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4501 }
4502 break;
4503 case ISD::SETLE:
4504 case ISD::SETGT:
4505 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4506 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4507 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4508 }
4509 break;
4510 case ISD::SETULE:
4511 case ISD::SETUGT:
4512 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4513 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4514 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4515 }
4516 break;
4517 }
4518 }
4519 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4521 // In ARM and Thumb-2, the compare instructions can shift their second
4522 // operand.
4524 std::swap(LHS, RHS);
4525 }
4526
4527 // Thumb1 has very limited immediate modes, so turning an "and" into a
4528 // shift can save multiple instructions.
4529 //
4530 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4531 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4532 // own. If it's the operand to an unsigned comparison with an immediate,
4533 // we can eliminate one of the shifts: we transform
4534 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4535 //
4536 // We avoid transforming cases which aren't profitable due to encoding
4537 // details:
4538 //
4539 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4540 // would not; in that case, we're essentially trading one immediate load for
4541 // another.
4542 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4543 // 3. C2 is zero; we have other code for this special case.
4544 //
4545 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4546 // instruction, since the AND is always one instruction anyway, but we could
4547 // use narrow instructions in some cases.
4548 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4549 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4550 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4551 !isSignedIntSetCC(CC)) {
4552 unsigned Mask = LHS.getConstantOperandVal(1);
4553 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4554 uint64_t RHSV = RHSC->getZExtValue();
4555 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4556 unsigned ShiftBits = llvm::countl_zero(Mask);
4557 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4558 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4559 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4560 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4561 }
4562 }
4563 }
4564
4565 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4566 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4567 // way a cmp would.
4568 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4569 // some tweaks to the heuristics for the previous and->shift transform.
4570 // FIXME: Optimize cases where the LHS isn't a shift.
4571 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4572 isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4573 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4574 LHS.getConstantOperandVal(1) < 31) {
4575 unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4576 SDValue Shift =
4577 DAG.getNode(ARMISD::LSLS, dl, DAG.getVTList(MVT::i32, FlagsVT),
4578 LHS.getOperand(0), DAG.getConstant(ShiftAmt, dl, MVT::i32));
4579 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4580 return Shift.getValue(1);
4581 }
4582
4584
4585 // If the RHS is a constant zero then the V (overflow) flag will never be
4586 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4587 // simpler for other passes (like the peephole optimiser) to deal with.
4588 if (isNullConstant(RHS)) {
4589 switch (CondCode) {
4590 default: break;
4591 case ARMCC::GE:
4593 break;
4594 case ARMCC::LT:
4596 break;
4597 }
4598 }
4599
4600 unsigned CompareType;
4601 switch (CondCode) {
4602 default:
4603 CompareType = ARMISD::CMP;
4604 break;
4605 case ARMCC::EQ:
4606 case ARMCC::NE:
4607 // Uses only Z Flag
4608 CompareType = ARMISD::CMPZ;
4609 break;
4610 }
4611
4612 // TODO: Remove CMPZ check once we generalize and remove the CMPZ enum from
4613 // the codebase.
4614
4615 // TODO: When we have a solution to the vselect predicate not allowing pl/mi
4616 // all the time, allow those cases to be cmn too no matter what.
4617 if (CompareType != ARMISD::CMPZ && isCMN(RHS, CC, DAG)) {
4618 CompareType = ARMISD::CMN;
4619 RHS = RHS.getOperand(1);
4620 } else if (CompareType != ARMISD::CMPZ && isCMN(LHS, CC, DAG)) {
4621 CompareType = ARMISD::CMN;
4622 LHS = LHS.getOperand(1);
4624 }
4625
4626 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4627 return DAG.getNode(CompareType, dl, FlagsVT, LHS, RHS);
4628}
4629
4630/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4631SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4632 SelectionDAG &DAG, const SDLoc &dl,
4633 bool Signaling) const {
4634 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4635 SDValue Flags;
4637 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, dl, FlagsVT,
4638 LHS, RHS);
4639 else
4640 Flags = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, dl,
4641 FlagsVT, LHS);
4642 return DAG.getNode(ARMISD::FMSTAT, dl, FlagsVT, Flags);
4643}
4644
4645// This function returns three things: the arithmetic computation itself
4646// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4647// comparison and the condition code define the case in which the arithmetic
4648// computation *does not* overflow.
4649std::pair<SDValue, SDValue>
4650ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4651 SDValue &ARMcc) const {
4652 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4653
4654 SDValue Value, OverflowCmp;
4655 SDValue LHS = Op.getOperand(0);
4656 SDValue RHS = Op.getOperand(1);
4657 SDLoc dl(Op);
4658
4659 // FIXME: We are currently always generating CMPs because we don't support
4660 // generating CMN through the backend. This is not as good as the natural
4661 // CMP case because it causes a register dependency and cannot be folded
4662 // later.
4663
4664 switch (Op.getOpcode()) {
4665 default:
4666 llvm_unreachable("Unknown overflow instruction!");
4667 case ISD::SADDO:
4668 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4669 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4670 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4671 break;
4672 case ISD::UADDO:
4673 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4674 // We use ADDC here to correspond to its use in LowerALUO.
4675 // We do not use it in the USUBO case as Value may not be used.
4676 Value = DAG.getNode(ARMISD::ADDC, dl,
4677 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4678 .getValue(0);
4679 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
4680 break;
4681 case ISD::SSUBO:
4682 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4683 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4684 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4685 break;
4686 case ISD::USUBO:
4687 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4688 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4689 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
4690 break;
4691 case ISD::UMULO:
4692 // We generate a UMUL_LOHI and then check if the high word is 0.
4693 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4694 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4695 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4696 LHS, RHS);
4697 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4698 DAG.getConstant(0, dl, MVT::i32));
4699 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4700 break;
4701 case ISD::SMULO:
4702 // We generate a SMUL_LOHI and then check if all the bits of the high word
4703 // are the same as the sign bit of the low word.
4704 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4705 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4706 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4707 LHS, RHS);
4708 OverflowCmp = DAG.getNode(ARMISD::CMPZ, dl, FlagsVT, Value.getValue(1),
4709 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4710 Value.getValue(0),
4711 DAG.getConstant(31, dl, MVT::i32)));
4712 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4713 break;
4714 } // switch (...)
4715
4716 return std::make_pair(Value, OverflowCmp);
4717}
4718
4720 SDLoc DL(Value);
4721 EVT VT = Value.getValueType();
4722
4723 if (Invert)
4724 Value = DAG.getNode(ISD::SUB, DL, MVT::i32,
4725 DAG.getConstant(1, DL, MVT::i32), Value);
4726
4727 SDValue Cmp = DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(VT, MVT::i32),
4728 Value, DAG.getConstant(1, DL, VT));
4729 return Cmp.getValue(1);
4730}
4731
4733 bool Invert) {
4734 SDLoc DL(Flags);
4735
4736 if (Invert) {
4737 // Convert flags to boolean with ADDE 0,0,Carry then compute 1 - bool.
4738 SDValue BoolCarry = DAG.getNode(
4739 ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4740 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT), Flags);
4741 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(1, DL, VT), BoolCarry);
4742 }
4743
4744 // Now convert the carry flag into a boolean carry. We do this
4745 // using ARMISD::ADDE 0, 0, Carry
4746 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4747 DAG.getConstant(0, DL, VT), DAG.getConstant(0, DL, VT),
4748 Flags);
4749}
4750
4751// Value is 1 if 'V' bit is 1, else 0
4753 SDLoc DL(Flags);
4754 SDValue Zero = DAG.getConstant(0, DL, VT);
4755 SDValue One = DAG.getConstant(1, DL, VT);
4756 SDValue ARMcc = DAG.getConstant(ARMCC::VS, DL, MVT::i32);
4757 return DAG.getNode(ARMISD::CMOV, DL, VT, Zero, One, ARMcc, Flags);
4758}
4759
4760SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4761 // Let legalize expand this if it isn't a legal type yet.
4762 if (!isTypeLegal(Op.getValueType()))
4763 return SDValue();
4764
4765 SDValue LHS = Op.getOperand(0);
4766 SDValue RHS = Op.getOperand(1);
4767 SDLoc dl(Op);
4768
4769 EVT VT = Op.getValueType();
4770 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4771 SDValue Value;
4772 SDValue Overflow;
4773 switch (Op.getOpcode()) {
4774 case ISD::UADDO:
4775 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4776 // Convert the carry flag into a boolean value.
4777 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, false);
4778 break;
4779 case ISD::USUBO:
4780 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4781 // Convert the carry flag into a boolean value.
4782 Overflow = carryFlagToValue(Value.getValue(1), VT, DAG, true);
4783 break;
4784 default: {
4785 // Handle other operations with getARMXALUOOp
4786 SDValue OverflowCmp, ARMcc;
4787 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4788 // We use 0 and 1 as false and true values.
4789 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4790 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4791 // position to get Overflow=1 when the "no overflow" condition is false.
4792 Overflow =
4793 DAG.getNode(ARMISD::CMOV, dl, MVT::i32,
4794 DAG.getConstant(1, dl, MVT::i32), // FalseVal: overflow
4795 DAG.getConstant(0, dl, MVT::i32), // TrueVal: no overflow
4796 ARMcc, OverflowCmp);
4797 break;
4798 }
4799 }
4800
4801 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4802}
4803
4805 const ARMSubtarget *Subtarget) {
4806 EVT VT = Op.getValueType();
4807 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
4808 return SDValue();
4809 if (!VT.isSimple())
4810 return SDValue();
4811
4812 unsigned NewOpcode;
4813 switch (VT.getSimpleVT().SimpleTy) {
4814 default:
4815 return SDValue();
4816 case MVT::i8:
4817 switch (Op->getOpcode()) {
4818 case ISD::UADDSAT:
4819 NewOpcode = ARMISD::UQADD8b;
4820 break;
4821 case ISD::SADDSAT:
4822 NewOpcode = ARMISD::QADD8b;
4823 break;
4824 case ISD::USUBSAT:
4825 NewOpcode = ARMISD::UQSUB8b;
4826 break;
4827 case ISD::SSUBSAT:
4828 NewOpcode = ARMISD::QSUB8b;
4829 break;
4830 }
4831 break;
4832 case MVT::i16:
4833 switch (Op->getOpcode()) {
4834 case ISD::UADDSAT:
4835 NewOpcode = ARMISD::UQADD16b;
4836 break;
4837 case ISD::SADDSAT:
4838 NewOpcode = ARMISD::QADD16b;
4839 break;
4840 case ISD::USUBSAT:
4841 NewOpcode = ARMISD::UQSUB16b;
4842 break;
4843 case ISD::SSUBSAT:
4844 NewOpcode = ARMISD::QSUB16b;
4845 break;
4846 }
4847 break;
4848 }
4849
4850 SDLoc dl(Op);
4851 SDValue Add =
4852 DAG.getNode(NewOpcode, dl, MVT::i32,
4853 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4854 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4855 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4856}
4857
4858SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4859 SDValue Cond = Op.getOperand(0);
4860 SDValue SelectTrue = Op.getOperand(1);
4861 SDValue SelectFalse = Op.getOperand(2);
4862 SDLoc dl(Op);
4863 unsigned Opc = Cond.getOpcode();
4864
4865 if (Cond.getResNo() == 1 &&
4866 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4867 Opc == ISD::USUBO)) {
4868 if (!isTypeLegal(Cond->getValueType(0)))
4869 return SDValue();
4870
4871 SDValue Value, OverflowCmp;
4872 SDValue ARMcc;
4873 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4874 EVT VT = Op.getValueType();
4875
4876 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, OverflowCmp, DAG);
4877 }
4878
4879 // Convert:
4880 //
4881 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4882 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4883 //
4884 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4885 const ConstantSDNode *CMOVTrue =
4886 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4887 const ConstantSDNode *CMOVFalse =
4888 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4889
4890 if (CMOVTrue && CMOVFalse) {
4891 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4892 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4893
4894 SDValue True;
4895 SDValue False;
4896 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4897 True = SelectTrue;
4898 False = SelectFalse;
4899 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4900 True = SelectFalse;
4901 False = SelectTrue;
4902 }
4903
4904 if (True.getNode() && False.getNode())
4905 return getCMOV(dl, Op.getValueType(), True, False, Cond.getOperand(2),
4906 Cond.getOperand(3), DAG);
4907 }
4908 }
4909
4910 return DAG.getSelectCC(dl, Cond,
4911 DAG.getConstant(0, dl, Cond.getValueType()),
4912 SelectTrue, SelectFalse, ISD::SETNE);
4913}
4914
4916 bool &swpCmpOps, bool &swpVselOps) {
4917 // Start by selecting the GE condition code for opcodes that return true for
4918 // 'equality'
4919 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4920 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4921 CondCode = ARMCC::GE;
4922
4923 // and GT for opcodes that return false for 'equality'.
4924 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4925 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4926 CondCode = ARMCC::GT;
4927
4928 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4929 // to swap the compare operands.
4930 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4931 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4932 swpCmpOps = true;
4933
4934 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4935 // If we have an unordered opcode, we need to swap the operands to the VSEL
4936 // instruction (effectively negating the condition).
4937 //
4938 // This also has the effect of swapping which one of 'less' or 'greater'
4939 // returns true, so we also swap the compare operands. It also switches
4940 // whether we return true for 'equality', so we compensate by picking the
4941 // opposite condition code to our original choice.
4942 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4943 CC == ISD::SETUGT) {
4944 swpCmpOps = !swpCmpOps;
4945 swpVselOps = !swpVselOps;
4946 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4947 }
4948
4949 // 'ordered' is 'anything but unordered', so use the VS condition code and
4950 // swap the VSEL operands.
4951 if (CC == ISD::SETO) {
4952 CondCode = ARMCC::VS;
4953 swpVselOps = true;
4954 }
4955
4956 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4957 // code and swap the VSEL operands. Also do this if we don't care about the
4958 // unordered case.
4959 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4960 CondCode = ARMCC::EQ;
4961 swpVselOps = true;
4962 }
4963}
4964
4965SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4966 SDValue TrueVal, SDValue ARMcc,
4967 SDValue Flags, SelectionDAG &DAG) const {
4968 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4969 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4970 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4971 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4972 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4973
4974 SDValue TrueLow = TrueVal.getValue(0);
4975 SDValue TrueHigh = TrueVal.getValue(1);
4976 SDValue FalseLow = FalseVal.getValue(0);
4977 SDValue FalseHigh = FalseVal.getValue(1);
4978
4979 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4980 ARMcc, Flags);
4981 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4982 ARMcc, Flags);
4983
4984 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4985 }
4986 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, Flags);
4987}
4988
4989static bool isGTorGE(ISD::CondCode CC) {
4990 return CC == ISD::SETGT || CC == ISD::SETGE;
4991}
4992
4993static bool isLTorLE(ISD::CondCode CC) {
4994 return CC == ISD::SETLT || CC == ISD::SETLE;
4995}
4996
4997// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4998// All of these conditions (and their <= and >= counterparts) will do:
4999// x < k ? k : x
5000// x > k ? x : k
5001// k < x ? x : k
5002// k > x ? k : x
5003static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5004 const SDValue TrueVal, const SDValue FalseVal,
5005 const ISD::CondCode CC, const SDValue K) {
5006 return (isGTorGE(CC) &&
5007 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5008 (isLTorLE(CC) &&
5009 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5010}
5011
5012// Check if two chained conditionals could be converted into SSAT or USAT.
5013//
5014// SSAT can replace a set of two conditional selectors that bound a number to an
5015// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5016//
5017// x < -k ? -k : (x > k ? k : x)
5018// x < -k ? -k : (x < k ? x : k)
5019// x > -k ? (x > k ? k : x) : -k
5020// x < k ? (x < -k ? -k : x) : k
5021// etc.
5022//
5023// LLVM canonicalizes these to either a min(max()) or a max(min())
5024// pattern. This function tries to match one of these and will return a SSAT
5025// node if successful.
5026//
5027// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
5028// is a power of 2.
5030 EVT VT = Op.getValueType();
5031 SDValue V1 = Op.getOperand(0);
5032 SDValue K1 = Op.getOperand(1);
5033 SDValue TrueVal1 = Op.getOperand(2);
5034 SDValue FalseVal1 = Op.getOperand(3);
5035 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5036
5037 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5038 if (Op2.getOpcode() != ISD::SELECT_CC)
5039 return SDValue();
5040
5041 SDValue V2 = Op2.getOperand(0);
5042 SDValue K2 = Op2.getOperand(1);
5043 SDValue TrueVal2 = Op2.getOperand(2);
5044 SDValue FalseVal2 = Op2.getOperand(3);
5045 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5046
5047 SDValue V1Tmp = V1;
5048 SDValue V2Tmp = V2;
5049
5050 // Check that the registers and the constants match a max(min()) or min(max())
5051 // pattern
5052 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5053 K2 != FalseVal2 ||
5054 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5055 return SDValue();
5056
5057 // Check that the constant in the lower-bound check is
5058 // the opposite of the constant in the upper-bound check
5059 // in 1's complement.
5061 return SDValue();
5062
5063 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5064 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5065 int64_t PosVal = std::max(Val1, Val2);
5066 int64_t NegVal = std::min(Val1, Val2);
5067
5068 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5069 !isPowerOf2_64(PosVal + 1))
5070 return SDValue();
5071
5072 // Handle the difference between USAT (unsigned) and SSAT (signed)
5073 // saturation
5074 // At this point, PosVal is guaranteed to be positive
5075 uint64_t K = PosVal;
5076 SDLoc dl(Op);
5077 if (Val1 == ~Val2)
5078 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5079 DAG.getConstant(llvm::countr_one(K), dl, VT));
5080 if (NegVal == 0)
5081 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5082 DAG.getConstant(llvm::countr_one(K), dl, VT));
5083
5084 return SDValue();
5085}
5086
5087// Check if a condition of the type x < k ? k : x can be converted into a
5088// bit operation instead of conditional moves.
5089// Currently this is allowed given:
5090// - The conditions and values match up
5091// - k is 0 or -1 (all ones)
5092// This function will not check the last condition, thats up to the caller
5093// It returns true if the transformation can be made, and in such case
5094// returns x in V, and k in SatK.
5096 SDValue &SatK)
5097{
5098 SDValue LHS = Op.getOperand(0);
5099 SDValue RHS = Op.getOperand(1);
5100 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5101 SDValue TrueVal = Op.getOperand(2);
5102 SDValue FalseVal = Op.getOperand(3);
5103
5105 ? &RHS
5106 : nullptr;
5107
5108 // No constant operation in comparison, early out
5109 if (!K)
5110 return false;
5111
5112 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5113 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5114 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5115
5116 // If the constant on left and right side, or variable on left and right,
5117 // does not match, early out
5118 if (*K != KTmp || V != VTmp)
5119 return false;
5120
5121 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5122 SatK = *K;
5123 return true;
5124 }
5125
5126 return false;
5127}
5128
5129bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5130 if (VT == MVT::f32)
5131 return !Subtarget->hasVFP2Base();
5132 if (VT == MVT::f64)
5133 return !Subtarget->hasFP64();
5134 if (VT == MVT::f16)
5135 return !Subtarget->hasFullFP16();
5136 return false;
5137}
5138
5139static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5140 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5141 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5142 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5143 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5144 return SDValue();
5145
5146 unsigned TVal = CTVal->getZExtValue();
5147 unsigned FVal = CFVal->getZExtValue();
5148
5149 Opcode = 0;
5150 InvertCond = false;
5151 if (TVal == ~FVal) {
5152 Opcode = ARMISD::CSINV;
5153 } else if (TVal == ~FVal + 1) {
5154 Opcode = ARMISD::CSNEG;
5155 } else if (TVal + 1 == FVal) {
5156 Opcode = ARMISD::CSINC;
5157 } else if (TVal == FVal + 1) {
5158 Opcode = ARMISD::CSINC;
5159 std::swap(TrueVal, FalseVal);
5160 std::swap(TVal, FVal);
5161 InvertCond = !InvertCond;
5162 } else {
5163 return SDValue();
5164 }
5165
5166 // If one of the constants is cheaper than another, materialise the
5167 // cheaper one and let the csel generate the other.
5168 if (Opcode != ARMISD::CSINC &&
5169 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5170 std::swap(TrueVal, FalseVal);
5171 std::swap(TVal, FVal);
5172 InvertCond = !InvertCond;
5173 }
5174
5175 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5176 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5177 // -(-a) == a, but (a+1)+1 != a).
5178 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5179 std::swap(TrueVal, FalseVal);
5180 std::swap(TVal, FVal);
5181 InvertCond = !InvertCond;
5182 }
5183
5184 return TrueVal;
5185}
5186
5187SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5188 EVT VT = Op.getValueType();
5189 SDLoc dl(Op);
5190
5191 // Try to convert two saturating conditional selects into a single SSAT
5192 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5193 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5194 return SatValue;
5195
5196 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5197 // into more efficient bit operations, which is possible when k is 0 or -1
5198 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5199 // single instructions. On Thumb the shift and the bit operation will be two
5200 // instructions.
5201 // Only allow this transformation on full-width (32-bit) operations
5202 SDValue LowerSatConstant;
5203 SDValue SatValue;
5204 if (VT == MVT::i32 &&
5205 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5206 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5207 DAG.getConstant(31, dl, VT));
5208 if (isNullConstant(LowerSatConstant)) {
5209 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5210 DAG.getAllOnesConstant(dl, VT));
5211 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5212 } else if (isAllOnesConstant(LowerSatConstant))
5213 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5214 }
5215
5216 SDValue LHS = Op.getOperand(0);
5217 SDValue RHS = Op.getOperand(1);
5218 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5219 SDValue TrueVal = Op.getOperand(2);
5220 SDValue FalseVal = Op.getOperand(3);
5221 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5222 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5223 if (Op.getValueType().isInteger()) {
5224
5225 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5226 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5227 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5228 // Both require less instructions than compare and conditional select.
5229 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5230 RHSC->isZero() && CFVal && CFVal->isZero() &&
5231 LHS.getValueType() == RHS.getValueType()) {
5232 EVT VT = LHS.getValueType();
5233 SDValue Shift =
5234 DAG.getNode(ISD::SRA, dl, VT, LHS,
5235 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5236
5237 if (CC == ISD::SETGT)
5238 Shift = DAG.getNOT(dl, Shift, VT);
5239
5240 return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
5241 }
5242
5243 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5244 if (CC == ISD::SETLT && isNullConstant(RHS) && isOneConstant(TrueVal) &&
5245 isNullConstant(FalseVal) && LHS.getValueType() == VT)
5246 return DAG.getNode(ISD::SRL, dl, VT, LHS,
5247 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5248 }
5249
5250 if (LHS.getValueType() == MVT::i32) {
5251 unsigned Opcode;
5252 bool InvertCond;
5253 if (SDValue Op =
5254 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5255 if (InvertCond)
5256 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5257
5258 SDValue ARMcc;
5259 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5260 EVT VT = Op.getValueType();
5261 return DAG.getNode(Opcode, dl, VT, Op, Op, ARMcc, Cmp);
5262 }
5263 }
5264
5265 if (isUnsupportedFloatingType(LHS.getValueType())) {
5266 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5267
5268 // If softenSetCCOperands only returned one value, we should compare it to
5269 // zero.
5270 if (!RHS.getNode()) {
5271 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5272 CC = ISD::SETNE;
5273 }
5274 }
5275
5276 if (LHS.getValueType() == MVT::i32) {
5277 // Try to generate VSEL on ARMv8.
5278 // The VSEL instruction can't use all the usual ARM condition
5279 // codes: it only has two bits to select the condition code, so it's
5280 // constrained to use only GE, GT, VS and EQ.
5281 //
5282 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5283 // swap the operands of the previous compare instruction (effectively
5284 // inverting the compare condition, swapping 'less' and 'greater') and
5285 // sometimes need to swap the operands to the VSEL (which inverts the
5286 // condition in the sense of firing whenever the previous condition didn't)
5287 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5288 TrueVal.getValueType() == MVT::f32 ||
5289 TrueVal.getValueType() == MVT::f64)) {
5291 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5292 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5293 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5294 std::swap(TrueVal, FalseVal);
5295 }
5296 }
5297
5298 SDValue ARMcc;
5299 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5300 // Choose GE over PL, which vsel does now support
5301 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5302 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5303 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5304 }
5305
5306 ARMCC::CondCodes CondCode, CondCode2;
5307 FPCCToARMCC(CC, CondCode, CondCode2);
5308
5309 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5310 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5311 // must use VSEL (limited condition codes), due to not having conditional f16
5312 // moves.
5313 if (Subtarget->hasFPARMv8Base() &&
5314 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5315 (TrueVal.getValueType() == MVT::f16 ||
5316 TrueVal.getValueType() == MVT::f32 ||
5317 TrueVal.getValueType() == MVT::f64)) {
5318 bool swpCmpOps = false;
5319 bool swpVselOps = false;
5320 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5321
5322 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5323 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5324 if (swpCmpOps)
5325 std::swap(LHS, RHS);
5326 if (swpVselOps)
5327 std::swap(TrueVal, FalseVal);
5328 }
5329 }
5330
5331 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5332 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5333 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5334 if (CondCode2 != ARMCC::AL) {
5335 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5336 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, Cmp, DAG);
5337 }
5338 return Result;
5339}
5340
5341/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5342/// to morph to an integer compare sequence.
5343static bool canChangeToInt(SDValue Op, bool &SeenZero,
5344 const ARMSubtarget *Subtarget) {
5345 SDNode *N = Op.getNode();
5346 if (!N->hasOneUse())
5347 // Otherwise it requires moving the value from fp to integer registers.
5348 return false;
5349 if (!N->getNumValues())
5350 return false;
5351 EVT VT = Op.getValueType();
5352 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5353 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5354 // vmrs are very slow, e.g. cortex-a8.
5355 return false;
5356
5357 if (isFloatingPointZero(Op)) {
5358 SeenZero = true;
5359 return true;
5360 }
5361 return ISD::isNormalLoad(N);
5362}
5363
5366 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5367
5369 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5370 Ld->getPointerInfo(), Ld->getAlign(),
5371 Ld->getMemOperand()->getFlags());
5372
5373 llvm_unreachable("Unknown VFP cmp argument!");
5374}
5375
5377 SDValue &RetVal1, SDValue &RetVal2) {
5378 SDLoc dl(Op);
5379
5380 if (isFloatingPointZero(Op)) {
5381 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5382 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5383 return;
5384 }
5385
5386 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5387 SDValue Ptr = Ld->getBasePtr();
5388 RetVal1 =
5389 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5390 Ld->getAlign(), Ld->getMemOperand()->getFlags());
5391
5392 EVT PtrType = Ptr.getValueType();
5393 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5394 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5395 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5396 Ld->getPointerInfo().getWithOffset(4),
5397 commonAlignment(Ld->getAlign(), 4),
5398 Ld->getMemOperand()->getFlags());
5399 return;
5400 }
5401
5402 llvm_unreachable("Unknown VFP cmp argument!");
5403}
5404
5405/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5406/// f32 and even f64 comparisons to integer ones.
5407SDValue
5408ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5409 SDValue Chain = Op.getOperand(0);
5410 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5411 SDValue LHS = Op.getOperand(2);
5412 SDValue RHS = Op.getOperand(3);
5413 SDValue Dest = Op.getOperand(4);
5414 SDLoc dl(Op);
5415
5416 bool LHSSeenZero = false;
5417 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5418 bool RHSSeenZero = false;
5419 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5420 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5421 // If unsafe fp math optimization is enabled and there are no other uses of
5422 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5423 // to an integer comparison.
5424 if (CC == ISD::SETOEQ)
5425 CC = ISD::SETEQ;
5426 else if (CC == ISD::SETUNE)
5427 CC = ISD::SETNE;
5428
5429 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5430 SDValue ARMcc;
5431 if (LHS.getValueType() == MVT::f32) {
5432 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5433 bitcastf32Toi32(LHS, DAG), Mask);
5434 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5435 bitcastf32Toi32(RHS, DAG), Mask);
5436 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5437 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5438 Cmp);
5439 }
5440
5441 SDValue LHS1, LHS2;
5442 SDValue RHS1, RHS2;
5443 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5444 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5445 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5446 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5448 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5449 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5450 return DAG.getNode(ARMISD::BCC_i64, dl, MVT::Other, Ops);
5451 }
5452
5453 return SDValue();
5454}
5455
5456// Generate CMP + CMOV for integer abs.
5457SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5458 SDLoc DL(Op);
5459
5460 SDValue Neg = DAG.getNegative(Op.getOperand(0), DL, MVT::i32);
5461
5462 // Generate CMP & CMOV.
5463 SDValue Cmp = DAG.getNode(ARMISD::CMP, DL, FlagsVT, Op.getOperand(0),
5464 DAG.getConstant(0, DL, MVT::i32));
5465 return DAG.getNode(ARMISD::CMOV, DL, MVT::i32, Op.getOperand(0), Neg,
5466 DAG.getConstant(ARMCC::MI, DL, MVT::i32), Cmp);
5467}
5468
5470 ARMCC::CondCodes CondCode =
5471 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
5472 CondCode = ARMCC::getOppositeCondition(CondCode);
5473 return DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5474}
5475
5476SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5477 SDValue Chain = Op.getOperand(0);
5478 SDValue Cond = Op.getOperand(1);
5479 SDValue Dest = Op.getOperand(2);
5480 SDLoc dl(Op);
5481
5482 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5483 // instruction.
5484 unsigned Opc = Cond.getOpcode();
5485 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5486 !Subtarget->isThumb1Only();
5487 if (Cond.getResNo() == 1 &&
5488 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5489 Opc == ISD::USUBO || OptimizeMul)) {
5490 // Only lower legal XALUO ops.
5491 if (!isTypeLegal(Cond->getValueType(0)))
5492 return SDValue();
5493
5494 // The actual operation with overflow check.
5495 SDValue Value, OverflowCmp;
5496 SDValue ARMcc;
5497 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5498
5499 // Reverse the condition code.
5500 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5501
5502 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5503 OverflowCmp);
5504 }
5505
5506 return SDValue();
5507}
5508
5509SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5510 SDValue Chain = Op.getOperand(0);
5511 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5512 SDValue LHS = Op.getOperand(2);
5513 SDValue RHS = Op.getOperand(3);
5514 SDValue Dest = Op.getOperand(4);
5515 SDLoc dl(Op);
5516
5517 if (isUnsupportedFloatingType(LHS.getValueType())) {
5518 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5519
5520 // If softenSetCCOperands only returned one value, we should compare it to
5521 // zero.
5522 if (!RHS.getNode()) {
5523 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5524 CC = ISD::SETNE;
5525 }
5526 }
5527
5528 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5529 // instruction.
5530 unsigned Opc = LHS.getOpcode();
5531 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5532 !Subtarget->isThumb1Only();
5533 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5534 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5535 Opc == ISD::USUBO || OptimizeMul) &&
5536 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5537 // Only lower legal XALUO ops.
5538 if (!isTypeLegal(LHS->getValueType(0)))
5539 return SDValue();
5540
5541 // The actual operation with overflow check.
5542 SDValue Value, OverflowCmp;
5543 SDValue ARMcc;
5544 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5545
5546 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5547 // Reverse the condition code.
5548 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5549 }
5550
5551 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5552 OverflowCmp);
5553 }
5554
5555 if (LHS.getValueType() == MVT::i32) {
5556 SDValue ARMcc;
5557 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5558 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, Cmp);
5559 }
5560
5561 SDNodeFlags Flags = Op->getFlags();
5562 if (Flags.hasNoNaNs() &&
5563 DAG.getDenormalMode(MVT::f32) == DenormalMode::getIEEE() &&
5564 DAG.getDenormalMode(MVT::f64) == DenormalMode::getIEEE() &&
5565 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5566 CC == ISD::SETUNE)) {
5567 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5568 return Result;
5569 }
5570
5571 ARMCC::CondCodes CondCode, CondCode2;
5572 FPCCToARMCC(CC, CondCode, CondCode2);
5573
5574 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5575 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5576 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5577 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5578 if (CondCode2 != ARMCC::AL) {
5579 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5580 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5581 Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5582 }
5583 return Res;
5584}
5585
5586SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5587 SDValue Chain = Op.getOperand(0);
5588 SDValue Table = Op.getOperand(1);
5589 SDValue Index = Op.getOperand(2);
5590 SDLoc dl(Op);
5591
5592 EVT PTy = getPointerTy(DAG.getDataLayout());
5593 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5594 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5595 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5596 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5597 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5598 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5599 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5600 // which does another jump to the destination. This also makes it easier
5601 // to translate it to TBB / TBH later (Thumb2 only).
5602 // FIXME: This might not work if the function is extremely large.
5603 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5604 Addr, Op.getOperand(2), JTI);
5605 }
5606 if (isPositionIndependent() || Subtarget->isROPI()) {
5607 Addr =
5608 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5610 Chain = Addr.getValue(1);
5611 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5612 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5613 } else {
5614 Addr =
5615 DAG.getLoad(PTy, dl, Chain, Addr,
5617 Chain = Addr.getValue(1);
5618 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5619 }
5620}
5621
5623 EVT VT = Op.getValueType();
5624 SDLoc dl(Op);
5625
5626 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5627 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5628 return Op;
5629 return DAG.UnrollVectorOp(Op.getNode());
5630 }
5631
5632 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5633
5634 EVT NewTy;
5635 const EVT OpTy = Op.getOperand(0).getValueType();
5636 if (OpTy == MVT::v4f32)
5637 NewTy = MVT::v4i32;
5638 else if (OpTy == MVT::v4f16 && HasFullFP16)
5639 NewTy = MVT::v4i16;
5640 else if (OpTy == MVT::v8f16 && HasFullFP16)
5641 NewTy = MVT::v8i16;
5642 else
5643 llvm_unreachable("Invalid type for custom lowering!");
5644
5645 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5646 return DAG.UnrollVectorOp(Op.getNode());
5647
5648 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5649 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5650}
5651
5652SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5653 EVT VT = Op.getValueType();
5654 if (VT.isVector())
5655 return LowerVectorFP_TO_INT(Op, DAG);
5656
5657 bool IsStrict = Op->isStrictFPOpcode();
5658 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5659
5660 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5661 RTLIB::Libcall LC;
5662 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5663 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5664 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5665 Op.getValueType());
5666 else
5667 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5668 Op.getValueType());
5669 SDLoc Loc(Op);
5670 MakeLibCallOptions CallOptions;
5671 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5673 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5674 CallOptions, Loc, Chain);
5675 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5676 }
5677
5678 // FIXME: Remove this when we have strict fp instruction selection patterns
5679 if (IsStrict) {
5680 SDLoc Loc(Op);
5681 SDValue Result =
5684 Loc, Op.getValueType(), SrcVal);
5685 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5686 }
5687
5688 return Op;
5689}
5690
5692 const ARMSubtarget *Subtarget) {
5693 EVT VT = Op.getValueType();
5694 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5695 EVT FromVT = Op.getOperand(0).getValueType();
5696
5697 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5698 return Op;
5699 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5700 Subtarget->hasFP64())
5701 return Op;
5702 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5703 Subtarget->hasFullFP16())
5704 return Op;
5705 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5706 Subtarget->hasMVEFloatOps())
5707 return Op;
5708 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5709 Subtarget->hasMVEFloatOps())
5710 return Op;
5711
5712 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5713 return SDValue();
5714
5715 SDLoc DL(Op);
5716 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5717 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5718 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5719 DAG.getValueType(VT.getScalarType()));
5720 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5721 DAG.getConstant((1 << BW) - 1, DL, VT));
5722 if (IsSigned)
5723 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5724 DAG.getSignedConstant(-(1 << BW), DL, VT));
5725 return Max;
5726}
5727
5729 EVT VT = Op.getValueType();
5730 SDLoc dl(Op);
5731
5732 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5733 if (VT.getVectorElementType() == MVT::f32)
5734 return Op;
5735 return DAG.UnrollVectorOp(Op.getNode());
5736 }
5737
5738 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5739 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5740 "Invalid type for custom lowering!");
5741
5742 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5743
5744 EVT DestVecType;
5745 if (VT == MVT::v4f32)
5746 DestVecType = MVT::v4i32;
5747 else if (VT == MVT::v4f16 && HasFullFP16)
5748 DestVecType = MVT::v4i16;
5749 else if (VT == MVT::v8f16 && HasFullFP16)
5750 DestVecType = MVT::v8i16;
5751 else
5752 return DAG.UnrollVectorOp(Op.getNode());
5753
5754 unsigned CastOpc;
5755 unsigned Opc;
5756 switch (Op.getOpcode()) {
5757 default: llvm_unreachable("Invalid opcode!");
5758 case ISD::SINT_TO_FP:
5759 CastOpc = ISD::SIGN_EXTEND;
5761 break;
5762 case ISD::UINT_TO_FP:
5763 CastOpc = ISD::ZERO_EXTEND;
5765 break;
5766 }
5767
5768 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5769 return DAG.getNode(Opc, dl, VT, Op);
5770}
5771
5772SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5773 EVT VT = Op.getValueType();
5774 if (VT.isVector())
5775 return LowerVectorINT_TO_FP(Op, DAG);
5776 if (isUnsupportedFloatingType(VT)) {
5777 RTLIB::Libcall LC;
5778 if (Op.getOpcode() == ISD::SINT_TO_FP)
5779 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5780 Op.getValueType());
5781 else
5782 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5783 Op.getValueType());
5784 MakeLibCallOptions CallOptions;
5785 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5786 CallOptions, SDLoc(Op)).first;
5787 }
5788
5789 return Op;
5790}
5791
5792SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5793 // Implement fcopysign with a fabs and a conditional fneg.
5794 SDValue Tmp0 = Op.getOperand(0);
5795 SDValue Tmp1 = Op.getOperand(1);
5796 SDLoc dl(Op);
5797 EVT VT = Op.getValueType();
5798 EVT SrcVT = Tmp1.getValueType();
5799 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5800 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5801 bool UseNEON = !InGPR && Subtarget->hasNEON();
5802
5803 if (UseNEON) {
5804 // Use VBSL to copy the sign bit.
5805 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5806 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5807 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5808 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5809 if (VT == MVT::f64)
5810 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5811 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5812 DAG.getConstant(32, dl, MVT::i32));
5813 else /*if (VT == MVT::f32)*/
5814 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5815 if (SrcVT == MVT::f32) {
5816 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5817 if (VT == MVT::f64)
5818 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5819 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5820 DAG.getConstant(32, dl, MVT::i32));
5821 } else if (VT == MVT::f32)
5822 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5823 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5824 DAG.getConstant(32, dl, MVT::i32));
5825 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5826 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5827
5829 dl, MVT::i32);
5830 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5831 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5832 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5833
5834 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5835 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5836 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5837 if (VT == MVT::f32) {
5838 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5839 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5840 DAG.getConstant(0, dl, MVT::i32));
5841 } else {
5842 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5843 }
5844
5845 return Res;
5846 }
5847
5848 // Bitcast operand 1 to i32.
5849 if (SrcVT == MVT::f64)
5850 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5851 Tmp1).getValue(1);
5852 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5853
5854 // Or in the signbit with integer operations.
5855 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5856 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5857 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5858 if (VT == MVT::f32) {
5859 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5860 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5862 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5863 }
5864
5865 // f64: Or the high part with signbit and then combine two parts.
5866 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5867 Tmp0);
5868 SDValue Lo = Tmp0.getValue(0);
5869 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5870 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5871 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5872}
5873
5874SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5875 MachineFunction &MF = DAG.getMachineFunction();
5876 MachineFrameInfo &MFI = MF.getFrameInfo();
5877 MFI.setReturnAddressIsTaken(true);
5878
5879 EVT VT = Op.getValueType();
5880 SDLoc dl(Op);
5881 unsigned Depth = Op.getConstantOperandVal(0);
5882 if (Depth) {
5883 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5884 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5885 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5886 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5887 MachinePointerInfo());
5888 }
5889
5890 // Return LR, which contains the return address. Mark it an implicit live-in.
5891 Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5892 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5893}
5894
5895SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5896 const ARMBaseRegisterInfo &ARI =
5897 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5898 MachineFunction &MF = DAG.getMachineFunction();
5899 MachineFrameInfo &MFI = MF.getFrameInfo();
5900 MFI.setFrameAddressIsTaken(true);
5901
5902 EVT VT = Op.getValueType();
5903 SDLoc dl(Op); // FIXME probably not meaningful
5904 unsigned Depth = Op.getConstantOperandVal(0);
5905 Register FrameReg = ARI.getFrameRegister(MF);
5906 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5907 while (Depth--)
5908 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5909 MachinePointerInfo());
5910 return FrameAddr;
5911}
5912
5913// FIXME? Maybe this could be a TableGen attribute on some registers and
5914// this table could be generated automatically from RegInfo.
5915Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5916 const MachineFunction &MF) const {
5917 return StringSwitch<Register>(RegName)
5918 .Case("sp", ARM::SP)
5919 .Default(Register());
5920}
5921
5922// Result is 64 bit value so split into two 32 bit values and return as a
5923// pair of values.
5925 SelectionDAG &DAG) {
5926 SDLoc DL(N);
5927
5928 // This function is only supposed to be called for i64 type destination.
5929 assert(N->getValueType(0) == MVT::i64
5930 && "ExpandREAD_REGISTER called for non-i64 type result.");
5931
5933 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5934 N->getOperand(0),
5935 N->getOperand(1));
5936
5937 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5938 Read.getValue(1)));
5939 Results.push_back(Read.getValue(2)); // Chain
5940}
5941
5942/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5943/// When \p DstVT, the destination type of \p BC, is on the vector
5944/// register bank and the source of bitcast, \p Op, operates on the same bank,
5945/// it might be possible to combine them, such that everything stays on the
5946/// vector register bank.
5947/// \p return The node that would replace \p BT, if the combine
5948/// is possible.
5950 SelectionDAG &DAG) {
5951 SDValue Op = BC->getOperand(0);
5952 EVT DstVT = BC->getValueType(0);
5953
5954 // The only vector instruction that can produce a scalar (remember,
5955 // since the bitcast was about to be turned into VMOVDRR, the source
5956 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5957 // Moreover, we can do this combine only if there is one use.
5958 // Finally, if the destination type is not a vector, there is not
5959 // much point on forcing everything on the vector bank.
5960 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5961 !Op.hasOneUse())
5962 return SDValue();
5963
5964 // If the index is not constant, we will introduce an additional
5965 // multiply that will stick.
5966 // Give up in that case.
5967 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5968 if (!Index)
5969 return SDValue();
5970 unsigned DstNumElt = DstVT.getVectorNumElements();
5971
5972 // Compute the new index.
5973 const APInt &APIntIndex = Index->getAPIntValue();
5974 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5975 NewIndex *= APIntIndex;
5976 // Check if the new constant index fits into i32.
5977 if (NewIndex.getBitWidth() > 32)
5978 return SDValue();
5979
5980 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5981 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5982 SDLoc dl(Op);
5983 SDValue ExtractSrc = Op.getOperand(0);
5984 EVT VecVT = EVT::getVectorVT(
5985 *DAG.getContext(), DstVT.getScalarType(),
5986 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5987 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5988 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5989 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5990}
5991
5992/// ExpandBITCAST - If the target supports VFP, this function is called to
5993/// expand a bit convert where either the source or destination type is i64 to
5994/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5995/// operand type is illegal (e.g., v2f32 for a target that doesn't support
5996/// vectors), since the legalizer won't know what to do with that.
5997SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5998 const ARMSubtarget *Subtarget) const {
5999 SDLoc dl(N);
6000 SDValue Op = N->getOperand(0);
6001
6002 // This function is only supposed to be called for i16 and i64 types, either
6003 // as the source or destination of the bit convert.
6004 EVT SrcVT = Op.getValueType();
6005 EVT DstVT = N->getValueType(0);
6006
6007 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6008 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6009 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6010 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6011
6012 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6013 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
6014 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
6015 Op = DAG.getBitcast(MVT::f16, Op);
6016 return DAG.getNode(
6017 ISD::TRUNCATE, SDLoc(N), DstVT,
6018 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6019 }
6020
6021 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6022 return SDValue();
6023
6024 // Turn i64->f64 into VMOVDRR.
6025 if (SrcVT == MVT::i64 && isTypeLegal(DstVT)) {
6026 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6027 // if we can combine the bitcast with its source.
6029 return Val;
6030 SDValue Lo, Hi;
6031 std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6032 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6033 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6034 }
6035
6036 // Turn f64->i64 into VMOVRRD.
6037 if (DstVT == MVT::i64 && isTypeLegal(SrcVT)) {
6038 SDValue Cvt;
6039 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6040 SrcVT.getVectorNumElements() > 1)
6041 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6042 DAG.getVTList(MVT::i32, MVT::i32),
6043 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6044 else
6045 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6046 DAG.getVTList(MVT::i32, MVT::i32), Op);
6047 // Merge the pieces into a single i64 value.
6048 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6049 }
6050
6051 return SDValue();
6052}
6053
6054/// getZeroVector - Returns a vector of specified type with all zero elements.
6055/// Zero vectors are used to represent vector negation and in those cases
6056/// will be implemented with the NEON VNEG instruction. However, VNEG does
6057/// not support i64 elements, so sometimes the zero vectors will need to be
6058/// explicitly constructed. Regardless, use a canonical VMOV to create the
6059/// zero vector.
6060static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6061 assert(VT.isVector() && "Expected a vector type");
6062 // The canonical modified immediate encoding of a zero vector is....0!
6063 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6064 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6065 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6066 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6067}
6068
6069/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6070/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6071SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6072 SelectionDAG &DAG) const {
6073 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6074 EVT VT = Op.getValueType();
6075 unsigned VTBits = VT.getSizeInBits();
6076 SDLoc dl(Op);
6077 SDValue ShOpLo = Op.getOperand(0);
6078 SDValue ShOpHi = Op.getOperand(1);
6079 SDValue ShAmt = Op.getOperand(2);
6080 SDValue ARMcc;
6081 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6082
6083 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6084
6085 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6086 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6087 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6088 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6089 DAG.getConstant(VTBits, dl, MVT::i32));
6090 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6091 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6092 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6093 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6094 ISD::SETGE, ARMcc, DAG, dl);
6095 SDValue Lo =
6096 DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, ARMcc, CmpLo);
6097
6098 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6099 SDValue HiBigShift = Opc == ISD::SRA
6100 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6101 DAG.getConstant(VTBits - 1, dl, VT))
6102 : DAG.getConstant(0, dl, VT);
6103 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6104 ISD::SETGE, ARMcc, DAG, dl);
6105 SDValue Hi =
6106 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6107
6108 SDValue Ops[2] = { Lo, Hi };
6109 return DAG.getMergeValues(Ops, dl);
6110}
6111
6112/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6113/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6114SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6115 SelectionDAG &DAG) const {
6116 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6117 EVT VT = Op.getValueType();
6118 unsigned VTBits = VT.getSizeInBits();
6119 SDLoc dl(Op);
6120 SDValue ShOpLo = Op.getOperand(0);
6121 SDValue ShOpHi = Op.getOperand(1);
6122 SDValue ShAmt = Op.getOperand(2);
6123 SDValue ARMcc;
6124
6125 assert(Op.getOpcode() == ISD::SHL_PARTS);
6126 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6127 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6128 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6129 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6130 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6131
6132 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6133 DAG.getConstant(VTBits, dl, MVT::i32));
6134 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6135 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6136 ISD::SETGE, ARMcc, DAG, dl);
6137 SDValue Hi =
6138 DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6139
6140 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6141 ISD::SETGE, ARMcc, DAG, dl);
6142 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6143 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6144 DAG.getConstant(0, dl, VT), ARMcc, CmpLo);
6145
6146 SDValue Ops[2] = { Lo, Hi };
6147 return DAG.getMergeValues(Ops, dl);
6148}
6149
6150SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6151 SelectionDAG &DAG) const {
6152 // The rounding mode is in bits 23:22 of the FPSCR.
6153 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6154 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6155 // so that the shift + and get folded into a bitfield extract.
6156 SDLoc dl(Op);
6157 SDValue Chain = Op.getOperand(0);
6158 SDValue Ops[] = {Chain,
6159 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6160
6161 SDValue FPSCR =
6162 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6163 Chain = FPSCR.getValue(1);
6164 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6165 DAG.getConstant(1U << 22, dl, MVT::i32));
6166 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6167 DAG.getConstant(22, dl, MVT::i32));
6168 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6169 DAG.getConstant(3, dl, MVT::i32));
6170 return DAG.getMergeValues({And, Chain}, dl);
6171}
6172
6173SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6174 SelectionDAG &DAG) const {
6175 SDLoc DL(Op);
6176 SDValue Chain = Op->getOperand(0);
6177 SDValue RMValue = Op->getOperand(1);
6178
6179 // The rounding mode is in bits 23:22 of the FPSCR.
6180 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6181 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6182 // ((arg - 1) & 3) << 22).
6183 //
6184 // It is expected that the argument of llvm.set.rounding is within the
6185 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6186 // responsibility of the code generated llvm.set.rounding to ensure this
6187 // condition.
6188
6189 // Calculate new value of FPSCR[23:22].
6190 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6191 DAG.getConstant(1, DL, MVT::i32));
6192 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6193 DAG.getConstant(0x3, DL, MVT::i32));
6194 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6195 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6196
6197 // Get current value of FPSCR.
6198 SDValue Ops[] = {Chain,
6199 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6200 SDValue FPSCR =
6201 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6202 Chain = FPSCR.getValue(1);
6203 FPSCR = FPSCR.getValue(0);
6204
6205 // Put new rounding mode into FPSCR[23:22].
6206 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6207 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6208 DAG.getConstant(RMMask, DL, MVT::i32));
6209 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6210 SDValue Ops2[] = {
6211 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6212 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6213}
6214
6215SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6216 SelectionDAG &DAG) const {
6217 SDLoc DL(Op);
6218 SDValue Chain = Op->getOperand(0);
6219 SDValue Mode = Op->getOperand(1);
6220
6221 // Generate nodes to build:
6222 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6223 SDValue Ops[] = {Chain,
6224 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6225 SDValue FPSCR =
6226 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6227 Chain = FPSCR.getValue(1);
6228 FPSCR = FPSCR.getValue(0);
6229
6230 SDValue FPSCRMasked =
6231 DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6232 DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6233 SDValue InputMasked =
6234 DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6235 DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6236 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6237
6238 SDValue Ops2[] = {
6239 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6240 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6241}
6242
6243SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6244 SelectionDAG &DAG) const {
6245 SDLoc DL(Op);
6246 SDValue Chain = Op->getOperand(0);
6247
6248 // To get the default FP mode all control bits are cleared:
6249 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6250 SDValue Ops[] = {Chain,
6251 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6252 SDValue FPSCR =
6253 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6254 Chain = FPSCR.getValue(1);
6255 FPSCR = FPSCR.getValue(0);
6256
6257 SDValue FPSCRMasked = DAG.getNode(
6258 ISD::AND, DL, MVT::i32, FPSCR,
6260 SDValue Ops2[] = {Chain,
6261 DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6262 FPSCRMasked};
6263 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6264}
6265
6267 const ARMSubtarget *ST) {
6268 SDLoc dl(N);
6269 EVT VT = N->getValueType(0);
6270 if (VT.isVector() && ST->hasNEON()) {
6271
6272 // Compute the least significant set bit: LSB = X & -X
6273 SDValue X = N->getOperand(0);
6274 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6275 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6276
6277 EVT ElemTy = VT.getVectorElementType();
6278
6279 if (ElemTy == MVT::i8) {
6280 // Compute with: cttz(x) = ctpop(lsb - 1)
6281 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6282 DAG.getTargetConstant(1, dl, ElemTy));
6283 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6284 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6285 }
6286
6287 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6288 (N->getOpcode() == ISD::CTTZ_ZERO_POISON)) {
6289 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6290 unsigned NumBits = ElemTy.getSizeInBits();
6291 SDValue WidthMinus1 =
6292 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6293 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6294 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6295 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6296 }
6297
6298 // Compute with: cttz(x) = ctpop(lsb - 1)
6299
6300 // Compute LSB - 1.
6301 SDValue Bits;
6302 if (ElemTy == MVT::i64) {
6303 // Load constant 0xffff'ffff'ffff'ffff to register.
6304 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6305 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6306 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6307 } else {
6308 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6309 DAG.getTargetConstant(1, dl, ElemTy));
6310 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6311 }
6312 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6313 }
6314
6315 if (!ST->hasV6T2Ops())
6316 return SDValue();
6317
6318 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6319 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6320}
6321
6323 const ARMSubtarget *ST) {
6324 EVT VT = N->getValueType(0);
6325 SDLoc DL(N);
6326
6327 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6328 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6329 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6330 "Unexpected type for custom ctpop lowering");
6331
6332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6333 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6334 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6335 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6336
6337 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6338 unsigned EltSize = 8;
6339 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6340 while (EltSize != VT.getScalarSizeInBits()) {
6342 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6343 TLI.getPointerTy(DAG.getDataLayout())));
6344 Ops.push_back(Res);
6345
6346 EltSize *= 2;
6347 NumElts /= 2;
6348 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6349 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6350 }
6351
6352 return Res;
6353}
6354
6355/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6356/// operand of a vector shift operation, where all the elements of the
6357/// build_vector must have the same constant integer value.
6358static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6359 // Ignore bit_converts.
6360 while (Op.getOpcode() == ISD::BITCAST)
6361 Op = Op.getOperand(0);
6363 APInt SplatBits, SplatUndef;
6364 unsigned SplatBitSize;
6365 bool HasAnyUndefs;
6366 if (!BVN ||
6367 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6368 ElementBits) ||
6369 SplatBitSize > ElementBits)
6370 return false;
6371 Cnt = SplatBits.getSExtValue();
6372 return true;
6373}
6374
6375/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6376/// operand of a vector shift left operation. That value must be in the range:
6377/// 0 <= Value < ElementBits for a left shift; or
6378/// 0 <= Value <= ElementBits for a long left shift.
6379static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6380 assert(VT.isVector() && "vector shift count is not a vector type");
6381 int64_t ElementBits = VT.getScalarSizeInBits();
6382 if (!getVShiftImm(Op, ElementBits, Cnt))
6383 return false;
6384 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6385}
6386
6387/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6388/// operand of a vector shift right operation. For a shift opcode, the value
6389/// is positive, but for an intrinsic the value count must be negative. The
6390/// absolute value must be in the range:
6391/// 1 <= |Value| <= ElementBits for a right shift; or
6392/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6393static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6394 int64_t &Cnt) {
6395 assert(VT.isVector() && "vector shift count is not a vector type");
6396 int64_t ElementBits = VT.getScalarSizeInBits();
6397 if (!getVShiftImm(Op, ElementBits, Cnt))
6398 return false;
6399 if (!isIntrinsic)
6400 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6401 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6402 Cnt = -Cnt;
6403 return true;
6404 }
6405 return false;
6406}
6407
6409 const ARMSubtarget *ST) {
6410 EVT VT = N->getValueType(0);
6411 SDLoc dl(N);
6412 int64_t Cnt;
6413
6414 if (!VT.isVector())
6415 return SDValue();
6416
6417 // We essentially have two forms here. Shift by an immediate and shift by a
6418 // vector register (there are also shift by a gpr, but that is just handled
6419 // with a tablegen pattern). We cannot easily match shift by an immediate in
6420 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6421 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6422 // signed or unsigned, and a negative shift indicates a shift right).
6423 if (N->getOpcode() == ISD::SHL) {
6424 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6425 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6426 DAG.getConstant(Cnt, dl, MVT::i32));
6427 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6428 N->getOperand(1));
6429 }
6430
6431 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6432 "unexpected vector shift opcode");
6433
6434 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6435 unsigned VShiftOpc =
6436 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6437 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6438 DAG.getConstant(Cnt, dl, MVT::i32));
6439 }
6440
6441 // Other right shifts we don't have operations for (we use a shift left by a
6442 // negative number).
6443 EVT ShiftVT = N->getOperand(1).getValueType();
6444 SDValue NegatedCount = DAG.getNode(
6445 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6446 unsigned VShiftOpc =
6447 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6448 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6449}
6450
6452 const ARMSubtarget *ST) {
6453 EVT VT = N->getValueType(0);
6454 SDLoc dl(N);
6455
6456 // We can get here for a node like i32 = ISD::SHL i32, i64
6457 if (VT != MVT::i64)
6458 return SDValue();
6459
6460 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6461 N->getOpcode() == ISD::SHL) &&
6462 "Unknown shift to lower!");
6463
6464 unsigned ShOpc = N->getOpcode();
6465 if (ST->hasMVEIntegerOps()) {
6466 SDValue ShAmt = N->getOperand(1);
6467 unsigned ShPartsOpc = ARMISD::LSLL;
6469
6470 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6471 // then do the default optimisation
6472 if ((!Con && ShAmt->getValueType(0).getSizeInBits() > 64) ||
6473 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(32))))
6474 return SDValue();
6475
6476 // Extract the lower 32 bits of the shift amount if it's not an i32
6477 if (ShAmt->getValueType(0) != MVT::i32)
6478 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6479
6480 if (ShOpc == ISD::SRL) {
6481 if (!Con)
6482 // There is no t2LSRLr instruction so negate and perform an lsll if the
6483 // shift amount is in a register, emulating a right shift.
6484 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6485 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6486 else
6487 // Else generate an lsrl on the immediate shift amount
6488 ShPartsOpc = ARMISD::LSRL;
6489 } else if (ShOpc == ISD::SRA)
6490 ShPartsOpc = ARMISD::ASRL;
6491
6492 // Split Lower/Upper 32 bits of the destination/source
6493 SDValue Lo, Hi;
6494 std::tie(Lo, Hi) =
6495 DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6496 // Generate the shift operation as computed above
6497 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6498 ShAmt);
6499 // The upper 32 bits come from the second return value of lsll
6500 Hi = SDValue(Lo.getNode(), 1);
6501 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6502 }
6503
6504 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6505 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6506 return SDValue();
6507
6508 // If we are in thumb mode, we don't have RRX.
6509 if (ST->isThumb1Only())
6510 return SDValue();
6511
6512 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6513 SDValue Lo, Hi;
6514 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6515
6516 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6517 // captures the shifted out bit into a carry flag.
6518 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6519 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, FlagsVT), Hi);
6520
6521 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6522 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6523
6524 // Merge the pieces into a single i64 value.
6525 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6526}
6527
6529 const ARMSubtarget *ST) {
6530 bool Invert = false;
6531 bool Swap = false;
6532 unsigned Opc = ARMCC::AL;
6533
6534 SDValue Op0 = Op.getOperand(0);
6535 SDValue Op1 = Op.getOperand(1);
6536 SDValue CC = Op.getOperand(2);
6537 EVT VT = Op.getValueType();
6538 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6539 SDLoc dl(Op);
6540
6541 EVT CmpVT;
6542 if (ST->hasNEON())
6544 else {
6545 assert(ST->hasMVEIntegerOps() &&
6546 "No hardware support for integer vector comparison!");
6547
6548 if (Op.getValueType().getVectorElementType() != MVT::i1)
6549 return SDValue();
6550
6551 // Make sure we expand floating point setcc to scalar if we do not have
6552 // mve.fp, so that we can handle them from there.
6553 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6554 return SDValue();
6555
6556 CmpVT = VT;
6557 }
6558
6559 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6560 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6561 // Special-case integer 64-bit equality comparisons. They aren't legal,
6562 // but they can be lowered with a few vector instructions.
6563 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6564 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6565 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6566 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6567 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6568 DAG.getCondCode(ISD::SETEQ));
6569 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6570 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6571 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6572 if (SetCCOpcode == ISD::SETNE)
6573 Merged = DAG.getNOT(dl, Merged, CmpVT);
6574 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6575 return Merged;
6576 }
6577
6578 if (CmpVT.getVectorElementType() == MVT::i64)
6579 // 64-bit comparisons are not legal in general.
6580 return SDValue();
6581
6582 if (Op1.getValueType().isFloatingPoint()) {
6583 switch (SetCCOpcode) {
6584 default: llvm_unreachable("Illegal FP comparison");
6585 case ISD::SETUNE:
6586 case ISD::SETNE:
6587 if (ST->hasMVEFloatOps()) {
6588 Opc = ARMCC::NE; break;
6589 } else {
6590 Invert = true; [[fallthrough]];
6591 }
6592 case ISD::SETOEQ:
6593 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6594 case ISD::SETOLT:
6595 case ISD::SETLT: Swap = true; [[fallthrough]];
6596 case ISD::SETOGT:
6597 case ISD::SETGT: Opc = ARMCC::GT; break;
6598 case ISD::SETOLE:
6599 case ISD::SETLE: Swap = true; [[fallthrough]];
6600 case ISD::SETOGE:
6601 case ISD::SETGE: Opc = ARMCC::GE; break;
6602 case ISD::SETUGE: Swap = true; [[fallthrough]];
6603 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6604 case ISD::SETUGT: Swap = true; [[fallthrough]];
6605 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6606 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6607 case ISD::SETONE: {
6608 // Expand this to (OLT | OGT).
6609 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6610 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6611 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6612 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6613 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6614 if (Invert)
6615 Result = DAG.getNOT(dl, Result, VT);
6616 return Result;
6617 }
6618 case ISD::SETUO: Invert = true; [[fallthrough]];
6619 case ISD::SETO: {
6620 // Expand this to (OLT | OGE).
6621 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6622 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6623 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6624 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6625 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6626 if (Invert)
6627 Result = DAG.getNOT(dl, Result, VT);
6628 return Result;
6629 }
6630 }
6631 } else {
6632 // Integer comparisons.
6633 switch (SetCCOpcode) {
6634 default: llvm_unreachable("Illegal integer comparison");
6635 case ISD::SETNE:
6636 if (ST->hasMVEIntegerOps()) {
6637 Opc = ARMCC::NE; break;
6638 } else {
6639 Invert = true; [[fallthrough]];
6640 }
6641 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6642 case ISD::SETLT: Swap = true; [[fallthrough]];
6643 case ISD::SETGT: Opc = ARMCC::GT; break;
6644 case ISD::SETLE: Swap = true; [[fallthrough]];
6645 case ISD::SETGE: Opc = ARMCC::GE; break;
6646 case ISD::SETULT: Swap = true; [[fallthrough]];
6647 case ISD::SETUGT: Opc = ARMCC::HI; break;
6648 case ISD::SETULE: Swap = true; [[fallthrough]];
6649 case ISD::SETUGE: Opc = ARMCC::HS; break;
6650 }
6651
6652 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6653 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6654 SDValue AndOp;
6656 AndOp = Op0;
6657 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6658 AndOp = Op1;
6659
6660 // Ignore bitconvert.
6661 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6662 AndOp = AndOp.getOperand(0);
6663
6664 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6665 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6666 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6667 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6668 if (!Invert)
6669 Result = DAG.getNOT(dl, Result, VT);
6670 return Result;
6671 }
6672 }
6673 }
6674
6675 if (Swap)
6676 std::swap(Op0, Op1);
6677
6678 // If one of the operands is a constant vector zero, attempt to fold the
6679 // comparison to a specialized compare-against-zero form.
6681 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6682 Opc == ARMCC::NE)) {
6683 if (Opc == ARMCC::GE)
6684 Opc = ARMCC::LE;
6685 else if (Opc == ARMCC::GT)
6686 Opc = ARMCC::LT;
6687 std::swap(Op0, Op1);
6688 }
6689
6690 SDValue Result;
6692 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6693 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6694 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
6695 DAG.getConstant(Opc, dl, MVT::i32));
6696 else
6697 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6698 DAG.getConstant(Opc, dl, MVT::i32));
6699
6700 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6701
6702 if (Invert)
6703 Result = DAG.getNOT(dl, Result, VT);
6704
6705 return Result;
6706}
6707
6709 SDValue LHS = Op.getOperand(0);
6710 SDValue RHS = Op.getOperand(1);
6711
6712 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6713
6714 SDValue Carry = Op.getOperand(2);
6715 SDValue Cond = Op.getOperand(3);
6716 SDLoc DL(Op);
6717
6718 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6719 // have to invert the carry first.
6720 SDValue InvCarry = valueToCarryFlag(Carry, DAG, true);
6721
6722 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6723 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, InvCarry);
6724
6725 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6726 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6727 SDValue ARMcc = DAG.getConstant(
6728 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6729 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6730 Cmp.getValue(1));
6731}
6732
6733/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6734/// valid vector constant for a NEON or MVE instruction with a "modified
6735/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6736static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6737 unsigned SplatBitSize, SelectionDAG &DAG,
6738 const SDLoc &dl, EVT &VT, EVT VectorVT,
6739 VMOVModImmType type) {
6740 unsigned OpCmode, Imm;
6741 bool is128Bits = VectorVT.is128BitVector();
6742
6743 // SplatBitSize is set to the smallest size that splats the vector, so a
6744 // zero vector will always have SplatBitSize == 8. However, NEON modified
6745 // immediate instructions others than VMOV do not support the 8-bit encoding
6746 // of a zero vector, and the default encoding of zero is supposed to be the
6747 // 32-bit version.
6748 if (SplatBits == 0)
6749 SplatBitSize = 32;
6750
6751 switch (SplatBitSize) {
6752 case 8:
6753 if (type != VMOVModImm)
6754 return SDValue();
6755 // Any 1-byte value is OK. Op=0, Cmode=1110.
6756 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6757 OpCmode = 0xe;
6758 Imm = SplatBits;
6759 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6760 break;
6761
6762 case 16:
6763 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6764 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6765 if ((SplatBits & ~0xff) == 0) {
6766 // Value = 0x00nn: Op=x, Cmode=100x.
6767 OpCmode = 0x8;
6768 Imm = SplatBits;
6769 break;
6770 }
6771 if ((SplatBits & ~0xff00) == 0) {
6772 // Value = 0xnn00: Op=x, Cmode=101x.
6773 OpCmode = 0xa;
6774 Imm = SplatBits >> 8;
6775 break;
6776 }
6777 return SDValue();
6778
6779 case 32:
6780 // NEON's 32-bit VMOV supports splat values where:
6781 // * only one byte is nonzero, or
6782 // * the least significant byte is 0xff and the second byte is nonzero, or
6783 // * the least significant 2 bytes are 0xff and the third is nonzero.
6784 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6785 if ((SplatBits & ~0xff) == 0) {
6786 // Value = 0x000000nn: Op=x, Cmode=000x.
6787 OpCmode = 0;
6788 Imm = SplatBits;
6789 break;
6790 }
6791 if ((SplatBits & ~0xff00) == 0) {
6792 // Value = 0x0000nn00: Op=x, Cmode=001x.
6793 OpCmode = 0x2;
6794 Imm = SplatBits >> 8;
6795 break;
6796 }
6797 if ((SplatBits & ~0xff0000) == 0) {
6798 // Value = 0x00nn0000: Op=x, Cmode=010x.
6799 OpCmode = 0x4;
6800 Imm = SplatBits >> 16;
6801 break;
6802 }
6803 if ((SplatBits & ~0xff000000) == 0) {
6804 // Value = 0xnn000000: Op=x, Cmode=011x.
6805 OpCmode = 0x6;
6806 Imm = SplatBits >> 24;
6807 break;
6808 }
6809
6810 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6811 if (type == OtherModImm) return SDValue();
6812
6813 if ((SplatBits & ~0xffff) == 0 &&
6814 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6815 // Value = 0x0000nnff: Op=x, Cmode=1100.
6816 OpCmode = 0xc;
6817 Imm = SplatBits >> 8;
6818 break;
6819 }
6820
6821 // cmode == 0b1101 is not supported for MVE VMVN
6822 if (type == MVEVMVNModImm)
6823 return SDValue();
6824
6825 if ((SplatBits & ~0xffffff) == 0 &&
6826 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6827 // Value = 0x00nnffff: Op=x, Cmode=1101.
6828 OpCmode = 0xd;
6829 Imm = SplatBits >> 16;
6830 break;
6831 }
6832
6833 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6834 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6835 // VMOV.I32. A (very) minor optimization would be to replicate the value
6836 // and fall through here to test for a valid 64-bit splat. But, then the
6837 // caller would also need to check and handle the change in size.
6838 return SDValue();
6839
6840 case 64: {
6841 if (type != VMOVModImm)
6842 return SDValue();
6843 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6844 uint64_t BitMask = 0xff;
6845 unsigned ImmMask = 1;
6846 Imm = 0;
6847 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6848 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6849 Imm |= ImmMask;
6850 } else if ((SplatBits & BitMask) != 0) {
6851 return SDValue();
6852 }
6853 BitMask <<= 8;
6854 ImmMask <<= 1;
6855 }
6856
6857 // Op=1, Cmode=1110.
6858 OpCmode = 0x1e;
6859 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6860 break;
6861 }
6862
6863 default:
6864 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6865 }
6866
6867 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6868 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6869}
6870
6871SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6872 const ARMSubtarget *ST) const {
6873 EVT VT = Op.getValueType();
6874 bool IsDouble = (VT == MVT::f64);
6875 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6876 const APFloat &FPVal = CFP->getValueAPF();
6877
6878 // Prevent floating-point constants from using literal loads
6879 // when execute-only is enabled.
6880 if (ST->genExecuteOnly()) {
6881 // We shouldn't trigger this for v6m execute-only
6882 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
6883 "Unexpected architecture");
6884
6885 // If we can represent the constant as an immediate, don't lower it
6886 if (isFPImmLegal(FPVal, VT))
6887 return Op;
6888 // Otherwise, construct as integer, and move to float register
6889 APInt INTVal = FPVal.bitcastToAPInt();
6890 SDLoc DL(CFP);
6891 switch (VT.getSimpleVT().SimpleTy) {
6892 default:
6893 llvm_unreachable("Unknown floating point type!");
6894 break;
6895 case MVT::f64: {
6896 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6897 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6898 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6899 }
6900 case MVT::f32:
6901 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6902 DAG.getConstant(INTVal, DL, MVT::i32));
6903 }
6904 }
6905
6906 if (!ST->hasVFP3Base())
6907 return SDValue();
6908
6909 // Use the default (constant pool) lowering for double constants when we have
6910 // an SP-only FPU
6911 if (IsDouble && !Subtarget->hasFP64())
6912 return SDValue();
6913
6914 // Try splatting with a VMOV.f32...
6915 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6916
6917 if (ImmVal != -1) {
6918 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6919 // We have code in place to select a valid ConstantFP already, no need to
6920 // do any mangling.
6921 return Op;
6922 }
6923
6924 // It's a float and we are trying to use NEON operations where
6925 // possible. Lower it to a splat followed by an extract.
6926 SDLoc DL(Op);
6927 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6928 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6929 NewVal);
6930 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6931 DAG.getConstant(0, DL, MVT::i32));
6932 }
6933
6934 // The rest of our options are NEON only, make sure that's allowed before
6935 // proceeding..
6936 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6937 return SDValue();
6938
6939 EVT VMovVT;
6940 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6941
6942 // It wouldn't really be worth bothering for doubles except for one very
6943 // important value, which does happen to match: 0.0. So make sure we don't do
6944 // anything stupid.
6945 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6946 return SDValue();
6947
6948 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6949 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6950 VMovVT, VT, VMOVModImm);
6951 if (NewVal != SDValue()) {
6952 SDLoc DL(Op);
6953 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6954 NewVal);
6955 if (IsDouble)
6956 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6957
6958 // It's a float: cast and extract a vector element.
6959 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6960 VecConstant);
6961 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6962 DAG.getConstant(0, DL, MVT::i32));
6963 }
6964
6965 // Finally, try a VMVN.i32
6966 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6967 VT, VMVNModImm);
6968 if (NewVal != SDValue()) {
6969 SDLoc DL(Op);
6970 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6971
6972 if (IsDouble)
6973 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6974
6975 // It's a float: cast and extract a vector element.
6976 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6977 VecConstant);
6978 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6979 DAG.getConstant(0, DL, MVT::i32));
6980 }
6981
6982 return SDValue();
6983}
6984
6985// check if an VEXT instruction can handle the shuffle mask when the
6986// vector sources of the shuffle are the same.
6987static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6988 unsigned NumElts = VT.getVectorNumElements();
6989
6990 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6991 if (M[0] < 0)
6992 return false;
6993
6994 Imm = M[0];
6995
6996 // If this is a VEXT shuffle, the immediate value is the index of the first
6997 // element. The other shuffle indices must be the successive elements after
6998 // the first one.
6999 unsigned ExpectedElt = Imm;
7000 for (unsigned i = 1; i < NumElts; ++i) {
7001 // Increment the expected index. If it wraps around, just follow it
7002 // back to index zero and keep going.
7003 ++ExpectedElt;
7004 if (ExpectedElt == NumElts)
7005 ExpectedElt = 0;
7006
7007 if (M[i] < 0) continue; // ignore UNDEF indices
7008 if (ExpectedElt != static_cast<unsigned>(M[i]))
7009 return false;
7010 }
7011
7012 return true;
7013}
7014
7015static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7016 bool &ReverseVEXT, unsigned &Imm) {
7017 unsigned NumElts = VT.getVectorNumElements();
7018 ReverseVEXT = false;
7019
7020 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7021 if (M[0] < 0)
7022 return false;
7023
7024 Imm = M[0];
7025
7026 // If this is a VEXT shuffle, the immediate value is the index of the first
7027 // element. The other shuffle indices must be the successive elements after
7028 // the first one.
7029 unsigned ExpectedElt = Imm;
7030 for (unsigned i = 1; i < NumElts; ++i) {
7031 // Increment the expected index. If it wraps around, it may still be
7032 // a VEXT but the source vectors must be swapped.
7033 ExpectedElt += 1;
7034 if (ExpectedElt == NumElts * 2) {
7035 ExpectedElt = 0;
7036 ReverseVEXT = true;
7037 }
7038
7039 if (M[i] < 0) continue; // ignore UNDEF indices
7040 if (ExpectedElt != static_cast<unsigned>(M[i]))
7041 return false;
7042 }
7043
7044 // Adjust the index value if the source operands will be swapped.
7045 if (ReverseVEXT)
7046 Imm -= NumElts;
7047
7048 return true;
7049}
7050
7051static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7052 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7053 // range, then 0 is placed into the resulting vector. So pretty much any mask
7054 // of 8 elements can work here.
7055 return VT == MVT::v8i8 && M.size() == 8;
7056}
7057
7058static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7059 unsigned Index) {
7060 if (Mask.size() == Elements * 2)
7061 return Index / Elements;
7062 return Mask[Index] == 0 ? 0 : 1;
7063}
7064
7065// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7066// checking that pairs of elements in the shuffle mask represent the same index
7067// in each vector, incrementing the expected index by 2 at each step.
7068// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7069// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7070// v2={e,f,g,h}
7071// WhichResult gives the offset for each element in the mask based on which
7072// of the two results it belongs to.
7073//
7074// The transpose can be represented either as:
7075// result1 = shufflevector v1, v2, result1_shuffle_mask
7076// result2 = shufflevector v1, v2, result2_shuffle_mask
7077// where v1/v2 and the shuffle masks have the same number of elements
7078// (here WhichResult (see below) indicates which result is being checked)
7079//
7080// or as:
7081// results = shufflevector v1, v2, shuffle_mask
7082// where both results are returned in one vector and the shuffle mask has twice
7083// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7084// want to check the low half and high half of the shuffle mask as if it were
7085// the other case
7086static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7087 unsigned EltSz = VT.getScalarSizeInBits();
7088 if (EltSz == 64)
7089 return false;
7090
7091 unsigned NumElts = VT.getVectorNumElements();
7092 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7093 return false;
7094
7095 // If the mask is twice as long as the input vector then we need to check the
7096 // upper and lower parts of the mask with a matching value for WhichResult
7097 // FIXME: A mask with only even values will be rejected in case the first
7098 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7099 // M[0] is used to determine WhichResult
7100 for (unsigned i = 0; i < M.size(); i += NumElts) {
7101 WhichResult = SelectPairHalf(NumElts, M, i);
7102 for (unsigned j = 0; j < NumElts; j += 2) {
7103 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7104 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7105 return false;
7106 }
7107 }
7108
7109 if (M.size() == NumElts*2)
7110 WhichResult = 0;
7111
7112 return true;
7113}
7114
7115/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7116/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7117/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7118static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7119 unsigned EltSz = VT.getScalarSizeInBits();
7120 if (EltSz == 64)
7121 return false;
7122
7123 unsigned NumElts = VT.getVectorNumElements();
7124 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7125 return false;
7126
7127 for (unsigned i = 0; i < M.size(); i += NumElts) {
7128 WhichResult = SelectPairHalf(NumElts, M, i);
7129 for (unsigned j = 0; j < NumElts; j += 2) {
7130 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7131 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7132 return false;
7133 }
7134 }
7135
7136 if (M.size() == NumElts*2)
7137 WhichResult = 0;
7138
7139 return true;
7140}
7141
7142// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7143// that the mask elements are either all even and in steps of size 2 or all odd
7144// and in steps of size 2.
7145// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7146// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7147// v2={e,f,g,h}
7148// Requires similar checks to that of isVTRNMask with
7149// respect the how results are returned.
7150static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7151 unsigned EltSz = VT.getScalarSizeInBits();
7152 if (EltSz == 64)
7153 return false;
7154
7155 unsigned NumElts = VT.getVectorNumElements();
7156 if (M.size() != NumElts && M.size() != NumElts*2)
7157 return false;
7158
7159 for (unsigned i = 0; i < M.size(); i += NumElts) {
7160 WhichResult = SelectPairHalf(NumElts, M, i);
7161 for (unsigned j = 0; j < NumElts; ++j) {
7162 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7163 return false;
7164 }
7165 }
7166
7167 if (M.size() == NumElts*2)
7168 WhichResult = 0;
7169
7170 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7171 if (VT.is64BitVector() && EltSz == 32)
7172 return false;
7173
7174 return true;
7175}
7176
7177/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7178/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7179/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7180static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7181 unsigned EltSz = VT.getScalarSizeInBits();
7182 if (EltSz == 64)
7183 return false;
7184
7185 unsigned NumElts = VT.getVectorNumElements();
7186 if (M.size() != NumElts && M.size() != NumElts*2)
7187 return false;
7188
7189 unsigned Half = NumElts / 2;
7190 for (unsigned i = 0; i < M.size(); i += NumElts) {
7191 WhichResult = SelectPairHalf(NumElts, M, i);
7192 for (unsigned j = 0; j < NumElts; j += Half) {
7193 unsigned Idx = WhichResult;
7194 for (unsigned k = 0; k < Half; ++k) {
7195 int MIdx = M[i + j + k];
7196 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7197 return false;
7198 Idx += 2;
7199 }
7200 }
7201 }
7202
7203 if (M.size() == NumElts*2)
7204 WhichResult = 0;
7205
7206 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7207 if (VT.is64BitVector() && EltSz == 32)
7208 return false;
7209
7210 return true;
7211}
7212
7213// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7214// that pairs of elements of the shufflemask represent the same index in each
7215// vector incrementing sequentially through the vectors.
7216// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7217// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7218// v2={e,f,g,h}
7219// Requires similar checks to that of isVTRNMask with respect the how results
7220// are returned.
7221static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7222 unsigned EltSz = VT.getScalarSizeInBits();
7223 if (EltSz == 64)
7224 return false;
7225
7226 unsigned NumElts = VT.getVectorNumElements();
7227 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7228 return false;
7229
7230 for (unsigned i = 0; i < M.size(); i += NumElts) {
7231 WhichResult = SelectPairHalf(NumElts, M, i);
7232 unsigned Idx = WhichResult * NumElts / 2;
7233 for (unsigned j = 0; j < NumElts; j += 2) {
7234 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7235 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7236 return false;
7237 Idx += 1;
7238 }
7239 }
7240
7241 if (M.size() == NumElts*2)
7242 WhichResult = 0;
7243
7244 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7245 if (VT.is64BitVector() && EltSz == 32)
7246 return false;
7247
7248 return true;
7249}
7250
7251/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7252/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7253/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7254static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7255 unsigned EltSz = VT.getScalarSizeInBits();
7256 if (EltSz == 64)
7257 return false;
7258
7259 unsigned NumElts = VT.getVectorNumElements();
7260 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7261 return false;
7262
7263 for (unsigned i = 0; i < M.size(); i += NumElts) {
7264 WhichResult = SelectPairHalf(NumElts, M, i);
7265 unsigned Idx = WhichResult * NumElts / 2;
7266 for (unsigned j = 0; j < NumElts; j += 2) {
7267 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7268 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7269 return false;
7270 Idx += 1;
7271 }
7272 }
7273
7274 if (M.size() == NumElts*2)
7275 WhichResult = 0;
7276
7277 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7278 if (VT.is64BitVector() && EltSz == 32)
7279 return false;
7280
7281 return true;
7282}
7283
7284/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7285/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7286static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7287 unsigned &WhichResult,
7288 bool &isV_UNDEF) {
7289 isV_UNDEF = false;
7290 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7291 return ARMISD::VTRN;
7292 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7293 return ARMISD::VUZP;
7294 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7295 return ARMISD::VZIP;
7296
7297 isV_UNDEF = true;
7298 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7299 return ARMISD::VTRN;
7300 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7301 return ARMISD::VUZP;
7302 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7303 return ARMISD::VZIP;
7304
7305 return 0;
7306}
7307
7308/// \return true if this is a reverse operation on an vector.
7309static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7310 unsigned NumElts = VT.getVectorNumElements();
7311 // Make sure the mask has the right size.
7312 if (NumElts != M.size())
7313 return false;
7314
7315 // Look for <15, ..., 3, -1, 1, 0>.
7316 for (unsigned i = 0; i != NumElts; ++i)
7317 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7318 return false;
7319
7320 return true;
7321}
7322
7323static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7324 unsigned NumElts = VT.getVectorNumElements();
7325 // Make sure the mask has the right size.
7326 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7327 return false;
7328
7329 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7330 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7331 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7332 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7333 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7334 int Ofs = Top ? 1 : 0;
7335 int Upper = SingleSource ? 0 : NumElts;
7336 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7337 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7338 return false;
7339 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7340 return false;
7341 }
7342 return true;
7343}
7344
7345static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7346 unsigned NumElts = VT.getVectorNumElements();
7347 // Make sure the mask has the right size.
7348 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7349 return false;
7350
7351 // If Top
7352 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7353 // This inserts Input2 into Input1
7354 // else if not Top
7355 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7356 // This inserts Input1 into Input2
7357 unsigned Offset = Top ? 0 : 1;
7358 unsigned N = SingleSource ? 0 : NumElts;
7359 for (unsigned i = 0; i < NumElts; i += 2) {
7360 if (M[i] >= 0 && M[i] != (int)i)
7361 return false;
7362 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7363 return false;
7364 }
7365
7366 return true;
7367}
7368
7369static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7370 unsigned NumElts = ToVT.getVectorNumElements();
7371 if (NumElts != M.size())
7372 return false;
7373
7374 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7375 // looking for patterns of:
7376 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7377 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7378
7379 unsigned Off0 = rev ? NumElts / 2 : 0;
7380 unsigned Off1 = rev ? 0 : NumElts / 2;
7381 for (unsigned i = 0; i < NumElts; i += 2) {
7382 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7383 return false;
7384 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7385 return false;
7386 }
7387
7388 return true;
7389}
7390
7391// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7392// from a pair of inputs. For example:
7393// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7394// FP_ROUND(EXTRACT_ELT(Y, 0),
7395// FP_ROUND(EXTRACT_ELT(X, 1),
7396// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7398 const ARMSubtarget *ST) {
7399 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7400 if (!ST->hasMVEFloatOps())
7401 return SDValue();
7402
7403 SDLoc dl(BV);
7404 EVT VT = BV.getValueType();
7405 if (VT != MVT::v8f16)
7406 return SDValue();
7407
7408 // We are looking for a buildvector of fptrunc elements, where all the
7409 // elements are interleavingly extracted from two sources. Check the first two
7410 // items are valid enough and extract some info from them (they are checked
7411 // properly in the loop below).
7412 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7415 return SDValue();
7416 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7419 return SDValue();
7420 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7421 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7422 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7423 return SDValue();
7424
7425 // Check all the values in the BuildVector line up with our expectations.
7426 for (unsigned i = 1; i < 4; i++) {
7427 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7428 return Trunc.getOpcode() == ISD::FP_ROUND &&
7430 Trunc.getOperand(0).getOperand(0) == Op &&
7431 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7432 };
7433 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7434 return SDValue();
7435 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7436 return SDValue();
7437 }
7438
7439 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7440 DAG.getConstant(0, dl, MVT::i32));
7441 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7442 DAG.getConstant(1, dl, MVT::i32));
7443}
7444
7445// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7446// from a single input on alternating lanes. For example:
7447// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7448// FP_ROUND(EXTRACT_ELT(X, 2),
7449// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7451 const ARMSubtarget *ST) {
7452 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7453 if (!ST->hasMVEFloatOps())
7454 return SDValue();
7455
7456 SDLoc dl(BV);
7457 EVT VT = BV.getValueType();
7458 if (VT != MVT::v4f32)
7459 return SDValue();
7460
7461 // We are looking for a buildvector of fptext elements, where all the
7462 // elements are alternating lanes from a single source. For example <0,2,4,6>
7463 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7464 // info from them (they are checked properly in the loop below).
7465 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7467 return SDValue();
7468 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7470 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7471 return SDValue();
7472
7473 // Check all the values in the BuildVector line up with our expectations.
7474 for (unsigned i = 1; i < 4; i++) {
7475 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7476 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7478 Trunc.getOperand(0).getOperand(0) == Op &&
7479 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7480 };
7481 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7482 return SDValue();
7483 }
7484
7485 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7486 DAG.getConstant(Offset, dl, MVT::i32));
7487}
7488
7489// If N is an integer constant that can be moved into a register in one
7490// instruction, return an SDValue of such a constant (will become a MOV
7491// instruction). Otherwise return null.
7493 const ARMSubtarget *ST, const SDLoc &dl) {
7494 uint64_t Val;
7495 if (!isa<ConstantSDNode>(N))
7496 return SDValue();
7497 Val = N->getAsZExtVal();
7498
7499 if (ST->isThumb1Only()) {
7500 if (Val <= 255 || ~Val <= 255)
7501 return DAG.getConstant(Val, dl, MVT::i32);
7502 } else {
7503 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7504 return DAG.getConstant(Val, dl, MVT::i32);
7505 }
7506 return SDValue();
7507}
7508
7510 const ARMSubtarget *ST) {
7511 SDLoc dl(Op);
7512 EVT VT = Op.getValueType();
7513
7514 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7515
7516 unsigned NumElts = VT.getVectorNumElements();
7517 unsigned BoolMask;
7518 unsigned BitsPerBool;
7519 if (NumElts == 2) {
7520 BitsPerBool = 8;
7521 BoolMask = 0xff;
7522 } else if (NumElts == 4) {
7523 BitsPerBool = 4;
7524 BoolMask = 0xf;
7525 } else if (NumElts == 8) {
7526 BitsPerBool = 2;
7527 BoolMask = 0x3;
7528 } else if (NumElts == 16) {
7529 BitsPerBool = 1;
7530 BoolMask = 0x1;
7531 } else
7532 return SDValue();
7533
7534 // If this is a single value copied into all lanes (a splat), we can just sign
7535 // extend that single value
7536 SDValue FirstOp = Op.getOperand(0);
7537 if (!isa<ConstantSDNode>(FirstOp) &&
7538 llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7539 return U.get().isUndef() || U.get() == FirstOp;
7540 })) {
7541 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7542 DAG.getValueType(MVT::i1));
7543 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7544 }
7545
7546 // First create base with bits set where known
7547 unsigned Bits32 = 0;
7548 for (unsigned i = 0; i < NumElts; ++i) {
7549 SDValue V = Op.getOperand(i);
7550 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7551 continue;
7552 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7553 if (BitSet)
7554 Bits32 |= BoolMask << (i * BitsPerBool);
7555 }
7556
7557 // Add in unknown nodes
7558 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7559 DAG.getConstant(Bits32, dl, MVT::i32));
7560 for (unsigned i = 0; i < NumElts; ++i) {
7561 SDValue V = Op.getOperand(i);
7562 if (isa<ConstantSDNode>(V) || V.isUndef())
7563 continue;
7564 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7565 DAG.getConstant(i, dl, MVT::i32));
7566 }
7567
7568 return Base;
7569}
7570
7572 const ARMSubtarget *ST) {
7573 if (!ST->hasMVEIntegerOps())
7574 return SDValue();
7575
7576 // We are looking for a buildvector where each element is Op[0] + i*N
7577 EVT VT = Op.getValueType();
7578 SDValue Op0 = Op.getOperand(0);
7579 unsigned NumElts = VT.getVectorNumElements();
7580
7581 // Get the increment value from operand 1
7582 SDValue Op1 = Op.getOperand(1);
7583 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7585 return SDValue();
7586 unsigned N = Op1.getConstantOperandVal(1);
7587 if (N != 1 && N != 2 && N != 4 && N != 8)
7588 return SDValue();
7589
7590 // Check that each other operand matches
7591 for (unsigned I = 2; I < NumElts; I++) {
7592 SDValue OpI = Op.getOperand(I);
7593 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7595 OpI.getConstantOperandVal(1) != I * N)
7596 return SDValue();
7597 }
7598
7599 SDLoc DL(Op);
7600 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7601 DAG.getConstant(N, DL, MVT::i32));
7602}
7603
7604// Returns true if the operation N can be treated as qr instruction variant at
7605// operand Op.
7606static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7607 switch (N->getOpcode()) {
7608 case ISD::ADD:
7609 case ISD::MUL:
7610 case ISD::SADDSAT:
7611 case ISD::UADDSAT:
7612 case ISD::AVGFLOORS:
7613 case ISD::AVGFLOORU:
7614 return true;
7615 case ISD::SUB:
7616 case ISD::SSUBSAT:
7617 case ISD::USUBSAT:
7618 return N->getOperand(1).getNode() == Op;
7620 switch (N->getConstantOperandVal(0)) {
7621 case Intrinsic::arm_mve_add_predicated:
7622 case Intrinsic::arm_mve_mul_predicated:
7623 case Intrinsic::arm_mve_qadd_predicated:
7624 case Intrinsic::arm_mve_vhadd:
7625 case Intrinsic::arm_mve_hadd_predicated:
7626 case Intrinsic::arm_mve_vqdmulh:
7627 case Intrinsic::arm_mve_qdmulh_predicated:
7628 case Intrinsic::arm_mve_vqrdmulh:
7629 case Intrinsic::arm_mve_qrdmulh_predicated:
7630 case Intrinsic::arm_mve_vqdmull:
7631 case Intrinsic::arm_mve_vqdmull_predicated:
7632 return true;
7633 case Intrinsic::arm_mve_sub_predicated:
7634 case Intrinsic::arm_mve_qsub_predicated:
7635 case Intrinsic::arm_mve_vhsub:
7636 case Intrinsic::arm_mve_hsub_predicated:
7637 return N->getOperand(2).getNode() == Op;
7638 default:
7639 return false;
7640 }
7641 default:
7642 return false;
7643 }
7644}
7645
7646// If this is a case we can't handle, return null and let the default
7647// expansion code take care of it.
7648SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7649 const ARMSubtarget *ST) const {
7650 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7651 SDLoc dl(Op);
7652 EVT VT = Op.getValueType();
7653
7654 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7655 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7656
7657 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7658 return R;
7659
7660 APInt SplatBits, SplatUndef;
7661 unsigned SplatBitSize;
7662 bool HasAnyUndefs;
7663 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7664 if (SplatUndef.isAllOnes())
7665 return DAG.getUNDEF(VT);
7666
7667 // If all the users of this constant splat are qr instruction variants,
7668 // generate a vdup of the constant.
7669 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7670 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7671 all_of(BVN->users(),
7672 [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7673 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7674 : SplatBitSize == 16 ? MVT::v8i16
7675 : MVT::v16i8;
7676 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7677 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7678 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7679 }
7680
7681 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7682 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7683 // Check if an immediate VMOV works.
7684 EVT VmovVT;
7685 SDValue Val =
7686 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7687 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7688
7689 if (Val.getNode()) {
7690 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7691 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7692 }
7693
7694 // Try an immediate VMVN.
7695 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7696 Val = isVMOVModifiedImm(
7697 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7698 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7699 if (Val.getNode()) {
7700 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7701 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
7702 }
7703
7704 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7705 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7706 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7707 if (ImmVal != -1) {
7708 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7709 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7710 }
7711 }
7712
7713 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7714 // type.
7715 if (ST->hasMVEIntegerOps() &&
7716 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7717 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7718 : SplatBitSize == 16 ? MVT::v8i16
7719 : MVT::v16i8;
7720 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7721 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7722 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7723 }
7724 }
7725 }
7726
7727 // Scan through the operands to see if only one value is used.
7728 //
7729 // As an optimisation, even if more than one value is used it may be more
7730 // profitable to splat with one value then change some lanes.
7731 //
7732 // Heuristically we decide to do this if the vector has a "dominant" value,
7733 // defined as splatted to more than half of the lanes.
7734 unsigned NumElts = VT.getVectorNumElements();
7735 bool isOnlyLowElement = true;
7736 bool usesOnlyOneValue = true;
7737 bool hasDominantValue = false;
7738 bool isConstant = true;
7739
7740 // Map of the number of times a particular SDValue appears in the
7741 // element list.
7742 DenseMap<SDValue, unsigned> ValueCounts;
7743 SDValue Value;
7744 for (unsigned i = 0; i < NumElts; ++i) {
7745 SDValue V = Op.getOperand(i);
7746 if (V.isUndef())
7747 continue;
7748 if (i > 0)
7749 isOnlyLowElement = false;
7751 isConstant = false;
7752
7753 unsigned &Count = ValueCounts[V];
7754
7755 // Is this value dominant? (takes up more than half of the lanes)
7756 if (++Count > (NumElts / 2)) {
7757 hasDominantValue = true;
7758 Value = V;
7759 }
7760 }
7761 if (ValueCounts.size() != 1)
7762 usesOnlyOneValue = false;
7763 if (!Value.getNode() && !ValueCounts.empty())
7764 Value = ValueCounts.begin()->first;
7765
7766 if (ValueCounts.empty())
7767 return DAG.getUNDEF(VT);
7768
7769 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7770 // Keep going if we are hitting this case.
7771 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7772 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7773
7774 unsigned EltSize = VT.getScalarSizeInBits();
7775
7776 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7777 // i32 and try again.
7778 if (hasDominantValue && EltSize <= 32) {
7779 if (!isConstant) {
7780 SDValue N;
7781
7782 // If we are VDUPing a value that comes directly from a vector, that will
7783 // cause an unnecessary move to and from a GPR, where instead we could
7784 // just use VDUPLANE. We can only do this if the lane being extracted
7785 // is at a constant index, as the VDUP from lane instructions only have
7786 // constant-index forms.
7787 ConstantSDNode *constIndex;
7788 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7789 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7790 // We need to create a new undef vector to use for the VDUPLANE if the
7791 // size of the vector from which we get the value is different than the
7792 // size of the vector that we need to create. We will insert the element
7793 // such that the register coalescer will remove unnecessary copies.
7794 if (VT != Value->getOperand(0).getValueType()) {
7795 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7797 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7798 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7799 Value, DAG.getConstant(index, dl, MVT::i32)),
7800 DAG.getConstant(index, dl, MVT::i32));
7801 } else
7802 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7803 Value->getOperand(0), Value->getOperand(1));
7804 } else
7805 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7806
7807 if (!usesOnlyOneValue) {
7808 // The dominant value was splatted as 'N', but we now have to insert
7809 // all differing elements.
7810 for (unsigned I = 0; I < NumElts; ++I) {
7811 if (Op.getOperand(I) == Value)
7812 continue;
7814 Ops.push_back(N);
7815 Ops.push_back(Op.getOperand(I));
7816 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7817 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7818 }
7819 }
7820 return N;
7821 }
7824 MVT FVT = VT.getVectorElementType().getSimpleVT();
7825 assert(FVT == MVT::f32 || FVT == MVT::f16);
7826 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7827 for (unsigned i = 0; i < NumElts; ++i)
7828 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7829 Op.getOperand(i)));
7830 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7831 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7832 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7833 if (Val.getNode())
7834 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7835 }
7836 if (usesOnlyOneValue) {
7837 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7838 if (isConstant && Val.getNode())
7839 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7840 }
7841 }
7842
7843 // If all elements are constants and the case above didn't get hit, fall back
7844 // to the default expansion, which will generate a load from the constant
7845 // pool.
7846 if (isConstant)
7847 return SDValue();
7848
7849 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7850 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7851 // length <= 2.
7852 if (NumElts >= 4)
7853 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7854 return shuffle;
7855
7856 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7857 // VCVT's
7858 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7859 return VCVT;
7860 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7861 return VCVT;
7862
7863 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7864 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7865 // into two 64-bit vectors; we might discover a better way to lower it.
7866 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7867 EVT ExtVT = VT.getVectorElementType();
7868 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7869 SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
7870 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7871 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7872 SDValue Upper =
7873 DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7874 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7875 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7876 if (Lower && Upper)
7877 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7878 }
7879
7880 // Vectors with 32- or 64-bit elements can be built by directly assigning
7881 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7882 // will be legalized.
7883 if (EltSize >= 32) {
7884 // Do the expansion with floating-point types, since that is what the VFP
7885 // registers are defined to use, and since i64 is not legal.
7886 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7887 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7889 for (unsigned i = 0; i < NumElts; ++i)
7890 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7891 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7892 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7893 }
7894
7895 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7896 // know the default expansion would otherwise fall back on something even
7897 // worse. For a vector with one or two non-undef values, that's
7898 // scalar_to_vector for the elements followed by a shuffle (provided the
7899 // shuffle is valid for the target) and materialization element by element
7900 // on the stack followed by a load for everything else.
7901 if (!isConstant && !usesOnlyOneValue) {
7902 SDValue Vec = DAG.getUNDEF(VT);
7903 for (unsigned i = 0 ; i < NumElts; ++i) {
7904 SDValue V = Op.getOperand(i);
7905 if (V.isUndef())
7906 continue;
7907 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7908 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7909 }
7910 return Vec;
7911 }
7912
7913 return SDValue();
7914}
7915
7916// Gather data to see if the operation can be modelled as a
7917// shuffle in combination with VEXTs.
7918SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7919 SelectionDAG &DAG) const {
7920 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7921 SDLoc dl(Op);
7922 EVT VT = Op.getValueType();
7923 unsigned NumElts = VT.getVectorNumElements();
7924
7925 struct ShuffleSourceInfo {
7926 SDValue Vec;
7927 unsigned MinElt = std::numeric_limits<unsigned>::max();
7928 unsigned MaxElt = 0;
7929
7930 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7931 // be compatible with the shuffle we intend to construct. As a result
7932 // ShuffleVec will be some sliding window into the original Vec.
7933 SDValue ShuffleVec;
7934
7935 // Code should guarantee that element i in Vec starts at element "WindowBase
7936 // + i * WindowScale in ShuffleVec".
7937 int WindowBase = 0;
7938 int WindowScale = 1;
7939
7940 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7941
7942 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7943 };
7944
7945 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7946 // node.
7948 for (unsigned i = 0; i < NumElts; ++i) {
7949 SDValue V = Op.getOperand(i);
7950 if (V.isUndef())
7951 continue;
7952 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7953 // A shuffle can only come from building a vector from various
7954 // elements of other vectors.
7955 return SDValue();
7956 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7957 // Furthermore, shuffles require a constant mask, whereas extractelts
7958 // accept variable indices.
7959 return SDValue();
7960 }
7961
7962 // Add this element source to the list if it's not already there.
7963 SDValue SourceVec = V.getOperand(0);
7964 auto Source = llvm::find(Sources, SourceVec);
7965 if (Source == Sources.end())
7966 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7967
7968 // Update the minimum and maximum lane number seen.
7969 unsigned EltNo = V.getConstantOperandVal(1);
7970 Source->MinElt = std::min(Source->MinElt, EltNo);
7971 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7972 }
7973
7974 // Currently only do something sane when at most two source vectors
7975 // are involved.
7976 if (Sources.size() > 2)
7977 return SDValue();
7978
7979 // Find out the smallest element size among result and two sources, and use
7980 // it as element size to build the shuffle_vector.
7981 EVT SmallestEltTy = VT.getVectorElementType();
7982 for (auto &Source : Sources) {
7983 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7984 if (SrcEltTy.bitsLT(SmallestEltTy))
7985 SmallestEltTy = SrcEltTy;
7986 }
7987 unsigned ResMultiplier =
7988 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7989 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7990 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7991
7992 // If the source vector is too wide or too narrow, we may nevertheless be able
7993 // to construct a compatible shuffle either by concatenating it with UNDEF or
7994 // extracting a suitable range of elements.
7995 for (auto &Src : Sources) {
7996 EVT SrcVT = Src.ShuffleVec.getValueType();
7997
7998 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7999 uint64_t VTSize = VT.getFixedSizeInBits();
8000 if (SrcVTSize == VTSize)
8001 continue;
8002
8003 // This stage of the search produces a source with the same element type as
8004 // the original, but with a total width matching the BUILD_VECTOR output.
8005 EVT EltVT = SrcVT.getVectorElementType();
8006 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8007 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8008
8009 if (SrcVTSize < VTSize) {
8010 if (2 * SrcVTSize != VTSize)
8011 return SDValue();
8012 // We can pad out the smaller vector for free, so if it's part of a
8013 // shuffle...
8014 Src.ShuffleVec =
8015 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8016 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8017 continue;
8018 }
8019
8020 if (SrcVTSize != 2 * VTSize)
8021 return SDValue();
8022
8023 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8024 // Span too large for a VEXT to cope
8025 return SDValue();
8026 }
8027
8028 if (Src.MinElt >= NumSrcElts) {
8029 // The extraction can just take the second half
8030 Src.ShuffleVec =
8031 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8032 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8033 Src.WindowBase = -NumSrcElts;
8034 } else if (Src.MaxElt < NumSrcElts) {
8035 // The extraction can just take the first half
8036 Src.ShuffleVec =
8037 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8038 DAG.getConstant(0, dl, MVT::i32));
8039 } else {
8040 // An actual VEXT is needed
8041 SDValue VEXTSrc1 =
8042 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8043 DAG.getConstant(0, dl, MVT::i32));
8044 SDValue VEXTSrc2 =
8045 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8046 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8047
8048 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8049 VEXTSrc2,
8050 DAG.getConstant(Src.MinElt, dl, MVT::i32));
8051 Src.WindowBase = -Src.MinElt;
8052 }
8053 }
8054
8055 // Another possible incompatibility occurs from the vector element types. We
8056 // can fix this by bitcasting the source vectors to the same type we intend
8057 // for the shuffle.
8058 for (auto &Src : Sources) {
8059 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8060 if (SrcEltTy == SmallestEltTy)
8061 continue;
8062 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8063 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8064 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8065 Src.WindowBase *= Src.WindowScale;
8066 }
8067
8068 // Final check before we try to actually produce a shuffle.
8069 LLVM_DEBUG({
8070 for (auto Src : Sources)
8071 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8072 });
8073
8074 // The stars all align, our next step is to produce the mask for the shuffle.
8075 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8076 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8077 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8078 SDValue Entry = Op.getOperand(i);
8079 if (Entry.isUndef())
8080 continue;
8081
8082 auto Src = llvm::find(Sources, Entry.getOperand(0));
8083 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8084
8085 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8086 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8087 // segment.
8088 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8089 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8090 VT.getScalarSizeInBits());
8091 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8092
8093 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8094 // starting at the appropriate offset.
8095 int *LaneMask = &Mask[i * ResMultiplier];
8096
8097 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8098 ExtractBase += NumElts * (Src - Sources.begin());
8099 for (int j = 0; j < LanesDefined; ++j)
8100 LaneMask[j] = ExtractBase + j;
8101 }
8102
8103
8104 // We can't handle more than two sources. This should have already
8105 // been checked before this point.
8106 assert(Sources.size() <= 2 && "Too many sources!");
8107
8108 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8109 for (unsigned i = 0; i < Sources.size(); ++i)
8110 ShuffleOps[i] = Sources[i].ShuffleVec;
8111
8112 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8113 ShuffleOps[1], Mask, DAG);
8114 if (!Shuffle)
8115 return SDValue();
8116 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8117}
8118
8120 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8129 OP_VUZPL, // VUZP, left result
8130 OP_VUZPR, // VUZP, right result
8131 OP_VZIPL, // VZIP, left result
8132 OP_VZIPR, // VZIP, right result
8133 OP_VTRNL, // VTRN, left result
8134 OP_VTRNR // VTRN, right result
8135};
8136
8137static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8138 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8139 switch (OpNum) {
8140 case OP_COPY:
8141 case OP_VREV:
8142 case OP_VDUP0:
8143 case OP_VDUP1:
8144 case OP_VDUP2:
8145 case OP_VDUP3:
8146 return true;
8147 }
8148 return false;
8149}
8150
8151/// isShuffleMaskLegal - Targets can use this to indicate that they only
8152/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8153/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8154/// are assumed to be legal.
8156 if (VT.getVectorNumElements() == 4 &&
8157 (VT.is128BitVector() || VT.is64BitVector())) {
8158 unsigned PFIndexes[4];
8159 for (unsigned i = 0; i != 4; ++i) {
8160 if (M[i] < 0)
8161 PFIndexes[i] = 8;
8162 else
8163 PFIndexes[i] = M[i];
8164 }
8165
8166 // Compute the index in the perfect shuffle table.
8167 unsigned PFTableIndex =
8168 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8169 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8170 unsigned Cost = (PFEntry >> 30);
8171
8172 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8173 return true;
8174 }
8175
8176 bool ReverseVEXT, isV_UNDEF;
8177 unsigned Imm, WhichResult;
8178
8179 unsigned EltSize = VT.getScalarSizeInBits();
8180 if (EltSize >= 32 ||
8182 ShuffleVectorInst::isIdentityMask(M, M.size()) ||
8183 isVREVMask(M, VT, 64) ||
8184 isVREVMask(M, VT, 32) ||
8185 isVREVMask(M, VT, 16))
8186 return true;
8187 else if (Subtarget->hasNEON() &&
8188 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8189 isVTBLMask(M, VT) ||
8190 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8191 return true;
8192 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8193 isReverseMask(M, VT))
8194 return true;
8195 else if (Subtarget->hasMVEIntegerOps() &&
8196 (isVMOVNMask(M, VT, true, false) ||
8197 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8198 return true;
8199 else if (Subtarget->hasMVEIntegerOps() &&
8200 (isTruncMask(M, VT, false, false) ||
8201 isTruncMask(M, VT, false, true) ||
8202 isTruncMask(M, VT, true, false) || isTruncMask(M, VT, true, true)))
8203 return true;
8204 else
8205 return false;
8206}
8207
8208/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8209/// the specified operations to build the shuffle.
8211 SDValue RHS, SelectionDAG &DAG,
8212 const SDLoc &dl) {
8213 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8214 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8215 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8216
8217 if (OpNum == OP_COPY) {
8218 if (LHSID == (1*9+2)*9+3) return LHS;
8219 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8220 return RHS;
8221 }
8222
8223 SDValue OpLHS, OpRHS;
8224 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8225 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8226 EVT VT = OpLHS.getValueType();
8227
8228 switch (OpNum) {
8229 default: llvm_unreachable("Unknown shuffle opcode!");
8230 case OP_VREV:
8231 // VREV divides the vector in half and swaps within the half.
8232 if (VT.getScalarSizeInBits() == 32)
8233 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8234 // vrev <4 x i16> -> VREV32
8235 if (VT.getScalarSizeInBits() == 16)
8236 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8237 // vrev <4 x i8> -> VREV16
8238 assert(VT.getScalarSizeInBits() == 8);
8239 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8240 case OP_VDUP0:
8241 case OP_VDUP1:
8242 case OP_VDUP2:
8243 case OP_VDUP3:
8244 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8245 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8246 case OP_VEXT1:
8247 case OP_VEXT2:
8248 case OP_VEXT3:
8249 return DAG.getNode(ARMISD::VEXT, dl, VT,
8250 OpLHS, OpRHS,
8251 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8252 case OP_VUZPL:
8253 case OP_VUZPR:
8254 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8255 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8256 case OP_VZIPL:
8257 case OP_VZIPR:
8258 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8259 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8260 case OP_VTRNL:
8261 case OP_VTRNR:
8262 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8263 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8264 }
8265}
8266
8268 ArrayRef<int> ShuffleMask,
8269 SelectionDAG &DAG) {
8270 // Check to see if we can use the VTBL instruction.
8271 SDValue V1 = Op.getOperand(0);
8272 SDValue V2 = Op.getOperand(1);
8273 SDLoc DL(Op);
8274
8275 SmallVector<SDValue, 8> VTBLMask;
8276 for (int I : ShuffleMask)
8277 VTBLMask.push_back(DAG.getSignedConstant(I, DL, MVT::i32));
8278
8279 if (V2.getNode()->isUndef())
8280 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8281 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8282
8283 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8284 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8285}
8286
8288 SDLoc DL(Op);
8289 EVT VT = Op.getValueType();
8290
8291 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8292 "Expect an v8i16/v16i8 type");
8293 SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8294 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8295 // extract the first 8 bytes into the top double word and the last 8 bytes
8296 // into the bottom double word, through a new vector shuffle that will be
8297 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8298 std::vector<int> NewMask;
8299 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8300 NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8301 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8302 NewMask.push_back(i);
8303 return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8304}
8305
8307 switch (VT.getSimpleVT().SimpleTy) {
8308 case MVT::v2i1:
8309 return MVT::v2f64;
8310 case MVT::v4i1:
8311 return MVT::v4i32;
8312 case MVT::v8i1:
8313 return MVT::v8i16;
8314 case MVT::v16i1:
8315 return MVT::v16i8;
8316 default:
8317 llvm_unreachable("Unexpected vector predicate type");
8318 }
8319}
8320
8322 SelectionDAG &DAG) {
8323 // Converting from boolean predicates to integers involves creating a vector
8324 // of all ones or all zeroes and selecting the lanes based upon the real
8325 // predicate.
8327 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8328 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8329
8330 SDValue AllZeroes =
8331 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8332 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8333
8334 // Get full vector type from predicate type
8336
8337 SDValue RecastV1;
8338 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8339 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8340 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8341 // since we know in hardware the sizes are really the same.
8342 if (VT != MVT::v16i1)
8343 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8344 else
8345 RecastV1 = Pred;
8346
8347 // Select either all ones or zeroes depending upon the real predicate bits.
8348 SDValue PredAsVector =
8349 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8350
8351 // Recast our new predicate-as-integer v16i8 vector into something
8352 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8353 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8354}
8355
8357 const ARMSubtarget *ST) {
8358 EVT VT = Op.getValueType();
8360 ArrayRef<int> ShuffleMask = SVN->getMask();
8361
8362 assert(ST->hasMVEIntegerOps() &&
8363 "No support for vector shuffle of boolean predicates");
8364
8365 SDValue V1 = Op.getOperand(0);
8366 SDValue V2 = Op.getOperand(1);
8367 SDLoc dl(Op);
8368 if (isReverseMask(ShuffleMask, VT)) {
8369 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8370 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8371 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8372 DAG.getConstant(16, dl, MVT::i32));
8373 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8374 }
8375
8376 // Until we can come up with optimised cases for every single vector
8377 // shuffle in existence we have chosen the least painful strategy. This is
8378 // to essentially promote the boolean predicate to a 8-bit integer, where
8379 // each predicate represents a byte. Then we fall back on a normal integer
8380 // vector shuffle and convert the result back into a predicate vector. In
8381 // many cases the generated code might be even better than scalar code
8382 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8383 // fields in a register into 8 other arbitrary 2-bit fields!
8384 SDValue PredAsVector1 = PromoteMVEPredVector(dl, V1, VT, DAG);
8385 EVT NewVT = PredAsVector1.getValueType();
8386 SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(NewVT)
8387 : PromoteMVEPredVector(dl, V2, VT, DAG);
8388 assert(PredAsVector2.getValueType() == NewVT &&
8389 "Expected identical vector type in expanded i1 shuffle!");
8390
8391 // Do the shuffle!
8392 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector1,
8393 PredAsVector2, ShuffleMask);
8394
8395 // Now return the result of comparing the shuffled vector with zero,
8396 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8397 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8398 if (VT == MVT::v2i1) {
8399 SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8400 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8401 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8402 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8403 }
8404 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8405 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8406}
8407
8409 ArrayRef<int> ShuffleMask,
8410 SelectionDAG &DAG) {
8411 // Attempt to lower the vector shuffle using as many whole register movs as
8412 // possible. This is useful for types smaller than 32bits, which would
8413 // often otherwise become a series for grp movs.
8414 SDLoc dl(Op);
8415 EVT VT = Op.getValueType();
8416 if (VT.getScalarSizeInBits() >= 32)
8417 return SDValue();
8418
8419 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8420 "Unexpected vector type");
8421 int NumElts = VT.getVectorNumElements();
8422 int QuarterSize = NumElts / 4;
8423 // The four final parts of the vector, as i32's
8424 SDValue Parts[4];
8425
8426 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8427 // <u,u,u,u>), returning the vmov lane index
8428 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8429 // Detect which mov lane this would be from the first non-undef element.
8430 int MovIdx = -1;
8431 for (int i = 0; i < Length; i++) {
8432 if (ShuffleMask[Start + i] >= 0) {
8433 if (ShuffleMask[Start + i] % Length != i)
8434 return -1;
8435 MovIdx = ShuffleMask[Start + i] / Length;
8436 break;
8437 }
8438 }
8439 // If all items are undef, leave this for other combines
8440 if (MovIdx == -1)
8441 return -1;
8442 // Check the remaining values are the correct part of the same mov
8443 for (int i = 1; i < Length; i++) {
8444 if (ShuffleMask[Start + i] >= 0 &&
8445 (ShuffleMask[Start + i] / Length != MovIdx ||
8446 ShuffleMask[Start + i] % Length != i))
8447 return -1;
8448 }
8449 return MovIdx;
8450 };
8451
8452 for (int Part = 0; Part < 4; ++Part) {
8453 // Does this part look like a mov
8454 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8455 if (Elt != -1) {
8456 SDValue Input = Op->getOperand(0);
8457 if (Elt >= 4) {
8458 Input = Op->getOperand(1);
8459 Elt -= 4;
8460 }
8461 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8462 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8463 DAG.getConstant(Elt, dl, MVT::i32));
8464 }
8465 }
8466
8467 // Nothing interesting found, just return
8468 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8469 return SDValue();
8470
8471 // The other parts need to be built with the old shuffle vector, cast to a
8472 // v4i32 and extract_vector_elts
8473 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8474 SmallVector<int, 16> NewShuffleMask;
8475 for (int Part = 0; Part < 4; ++Part)
8476 for (int i = 0; i < QuarterSize; i++)
8477 NewShuffleMask.push_back(
8478 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8479 SDValue NewShuffle = DAG.getVectorShuffle(
8480 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8481 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8482
8483 for (int Part = 0; Part < 4; ++Part)
8484 if (!Parts[Part])
8485 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8486 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8487 }
8488 // Build a vector out of the various parts and bitcast it back to the original
8489 // type.
8490 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8491 return DAG.getBitcast(VT, NewVec);
8492}
8493
8495 ArrayRef<int> ShuffleMask,
8496 SelectionDAG &DAG) {
8497 SDValue V1 = Op.getOperand(0);
8498 SDValue V2 = Op.getOperand(1);
8499 EVT VT = Op.getValueType();
8500 unsigned NumElts = VT.getVectorNumElements();
8501
8502 // An One-Off Identity mask is one that is mostly an identity mask from as
8503 // single source but contains a single element out-of-place, either from a
8504 // different vector or from another position in the same vector. As opposed to
8505 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8506 // pair directly.
8507 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8508 int &OffElement) {
8509 OffElement = -1;
8510 int NonUndef = 0;
8511 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8512 if (Mask[i] == -1)
8513 continue;
8514 NonUndef++;
8515 if (Mask[i] != i + BaseOffset) {
8516 if (OffElement == -1)
8517 OffElement = i;
8518 else
8519 return false;
8520 }
8521 }
8522 return NonUndef > 2 && OffElement != -1;
8523 };
8524 int OffElement;
8525 SDValue VInput;
8526 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8527 VInput = V1;
8528 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8529 VInput = V2;
8530 else
8531 return SDValue();
8532
8533 SDLoc dl(Op);
8534 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8535 ? MVT::i32
8536 : VT.getScalarType();
8537 SDValue Elt = DAG.getNode(
8538 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8539 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8540 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8541 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8542 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8543}
8544
8546 const ARMSubtarget *ST) {
8547 SDValue V1 = Op.getOperand(0);
8548 SDValue V2 = Op.getOperand(1);
8549 SDLoc dl(Op);
8550 EVT VT = Op.getValueType();
8552 unsigned EltSize = VT.getScalarSizeInBits();
8553
8554 if (ST->hasMVEIntegerOps() && EltSize == 1)
8555 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8556
8557 // Convert shuffles that are directly supported on NEON to target-specific
8558 // DAG nodes, instead of keeping them as shuffles and matching them again
8559 // during code selection. This is more efficient and avoids the possibility
8560 // of inconsistencies between legalization and selection.
8561 // FIXME: floating-point vectors should be canonicalized to integer vectors
8562 // of the same time so that they get CSEd properly.
8563 ArrayRef<int> ShuffleMask = SVN->getMask();
8564
8565 if (EltSize <= 32) {
8566 if (SVN->isSplat()) {
8567 int Lane = SVN->getSplatIndex();
8568 // If this is undef splat, generate it via "just" vdup, if possible.
8569 if (Lane == -1) Lane = 0;
8570
8571 // Test if V1 is a SCALAR_TO_VECTOR.
8572 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8573 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8574 }
8575 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8576 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8577 // reaches it).
8578 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8580 bool IsScalarToVector = true;
8581 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8582 if (!V1.getOperand(i).isUndef()) {
8583 IsScalarToVector = false;
8584 break;
8585 }
8586 if (IsScalarToVector)
8587 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8588 }
8589 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8590 DAG.getConstant(Lane, dl, MVT::i32));
8591 }
8592
8593 bool ReverseVEXT = false;
8594 unsigned Imm = 0;
8595 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8596 if (ReverseVEXT)
8597 std::swap(V1, V2);
8598 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8599 DAG.getConstant(Imm, dl, MVT::i32));
8600 }
8601
8602 if (isVREVMask(ShuffleMask, VT, 64))
8603 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8604 if (isVREVMask(ShuffleMask, VT, 32))
8605 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8606 if (isVREVMask(ShuffleMask, VT, 16))
8607 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8608
8609 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8610 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8611 DAG.getConstant(Imm, dl, MVT::i32));
8612 }
8613
8614 // Check for Neon shuffles that modify both input vectors in place.
8615 // If both results are used, i.e., if there are two shuffles with the same
8616 // source operands and with masks corresponding to both results of one of
8617 // these operations, DAG memoization will ensure that a single node is
8618 // used for both shuffles.
8619 unsigned WhichResult = 0;
8620 bool isV_UNDEF = false;
8621 if (ST->hasNEON()) {
8622 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8623 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8624 if (isV_UNDEF)
8625 V2 = V1;
8626 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8627 .getValue(WhichResult);
8628 }
8629 }
8630 if (ST->hasMVEIntegerOps()) {
8631 if (isVMOVNMask(ShuffleMask, VT, false, false))
8632 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8633 DAG.getConstant(0, dl, MVT::i32));
8634 if (isVMOVNMask(ShuffleMask, VT, true, false))
8635 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8636 DAG.getConstant(1, dl, MVT::i32));
8637 if (isVMOVNMask(ShuffleMask, VT, true, true))
8638 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8639 DAG.getConstant(1, dl, MVT::i32));
8640 }
8641
8642 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8643 // shuffles that produce a result larger than their operands with:
8644 // shuffle(concat(v1, undef), concat(v2, undef))
8645 // ->
8646 // shuffle(concat(v1, v2), undef)
8647 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8648 //
8649 // This is useful in the general case, but there are special cases where
8650 // native shuffles produce larger results: the two-result ops.
8651 //
8652 // Look through the concat when lowering them:
8653 // shuffle(concat(v1, v2), undef)
8654 // ->
8655 // concat(VZIP(v1, v2):0, :1)
8656 //
8657 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8658 SDValue SubV1 = V1->getOperand(0);
8659 SDValue SubV2 = V1->getOperand(1);
8660 EVT SubVT = SubV1.getValueType();
8661
8662 // We expect these to have been canonicalized to -1.
8663 assert(llvm::all_of(ShuffleMask, [&](int i) {
8664 return i < (int)VT.getVectorNumElements();
8665 }) && "Unexpected shuffle index into UNDEF operand!");
8666
8667 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8668 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8669 if (isV_UNDEF)
8670 SubV2 = SubV1;
8671 assert((WhichResult == 0) &&
8672 "In-place shuffle of concat can only have one result!");
8673 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8674 SubV1, SubV2);
8675 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8676 Res.getValue(1));
8677 }
8678 }
8679 }
8680
8681 if (ST->hasMVEIntegerOps() && EltSize <= 32) {
8682 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8683 return V;
8684
8685 for (bool Top : {false, true}) {
8686 for (bool SingleSource : {false, true}) {
8687 if (isTruncMask(ShuffleMask, VT, Top, SingleSource)) {
8688 MVT FromSVT = MVT::getIntegerVT(EltSize * 2);
8689 MVT FromVT = MVT::getVectorVT(FromSVT, ShuffleMask.size() / 2);
8690 SDValue Lo = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT, V1);
8691 SDValue Hi = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT,
8692 SingleSource ? V1 : V2);
8693 if (Top) {
8694 SDValue Amt = DAG.getConstant(EltSize, dl, FromVT);
8695 Lo = DAG.getNode(ISD::SRL, dl, FromVT, Lo, Amt);
8696 Hi = DAG.getNode(ISD::SRL, dl, FromVT, Hi, Amt);
8697 }
8698 return DAG.getNode(ARMISD::MVETRUNC, dl, VT, Lo, Hi);
8699 }
8700 }
8701 }
8702 }
8703
8704 // If the shuffle is not directly supported and it has 4 elements, use
8705 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8706 unsigned NumElts = VT.getVectorNumElements();
8707 if (NumElts == 4) {
8708 unsigned PFIndexes[4];
8709 for (unsigned i = 0; i != 4; ++i) {
8710 if (ShuffleMask[i] < 0)
8711 PFIndexes[i] = 8;
8712 else
8713 PFIndexes[i] = ShuffleMask[i];
8714 }
8715
8716 // Compute the index in the perfect shuffle table.
8717 unsigned PFTableIndex =
8718 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8719 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8720 unsigned Cost = (PFEntry >> 30);
8721
8722 if (Cost <= 4) {
8723 if (ST->hasNEON())
8724 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8725 else if (isLegalMVEShuffleOp(PFEntry)) {
8726 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8727 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8728 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8729 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8730 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8732 }
8733 }
8734 }
8735
8736 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8737 if (EltSize >= 32) {
8738 // Do the expansion with floating-point types, since that is what the VFP
8739 // registers are defined to use, and since i64 is not legal.
8740 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8741 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8742 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8743 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8745 for (unsigned i = 0; i < NumElts; ++i) {
8746 if (ShuffleMask[i] < 0)
8747 Ops.push_back(DAG.getUNDEF(EltVT));
8748 else
8749 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8750 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8751 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8752 dl, MVT::i32)));
8753 }
8754 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8755 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8756 }
8757
8758 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8759 isReverseMask(ShuffleMask, VT))
8760 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8761
8762 if (ST->hasNEON() && VT == MVT::v8i8)
8763 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8764 return NewOp;
8765
8766 if (ST->hasMVEIntegerOps())
8767 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8768 return NewOp;
8769
8770 return SDValue();
8771}
8772
8774 const ARMSubtarget *ST) {
8775 EVT VecVT = Op.getOperand(0).getValueType();
8776 SDLoc dl(Op);
8777
8778 assert(ST->hasMVEIntegerOps() &&
8779 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8780
8781 SDValue Conv =
8782 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8783 unsigned Lane = Op.getConstantOperandVal(2);
8784 unsigned LaneWidth =
8786 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8787 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8788 Op.getOperand(1), DAG.getValueType(MVT::i1));
8789 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8790 DAG.getConstant(~Mask, dl, MVT::i32));
8791 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8792}
8793
8794SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8795 SelectionDAG &DAG) const {
8796 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8797 SDValue Lane = Op.getOperand(2);
8798 if (!isa<ConstantSDNode>(Lane))
8799 return SDValue();
8800
8801 SDValue Elt = Op.getOperand(1);
8802 EVT EltVT = Elt.getValueType();
8803
8804 if (Subtarget->hasMVEIntegerOps() &&
8805 Op.getValueType().getScalarSizeInBits() == 1)
8806 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8807
8808 if (getTypeAction(*DAG.getContext(), EltVT) ==
8810 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8811 // but the type system will try to do that if we don't intervene.
8812 // Reinterpret any such vector-element insertion as one with the
8813 // corresponding integer types.
8814
8815 SDLoc dl(Op);
8816
8817 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8818 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8820
8821 SDValue VecIn = Op.getOperand(0);
8822 EVT VecVT = VecIn.getValueType();
8823 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8824 VecVT.getVectorNumElements());
8825
8826 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8827 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8828 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8829 IVecIn, IElt, Lane);
8830 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8831 }
8832
8833 return Op;
8834}
8835
8837 const ARMSubtarget *ST) {
8838 EVT VecVT = Op.getOperand(0).getValueType();
8839 SDLoc dl(Op);
8840
8841 assert(ST->hasMVEIntegerOps() &&
8842 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8843
8844 SDValue Conv =
8845 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8846 unsigned Lane = Op.getConstantOperandVal(1);
8847 unsigned LaneWidth =
8849 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8850 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8851 return Shift;
8852}
8853
8855 const ARMSubtarget *ST) {
8856 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8857 SDValue Lane = Op.getOperand(1);
8858 if (!isa<ConstantSDNode>(Lane))
8859 return SDValue();
8860
8861 SDValue Vec = Op.getOperand(0);
8862 EVT VT = Vec.getValueType();
8863
8864 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8865 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8866
8867 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8868 SDLoc dl(Op);
8869 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8870 }
8871
8872 return Op;
8873}
8874
8876 const ARMSubtarget *ST) {
8877 SDLoc dl(Op);
8878 assert(Op.getValueType().getScalarSizeInBits() == 1 &&
8879 "Unexpected custom CONCAT_VECTORS lowering");
8880 assert(isPowerOf2_32(Op.getNumOperands()) &&
8881 "Unexpected custom CONCAT_VECTORS lowering");
8882 assert(ST->hasMVEIntegerOps() &&
8883 "CONCAT_VECTORS lowering only supported for MVE");
8884
8885 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8886 EVT Op1VT = V1.getValueType();
8887 EVT Op2VT = V2.getValueType();
8888 assert(Op1VT == Op2VT && "Operand types don't match!");
8889 assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
8890 "Unexpected i1 concat operations!");
8891 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
8892
8893 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8894 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8895
8896 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8897 // promoted to v8i16, etc.
8898 MVT ElType =
8900 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8901
8902 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8903 if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
8904 // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
8905 // ConcatVT.
8906 SDValue ConVec =
8907 DAG.getNode(ARMISD::MVETRUNC, dl, ConcatVT, NewV1, NewV2);
8908 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8909 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8910 }
8911
8912 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8913 // to be the right size for the destination. For example, if Op1 is v4i1
8914 // then the promoted vector is v4i32. The result of concatenation gives a
8915 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8916 // needs truncating to i16 and inserting in the result.
8917 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8918 EVT NewVT = NewV.getValueType();
8919 EVT ConcatVT = ConVec.getValueType();
8920 unsigned ExtScale = 1;
8921 if (NewVT == MVT::v2f64) {
8922 NewV = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, NewV);
8923 ExtScale = 2;
8924 }
8925 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8926 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8927 DAG.getIntPtrConstant(i * ExtScale, dl));
8928 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8929 DAG.getConstant(j, dl, MVT::i32));
8930 }
8931 return ConVec;
8932 };
8933 unsigned j = 0;
8934 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8935 ConVec = ExtractInto(NewV1, ConVec, j);
8936 ConVec = ExtractInto(NewV2, ConVec, j);
8937
8938 // Now return the result of comparing the subvector with zero, which will
8939 // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8940 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8941 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8942 };
8943
8944 // Concat each pair of subvectors and pack into the lower half of the array.
8945 SmallVector<SDValue> ConcatOps(Op->ops());
8946 while (ConcatOps.size() > 1) {
8947 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8948 SDValue V1 = ConcatOps[I];
8949 SDValue V2 = ConcatOps[I + 1];
8950 ConcatOps[I / 2] = ConcatPair(V1, V2);
8951 }
8952 ConcatOps.resize(ConcatOps.size() / 2);
8953 }
8954 return ConcatOps[0];
8955}
8956
8958 const ARMSubtarget *ST) {
8959 EVT VT = Op->getValueType(0);
8960 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8961 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8962
8963 // The only time a CONCAT_VECTORS operation can have legal types is when
8964 // two 64-bit vectors are concatenated to a 128-bit vector.
8965 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8966 "unexpected CONCAT_VECTORS");
8967 SDLoc dl(Op);
8968 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8969 SDValue Op0 = Op.getOperand(0);
8970 SDValue Op1 = Op.getOperand(1);
8971 if (!Op0.isUndef())
8972 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8973 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8974 DAG.getIntPtrConstant(0, dl));
8975 if (!Op1.isUndef())
8976 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8977 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8978 DAG.getIntPtrConstant(1, dl));
8979 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8980}
8981
8983 const ARMSubtarget *ST) {
8984 SDValue V1 = Op.getOperand(0);
8985 SDValue V2 = Op.getOperand(1);
8986 SDLoc dl(Op);
8987 EVT VT = Op.getValueType();
8988 EVT Op1VT = V1.getValueType();
8989 unsigned NumElts = VT.getVectorNumElements();
8990 unsigned Index = V2->getAsZExtVal();
8991
8992 assert(VT.getScalarSizeInBits() == 1 &&
8993 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8994 assert(ST->hasMVEIntegerOps() &&
8995 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8996
8997 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8998
8999 // We now have Op1 promoted to a vector of integers, where v8i1 gets
9000 // promoted to v8i16, etc.
9001
9003
9004 if (NumElts == 2) {
9005 EVT SubVT = MVT::v4i32;
9006 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9007 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
9008 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9009 DAG.getIntPtrConstant(i, dl));
9010 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9011 DAG.getConstant(j, dl, MVT::i32));
9012 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9013 DAG.getConstant(j + 1, dl, MVT::i32));
9014 }
9015 SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
9016 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9017 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9018 }
9019
9020 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
9021 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9022 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
9023 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9024 DAG.getIntPtrConstant(i, dl));
9025 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9026 DAG.getConstant(j, dl, MVT::i32));
9027 }
9028
9029 // Now return the result of comparing the subvector with zero,
9030 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9031 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9032 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9033}
9034
9035// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
9037 const ARMSubtarget *ST) {
9038 assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9039 EVT VT = N->getValueType(0);
9040 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9041 "Expected a vector i1 type!");
9042 SDValue Op = N->getOperand(0);
9043 EVT FromVT = Op.getValueType();
9044 SDLoc DL(N);
9045
9046 SDValue And =
9047 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9048 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9049 DAG.getCondCode(ISD::SETNE));
9050}
9051
9053 const ARMSubtarget *Subtarget) {
9054 if (!Subtarget->hasMVEIntegerOps())
9055 return SDValue();
9056
9057 EVT ToVT = N->getValueType(0);
9058 if (ToVT.getScalarType() == MVT::i1)
9059 return LowerTruncatei1(N, DAG, Subtarget);
9060
9061 // MVE does not have a single instruction to perform the truncation of a v4i32
9062 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9063 // Most of the instructions in MVE follow the 'Beats' system, where moving
9064 // values from different lanes is usually something that the instructions
9065 // avoid.
9066 //
9067 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9068 // which take a the top/bottom half of a larger lane and extend it (or do the
9069 // opposite, truncating into the top/bottom lane from a larger lane). Note
9070 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9071 // bottom 16bits from each vector lane. This works really well with T/B
9072 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9073 // to move order.
9074 //
9075 // But truncates and sext/zext are always going to be fairly common from llvm.
9076 // We have several options for how to deal with them:
9077 // - Wherever possible combine them into an instruction that makes them
9078 // "free". This includes loads/stores, which can perform the trunc as part
9079 // of the memory operation. Or certain shuffles that can be turned into
9080 // VMOVN/VMOVL.
9081 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9082 // trunc(mul(sext(a), sext(b))) may become
9083 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9084 // this case can use VMULL). This is performed in the
9085 // MVELaneInterleavingPass.
9086 // - Otherwise we have an option. By default we would expand the
9087 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9088 // registers. One for each vector lane in the vector. This can obviously be
9089 // very expensive.
9090 // - The other option is to use the fact that loads/store can extend/truncate
9091 // to turn a trunc into two truncating stack stores and a stack reload. This
9092 // becomes 3 back-to-back memory operations, but at least that is less than
9093 // all the insert/extracts.
9094 //
9095 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9096 // are either optimized where they can be, or eventually lowered into stack
9097 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9098 // two early, where other instructions would be better, and stops us from
9099 // having to reconstruct multiple buildvector shuffles into loads/stores.
9100 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9101 return SDValue();
9102 EVT FromVT = N->getOperand(0).getValueType();
9103 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9104 return SDValue();
9105
9106 SDValue Lo, Hi;
9107 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9108 SDLoc DL(N);
9109 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9110}
9111
9113 const ARMSubtarget *Subtarget) {
9114 if (!Subtarget->hasMVEIntegerOps())
9115 return SDValue();
9116
9117 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9118
9119 EVT ToVT = N->getValueType(0);
9120 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9121 return SDValue();
9122 SDValue Op = N->getOperand(0);
9123 EVT FromVT = Op.getValueType();
9124 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9125 return SDValue();
9126
9127 SDLoc DL(N);
9128 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9129 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9130 ExtVT = MVT::v8i16;
9131
9132 unsigned Opcode =
9134 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9135 SDValue Ext1 = Ext.getValue(1);
9136
9137 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9138 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9139 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9140 }
9141
9142 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9143}
9144
9145/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9146/// element has been zero/sign-extended, depending on the isSigned parameter,
9147/// from an integer type half its size.
9149 bool isSigned) {
9150 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9151 EVT VT = N->getValueType(0);
9152 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9153 SDNode *BVN = N->getOperand(0).getNode();
9154 if (BVN->getValueType(0) != MVT::v4i32 ||
9155 BVN->getOpcode() != ISD::BUILD_VECTOR)
9156 return false;
9157 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9158 unsigned HiElt = 1 - LoElt;
9163 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9164 return false;
9165 if (isSigned) {
9166 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9167 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9168 return true;
9169 } else {
9170 if (Hi0->isZero() && Hi1->isZero())
9171 return true;
9172 }
9173 return false;
9174 }
9175
9176 if (N->getOpcode() != ISD::BUILD_VECTOR)
9177 return false;
9178
9179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9180 SDNode *Elt = N->getOperand(i).getNode();
9182 unsigned EltSize = VT.getScalarSizeInBits();
9183 unsigned HalfSize = EltSize / 2;
9184 if (isSigned) {
9185 if (!isIntN(HalfSize, C->getSExtValue()))
9186 return false;
9187 } else {
9188 if (!isUIntN(HalfSize, C->getZExtValue()))
9189 return false;
9190 }
9191 continue;
9192 }
9193 return false;
9194 }
9195
9196 return true;
9197}
9198
9199/// isSignExtended - Check if a node is a vector value that is sign-extended
9200/// or a constant BUILD_VECTOR with sign-extended elements.
9202 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9203 return true;
9204 if (isExtendedBUILD_VECTOR(N, DAG, true))
9205 return true;
9206 return false;
9207}
9208
9209/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9210/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9212 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9214 return true;
9215 if (isExtendedBUILD_VECTOR(N, DAG, false))
9216 return true;
9217 return false;
9218}
9219
9220static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9221 if (OrigVT.getSizeInBits() >= 64)
9222 return OrigVT;
9223
9224 assert(OrigVT.isSimple() && "Expecting a simple value type");
9225
9226 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9227 switch (OrigSimpleTy) {
9228 default: llvm_unreachable("Unexpected Vector Type");
9229 case MVT::v2i8:
9230 case MVT::v2i16:
9231 return MVT::v2i32;
9232 case MVT::v4i8:
9233 return MVT::v4i16;
9234 }
9235}
9236
9237/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9238/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9239/// We insert the required extension here to get the vector to fill a D register.
9241 const EVT &OrigTy,
9242 const EVT &ExtTy,
9243 unsigned ExtOpcode) {
9244 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9245 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9246 // 64-bits we need to insert a new extension so that it will be 64-bits.
9247 assert(ExtTy.is128BitVector() && "Unexpected extension size");
9248 if (OrigTy.getSizeInBits() >= 64)
9249 return N;
9250
9251 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9252 EVT NewVT = getExtensionTo64Bits(OrigTy);
9253
9254 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9255}
9256
9257/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9258/// does not do any sign/zero extension. If the original vector is less
9259/// than 64 bits, an appropriate extension will be added after the load to
9260/// reach a total size of 64 bits. We have to add the extension separately
9261/// because ARM does not have a sign/zero extending load for vectors.
9263 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9264
9265 // The load already has the right type.
9266 if (ExtendedTy == LD->getMemoryVT())
9267 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9268 LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9269 LD->getMemOperand()->getFlags());
9270
9271 // We need to create a zextload/sextload. We cannot just create a load
9272 // followed by a zext/zext node because LowerMUL is also run during normal
9273 // operation legalization where we can't create illegal types.
9274 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9275 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9276 LD->getMemoryVT(), LD->getAlign(),
9277 LD->getMemOperand()->getFlags());
9278}
9279
9280/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9281/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9282/// the unextended value. The unextended vector should be 64 bits so that it can
9283/// be used as an operand to a VMULL instruction. If the original vector size
9284/// before extension is less than 64 bits we add a an extension to resize
9285/// the vector to 64 bits.
9287 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9288 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9289 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9290 N->getOperand(0)->getValueType(0),
9291 N->getValueType(0),
9292 N->getOpcode());
9293
9294 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9295 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9296 "Expected extending load");
9297
9298 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9299 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9300 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9301 SDValue extLoad =
9302 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9303 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9304
9305 return newLoad;
9306 }
9307
9308 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9309 // have been legalized as a BITCAST from v4i32.
9310 if (N->getOpcode() == ISD::BITCAST) {
9311 SDNode *BVN = N->getOperand(0).getNode();
9313 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9314 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9315 return DAG.getBuildVector(
9316 MVT::v2i32, SDLoc(N),
9317 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9318 }
9319 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9320 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9321 EVT VT = N->getValueType(0);
9322 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9323 unsigned NumElts = VT.getVectorNumElements();
9324 MVT TruncVT = MVT::getIntegerVT(EltSize);
9326 SDLoc dl(N);
9327 for (unsigned i = 0; i != NumElts; ++i) {
9328 const APInt &CInt = N->getConstantOperandAPInt(i);
9329 // Element types smaller than 32 bits are not legal, so use i32 elements.
9330 // The values are implicitly truncated so sext vs. zext doesn't matter.
9331 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9332 }
9333 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9334}
9335
9336static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9337 unsigned Opcode = N->getOpcode();
9338 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9339 SDNode *N0 = N->getOperand(0).getNode();
9340 SDNode *N1 = N->getOperand(1).getNode();
9341 return N0->hasOneUse() && N1->hasOneUse() &&
9342 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9343 }
9344 return false;
9345}
9346
9347static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9348 unsigned Opcode = N->getOpcode();
9349 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9350 SDNode *N0 = N->getOperand(0).getNode();
9351 SDNode *N1 = N->getOperand(1).getNode();
9352 return N0->hasOneUse() && N1->hasOneUse() &&
9353 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9354 }
9355 return false;
9356}
9357
9359 // Multiplications are only custom-lowered for 128-bit vectors so that
9360 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9361 EVT VT = Op.getValueType();
9362 assert(VT.is128BitVector() && VT.isInteger() &&
9363 "unexpected type for custom-lowering ISD::MUL");
9364 SDNode *N0 = Op.getOperand(0).getNode();
9365 SDNode *N1 = Op.getOperand(1).getNode();
9366 unsigned NewOpc = 0;
9367 bool isMLA = false;
9368 bool isN0SExt = isSignExtended(N0, DAG);
9369 bool isN1SExt = isSignExtended(N1, DAG);
9370 if (isN0SExt && isN1SExt)
9371 NewOpc = ARMISD::VMULLs;
9372 else {
9373 bool isN0ZExt = isZeroExtended(N0, DAG);
9374 bool isN1ZExt = isZeroExtended(N1, DAG);
9375 if (isN0ZExt && isN1ZExt)
9376 NewOpc = ARMISD::VMULLu;
9377 else if (isN1SExt || isN1ZExt) {
9378 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9379 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9380 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9381 NewOpc = ARMISD::VMULLs;
9382 isMLA = true;
9383 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9384 NewOpc = ARMISD::VMULLu;
9385 isMLA = true;
9386 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9387 std::swap(N0, N1);
9388 NewOpc = ARMISD::VMULLu;
9389 isMLA = true;
9390 }
9391 }
9392
9393 if (!NewOpc) {
9394 if (VT == MVT::v2i64)
9395 // Fall through to expand this. It is not legal.
9396 return SDValue();
9397 else
9398 // Other vector multiplications are legal.
9399 return Op;
9400 }
9401 }
9402
9403 // Legalize to a VMULL instruction.
9404 SDLoc DL(Op);
9405 SDValue Op0;
9406 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9407 if (!isMLA) {
9408 Op0 = SkipExtensionForVMULL(N0, DAG);
9410 Op1.getValueType().is64BitVector() &&
9411 "unexpected types for extended operands to VMULL");
9412 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9413 }
9414
9415 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9416 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9417 // vmull q0, d4, d6
9418 // vmlal q0, d5, d6
9419 // is faster than
9420 // vaddl q0, d4, d5
9421 // vmovl q1, d6
9422 // vmul q0, q0, q1
9423 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9424 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9425 EVT Op1VT = Op1.getValueType();
9426 return DAG.getNode(N0->getOpcode(), DL, VT,
9427 DAG.getNode(NewOpc, DL, VT,
9428 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9429 DAG.getNode(NewOpc, DL, VT,
9430 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9431}
9432
9434 SelectionDAG &DAG) {
9435 // TODO: Should this propagate fast-math-flags?
9436
9437 // Convert to float
9438 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9439 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9440 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9441 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9442 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9443 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9444 // Get reciprocal estimate.
9445 // float4 recip = vrecpeq_f32(yf);
9446 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9447 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9448 Y);
9449 // Because char has a smaller range than uchar, we can actually get away
9450 // without any newton steps. This requires that we use a weird bias
9451 // of 0xb000, however (again, this has been exhaustively tested).
9452 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9453 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9454 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9455 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9456 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9457 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9458 // Convert back to short.
9459 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9460 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9461 return X;
9462}
9463
9465 SelectionDAG &DAG) {
9466 // TODO: Should this propagate fast-math-flags?
9467
9468 SDValue N2;
9469 // Convert to float.
9470 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9471 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9472 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9473 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9474 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9475 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9476
9477 // Use reciprocal estimate and one refinement step.
9478 // float4 recip = vrecpeq_f32(yf);
9479 // recip *= vrecpsq_f32(yf, recip);
9480 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9481 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9482 N1);
9483 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9484 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9485 N1, N2);
9486 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9487 // Because short has a smaller range than ushort, we can actually get away
9488 // with only a single newton step. This requires that we use a weird bias
9489 // of 89, however (again, this has been exhaustively tested).
9490 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9491 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9492 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9493 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9494 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9495 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9496 // Convert back to integer and return.
9497 // return vmovn_s32(vcvt_s32_f32(result));
9498 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9499 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9500 return N0;
9501}
9502
9504 const ARMSubtarget *ST) {
9505 EVT VT = Op.getValueType();
9506 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9507 "unexpected type for custom-lowering ISD::SDIV");
9508
9509 SDLoc dl(Op);
9510 SDValue N0 = Op.getOperand(0);
9511 SDValue N1 = Op.getOperand(1);
9512 SDValue N2, N3;
9513
9514 if (VT == MVT::v8i8) {
9515 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9516 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9517
9518 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9519 DAG.getIntPtrConstant(4, dl));
9520 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9521 DAG.getIntPtrConstant(4, dl));
9522 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9523 DAG.getIntPtrConstant(0, dl));
9524 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9525 DAG.getIntPtrConstant(0, dl));
9526
9527 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9528 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9529
9530 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9531 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9532
9533 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9534 return N0;
9535 }
9536 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9537}
9538
9540 const ARMSubtarget *ST) {
9541 // TODO: Should this propagate fast-math-flags?
9542 EVT VT = Op.getValueType();
9543 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9544 "unexpected type for custom-lowering ISD::UDIV");
9545
9546 SDLoc dl(Op);
9547 SDValue N0 = Op.getOperand(0);
9548 SDValue N1 = Op.getOperand(1);
9549 SDValue N2, N3;
9550
9551 if (VT == MVT::v8i8) {
9552 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9553 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9554
9555 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9556 DAG.getIntPtrConstant(4, dl));
9557 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9558 DAG.getIntPtrConstant(4, dl));
9559 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9560 DAG.getIntPtrConstant(0, dl));
9561 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9562 DAG.getIntPtrConstant(0, dl));
9563
9564 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9565 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9566
9567 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9568 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9569
9570 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9571 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9572 MVT::i32),
9573 N0);
9574 return N0;
9575 }
9576
9577 // v4i16 sdiv ... Convert to float.
9578 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9579 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9580 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9581 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9582 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9583 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9584
9585 // Use reciprocal estimate and two refinement steps.
9586 // float4 recip = vrecpeq_f32(yf);
9587 // recip *= vrecpsq_f32(yf, recip);
9588 // recip *= vrecpsq_f32(yf, recip);
9589 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9590 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9591 BN1);
9592 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9593 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9594 BN1, N2);
9595 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9596 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9597 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9598 BN1, N2);
9599 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9600 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9601 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9602 // and that it will never cause us to return an answer too large).
9603 // float4 result = as_float4(as_int4(xf*recip) + 2);
9604 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9605 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9606 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9607 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9608 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9609 // Convert back to integer and return.
9610 // return vmovn_u32(vcvt_s32_f32(result));
9611 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9612 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9613 return N0;
9614}
9615
9617 unsigned Opcode, bool IsSigned) {
9618 EVT VT0 = Op.getValue(0).getValueType();
9619 EVT VT1 = Op.getValue(1).getValueType();
9620
9621 bool InvertCarry = Opcode == ARMISD::SUBE;
9622 SDValue OpLHS = Op.getOperand(0);
9623 SDValue OpRHS = Op.getOperand(1);
9624 SDValue OpCarryIn = valueToCarryFlag(Op.getOperand(2), DAG, InvertCarry);
9625
9626 SDLoc DL(Op);
9627
9628 SDValue Result = DAG.getNode(Opcode, DL, DAG.getVTList(VT0, MVT::i32), OpLHS,
9629 OpRHS, OpCarryIn);
9630
9631 SDValue OutFlag =
9632 IsSigned ? overflowFlagToValue(Result.getValue(1), VT1, DAG)
9633 : carryFlagToValue(Result.getValue(1), VT1, DAG, InvertCarry);
9634
9635 return DAG.getMergeValues({Result, OutFlag}, DL);
9636}
9637
9638SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9639 bool Signed,
9640 SDValue &Chain) const {
9641 EVT VT = Op.getValueType();
9642 assert((VT == MVT::i32 || VT == MVT::i64) &&
9643 "unexpected type for custom lowering DIV");
9644 SDLoc dl(Op);
9645
9646 const auto &DL = DAG.getDataLayout();
9647 RTLIB::Libcall LC;
9648 if (Signed)
9649 LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
9650 else
9651 LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
9652
9653 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
9654 SDValue ES = DAG.getExternalSymbol(LCImpl, getPointerTy(DL));
9655
9657
9658 for (auto AI : {1, 0}) {
9659 SDValue Operand = Op.getOperand(AI);
9660 Args.emplace_back(Operand,
9661 Operand.getValueType().getTypeForEVT(*DAG.getContext()));
9662 }
9663
9664 CallLoweringInfo CLI(DAG);
9665 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
9667 VT.getTypeForEVT(*DAG.getContext()), ES, std::move(Args));
9668
9669 return LowerCallTo(CLI).first;
9670}
9671
9672// This is a code size optimisation: return the original SDIV node to
9673// DAGCombiner when we don't want to expand SDIV into a sequence of
9674// instructions, and an empty node otherwise which will cause the
9675// SDIV to be expanded in DAGCombine.
9676SDValue
9677ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9678 SelectionDAG &DAG,
9679 SmallVectorImpl<SDNode *> &Created) const {
9680 // TODO: Support SREM
9681 if (N->getOpcode() != ISD::SDIV)
9682 return SDValue();
9683
9684 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9685 const bool MinSize = ST.hasMinSize();
9686 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9687 : ST.hasDivideInARMMode();
9688
9689 // Don't touch vector types; rewriting this may lead to scalarizing
9690 // the int divs.
9691 if (N->getOperand(0).getValueType().isVector())
9692 return SDValue();
9693
9694 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9695 // hwdiv support for this to be really profitable.
9696 if (!(MinSize && HasDivide))
9697 return SDValue();
9698
9699 // ARM mode is a bit simpler than Thumb: we can handle large power
9700 // of 2 immediates with 1 mov instruction; no further checks required,
9701 // just return the sdiv node.
9702 if (!ST.isThumb())
9703 return SDValue(N, 0);
9704
9705 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9706 // and thus lose the code size benefits of a MOVS that requires only 2.
9707 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9708 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9709 if (Divisor.sgt(128))
9710 return SDValue();
9711
9712 return SDValue(N, 0);
9713}
9714
9715SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9716 bool Signed) const {
9717 assert(Op.getValueType() == MVT::i32 &&
9718 "unexpected type for custom lowering DIV");
9719 SDLoc dl(Op);
9720
9721 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9722 DAG.getEntryNode(), Op.getOperand(1));
9723
9724 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9725}
9726
9728 SDLoc DL(N);
9729 SDValue Op = N->getOperand(1);
9730 if (N->getValueType(0) == MVT::i32)
9731 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9732 SDValue Lo, Hi;
9733 std::tie(Lo, Hi) = DAG.SplitScalar(Op, DL, MVT::i32, MVT::i32);
9734 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9735 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9736}
9737
9738void ARMTargetLowering::ExpandDIV_Windows(
9739 SDValue Op, SelectionDAG &DAG, bool Signed,
9741 const auto &DL = DAG.getDataLayout();
9742
9743 assert(Op.getValueType() == MVT::i64 &&
9744 "unexpected type for custom lowering DIV");
9745 SDLoc dl(Op);
9746
9747 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9748
9749 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9750
9751 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9752 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9753 DAG.getConstant(32, dl, getPointerTy(DL)));
9754 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9755
9756 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9757}
9758
9759std::pair<SDValue, SDValue>
9760ARMTargetLowering::LowerAEABIUnalignedLoad(SDValue Op,
9761 SelectionDAG &DAG) const {
9762 // If we have an unaligned load from a i32 or i64 that would normally be
9763 // split into separate ldrb's, we can use the __aeabi_uread4/__aeabi_uread8
9764 // functions instead.
9765 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9766 EVT MemVT = LD->getMemoryVT();
9767 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9768 return std::make_pair(SDValue(), SDValue());
9769
9770 const auto &MF = DAG.getMachineFunction();
9771 unsigned AS = LD->getAddressSpace();
9772 Align Alignment = LD->getAlign();
9773 const DataLayout &DL = DAG.getDataLayout();
9774 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9775
9776 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9777 Alignment <= llvm::Align(2)) {
9778
9779 RTLIB::Libcall LC =
9780 (MemVT == MVT::i32) ? RTLIB::AEABI_UREAD4 : RTLIB::AEABI_UREAD8;
9781
9782 MakeLibCallOptions Opts;
9783 SDLoc dl(Op);
9784
9785 auto Pair = makeLibCall(DAG, LC, MemVT.getSimpleVT(), LD->getBasePtr(),
9786 Opts, dl, LD->getChain());
9787
9788 // If necessary, extend the node to 64bit
9789 if (LD->getExtensionType() != ISD::NON_EXTLOAD) {
9790 unsigned ExtType = LD->getExtensionType() == ISD::SEXTLOAD
9793 SDValue EN = DAG.getNode(ExtType, dl, LD->getValueType(0), Pair.first);
9794 Pair.first = EN;
9795 }
9796 return Pair;
9797 }
9798
9799 // Default expand to individual loads
9800 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9801 return expandUnalignedLoad(LD, DAG);
9802 return std::make_pair(SDValue(), SDValue());
9803}
9804
9805SDValue ARMTargetLowering::LowerAEABIUnalignedStore(SDValue Op,
9806 SelectionDAG &DAG) const {
9807 // If we have an unaligned store to a i32 or i64 that would normally be
9808 // split into separate ldrb's, we can use the __aeabi_uwrite4/__aeabi_uwrite8
9809 // functions instead.
9810 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9811 EVT MemVT = ST->getMemoryVT();
9812 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9813 return SDValue();
9814
9815 const auto &MF = DAG.getMachineFunction();
9816 unsigned AS = ST->getAddressSpace();
9817 Align Alignment = ST->getAlign();
9818 const DataLayout &DL = DAG.getDataLayout();
9819 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9820
9821 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9822 Alignment <= llvm::Align(2)) {
9823
9824 SDLoc dl(Op);
9825
9826 // If necessary, trunc the value to 32bit
9827 SDValue StoreVal = ST->getOperand(1);
9828 if (ST->isTruncatingStore())
9829 StoreVal = DAG.getNode(ISD::TRUNCATE, dl, MemVT, ST->getOperand(1));
9830
9831 RTLIB::Libcall LC =
9832 (MemVT == MVT::i32) ? RTLIB::AEABI_UWRITE4 : RTLIB::AEABI_UWRITE8;
9833
9834 MakeLibCallOptions Opts;
9835 auto CallResult =
9836 makeLibCall(DAG, LC, MVT::isVoid, {StoreVal, ST->getBasePtr()}, Opts,
9837 dl, ST->getChain());
9838
9839 return CallResult.second;
9840 }
9841
9842 // Default expand to individual stores
9843 if (!allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Alignment))
9844 return expandUnalignedStore(ST, DAG);
9845 return SDValue();
9846}
9847
9849 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9850 EVT MemVT = LD->getMemoryVT();
9851 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9852 MemVT == MVT::v16i1) &&
9853 "Expected a predicate type!");
9854 assert(MemVT == Op.getValueType());
9855 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9856 "Expected a non-extending load");
9857 assert(LD->isUnindexed() && "Expected a unindexed load");
9858
9859 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9860 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9861 // need to make sure that 8/4/2 bits are actually loaded into the correct
9862 // place, which means loading the value and then shuffling the values into
9863 // the bottom bits of the predicate.
9864 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9865 // for BE).
9866 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9867 // a natural VMSR(load), so needs to be reversed.
9868
9869 SDLoc dl(Op);
9870 SDValue Load = DAG.getExtLoad(
9871 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9873 LD->getMemOperand());
9874 SDValue Val = Load;
9875 if (DAG.getDataLayout().isBigEndian())
9876 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
9877 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
9878 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
9879 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
9880 if (MemVT != MVT::v16i1)
9881 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9882 DAG.getConstant(0, dl, MVT::i32));
9883 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9884}
9885
9886void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9887 SelectionDAG &DAG) const {
9888 LoadSDNode *LD = cast<LoadSDNode>(N);
9889 EVT MemVT = LD->getMemoryVT();
9890
9891 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9892 !Subtarget->isThumb1Only() && LD->isVolatile() &&
9893 LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9894 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9895 SDLoc dl(N);
9897 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9898 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9899 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9900 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9901 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9902 Results.append({Pair, Result.getValue(2)});
9903 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9904 auto Pair = LowerAEABIUnalignedLoad(SDValue(N, 0), DAG);
9905 if (Pair.first) {
9906 Results.push_back(Pair.first);
9907 Results.push_back(Pair.second);
9908 }
9909 }
9910}
9911
9913 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9914 EVT MemVT = ST->getMemoryVT();
9915 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9916 MemVT == MVT::v16i1) &&
9917 "Expected a predicate type!");
9918 assert(MemVT == ST->getValue().getValueType());
9919 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9920 assert(ST->isUnindexed() && "Expected a unindexed store");
9921
9922 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
9923 // top bits unset and a scalar store.
9924 SDLoc dl(Op);
9925 SDValue Build = ST->getValue();
9926 if (MemVT != MVT::v16i1) {
9928 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9929 unsigned Elt = DAG.getDataLayout().isBigEndian()
9930 ? MemVT.getVectorNumElements() - I - 1
9931 : I;
9932 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9933 DAG.getConstant(Elt, dl, MVT::i32)));
9934 }
9935 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9936 Ops.push_back(DAG.getUNDEF(MVT::i32));
9937 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9938 }
9939 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9940 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9941 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
9942 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
9943 DAG.getConstant(16, dl, MVT::i32));
9944 return DAG.getTruncStore(
9945 ST->getChain(), dl, GRP, ST->getBasePtr(),
9947 ST->getMemOperand());
9948}
9949
9950SDValue ARMTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG,
9951 const ARMSubtarget *Subtarget) const {
9952 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9953 EVT MemVT = ST->getMemoryVT();
9954
9955 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9956 !Subtarget->isThumb1Only() && ST->isVolatile() &&
9957 ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9958 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9959 SDNode *N = Op.getNode();
9960 SDLoc dl(N);
9961
9962 SDValue Lo = DAG.getNode(
9963 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9964 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9965 MVT::i32));
9966 SDValue Hi = DAG.getNode(
9967 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9968 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9969 MVT::i32));
9970
9971 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9972 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9973 MemVT, ST->getMemOperand());
9974 } else if (Subtarget->hasMVEIntegerOps() &&
9975 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9976 MemVT == MVT::v16i1))) {
9977 return LowerPredicateStore(Op, DAG);
9978 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9979 return LowerAEABIUnalignedStore(Op, DAG);
9980 }
9981 return SDValue();
9982}
9983
9984static bool isZeroVector(SDValue N) {
9985 return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9986 (N->getOpcode() == ARMISD::VMOVIMM &&
9987 isNullConstant(N->getOperand(0))));
9988}
9989
9992 MVT VT = Op.getSimpleValueType();
9993 SDValue Mask = N->getMask();
9994 SDValue PassThru = N->getPassThru();
9995 SDLoc dl(Op);
9996
9997 if (isZeroVector(PassThru))
9998 return Op;
9999
10000 // MVE Masked loads use zero as the passthru value. Here we convert undef to
10001 // zero too, and other values are lowered to a select.
10002 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
10003 DAG.getTargetConstant(0, dl, MVT::i32));
10004 SDValue NewLoad = DAG.getMaskedLoad(
10005 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
10006 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
10007 N->getExtensionType(), N->isExpandingLoad());
10008 SDValue Combo = NewLoad;
10009 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
10010 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
10011 isZeroVector(PassThru->getOperand(0));
10012 if (!PassThru.isUndef() && !PassThruIsCastZero)
10013 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
10014 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
10015}
10016
10018 const ARMSubtarget *ST) {
10019 if (!ST->hasMVEIntegerOps())
10020 return SDValue();
10021
10022 SDLoc dl(Op);
10023 unsigned BaseOpcode = 0;
10024 switch (Op->getOpcode()) {
10025 default: llvm_unreachable("Expected VECREDUCE opcode");
10026 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10027 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10028 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10029 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10030 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10031 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10032 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10033 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10034 }
10035
10036 SDValue Op0 = Op->getOperand(0);
10037 EVT VT = Op0.getValueType();
10038 EVT EltVT = VT.getVectorElementType();
10039 unsigned NumElts = VT.getVectorNumElements();
10040 unsigned NumActiveLanes = NumElts;
10041
10042 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10043 NumActiveLanes == 2) &&
10044 "Only expected a power 2 vector size");
10045
10046 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10047 // allows us to easily extract vector elements from the lanes.
10048 while (NumActiveLanes > 4) {
10049 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10050 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10051 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10052 NumActiveLanes /= 2;
10053 }
10054
10055 SDValue Res;
10056 if (NumActiveLanes == 4) {
10057 // The remaining 4 elements are summed sequentially
10058 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10059 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10060 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10061 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10062 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10063 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10064 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10065 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10066 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10067 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10068 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10069 } else {
10070 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10071 DAG.getConstant(0, dl, MVT::i32));
10072 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10073 DAG.getConstant(1, dl, MVT::i32));
10074 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10075 }
10076
10077 // Result type may be wider than element type.
10078 if (EltVT != Op->getValueType(0))
10079 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10080 return Res;
10081}
10082
10084 const ARMSubtarget *ST) {
10085 if (!ST->hasMVEFloatOps())
10086 return SDValue();
10087 return LowerVecReduce(Op, DAG, ST);
10088}
10089
10091 const ARMSubtarget *ST) {
10092 if (!ST->hasNEON())
10093 return SDValue();
10094
10095 SDLoc dl(Op);
10096 SDValue Op0 = Op->getOperand(0);
10097 EVT VT = Op0.getValueType();
10098 EVT EltVT = VT.getVectorElementType();
10099
10100 unsigned PairwiseIntrinsic = 0;
10101 switch (Op->getOpcode()) {
10102 default:
10103 llvm_unreachable("Expected VECREDUCE opcode");
10105 PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10106 break;
10108 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10109 break;
10111 PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10112 break;
10114 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10115 break;
10116 }
10117 SDValue PairwiseOp = DAG.getConstant(PairwiseIntrinsic, dl, MVT::i32);
10118
10119 unsigned NumElts = VT.getVectorNumElements();
10120 unsigned NumActiveLanes = NumElts;
10121
10122 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10123 NumActiveLanes == 2) &&
10124 "Only expected a power 2 vector size");
10125
10126 // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10127 if (VT.is128BitVector()) {
10128 SDValue Lo, Hi;
10129 std::tie(Lo, Hi) = DAG.SplitVector(Op0, dl);
10130 VT = Lo.getValueType();
10131 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Lo, Hi});
10132 NumActiveLanes /= 2;
10133 }
10134
10135 // Use pairwise reductions until one lane remains
10136 while (NumActiveLanes > 1) {
10137 Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Op0, Op0});
10138 NumActiveLanes /= 2;
10139 }
10140
10141 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10142 DAG.getConstant(0, dl, MVT::i32));
10143
10144 // Result type may be wider than element type.
10145 if (EltVT != Op.getValueType()) {
10146 unsigned Extend = 0;
10147 switch (Op->getOpcode()) {
10148 default:
10149 llvm_unreachable("Expected VECREDUCE opcode");
10152 Extend = ISD::ZERO_EXTEND;
10153 break;
10156 Extend = ISD::SIGN_EXTEND;
10157 break;
10158 }
10159 Res = DAG.getNode(Extend, dl, Op.getValueType(), Res);
10160 }
10161 return Res;
10162}
10163
10165 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10166 // Acquire/Release load/store is not legal for targets without a dmb or
10167 // equivalent available.
10168 return SDValue();
10169
10170 // Monotonic load/store is legal for all targets.
10171 return Op;
10172}
10173
10176 SelectionDAG &DAG,
10177 const ARMSubtarget *Subtarget) {
10178 SDLoc DL(N);
10179 // Under Power Management extensions, the cycle-count is:
10180 // mrc p15, #0, <Rt>, c9, c13, #0
10181 SDValue Ops[] = { N->getOperand(0), // Chain
10182 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10183 DAG.getTargetConstant(15, DL, MVT::i32),
10184 DAG.getTargetConstant(0, DL, MVT::i32),
10185 DAG.getTargetConstant(9, DL, MVT::i32),
10186 DAG.getTargetConstant(13, DL, MVT::i32),
10187 DAG.getTargetConstant(0, DL, MVT::i32)
10188 };
10189
10190 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10191 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10192 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10193 DAG.getConstant(0, DL, MVT::i32)));
10194 Results.push_back(Cycles32.getValue(1));
10195}
10196
10198 SDValue V1) {
10199 SDLoc dl(V0.getNode());
10200 SDValue RegClass =
10201 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10202 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10203 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10204 const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10205 return SDValue(
10206 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10207}
10208
10210 SDLoc dl(V.getNode());
10211 auto [VLo, VHi] = DAG.SplitScalar(V, dl, MVT::i32, MVT::i32);
10212 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10213 if (isBigEndian)
10214 std::swap(VLo, VHi);
10215 return createGPRPairNode2xi32(DAG, VLo, VHi);
10216}
10217
10220 SelectionDAG &DAG) {
10221 assert(N->getValueType(0) == MVT::i64 &&
10222 "AtomicCmpSwap on types less than 64 should be legal");
10223 SDValue Ops[] = {
10224 createGPRPairNode2xi32(DAG, N->getOperand(1),
10225 DAG.getUNDEF(MVT::i32)), // pointer, temp
10226 createGPRPairNodei64(DAG, N->getOperand(2)), // expected
10227 createGPRPairNodei64(DAG, N->getOperand(3)), // new
10228 N->getOperand(0), // chain in
10229 };
10230 SDNode *CmpSwap = DAG.getMachineNode(
10231 ARM::CMP_SWAP_64, SDLoc(N),
10232 DAG.getVTList(MVT::Untyped, MVT::Untyped, MVT::Other), Ops);
10233
10234 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10235 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10236
10237 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10238
10239 SDValue Lo =
10240 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10241 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10242 SDValue Hi =
10243 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10244 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10245 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10246 Results.push_back(SDValue(CmpSwap, 2));
10247}
10248
10249SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10250 SDLoc dl(Op);
10251 EVT VT = Op.getValueType();
10252 SDValue Chain = Op.getOperand(0);
10253 SDValue LHS = Op.getOperand(1);
10254 SDValue RHS = Op.getOperand(2);
10255 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10256 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10257
10258 // If we don't have instructions of this float type then soften to a libcall
10259 // and use SETCC instead.
10260 if (isUnsupportedFloatingType(LHS.getValueType())) {
10261 softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS,
10262 Chain, IsSignaling);
10263 if (!RHS.getNode()) {
10264 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10265 CC = ISD::SETNE;
10266 }
10267 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10268 DAG.getCondCode(CC));
10269 return DAG.getMergeValues({Result, Chain}, dl);
10270 }
10271
10272 ARMCC::CondCodes CondCode, CondCode2;
10273 FPCCToARMCC(CC, CondCode, CondCode2);
10274
10275 SDValue True = DAG.getConstant(1, dl, VT);
10276 SDValue False = DAG.getConstant(0, dl, VT);
10277 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10278 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10279 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, Cmp, DAG);
10280 if (CondCode2 != ARMCC::AL) {
10281 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10282 Result = getCMOV(dl, VT, Result, True, ARMcc, Cmp, DAG);
10283 }
10284 return DAG.getMergeValues({Result, Chain}, dl);
10285}
10286
10287SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10288 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10289
10290 EVT VT = getPointerTy(DAG.getDataLayout());
10291 int FI = MFI.CreateFixedObject(4, 0, false);
10292 return DAG.getFrameIndex(FI, VT);
10293}
10294
10295SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10296 SelectionDAG &DAG) const {
10297 SDLoc DL(Op);
10298 MakeLibCallOptions CallOptions;
10299 MVT SVT = Op.getOperand(0).getSimpleValueType();
10300 RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
10301 SDValue Res =
10302 makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
10303 return DAG.getBitcast(MVT::i32, Res);
10304}
10305
10306SDValue ARMTargetLowering::LowerCMP(SDValue Op, SelectionDAG &DAG) const {
10307 SDLoc dl(Op);
10308 SDValue LHS = Op.getOperand(0);
10309 SDValue RHS = Op.getOperand(1);
10310
10311 // Determine if this is signed or unsigned comparison
10312 bool IsSigned = (Op.getOpcode() == ISD::SCMP);
10313
10314 // Special case for Thumb1 UCMP only
10315 if (!IsSigned && Subtarget->isThumb1Only()) {
10316 // For Thumb unsigned comparison, use this sequence:
10317 // subs r2, r0, r1 ; r2 = LHS - RHS, sets flags
10318 // sbc r2, r2 ; r2 = r2 - r2 - !carry
10319 // cmp r1, r0 ; compare RHS with LHS
10320 // sbc r1, r1 ; r1 = r1 - r1 - !carry
10321 // subs r0, r2, r1 ; r0 = r2 - r1 (final result)
10322
10323 // First subtraction: LHS - RHS
10324 SDValue Sub1WithFlags = DAG.getNode(
10325 ARMISD::SUBC, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10326 SDValue Sub1Result = Sub1WithFlags.getValue(0);
10327 SDValue Flags1 = Sub1WithFlags.getValue(1);
10328
10329 // SUBE: Sub1Result - Sub1Result - !carry
10330 // This gives 0 if LHS >= RHS (unsigned), -1 if LHS < RHS (unsigned)
10331 SDValue Sbc1 =
10332 DAG.getNode(ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT),
10333 Sub1Result, Sub1Result, Flags1);
10334 SDValue Sbc1Result = Sbc1.getValue(0);
10335
10336 // Second comparison: RHS vs LHS (reverse comparison)
10337 SDValue CmpFlags = DAG.getNode(ARMISD::CMP, dl, FlagsVT, RHS, LHS);
10338
10339 // SUBE: RHS - RHS - !carry
10340 // This gives 0 if RHS <= LHS (unsigned), -1 if RHS > LHS (unsigned)
10341 SDValue Sbc2 = DAG.getNode(
10342 ARMISD::SUBE, dl, DAG.getVTList(MVT::i32, FlagsVT), RHS, RHS, CmpFlags);
10343 SDValue Sbc2Result = Sbc2.getValue(0);
10344
10345 // Final subtraction: Sbc1Result - Sbc2Result (no flags needed)
10346 SDValue Result =
10347 DAG.getNode(ISD::SUB, dl, MVT::i32, Sbc1Result, Sbc2Result);
10348 if (Op.getValueType() != MVT::i32)
10349 Result = DAG.getSExtOrTrunc(Result, dl, Op.getValueType());
10350
10351 return Result;
10352 }
10353
10354 // For the ARM assembly pattern:
10355 // subs r0, r0, r1 ; subtract RHS from LHS and set flags
10356 // movgt r0, #1 ; if LHS > RHS, set result to 1 (GT for signed, HI for
10357 // unsigned) mvnlt r0, #0 ; if LHS < RHS, set result to -1 (LT for
10358 // signed, LO for unsigned)
10359 // ; if LHS == RHS, result remains 0 from the subs
10360
10361 // Optimization: if RHS is a subtraction against 0, use ADDC instead of SUBC
10362 unsigned Opcode = ARMISD::SUBC;
10363
10364 // Check if RHS is a subtraction against 0: (0 - X)
10365 if (RHS.getOpcode() == ISD::SUB) {
10366 SDValue SubLHS = RHS.getOperand(0);
10367 SDValue SubRHS = RHS.getOperand(1);
10368
10369 // Check if it's 0 - X
10370 if (isNullConstant(SubLHS)) {
10371 bool CanUseAdd = false;
10372 if (IsSigned) {
10373 // For SCMP: only if X is known to never be INT_MIN (to avoid overflow)
10374 if (RHS->getFlags().hasNoSignedWrap() || !DAG.computeKnownBits(SubRHS)
10376 .isMinSignedValue()) {
10377 CanUseAdd = true;
10378 }
10379 } else {
10380 // For UCMP: only if X is known to never be zero
10381 if (DAG.isKnownNeverZero(SubRHS)) {
10382 CanUseAdd = true;
10383 }
10384 }
10385
10386 if (CanUseAdd) {
10387 Opcode = ARMISD::ADDC;
10388 RHS = SubRHS; // Replace RHS with X, so we do LHS + X instead of
10389 // LHS - (0 - X)
10390 }
10391 }
10392 }
10393
10394 // Generate the operation with flags
10395 SDValue OpWithFlags =
10396 DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, FlagsVT), LHS, RHS);
10397
10398 SDValue OpResult = OpWithFlags.getValue(0);
10399 SDValue Flags = OpWithFlags.getValue(1);
10400
10401 // Constants for conditional moves
10402 SDValue One = DAG.getConstant(1, dl, MVT::i32);
10403 SDValue MinusOne = DAG.getAllOnesConstant(dl, MVT::i32);
10404
10405 // Select condition codes based on signed vs unsigned
10406 ARMCC::CondCodes GTCond = IsSigned ? ARMCC::GT : ARMCC::HI;
10407 ARMCC::CondCodes LTCond = IsSigned ? ARMCC::LT : ARMCC::LO;
10408
10409 // First conditional move: if greater than, set to 1
10410 SDValue GTCondValue = DAG.getConstant(GTCond, dl, MVT::i32);
10411 SDValue Result1 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, OpResult, One,
10412 GTCondValue, Flags);
10413
10414 // Second conditional move: if less than, set to -1
10415 SDValue LTCondValue = DAG.getConstant(LTCond, dl, MVT::i32);
10416 SDValue Result2 = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, Result1, MinusOne,
10417 LTCondValue, Flags);
10418
10419 if (Op.getValueType() != MVT::i32)
10420 Result2 = DAG.getSExtOrTrunc(Result2, dl, Op.getValueType());
10421
10422 return Result2;
10423}
10424
10426 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10427 switch (Op.getOpcode()) {
10428 default: llvm_unreachable("Don't know how to custom lower this!");
10429 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10430 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10431 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10432 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10433 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10434 case ISD::SELECT: return LowerSELECT(Op, DAG);
10435 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10436 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10437 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10438 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10439 case ISD::VASTART: return LowerVASTART(Op, DAG);
10440 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10441 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10442 case ISD::SINT_TO_FP:
10443 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10446 case ISD::FP_TO_SINT:
10447 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10449 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10450 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10451 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10452 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10453 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10454 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10455 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10456 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10457 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10458 Subtarget);
10459 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10460 case ISD::SHL:
10461 case ISD::SRL:
10462 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10463 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10464 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10465 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10466 case ISD::SRL_PARTS:
10467 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10468 case ISD::CTTZ:
10469 case ISD::CTTZ_ZERO_POISON: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10470 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10471 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10472 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10473 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10474 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10475 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10476 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10477 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10478 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10479 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10480 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10481 case ISD::SIGN_EXTEND:
10482 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10483 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
10484 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10485 case ISD::SET_FPMODE:
10486 return LowerSET_FPMODE(Op, DAG);
10487 case ISD::RESET_FPMODE:
10488 return LowerRESET_FPMODE(Op, DAG);
10489 case ISD::MUL: return LowerMUL(Op, DAG);
10490 case ISD::SDIV:
10491 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10492 !Op.getValueType().isVector())
10493 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10494 return LowerSDIV(Op, DAG, Subtarget);
10495 case ISD::UDIV:
10496 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10497 !Op.getValueType().isVector())
10498 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10499 return LowerUDIV(Op, DAG, Subtarget);
10500 case ISD::UADDO_CARRY:
10501 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, false /*unsigned*/);
10502 case ISD::USUBO_CARRY:
10503 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, false /*unsigned*/);
10504 case ISD::SADDO_CARRY:
10505 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::ADDE, true /*signed*/);
10506 case ISD::SSUBO_CARRY:
10507 return LowerADDSUBO_CARRY(Op, DAG, ARMISD::SUBE, true /*signed*/);
10508 case ISD::UADDO:
10509 case ISD::USUBO:
10510 case ISD::UMULO:
10511 case ISD::SADDO:
10512 case ISD::SSUBO:
10513 case ISD::SMULO:
10514 return LowerALUO(Op, DAG);
10515 case ISD::SADDSAT:
10516 case ISD::SSUBSAT:
10517 case ISD::UADDSAT:
10518 case ISD::USUBSAT:
10519 return LowerADDSUBSAT(Op, DAG, Subtarget);
10520 case ISD::LOAD: {
10521 auto *LD = cast<LoadSDNode>(Op);
10522 EVT MemVT = LD->getMemoryVT();
10523 if (Subtarget->hasMVEIntegerOps() &&
10524 (MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10525 MemVT == MVT::v16i1))
10526 return LowerPredicateLoad(Op, DAG);
10527
10528 auto Pair = LowerAEABIUnalignedLoad(Op, DAG);
10529 if (Pair.first)
10530 return DAG.getMergeValues({Pair.first, Pair.second}, SDLoc(Pair.first));
10531 return SDValue();
10532 }
10533 case ISD::STORE:
10534 return LowerSTORE(Op, DAG, Subtarget);
10535 case ISD::MLOAD:
10536 return LowerMLOAD(Op, DAG);
10537 case ISD::VECREDUCE_MUL:
10538 case ISD::VECREDUCE_AND:
10539 case ISD::VECREDUCE_OR:
10540 case ISD::VECREDUCE_XOR:
10541 return LowerVecReduce(Op, DAG, Subtarget);
10546 return LowerVecReduceF(Op, DAG, Subtarget);
10551 return LowerVecReduceMinMax(Op, DAG, Subtarget);
10552 case ISD::ATOMIC_LOAD:
10553 case ISD::ATOMIC_STORE:
10554 return LowerAtomicLoadStore(Op, DAG);
10555 case ISD::SDIVREM:
10556 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10558 if (getTargetMachine().getTargetTriple().isOSWindows())
10559 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10560 llvm_unreachable("Don't know how to custom lower this!");
10562 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10564 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10565 case ISD::STRICT_FSETCC:
10566 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10567 case ISD::SPONENTRY:
10568 return LowerSPONENTRY(Op, DAG);
10569 case ISD::FP_TO_BF16:
10570 return LowerFP_TO_BF16(Op, DAG);
10571 case ARMISD::WIN__DBZCHK: return SDValue();
10572 case ISD::UCMP:
10573 case ISD::SCMP:
10574 return LowerCMP(Op, DAG);
10575 case ISD::ABS:
10576 return LowerABS(Op, DAG);
10577 case ISD::STRICT_LROUND:
10579 case ISD::STRICT_LRINT:
10580 case ISD::STRICT_LLRINT: {
10581 assert((Op.getOperand(1).getValueType() == MVT::f16 ||
10582 Op.getOperand(1).getValueType() == MVT::bf16) &&
10583 "Expected custom lowering of rounding operations only for f16");
10584 SDLoc DL(Op);
10585 SDValue Ext = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
10586 {Op.getOperand(0), Op.getOperand(1)});
10587 return DAG.getNode(Op.getOpcode(), DL, {Op.getValueType(), MVT::Other},
10588 {Ext.getValue(1), Ext.getValue(0)});
10589 }
10590 }
10591}
10592
10594 SelectionDAG &DAG) {
10595 unsigned IntNo = N->getConstantOperandVal(0);
10596 unsigned Opc = 0;
10597 if (IntNo == Intrinsic::arm_smlald)
10598 Opc = ARMISD::SMLALD;
10599 else if (IntNo == Intrinsic::arm_smlaldx)
10600 Opc = ARMISD::SMLALDX;
10601 else if (IntNo == Intrinsic::arm_smlsld)
10602 Opc = ARMISD::SMLSLD;
10603 else if (IntNo == Intrinsic::arm_smlsldx)
10604 Opc = ARMISD::SMLSLDX;
10605 else
10606 return;
10607
10608 SDLoc dl(N);
10609 SDValue Lo, Hi;
10610 std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(3), dl, MVT::i32, MVT::i32);
10611
10612 SDValue LongMul = DAG.getNode(Opc, dl,
10613 DAG.getVTList(MVT::i32, MVT::i32),
10614 N->getOperand(1), N->getOperand(2),
10615 Lo, Hi);
10616 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10617 LongMul.getValue(0), LongMul.getValue(1)));
10618}
10619
10620/// ReplaceNodeResults - Replace the results of node with an illegal result
10621/// type with new values built out of custom code.
10624 SelectionDAG &DAG) const {
10625 SDValue Res;
10626 switch (N->getOpcode()) {
10627 default:
10628 llvm_unreachable("Don't know how to custom expand this!");
10629 case ISD::READ_REGISTER:
10631 break;
10632 case ISD::BITCAST:
10633 Res = ExpandBITCAST(N, DAG, Subtarget);
10634 break;
10635 case ISD::SRL:
10636 case ISD::SRA:
10637 case ISD::SHL:
10638 Res = Expand64BitShift(N, DAG, Subtarget);
10639 break;
10640 case ISD::SREM:
10641 case ISD::UREM:
10642 Res = LowerREM(N, DAG);
10643 break;
10644 case ISD::SDIVREM:
10645 case ISD::UDIVREM:
10646 Res = LowerDivRem(SDValue(N, 0), DAG);
10647 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10648 Results.push_back(Res.getValue(0));
10649 Results.push_back(Res.getValue(1));
10650 return;
10651 case ISD::SADDSAT:
10652 case ISD::SSUBSAT:
10653 case ISD::UADDSAT:
10654 case ISD::USUBSAT:
10655 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10656 break;
10658 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10659 return;
10660 case ISD::UDIV:
10661 case ISD::SDIV:
10662 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
10663 "can only expand DIV on Windows");
10664 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10665 Results);
10668 return;
10670 return ReplaceLongIntrinsic(N, Results, DAG);
10671 case ISD::LOAD:
10672 LowerLOAD(N, Results, DAG);
10673 break;
10674 case ISD::STORE:
10675 Res = LowerAEABIUnalignedStore(SDValue(N, 0), DAG);
10676 break;
10677 case ISD::TRUNCATE:
10678 Res = LowerTruncate(N, DAG, Subtarget);
10679 break;
10680 case ISD::SIGN_EXTEND:
10681 case ISD::ZERO_EXTEND:
10682 Res = LowerVectorExtend(N, DAG, Subtarget);
10683 break;
10686 Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10687 break;
10688 }
10689 if (Res.getNode())
10690 Results.push_back(Res);
10691}
10692
10693//===----------------------------------------------------------------------===//
10694// ARM Scheduler Hooks
10695//===----------------------------------------------------------------------===//
10696
10697/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10698/// registers the function context.
10699void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10701 MachineBasicBlock *DispatchBB,
10702 int FI) const {
10703 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10704 "ROPI/RWPI not currently supported with SjLj");
10705 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10706 DebugLoc dl = MI.getDebugLoc();
10707 MachineFunction *MF = MBB->getParent();
10708 MachineRegisterInfo *MRI = &MF->getRegInfo();
10711 const Function &F = MF->getFunction();
10712
10713 bool isThumb = Subtarget->isThumb();
10714 bool isThumb2 = Subtarget->isThumb2();
10715
10716 unsigned PCLabelId = AFI->createPICLabelUId();
10717 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10719 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10720 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10721
10722 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10723 : &ARM::GPRRegClass;
10724
10725 // Grab constant pool and fixed stack memory operands.
10726 MachineMemOperand *CPMMO =
10729
10730 MachineMemOperand *FIMMOSt =
10733
10734 // Load the address of the dispatch MBB into the jump buffer.
10735 if (isThumb2) {
10736 // Incoming value: jbuf
10737 // ldr.n r5, LCPI1_1
10738 // orr r5, r5, #1
10739 // add r5, pc
10740 // str r5, [$jbuf, #+4] ; &jbuf[1]
10741 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10742 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10744 .addMemOperand(CPMMO)
10746 // Set the low bit because of thumb mode.
10747 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10748 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10749 .addReg(NewVReg1, RegState::Kill)
10750 .addImm(0x01)
10752 .add(condCodeOp());
10753 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10754 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10755 .addReg(NewVReg2, RegState::Kill)
10756 .addImm(PCLabelId);
10757 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10758 .addReg(NewVReg3, RegState::Kill)
10759 .addFrameIndex(FI)
10760 .addImm(36) // &jbuf[1] :: pc
10761 .addMemOperand(FIMMOSt)
10763 } else if (isThumb) {
10764 // Incoming value: jbuf
10765 // ldr.n r1, LCPI1_4
10766 // add r1, pc
10767 // mov r2, #1
10768 // orrs r1, r2
10769 // add r2, $jbuf, #+4 ; &jbuf[1]
10770 // str r1, [r2]
10771 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10772 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10774 .addMemOperand(CPMMO)
10776 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10777 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10778 .addReg(NewVReg1, RegState::Kill)
10779 .addImm(PCLabelId);
10780 // Set the low bit because of thumb mode.
10781 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10782 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10783 .addReg(ARM::CPSR, RegState::Define)
10784 .addImm(1)
10786 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10787 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10788 .addReg(ARM::CPSR, RegState::Define)
10789 .addReg(NewVReg2, RegState::Kill)
10790 .addReg(NewVReg3, RegState::Kill)
10792 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10793 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10794 .addFrameIndex(FI)
10795 .addImm(36); // &jbuf[1] :: pc
10796 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10797 .addReg(NewVReg4, RegState::Kill)
10798 .addReg(NewVReg5, RegState::Kill)
10799 .addImm(0)
10800 .addMemOperand(FIMMOSt)
10802 } else {
10803 // Incoming value: jbuf
10804 // ldr r1, LCPI1_1
10805 // add r1, pc, r1
10806 // str r1, [$jbuf, #+4] ; &jbuf[1]
10807 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10808 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10810 .addImm(0)
10811 .addMemOperand(CPMMO)
10813 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10814 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10815 .addReg(NewVReg1, RegState::Kill)
10816 .addImm(PCLabelId)
10818 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10819 .addReg(NewVReg2, RegState::Kill)
10820 .addFrameIndex(FI)
10821 .addImm(36) // &jbuf[1] :: pc
10822 .addMemOperand(FIMMOSt)
10824 }
10825}
10826
10827void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10828 MachineBasicBlock *MBB) const {
10829 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10830 DebugLoc dl = MI.getDebugLoc();
10831 MachineFunction *MF = MBB->getParent();
10832 MachineRegisterInfo *MRI = &MF->getRegInfo();
10833 MachineFrameInfo &MFI = MF->getFrameInfo();
10834 int FI = MFI.getFunctionContextIndex();
10835
10836 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10837 : &ARM::GPRnopcRegClass;
10838
10839 // Get a mapping of the call site numbers to all of the landing pads they're
10840 // associated with.
10841 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10842 unsigned MaxCSNum = 0;
10843 for (MachineBasicBlock &BB : *MF) {
10844 if (!BB.isEHPad())
10845 continue;
10846
10847 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10848 // pad.
10849 for (MachineInstr &II : BB) {
10850 if (!II.isEHLabel())
10851 continue;
10852
10853 MCSymbol *Sym = II.getOperand(0).getMCSymbol();
10854 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10855
10856 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10857 for (unsigned Idx : CallSiteIdxs) {
10858 CallSiteNumToLPad[Idx].push_back(&BB);
10859 MaxCSNum = std::max(MaxCSNum, Idx);
10860 }
10861 break;
10862 }
10863 }
10864
10865 // Get an ordered list of the machine basic blocks for the jump table.
10866 std::vector<MachineBasicBlock*> LPadList;
10867 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10868 LPadList.reserve(CallSiteNumToLPad.size());
10869 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10870 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10871 for (MachineBasicBlock *MBB : MBBList) {
10872 LPadList.push_back(MBB);
10873 InvokeBBs.insert_range(MBB->predecessors());
10874 }
10875 }
10876
10877 assert(!LPadList.empty() &&
10878 "No landing pad destinations for the dispatch jump table!");
10879
10880 // Create the jump table and associated information.
10881 MachineJumpTableInfo *JTI =
10882 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10883 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10884
10885 // Create the MBBs for the dispatch code.
10886
10887 // Shove the dispatch's address into the return slot in the function context.
10888 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10889 DispatchBB->setIsEHPad();
10890
10891 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10892
10893 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
10894 DispatchBB->addSuccessor(TrapBB);
10895
10896 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10897 DispatchBB->addSuccessor(DispContBB);
10898
10899 // Insert and MBBs.
10900 MF->insert(MF->end(), DispatchBB);
10901 MF->insert(MF->end(), DispContBB);
10902 MF->insert(MF->end(), TrapBB);
10903
10904 // Insert code into the entry block that creates and registers the function
10905 // context.
10906 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10907
10908 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10911
10912 MachineInstrBuilder MIB;
10913 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10914
10915 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10916 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10917
10918 // Add a register mask with no preserved registers. This results in all
10919 // registers being marked as clobbered. This can't work if the dispatch block
10920 // is in a Thumb1 function and is linked with ARM code which uses the FP
10921 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10923
10924 bool IsPositionIndependent = isPositionIndependent();
10925 unsigned NumLPads = LPadList.size();
10926 if (Subtarget->isThumb2()) {
10927 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10928 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10929 .addFrameIndex(FI)
10930 .addImm(4)
10931 .addMemOperand(FIMMOLd)
10933
10934 if (NumLPads < 256) {
10935 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10936 .addReg(NewVReg1)
10937 .addImm(LPadList.size())
10939 } else {
10940 Register VReg1 = MRI->createVirtualRegister(TRC);
10941 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10942 .addImm(NumLPads & 0xFFFF)
10944
10945 unsigned VReg2 = VReg1;
10946 if ((NumLPads & 0xFFFF0000) != 0) {
10947 VReg2 = MRI->createVirtualRegister(TRC);
10948 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10949 .addReg(VReg1)
10950 .addImm(NumLPads >> 16)
10952 }
10953
10954 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10955 .addReg(NewVReg1)
10956 .addReg(VReg2)
10958 }
10959
10960 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10961 .addMBB(TrapBB)
10963 .addReg(ARM::CPSR);
10964
10965 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10966 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10967 .addJumpTableIndex(MJTI)
10969
10970 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10971 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10972 .addReg(NewVReg3, RegState::Kill)
10973 .addReg(NewVReg1)
10976 .add(condCodeOp());
10977
10978 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10979 .addReg(NewVReg4, RegState::Kill)
10980 .addReg(NewVReg1)
10981 .addJumpTableIndex(MJTI);
10982 } else if (Subtarget->isThumb()) {
10983 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10984 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10985 .addFrameIndex(FI)
10986 .addImm(1)
10987 .addMemOperand(FIMMOLd)
10989
10990 if (NumLPads < 256) {
10991 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10992 .addReg(NewVReg1)
10993 .addImm(NumLPads)
10995 } else {
10996 MachineConstantPool *ConstantPool = MF->getConstantPool();
10997 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10998 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10999
11000 // MachineConstantPool wants an explicit alignment.
11001 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11002 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11003
11004 Register VReg1 = MRI->createVirtualRegister(TRC);
11005 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
11006 .addReg(VReg1, RegState::Define)
11009 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
11010 .addReg(NewVReg1)
11011 .addReg(VReg1)
11013 }
11014
11015 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
11016 .addMBB(TrapBB)
11018 .addReg(ARM::CPSR);
11019
11020 Register NewVReg2 = MRI->createVirtualRegister(TRC);
11021 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
11022 .addReg(ARM::CPSR, RegState::Define)
11023 .addReg(NewVReg1)
11024 .addImm(2)
11026
11027 Register NewVReg3 = MRI->createVirtualRegister(TRC);
11028 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
11029 .addJumpTableIndex(MJTI)
11031
11032 Register NewVReg4 = MRI->createVirtualRegister(TRC);
11033 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
11034 .addReg(ARM::CPSR, RegState::Define)
11035 .addReg(NewVReg2, RegState::Kill)
11036 .addReg(NewVReg3)
11038
11039 MachineMemOperand *JTMMOLd =
11040 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11042
11043 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11044 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
11045 .addReg(NewVReg4, RegState::Kill)
11046 .addImm(0)
11047 .addMemOperand(JTMMOLd)
11049
11050 unsigned NewVReg6 = NewVReg5;
11051 if (IsPositionIndependent) {
11052 NewVReg6 = MRI->createVirtualRegister(TRC);
11053 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
11054 .addReg(ARM::CPSR, RegState::Define)
11055 .addReg(NewVReg5, RegState::Kill)
11056 .addReg(NewVReg3)
11058 }
11059
11060 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
11061 .addReg(NewVReg6, RegState::Kill)
11062 .addJumpTableIndex(MJTI);
11063 } else {
11064 Register NewVReg1 = MRI->createVirtualRegister(TRC);
11065 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
11066 .addFrameIndex(FI)
11067 .addImm(4)
11068 .addMemOperand(FIMMOLd)
11070
11071 if (NumLPads < 256) {
11072 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
11073 .addReg(NewVReg1)
11074 .addImm(NumLPads)
11076 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
11077 Register VReg1 = MRI->createVirtualRegister(TRC);
11078 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
11079 .addImm(NumLPads & 0xFFFF)
11081
11082 unsigned VReg2 = VReg1;
11083 if ((NumLPads & 0xFFFF0000) != 0) {
11084 VReg2 = MRI->createVirtualRegister(TRC);
11085 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
11086 .addReg(VReg1)
11087 .addImm(NumLPads >> 16)
11089 }
11090
11091 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11092 .addReg(NewVReg1)
11093 .addReg(VReg2)
11095 } else {
11096 MachineConstantPool *ConstantPool = MF->getConstantPool();
11097 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11098 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11099
11100 // MachineConstantPool wants an explicit alignment.
11101 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11102 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11103
11104 Register VReg1 = MRI->createVirtualRegister(TRC);
11105 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
11106 .addReg(VReg1, RegState::Define)
11108 .addImm(0)
11110 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11111 .addReg(NewVReg1)
11112 .addReg(VReg1, RegState::Kill)
11114 }
11115
11116 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
11117 .addMBB(TrapBB)
11119 .addReg(ARM::CPSR);
11120
11121 Register NewVReg3 = MRI->createVirtualRegister(TRC);
11122 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
11123 .addReg(NewVReg1)
11126 .add(condCodeOp());
11127 Register NewVReg4 = MRI->createVirtualRegister(TRC);
11128 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
11129 .addJumpTableIndex(MJTI)
11131
11132 MachineMemOperand *JTMMOLd =
11133 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11135 Register NewVReg5 = MRI->createVirtualRegister(TRC);
11136 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11137 .addReg(NewVReg3, RegState::Kill)
11138 .addReg(NewVReg4)
11139 .addImm(0)
11140 .addMemOperand(JTMMOLd)
11142
11143 if (IsPositionIndependent) {
11144 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11145 .addReg(NewVReg5, RegState::Kill)
11146 .addReg(NewVReg4)
11147 .addJumpTableIndex(MJTI);
11148 } else {
11149 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11150 .addReg(NewVReg5, RegState::Kill)
11151 .addJumpTableIndex(MJTI);
11152 }
11153 }
11154
11155 // Add the jump table entries as successors to the MBB.
11156 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11157 for (MachineBasicBlock *CurMBB : LPadList) {
11158 if (SeenMBBs.insert(CurMBB).second)
11159 DispContBB->addSuccessor(CurMBB);
11160 }
11161
11162 // N.B. the order the invoke BBs are processed in doesn't matter here.
11163 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11165 for (MachineBasicBlock *BB : InvokeBBs) {
11166
11167 // Remove the landing pad successor from the invoke block and replace it
11168 // with the new dispatch block.
11169 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11170 while (!Successors.empty()) {
11171 MachineBasicBlock *SMBB = Successors.pop_back_val();
11172 if (SMBB->isEHPad()) {
11173 BB->removeSuccessor(SMBB);
11174 MBBLPads.push_back(SMBB);
11175 }
11176 }
11177
11178 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11179 BB->normalizeSuccProbs();
11180
11181 // Find the invoke call and mark all of the callee-saved registers as
11182 // 'implicit defined' so that they're spilled. This prevents code from
11183 // moving instructions to before the EH block, where they will never be
11184 // executed.
11186 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11187 if (!II->isCall()) continue;
11188
11189 DenseSet<unsigned> DefRegs;
11191 OI = II->operands_begin(), OE = II->operands_end();
11192 OI != OE; ++OI) {
11193 if (!OI->isReg()) continue;
11194 DefRegs.insert(OI->getReg());
11195 }
11196
11197 MachineInstrBuilder MIB(*MF, &*II);
11198
11199 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11200 unsigned Reg = SavedRegs[i];
11201 if (Subtarget->isThumb2() &&
11202 !ARM::tGPRRegClass.contains(Reg) &&
11203 !ARM::hGPRRegClass.contains(Reg))
11204 continue;
11205 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11206 continue;
11207 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11208 continue;
11209 if (!DefRegs.contains(Reg))
11211 }
11212
11213 break;
11214 }
11215 }
11216
11217 // Mark all former landing pads as non-landing pads. The dispatch is the only
11218 // landing pad now.
11219 for (MachineBasicBlock *MBBLPad : MBBLPads)
11220 MBBLPad->setIsEHPad(false);
11221
11222 // The instruction is gone now.
11223 MI.eraseFromParent();
11224}
11225
11226static
11228 for (MachineBasicBlock *S : MBB->successors())
11229 if (S != Succ)
11230 return S;
11231 llvm_unreachable("Expecting a BB with two successors!");
11232}
11233
11234/// Return the load opcode for a given load size. If load size >= 8,
11235/// neon opcode will be returned.
11236static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11237 if (LdSize >= 8)
11238 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11239 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11240 if (IsThumb1)
11241 return LdSize == 4 ? ARM::tLDRi
11242 : LdSize == 2 ? ARM::tLDRHi
11243 : LdSize == 1 ? ARM::tLDRBi : 0;
11244 if (IsThumb2)
11245 return LdSize == 4 ? ARM::t2LDR_POST
11246 : LdSize == 2 ? ARM::t2LDRH_POST
11247 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11248 return LdSize == 4 ? ARM::LDR_POST_IMM
11249 : LdSize == 2 ? ARM::LDRH_POST
11250 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11251}
11252
11253/// Return the store opcode for a given store size. If store size >= 8,
11254/// neon opcode will be returned.
11255static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11256 if (StSize >= 8)
11257 return StSize == 16 ? ARM::VST1q32wb_fixed
11258 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11259 if (IsThumb1)
11260 return StSize == 4 ? ARM::tSTRi
11261 : StSize == 2 ? ARM::tSTRHi
11262 : StSize == 1 ? ARM::tSTRBi : 0;
11263 if (IsThumb2)
11264 return StSize == 4 ? ARM::t2STR_POST
11265 : StSize == 2 ? ARM::t2STRH_POST
11266 : StSize == 1 ? ARM::t2STRB_POST : 0;
11267 return StSize == 4 ? ARM::STR_POST_IMM
11268 : StSize == 2 ? ARM::STRH_POST
11269 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11270}
11271
11272/// Emit a post-increment load operation with given size. The instructions
11273/// will be added to BB at Pos.
11275 const TargetInstrInfo *TII, const DebugLoc &dl,
11276 unsigned LdSize, unsigned Data, unsigned AddrIn,
11277 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11278 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11279 assert(LdOpc != 0 && "Should have a load opcode");
11280 if (LdSize >= 8) {
11281 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11282 .addReg(AddrOut, RegState::Define)
11283 .addReg(AddrIn)
11284 .addImm(0)
11286 } else if (IsThumb1) {
11287 // load + update AddrIn
11288 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11289 .addReg(AddrIn)
11290 .addImm(0)
11292 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11293 .add(t1CondCodeOp())
11294 .addReg(AddrIn)
11295 .addImm(LdSize)
11297 } else if (IsThumb2) {
11298 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11299 .addReg(AddrOut, RegState::Define)
11300 .addReg(AddrIn)
11301 .addImm(LdSize)
11303 } else { // arm
11304 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11305 .addReg(AddrOut, RegState::Define)
11306 .addReg(AddrIn)
11307 .addReg(0)
11308 .addImm(LdSize)
11310 }
11311}
11312
11313/// Emit a post-increment store operation with given size. The instructions
11314/// will be added to BB at Pos.
11316 const TargetInstrInfo *TII, const DebugLoc &dl,
11317 unsigned StSize, unsigned Data, unsigned AddrIn,
11318 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11319 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11320 assert(StOpc != 0 && "Should have a store opcode");
11321 if (StSize >= 8) {
11322 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11323 .addReg(AddrIn)
11324 .addImm(0)
11325 .addReg(Data)
11327 } else if (IsThumb1) {
11328 // store + update AddrIn
11329 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11330 .addReg(Data)
11331 .addReg(AddrIn)
11332 .addImm(0)
11334 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11335 .add(t1CondCodeOp())
11336 .addReg(AddrIn)
11337 .addImm(StSize)
11339 } else if (IsThumb2) {
11340 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11341 .addReg(Data)
11342 .addReg(AddrIn)
11343 .addImm(StSize)
11345 } else { // arm
11346 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11347 .addReg(Data)
11348 .addReg(AddrIn)
11349 .addReg(0)
11350 .addImm(StSize)
11352 }
11353}
11354
11356ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11357 MachineBasicBlock *BB) const {
11358 // This pseudo instruction has 3 operands: dst, src, size
11359 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11360 // Otherwise, we will generate unrolled scalar copies.
11361 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11362 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11364
11365 Register dest = MI.getOperand(0).getReg();
11366 Register src = MI.getOperand(1).getReg();
11367 unsigned SizeVal = MI.getOperand(2).getImm();
11368 unsigned Alignment = MI.getOperand(3).getImm();
11369 DebugLoc dl = MI.getDebugLoc();
11370
11371 MachineFunction *MF = BB->getParent();
11372 MachineRegisterInfo &MRI = MF->getRegInfo();
11373 unsigned UnitSize = 0;
11374 const TargetRegisterClass *TRC = nullptr;
11375 const TargetRegisterClass *VecTRC = nullptr;
11376
11377 bool IsThumb1 = Subtarget->isThumb1Only();
11378 bool IsThumb2 = Subtarget->isThumb2();
11379 bool IsThumb = Subtarget->isThumb();
11380
11381 if (Alignment & 1) {
11382 UnitSize = 1;
11383 } else if (Alignment & 2) {
11384 UnitSize = 2;
11385 } else {
11386 // Check whether we can use NEON instructions.
11387 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11388 Subtarget->hasNEON()) {
11389 if ((Alignment % 16 == 0) && SizeVal >= 16)
11390 UnitSize = 16;
11391 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11392 UnitSize = 8;
11393 }
11394 // Can't use NEON instructions.
11395 if (UnitSize == 0)
11396 UnitSize = 4;
11397 }
11398
11399 // Select the correct opcode and register class for unit size load/store
11400 bool IsNeon = UnitSize >= 8;
11401 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11402 if (IsNeon)
11403 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11404 : UnitSize == 8 ? &ARM::DPRRegClass
11405 : nullptr;
11406
11407 unsigned BytesLeft = SizeVal % UnitSize;
11408 unsigned LoopSize = SizeVal - BytesLeft;
11409
11410 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11411 // Use LDR and STR to copy.
11412 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11413 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11414 unsigned srcIn = src;
11415 unsigned destIn = dest;
11416 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11417 Register srcOut = MRI.createVirtualRegister(TRC);
11418 Register destOut = MRI.createVirtualRegister(TRC);
11419 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11420 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11421 IsThumb1, IsThumb2);
11422 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11423 IsThumb1, IsThumb2);
11424 srcIn = srcOut;
11425 destIn = destOut;
11426 }
11427
11428 // Handle the leftover bytes with LDRB and STRB.
11429 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11430 // [destOut] = STRB_POST(scratch, destIn, 1)
11431 for (unsigned i = 0; i < BytesLeft; i++) {
11432 Register srcOut = MRI.createVirtualRegister(TRC);
11433 Register destOut = MRI.createVirtualRegister(TRC);
11434 Register scratch = MRI.createVirtualRegister(TRC);
11435 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11436 IsThumb1, IsThumb2);
11437 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11438 IsThumb1, IsThumb2);
11439 srcIn = srcOut;
11440 destIn = destOut;
11441 }
11442 MI.eraseFromParent(); // The instruction is gone now.
11443 return BB;
11444 }
11445
11446 // Expand the pseudo op to a loop.
11447 // thisMBB:
11448 // ...
11449 // movw varEnd, # --> with thumb2
11450 // movt varEnd, #
11451 // ldrcp varEnd, idx --> without thumb2
11452 // fallthrough --> loopMBB
11453 // loopMBB:
11454 // PHI varPhi, varEnd, varLoop
11455 // PHI srcPhi, src, srcLoop
11456 // PHI destPhi, dst, destLoop
11457 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11458 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11459 // subs varLoop, varPhi, #UnitSize
11460 // bne loopMBB
11461 // fallthrough --> exitMBB
11462 // exitMBB:
11463 // epilogue to handle left-over bytes
11464 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11465 // [destOut] = STRB_POST(scratch, destLoop, 1)
11466 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11467 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11468 MF->insert(It, loopMBB);
11469 MF->insert(It, exitMBB);
11470
11471 // Set the call frame size on entry to the new basic blocks.
11472 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11473 loopMBB->setCallFrameSize(CallFrameSize);
11474 exitMBB->setCallFrameSize(CallFrameSize);
11475
11476 // Transfer the remainder of BB and its successor edges to exitMBB.
11477 exitMBB->splice(exitMBB->begin(), BB,
11478 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11480
11481 // Load an immediate to varEnd.
11482 Register varEnd = MRI.createVirtualRegister(TRC);
11483 if (Subtarget->useMovt()) {
11484 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11485 varEnd)
11486 .addImm(LoopSize);
11487 } else if (Subtarget->genExecuteOnly()) {
11488 assert(IsThumb && "Non-thumb expected to have used movt");
11489 BuildMI(BB, dl, TII->get(ARM::tMOVi32imm), varEnd).addImm(LoopSize);
11490 } else {
11491 MachineConstantPool *ConstantPool = MF->getConstantPool();
11493 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11494
11495 // MachineConstantPool wants an explicit alignment.
11496 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11497 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11498 MachineMemOperand *CPMMO =
11501
11502 if (IsThumb)
11503 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11504 .addReg(varEnd, RegState::Define)
11507 .addMemOperand(CPMMO);
11508 else
11509 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11510 .addReg(varEnd, RegState::Define)
11512 .addImm(0)
11514 .addMemOperand(CPMMO);
11515 }
11516 BB->addSuccessor(loopMBB);
11517
11518 // Generate the loop body:
11519 // varPhi = PHI(varLoop, varEnd)
11520 // srcPhi = PHI(srcLoop, src)
11521 // destPhi = PHI(destLoop, dst)
11522 MachineBasicBlock *entryBB = BB;
11523 BB = loopMBB;
11524 Register varLoop = MRI.createVirtualRegister(TRC);
11525 Register varPhi = MRI.createVirtualRegister(TRC);
11526 Register srcLoop = MRI.createVirtualRegister(TRC);
11527 Register srcPhi = MRI.createVirtualRegister(TRC);
11528 Register destLoop = MRI.createVirtualRegister(TRC);
11529 Register destPhi = MRI.createVirtualRegister(TRC);
11530
11531 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11532 .addReg(varLoop).addMBB(loopMBB)
11533 .addReg(varEnd).addMBB(entryBB);
11534 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11535 .addReg(srcLoop).addMBB(loopMBB)
11536 .addReg(src).addMBB(entryBB);
11537 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11538 .addReg(destLoop).addMBB(loopMBB)
11539 .addReg(dest).addMBB(entryBB);
11540
11541 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11542 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11543 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11544 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11545 IsThumb1, IsThumb2);
11546 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11547 IsThumb1, IsThumb2);
11548
11549 // Decrement loop variable by UnitSize.
11550 if (IsThumb1) {
11551 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11552 .add(t1CondCodeOp())
11553 .addReg(varPhi)
11554 .addImm(UnitSize)
11556 } else {
11557 MachineInstrBuilder MIB =
11558 BuildMI(*BB, BB->end(), dl,
11559 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11560 MIB.addReg(varPhi)
11561 .addImm(UnitSize)
11563 .add(condCodeOp());
11564 MIB->getOperand(5).setReg(ARM::CPSR);
11565 MIB->getOperand(5).setIsDef(true);
11566 }
11567 BuildMI(*BB, BB->end(), dl,
11568 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11569 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11570
11571 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11572 BB->addSuccessor(loopMBB);
11573 BB->addSuccessor(exitMBB);
11574
11575 // Add epilogue to handle BytesLeft.
11576 BB = exitMBB;
11577 auto StartOfExit = exitMBB->begin();
11578
11579 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11580 // [destOut] = STRB_POST(scratch, destLoop, 1)
11581 unsigned srcIn = srcLoop;
11582 unsigned destIn = destLoop;
11583 for (unsigned i = 0; i < BytesLeft; i++) {
11584 Register srcOut = MRI.createVirtualRegister(TRC);
11585 Register destOut = MRI.createVirtualRegister(TRC);
11586 Register scratch = MRI.createVirtualRegister(TRC);
11587 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11588 IsThumb1, IsThumb2);
11589 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11590 IsThumb1, IsThumb2);
11591 srcIn = srcOut;
11592 destIn = destOut;
11593 }
11594
11595 MI.eraseFromParent(); // The instruction is gone now.
11596 return BB;
11597}
11598
11600ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11601 MachineBasicBlock *MBB) const {
11602 const TargetMachine &TM = getTargetMachine();
11603 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11604 DebugLoc DL = MI.getDebugLoc();
11605
11606 assert(TM.getTargetTriple().isOSWindows() &&
11607 "__chkstk is only supported on Windows");
11608 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11609
11610 // __chkstk takes the number of words to allocate on the stack in R4, and
11611 // returns the stack adjustment in number of bytes in R4. This will not
11612 // clober any other registers (other than the obvious lr).
11613 //
11614 // Although, technically, IP should be considered a register which may be
11615 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11616 // thumb-2 environment, so there is no interworking required. As a result, we
11617 // do not expect a veneer to be emitted by the linker, clobbering IP.
11618 //
11619 // Each module receives its own copy of __chkstk, so no import thunk is
11620 // required, again, ensuring that IP is not clobbered.
11621 //
11622 // Finally, although some linkers may theoretically provide a trampoline for
11623 // out of range calls (which is quite common due to a 32M range limitation of
11624 // branches for Thumb), we can generate the long-call version via
11625 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11626 // IP.
11627
11628 RTLIB::LibcallImpl ChkStkLibcall = getLibcallImpl(RTLIB::STACK_PROBE);
11629 if (ChkStkLibcall == RTLIB::Unsupported)
11630 reportFatalUsageError("no available implementation of __chkstk");
11631
11632 const char *ChkStk = getLibcallImplName(ChkStkLibcall).data();
11633 switch (TM.getCodeModel()) {
11634 case CodeModel::Tiny:
11635 llvm_unreachable("Tiny code model not available on ARM.");
11636 case CodeModel::Small:
11637 case CodeModel::Medium:
11638 case CodeModel::Kernel:
11639 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11641 .addExternalSymbol(ChkStk)
11644 .addReg(ARM::R12,
11646 .addReg(ARM::CPSR,
11648 break;
11649 case CodeModel::Large: {
11650 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11651 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11652
11653 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11654 .addExternalSymbol(ChkStk);
11660 .addReg(ARM::R12,
11662 .addReg(ARM::CPSR,
11664 break;
11665 }
11666 }
11667
11668 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11669 .addReg(ARM::SP, RegState::Kill)
11670 .addReg(ARM::R4, RegState::Kill)
11673 .add(condCodeOp());
11674
11675 MI.eraseFromParent();
11676 return MBB;
11677}
11678
11680ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11681 MachineBasicBlock *MBB) const {
11682 DebugLoc DL = MI.getDebugLoc();
11683 MachineFunction *MF = MBB->getParent();
11684 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11685
11686 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11687 MF->insert(++MBB->getIterator(), ContBB);
11688 ContBB->splice(ContBB->begin(), MBB,
11689 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11691 MBB->addSuccessor(ContBB);
11692
11693 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11694 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11695 MF->push_back(TrapBB);
11696 MBB->addSuccessor(TrapBB);
11697
11698 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11699 .addReg(MI.getOperand(0).getReg())
11700 .addImm(0)
11702 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11703 .addMBB(TrapBB)
11705 .addReg(ARM::CPSR);
11706
11707 MI.eraseFromParent();
11708 return ContBB;
11709}
11710
11711// The CPSR operand of SelectItr might be missing a kill marker
11712// because there were multiple uses of CPSR, and ISel didn't know
11713// which to mark. Figure out whether SelectItr should have had a
11714// kill marker, and set it if it should. Returns the correct kill
11715// marker value.
11718 const TargetRegisterInfo* TRI) {
11719 // Scan forward through BB for a use/def of CPSR.
11720 MachineBasicBlock::iterator miI(std::next(SelectItr));
11721 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11722 const MachineInstr& mi = *miI;
11723 if (mi.readsRegister(ARM::CPSR, /*TRI=*/nullptr))
11724 return false;
11725 if (mi.definesRegister(ARM::CPSR, /*TRI=*/nullptr))
11726 break; // Should have kill-flag - update below.
11727 }
11728
11729 // If we hit the end of the block, check whether CPSR is live into a
11730 // successor.
11731 if (miI == BB->end()) {
11732 for (MachineBasicBlock *Succ : BB->successors())
11733 if (Succ->isLiveIn(ARM::CPSR))
11734 return false;
11735 }
11736
11737 // We found a def, or hit the end of the basic block and CPSR wasn't live
11738 // out. SelectMI should have a kill flag on CPSR.
11739 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11740 return true;
11741}
11742
11743/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11744/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11746 MachineBasicBlock *TpLoopBody,
11747 MachineBasicBlock *TpExit, Register OpSizeReg,
11748 const TargetInstrInfo *TII, DebugLoc Dl,
11749 MachineRegisterInfo &MRI) {
11750 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11751 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11752 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11753 .addUse(OpSizeReg)
11754 .addImm(15)
11756 .addReg(0);
11757
11758 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11759 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11760 .addUse(AddDestReg, RegState::Kill)
11761 .addImm(4)
11763 .addReg(0);
11764
11765 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11766 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11767 .addUse(LsrDestReg, RegState::Kill);
11768
11769 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11770 .addUse(TotalIterationsReg)
11771 .addMBB(TpExit);
11772
11773 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11774 .addMBB(TpLoopBody)
11776
11777 return TotalIterationsReg;
11778}
11779
11780/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11781/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11782/// loops.
11783static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11784 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11785 const TargetInstrInfo *TII, DebugLoc Dl,
11786 MachineRegisterInfo &MRI, Register OpSrcReg,
11787 Register OpDestReg, Register ElementCountReg,
11788 Register TotalIterationsReg, bool IsMemcpy) {
11789 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11790 // array, loop iteration counter, predication counter.
11791
11792 Register SrcPhiReg, CurrSrcReg;
11793 if (IsMemcpy) {
11794 // Current position in the src array
11795 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11796 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11797 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11798 .addUse(OpSrcReg)
11799 .addMBB(TpEntry)
11800 .addUse(CurrSrcReg)
11801 .addMBB(TpLoopBody);
11802 }
11803
11804 // Current position in the dest array
11805 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11806 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11807 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11808 .addUse(OpDestReg)
11809 .addMBB(TpEntry)
11810 .addUse(CurrDestReg)
11811 .addMBB(TpLoopBody);
11812
11813 // Current loop counter
11814 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11815 Register RemainingLoopIterationsReg =
11816 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11817 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11818 .addUse(TotalIterationsReg)
11819 .addMBB(TpEntry)
11820 .addUse(RemainingLoopIterationsReg)
11821 .addMBB(TpLoopBody);
11822
11823 // Predication counter
11824 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11825 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11826 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11827 .addUse(ElementCountReg)
11828 .addMBB(TpEntry)
11829 .addUse(RemainingElementsReg)
11830 .addMBB(TpLoopBody);
11831
11832 // Pass predication counter to VCTP
11833 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11834 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11835 .addUse(PredCounterPhiReg)
11837 .addReg(0)
11838 .addReg(0);
11839
11840 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11841 .addUse(PredCounterPhiReg)
11842 .addImm(16)
11844 .addReg(0);
11845
11846 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11847 Register SrcValueReg;
11848 if (IsMemcpy) {
11849 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11850 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11851 .addDef(CurrSrcReg)
11852 .addDef(SrcValueReg)
11853 .addReg(SrcPhiReg)
11854 .addImm(16)
11856 .addUse(VccrReg)
11857 .addReg(0);
11858 } else
11859 SrcValueReg = OpSrcReg;
11860
11861 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11862 .addDef(CurrDestReg)
11863 .addUse(SrcValueReg)
11864 .addReg(DestPhiReg)
11865 .addImm(16)
11867 .addUse(VccrReg)
11868 .addReg(0);
11869
11870 // Add the pseudoInstrs for decrementing the loop counter and marking the
11871 // end:t2DoLoopDec and t2DoLoopEnd
11872 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11873 .addUse(LoopCounterPhiReg)
11874 .addImm(1);
11875
11876 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11877 .addUse(RemainingLoopIterationsReg)
11878 .addMBB(TpLoopBody);
11879
11880 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11881 .addMBB(TpExit)
11883}
11884
11886 // KCFI is supported in all ARM/Thumb modes
11887 return true;
11888}
11889
11893 const TargetInstrInfo *TII) const {
11894 assert(MBBI->isCall() && MBBI->getCFIType() &&
11895 "Invalid call instruction for a KCFI check");
11896
11897 MachineOperand *TargetOp = nullptr;
11898 switch (MBBI->getOpcode()) {
11899 // ARM mode opcodes
11900 case ARM::BLX:
11901 case ARM::BLX_pred:
11902 case ARM::BLX_noip:
11903 case ARM::BLX_pred_noip:
11904 case ARM::BX_CALL:
11905 TargetOp = &MBBI->getOperand(0);
11906 break;
11907 case ARM::TCRETURNri:
11908 case ARM::TCRETURNrinotr12:
11909 case ARM::TAILJMPr:
11910 case ARM::TAILJMPr4:
11911 TargetOp = &MBBI->getOperand(0);
11912 break;
11913 // Thumb mode opcodes (Thumb1 and Thumb2)
11914 // Note: Most Thumb call instructions have predicate operands before the
11915 // target register Format: tBLXr pred, predreg, target_register, ...
11916 case ARM::tBLXr: // Thumb1/Thumb2: BLX register (requires V5T)
11917 case ARM::tBLXr_noip: // Thumb1/Thumb2: BLX register, no IP clobber
11918 case ARM::tBX_CALL: // Thumb1 only: BX call (push LR, BX)
11919 TargetOp = &MBBI->getOperand(2);
11920 break;
11921 // Tail call instructions don't have predicates, target is operand 0
11922 case ARM::tTAILJMPr: // Thumb1/Thumb2: Tail call via register
11923 TargetOp = &MBBI->getOperand(0);
11924 break;
11925 default:
11926 llvm_unreachable("Unexpected CFI call opcode");
11927 }
11928
11929 assert(TargetOp && TargetOp->isReg() && "Invalid target operand");
11930 TargetOp->setIsRenamable(false);
11931
11932 // Select the appropriate KCFI_CHECK variant based on the instruction set
11933 unsigned KCFICheckOpcode;
11934 if (Subtarget->isThumb()) {
11935 if (Subtarget->isThumb2()) {
11936 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb2;
11937 } else {
11938 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb1;
11939 }
11940 } else {
11941 KCFICheckOpcode = ARM::KCFI_CHECK_ARM;
11942 }
11943
11944 return BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(KCFICheckOpcode))
11945 .addReg(TargetOp->getReg())
11946 .addImm(MBBI->getCFIType())
11947 .getInstr();
11948}
11949
11952 MachineBasicBlock *BB) const {
11953 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11954 DebugLoc dl = MI.getDebugLoc();
11955 bool isThumb2 = Subtarget->isThumb2();
11956 switch (MI.getOpcode()) {
11957 default: {
11958 MI.print(errs());
11959 llvm_unreachable("Unexpected instr type to insert");
11960 }
11961
11962 // Thumb1 post-indexed loads are really just single-register LDMs.
11963 case ARM::tLDR_postidx: {
11964 MachineOperand Def(MI.getOperand(1));
11965 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11966 .add(Def) // Rn_wb
11967 .add(MI.getOperand(2)) // Rn
11968 .add(MI.getOperand(3)) // PredImm
11969 .add(MI.getOperand(4)) // PredReg
11970 .add(MI.getOperand(0)) // Rt
11971 .cloneMemRefs(MI);
11972 MI.eraseFromParent();
11973 return BB;
11974 }
11975
11976 case ARM::MVE_MEMCPYLOOPINST:
11977 case ARM::MVE_MEMSETLOOPINST: {
11978
11979 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11980 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11981 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11982 // adds the relevant instructions in the TP loop Body for generation of a
11983 // WLSTP loop.
11984
11985 // Below is relevant portion of the CFG after the transformation.
11986 // The Machine Basic Blocks are shown along with branch conditions (in
11987 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11988 // portion of the CFG and may not necessarily be the entry/exit of the
11989 // function.
11990
11991 // (Relevant) CFG after transformation:
11992 // TP entry MBB
11993 // |
11994 // |-----------------|
11995 // (n <= 0) (n > 0)
11996 // | |
11997 // | TP loop Body MBB<--|
11998 // | | |
11999 // \ |___________|
12000 // \ /
12001 // TP exit MBB
12002
12003 MachineFunction *MF = BB->getParent();
12004 MachineFunctionProperties &Properties = MF->getProperties();
12005 MachineRegisterInfo &MRI = MF->getRegInfo();
12006
12007 Register OpDestReg = MI.getOperand(0).getReg();
12008 Register OpSrcReg = MI.getOperand(1).getReg();
12009 Register OpSizeReg = MI.getOperand(2).getReg();
12010
12011 // Allocate the required MBBs and add to parent function.
12012 MachineBasicBlock *TpEntry = BB;
12013 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
12014 MachineBasicBlock *TpExit;
12015
12016 MF->push_back(TpLoopBody);
12017
12018 // If any instructions are present in the current block after
12019 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
12020 // move the instructions into the newly created exit block. If there are no
12021 // instructions add an explicit branch to the FallThrough block and then
12022 // split.
12023 //
12024 // The split is required for two reasons:
12025 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
12026 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
12027 // need to be updated. splitAt() already handles this.
12028 TpExit = BB->splitAt(MI, false);
12029 if (TpExit == BB) {
12030 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12031 "block containing memcpy/memset Pseudo");
12032 TpExit = BB->getFallThrough();
12033 BuildMI(BB, dl, TII->get(ARM::t2B))
12034 .addMBB(TpExit)
12036 TpExit = BB->splitAt(MI, false);
12037 }
12038
12039 // Add logic for iteration count
12040 Register TotalIterationsReg =
12041 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
12042
12043 // Add the vectorized (and predicated) loads/store instructions
12044 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12045 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
12046 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
12047
12048 // Required to avoid conflict with the MachineVerifier during testing.
12049 Properties.resetNoPHIs();
12050
12051 // Connect the blocks
12052 TpEntry->addSuccessor(TpLoopBody);
12053 TpLoopBody->addSuccessor(TpLoopBody);
12054 TpLoopBody->addSuccessor(TpExit);
12055
12056 // Reorder for a more natural layout
12057 TpLoopBody->moveAfter(TpEntry);
12058 TpExit->moveAfter(TpLoopBody);
12059
12060 // Finally, remove the memcpy Pseudo Instruction
12061 MI.eraseFromParent();
12062
12063 // Return the exit block as it may contain other instructions requiring a
12064 // custom inserter
12065 return TpExit;
12066 }
12067
12068 // The Thumb2 pre-indexed stores have the same MI operands, they just
12069 // define them differently in the .td files from the isel patterns, so
12070 // they need pseudos.
12071 case ARM::t2STR_preidx:
12072 MI.setDesc(TII->get(ARM::t2STR_PRE));
12073 return BB;
12074 case ARM::t2STRB_preidx:
12075 MI.setDesc(TII->get(ARM::t2STRB_PRE));
12076 return BB;
12077 case ARM::t2STRH_preidx:
12078 MI.setDesc(TII->get(ARM::t2STRH_PRE));
12079 return BB;
12080
12081 case ARM::STRi_preidx:
12082 case ARM::STRBi_preidx: {
12083 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12084 : ARM::STRB_PRE_IMM;
12085 // Decode the offset.
12086 unsigned Offset = MI.getOperand(4).getImm();
12087 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
12089 if (isSub)
12090 Offset = -Offset;
12091
12092 MachineMemOperand *MMO = *MI.memoperands_begin();
12093 BuildMI(*BB, MI, dl, TII->get(NewOpc))
12094 .add(MI.getOperand(0)) // Rn_wb
12095 .add(MI.getOperand(1)) // Rt
12096 .add(MI.getOperand(2)) // Rn
12097 .addImm(Offset) // offset (skip GPR==zero_reg)
12098 .add(MI.getOperand(5)) // pred
12099 .add(MI.getOperand(6))
12100 .addMemOperand(MMO);
12101 MI.eraseFromParent();
12102 return BB;
12103 }
12104 case ARM::STRr_preidx:
12105 case ARM::STRBr_preidx:
12106 case ARM::STRH_preidx: {
12107 unsigned NewOpc;
12108 switch (MI.getOpcode()) {
12109 default: llvm_unreachable("unexpected opcode!");
12110 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12111 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12112 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12113 }
12114 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
12115 for (const MachineOperand &MO : MI.operands())
12116 MIB.add(MO);
12117 MI.eraseFromParent();
12118 return BB;
12119 }
12120
12121 case ARM::tMOVCCr_pseudo: {
12122 // To "insert" a SELECT_CC instruction, we actually have to insert the
12123 // diamond control-flow pattern. The incoming instruction knows the
12124 // destination vreg to set, the condition code register to branch on, the
12125 // true/false values to select between, and a branch opcode to use.
12126 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12128
12129 // thisMBB:
12130 // ...
12131 // TrueVal = ...
12132 // cmpTY ccX, r1, r2
12133 // bCC copy1MBB
12134 // fallthrough --> copy0MBB
12135 MachineBasicBlock *thisMBB = BB;
12136 MachineFunction *F = BB->getParent();
12137 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12138 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12139 F->insert(It, copy0MBB);
12140 F->insert(It, sinkMBB);
12141
12142 // Set the call frame size on entry to the new basic blocks.
12143 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12144 copy0MBB->setCallFrameSize(CallFrameSize);
12145 sinkMBB->setCallFrameSize(CallFrameSize);
12146
12147 // Check whether CPSR is live past the tMOVCCr_pseudo.
12148 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12149 if (!MI.killsRegister(ARM::CPSR, /*TRI=*/nullptr) &&
12150 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
12151 copy0MBB->addLiveIn(ARM::CPSR);
12152 sinkMBB->addLiveIn(ARM::CPSR);
12153 }
12154
12155 // Transfer the remainder of BB and its successor edges to sinkMBB.
12156 sinkMBB->splice(sinkMBB->begin(), BB,
12157 std::next(MachineBasicBlock::iterator(MI)), BB->end());
12159
12160 BB->addSuccessor(copy0MBB);
12161 BB->addSuccessor(sinkMBB);
12162
12163 BuildMI(BB, dl, TII->get(ARM::tBcc))
12164 .addMBB(sinkMBB)
12165 .addImm(MI.getOperand(3).getImm())
12166 .addReg(MI.getOperand(4).getReg());
12167
12168 // copy0MBB:
12169 // %FalseValue = ...
12170 // # fallthrough to sinkMBB
12171 BB = copy0MBB;
12172
12173 // Update machine-CFG edges
12174 BB->addSuccessor(sinkMBB);
12175
12176 // sinkMBB:
12177 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12178 // ...
12179 BB = sinkMBB;
12180 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
12181 .addReg(MI.getOperand(1).getReg())
12182 .addMBB(copy0MBB)
12183 .addReg(MI.getOperand(2).getReg())
12184 .addMBB(thisMBB);
12185
12186 MI.eraseFromParent(); // The pseudo instruction is gone now.
12187 return BB;
12188 }
12189
12190 case ARM::BCCi64:
12191 case ARM::BCCZi64: {
12192 // If there is an unconditional branch to the other successor, remove it.
12193 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
12194
12195 // Compare both parts that make up the double comparison separately for
12196 // equality.
12197 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12198
12199 Register LHS1 = MI.getOperand(1).getReg();
12200 Register LHS2 = MI.getOperand(2).getReg();
12201 if (RHSisZero) {
12202 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12203 .addReg(LHS1)
12204 .addImm(0)
12206 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12207 .addReg(LHS2).addImm(0)
12208 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12209 } else {
12210 Register RHS1 = MI.getOperand(3).getReg();
12211 Register RHS2 = MI.getOperand(4).getReg();
12212 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12213 .addReg(LHS1)
12214 .addReg(RHS1)
12216 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12217 .addReg(LHS2).addReg(RHS2)
12218 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12219 }
12220
12221 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12222 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12223 if (MI.getOperand(0).getImm() == ARMCC::NE)
12224 std::swap(destMBB, exitMBB);
12225
12226 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12227 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12228 if (isThumb2)
12229 BuildMI(BB, dl, TII->get(ARM::t2B))
12230 .addMBB(exitMBB)
12232 else
12233 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12234
12235 MI.eraseFromParent(); // The pseudo instruction is gone now.
12236 return BB;
12237 }
12238
12239 case ARM::Int_eh_sjlj_setjmp:
12240 case ARM::Int_eh_sjlj_setjmp_nofp:
12241 case ARM::tInt_eh_sjlj_setjmp:
12242 case ARM::t2Int_eh_sjlj_setjmp:
12243 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12244 return BB;
12245
12246 case ARM::Int_eh_sjlj_setup_dispatch:
12247 EmitSjLjDispatchBlock(MI, BB);
12248 return BB;
12249 case ARM::COPY_STRUCT_BYVAL_I32:
12250 ++NumLoopByVals;
12251 return EmitStructByval(MI, BB);
12252 case ARM::WIN__CHKSTK:
12253 return EmitLowered__chkstk(MI, BB);
12254 case ARM::WIN__DBZCHK:
12255 return EmitLowered__dbzchk(MI, BB);
12256 }
12257}
12258
12259/// Attaches vregs to MEMCPY that it will use as scratch registers
12260/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12261/// instead of as a custom inserter because we need the use list from the SDNode.
12262static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12263 MachineInstr &MI, const SDNode *Node) {
12264 bool isThumb1 = Subtarget->isThumb1Only();
12265
12266 MachineFunction *MF = MI.getParent()->getParent();
12267 MachineRegisterInfo &MRI = MF->getRegInfo();
12268 MachineInstrBuilder MIB(*MF, MI);
12269
12270 // If the new dst/src is unused mark it as dead.
12271 if (!Node->hasAnyUseOfValue(0)) {
12272 MI.getOperand(0).setIsDead(true);
12273 }
12274 if (!Node->hasAnyUseOfValue(1)) {
12275 MI.getOperand(1).setIsDead(true);
12276 }
12277
12278 // The MEMCPY both defines and kills the scratch registers.
12279 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12280 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12281 : &ARM::GPRRegClass);
12283 }
12284}
12285
12287 SDNode *Node) const {
12288 if (MI.getOpcode() == ARM::MEMCPY) {
12289 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12290 return;
12291 }
12292
12293 const MCInstrDesc *MCID = &MI.getDesc();
12294 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12295 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12296 // operand is still set to noreg. If needed, set the optional operand's
12297 // register to CPSR, and remove the redundant implicit def.
12298 //
12299 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12300
12301 // Rename pseudo opcodes.
12302 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12303 unsigned ccOutIdx;
12304 if (NewOpc) {
12305 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12306 MCID = &TII->get(NewOpc);
12307
12308 assert(MCID->getNumOperands() ==
12309 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12310 && "converted opcode should be the same except for cc_out"
12311 " (and, on Thumb1, pred)");
12312
12313 MI.setDesc(*MCID);
12314
12315 // Add the optional cc_out operand
12316 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12317
12318 // On Thumb1, move all input operands to the end, then add the predicate
12319 if (Subtarget->isThumb1Only()) {
12320 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12321 MI.addOperand(MI.getOperand(1));
12322 MI.removeOperand(1);
12323 }
12324
12325 // Restore the ties
12326 for (unsigned i = MI.getNumOperands(); i--;) {
12327 const MachineOperand& op = MI.getOperand(i);
12328 if (op.isReg() && op.isUse()) {
12329 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12330 if (DefIdx != -1)
12331 MI.tieOperands(DefIdx, i);
12332 }
12333 }
12334
12336 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12337 ccOutIdx = 1;
12338 } else
12339 ccOutIdx = MCID->getNumOperands() - 1;
12340 } else
12341 ccOutIdx = MCID->getNumOperands() - 1;
12342
12343 // Any ARM instruction that sets the 's' bit should specify an optional
12344 // "cc_out" operand in the last operand position.
12345 if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12346 assert(!NewOpc && "Optional cc_out operand required");
12347 return;
12348 }
12349 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12350 // since we already have an optional CPSR def.
12351 bool definesCPSR = false;
12352 bool deadCPSR = false;
12353 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12354 ++i) {
12355 const MachineOperand &MO = MI.getOperand(i);
12356 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12357 definesCPSR = true;
12358 if (MO.isDead())
12359 deadCPSR = true;
12360 MI.removeOperand(i);
12361 break;
12362 }
12363 }
12364 if (!definesCPSR) {
12365 assert(!NewOpc && "Optional cc_out operand required");
12366 return;
12367 }
12368 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12369 if (deadCPSR) {
12370 assert(!MI.getOperand(ccOutIdx).getReg() &&
12371 "expect uninitialized optional cc_out operand");
12372 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12373 if (!Subtarget->isThumb1Only())
12374 return;
12375 }
12376
12377 // If this instruction was defined with an optional CPSR def and its dag node
12378 // had a live implicit CPSR def, then activate the optional CPSR def.
12379 MachineOperand &MO = MI.getOperand(ccOutIdx);
12380 MO.setReg(ARM::CPSR);
12381 MO.setIsDef(true);
12382}
12383
12384//===----------------------------------------------------------------------===//
12385// ARM Optimization Hooks
12386//===----------------------------------------------------------------------===//
12387
12388// Helper function that checks if N is a null or all ones constant.
12389static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12391}
12392
12393// Return true if N is conditionally 0 or all ones.
12394// Detects these expressions where cc is an i1 value:
12395//
12396// (select cc 0, y) [AllOnes=0]
12397// (select cc y, 0) [AllOnes=0]
12398// (zext cc) [AllOnes=0]
12399// (sext cc) [AllOnes=0/1]
12400// (select cc -1, y) [AllOnes=1]
12401// (select cc y, -1) [AllOnes=1]
12402//
12403// Invert is set when N is the null/all ones constant when CC is false.
12404// OtherOp is set to the alternative value of N.
12406 SDValue &CC, bool &Invert,
12407 SDValue &OtherOp,
12408 SelectionDAG &DAG) {
12409 switch (N->getOpcode()) {
12410 default: return false;
12411 case ISD::SELECT: {
12412 CC = N->getOperand(0);
12413 SDValue N1 = N->getOperand(1);
12414 SDValue N2 = N->getOperand(2);
12415 if (isZeroOrAllOnes(N1, AllOnes)) {
12416 Invert = false;
12417 OtherOp = N2;
12418 return true;
12419 }
12420 if (isZeroOrAllOnes(N2, AllOnes)) {
12421 Invert = true;
12422 OtherOp = N1;
12423 return true;
12424 }
12425 return false;
12426 }
12427 case ISD::ZERO_EXTEND:
12428 // (zext cc) can never be the all ones value.
12429 if (AllOnes)
12430 return false;
12431 [[fallthrough]];
12432 case ISD::SIGN_EXTEND: {
12433 SDLoc dl(N);
12434 EVT VT = N->getValueType(0);
12435 CC = N->getOperand(0);
12436 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12437 return false;
12438 Invert = !AllOnes;
12439 if (AllOnes)
12440 // When looking for an AllOnes constant, N is an sext, and the 'other'
12441 // value is 0.
12442 OtherOp = DAG.getConstant(0, dl, VT);
12443 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12444 // When looking for a 0 constant, N can be zext or sext.
12445 OtherOp = DAG.getConstant(1, dl, VT);
12446 else
12447 OtherOp = DAG.getAllOnesConstant(dl, VT);
12448 return true;
12449 }
12450 }
12451}
12452
12453// Combine a constant select operand into its use:
12454//
12455// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12456// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12457// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12458// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12459// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12460//
12461// The transform is rejected if the select doesn't have a constant operand that
12462// is null, or all ones when AllOnes is set.
12463//
12464// Also recognize sext/zext from i1:
12465//
12466// (add (zext cc), x) -> (select cc (add x, 1), x)
12467// (add (sext cc), x) -> (select cc (add x, -1), x)
12468//
12469// These transformations eventually create predicated instructions.
12470//
12471// @param N The node to transform.
12472// @param Slct The N operand that is a select.
12473// @param OtherOp The other N operand (x above).
12474// @param DCI Context.
12475// @param AllOnes Require the select constant to be all ones instead of null.
12476// @returns The new node, or SDValue() on failure.
12477static
12480 bool AllOnes = false) {
12481 SelectionDAG &DAG = DCI.DAG;
12482 EVT VT = N->getValueType(0);
12483 SDValue NonConstantVal;
12484 SDValue CCOp;
12485 bool SwapSelectOps;
12486 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12487 NonConstantVal, DAG))
12488 return SDValue();
12489
12490 // Slct is now know to be the desired identity constant when CC is true.
12491 SDValue TrueVal = OtherOp;
12492 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12493 OtherOp, NonConstantVal);
12494 // Unless SwapSelectOps says CC should be false.
12495 if (SwapSelectOps)
12496 std::swap(TrueVal, FalseVal);
12497
12498 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12499 CCOp, TrueVal, FalseVal);
12500}
12501
12502// Attempt combineSelectAndUse on each operand of a commutative operator N.
12503static
12506 SDValue N0 = N->getOperand(0);
12507 SDValue N1 = N->getOperand(1);
12508 if (N0.getNode()->hasOneUse())
12509 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12510 return Result;
12511 if (N1.getNode()->hasOneUse())
12512 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12513 return Result;
12514 return SDValue();
12515}
12516
12518 // VUZP shuffle node.
12519 if (N->getOpcode() == ARMISD::VUZP)
12520 return true;
12521
12522 // "VUZP" on i32 is an alias for VTRN.
12523 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12524 return true;
12525
12526 return false;
12527}
12528
12531 const ARMSubtarget *Subtarget) {
12532 // Look for ADD(VUZP.0, VUZP.1).
12533 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12534 N0 == N1)
12535 return SDValue();
12536
12537 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12538 if (!N->getValueType(0).is64BitVector())
12539 return SDValue();
12540
12541 // Generate vpadd.
12542 SelectionDAG &DAG = DCI.DAG;
12543 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12544 SDLoc dl(N);
12545 SDNode *Unzip = N0.getNode();
12546 EVT VT = N->getValueType(0);
12547
12549 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12550 TLI.getPointerTy(DAG.getDataLayout())));
12551 Ops.push_back(Unzip->getOperand(0));
12552 Ops.push_back(Unzip->getOperand(1));
12553
12554 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12555}
12556
12559 const ARMSubtarget *Subtarget) {
12560 // Check for two extended operands.
12561 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12562 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12563 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12564 N1.getOpcode() == ISD::ZERO_EXTEND))
12565 return SDValue();
12566
12567 SDValue N00 = N0.getOperand(0);
12568 SDValue N10 = N1.getOperand(0);
12569
12570 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12571 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12572 N00 == N10)
12573 return SDValue();
12574
12575 // We only recognize Q register paddl here; this can't be reached until
12576 // after type legalization.
12577 if (!N00.getValueType().is64BitVector() ||
12579 return SDValue();
12580
12581 // Generate vpaddl.
12582 SelectionDAG &DAG = DCI.DAG;
12583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12584 SDLoc dl(N);
12585 EVT VT = N->getValueType(0);
12586
12588 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12589 unsigned Opcode;
12590 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12591 Opcode = Intrinsic::arm_neon_vpaddls;
12592 else
12593 Opcode = Intrinsic::arm_neon_vpaddlu;
12594 Ops.push_back(DAG.getConstant(Opcode, dl,
12595 TLI.getPointerTy(DAG.getDataLayout())));
12596 EVT ElemTy = N00.getValueType().getVectorElementType();
12597 unsigned NumElts = VT.getVectorNumElements();
12598 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12599 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12600 N00.getOperand(0), N00.getOperand(1));
12601 Ops.push_back(Concat);
12602
12603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12604}
12605
12606// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12607// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12608// much easier to match.
12609static SDValue
12612 const ARMSubtarget *Subtarget) {
12613 // Only perform optimization if after legalize, and if NEON is available. We
12614 // also expected both operands to be BUILD_VECTORs.
12615 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12616 || N0.getOpcode() != ISD::BUILD_VECTOR
12617 || N1.getOpcode() != ISD::BUILD_VECTOR)
12618 return SDValue();
12619
12620 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12621 EVT VT = N->getValueType(0);
12622 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12623 return SDValue();
12624
12625 // Check that the vector operands are of the right form.
12626 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12627 // operands, where N is the size of the formed vector.
12628 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12629 // index such that we have a pair wise add pattern.
12630
12631 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12633 return SDValue();
12634 SDValue Vec = N0->getOperand(0)->getOperand(0);
12635 SDNode *V = Vec.getNode();
12636 unsigned nextIndex = 0;
12637
12638 // For each operands to the ADD which are BUILD_VECTORs,
12639 // check to see if each of their operands are an EXTRACT_VECTOR with
12640 // the same vector and appropriate index.
12641 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12644
12645 SDValue ExtVec0 = N0->getOperand(i);
12646 SDValue ExtVec1 = N1->getOperand(i);
12647
12648 // First operand is the vector, verify its the same.
12649 if (V != ExtVec0->getOperand(0).getNode() ||
12650 V != ExtVec1->getOperand(0).getNode())
12651 return SDValue();
12652
12653 // Second is the constant, verify its correct.
12656
12657 // For the constant, we want to see all the even or all the odd.
12658 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12659 || C1->getZExtValue() != nextIndex+1)
12660 return SDValue();
12661
12662 // Increment index.
12663 nextIndex+=2;
12664 } else
12665 return SDValue();
12666 }
12667
12668 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12669 // we're using the entire input vector, otherwise there's a size/legality
12670 // mismatch somewhere.
12671 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12673 return SDValue();
12674
12675 // Create VPADDL node.
12676 SelectionDAG &DAG = DCI.DAG;
12677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12678
12679 SDLoc dl(N);
12680
12681 // Build operand list.
12683 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12684 TLI.getPointerTy(DAG.getDataLayout())));
12685
12686 // Input is the vector.
12687 Ops.push_back(Vec);
12688
12689 // Get widened type and narrowed type.
12690 MVT widenType;
12691 unsigned numElem = VT.getVectorNumElements();
12692
12693 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12694 switch (inputLaneType.getSimpleVT().SimpleTy) {
12695 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12696 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12697 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12698 default:
12699 llvm_unreachable("Invalid vector element type for padd optimization.");
12700 }
12701
12702 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12703 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12704 return DAG.getNode(ExtOp, dl, VT, tmp);
12705}
12706
12708 if (V->getOpcode() == ISD::UMUL_LOHI ||
12709 V->getOpcode() == ISD::SMUL_LOHI)
12710 return V;
12711 return SDValue();
12712}
12713
12714static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12716 const ARMSubtarget *Subtarget) {
12717 if (!Subtarget->hasBaseDSP())
12718 return SDValue();
12719
12720 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12721 // accumulates the product into a 64-bit value. The 16-bit values will
12722 // be sign extended somehow or SRA'd into 32-bit values
12723 // (addc (adde (mul 16bit, 16bit), lo), hi)
12724 SDValue Mul = AddcNode->getOperand(0);
12725 SDValue Lo = AddcNode->getOperand(1);
12726 if (Mul.getOpcode() != ISD::MUL) {
12727 Lo = AddcNode->getOperand(0);
12728 Mul = AddcNode->getOperand(1);
12729 if (Mul.getOpcode() != ISD::MUL)
12730 return SDValue();
12731 }
12732
12733 SDValue SRA = AddeNode->getOperand(0);
12734 SDValue Hi = AddeNode->getOperand(1);
12735 if (SRA.getOpcode() != ISD::SRA) {
12736 SRA = AddeNode->getOperand(1);
12737 Hi = AddeNode->getOperand(0);
12738 if (SRA.getOpcode() != ISD::SRA)
12739 return SDValue();
12740 }
12741 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12742 if (Const->getZExtValue() != 31)
12743 return SDValue();
12744 } else
12745 return SDValue();
12746
12747 if (SRA.getOperand(0) != Mul)
12748 return SDValue();
12749
12750 SelectionDAG &DAG = DCI.DAG;
12751 SDLoc dl(AddcNode);
12752 unsigned Opcode = 0;
12753 SDValue Op0;
12754 SDValue Op1;
12755
12756 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12757 Opcode = ARMISD::SMLALBB;
12758 Op0 = Mul.getOperand(0);
12759 Op1 = Mul.getOperand(1);
12760 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12761 Opcode = ARMISD::SMLALBT;
12762 Op0 = Mul.getOperand(0);
12763 Op1 = Mul.getOperand(1).getOperand(0);
12764 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12765 Opcode = ARMISD::SMLALTB;
12766 Op0 = Mul.getOperand(0).getOperand(0);
12767 Op1 = Mul.getOperand(1);
12768 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12769 Opcode = ARMISD::SMLALTT;
12770 Op0 = Mul->getOperand(0).getOperand(0);
12771 Op1 = Mul->getOperand(1).getOperand(0);
12772 }
12773
12774 if (!Op0 || !Op1)
12775 return SDValue();
12776
12777 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12778 Op0, Op1, Lo, Hi);
12779 // Replace the ADDs' nodes uses by the MLA node's values.
12780 SDValue HiMLALResult(SMLAL.getNode(), 1);
12781 SDValue LoMLALResult(SMLAL.getNode(), 0);
12782
12783 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12784 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12785
12786 // Return original node to notify the driver to stop replacing.
12787 SDValue resNode(AddcNode, 0);
12788 return resNode;
12789}
12790
12793 const ARMSubtarget *Subtarget) {
12794 // Look for multiply add opportunities.
12795 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12796 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12797 // a glue link from the first add to the second add.
12798 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12799 // a S/UMLAL instruction.
12800 // UMUL_LOHI
12801 // / :lo \ :hi
12802 // V \ [no multiline comment]
12803 // loAdd -> ADDC |
12804 // \ :carry /
12805 // V V
12806 // ADDE <- hiAdd
12807 //
12808 // In the special case where only the higher part of a signed result is used
12809 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12810 // a constant with the exact value of 0x80000000, we recognize we are dealing
12811 // with a "rounded multiply and add" (or subtract) and transform it into
12812 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12813
12814 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12815 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12816 "Expect an ADDE or SUBE");
12817
12818 assert(AddeSubeNode->getNumOperands() == 3 &&
12819 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12820 "ADDE node has the wrong inputs");
12821
12822 // Check that we are chained to the right ADDC or SUBC node.
12823 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12824 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12825 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12826 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12827 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12828 return SDValue();
12829
12830 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12831 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12832
12833 // Check if the two operands are from the same mul_lohi node.
12834 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12835 return SDValue();
12836
12837 assert(AddcSubcNode->getNumValues() == 2 &&
12838 AddcSubcNode->getValueType(0) == MVT::i32 &&
12839 "Expect ADDC with two result values. First: i32");
12840
12841 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12842 // maybe a SMLAL which multiplies two 16-bit values.
12843 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12844 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12845 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12846 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12847 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12848 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12849
12850 // Check for the triangle shape.
12851 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12852 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12853
12854 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12855 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12856 return SDValue();
12857
12858 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12859 bool IsLeftOperandMUL = false;
12860 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12861 if (MULOp == SDValue())
12862 MULOp = findMUL_LOHI(AddeSubeOp1);
12863 else
12864 IsLeftOperandMUL = true;
12865 if (MULOp == SDValue())
12866 return SDValue();
12867
12868 // Figure out the right opcode.
12869 unsigned Opc = MULOp->getOpcode();
12870 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12871
12872 // Figure out the high and low input values to the MLAL node.
12873 SDValue *HiAddSub = nullptr;
12874 SDValue *LoMul = nullptr;
12875 SDValue *LowAddSub = nullptr;
12876
12877 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12878 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12879 return SDValue();
12880
12881 if (IsLeftOperandMUL)
12882 HiAddSub = &AddeSubeOp1;
12883 else
12884 HiAddSub = &AddeSubeOp0;
12885
12886 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12887 // whose low result is fed to the ADDC/SUBC we are checking.
12888
12889 if (AddcSubcOp0 == MULOp.getValue(0)) {
12890 LoMul = &AddcSubcOp0;
12891 LowAddSub = &AddcSubcOp1;
12892 }
12893 if (AddcSubcOp1 == MULOp.getValue(0)) {
12894 LoMul = &AddcSubcOp1;
12895 LowAddSub = &AddcSubcOp0;
12896 }
12897
12898 if (!LoMul)
12899 return SDValue();
12900
12901 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12902 // the replacement below will create a cycle.
12903 if (AddcSubcNode == HiAddSub->getNode() ||
12904 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12905 return SDValue();
12906
12907 // Create the merged node.
12908 SelectionDAG &DAG = DCI.DAG;
12909
12910 // Start building operand list.
12912 Ops.push_back(LoMul->getOperand(0));
12913 Ops.push_back(LoMul->getOperand(1));
12914
12915 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12916 // the case, we must be doing signed multiplication and only use the higher
12917 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12918 // addition or subtraction with the value of 0x800000.
12919 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12920 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
12921 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12922 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12923 0x80000000) {
12924 Ops.push_back(*HiAddSub);
12925 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12926 FinalOpc = ARMISD::SMMLSR;
12927 } else {
12928 FinalOpc = ARMISD::SMMLAR;
12929 }
12930 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12931 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12932
12933 return SDValue(AddeSubeNode, 0);
12934 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12935 // SMMLS is generated during instruction selection and the rest of this
12936 // function can not handle the case where AddcSubcNode is a SUBC.
12937 return SDValue();
12938
12939 // Finish building the operand list for {U/S}MLAL
12940 Ops.push_back(*LowAddSub);
12941 Ops.push_back(*HiAddSub);
12942
12943 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12944 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12945
12946 // Replace the ADDs' nodes uses by the MLA node's values.
12947 SDValue HiMLALResult(MLALNode.getNode(), 1);
12948 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12949
12950 SDValue LoMLALResult(MLALNode.getNode(), 0);
12951 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12952
12953 // Return original node to notify the driver to stop replacing.
12954 return SDValue(AddeSubeNode, 0);
12955}
12956
12959 const ARMSubtarget *Subtarget) {
12960 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12961 // While trying to combine for the other MLAL nodes, first search for the
12962 // chance to use UMAAL. Check if Addc uses a node which has already
12963 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12964 // as the addend, and it's handled in PerformUMLALCombine.
12965
12966 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12967 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12968
12969 // Check that we have a glued ADDC node.
12970 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12971 if (AddcNode->getOpcode() != ARMISD::ADDC)
12972 return SDValue();
12973
12974 // Find the converted UMAAL or quit if it doesn't exist.
12975 SDNode *UmlalNode = nullptr;
12976 SDValue AddHi;
12977 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12978 UmlalNode = AddcNode->getOperand(0).getNode();
12979 AddHi = AddcNode->getOperand(1);
12980 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12981 UmlalNode = AddcNode->getOperand(1).getNode();
12982 AddHi = AddcNode->getOperand(0);
12983 } else {
12984 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12985 }
12986
12987 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12988 // the ADDC as well as Zero.
12989 if (!isNullConstant(UmlalNode->getOperand(3)))
12990 return SDValue();
12991
12992 if ((isNullConstant(AddeNode->getOperand(0)) &&
12993 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12994 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12995 isNullConstant(AddeNode->getOperand(1)))) {
12996 SelectionDAG &DAG = DCI.DAG;
12997 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12998 UmlalNode->getOperand(2), AddHi };
12999 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
13000 DAG.getVTList(MVT::i32, MVT::i32), Ops);
13001
13002 // Replace the ADDs' nodes uses by the UMAAL node's values.
13003 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
13004 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
13005
13006 // Return original node to notify the driver to stop replacing.
13007 return SDValue(AddeNode, 0);
13008 }
13009 return SDValue();
13010}
13011
13013 const ARMSubtarget *Subtarget) {
13014 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
13015 return SDValue();
13016
13017 // Check that we have a pair of ADDC and ADDE as operands.
13018 // Both addends of the ADDE must be zero.
13019 SDNode* AddcNode = N->getOperand(2).getNode();
13020 SDNode* AddeNode = N->getOperand(3).getNode();
13021 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13022 (AddeNode->getOpcode() == ARMISD::ADDE) &&
13023 isNullConstant(AddeNode->getOperand(0)) &&
13024 isNullConstant(AddeNode->getOperand(1)) &&
13025 (AddeNode->getOperand(2).getNode() == AddcNode))
13026 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
13027 DAG.getVTList(MVT::i32, MVT::i32),
13028 {N->getOperand(0), N->getOperand(1),
13029 AddcNode->getOperand(0), AddcNode->getOperand(1)});
13030 else
13031 return SDValue();
13032}
13033
13036 const ARMSubtarget *Subtarget) {
13037 SelectionDAG &DAG(DCI.DAG);
13038
13039 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
13040 // (SUBC (ADDE 0, 0, C), 1) -> C
13041 SDValue LHS = N->getOperand(0);
13042 SDValue RHS = N->getOperand(1);
13043 if (LHS->getOpcode() == ARMISD::ADDE &&
13044 isNullConstant(LHS->getOperand(0)) &&
13045 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
13046 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
13047 }
13048 }
13049
13050 if (Subtarget->isThumb1Only()) {
13051 SDValue RHS = N->getOperand(1);
13053 int32_t imm = C->getSExtValue();
13054 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13055 SDLoc DL(N);
13056 RHS = DAG.getConstant(-imm, DL, MVT::i32);
13057 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13058 : ARMISD::ADDC;
13059 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
13060 }
13061 }
13062 }
13063
13064 return SDValue();
13065}
13066
13069 const ARMSubtarget *Subtarget) {
13070 if (Subtarget->isThumb1Only()) {
13071 SelectionDAG &DAG = DCI.DAG;
13072 SDValue RHS = N->getOperand(1);
13074 int64_t imm = C->getSExtValue();
13075 if (imm < 0) {
13076 SDLoc DL(N);
13077
13078 // The with-carry-in form matches bitwise not instead of the negation.
13079 // Effectively, the inverse interpretation of the carry flag already
13080 // accounts for part of the negation.
13081 RHS = DAG.getConstant(~imm, DL, MVT::i32);
13082
13083 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13084 : ARMISD::ADDE;
13085 return DAG.getNode(Opcode, DL, N->getVTList(),
13086 N->getOperand(0), RHS, N->getOperand(2));
13087 }
13088 }
13089 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
13090 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
13091 }
13092 return SDValue();
13093}
13094
13097 const ARMSubtarget *Subtarget) {
13098 if (!Subtarget->hasMVEIntegerOps())
13099 return SDValue();
13100
13101 SDLoc dl(N);
13102 SDValue SetCC;
13103 SDValue LHS;
13104 SDValue RHS;
13105 ISD::CondCode CC;
13106 SDValue TrueVal;
13107 SDValue FalseVal;
13108
13109 if (N->getOpcode() == ISD::SELECT &&
13110 N->getOperand(0)->getOpcode() == ISD::SETCC) {
13111 SetCC = N->getOperand(0);
13112 LHS = SetCC->getOperand(0);
13113 RHS = SetCC->getOperand(1);
13114 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
13115 TrueVal = N->getOperand(1);
13116 FalseVal = N->getOperand(2);
13117 } else if (N->getOpcode() == ISD::SELECT_CC) {
13118 LHS = N->getOperand(0);
13119 RHS = N->getOperand(1);
13120 CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
13121 TrueVal = N->getOperand(2);
13122 FalseVal = N->getOperand(3);
13123 } else {
13124 return SDValue();
13125 }
13126
13127 unsigned int Opcode = 0;
13128 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13129 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13130 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13131 Opcode = ARMISD::VMINVu;
13132 if (CC == ISD::SETUGT)
13133 std::swap(TrueVal, FalseVal);
13134 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13135 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13136 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13137 Opcode = ARMISD::VMINVs;
13138 if (CC == ISD::SETGT)
13139 std::swap(TrueVal, FalseVal);
13140 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13141 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13142 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13143 Opcode = ARMISD::VMAXVu;
13144 if (CC == ISD::SETULT)
13145 std::swap(TrueVal, FalseVal);
13146 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13147 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13148 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13149 Opcode = ARMISD::VMAXVs;
13150 if (CC == ISD::SETLT)
13151 std::swap(TrueVal, FalseVal);
13152 } else
13153 return SDValue();
13154
13155 // Normalise to the right hand side being the vector reduction
13156 switch (TrueVal->getOpcode()) {
13161 std::swap(LHS, RHS);
13162 std::swap(TrueVal, FalseVal);
13163 break;
13164 }
13165
13166 EVT VectorType = FalseVal->getOperand(0).getValueType();
13167
13168 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13169 VectorType != MVT::v4i32)
13170 return SDValue();
13171
13172 EVT VectorScalarType = VectorType.getVectorElementType();
13173
13174 // The values being selected must also be the ones being compared
13175 if (TrueVal != LHS || FalseVal != RHS)
13176 return SDValue();
13177
13178 EVT LeftType = LHS->getValueType(0);
13179 EVT RightType = RHS->getValueType(0);
13180
13181 // The types must match the reduced type too
13182 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13183 return SDValue();
13184
13185 // Legalise the scalar to an i32
13186 if (VectorScalarType != MVT::i32)
13187 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13188
13189 // Generate the reduction as an i32 for legalisation purposes
13190 auto Reduction =
13191 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13192
13193 // The result isn't actually an i32 so truncate it back to its original type
13194 if (VectorScalarType != MVT::i32)
13195 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13196
13197 return Reduction;
13198}
13199
13200// A special combine for the vqdmulh family of instructions. This is one of the
13201// potential set of patterns that could patch this instruction. The base pattern
13202// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13203// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13204// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13205// the max is unnecessary.
13207 EVT VT = N->getValueType(0);
13208 SDValue Shft;
13209 ConstantSDNode *Clamp;
13210
13211 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13212 return SDValue();
13213
13214 if (N->getOpcode() == ISD::SMIN) {
13215 Shft = N->getOperand(0);
13216 Clamp = isConstOrConstSplat(N->getOperand(1));
13217 } else if (N->getOpcode() == ISD::VSELECT) {
13218 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13219 SDValue Cmp = N->getOperand(0);
13220 if (Cmp.getOpcode() != ISD::SETCC ||
13221 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
13222 Cmp.getOperand(0) != N->getOperand(1) ||
13223 Cmp.getOperand(1) != N->getOperand(2))
13224 return SDValue();
13225 Shft = N->getOperand(1);
13226 Clamp = isConstOrConstSplat(N->getOperand(2));
13227 } else
13228 return SDValue();
13229
13230 if (!Clamp)
13231 return SDValue();
13232
13233 MVT ScalarType;
13234 int ShftAmt = 0;
13235 switch (Clamp->getSExtValue()) {
13236 case (1 << 7) - 1:
13237 ScalarType = MVT::i8;
13238 ShftAmt = 7;
13239 break;
13240 case (1 << 15) - 1:
13241 ScalarType = MVT::i16;
13242 ShftAmt = 15;
13243 break;
13244 case (1ULL << 31) - 1:
13245 ScalarType = MVT::i32;
13246 ShftAmt = 31;
13247 break;
13248 default:
13249 return SDValue();
13250 }
13251
13252 if (Shft.getOpcode() != ISD::SRA)
13253 return SDValue();
13255 if (!N1 || N1->getSExtValue() != ShftAmt)
13256 return SDValue();
13257
13258 SDValue Mul = Shft.getOperand(0);
13259 if (Mul.getOpcode() != ISD::MUL)
13260 return SDValue();
13261
13262 SDValue Ext0 = Mul.getOperand(0);
13263 SDValue Ext1 = Mul.getOperand(1);
13264 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13265 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13266 return SDValue();
13267 EVT VecVT = Ext0.getOperand(0).getValueType();
13268 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13269 return SDValue();
13270 if (Ext1.getOperand(0).getValueType() != VecVT ||
13271 VecVT.getScalarType() != ScalarType ||
13272 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13273 return SDValue();
13274
13275 SDLoc DL(Mul);
13276 unsigned LegalLanes = 128 / (ShftAmt + 1);
13277 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13278 // For types smaller than legal vectors extend to be legal and only use needed
13279 // lanes.
13280 if (VecVT.getSizeInBits() < 128) {
13281 EVT ExtVecVT =
13283 VecVT.getVectorNumElements());
13284 SDValue Inp0 =
13285 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13286 SDValue Inp1 =
13287 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13288 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13289 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13290 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13291 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13292 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13293 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13294 }
13295
13296 // For larger types, split into legal sized chunks.
13297 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13298 unsigned NumParts = VecVT.getSizeInBits() / 128;
13300 for (unsigned I = 0; I < NumParts; ++I) {
13301 SDValue Inp0 =
13302 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13303 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13304 SDValue Inp1 =
13305 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13306 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13307 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13308 Parts.push_back(VQDMULH);
13309 }
13310 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13311 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13312}
13313
13316 const ARMSubtarget *Subtarget) {
13317 if (!Subtarget->hasMVEIntegerOps())
13318 return SDValue();
13319
13320 // Constant fold vselect 0, A, B -> B
13321 // and vselect 0xffff, A, B -> A
13322 if (N->getOperand(0).getOpcode() == ARMISD::PREDICATE_CAST &&
13323 isa<ConstantSDNode>(N->getOperand(0).getOperand(0))) {
13324 unsigned C = N->getOperand(0).getConstantOperandVal(0);
13325 if (C == 0)
13326 return N->getOperand(2);
13327 if (C == 0xffff)
13328 return N->getOperand(1);
13329 }
13330
13331 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13332 return V;
13333
13334 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13335 //
13336 // We need to re-implement this optimization here as the implementation in the
13337 // Target-Independent DAGCombiner does not handle the kind of constant we make
13338 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13339 // good reason, allowing truncation there would break other targets).
13340 //
13341 // Currently, this is only done for MVE, as it's the only target that benefits
13342 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13343 if (N->getOperand(0).getOpcode() != ISD::XOR)
13344 return SDValue();
13345 SDValue XOR = N->getOperand(0);
13346
13347 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13348 // It is important to check with truncation allowed as the BUILD_VECTORs we
13349 // generate in those situations will truncate their operands.
13350 ConstantSDNode *Const =
13351 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13352 /*AllowTruncation*/ true);
13353 if (!Const || !Const->isOne())
13354 return SDValue();
13355
13356 // Rewrite into vselect(cond, rhs, lhs).
13357 SDValue Cond = XOR->getOperand(0);
13358 SDValue LHS = N->getOperand(1);
13359 SDValue RHS = N->getOperand(2);
13360 EVT Type = N->getValueType(0);
13361 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13362}
13363
13364// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13367 const ARMSubtarget *Subtarget) {
13368 SDValue Op0 = N->getOperand(0);
13369 SDValue Op1 = N->getOperand(1);
13370 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13371 EVT VT = N->getValueType(0);
13372
13373 if (!Subtarget->hasMVEIntegerOps() ||
13375 return SDValue();
13376
13377 if (CC == ISD::SETUGE) {
13378 std::swap(Op0, Op1);
13379 CC = ISD::SETULT;
13380 }
13381
13382 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13384 return SDValue();
13385
13386 // Check first operand is BuildVector of 0,1,2,...
13387 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13388 if (!Op0.getOperand(I).isUndef() &&
13390 Op0.getConstantOperandVal(I) == I))
13391 return SDValue();
13392 }
13393
13394 // The second is a Splat of Op1S
13395 SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13396 if (!Op1S)
13397 return SDValue();
13398
13399 unsigned Opc;
13400 switch (VT.getVectorNumElements()) {
13401 case 2:
13402 Opc = Intrinsic::arm_mve_vctp64;
13403 break;
13404 case 4:
13405 Opc = Intrinsic::arm_mve_vctp32;
13406 break;
13407 case 8:
13408 Opc = Intrinsic::arm_mve_vctp16;
13409 break;
13410 case 16:
13411 Opc = Intrinsic::arm_mve_vctp8;
13412 break;
13413 default:
13414 return SDValue();
13415 }
13416
13417 SDLoc DL(N);
13418 return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13419 DCI.DAG.getConstant(Opc, DL, MVT::i32),
13420 DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13421}
13422
13423/// PerformADDECombine - Target-specific dag combine transform from
13424/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13425/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13428 const ARMSubtarget *Subtarget) {
13429 // Only ARM and Thumb2 support UMLAL/SMLAL.
13430 if (Subtarget->isThumb1Only())
13431 return PerformAddeSubeCombine(N, DCI, Subtarget);
13432
13433 // Only perform the checks after legalize when the pattern is available.
13434 if (DCI.isBeforeLegalize()) return SDValue();
13435
13436 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13437}
13438
13439/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13440/// operands N0 and N1. This is a helper for PerformADDCombine that is
13441/// called with the default operands, and if that fails, with commuted
13442/// operands.
13445 const ARMSubtarget *Subtarget){
13446 // Attempt to create vpadd for this add.
13447 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13448 return Result;
13449
13450 // Attempt to create vpaddl for this add.
13451 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13452 return Result;
13453 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13454 Subtarget))
13455 return Result;
13456
13457 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13458 if (N0.getNode()->hasOneUse())
13459 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13460 return Result;
13461 return SDValue();
13462}
13463
13465 EVT VT = N->getValueType(0);
13466 SDValue N0 = N->getOperand(0);
13467 SDValue N1 = N->getOperand(1);
13468 SDLoc dl(N);
13469
13470 auto IsVecReduce = [](SDValue Op) {
13471 switch (Op.getOpcode()) {
13472 case ISD::VECREDUCE_ADD:
13473 case ARMISD::VADDVs:
13474 case ARMISD::VADDVu:
13475 case ARMISD::VMLAVs:
13476 case ARMISD::VMLAVu:
13477 return true;
13478 }
13479 return false;
13480 };
13481
13482 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13483 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13484 // add(add(X, vecreduce(Y)), vecreduce(Z))
13485 // to make better use of vaddva style instructions.
13486 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13487 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13488 !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13489 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13490 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13491 }
13492 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13493 // add(add(add(A, C), reduce(B)), reduce(D))
13494 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13495 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13496 unsigned N0RedOp = 0;
13497 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13498 N0RedOp = 1;
13499 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13500 return SDValue();
13501 }
13502
13503 unsigned N1RedOp = 0;
13504 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13505 N1RedOp = 1;
13506 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13507 return SDValue();
13508
13509 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13510 N1.getOperand(1 - N1RedOp));
13511 SDValue Add1 =
13512 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13513 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13514 }
13515 return SDValue();
13516 };
13517 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13518 return R;
13519 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13520 return R;
13521
13522 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13523 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13524 // by ascending load offsets. This can help cores prefetch if the order of
13525 // loads is more predictable.
13526 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13527 // Check if two reductions are known to load data where one is before/after
13528 // another. Return negative if N0 loads data before N1, positive if N1 is
13529 // before N0 and 0 otherwise if nothing is known.
13530 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13531 // Look through to the first operand of a MUL, for the VMLA case.
13532 // Currently only looks at the first operand, in the hope they are equal.
13533 if (N0.getOpcode() == ISD::MUL)
13534 N0 = N0.getOperand(0);
13535 if (N1.getOpcode() == ISD::MUL)
13536 N1 = N1.getOperand(0);
13537
13538 // Return true if the two operands are loads to the same object and the
13539 // offset of the first is known to be less than the offset of the second.
13540 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13541 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13542 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13543 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13544 Load1->isIndexed())
13545 return 0;
13546
13547 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13548 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13549
13550 if (!BaseLocDecomp0.getBase() ||
13551 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13552 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13553 return 0;
13554 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13555 return -1;
13556 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13557 return 1;
13558 return 0;
13559 };
13560
13561 SDValue X;
13562 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13563 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13564 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13565 N0.getOperand(1).getOperand(0));
13566 if (IsBefore < 0) {
13567 X = N0.getOperand(0);
13568 N0 = N0.getOperand(1);
13569 } else if (IsBefore > 0) {
13570 X = N0.getOperand(1);
13571 N0 = N0.getOperand(0);
13572 } else
13573 return SDValue();
13574 } else if (IsVecReduce(N0.getOperand(0))) {
13575 X = N0.getOperand(1);
13576 N0 = N0.getOperand(0);
13577 } else if (IsVecReduce(N0.getOperand(1))) {
13578 X = N0.getOperand(0);
13579 N0 = N0.getOperand(1);
13580 } else
13581 return SDValue();
13582 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13583 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13584 // Note this is backward to how you would expect. We create
13585 // add(reduce(load + 16), reduce(load + 0)) so that the
13586 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13587 // the X as VADDV(load + 0)
13588 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13589 } else
13590 return SDValue();
13591
13592 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13593 return SDValue();
13594
13595 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13596 return SDValue();
13597
13598 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13599 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13600 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13601 };
13602 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13603 return R;
13604 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13605 return R;
13606 return SDValue();
13607}
13608
13610 const ARMSubtarget *Subtarget) {
13611 if (!Subtarget->hasMVEIntegerOps())
13612 return SDValue();
13613
13615 return R;
13616
13617 EVT VT = N->getValueType(0);
13618 SDValue N0 = N->getOperand(0);
13619 SDValue N1 = N->getOperand(1);
13620 SDLoc dl(N);
13621
13622 if (VT != MVT::i64)
13623 return SDValue();
13624
13625 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13626 // will look like:
13627 // t1: i32,i32 = ARMISD::VADDLVs x
13628 // t2: i64 = build_pair t1, t1:1
13629 // t3: i64 = add t2, y
13630 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13631 // the add to be simplified separately.
13632 // We also need to check for sext / zext and commutitive adds.
13633 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13634 SDValue NB) {
13635 if (NB->getOpcode() != ISD::BUILD_PAIR)
13636 return SDValue();
13637 SDValue VecRed = NB->getOperand(0);
13638 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13639 VecRed.getResNo() != 0 ||
13640 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13641 return SDValue();
13642
13643 if (VecRed->getOpcode() == OpcodeA) {
13644 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13645 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13646 VecRed.getOperand(0), VecRed.getOperand(1));
13647 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13648 }
13649
13651 std::tie(Ops[0], Ops[1]) = DAG.SplitScalar(NA, dl, MVT::i32, MVT::i32);
13652
13653 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13654 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13655 Ops.push_back(VecRed->getOperand(I));
13656 SDValue Red =
13657 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13658 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13659 SDValue(Red.getNode(), 1));
13660 };
13661
13662 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13663 return M;
13664 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13665 return M;
13666 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13667 return M;
13668 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13669 return M;
13670 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13671 return M;
13672 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13673 return M;
13674 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13675 return M;
13676 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13677 return M;
13678 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13679 return M;
13680 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13681 return M;
13682 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13683 return M;
13684 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13685 return M;
13686 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13687 return M;
13688 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13689 return M;
13690 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13691 return M;
13692 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13693 return M;
13694 return SDValue();
13695}
13696
13697bool
13699 CombineLevel Level) const {
13700 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13701 N->getOpcode() == ISD::SRL) &&
13702 "Expected shift op");
13703
13704 SDValue ShiftLHS = N->getOperand(0);
13705 if (!ShiftLHS->hasOneUse())
13706 return false;
13707
13708 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13709 !ShiftLHS.getOperand(0)->hasOneUse())
13710 return false;
13711
13712 if (Level == BeforeLegalizeTypes)
13713 return true;
13714
13715 if (N->getOpcode() != ISD::SHL)
13716 return true;
13717
13718 if (Subtarget->isThumb1Only()) {
13719 // Avoid making expensive immediates by commuting shifts. (This logic
13720 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13721 // for free.)
13722 if (N->getOpcode() != ISD::SHL)
13723 return true;
13724 SDValue N1 = N->getOperand(0);
13725 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13726 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13727 return true;
13728 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13729 if (Const->getAPIntValue().ult(256))
13730 return false;
13731 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13732 Const->getAPIntValue().sgt(-256))
13733 return false;
13734 }
13735 return true;
13736 }
13737
13738 // Turn off commute-with-shift transform after legalization, so it doesn't
13739 // conflict with PerformSHLSimplify. (We could try to detect when
13740 // PerformSHLSimplify would trigger more precisely, but it isn't
13741 // really necessary.)
13742 return false;
13743}
13744
13746 const SDNode *N) const {
13747 assert(N->getOpcode() == ISD::XOR &&
13748 (N->getOperand(0).getOpcode() == ISD::SHL ||
13749 N->getOperand(0).getOpcode() == ISD::SRL) &&
13750 "Expected XOR(SHIFT) pattern");
13751
13752 // Only commute if the entire NOT mask is a hidden shifted mask.
13753 auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13754 auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13755 if (XorC && ShiftC) {
13756 unsigned MaskIdx, MaskLen;
13757 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13758 unsigned ShiftAmt = ShiftC->getZExtValue();
13759 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13760 if (N->getOperand(0).getOpcode() == ISD::SHL)
13761 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13762 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13763 }
13764 }
13765
13766 return false;
13767}
13768
13770 const SDNode *N) const {
13771 assert(((N->getOpcode() == ISD::SHL &&
13772 N->getOperand(0).getOpcode() == ISD::SRL) ||
13773 (N->getOpcode() == ISD::SRL &&
13774 N->getOperand(0).getOpcode() == ISD::SHL)) &&
13775 "Expected shift-shift mask");
13776
13777 if (!Subtarget->isThumb1Only())
13778 return true;
13779
13780 EVT VT = N->getValueType(0);
13781 if (VT.getScalarSizeInBits() > 32)
13782 return true;
13783
13784 return false;
13785}
13786
13788 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13789 SDValue Y) const {
13790 return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13791 SelectOpcode == ISD::VSELECT;
13792}
13793
13795 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps()) {
13796 if (Subtarget->isThumb1Only())
13797 return VT.getScalarSizeInBits() <= 32;
13798 return true;
13799 }
13800 return VT.isScalarInteger();
13801}
13802
13804 EVT VT) const {
13805 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13806 return false;
13807
13808 switch (FPVT.getSimpleVT().SimpleTy) {
13809 case MVT::f16:
13810 return Subtarget->hasVFP2Base();
13811 case MVT::f32:
13812 return Subtarget->hasVFP2Base();
13813 case MVT::f64:
13814 return Subtarget->hasFP64();
13815 case MVT::v4f32:
13816 case MVT::v8f16:
13817 return Subtarget->hasMVEFloatOps();
13818 default:
13819 return false;
13820 }
13821}
13822
13825 const ARMSubtarget *ST) {
13826 // Allow the generic combiner to identify potential bswaps.
13827 if (DCI.isBeforeLegalize())
13828 return SDValue();
13829
13830 // DAG combiner will fold:
13831 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13832 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13833 // Other code patterns that can be also be modified have the following form:
13834 // b + ((a << 1) | 510)
13835 // b + ((a << 1) & 510)
13836 // b + ((a << 1) ^ 510)
13837 // b + ((a << 1) + 510)
13838
13839 // Many instructions can perform the shift for free, but it requires both
13840 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13841 // instruction will needed. So, unfold back to the original pattern if:
13842 // - if c1 and c2 are small enough that they don't require mov imms.
13843 // - the user(s) of the node can perform an shl
13844
13845 // No shifted operands for 16-bit instructions.
13846 if (ST->isThumb() && ST->isThumb1Only())
13847 return SDValue();
13848
13849 // Check that all the users could perform the shl themselves.
13850 for (auto *U : N->users()) {
13851 switch(U->getOpcode()) {
13852 default:
13853 return SDValue();
13854 case ISD::SUB:
13855 case ISD::ADD:
13856 case ISD::AND:
13857 case ISD::OR:
13858 case ISD::XOR:
13859 case ISD::SETCC:
13860 case ARMISD::CMP:
13861 // Check that the user isn't already using a constant because there
13862 // aren't any instructions that support an immediate operand and a
13863 // shifted operand.
13864 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13865 isa<ConstantSDNode>(U->getOperand(1)))
13866 return SDValue();
13867
13868 // Check that it's not already using a shift.
13869 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13870 U->getOperand(1).getOpcode() == ISD::SHL)
13871 return SDValue();
13872 break;
13873 }
13874 }
13875
13876 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13877 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13878 return SDValue();
13879
13880 if (N->getOperand(0).getOpcode() != ISD::SHL)
13881 return SDValue();
13882
13883 SDValue SHL = N->getOperand(0);
13884
13885 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13886 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13887 if (!C1ShlC2 || !C2)
13888 return SDValue();
13889
13890 APInt C2Int = C2->getAPIntValue();
13891 APInt C1Int = C1ShlC2->getAPIntValue();
13892 unsigned C2Width = C2Int.getBitWidth();
13893 if (C2Int.uge(C2Width))
13894 return SDValue();
13895 uint64_t C2Value = C2Int.getZExtValue();
13896
13897 // Check that performing a lshr will not lose any information.
13898 APInt Mask = APInt::getHighBitsSet(C2Width, C2Width - C2Value);
13899 if ((C1Int & Mask) != C1Int)
13900 return SDValue();
13901
13902 // Shift the first constant.
13903 C1Int.lshrInPlace(C2Int);
13904
13905 // The immediates are encoded as an 8-bit value that can be rotated.
13906 auto LargeImm = [](const APInt &Imm) {
13907 unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13908 return Imm.getBitWidth() - Zeros > 8;
13909 };
13910
13911 if (LargeImm(C1Int) || LargeImm(C2Int))
13912 return SDValue();
13913
13914 SelectionDAG &DAG = DCI.DAG;
13915 SDLoc dl(N);
13916 SDValue X = SHL.getOperand(0);
13917 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13918 DAG.getConstant(C1Int, dl, MVT::i32));
13919 // Shift left to compensate for the lshr of C1Int.
13920 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13921
13922 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
13923 SHL.dump(); N->dump());
13924 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
13925 return Res;
13926}
13927
13928
13929/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13930///
13933 const ARMSubtarget *Subtarget) {
13934 SDValue N0 = N->getOperand(0);
13935 SDValue N1 = N->getOperand(1);
13936
13937 // Only works one way, because it needs an immediate operand.
13938 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13939 return Result;
13940
13941 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13942 return Result;
13943
13944 // First try with the default operand order.
13945 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13946 return Result;
13947
13948 // If that didn't work, try again with the operands commuted.
13949 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13950}
13951
13952// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13953// providing -X is as cheap as X (currently, just a constant).
13955 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13956 return SDValue();
13957 SDValue CSINC = N->getOperand(1);
13958 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13959 return SDValue();
13960
13962 if (!X)
13963 return SDValue();
13964
13965 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13966 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13967 CSINC.getOperand(0)),
13968 CSINC.getOperand(1), CSINC.getOperand(2),
13969 CSINC.getOperand(3));
13970}
13971
13973 // Free to negate.
13975 return 0;
13976
13977 // Will save one instruction.
13978 if (Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)))
13979 return -1;
13980
13981 // Can freely negate by converting sra <-> srl.
13982 if (Op.getOpcode() == ISD::SRA || Op.getOpcode() == ISD::SRL) {
13983 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13984 if (Op.hasOneUse() && ShiftAmt &&
13985 ShiftAmt->getZExtValue() == Op.getValueType().getScalarSizeInBits() - 1)
13986 return 0;
13987 }
13988
13989 // Will have to create sub.
13990 return 1;
13991}
13992
13993// Try to fold
13994//
13995// (neg (cmov X, Y)) -> (cmov (neg X), (neg Y))
13996//
13997// The folding helps cmov to be matched with csneg without generating
13998// redundant neg instruction.
14000 assert(N->getOpcode() == ISD::SUB);
14001 if (!isNullConstant(N->getOperand(0)))
14002 return SDValue();
14003
14004 SDValue CMov = N->getOperand(1);
14005 if (CMov.getOpcode() != ARMISD::CMOV || !CMov->hasOneUse())
14006 return SDValue();
14007
14008 SDValue N0 = CMov.getOperand(0);
14009 SDValue N1 = CMov.getOperand(1);
14010
14011 // Only perform the fold if we actually save something.
14012 if (getNegationCost(N0) + getNegationCost(N1) > 0)
14013 return SDValue();
14014
14015 SDLoc DL(N);
14016 EVT VT = CMov.getValueType();
14017
14018 SDValue N0N = DAG.getNegative(N0, DL, VT);
14019 SDValue N1N = DAG.getNegative(N1, DL, VT);
14020 return DAG.getNode(ARMISD::CMOV, DL, VT, N0N, N1N, CMov.getOperand(2),
14021 CMov.getOperand(3));
14022}
14023
14024/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
14025///
14028 const ARMSubtarget *Subtarget) {
14029 SDValue N0 = N->getOperand(0);
14030 SDValue N1 = N->getOperand(1);
14031
14032 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
14033 if (N1.getNode()->hasOneUse())
14034 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
14035 return Result;
14036
14037 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
14038 return R;
14039
14040 if (SDValue Val = performNegCMovCombine(N, DCI.DAG))
14041 return Val;
14042
14043 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
14044 return SDValue();
14045
14046 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14047 // so that we can readily pattern match more mve instructions which can use
14048 // a scalar operand.
14049 SDValue VDup = N->getOperand(1);
14050 if (VDup->getOpcode() != ARMISD::VDUP)
14051 return SDValue();
14052
14053 SDValue VMov = N->getOperand(0);
14054 if (VMov->getOpcode() == ISD::BITCAST)
14055 VMov = VMov->getOperand(0);
14056
14057 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
14058 return SDValue();
14059
14060 SDLoc dl(N);
14061 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
14062 DCI.DAG.getConstant(0, dl, MVT::i32),
14063 VDup->getOperand(0));
14064 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
14065}
14066
14067/// PerformVMULCombine
14068/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14069/// special multiplier accumulator forwarding.
14070/// vmul d3, d0, d2
14071/// vmla d3, d1, d2
14072/// is faster than
14073/// vadd d3, d0, d1
14074/// vmul d3, d3, d2
14075// However, for (A + B) * (A + B),
14076// vadd d2, d0, d1
14077// vmul d3, d0, d2
14078// vmla d3, d1, d2
14079// is slower than
14080// vadd d2, d0, d1
14081// vmul d3, d2, d2
14084 const ARMSubtarget *Subtarget) {
14085 if (!Subtarget->hasVMLxForwarding())
14086 return SDValue();
14087
14088 SelectionDAG &DAG = DCI.DAG;
14089 SDValue N0 = N->getOperand(0);
14090 SDValue N1 = N->getOperand(1);
14091 unsigned Opcode = N0.getOpcode();
14092 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14093 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14094 Opcode = N1.getOpcode();
14095 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14096 Opcode != ISD::FADD && Opcode != ISD::FSUB)
14097 return SDValue();
14098 std::swap(N0, N1);
14099 }
14100
14101 if (N0 == N1)
14102 return SDValue();
14103
14104 EVT VT = N->getValueType(0);
14105 SDLoc DL(N);
14106 SDValue N00 = N0->getOperand(0);
14107 SDValue N01 = N0->getOperand(1);
14108 return DAG.getNode(Opcode, DL, VT,
14109 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
14110 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
14111}
14112
14114 const ARMSubtarget *Subtarget) {
14115 EVT VT = N->getValueType(0);
14116 if (VT != MVT::v2i64)
14117 return SDValue();
14118
14119 SDValue N0 = N->getOperand(0);
14120 SDValue N1 = N->getOperand(1);
14121
14122 auto IsSignExt = [&](SDValue Op) {
14123 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14124 return SDValue();
14125 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
14126 if (VT.getScalarSizeInBits() == 32)
14127 return Op->getOperand(0);
14128 return SDValue();
14129 };
14130 auto IsZeroExt = [&](SDValue Op) {
14131 // Zero extends are a little more awkward. At the point we are matching
14132 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14133 // That might be before of after a bitcast depending on how the and is
14134 // placed. Because this has to look through bitcasts, it is currently only
14135 // supported on LE.
14136 if (!Subtarget->isLittle())
14137 return SDValue();
14138
14139 SDValue And = Op;
14140 if (And->getOpcode() == ISD::BITCAST)
14141 And = And->getOperand(0);
14142 if (And->getOpcode() != ISD::AND)
14143 return SDValue();
14144 SDValue Mask = And->getOperand(1);
14145 if (Mask->getOpcode() == ISD::BITCAST)
14146 Mask = Mask->getOperand(0);
14147
14148 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14149 Mask.getValueType() != MVT::v4i32)
14150 return SDValue();
14151 if (isAllOnesConstant(Mask->getOperand(0)) &&
14152 isNullConstant(Mask->getOperand(1)) &&
14153 isAllOnesConstant(Mask->getOperand(2)) &&
14154 isNullConstant(Mask->getOperand(3)))
14155 return And->getOperand(0);
14156 return SDValue();
14157 };
14158
14159 SDLoc dl(N);
14160 if (SDValue Op0 = IsSignExt(N0)) {
14161 if (SDValue Op1 = IsSignExt(N1)) {
14162 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14163 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14164 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
14165 }
14166 }
14167 if (SDValue Op0 = IsZeroExt(N0)) {
14168 if (SDValue Op1 = IsZeroExt(N1)) {
14169 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14170 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14171 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
14172 }
14173 }
14174
14175 return SDValue();
14176}
14177
14180 const ARMSubtarget *Subtarget) {
14181 SelectionDAG &DAG = DCI.DAG;
14182
14183 EVT VT = N->getValueType(0);
14184 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14185 return PerformMVEVMULLCombine(N, DAG, Subtarget);
14186
14187 if (Subtarget->isThumb1Only())
14188 return SDValue();
14189
14190 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14191 return SDValue();
14192
14193 if (VT.is64BitVector() || VT.is128BitVector())
14194 return PerformVMULCombine(N, DCI, Subtarget);
14195 if (VT != MVT::i32)
14196 return SDValue();
14197
14198 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14199 if (!C)
14200 return SDValue();
14201
14202 int64_t MulAmt = C->getSExtValue();
14203 unsigned ShiftAmt = llvm::countr_zero<uint64_t>(MulAmt);
14204
14205 ShiftAmt = ShiftAmt & (32 - 1);
14206 SDValue V = N->getOperand(0);
14207 SDLoc DL(N);
14208
14209 SDValue Res;
14210 MulAmt >>= ShiftAmt;
14211
14212 if (MulAmt >= 0) {
14213 if (llvm::has_single_bit<uint32_t>(MulAmt - 1)) {
14214 // (mul x, 2^N + 1) => (add (shl x, N), x)
14215 Res = DAG.getNode(ISD::ADD, DL, VT,
14216 V,
14217 DAG.getNode(ISD::SHL, DL, VT,
14218 V,
14219 DAG.getConstant(Log2_32(MulAmt - 1), DL,
14220 MVT::i32)));
14221 } else if (llvm::has_single_bit<uint32_t>(MulAmt + 1)) {
14222 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14223 Res = DAG.getNode(ISD::SUB, DL, VT,
14224 DAG.getNode(ISD::SHL, DL, VT,
14225 V,
14226 DAG.getConstant(Log2_32(MulAmt + 1), DL,
14227 MVT::i32)),
14228 V);
14229 } else
14230 return SDValue();
14231 } else {
14232 uint64_t MulAmtAbs = -MulAmt;
14233 if (llvm::has_single_bit<uint32_t>(MulAmtAbs + 1)) {
14234 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14235 Res = DAG.getNode(ISD::SUB, DL, VT,
14236 V,
14237 DAG.getNode(ISD::SHL, DL, VT,
14238 V,
14239 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14240 MVT::i32)));
14241 } else if (llvm::has_single_bit<uint32_t>(MulAmtAbs - 1)) {
14242 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14243 Res = DAG.getNode(ISD::ADD, DL, VT,
14244 V,
14245 DAG.getNode(ISD::SHL, DL, VT,
14246 V,
14247 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14248 MVT::i32)));
14249 Res = DAG.getNode(ISD::SUB, DL, VT,
14250 DAG.getConstant(0, DL, MVT::i32), Res);
14251 } else
14252 return SDValue();
14253 }
14254
14255 if (ShiftAmt != 0)
14256 Res = DAG.getNode(ISD::SHL, DL, VT,
14257 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14258
14259 // Do not add new nodes to DAG combiner worklist.
14260 DCI.CombineTo(N, Res, false);
14261 return SDValue();
14262}
14263
14266 const ARMSubtarget *Subtarget) {
14267 // Allow DAGCombine to pattern-match before we touch the canonical form.
14268 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14269 return SDValue();
14270
14271 if (N->getValueType(0) != MVT::i32)
14272 return SDValue();
14273
14274 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14275 if (!N1C)
14276 return SDValue();
14277
14278 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14279 // Don't transform uxtb/uxth.
14280 if (C1 == 255 || C1 == 65535)
14281 return SDValue();
14282
14283 SDNode *N0 = N->getOperand(0).getNode();
14284 if (!N0->hasOneUse())
14285 return SDValue();
14286
14287 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14288 return SDValue();
14289
14290 bool LeftShift = N0->getOpcode() == ISD::SHL;
14291
14293 if (!N01C)
14294 return SDValue();
14295
14296 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14297 if (!C2 || C2 >= 32)
14298 return SDValue();
14299
14300 // Clear irrelevant bits in the mask.
14301 if (LeftShift)
14302 C1 &= (-1U << C2);
14303 else
14304 C1 &= (-1U >> C2);
14305
14306 SelectionDAG &DAG = DCI.DAG;
14307 SDLoc DL(N);
14308
14309 // We have a pattern of the form "(and (shl x, c2) c1)" or
14310 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14311 // transform to a pair of shifts, to save materializing c1.
14312
14313 // First pattern: right shift, then mask off leading bits.
14314 // FIXME: Use demanded bits?
14315 if (!LeftShift && isMask_32(C1)) {
14316 uint32_t C3 = llvm::countl_zero(C1);
14317 if (C2 < C3) {
14318 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14319 DAG.getConstant(C3 - C2, DL, MVT::i32));
14320 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14321 DAG.getConstant(C3, DL, MVT::i32));
14322 }
14323 }
14324
14325 // First pattern, reversed: left shift, then mask off trailing bits.
14326 if (LeftShift && isMask_32(~C1)) {
14327 uint32_t C3 = llvm::countr_zero(C1);
14328 if (C2 < C3) {
14329 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14330 DAG.getConstant(C3 - C2, DL, MVT::i32));
14331 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14332 DAG.getConstant(C3, DL, MVT::i32));
14333 }
14334 }
14335
14336 // Second pattern: left shift, then mask off leading bits.
14337 // FIXME: Use demanded bits?
14338 if (LeftShift && isShiftedMask_32(C1)) {
14339 uint32_t Trailing = llvm::countr_zero(C1);
14340 uint32_t C3 = llvm::countl_zero(C1);
14341 if (Trailing == C2 && C2 + C3 < 32) {
14342 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14343 DAG.getConstant(C2 + C3, DL, MVT::i32));
14344 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14345 DAG.getConstant(C3, DL, MVT::i32));
14346 }
14347 }
14348
14349 // Second pattern, reversed: right shift, then mask off trailing bits.
14350 // FIXME: Handle other patterns of known/demanded bits.
14351 if (!LeftShift && isShiftedMask_32(C1)) {
14352 uint32_t Leading = llvm::countl_zero(C1);
14353 uint32_t C3 = llvm::countr_zero(C1);
14354 if (Leading == C2 && C2 + C3 < 32) {
14355 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14356 DAG.getConstant(C2 + C3, DL, MVT::i32));
14357 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14358 DAG.getConstant(C3, DL, MVT::i32));
14359 }
14360 }
14361
14362 // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14363 // if "c1 >> c2" is a cheaper immediate than "c1"
14364 if (LeftShift &&
14365 HasLowerConstantMaterializationCost(C1 >> C2, C1, Subtarget)) {
14366
14367 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i32, N0->getOperand(0),
14368 DAG.getConstant(C1 >> C2, DL, MVT::i32));
14369 return DAG.getNode(ISD::SHL, DL, MVT::i32, And,
14370 DAG.getConstant(C2, DL, MVT::i32));
14371 }
14372
14373 return SDValue();
14374}
14375
14378 const ARMSubtarget *Subtarget) {
14379 // Attempt to use immediate-form VBIC
14380 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14381 SDLoc dl(N);
14382 EVT VT = N->getValueType(0);
14383 SelectionDAG &DAG = DCI.DAG;
14384
14385 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14386 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14387 return SDValue();
14388
14389 APInt SplatBits, SplatUndef;
14390 unsigned SplatBitSize;
14391 bool HasAnyUndefs;
14392 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14393 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14394 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14395 SplatBitSize == 64) {
14396 EVT VbicVT;
14397 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14398 SplatUndef.getZExtValue(), SplatBitSize,
14399 DAG, dl, VbicVT, VT, OtherModImm);
14400 if (Val.getNode()) {
14401 SDValue Input =
14402 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VbicVT, N->getOperand(0));
14403 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14404 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vbic);
14405 }
14406 }
14407 }
14408
14409 if (!Subtarget->isThumb1Only()) {
14410 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14411 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14412 return Result;
14413
14414 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14415 return Result;
14416 }
14417
14418 if (Subtarget->isThumb1Only())
14419 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14420 return Result;
14421
14422 return SDValue();
14423}
14424
14425// Try combining OR nodes to SMULWB, SMULWT.
14428 const ARMSubtarget *Subtarget) {
14429 if (!Subtarget->hasV6Ops() ||
14430 (Subtarget->isThumb() &&
14431 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14432 return SDValue();
14433
14434 SDValue SRL = OR->getOperand(0);
14435 SDValue SHL = OR->getOperand(1);
14436
14437 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14438 SRL = OR->getOperand(1);
14439 SHL = OR->getOperand(0);
14440 }
14441 if (!isSRL16(SRL) || !isSHL16(SHL))
14442 return SDValue();
14443
14444 // The first operands to the shifts need to be the two results from the
14445 // same smul_lohi node.
14446 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14447 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14448 return SDValue();
14449
14450 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14451 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14452 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14453 return SDValue();
14454
14455 // Now we have:
14456 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14457 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14458 // For SMUWB the 16-bit value will signed extended somehow.
14459 // For SMULWT only the SRA is required.
14460 // Check both sides of SMUL_LOHI
14461 SDValue OpS16 = SMULLOHI->getOperand(0);
14462 SDValue OpS32 = SMULLOHI->getOperand(1);
14463
14464 SelectionDAG &DAG = DCI.DAG;
14465 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14466 OpS16 = OpS32;
14467 OpS32 = SMULLOHI->getOperand(0);
14468 }
14469
14470 SDLoc dl(OR);
14471 unsigned Opcode = 0;
14472 if (isS16(OpS16, DAG))
14473 Opcode = ARMISD::SMULWB;
14474 else if (isSRA16(OpS16)) {
14475 Opcode = ARMISD::SMULWT;
14476 OpS16 = OpS16->getOperand(0);
14477 }
14478 else
14479 return SDValue();
14480
14481 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14482 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14483 return SDValue(OR, 0);
14484}
14485
14488 const ARMSubtarget *Subtarget) {
14489 // BFI is only available on V6T2+
14490 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14491 return SDValue();
14492
14493 EVT VT = N->getValueType(0);
14494 SDValue N0 = N->getOperand(0);
14495 SDValue N1 = N->getOperand(1);
14496 SelectionDAG &DAG = DCI.DAG;
14497 SDLoc DL(N);
14498 // 1) or (and A, mask), val => ARMbfi A, val, mask
14499 // iff (val & mask) == val
14500 //
14501 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14502 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14503 // && mask == ~mask2
14504 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14505 // && ~mask == mask2
14506 // (i.e., copy a bitfield value into another bitfield of the same width)
14507
14508 if (VT != MVT::i32)
14509 return SDValue();
14510
14511 SDValue N00 = N0.getOperand(0);
14512
14513 // The value and the mask need to be constants so we can verify this is
14514 // actually a bitfield set. If the mask is 0xffff, we can do better
14515 // via a movt instruction, so don't use BFI in that case.
14516 SDValue MaskOp = N0.getOperand(1);
14518 if (!MaskC)
14519 return SDValue();
14520 unsigned Mask = MaskC->getZExtValue();
14521 if (Mask == 0xffff)
14522 return SDValue();
14523 SDValue Res;
14524 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14526 if (N1C) {
14527 unsigned Val = N1C->getZExtValue();
14528 if ((Val & ~Mask) != Val)
14529 return SDValue();
14530
14531 if (ARM::isBitFieldInvertedMask(Mask)) {
14532 Val >>= llvm::countr_zero(~Mask);
14533
14534 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14535 DAG.getConstant(Val, DL, MVT::i32),
14536 DAG.getConstant(Mask, DL, MVT::i32));
14537
14538 DCI.CombineTo(N, Res, false);
14539 // Return value from the original node to inform the combiner than N is
14540 // now dead.
14541 return SDValue(N, 0);
14542 }
14543 } else if (N1.getOpcode() == ISD::AND) {
14544 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14546 if (!N11C)
14547 return SDValue();
14548 unsigned Mask2 = N11C->getZExtValue();
14549
14550 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14551 // as is to match.
14552 if (ARM::isBitFieldInvertedMask(Mask) &&
14553 (Mask == ~Mask2)) {
14554 // The pack halfword instruction works better for masks that fit it,
14555 // so use that when it's available.
14556 if (Subtarget->hasDSP() &&
14557 (Mask == 0xffff || Mask == 0xffff0000))
14558 return SDValue();
14559 // 2a
14560 unsigned amt = llvm::countr_zero(Mask2);
14561 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14562 DAG.getConstant(amt, DL, MVT::i32));
14563 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14564 DAG.getConstant(Mask, DL, MVT::i32));
14565 DCI.CombineTo(N, Res, false);
14566 // Return value from the original node to inform the combiner than N is
14567 // now dead.
14568 return SDValue(N, 0);
14569 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14570 (~Mask == Mask2)) {
14571 // The pack halfword instruction works better for masks that fit it,
14572 // so use that when it's available.
14573 if (Subtarget->hasDSP() &&
14574 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14575 return SDValue();
14576 // 2b
14577 unsigned lsb = llvm::countr_zero(Mask);
14578 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14579 DAG.getConstant(lsb, DL, MVT::i32));
14580 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14581 DAG.getConstant(Mask2, DL, MVT::i32));
14582 DCI.CombineTo(N, Res, false);
14583 // Return value from the original node to inform the combiner than N is
14584 // now dead.
14585 return SDValue(N, 0);
14586 }
14587 }
14588
14589 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14590 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14592 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14593 // where lsb(mask) == #shamt and masked bits of B are known zero.
14594 SDValue ShAmt = N00.getOperand(1);
14595 unsigned ShAmtC = ShAmt->getAsZExtVal();
14596 unsigned LSB = llvm::countr_zero(Mask);
14597 if (ShAmtC != LSB)
14598 return SDValue();
14599
14600 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14601 DAG.getConstant(~Mask, DL, MVT::i32));
14602
14603 DCI.CombineTo(N, Res, false);
14604 // Return value from the original node to inform the combiner than N is
14605 // now dead.
14606 return SDValue(N, 0);
14607 }
14608
14609 return SDValue();
14610}
14611
14612static bool isValidMVECond(unsigned CC, bool IsFloat) {
14613 switch (CC) {
14614 case ARMCC::EQ:
14615 case ARMCC::NE:
14616 case ARMCC::LE:
14617 case ARMCC::GT:
14618 case ARMCC::GE:
14619 case ARMCC::LT:
14620 return true;
14621 case ARMCC::HS:
14622 case ARMCC::HI:
14623 return !IsFloat;
14624 default:
14625 return false;
14626 };
14627}
14628
14630 if (N->getOpcode() == ARMISD::VCMP)
14631 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14632 else if (N->getOpcode() == ARMISD::VCMPZ)
14633 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14634 else
14635 llvm_unreachable("Not a VCMP/VCMPZ!");
14636}
14637
14640 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14641}
14642
14644 const ARMSubtarget *Subtarget) {
14645 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14646 // together with predicates
14647 EVT VT = N->getValueType(0);
14648 SDLoc DL(N);
14649 SDValue N0 = N->getOperand(0);
14650 SDValue N1 = N->getOperand(1);
14651
14652 auto IsFreelyInvertable = [&](SDValue V) {
14653 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14654 return CanInvertMVEVCMP(V);
14655 return false;
14656 };
14657
14658 // At least one operand must be freely invertable.
14659 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14660 return SDValue();
14661
14662 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14663 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14664 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14665 return DAG.getLogicalNOT(DL, And, VT);
14666}
14667
14668// Try to form a NEON shift-{right, left}-and-insert (VSRI/VSLI) from:
14669// (or (and X, splat (i32 C1)), (srl Y, splat (i32 C2))) -> VSRI X, Y, #C2
14670// (or (and X, splat (i32 C1)), (shl Y, splat (i32 C2))) -> VSLI X, Y, #C2
14671// where C1 is a mask that preserves the bits not written by the shift/insert,
14672// i.e. `C1 == (1 << C2) - 1`.
14674 SDValue ShiftOp, EVT VT,
14675 SDLoc dl) {
14676 // Match (and X, Mask)
14677 if (AndOp.getOpcode() != ISD::AND)
14678 return SDValue();
14679
14680 SDValue X = AndOp.getOperand(0);
14681 SDValue Mask = AndOp.getOperand(1);
14682
14683 ConstantSDNode *MaskC = isConstOrConstSplat(Mask, false, true);
14684 if (!MaskC)
14685 return SDValue();
14686 APInt MaskBits =
14687 MaskC->getAPIntValue().trunc(Mask.getScalarValueSizeInBits());
14688
14689 // Match shift (srl/shl Y, CntVec)
14690 int64_t Cnt = 0;
14691 bool IsShiftRight = false;
14692 SDValue Y;
14693
14694 if (ShiftOp.getOpcode() == ARMISD::VSHRuIMM) {
14695 IsShiftRight = true;
14696 Y = ShiftOp.getOperand(0);
14697 Cnt = ShiftOp.getConstantOperandVal(1);
14698 } else if (ShiftOp.getOpcode() == ARMISD::VSHLIMM) {
14699 Y = ShiftOp.getOperand(0);
14700 Cnt = ShiftOp.getConstantOperandVal(1);
14701 } else {
14702 return SDValue();
14703 }
14704
14705 unsigned ElemBits = VT.getScalarSizeInBits();
14706 APInt RequiredMask = IsShiftRight
14707 ? APInt::getHighBitsSet(ElemBits, (unsigned)Cnt)
14708 : APInt::getLowBitsSet(ElemBits, (unsigned)Cnt);
14709 if (MaskBits != RequiredMask)
14710 return SDValue();
14711
14712 unsigned Opc = IsShiftRight ? ARMISD::VSRIIMM : ARMISD::VSLIIMM;
14713 return DAG.getNode(Opc, dl, VT, X, Y, DAG.getConstant(Cnt, dl, MVT::i32));
14714}
14715
14716/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14718 const ARMSubtarget *Subtarget) {
14719 // Attempt to use immediate-form VORR
14720 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14721 SDLoc dl(N);
14722 EVT VT = N->getValueType(0);
14723 SelectionDAG &DAG = DCI.DAG;
14724
14725 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14726 return SDValue();
14727
14728 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14729 VT == MVT::v8i1 || VT == MVT::v16i1))
14730 return PerformORCombine_i1(N, DAG, Subtarget);
14731
14732 APInt SplatBits, SplatUndef;
14733 unsigned SplatBitSize;
14734 bool HasAnyUndefs;
14735 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14736 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14737 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14738 SplatBitSize == 64) {
14739 EVT VorrVT;
14740 SDValue Val =
14741 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14742 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14743 if (Val.getNode()) {
14744 SDValue Input =
14745 DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VorrVT, N->getOperand(0));
14746 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14747 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vorr);
14748 }
14749 }
14750 }
14751
14752 if (!Subtarget->isThumb1Only()) {
14753 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14754 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14755 return Result;
14756 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14757 return Result;
14758 }
14759
14760 SDValue N0 = N->getOperand(0);
14761 SDValue N1 = N->getOperand(1);
14762
14763 // (or (and X, C1), (srl Y, C2)) -> VSRI X, Y, #C2
14764 // (or (and X, C1), (shl Y, C2)) -> VSLI X, Y, #C2
14765 if (VT.isVector() &&
14766 ((Subtarget->hasNEON() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) ||
14767 (Subtarget->hasMVEIntegerOps() &&
14768 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32)))) {
14769 if (SDValue ShiftInsert =
14770 PerformORCombineToShiftInsert(DAG, N0, N1, VT, dl))
14771 return ShiftInsert;
14772
14773 if (SDValue ShiftInsert =
14774 PerformORCombineToShiftInsert(DAG, N1, N0, VT, dl))
14775 return ShiftInsert;
14776 }
14777
14778 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14779 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14781
14782 // The code below optimizes (or (and X, Y), Z).
14783 // The AND operand needs to have a single user to make these optimizations
14784 // profitable.
14785 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14786 return SDValue();
14787
14788 APInt SplatUndef;
14789 unsigned SplatBitSize;
14790 bool HasAnyUndefs;
14791
14792 APInt SplatBits0, SplatBits1;
14795 // Ensure that the second operand of both ands are constants
14796 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14797 HasAnyUndefs) && !HasAnyUndefs) {
14798 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14799 HasAnyUndefs) && !HasAnyUndefs) {
14800 // Ensure that the bit width of the constants are the same and that
14801 // the splat arguments are logical inverses as per the pattern we
14802 // are trying to simplify.
14803 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14804 SplatBits0 == ~SplatBits1) {
14805 // Canonicalize the vector type to make instruction selection
14806 // simpler.
14807 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14808 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14809 N0->getOperand(1),
14810 N0->getOperand(0),
14811 N1->getOperand(0));
14812 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Result);
14813 }
14814 }
14815 }
14816 }
14817
14818 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14819 // reasonable.
14820 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14821 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14822 return Res;
14823 }
14824
14825 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14826 return Result;
14827
14828 // (or x, (csinc 0, 0, cc)) -> (csinc x, 0, cc)
14829 // providing that the x is 0 or 1.
14830 SDValue CSINC = N1;
14831 SDValue Other = N0;
14832 if (CSINC.getOpcode() != ARMISD::CSINC)
14833 std::swap(CSINC, Other);
14834 if (CSINC.getOpcode() == ARMISD::CSINC &&
14835 isNullConstant(CSINC.getOperand(0)) &&
14836 isNullConstant(CSINC.getOperand(1)) &&
14838 return DAG.getNode(ARMISD::CSINC, dl, VT, Other, CSINC.getOperand(1),
14839 CSINC.getOperand(2), CSINC.getOperand(3));
14840
14841 return SDValue();
14842}
14843
14846 const ARMSubtarget *Subtarget) {
14847 EVT VT = N->getValueType(0);
14848 SelectionDAG &DAG = DCI.DAG;
14849
14850 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14851 return SDValue();
14852
14853 if (!Subtarget->isThumb1Only()) {
14854 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14855 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14856 return Result;
14857
14858 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14859 return Result;
14860 }
14861
14862 if (Subtarget->hasMVEIntegerOps()) {
14863 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14864 SDValue N0 = N->getOperand(0);
14865 SDValue N1 = N->getOperand(1);
14866 const TargetLowering *TLI = Subtarget->getTargetLowering();
14867 if (TLI->isConstTrueVal(N1) &&
14868 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14869 if (CanInvertMVEVCMP(N0)) {
14870 SDLoc DL(N0);
14872
14874 Ops.push_back(N0->getOperand(0));
14875 if (N0->getOpcode() == ARMISD::VCMP)
14876 Ops.push_back(N0->getOperand(1));
14877 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14878 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14879 }
14880 }
14881 }
14882
14883 return SDValue();
14884}
14885
14886// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14887// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14888// their position in "to" (Rd).
14889static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14890 assert(N->getOpcode() == ARMISD::BFI);
14891
14892 SDValue From = N->getOperand(1);
14893 ToMask = ~N->getConstantOperandAPInt(2);
14894 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.popcount());
14895
14896 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14897 // #C in the base of the SHR.
14898 if (From->getOpcode() == ISD::SRL &&
14899 isa<ConstantSDNode>(From->getOperand(1))) {
14900 APInt Shift = From->getConstantOperandAPInt(1);
14901 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14902 FromMask <<= Shift.getLimitedValue(31);
14903 From = From->getOperand(0);
14904 }
14905
14906 return From;
14907}
14908
14909// If A and B contain one contiguous set of bits, does A | B == A . B?
14910//
14911// Neither A nor B must be zero.
14912static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14913 unsigned LastActiveBitInA = A.countr_zero();
14914 unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14915 return LastActiveBitInA - 1 == FirstActiveBitInB;
14916}
14917
14919 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14920 APInt ToMask, FromMask;
14921 SDValue From = ParseBFI(N, ToMask, FromMask);
14922 SDValue To = N->getOperand(0);
14923
14924 SDValue V = To;
14925 if (V.getOpcode() != ARMISD::BFI)
14926 return SDValue();
14927
14928 APInt NewToMask, NewFromMask;
14929 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14930 if (NewFrom != From)
14931 return SDValue();
14932
14933 // Do the written bits conflict with any we've seen so far?
14934 if ((NewToMask & ToMask).getBoolValue())
14935 // Conflicting bits.
14936 return SDValue();
14937
14938 // Are the new bits contiguous when combined with the old bits?
14939 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14940 BitsProperlyConcatenate(FromMask, NewFromMask))
14941 return V;
14942 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14943 BitsProperlyConcatenate(NewFromMask, FromMask))
14944 return V;
14945
14946 return SDValue();
14947}
14948
14950 SDValue N0 = N->getOperand(0);
14951 SDValue N1 = N->getOperand(1);
14952
14953 if (N1.getOpcode() == ISD::AND) {
14954 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14955 // the bits being cleared by the AND are not demanded by the BFI.
14957 if (!N11C)
14958 return SDValue();
14959 unsigned InvMask = N->getConstantOperandVal(2);
14960 unsigned LSB = llvm::countr_zero(~InvMask);
14961 unsigned Width = llvm::bit_width<unsigned>(~InvMask) - LSB;
14962 assert(Width <
14963 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14964 "undefined behavior");
14965 unsigned Mask = (1u << Width) - 1;
14966 unsigned Mask2 = N11C->getZExtValue();
14967 if ((Mask & (~Mask2)) == 0)
14968 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14969 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14970 return SDValue();
14971 }
14972
14973 // Look for another BFI to combine with.
14974 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14975 // We've found a BFI.
14976 APInt ToMask1, FromMask1;
14977 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14978
14979 APInt ToMask2, FromMask2;
14980 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14981 assert(From1 == From2);
14982 (void)From2;
14983
14984 // Create a new BFI, combining the two together.
14985 APInt NewFromMask = FromMask1 | FromMask2;
14986 APInt NewToMask = ToMask1 | ToMask2;
14987
14988 EVT VT = N->getValueType(0);
14989 SDLoc dl(N);
14990
14991 if (NewFromMask[0] == 0)
14992 From1 = DAG.getNode(ISD::SRL, dl, VT, From1,
14993 DAG.getConstant(NewFromMask.countr_zero(), dl, VT));
14994 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14995 DAG.getConstant(~NewToMask, dl, VT));
14996 }
14997
14998 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14999 // that lower bit insertions are performed first, providing that M1 and M2
15000 // do no overlap. This can allow multiple BFI instructions to be combined
15001 // together by the other folds above.
15002 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
15003 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
15004 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
15005
15006 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
15007 ToMask1.countl_zero() < ToMask2.countl_zero())
15008 return SDValue();
15009
15010 EVT VT = N->getValueType(0);
15011 SDLoc dl(N);
15012 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
15013 N->getOperand(1), N->getOperand(2));
15014 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
15015 N0.getOperand(2));
15016 }
15017
15018 return SDValue();
15019}
15020
15021// Check that N is CMPZ(CSINC(0, 0, CC, X)),
15022// or CMPZ(CMOV(1, 0, CC, X))
15023// return X if valid.
15025 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
15026 return SDValue();
15027 SDValue CSInc = Cmp->getOperand(0);
15028
15029 // Ignore any `And 1` nodes that may not yet have been removed. We are
15030 // looking for a value that produces 1/0, so these have no effect on the
15031 // code.
15032 while (CSInc.getOpcode() == ISD::AND &&
15033 isa<ConstantSDNode>(CSInc.getOperand(1)) &&
15034 CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
15035 CSInc = CSInc.getOperand(0);
15036
15037 if (CSInc.getOpcode() == ARMISD::CSINC &&
15038 isNullConstant(CSInc.getOperand(0)) &&
15039 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15041 return CSInc.getOperand(3);
15042 }
15043 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
15044 isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15046 return CSInc.getOperand(3);
15047 }
15048 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
15049 isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
15052 return CSInc.getOperand(3);
15053 }
15054 return SDValue();
15055}
15056
15058 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15059 // t92: flags = ARMISD::CMPZ t74, 0
15060 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15061 // t96: flags = ARMISD::CMPZ t93, 0
15062 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15064 if (SDValue C = IsCMPZCSINC(N, Cond))
15065 if (Cond == ARMCC::EQ)
15066 return C;
15067 return SDValue();
15068}
15069
15071 // Fold away an unnecessary CMPZ/CSINC
15072 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15073 // if C1==EQ -> CSXYZ A, B, C2, D
15074 // if C1==NE -> CSXYZ A, B, NOT(C2), D
15076 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
15077 if (N->getConstantOperandVal(2) == ARMCC::EQ)
15078 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15079 N->getOperand(1),
15080 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
15081 if (N->getConstantOperandVal(2) == ARMCC::NE)
15082 return DAG.getNode(
15083 N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15084 N->getOperand(1),
15086 }
15087 return SDValue();
15088}
15089
15090/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15091/// ARMISD::VMOVRRD.
15094 const ARMSubtarget *Subtarget) {
15095 // vmovrrd(vmovdrr x, y) -> x,y
15096 SDValue InDouble = N->getOperand(0);
15097 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15098 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
15099
15100 // vmovrrd(load f64) -> (load i32), (load i32)
15101 SDNode *InNode = InDouble.getNode();
15102 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
15103 InNode->getValueType(0) == MVT::f64 &&
15104 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
15105 !cast<LoadSDNode>(InNode)->isVolatile()) {
15106 // TODO: Should this be done for non-FrameIndex operands?
15107 LoadSDNode *LD = cast<LoadSDNode>(InNode);
15108
15109 SelectionDAG &DAG = DCI.DAG;
15110 SDLoc DL(LD);
15111 SDValue BasePtr = LD->getBasePtr();
15112 SDValue NewLD1 =
15113 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
15114 LD->getAlign(), LD->getMemOperand()->getFlags());
15115
15116 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
15117 DAG.getConstant(4, DL, MVT::i32));
15118
15119 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
15120 LD->getPointerInfo().getWithOffset(4),
15121 commonAlignment(LD->getAlign(), 4),
15122 LD->getMemOperand()->getFlags());
15123
15124 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
15125 if (DCI.DAG.getDataLayout().isBigEndian())
15126 std::swap (NewLD1, NewLD2);
15127 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
15128 return Result;
15129 }
15130
15131 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15132 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15133 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15134 isa<ConstantSDNode>(InDouble.getOperand(1))) {
15135 SDValue BV = InDouble.getOperand(0);
15136 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15137 // change lane order under big endian.
15138 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15139 while (
15140 (BV.getOpcode() == ISD::BITCAST ||
15141 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15142 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15143 BVSwap = BV.getOpcode() == ISD::BITCAST;
15144 BV = BV.getOperand(0);
15145 }
15146 if (BV.getValueType() != MVT::v4i32)
15147 return SDValue();
15148
15149 // Handle buildvectors, pulling out the correct lane depending on
15150 // endianness.
15151 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
15152 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15153 SDValue Op0 = BV.getOperand(Offset);
15154 SDValue Op1 = BV.getOperand(Offset + 1);
15155 if (!Subtarget->isLittle() && BVSwap)
15156 std::swap(Op0, Op1);
15157
15158 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15159 }
15160
15161 // A chain of insert_vectors, grabbing the correct value of the chain of
15162 // inserts.
15163 SDValue Op0, Op1;
15164 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15165 if (isa<ConstantSDNode>(BV.getOperand(2))) {
15166 if (BV.getConstantOperandVal(2) == Offset && !Op0)
15167 Op0 = BV.getOperand(1);
15168 if (BV.getConstantOperandVal(2) == Offset + 1 && !Op1)
15169 Op1 = BV.getOperand(1);
15170 }
15171 BV = BV.getOperand(0);
15172 }
15173 if (!Subtarget->isLittle() && BVSwap)
15174 std::swap(Op0, Op1);
15175 if (Op0 && Op1)
15176 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15177 }
15178
15179 return SDValue();
15180}
15181
15182/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15183/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
15185 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15186 SDValue Op0 = N->getOperand(0);
15187 SDValue Op1 = N->getOperand(1);
15188 if (Op0.getOpcode() == ISD::BITCAST)
15189 Op0 = Op0.getOperand(0);
15190 if (Op1.getOpcode() == ISD::BITCAST)
15191 Op1 = Op1.getOperand(0);
15192 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15193 Op0.getNode() == Op1.getNode() &&
15194 Op0.getResNo() == 0 && Op1.getResNo() == 1)
15195 return DAG.getNode(ISD::BITCAST, SDLoc(N),
15196 N->getValueType(0), Op0.getOperand(0));
15197 return SDValue();
15198}
15199
15202 SDValue Op0 = N->getOperand(0);
15203
15204 // VMOVhr (VMOVrh (X)) -> X
15205 if (Op0->getOpcode() == ARMISD::VMOVrh)
15206 return Op0->getOperand(0);
15207
15208 // FullFP16: half values are passed in S-registers, and we don't
15209 // need any of the bitcast and moves:
15210 //
15211 // t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15212 // t5: i32 = bitcast t2
15213 // t18: f16 = ARMISD::VMOVhr t5
15214 // =>
15215 // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15216 if (Op0->getOpcode() == ISD::BITCAST) {
15217 SDValue Copy = Op0->getOperand(0);
15218 if (Copy.getValueType() == MVT::f32 &&
15219 Copy->getOpcode() == ISD::CopyFromReg) {
15220 bool HasGlue = Copy->getNumOperands() == 3;
15221 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1),
15222 HasGlue ? Copy->getOperand(2) : SDValue()};
15223 EVT OutTys[] = {N->getValueType(0), MVT::Other, MVT::Glue};
15224 SDValue NewCopy =
15226 DCI.DAG.getVTList(ArrayRef(OutTys, HasGlue ? 3 : 2)),
15227 ArrayRef(Ops, HasGlue ? 3 : 2));
15228
15229 // Update Users, Chains, and Potential Glue.
15230 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), NewCopy.getValue(0));
15231 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(1), NewCopy.getValue(1));
15232 if (HasGlue)
15233 DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(2),
15234 NewCopy.getValue(2));
15235
15236 return NewCopy;
15237 }
15238 }
15239
15240 // fold (VMOVhr (load x)) -> (load (f16*)x)
15241 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
15242 if (LN0->hasOneUse() && LN0->isUnindexed() &&
15243 LN0->getMemoryVT() == MVT::i16) {
15244 SDValue Load =
15245 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
15246 LN0->getBasePtr(), LN0->getMemOperand());
15247 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15248 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
15249 return Load;
15250 }
15251 }
15252
15253 // Only the bottom 16 bits of the source register are used.
15254 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15255 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15256 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
15257 return SDValue(N, 0);
15258
15259 return SDValue();
15260}
15261
15263 SDValue N0 = N->getOperand(0);
15264 EVT VT = N->getValueType(0);
15265
15266 // fold (VMOVrh (fpconst x)) -> const x
15268 APFloat V = C->getValueAPF();
15269 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
15270 }
15271
15272 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15273 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
15274 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15275
15276 SDValue Load =
15277 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
15278 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
15279 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15280 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
15281 return Load;
15282 }
15283
15284 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15285 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15287 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
15288 N0->getOperand(1));
15289
15290 return SDValue();
15291}
15292
15293/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15294/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15295/// i64 vector to have f64 elements, since the value can then be loaded
15296/// directly into a VFP register.
15298 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15299 for (unsigned i = 0; i < NumElts; ++i) {
15300 SDNode *Elt = N->getOperand(i).getNode();
15301 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15302 return true;
15303 }
15304 return false;
15305}
15306
15307/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15308/// ISD::BUILD_VECTOR.
15311 const ARMSubtarget *Subtarget) {
15312 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15313 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15314 // into a pair of GPRs, which is fine when the value is used as a scalar,
15315 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15316 SelectionDAG &DAG = DCI.DAG;
15317 if (N->getNumOperands() == 2)
15318 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15319 return RV;
15320
15321 // Load i64 elements as f64 values so that type legalization does not split
15322 // them up into i32 values.
15323 EVT VT = N->getValueType(0);
15324 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15325 return SDValue();
15326 SDLoc dl(N);
15328 unsigned NumElts = VT.getVectorNumElements();
15329 for (unsigned i = 0; i < NumElts; ++i) {
15330 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15331 Ops.push_back(V);
15332 // Make the DAGCombiner fold the bitcast.
15333 DCI.AddToWorklist(V.getNode());
15334 }
15335 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15336 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15337 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15338}
15339
15340/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15341static SDValue
15343 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15344 // At that time, we may have inserted bitcasts from integer to float.
15345 // If these bitcasts have survived DAGCombine, change the lowering of this
15346 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15347 // force to use floating point types.
15348
15349 // Make sure we can change the type of the vector.
15350 // This is possible iff:
15351 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15352 // 1.1. Vector is used only once.
15353 // 1.2. Use is a bit convert to an integer type.
15354 // 2. The size of its operands are 32-bits (64-bits are not legal).
15355 EVT VT = N->getValueType(0);
15356 EVT EltVT = VT.getVectorElementType();
15357
15358 // Check 1.1. and 2.
15359 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15360 return SDValue();
15361
15362 // By construction, the input type must be float.
15363 assert(EltVT == MVT::f32 && "Unexpected type!");
15364
15365 // Check 1.2.
15366 SDNode *Use = *N->user_begin();
15367 if (Use->getOpcode() != ISD::BITCAST ||
15368 Use->getValueType(0).isFloatingPoint())
15369 return SDValue();
15370
15371 // Check profitability.
15372 // Model is, if more than half of the relevant operands are bitcast from
15373 // i32, turn the build_vector into a sequence of insert_vector_elt.
15374 // Relevant operands are everything that is not statically
15375 // (i.e., at compile time) bitcasted.
15376 unsigned NumOfBitCastedElts = 0;
15377 unsigned NumElts = VT.getVectorNumElements();
15378 unsigned NumOfRelevantElts = NumElts;
15379 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15380 SDValue Elt = N->getOperand(Idx);
15381 if (Elt->getOpcode() == ISD::BITCAST) {
15382 // Assume only bit cast to i32 will go away.
15383 if (Elt->getOperand(0).getValueType() == MVT::i32)
15384 ++NumOfBitCastedElts;
15385 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15386 // Constants are statically casted, thus do not count them as
15387 // relevant operands.
15388 --NumOfRelevantElts;
15389 }
15390
15391 // Check if more than half of the elements require a non-free bitcast.
15392 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15393 return SDValue();
15394
15395 SelectionDAG &DAG = DCI.DAG;
15396 // Create the new vector type.
15397 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15398 // Check if the type is legal.
15399 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15400 if (!TLI.isTypeLegal(VecVT))
15401 return SDValue();
15402
15403 // Combine:
15404 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15405 // => BITCAST INSERT_VECTOR_ELT
15406 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15407 // (BITCAST EN), N.
15408 SDValue Vec = DAG.getUNDEF(VecVT);
15409 SDLoc dl(N);
15410 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15411 SDValue V = N->getOperand(Idx);
15412 if (V.isUndef())
15413 continue;
15414 if (V.getOpcode() == ISD::BITCAST &&
15415 V->getOperand(0).getValueType() == MVT::i32)
15416 // Fold obvious case.
15417 V = V.getOperand(0);
15418 else {
15419 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15420 // Make the DAGCombiner fold the bitcasts.
15421 DCI.AddToWorklist(V.getNode());
15422 }
15423 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15424 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15425 }
15426 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15427 // Make the DAGCombiner fold the bitcasts.
15428 DCI.AddToWorklist(Vec.getNode());
15429 return Vec;
15430}
15431
15432static SDValue
15434 EVT VT = N->getValueType(0);
15435 SDValue Op = N->getOperand(0);
15436 SDLoc dl(N);
15437
15438 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15439 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15440 // If the valuetypes are the same, we can remove the cast entirely.
15441 if (Op->getOperand(0).getValueType() == VT)
15442 return Op->getOperand(0);
15443 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15444 }
15445
15446 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15447 // more VPNOT which might get folded as else predicates.
15448 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15449 SDValue X =
15450 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15451 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15452 DCI.DAG.getConstant(65535, dl, MVT::i32));
15453 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15454 }
15455
15456 // Only the bottom 16 bits of the source register are used.
15457 if (Op.getValueType() == MVT::i32) {
15458 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15459 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15460 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15461 return SDValue(N, 0);
15462 }
15463 return SDValue();
15464}
15465
15467 const ARMSubtarget *ST) {
15468 EVT VT = N->getValueType(0);
15469 SDValue Op = N->getOperand(0);
15470 SDLoc dl(N);
15471
15472 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15473 if (ST->isLittle())
15474 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15475
15476 // VT VECTOR_REG_CAST (VT Op) -> Op
15477 if (Op.getValueType() == VT)
15478 return Op;
15479 // VECTOR_REG_CAST undef -> undef
15480 if (Op.isUndef())
15481 return DAG.getUNDEF(VT);
15482
15483 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15484 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15485 // If the valuetypes are the same, we can remove the cast entirely.
15486 if (Op->getOperand(0).getValueType() == VT)
15487 return Op->getOperand(0);
15488 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15489 }
15490
15491 return SDValue();
15492}
15493
15495 const ARMSubtarget *Subtarget) {
15496 if (!Subtarget->hasMVEIntegerOps())
15497 return SDValue();
15498
15499 EVT VT = N->getValueType(0);
15500 SDValue Op0 = N->getOperand(0);
15501 SDValue Op1 = N->getOperand(1);
15502 ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(2);
15503 SDLoc dl(N);
15504
15505 // vcmp X, 0, cc -> vcmpz X, cc
15506 if (isZeroVector(Op1))
15507 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15508
15509 unsigned SwappedCond = getSwappedCondition(Cond);
15510 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15511 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15512 if (isZeroVector(Op0))
15513 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15514 DAG.getConstant(SwappedCond, dl, MVT::i32));
15515 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15516 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15517 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15518 DAG.getConstant(SwappedCond, dl, MVT::i32));
15519 }
15520
15521 return SDValue();
15522}
15523
15524/// PerformInsertEltCombine - Target-specific dag combine xforms for
15525/// ISD::INSERT_VECTOR_ELT.
15528 // Bitcast an i64 load inserted into a vector to f64.
15529 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15530 EVT VT = N->getValueType(0);
15531 SDNode *Elt = N->getOperand(1).getNode();
15532 if (VT.getVectorElementType() != MVT::i64 ||
15533 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15534 return SDValue();
15535
15536 SelectionDAG &DAG = DCI.DAG;
15537 SDLoc dl(N);
15538 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15540 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15541 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15542 // Make the DAGCombiner fold the bitcasts.
15543 DCI.AddToWorklist(Vec.getNode());
15544 DCI.AddToWorklist(V.getNode());
15545 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15546 Vec, V, N->getOperand(2));
15547 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15548}
15549
15550// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15551// directly or bitcast to an integer if the original is a float vector.
15552// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15553// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15554static SDValue
15556 EVT VT = N->getValueType(0);
15557 SDLoc dl(N);
15558
15559 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15560 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15561 return SDValue();
15562
15563 SDValue Ext = SDValue(N, 0);
15564 if (Ext.getOpcode() == ISD::BITCAST &&
15565 Ext.getOperand(0).getValueType() == MVT::f32)
15566 Ext = Ext.getOperand(0);
15567 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15569 Ext.getConstantOperandVal(1) % 2 != 0)
15570 return SDValue();
15571 if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15572 Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15573 return SDValue();
15574
15575 SDValue Op0 = Ext.getOperand(0);
15576 EVT VecVT = Op0.getValueType();
15577 unsigned ResNo = Op0.getResNo();
15578 unsigned Lane = Ext.getConstantOperandVal(1);
15579 if (VecVT.getVectorNumElements() != 4)
15580 return SDValue();
15581
15582 // Find another extract, of Lane + 1
15583 auto OtherIt = find_if(Op0->users(), [&](SDNode *V) {
15584 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15585 isa<ConstantSDNode>(V->getOperand(1)) &&
15586 V->getConstantOperandVal(1) == Lane + 1 &&
15587 V->getOperand(0).getResNo() == ResNo;
15588 });
15589 if (OtherIt == Op0->users().end())
15590 return SDValue();
15591
15592 // For float extracts, we need to be converting to a i32 for both vector
15593 // lanes.
15594 SDValue OtherExt(*OtherIt, 0);
15595 if (OtherExt.getValueType() != MVT::i32) {
15596 if (!OtherExt->hasOneUse() ||
15597 OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15598 OtherExt->user_begin()->getValueType(0) != MVT::i32)
15599 return SDValue();
15600 OtherExt = SDValue(*OtherExt->user_begin(), 0);
15601 }
15602
15603 // Convert the type to a f64 and extract with a VMOVRRD.
15604 SDValue F64 = DCI.DAG.getNode(
15605 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15606 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15607 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15608 SDValue VMOVRRD =
15609 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15610
15611 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15612 return VMOVRRD;
15613}
15614
15617 const ARMSubtarget *ST) {
15618 SDValue Op0 = N->getOperand(0);
15619 EVT VT = N->getValueType(0);
15620 SDLoc dl(N);
15621
15622 // extract (vdup x) -> x
15623 if (Op0->getOpcode() == ARMISD::VDUP) {
15624 SDValue X = Op0->getOperand(0);
15625 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15626 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15627 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15628 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15629 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15630 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15631
15632 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15633 X = X->getOperand(0);
15634 if (X.getValueType() == VT)
15635 return X;
15636 }
15637
15638 // extract ARM_BUILD_VECTOR -> x
15639 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15640 isa<ConstantSDNode>(N->getOperand(1)) &&
15641 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15642 return Op0.getOperand(N->getConstantOperandVal(1));
15643 }
15644
15645 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15646 if (Op0.getValueType() == MVT::v4i32 &&
15647 isa<ConstantSDNode>(N->getOperand(1)) &&
15648 Op0.getOpcode() == ISD::BITCAST &&
15650 Op0.getOperand(0).getValueType() == MVT::v2f64) {
15651 SDValue BV = Op0.getOperand(0);
15652 unsigned Offset = N->getConstantOperandVal(1);
15653 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15654 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15655 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15656 }
15657
15658 // extract x, n; extract x, n+1 -> VMOVRRD x
15659 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15660 return R;
15661
15662 // extract (MVETrunc(x)) -> extract x
15663 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15664 unsigned Idx = N->getConstantOperandVal(1);
15665 unsigned Vec =
15667 unsigned SubIdx =
15669 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15670 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15671 }
15672
15673 // extract(bitcast(BUILD_VECTOR(extract(bitcast(a)), ..))) -> extract(a)
15674 if (ST->isLittle() && Op0.getOpcode() == ISD::BITCAST &&
15676 isa<ConstantSDNode>(N->getOperand(1)) &&
15679 unsigned Lane = N->getConstantOperandVal(1);
15680 EVT ExtVT = Op0.getValueType();
15681 EVT BVVT = Op0.getOperand(0).getValueType();
15682 unsigned BVLane =
15683 (Lane * BVVT.getVectorNumElements()) / ExtVT.getVectorNumElements();
15684 assert(BVLane < Op0.getOperand(0).getNumOperands());
15685 SDValue Ext = Op0.getOperand(0).getOperand(BVLane);
15686 if (Ext.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15687 Ext.getOperand(0).getOpcode() == ISD::BITCAST &&
15689 Ext.getOperand(0).getOperand(0).getValueType() == ExtVT) {
15690 unsigned InnerLane = Ext.getConstantOperandVal(1);
15691 unsigned BVSubLane = Lane - (BVLane * ExtVT.getVectorNumElements()) /
15692 BVVT.getVectorNumElements();
15693 unsigned FinalLane = (InnerLane * ExtVT.getVectorNumElements()) /
15694 BVVT.getVectorNumElements() +
15695 BVSubLane;
15696 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT,
15697 Ext.getOperand(0).getOperand(0),
15698 DCI.DAG.getConstant(FinalLane, dl, MVT::i32));
15699 }
15700 }
15701
15702 return SDValue();
15703}
15704
15706 SDValue Op = N->getOperand(0);
15707 EVT VT = N->getValueType(0);
15708
15709 // sext_inreg(VGETLANEu) -> VGETLANEs
15710 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15711 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15712 Op.getOperand(0).getValueType().getScalarType())
15713 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15714 Op.getOperand(1));
15715
15716 return SDValue();
15717}
15718
15719static SDValue
15721 SDValue Vec = N->getOperand(0);
15722 SDValue SubVec = N->getOperand(1);
15723 uint64_t IdxVal = N->getConstantOperandVal(2);
15724 EVT VecVT = Vec.getValueType();
15725 EVT SubVT = SubVec.getValueType();
15726
15727 // Only do this for legal fixed vector types.
15728 if (!VecVT.isFixedLengthVector() ||
15729 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15731 return SDValue();
15732
15733 // Ignore widening patterns.
15734 if (IdxVal == 0 && Vec.isUndef())
15735 return SDValue();
15736
15737 // Subvector must be half the width and an "aligned" insertion.
15738 unsigned NumSubElts = SubVT.getVectorNumElements();
15739 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15740 (IdxVal != 0 && IdxVal != NumSubElts))
15741 return SDValue();
15742
15743 // Fold insert_subvector -> concat_vectors
15744 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15745 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15746 SDLoc DL(N);
15747 SDValue Lo, Hi;
15748 if (IdxVal == 0) {
15749 Lo = SubVec;
15750 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15751 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15752 } else {
15753 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15754 DCI.DAG.getVectorIdxConstant(0, DL));
15755 Hi = SubVec;
15756 }
15757 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15758}
15759
15760// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15762 SelectionDAG &DAG) {
15763 SDValue Trunc = N->getOperand(0);
15764 EVT VT = Trunc.getValueType();
15765 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15766 return SDValue();
15767
15768 SDLoc DL(Trunc);
15769 if (isVMOVNTruncMask(N->getMask(), VT, false))
15770 return DAG.getNode(
15771 ARMISD::VMOVN, DL, VT,
15772 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15773 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15774 DAG.getConstant(1, DL, MVT::i32));
15775 else if (isVMOVNTruncMask(N->getMask(), VT, true))
15776 return DAG.getNode(
15777 ARMISD::VMOVN, DL, VT,
15778 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15779 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15780 DAG.getConstant(1, DL, MVT::i32));
15781 return SDValue();
15782}
15783
15784/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15785/// ISD::VECTOR_SHUFFLE.
15788 return R;
15789
15790 // The LLVM shufflevector instruction does not require the shuffle mask
15791 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15792 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15793 // operands do not match the mask length, they are extended by concatenating
15794 // them with undef vectors. That is probably the right thing for other
15795 // targets, but for NEON it is better to concatenate two double-register
15796 // size vector operands into a single quad-register size vector. Do that
15797 // transformation here:
15798 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15799 // shuffle(concat(v1, v2), undef)
15800 SDValue Op0 = N->getOperand(0);
15801 SDValue Op1 = N->getOperand(1);
15802 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15803 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15804 Op0.getNumOperands() != 2 ||
15805 Op1.getNumOperands() != 2)
15806 return SDValue();
15807 SDValue Concat0Op1 = Op0.getOperand(1);
15808 SDValue Concat1Op1 = Op1.getOperand(1);
15809 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15810 return SDValue();
15811 // Skip the transformation if any of the types are illegal.
15812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15813 EVT VT = N->getValueType(0);
15814 if (!TLI.isTypeLegal(VT) ||
15815 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15816 !TLI.isTypeLegal(Concat1Op1.getValueType()))
15817 return SDValue();
15818
15819 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15820 Op0.getOperand(0), Op1.getOperand(0));
15821 // Translate the shuffle mask.
15822 SmallVector<int, 16> NewMask;
15823 unsigned NumElts = VT.getVectorNumElements();
15824 unsigned HalfElts = NumElts/2;
15826 for (unsigned n = 0; n < NumElts; ++n) {
15827 int MaskElt = SVN->getMaskElt(n);
15828 int NewElt = -1;
15829 if (MaskElt < (int)HalfElts)
15830 NewElt = MaskElt;
15831 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15832 NewElt = HalfElts + MaskElt - NumElts;
15833 NewMask.push_back(NewElt);
15834 }
15835 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15836 DAG.getUNDEF(VT), NewMask);
15837}
15838
15839/// Load/store instruction that can be merged with a base address
15840/// update
15845 unsigned AddrOpIdx;
15846};
15847
15849 /// Instruction that updates a pointer
15851 /// Pointer increment operand
15853 /// Pointer increment value if it is a constant, or 0 otherwise
15854 unsigned ConstInc;
15855};
15856
15858 // Check that the add is independent of the load/store.
15859 // Otherwise, folding it would create a cycle. Search through Addr
15860 // as well, since the User may not be a direct user of Addr and
15861 // only share a base pointer.
15864 Worklist.push_back(N);
15865 Worklist.push_back(User);
15866 const unsigned MaxSteps = 1024;
15867 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
15868 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
15869 return false;
15870 return true;
15871}
15872
15874 struct BaseUpdateUser &User,
15875 bool SimpleConstIncOnly,
15877 SelectionDAG &DAG = DCI.DAG;
15878 SDNode *N = Target.N;
15879 MemSDNode *MemN = cast<MemSDNode>(N);
15880 SDLoc dl(N);
15881
15882 // Find the new opcode for the updating load/store.
15883 bool isLoadOp = true;
15884 bool isLaneOp = false;
15885 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15886 // as an operand.
15887 bool hasAlignment = true;
15888 unsigned NewOpc = 0;
15889 unsigned NumVecs = 0;
15890 if (Target.isIntrinsic) {
15891 unsigned IntNo = N->getConstantOperandVal(1);
15892 switch (IntNo) {
15893 default:
15894 llvm_unreachable("unexpected intrinsic for Neon base update");
15895 case Intrinsic::arm_neon_vld1:
15896 NewOpc = ARMISD::VLD1_UPD;
15897 NumVecs = 1;
15898 break;
15899 case Intrinsic::arm_neon_vld2:
15900 NewOpc = ARMISD::VLD2_UPD;
15901 NumVecs = 2;
15902 break;
15903 case Intrinsic::arm_neon_vld3:
15904 NewOpc = ARMISD::VLD3_UPD;
15905 NumVecs = 3;
15906 break;
15907 case Intrinsic::arm_neon_vld4:
15908 NewOpc = ARMISD::VLD4_UPD;
15909 NumVecs = 4;
15910 break;
15911 case Intrinsic::arm_neon_vld1x2:
15912 NewOpc = ARMISD::VLD1x2_UPD;
15913 NumVecs = 2;
15914 hasAlignment = false;
15915 break;
15916 case Intrinsic::arm_neon_vld1x3:
15917 NewOpc = ARMISD::VLD1x3_UPD;
15918 NumVecs = 3;
15919 hasAlignment = false;
15920 break;
15921 case Intrinsic::arm_neon_vld1x4:
15922 NewOpc = ARMISD::VLD1x4_UPD;
15923 NumVecs = 4;
15924 hasAlignment = false;
15925 break;
15926 case Intrinsic::arm_neon_vld2dup:
15927 NewOpc = ARMISD::VLD2DUP_UPD;
15928 NumVecs = 2;
15929 break;
15930 case Intrinsic::arm_neon_vld3dup:
15931 NewOpc = ARMISD::VLD3DUP_UPD;
15932 NumVecs = 3;
15933 break;
15934 case Intrinsic::arm_neon_vld4dup:
15935 NewOpc = ARMISD::VLD4DUP_UPD;
15936 NumVecs = 4;
15937 break;
15938 case Intrinsic::arm_neon_vld2lane:
15939 NewOpc = ARMISD::VLD2LN_UPD;
15940 NumVecs = 2;
15941 isLaneOp = true;
15942 break;
15943 case Intrinsic::arm_neon_vld3lane:
15944 NewOpc = ARMISD::VLD3LN_UPD;
15945 NumVecs = 3;
15946 isLaneOp = true;
15947 break;
15948 case Intrinsic::arm_neon_vld4lane:
15949 NewOpc = ARMISD::VLD4LN_UPD;
15950 NumVecs = 4;
15951 isLaneOp = true;
15952 break;
15953 case Intrinsic::arm_neon_vst1:
15954 NewOpc = ARMISD::VST1_UPD;
15955 NumVecs = 1;
15956 isLoadOp = false;
15957 break;
15958 case Intrinsic::arm_neon_vst2:
15959 NewOpc = ARMISD::VST2_UPD;
15960 NumVecs = 2;
15961 isLoadOp = false;
15962 break;
15963 case Intrinsic::arm_neon_vst3:
15964 NewOpc = ARMISD::VST3_UPD;
15965 NumVecs = 3;
15966 isLoadOp = false;
15967 break;
15968 case Intrinsic::arm_neon_vst4:
15969 NewOpc = ARMISD::VST4_UPD;
15970 NumVecs = 4;
15971 isLoadOp = false;
15972 break;
15973 case Intrinsic::arm_neon_vst2lane:
15974 NewOpc = ARMISD::VST2LN_UPD;
15975 NumVecs = 2;
15976 isLoadOp = false;
15977 isLaneOp = true;
15978 break;
15979 case Intrinsic::arm_neon_vst3lane:
15980 NewOpc = ARMISD::VST3LN_UPD;
15981 NumVecs = 3;
15982 isLoadOp = false;
15983 isLaneOp = true;
15984 break;
15985 case Intrinsic::arm_neon_vst4lane:
15986 NewOpc = ARMISD::VST4LN_UPD;
15987 NumVecs = 4;
15988 isLoadOp = false;
15989 isLaneOp = true;
15990 break;
15991 case Intrinsic::arm_neon_vst1x2:
15992 NewOpc = ARMISD::VST1x2_UPD;
15993 NumVecs = 2;
15994 isLoadOp = false;
15995 hasAlignment = false;
15996 break;
15997 case Intrinsic::arm_neon_vst1x3:
15998 NewOpc = ARMISD::VST1x3_UPD;
15999 NumVecs = 3;
16000 isLoadOp = false;
16001 hasAlignment = false;
16002 break;
16003 case Intrinsic::arm_neon_vst1x4:
16004 NewOpc = ARMISD::VST1x4_UPD;
16005 NumVecs = 4;
16006 isLoadOp = false;
16007 hasAlignment = false;
16008 break;
16009 }
16010 } else {
16011 isLaneOp = true;
16012 switch (N->getOpcode()) {
16013 default:
16014 llvm_unreachable("unexpected opcode for Neon base update");
16015 case ARMISD::VLD1DUP:
16016 NewOpc = ARMISD::VLD1DUP_UPD;
16017 NumVecs = 1;
16018 break;
16019 case ARMISD::VLD2DUP:
16020 NewOpc = ARMISD::VLD2DUP_UPD;
16021 NumVecs = 2;
16022 break;
16023 case ARMISD::VLD3DUP:
16024 NewOpc = ARMISD::VLD3DUP_UPD;
16025 NumVecs = 3;
16026 break;
16027 case ARMISD::VLD4DUP:
16028 NewOpc = ARMISD::VLD4DUP_UPD;
16029 NumVecs = 4;
16030 break;
16031 case ISD::LOAD:
16032 NewOpc = ARMISD::VLD1_UPD;
16033 NumVecs = 1;
16034 isLaneOp = false;
16035 break;
16036 case ISD::STORE:
16037 NewOpc = ARMISD::VST1_UPD;
16038 NumVecs = 1;
16039 isLaneOp = false;
16040 isLoadOp = false;
16041 break;
16042 }
16043 }
16044
16045 // Find the size of memory referenced by the load/store.
16046 EVT VecTy;
16047 if (isLoadOp) {
16048 VecTy = N->getValueType(0);
16049 } else if (Target.isIntrinsic) {
16050 VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
16051 } else {
16052 assert(Target.isStore &&
16053 "Node has to be a load, a store, or an intrinsic!");
16054 VecTy = N->getOperand(1).getValueType();
16055 }
16056
16057 bool isVLDDUPOp =
16058 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
16059 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
16060
16061 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16062 if (isLaneOp || isVLDDUPOp)
16063 NumBytes /= VecTy.getVectorNumElements();
16064
16065 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
16066 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
16067 // separate instructions that make it harder to use a non-constant update.
16068 return false;
16069 }
16070
16071 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
16072 return false;
16073
16074 if (!isValidBaseUpdate(N, User.N))
16075 return false;
16076
16077 // OK, we found an ADD we can fold into the base update.
16078 // Now, create a _UPD node, taking care of not breaking alignment.
16079
16080 EVT AlignedVecTy = VecTy;
16081 Align Alignment = MemN->getAlign();
16082
16083 // If this is a less-than-standard-aligned load/store, change the type to
16084 // match the standard alignment.
16085 // The alignment is overlooked when selecting _UPD variants; and it's
16086 // easier to introduce bitcasts here than fix that.
16087 // There are 3 ways to get to this base-update combine:
16088 // - intrinsics: they are assumed to be properly aligned (to the standard
16089 // alignment of the memory type), so we don't need to do anything.
16090 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16091 // intrinsics, so, likewise, there's nothing to do.
16092 // - generic load/store instructions: the alignment is specified as an
16093 // explicit operand, rather than implicitly as the standard alignment
16094 // of the memory type (like the intrinsics). We need to change the
16095 // memory type to match the explicit alignment. That way, we don't
16096 // generate non-standard-aligned ARMISD::VLDx nodes.
16097 if (isa<LSBaseSDNode>(N)) {
16098 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16099 MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
16100 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16101 assert(!isLaneOp && "Unexpected generic load/store lane.");
16102 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16103 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
16104 }
16105 // Don't set an explicit alignment on regular load/stores that we want
16106 // to transform to VLD/VST 1_UPD nodes.
16107 // This matches the behavior of regular load/stores, which only get an
16108 // explicit alignment if the MMO alignment is larger than the standard
16109 // alignment of the memory type.
16110 // Intrinsics, however, always get an explicit alignment, set to the
16111 // alignment of the MMO.
16112 Alignment = Align(1);
16113 }
16114
16115 // Create the new updating load/store node.
16116 // First, create an SDVTList for the new updating node's results.
16117 EVT Tys[6];
16118 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16119 unsigned n;
16120 for (n = 0; n < NumResultVecs; ++n)
16121 Tys[n] = AlignedVecTy;
16122 Tys[n++] = MVT::i32;
16123 Tys[n] = MVT::Other;
16124 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16125
16126 // Then, gather the new node's operands.
16128 Ops.push_back(N->getOperand(0)); // incoming chain
16129 Ops.push_back(N->getOperand(Target.AddrOpIdx));
16130 Ops.push_back(User.Inc);
16131
16132 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
16133 // Try to match the intrinsic's signature
16134 Ops.push_back(StN->getValue());
16135 } else {
16136 // Loads (and of course intrinsics) match the intrinsics' signature,
16137 // so just add all but the alignment operand.
16138 unsigned LastOperand =
16139 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16140 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16141 Ops.push_back(N->getOperand(i));
16142 }
16143
16144 // For all node types, the alignment operand is always the last one.
16145 Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
16146
16147 // If this is a non-standard-aligned STORE, the penultimate operand is the
16148 // stored value. Bitcast it to the aligned type.
16149 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16150 SDValue &StVal = Ops[Ops.size() - 2];
16151 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
16152 }
16153
16154 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16155 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
16156 MemN->getMemOperand());
16157
16158 // Update the uses.
16159 SmallVector<SDValue, 5> NewResults;
16160 for (unsigned i = 0; i < NumResultVecs; ++i)
16161 NewResults.push_back(SDValue(UpdN.getNode(), i));
16162
16163 // If this is an non-standard-aligned LOAD, the first result is the loaded
16164 // value. Bitcast it to the expected result type.
16165 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16166 SDValue &LdVal = NewResults[0];
16167 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
16168 }
16169
16170 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16171 DCI.CombineTo(N, NewResults);
16172 DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
16173
16174 return true;
16175}
16176
16177// If (opcode ptr inc) is and ADD-like instruction, return the
16178// increment value. Otherwise return 0.
16179static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16180 SDValue Inc, const SelectionDAG &DAG) {
16182 if (!CInc)
16183 return 0;
16184
16185 switch (Opcode) {
16186 case ARMISD::VLD1_UPD:
16187 case ISD::ADD:
16188 return CInc->getZExtValue();
16189 case ISD::OR: {
16190 if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
16191 // (OR ptr inc) is the same as (ADD ptr inc)
16192 return CInc->getZExtValue();
16193 }
16194 return 0;
16195 }
16196 default:
16197 return 0;
16198 }
16199}
16200
16202 switch (N->getOpcode()) {
16203 case ISD::ADD:
16204 case ISD::OR: {
16205 if (isa<ConstantSDNode>(N->getOperand(1))) {
16206 *Ptr = N->getOperand(0);
16207 *CInc = N->getOperand(1);
16208 return true;
16209 }
16210 return false;
16211 }
16212 case ARMISD::VLD1_UPD: {
16213 if (isa<ConstantSDNode>(N->getOperand(2))) {
16214 *Ptr = N->getOperand(1);
16215 *CInc = N->getOperand(2);
16216 return true;
16217 }
16218 return false;
16219 }
16220 default:
16221 return false;
16222 }
16223}
16224
16225/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16226/// NEON load/store intrinsics, and generic vector load/stores, to merge
16227/// base address updates.
16228/// For generic load/stores, the memory type is assumed to be a vector.
16229/// The caller is assumed to have checked legality.
16232 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16233 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16234 const bool isStore = N->getOpcode() == ISD::STORE;
16235 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16236 BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
16237
16238 // Limit the number of possible base-updates we look at to prevent degenerate
16239 // cases.
16240 unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16241
16242 SDValue Addr = N->getOperand(AddrOpIdx);
16243
16245
16246 // Search for a use of the address operand that is an increment.
16247 for (SDUse &Use : Addr->uses()) {
16248 SDNode *User = Use.getUser();
16249 if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16250 continue;
16251
16252 SDValue Inc = User->getOperand(Use.getOperandNo() == 1 ? 0 : 1);
16253 unsigned ConstInc =
16254 getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
16255
16256 if (ConstInc || User->getOpcode() == ISD::ADD) {
16257 BaseUpdates.push_back({User, Inc, ConstInc});
16258 if (BaseUpdates.size() >= MaxBaseUpdates)
16259 break;
16260 }
16261 }
16262
16263 // If the address is a constant pointer increment itself, find
16264 // another constant increment that has the same base operand
16265 SDValue Base;
16266 SDValue CInc;
16267 if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
16268 unsigned Offset =
16269 getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
16270 if (Offset) {
16271 for (SDUse &Use : Base->uses()) {
16272
16273 SDNode *User = Use.getUser();
16274 if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16275 User->getNumOperands() != 2)
16276 continue;
16277
16278 SDValue UserInc = User->getOperand(Use.getOperandNo() == 0 ? 1 : 0);
16279 unsigned UserOffset =
16280 getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
16281
16282 if (!UserOffset || UserOffset <= Offset)
16283 continue;
16284
16285 unsigned NewConstInc = UserOffset - Offset;
16286 SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16287 BaseUpdates.push_back({User, NewInc, NewConstInc});
16288 if (BaseUpdates.size() >= MaxBaseUpdates)
16289 break;
16290 }
16291 }
16292 }
16293
16294 // Try to fold the load/store with an update that matches memory
16295 // access size. This should work well for sequential loads.
16296 unsigned NumValidUpd = BaseUpdates.size();
16297 for (unsigned I = 0; I < NumValidUpd; I++) {
16298 BaseUpdateUser &User = BaseUpdates[I];
16299 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16300 return SDValue();
16301 }
16302
16303 // Try to fold with other users. Non-constant updates are considered
16304 // first, and constant updates are sorted to not break a sequence of
16305 // strided accesses (if there is any).
16306 llvm::stable_sort(BaseUpdates,
16307 [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16308 return LHS.ConstInc < RHS.ConstInc;
16309 });
16310 for (BaseUpdateUser &User : BaseUpdates) {
16311 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16312 return SDValue();
16313 }
16314 return SDValue();
16315}
16316
16319 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16320 return SDValue();
16321
16322 return CombineBaseUpdate(N, DCI);
16323}
16324
16327 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16328 return SDValue();
16329
16330 SelectionDAG &DAG = DCI.DAG;
16331 SDValue Addr = N->getOperand(2);
16332 MemSDNode *MemN = cast<MemSDNode>(N);
16333 SDLoc dl(N);
16334
16335 // For the stores, where there are multiple intrinsics we only actually want
16336 // to post-inc the last of the them.
16337 unsigned IntNo = N->getConstantOperandVal(1);
16338 if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(5) != 1)
16339 return SDValue();
16340 if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(7) != 3)
16341 return SDValue();
16342
16343 // Search for a use of the address operand that is an increment.
16344 for (SDUse &Use : Addr->uses()) {
16345 SDNode *User = Use.getUser();
16346 if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16347 continue;
16348
16349 // Check that the add is independent of the load/store. Otherwise, folding
16350 // it would create a cycle. We can avoid searching through Addr as it's a
16351 // predecessor to both.
16354 Visited.insert(Addr.getNode());
16355 Worklist.push_back(N);
16356 Worklist.push_back(User);
16357 const unsigned MaxSteps = 1024;
16358 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16359 SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16360 continue;
16361
16362 // Find the new opcode for the updating load/store.
16363 bool isLoadOp = true;
16364 unsigned NewOpc = 0;
16365 unsigned NumVecs = 0;
16366 switch (IntNo) {
16367 default:
16368 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16369 case Intrinsic::arm_mve_vld2q:
16370 NewOpc = ARMISD::VLD2_UPD;
16371 NumVecs = 2;
16372 break;
16373 case Intrinsic::arm_mve_vld4q:
16374 NewOpc = ARMISD::VLD4_UPD;
16375 NumVecs = 4;
16376 break;
16377 case Intrinsic::arm_mve_vst2q:
16378 NewOpc = ARMISD::VST2_UPD;
16379 NumVecs = 2;
16380 isLoadOp = false;
16381 break;
16382 case Intrinsic::arm_mve_vst4q:
16383 NewOpc = ARMISD::VST4_UPD;
16384 NumVecs = 4;
16385 isLoadOp = false;
16386 break;
16387 }
16388
16389 // Find the size of memory referenced by the load/store.
16390 EVT VecTy;
16391 if (isLoadOp) {
16392 VecTy = N->getValueType(0);
16393 } else {
16394 VecTy = N->getOperand(3).getValueType();
16395 }
16396
16397 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16398
16399 // If the increment is a constant, it must match the memory ref size.
16400 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16402 if (!CInc || CInc->getZExtValue() != NumBytes)
16403 continue;
16404
16405 // Create the new updating load/store node.
16406 // First, create an SDVTList for the new updating node's results.
16407 EVT Tys[6];
16408 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16409 unsigned n;
16410 for (n = 0; n < NumResultVecs; ++n)
16411 Tys[n] = VecTy;
16412 Tys[n++] = MVT::i32;
16413 Tys[n] = MVT::Other;
16414 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16415
16416 // Then, gather the new node's operands.
16418 Ops.push_back(N->getOperand(0)); // incoming chain
16419 Ops.push_back(N->getOperand(2)); // ptr
16420 Ops.push_back(Inc);
16421
16422 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16423 Ops.push_back(N->getOperand(i));
16424
16425 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16426 MemN->getMemOperand());
16427
16428 // Update the uses.
16429 SmallVector<SDValue, 5> NewResults;
16430 for (unsigned i = 0; i < NumResultVecs; ++i)
16431 NewResults.push_back(SDValue(UpdN.getNode(), i));
16432
16433 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16434 DCI.CombineTo(N, NewResults);
16435 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16436
16437 break;
16438 }
16439
16440 return SDValue();
16441}
16442
16443/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16444/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16445/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16446/// return true.
16448 SelectionDAG &DAG = DCI.DAG;
16449 EVT VT = N->getValueType(0);
16450 // vldN-dup instructions only support 64-bit vectors for N > 1.
16451 if (!VT.is64BitVector())
16452 return false;
16453
16454 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16455 SDNode *VLD = N->getOperand(0).getNode();
16456 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16457 return false;
16458 unsigned NumVecs = 0;
16459 unsigned NewOpc = 0;
16460 unsigned IntNo = VLD->getConstantOperandVal(1);
16461 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16462 NumVecs = 2;
16463 NewOpc = ARMISD::VLD2DUP;
16464 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16465 NumVecs = 3;
16466 NewOpc = ARMISD::VLD3DUP;
16467 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16468 NumVecs = 4;
16469 NewOpc = ARMISD::VLD4DUP;
16470 } else {
16471 return false;
16472 }
16473
16474 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16475 // numbers match the load.
16476 unsigned VLDLaneNo = VLD->getConstantOperandVal(NumVecs + 3);
16477 for (SDUse &Use : VLD->uses()) {
16478 // Ignore uses of the chain result.
16479 if (Use.getResNo() == NumVecs)
16480 continue;
16481 SDNode *User = Use.getUser();
16482 if (User->getOpcode() != ARMISD::VDUPLANE ||
16483 VLDLaneNo != User->getConstantOperandVal(1))
16484 return false;
16485 }
16486
16487 // Create the vldN-dup node.
16488 EVT Tys[5];
16489 unsigned n;
16490 for (n = 0; n < NumVecs; ++n)
16491 Tys[n] = VT;
16492 Tys[n] = MVT::Other;
16493 SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumVecs + 1));
16494 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16496 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16497 Ops, VLDMemInt->getMemoryVT(),
16498 VLDMemInt->getMemOperand());
16499
16500 // Update the uses.
16501 for (SDUse &Use : VLD->uses()) {
16502 unsigned ResNo = Use.getResNo();
16503 // Ignore uses of the chain result.
16504 if (ResNo == NumVecs)
16505 continue;
16506 DCI.CombineTo(Use.getUser(), SDValue(VLDDup.getNode(), ResNo));
16507 }
16508
16509 // Now the vldN-lane intrinsic is dead except for its chain result.
16510 // Update uses of the chain.
16511 std::vector<SDValue> VLDDupResults;
16512 for (unsigned n = 0; n < NumVecs; ++n)
16513 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16514 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16515 DCI.CombineTo(VLD, VLDDupResults);
16516
16517 return true;
16518}
16519
16520/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16521/// ARMISD::VDUPLANE.
16524 const ARMSubtarget *Subtarget) {
16525 SDValue Op = N->getOperand(0);
16526 EVT VT = N->getValueType(0);
16527
16528 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16529 if (Subtarget->hasMVEIntegerOps()) {
16530 EVT ExtractVT = VT.getVectorElementType();
16531 // We need to ensure we are creating a legal type.
16532 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16533 ExtractVT = MVT::i32;
16534 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16535 N->getOperand(0), N->getOperand(1));
16536 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16537 }
16538
16539 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16540 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16541 if (CombineVLDDUP(N, DCI))
16542 return SDValue(N, 0);
16543
16544 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16545 // redundant. Ignore bit_converts for now; element sizes are checked below.
16546 while (Op.getOpcode() == ISD::BITCAST)
16547 Op = Op.getOperand(0);
16548 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16549 return SDValue();
16550
16551 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16552 unsigned EltSize = Op.getScalarValueSizeInBits();
16553 // The canonical VMOV for a zero vector uses a 32-bit element size.
16554 unsigned Imm = Op.getConstantOperandVal(0);
16555 unsigned EltBits;
16556 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16557 EltSize = 8;
16558 if (EltSize > VT.getScalarSizeInBits())
16559 return SDValue();
16560
16561 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16562}
16563
16564/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16566 const ARMSubtarget *Subtarget) {
16567 SDValue Op = N->getOperand(0);
16568 SDLoc dl(N);
16569
16570 if (Subtarget->hasMVEIntegerOps()) {
16571 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16572 // need to come from a GPR.
16573 if (Op.getValueType() == MVT::f32)
16574 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16575 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16576 else if (Op.getValueType() == MVT::f16)
16577 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16578 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16579 }
16580
16581 if (!Subtarget->hasNEON())
16582 return SDValue();
16583
16584 // Match VDUP(LOAD) -> VLD1DUP.
16585 // We match this pattern here rather than waiting for isel because the
16586 // transform is only legal for unindexed loads.
16587 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16588 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16589 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16590 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16591 DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16592 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16593 SDValue VLDDup =
16595 LD->getMemoryVT(), LD->getMemOperand());
16596 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16597 return VLDDup;
16598 }
16599
16600 return SDValue();
16601}
16602
16605 const ARMSubtarget *Subtarget) {
16606 EVT VT = N->getValueType(0);
16607
16608 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16609 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16611 return CombineBaseUpdate(N, DCI);
16612
16613 return SDValue();
16614}
16615
16616// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16617// pack all of the elements in one place. Next, store to memory in fewer
16618// chunks.
16620 SelectionDAG &DAG) {
16621 SDValue StVal = St->getValue();
16622 EVT VT = StVal.getValueType();
16623 if (!St->isTruncatingStore() || !VT.isVector())
16624 return SDValue();
16625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16626 EVT StVT = St->getMemoryVT();
16627 unsigned NumElems = VT.getVectorNumElements();
16628 assert(StVT != VT && "Cannot truncate to the same type");
16629 unsigned FromEltSz = VT.getScalarSizeInBits();
16630 unsigned ToEltSz = StVT.getScalarSizeInBits();
16631
16632 // From, To sizes and ElemCount must be pow of two
16633 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16634 return SDValue();
16635
16636 // We are going to use the original vector elt for storing.
16637 // Accumulated smaller vector elements must be a multiple of the store size.
16638 if (0 != (NumElems * FromEltSz) % ToEltSz)
16639 return SDValue();
16640
16641 unsigned SizeRatio = FromEltSz / ToEltSz;
16642 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16643
16644 // Create a type on which we perform the shuffle.
16645 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16646 NumElems * SizeRatio);
16647 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16648
16649 SDLoc DL(St);
16650 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16651 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16652 for (unsigned i = 0; i < NumElems; ++i)
16653 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16654 : i * SizeRatio;
16655
16656 // Can't shuffle using an illegal type.
16657 if (!TLI.isTypeLegal(WideVecVT))
16658 return SDValue();
16659
16660 SDValue Shuff = DAG.getVectorShuffle(
16661 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16662 // At this point all of the data is stored at the bottom of the
16663 // register. We now need to save it to mem.
16664
16665 // Find the largest store unit
16666 MVT StoreType = MVT::i8;
16667 for (MVT Tp : MVT::integer_valuetypes()) {
16668 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16669 StoreType = Tp;
16670 }
16671 // Didn't find a legal store type.
16672 if (!TLI.isTypeLegal(StoreType))
16673 return SDValue();
16674
16675 // Bitcast the original vector into a vector of store-size units
16676 EVT StoreVecVT =
16677 EVT::getVectorVT(*DAG.getContext(), StoreType,
16678 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16679 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16680 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16682 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16683 TLI.getPointerTy(DAG.getDataLayout()));
16684 SDValue BasePtr = St->getBasePtr();
16685
16686 // Perform one or more big stores into memory.
16687 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16688 for (unsigned I = 0; I < E; I++) {
16689 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16690 ShuffWide, DAG.getIntPtrConstant(I, DL));
16691 SDValue Ch =
16692 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16693 St->getAlign(), St->getMemOperand()->getFlags());
16694 BasePtr =
16695 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16696 Chains.push_back(Ch);
16697 }
16698 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16699}
16700
16701// Try taking a single vector store from an fpround (which would otherwise turn
16702// into an expensive buildvector) and splitting it into a series of narrowing
16703// stores.
16705 SelectionDAG &DAG) {
16706 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16707 return SDValue();
16708 SDValue Trunc = St->getValue();
16709 if (Trunc->getOpcode() != ISD::FP_ROUND)
16710 return SDValue();
16711 EVT FromVT = Trunc->getOperand(0).getValueType();
16712 EVT ToVT = Trunc.getValueType();
16713 if (!ToVT.isVector())
16714 return SDValue();
16716 EVT ToEltVT = ToVT.getVectorElementType();
16717 EVT FromEltVT = FromVT.getVectorElementType();
16718
16719 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16720 return SDValue();
16721
16722 unsigned NumElements = 4;
16723 if (FromVT.getVectorNumElements() % NumElements != 0)
16724 return SDValue();
16725
16726 // Test if the Trunc will be convertible to a VMOVN with a shuffle, and if so
16727 // use the VMOVN over splitting the store. We are looking for patterns of:
16728 // !rev: 0 N 1 N+1 2 N+2 ...
16729 // rev: N 0 N+1 1 N+2 2 ...
16730 // The shuffle may either be a single source (in which case N = NumElts/2) or
16731 // two inputs extended with concat to the same size (in which case N =
16732 // NumElts).
16733 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16734 ArrayRef<int> M = SVN->getMask();
16735 unsigned NumElts = ToVT.getVectorNumElements();
16736 if (SVN->getOperand(1).isUndef())
16737 NumElts /= 2;
16738
16739 unsigned Off0 = Rev ? NumElts : 0;
16740 unsigned Off1 = Rev ? 0 : NumElts;
16741
16742 for (unsigned I = 0; I < NumElts; I += 2) {
16743 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16744 return false;
16745 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16746 return false;
16747 }
16748
16749 return true;
16750 };
16751
16752 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16753 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16754 return SDValue();
16755
16756 LLVMContext &C = *DAG.getContext();
16757 SDLoc DL(St);
16758 // Details about the old store
16759 SDValue Ch = St->getChain();
16760 SDValue BasePtr = St->getBasePtr();
16761 Align Alignment = St->getBaseAlign();
16763 AAMDNodes AAInfo = St->getAAInfo();
16764
16765 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16766 // and then stored as truncating integer stores.
16767 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16768 EVT NewToVT = EVT::getVectorVT(
16769 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16770
16772 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16773 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16774 SDValue NewPtr =
16775 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16776
16777 SDValue Extract =
16778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16779 DAG.getConstant(i * NumElements, DL, MVT::i32));
16780
16781 SDValue FPTrunc =
16782 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16783 Extract, DAG.getConstant(0, DL, MVT::i32));
16784 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16785
16786 SDValue Store = DAG.getTruncStore(
16787 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16788 NewToVT, Alignment, MMOFlags, AAInfo);
16789 Stores.push_back(Store);
16790 }
16791 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16792}
16793
16794// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16795// into an expensive buildvector) and splitting it into a series of narrowing
16796// stores.
16798 SelectionDAG &DAG) {
16799 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16800 return SDValue();
16801 SDValue Trunc = St->getValue();
16802 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16803 return SDValue();
16804 EVT FromVT = Trunc->getOperand(0).getValueType();
16805 EVT ToVT = Trunc.getValueType();
16806
16807 LLVMContext &C = *DAG.getContext();
16808 SDLoc DL(St);
16809 // Details about the old store
16810 SDValue Ch = St->getChain();
16811 SDValue BasePtr = St->getBasePtr();
16812 Align Alignment = St->getBaseAlign();
16814 AAMDNodes AAInfo = St->getAAInfo();
16815
16816 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16817 FromVT.getVectorNumElements());
16818
16820 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16821 unsigned NewOffset =
16822 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16823 SDValue NewPtr =
16824 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16825
16826 SDValue Extract = Trunc.getOperand(i);
16827 SDValue Store = DAG.getTruncStore(
16828 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16829 NewToVT, Alignment, MMOFlags, AAInfo);
16830 Stores.push_back(Store);
16831 }
16832 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16833}
16834
16835// Given a floating point store from an extracted vector, with an integer
16836// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16837// help reduce fp register pressure, doesn't require the fp extract and allows
16838// use of more integer post-inc stores not available with vstr.
16840 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16841 return SDValue();
16842 SDValue Extract = St->getValue();
16843 EVT VT = Extract.getValueType();
16844 // For now only uses f16. This may be useful for f32 too, but that will
16845 // be bitcast(extract), not the VGETLANEu we currently check here.
16846 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16847 return SDValue();
16848
16849 SDNode *GetLane =
16850 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
16851 {Extract.getOperand(0), Extract.getOperand(1)});
16852 if (!GetLane)
16853 return SDValue();
16854
16855 LLVMContext &C = *DAG.getContext();
16856 SDLoc DL(St);
16857 // Create a new integer store to replace the existing floating point version.
16858 SDValue Ch = St->getChain();
16859 SDValue BasePtr = St->getBasePtr();
16860 Align Alignment = St->getBaseAlign();
16862 AAMDNodes AAInfo = St->getAAInfo();
16863 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
16864 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
16865 St->getPointerInfo(), NewToVT, Alignment,
16866 MMOFlags, AAInfo);
16867
16868 return Store;
16869}
16870
16871/// PerformSTORECombine - Target-specific dag combine xforms for
16872/// ISD::STORE.
16875 const ARMSubtarget *Subtarget) {
16877 if (St->isVolatile())
16878 return SDValue();
16879 SDValue StVal = St->getValue();
16880 EVT VT = StVal.getValueType();
16881
16882 if (Subtarget->hasNEON())
16883 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16884 return Store;
16885
16886 if (Subtarget->hasMVEFloatOps())
16887 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16888 return NewToken;
16889
16890 if (Subtarget->hasMVEIntegerOps()) {
16891 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16892 return NewChain;
16893 if (SDValue NewToken =
16895 return NewToken;
16896 }
16897
16898 if (!ISD::isNormalStore(St))
16899 return SDValue();
16900
16901 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16902 // ARM stores of arguments in the same cache line.
16903 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16904 StVal.getNode()->hasOneUse()) {
16905 SelectionDAG &DAG = DCI.DAG;
16906 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16907 SDLoc DL(St);
16908 SDValue BasePtr = St->getBasePtr();
16909 SDValue NewST1 = DAG.getStore(
16910 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16911 BasePtr, St->getPointerInfo(), St->getBaseAlign(),
16912 St->getMemOperand()->getFlags());
16913
16914 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16915 DAG.getConstant(4, DL, MVT::i32));
16916 return DAG.getStore(NewST1.getValue(0), DL,
16917 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16918 OffsetPtr, St->getPointerInfo().getWithOffset(4),
16919 St->getBaseAlign(), St->getMemOperand()->getFlags());
16920 }
16921
16922 if (StVal.getValueType() == MVT::i64 &&
16924
16925 // Bitcast an i64 store extracted from a vector to f64.
16926 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16927 SelectionDAG &DAG = DCI.DAG;
16928 SDLoc dl(StVal);
16929 SDValue IntVec = StVal.getOperand(0);
16930 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16932 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16933 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16934 Vec, StVal.getOperand(1));
16935 dl = SDLoc(N);
16936 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16937 // Make the DAGCombiner fold the bitcasts.
16938 DCI.AddToWorklist(Vec.getNode());
16939 DCI.AddToWorklist(ExtElt.getNode());
16940 DCI.AddToWorklist(V.getNode());
16941 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16942 St->getPointerInfo(), St->getAlign(),
16943 St->getMemOperand()->getFlags(), St->getAAInfo());
16944 }
16945
16946 // If this is a legal vector store, try to combine it into a VST1_UPD.
16947 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16949 return CombineBaseUpdate(N, DCI);
16950
16951 return SDValue();
16952}
16953
16954/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16955/// can replace combinations of VMUL and VCVT (floating-point to integer)
16956/// when the VMUL has a constant operand that is a power of 2.
16957///
16958/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16959/// vmul.f32 d16, d17, d16
16960/// vcvt.s32.f32 d16, d16
16961/// becomes:
16962/// vcvt.s32.f32 d16, d16, #3
16964 const ARMSubtarget *Subtarget) {
16965 if (!Subtarget->hasNEON())
16966 return SDValue();
16967
16968 SDValue Op = N->getOperand(0);
16969 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16970 Op.getOpcode() != ISD::FMUL)
16971 return SDValue();
16972
16973 SDValue ConstVec = Op->getOperand(1);
16974 if (!isa<BuildVectorSDNode>(ConstVec))
16975 return SDValue();
16976
16977 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16978 uint32_t FloatBits = FloatTy.getSizeInBits();
16979 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16980 uint32_t IntBits = IntTy.getSizeInBits();
16981 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16982 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16983 // These instructions only exist converting from f32 to i32. We can handle
16984 // smaller integers by generating an extra truncate, but larger ones would
16985 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16986 // these instructions only support v2i32/v4i32 types.
16987 return SDValue();
16988 }
16989
16990 BitVector UndefElements;
16992 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16993 if (C == -1 || C == 0 || C > 32)
16994 return SDValue();
16995
16996 SDLoc dl(N);
16997 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16998 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16999 Intrinsic::arm_neon_vcvtfp2fxu;
17000 SDValue FixConv = DAG.getNode(
17001 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
17002 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
17003 DAG.getConstant(C, dl, MVT::i32));
17004
17005 if (IntBits < FloatBits)
17006 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
17007
17008 return FixConv;
17009}
17010
17012 const ARMSubtarget *Subtarget) {
17013 if (!Subtarget->hasMVEFloatOps())
17014 return SDValue();
17015
17016 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
17017 // The second form can be more easily turned into a predicated vadd, and
17018 // possibly combined into a fma to become a predicated vfma.
17019 SDValue Op0 = N->getOperand(0);
17020 SDValue Op1 = N->getOperand(1);
17021 EVT VT = N->getValueType(0);
17022 SDLoc DL(N);
17023
17024 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
17025 // which these VMOV's represent.
17026 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
17027 if (Op.getOpcode() != ISD::BITCAST ||
17028 Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
17029 return false;
17030 uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
17031 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
17032 return true;
17033 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
17034 return true;
17035 return false;
17036 };
17037
17038 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
17039 std::swap(Op0, Op1);
17040
17041 if (Op1.getOpcode() != ISD::VSELECT)
17042 return SDValue();
17043
17044 SDNodeFlags FaddFlags = N->getFlags();
17045 bool NSZ = FaddFlags.hasNoSignedZeros();
17046 if (!isIdentitySplat(Op1.getOperand(2), NSZ))
17047 return SDValue();
17048
17049 SDValue FAdd =
17050 DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
17051 return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
17052}
17053
17055 SDValue LHS = N->getOperand(0);
17056 SDValue RHS = N->getOperand(1);
17057 EVT VT = N->getValueType(0);
17058 SDLoc DL(N);
17059
17060 if (!N->getFlags().hasAllowReassociation())
17061 return SDValue();
17062
17063 // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
17064 auto ReassocComplex = [&](SDValue A, SDValue B) {
17065 if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
17066 return SDValue();
17067 unsigned Opc = A.getConstantOperandVal(0);
17068 if (Opc != Intrinsic::arm_mve_vcmlaq)
17069 return SDValue();
17070 SDValue VCMLA = DAG.getNode(
17071 ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0), A.getOperand(1),
17072 DAG.getNode(ISD::FADD, DL, VT, A.getOperand(2), B, N->getFlags()),
17073 A.getOperand(3), A.getOperand(4));
17074 VCMLA->setFlags(A->getFlags());
17075 return VCMLA;
17076 };
17077 if (SDValue R = ReassocComplex(LHS, RHS))
17078 return R;
17079 if (SDValue R = ReassocComplex(RHS, LHS))
17080 return R;
17081
17082 return SDValue();
17083}
17084
17086 const ARMSubtarget *Subtarget) {
17087 if (SDValue S = PerformFAddVSelectCombine(N, DAG, Subtarget))
17088 return S;
17089 if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17090 return S;
17091 return SDValue();
17092}
17093
17094/// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17095/// can replace combinations of VCVT (integer to floating-point) and VMUL
17096/// when the VMUL has a constant operand that is a power of 2.
17097///
17098/// Example (assume d17 = <float 0.125, float 0.125>):
17099/// vcvt.f32.s32 d16, d16
17100/// vmul.f32 d16, d16, d17
17101/// becomes:
17102/// vcvt.f32.s32 d16, d16, #3
17104 const ARMSubtarget *Subtarget) {
17105 if (!Subtarget->hasNEON())
17106 return SDValue();
17107
17108 SDValue Op = N->getOperand(0);
17109 unsigned OpOpcode = Op.getNode()->getOpcode();
17110 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
17111 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17112 return SDValue();
17113
17114 SDValue ConstVec = N->getOperand(1);
17115 if (!isa<BuildVectorSDNode>(ConstVec))
17116 return SDValue();
17117
17118 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
17119 uint32_t FloatBits = FloatTy.getSizeInBits();
17120 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
17121 uint32_t IntBits = IntTy.getSizeInBits();
17122 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17123 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17124 // These instructions only exist converting from i32 to f32. We can handle
17125 // smaller integers by generating an extra extend, but larger ones would
17126 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17127 // these instructions only support v2i32/v4i32 types.
17128 return SDValue();
17129 }
17130
17131 ConstantFPSDNode *CN = isConstOrConstSplatFP(ConstVec, true);
17132 APFloat Recip(0.0f);
17133 if (!CN || !CN->getValueAPF().getExactInverse(&Recip))
17134 return SDValue();
17135
17136 bool IsExact;
17137 APSInt IntVal(33);
17138 if (Recip.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
17139 APFloat::opOK ||
17140 !IsExact)
17141 return SDValue();
17142
17143 int32_t C = IntVal.exactLogBase2();
17144 if (C == -1 || C == 0 || C > 32)
17145 return SDValue();
17146
17147 SDLoc DL(N);
17148 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17149 SDValue ConvInput = Op.getOperand(0);
17150 if (IntBits < FloatBits)
17152 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, ConvInput);
17153
17154 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17155 : Intrinsic::arm_neon_vcvtfxu2fp;
17156 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
17157 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
17158 DAG.getConstant(C, DL, MVT::i32));
17159}
17160
17162 const ARMSubtarget *ST) {
17163 if (!ST->hasMVEIntegerOps())
17164 return SDValue();
17165
17166 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17167 EVT ResVT = N->getValueType(0);
17168 SDValue N0 = N->getOperand(0);
17169 SDLoc dl(N);
17170
17171 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17172 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17173 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17174 N0.getValueType() == MVT::v16i8)) {
17175 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
17176 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
17177 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
17178 }
17179
17180 // We are looking for something that will have illegal types if left alone,
17181 // but that we can convert to a single instruction under MVE. For example
17182 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17183 // or
17184 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17185
17186 // The legal cases are:
17187 // VADDV u/s 8/16/32
17188 // VMLAV u/s 8/16/32
17189 // VADDLV u/s 32
17190 // VMLALV u/s 16/32
17191
17192 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17193 // extend it and use v4i32 instead.
17194 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17195 EVT AVT = A.getValueType();
17196 return any_of(ExtTypes, [&](MVT Ty) {
17197 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17198 AVT.bitsLE(Ty);
17199 });
17200 };
17201 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17202 EVT AVT = A.getValueType();
17203 if (!AVT.is128BitVector())
17204 A = DAG.getNode(
17205 ExtendCode, dl,
17207 *DAG.getContext(),
17209 A);
17210 return A;
17211 };
17212 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17213 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17214 return SDValue();
17215 SDValue A = N0->getOperand(0);
17216 if (ExtTypeMatches(A, ExtTypes))
17217 return ExtendIfNeeded(A, ExtendCode);
17218 return SDValue();
17219 };
17220 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
17221 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
17222 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17224 return SDValue();
17225 Mask = N0->getOperand(0);
17226 SDValue Ext = N0->getOperand(1);
17227 if (Ext->getOpcode() != ExtendCode)
17228 return SDValue();
17229 SDValue A = Ext->getOperand(0);
17230 if (ExtTypeMatches(A, ExtTypes))
17231 return ExtendIfNeeded(A, ExtendCode);
17232 return SDValue();
17233 };
17234 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17235 SDValue &A, SDValue &B) {
17236 // For a vmla we are trying to match a larger pattern:
17237 // ExtA = sext/zext A
17238 // ExtB = sext/zext B
17239 // Mul = mul ExtA, ExtB
17240 // vecreduce.add Mul
17241 // There might also be en extra extend between the mul and the addreduce, so
17242 // long as the bitwidth is high enough to make them equivalent (for example
17243 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17244 if (ResVT != RetTy)
17245 return false;
17246 SDValue Mul = N0;
17247 if (Mul->getOpcode() == ExtendCode &&
17248 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17249 ResVT.getScalarSizeInBits())
17250 Mul = Mul->getOperand(0);
17251 if (Mul->getOpcode() != ISD::MUL)
17252 return false;
17253 SDValue ExtA = Mul->getOperand(0);
17254 SDValue ExtB = Mul->getOperand(1);
17255 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17256 return false;
17257 A = ExtA->getOperand(0);
17258 B = ExtB->getOperand(0);
17259 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17260 A = ExtendIfNeeded(A, ExtendCode);
17261 B = ExtendIfNeeded(B, ExtendCode);
17262 return true;
17263 }
17264 return false;
17265 };
17266 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17267 SDValue &A, SDValue &B, SDValue &Mask) {
17268 // Same as the pattern above with a select for the zero predicated lanes
17269 // ExtA = sext/zext A
17270 // ExtB = sext/zext B
17271 // Mul = mul ExtA, ExtB
17272 // N0 = select Mask, Mul, 0
17273 // vecreduce.add N0
17274 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17276 return false;
17277 Mask = N0->getOperand(0);
17278 SDValue Mul = N0->getOperand(1);
17279 if (Mul->getOpcode() == ExtendCode &&
17280 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17281 ResVT.getScalarSizeInBits())
17282 Mul = Mul->getOperand(0);
17283 if (Mul->getOpcode() != ISD::MUL)
17284 return false;
17285 SDValue ExtA = Mul->getOperand(0);
17286 SDValue ExtB = Mul->getOperand(1);
17287 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17288 return false;
17289 A = ExtA->getOperand(0);
17290 B = ExtB->getOperand(0);
17291 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17292 A = ExtendIfNeeded(A, ExtendCode);
17293 B = ExtendIfNeeded(B, ExtendCode);
17294 return true;
17295 }
17296 return false;
17297 };
17298 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17299 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17300 // reductions. The operands are extended with MVEEXT, but as they are
17301 // reductions the lane orders do not matter. MVEEXT may be combined with
17302 // loads to produce two extending loads, or else they will be expanded to
17303 // VREV/VMOVL.
17304 EVT VT = Ops[0].getValueType();
17305 if (VT == MVT::v16i8) {
17306 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17307 "Unexpected illegal long reduction opcode");
17308 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17309
17310 SDValue Ext0 =
17311 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17312 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
17313 SDValue Ext1 =
17314 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17315 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
17316
17317 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
17318 Ext0, Ext1);
17319 SDValue MLA1 =
17320 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
17321 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17322 Ext0.getValue(1), Ext1.getValue(1));
17323 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17324 }
17325 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17326 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17327 SDValue(Node.getNode(), 1));
17328 };
17329
17330 SDValue A, B;
17331 SDValue Mask;
17332 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17333 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17334 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17335 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17336 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17337 A, B))
17338 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17339 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17340 A, B))
17341 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17342 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17343 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17344 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17345 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17346 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17347 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17348
17349 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17350 Mask))
17351 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17352 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17353 Mask))
17354 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17355 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17356 Mask))
17357 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17358 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17359 Mask))
17360 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17361 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17362 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17363 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17364 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17365 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17366 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17367
17368 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17369 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17370 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17371 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17372 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17373 return Create64bitNode(ARMISD::VADDLVs, {A});
17374 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17375 return Create64bitNode(ARMISD::VADDLVu, {A});
17376 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17377 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17378 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17379 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17380 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17381 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17382
17383 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17384 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17385 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17386 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17387 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17388 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17389 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17390 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17391 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17392 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17393 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17394 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17395 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17396 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17397
17398 // Some complications. We can get a case where the two inputs of the mul are
17399 // the same, then the output sext will have been helpfully converted to a
17400 // zext. Turn it back.
17401 SDValue Op = N0;
17402 if (Op->getOpcode() == ISD::VSELECT)
17403 Op = Op->getOperand(1);
17404 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17405 Op->getOperand(0)->getOpcode() == ISD::MUL) {
17406 SDValue Mul = Op->getOperand(0);
17407 if (Mul->getOperand(0) == Mul->getOperand(1) &&
17408 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17409 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17410 if (Op != N0)
17411 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17412 N0->getOperand(0), Ext, N0->getOperand(2));
17413 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17414 }
17415 }
17416
17417 return SDValue();
17418}
17419
17420// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17421// the lanes are used. Due to the reduction being commutative the shuffle can be
17422// removed.
17424 unsigned VecOp = N->getOperand(0).getValueType().isVector() ? 0 : 2;
17425 auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp));
17426 if (!Shuf || !Shuf->getOperand(1).isUndef())
17427 return SDValue();
17428
17429 // Check all elements are used once in the mask.
17430 ArrayRef<int> Mask = Shuf->getMask();
17431 APInt SetElts(Mask.size(), 0);
17432 for (int E : Mask) {
17433 if (E < 0 || E >= (int)Mask.size())
17434 return SDValue();
17435 SetElts.setBit(E);
17436 }
17437 if (!SetElts.isAllOnes())
17438 return SDValue();
17439
17440 if (N->getNumOperands() != VecOp + 1) {
17441 auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp + 1));
17442 if (!Shuf2 || !Shuf2->getOperand(1).isUndef() || Shuf2->getMask() != Mask)
17443 return SDValue();
17444 }
17445
17447 for (SDValue Op : N->ops()) {
17448 if (Op.getValueType().isVector())
17449 Ops.push_back(Op.getOperand(0));
17450 else
17451 Ops.push_back(Op);
17452 }
17453 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops);
17454}
17455
17458 SDValue Op0 = N->getOperand(0);
17459 SDValue Op1 = N->getOperand(1);
17460 unsigned IsTop = N->getConstantOperandVal(2);
17461
17462 // VMOVNT a undef -> a
17463 // VMOVNB a undef -> a
17464 // VMOVNB undef a -> a
17465 if (Op1->isUndef())
17466 return Op0;
17467 if (Op0->isUndef() && !IsTop)
17468 return Op1;
17469
17470 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17471 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17472 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17473 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17474 Op1->getConstantOperandVal(2) == 0)
17475 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17476 Op0, Op1->getOperand(1), N->getOperand(2));
17477
17478 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17479 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17480 // into the top or bottom lanes.
17481 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17482 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17483 APInt Op0DemandedElts =
17484 IsTop ? Op1DemandedElts
17485 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17486
17487 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17488 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17489 return SDValue(N, 0);
17490 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17491 return SDValue(N, 0);
17492
17493 return SDValue();
17494}
17495
17498 SDValue Op0 = N->getOperand(0);
17499 unsigned IsTop = N->getConstantOperandVal(2);
17500
17501 unsigned NumElts = N->getValueType(0).getVectorNumElements();
17502 APInt Op0DemandedElts =
17503 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17504 : APInt::getHighBitsSet(2, 1));
17505
17506 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17507 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17508 return SDValue(N, 0);
17509 return SDValue();
17510}
17511
17514 EVT VT = N->getValueType(0);
17515 SDValue LHS = N->getOperand(0);
17516 SDValue RHS = N->getOperand(1);
17517
17518 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
17519 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
17520 // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17521 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
17522 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
17523 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17524 SDLoc DL(N);
17525 SDValue NewBinOp = DCI.DAG.getNode(N->getOpcode(), DL, VT,
17526 LHS.getOperand(0), RHS.getOperand(0));
17527 SDValue UndefV = LHS.getOperand(1);
17528 return DCI.DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
17529 }
17530 return SDValue();
17531}
17532
17534 SDLoc DL(N);
17535 SDValue Op0 = N->getOperand(0);
17536 SDValue Op1 = N->getOperand(1);
17537
17538 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17539 // uses of the intrinsics.
17540 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17541 int ShiftAmt = C->getSExtValue();
17542 if (ShiftAmt == 0) {
17543 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17544 DAG.ReplaceAllUsesWith(N, Merge.getNode());
17545 return SDValue();
17546 }
17547
17548 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17549 unsigned NewOpcode =
17550 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17551 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17552 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17553 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17554 return NewShift;
17555 }
17556 }
17557
17558 return SDValue();
17559}
17560
17561/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17563 DAGCombinerInfo &DCI) const {
17564 SelectionDAG &DAG = DCI.DAG;
17565 unsigned IntNo = N->getConstantOperandVal(0);
17566 switch (IntNo) {
17567 default:
17568 // Don't do anything for most intrinsics.
17569 break;
17570
17571 // Vector shifts: check for immediate versions and lower them.
17572 // Note: This is done during DAG combining instead of DAG legalizing because
17573 // the build_vectors for 64-bit vector element shift counts are generally
17574 // not legal, and it is hard to see their values after they get legalized to
17575 // loads from a constant pool.
17576 case Intrinsic::arm_neon_vshifts:
17577 case Intrinsic::arm_neon_vshiftu:
17578 case Intrinsic::arm_neon_vrshifts:
17579 case Intrinsic::arm_neon_vrshiftu:
17580 case Intrinsic::arm_neon_vrshiftn:
17581 case Intrinsic::arm_neon_vqshifts:
17582 case Intrinsic::arm_neon_vqshiftu:
17583 case Intrinsic::arm_neon_vqshiftsu:
17584 case Intrinsic::arm_neon_vqshiftns:
17585 case Intrinsic::arm_neon_vqshiftnu:
17586 case Intrinsic::arm_neon_vqshiftnsu:
17587 case Intrinsic::arm_neon_vqrshiftns:
17588 case Intrinsic::arm_neon_vqrshiftnu:
17589 case Intrinsic::arm_neon_vqrshiftnsu: {
17590 EVT VT = N->getOperand(1).getValueType();
17591 int64_t Cnt;
17592 unsigned VShiftOpc = 0;
17593
17594 switch (IntNo) {
17595 case Intrinsic::arm_neon_vshifts:
17596 case Intrinsic::arm_neon_vshiftu:
17597 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
17598 VShiftOpc = ARMISD::VSHLIMM;
17599 break;
17600 }
17601 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
17602 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17603 : ARMISD::VSHRuIMM);
17604 break;
17605 }
17606 return SDValue();
17607
17608 case Intrinsic::arm_neon_vrshifts:
17609 case Intrinsic::arm_neon_vrshiftu:
17610 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
17611 break;
17612 return SDValue();
17613
17614 case Intrinsic::arm_neon_vqshifts:
17615 case Intrinsic::arm_neon_vqshiftu:
17616 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17617 break;
17618 return SDValue();
17619
17620 case Intrinsic::arm_neon_vqshiftsu:
17621 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17622 break;
17623 llvm_unreachable("invalid shift count for vqshlu intrinsic");
17624
17625 case Intrinsic::arm_neon_vrshiftn:
17626 case Intrinsic::arm_neon_vqshiftns:
17627 case Intrinsic::arm_neon_vqshiftnu:
17628 case Intrinsic::arm_neon_vqshiftnsu:
17629 case Intrinsic::arm_neon_vqrshiftns:
17630 case Intrinsic::arm_neon_vqrshiftnu:
17631 case Intrinsic::arm_neon_vqrshiftnsu:
17632 // Narrowing shifts require an immediate right shift.
17633 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
17634 break;
17635 llvm_unreachable("invalid shift count for narrowing vector shift "
17636 "intrinsic");
17637
17638 default:
17639 llvm_unreachable("unhandled vector shift");
17640 }
17641
17642 switch (IntNo) {
17643 case Intrinsic::arm_neon_vshifts:
17644 case Intrinsic::arm_neon_vshiftu:
17645 // Opcode already set above.
17646 break;
17647 case Intrinsic::arm_neon_vrshifts:
17648 VShiftOpc = ARMISD::VRSHRsIMM;
17649 break;
17650 case Intrinsic::arm_neon_vrshiftu:
17651 VShiftOpc = ARMISD::VRSHRuIMM;
17652 break;
17653 case Intrinsic::arm_neon_vrshiftn:
17654 VShiftOpc = ARMISD::VRSHRNIMM;
17655 break;
17656 case Intrinsic::arm_neon_vqshifts:
17657 VShiftOpc = ARMISD::VQSHLsIMM;
17658 break;
17659 case Intrinsic::arm_neon_vqshiftu:
17660 VShiftOpc = ARMISD::VQSHLuIMM;
17661 break;
17662 case Intrinsic::arm_neon_vqshiftsu:
17663 VShiftOpc = ARMISD::VQSHLsuIMM;
17664 break;
17665 case Intrinsic::arm_neon_vqshiftns:
17666 VShiftOpc = ARMISD::VQSHRNsIMM;
17667 break;
17668 case Intrinsic::arm_neon_vqshiftnu:
17669 VShiftOpc = ARMISD::VQSHRNuIMM;
17670 break;
17671 case Intrinsic::arm_neon_vqshiftnsu:
17672 VShiftOpc = ARMISD::VQSHRNsuIMM;
17673 break;
17674 case Intrinsic::arm_neon_vqrshiftns:
17675 VShiftOpc = ARMISD::VQRSHRNsIMM;
17676 break;
17677 case Intrinsic::arm_neon_vqrshiftnu:
17678 VShiftOpc = ARMISD::VQRSHRNuIMM;
17679 break;
17680 case Intrinsic::arm_neon_vqrshiftnsu:
17681 VShiftOpc = ARMISD::VQRSHRNsuIMM;
17682 break;
17683 }
17684
17685 SDLoc dl(N);
17686 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17687 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
17688 }
17689
17690 case Intrinsic::arm_neon_vshiftins: {
17691 EVT VT = N->getOperand(1).getValueType();
17692 int64_t Cnt;
17693 unsigned VShiftOpc = 0;
17694
17695 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
17696 VShiftOpc = ARMISD::VSLIIMM;
17697 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
17698 VShiftOpc = ARMISD::VSRIIMM;
17699 else {
17700 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
17701 }
17702
17703 SDLoc dl(N);
17704 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17705 N->getOperand(1), N->getOperand(2),
17706 DAG.getConstant(Cnt, dl, MVT::i32));
17707 }
17708
17709 case Intrinsic::arm_neon_vqrshifts:
17710 case Intrinsic::arm_neon_vqrshiftu:
17711 // No immediate versions of these to check for.
17712 break;
17713
17714 case Intrinsic::arm_neon_vbsl: {
17715 SDLoc dl(N);
17716 return DAG.getNode(ARMISD::VBSP, dl, N->getValueType(0), N->getOperand(1),
17717 N->getOperand(2), N->getOperand(3));
17718 }
17719 case Intrinsic::arm_mve_vqdmlah:
17720 case Intrinsic::arm_mve_vqdmlash:
17721 case Intrinsic::arm_mve_vqrdmlah:
17722 case Intrinsic::arm_mve_vqrdmlash:
17723 case Intrinsic::arm_mve_vmla_n_predicated:
17724 case Intrinsic::arm_mve_vmlas_n_predicated:
17725 case Intrinsic::arm_mve_vqdmlah_predicated:
17726 case Intrinsic::arm_mve_vqdmlash_predicated:
17727 case Intrinsic::arm_mve_vqrdmlah_predicated:
17728 case Intrinsic::arm_mve_vqrdmlash_predicated: {
17729 // These intrinsics all take an i32 scalar operand which is narrowed to the
17730 // size of a single lane of the vector type they return. So we don't need
17731 // any bits of that operand above that point, which allows us to eliminate
17732 // uxth/sxth.
17733 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
17734 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17735 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
17736 return SDValue();
17737 break;
17738 }
17739
17740 case Intrinsic::arm_mve_minv:
17741 case Intrinsic::arm_mve_maxv:
17742 case Intrinsic::arm_mve_minav:
17743 case Intrinsic::arm_mve_maxav:
17744 case Intrinsic::arm_mve_minv_predicated:
17745 case Intrinsic::arm_mve_maxv_predicated:
17746 case Intrinsic::arm_mve_minav_predicated:
17747 case Intrinsic::arm_mve_maxav_predicated: {
17748 // These intrinsics all take an i32 scalar operand which is narrowed to the
17749 // size of a single lane of the vector type they take as the other input.
17750 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
17751 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17752 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17753 return SDValue();
17754 break;
17755 }
17756
17757 case Intrinsic::arm_mve_addv: {
17758 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17759 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17760 bool Unsigned = N->getConstantOperandVal(2);
17761 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17762 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
17763 }
17764
17765 case Intrinsic::arm_mve_addlv:
17766 case Intrinsic::arm_mve_addlv_predicated: {
17767 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17768 // which recombines the two outputs into an i64
17769 bool Unsigned = N->getConstantOperandVal(2);
17770 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17771 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17772 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17773
17775 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17776 if (i != 2) // skip the unsigned flag
17777 Ops.push_back(N->getOperand(i));
17778
17779 SDLoc dl(N);
17780 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
17781 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
17782 val.getValue(1));
17783 }
17784 }
17785
17786 return SDValue();
17787}
17788
17790 EVT VT = Y.getValueType();
17791 if (!VT.isVector())
17792 return hasAndNotCompare(Y);
17793 if (Subtarget->hasMVEIntegerOps())
17794 return VT.is128BitVector();
17795 if (Subtarget->hasNEON())
17796 return VT.is64BitVector() || VT.is128BitVector();
17797 return false;
17798}
17799
17800/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17801/// lowers them. As with the vector shift intrinsics, this is done during DAG
17802/// combining instead of DAG legalizing because the build_vectors for 64-bit
17803/// vector element shift counts are generally not legal, and it is hard to see
17804/// their values after they get legalized to loads from a constant pool.
17807 const ARMSubtarget *ST) {
17808 SelectionDAG &DAG = DCI.DAG;
17809 EVT VT = N->getValueType(0);
17810
17811 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17812 N->getOperand(0)->getOpcode() == ISD::AND &&
17813 N->getOperand(0)->hasOneUse()) {
17814 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17815 return SDValue();
17816 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17817 // usually show up because instcombine prefers to canonicalize it to
17818 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17819 // out of GEP lowering in some cases.
17820 SDValue N0 = N->getOperand(0);
17821 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
17822 if (!ShiftAmtNode)
17823 return SDValue();
17824 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17825 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17826 if (!AndMaskNode)
17827 return SDValue();
17828 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17829 // Don't transform uxtb/uxth.
17830 if (AndMask == 255 || AndMask == 65535)
17831 return SDValue();
17832 if (isMask_32(AndMask)) {
17833 uint32_t MaskedBits = llvm::countl_zero(AndMask);
17834 if (MaskedBits > ShiftAmt) {
17835 SDLoc DL(N);
17836 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
17837 DAG.getConstant(MaskedBits, DL, MVT::i32));
17838 return DAG.getNode(
17839 ISD::SRL, DL, MVT::i32, SHL,
17840 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
17841 }
17842 }
17843 }
17844
17845 // Nothing to be done for scalar shifts.
17846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17847 if (!VT.isVector() || !TLI.isTypeLegal(VT))
17848 return SDValue();
17849 if (ST->hasMVEIntegerOps())
17850 return SDValue();
17851
17852 int64_t Cnt;
17853
17854 switch (N->getOpcode()) {
17855 default: llvm_unreachable("unexpected shift opcode");
17856
17857 case ISD::SHL:
17858 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
17859 SDLoc dl(N);
17860 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
17861 DAG.getConstant(Cnt, dl, MVT::i32));
17862 }
17863 break;
17864
17865 case ISD::SRA:
17866 case ISD::SRL:
17867 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
17868 unsigned VShiftOpc =
17869 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17870 SDLoc dl(N);
17871 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
17872 DAG.getConstant(Cnt, dl, MVT::i32));
17873 }
17874 }
17875 return SDValue();
17876}
17877
17878// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17879// split into multiple extending loads, which are simpler to deal with than an
17880// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17881// to convert the type to an f32.
17883 SDValue N0 = N->getOperand(0);
17884 if (N0.getOpcode() != ISD::LOAD)
17885 return SDValue();
17887 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17888 LD->getExtensionType() != ISD::NON_EXTLOAD)
17889 return SDValue();
17890 EVT FromVT = LD->getValueType(0);
17891 EVT ToVT = N->getValueType(0);
17892 if (!ToVT.isVector())
17893 return SDValue();
17895 EVT ToEltVT = ToVT.getVectorElementType();
17896 EVT FromEltVT = FromVT.getVectorElementType();
17897
17898 unsigned NumElements = 0;
17899 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17900 NumElements = 4;
17901 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17902 NumElements = 4;
17903 if (NumElements == 0 ||
17904 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17905 FromVT.getVectorNumElements() % NumElements != 0 ||
17906 !isPowerOf2_32(NumElements))
17907 return SDValue();
17908
17909 LLVMContext &C = *DAG.getContext();
17910 SDLoc DL(LD);
17911 // Details about the old load
17912 SDValue Ch = LD->getChain();
17913 SDValue BasePtr = LD->getBasePtr();
17914 Align Alignment = LD->getBaseAlign();
17915 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17916 AAMDNodes AAInfo = LD->getAAInfo();
17917
17918 ISD::LoadExtType NewExtType =
17919 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17920 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17921 EVT NewFromVT = EVT::getVectorVT(
17922 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17923 EVT NewToVT = EVT::getVectorVT(
17924 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17925
17928 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17929 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17930 SDValue NewPtr =
17931 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
17932
17933 SDValue NewLoad =
17934 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17935 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17936 Alignment, MMOFlags, AAInfo);
17937 Loads.push_back(NewLoad);
17938 Chains.push_back(SDValue(NewLoad.getNode(), 1));
17939 }
17940
17941 // Float truncs need to extended with VCVTB's into their floating point types.
17942 if (FromEltVT == MVT::f16) {
17944
17945 for (unsigned i = 0; i < Loads.size(); i++) {
17946 SDValue LoadBC =
17947 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
17948 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
17949 DAG.getConstant(0, DL, MVT::i32));
17950 Extends.push_back(FPExt);
17951 }
17952
17953 Loads = Extends;
17954 }
17955
17956 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17957 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17958 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
17959}
17960
17961/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17962/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17964 const ARMSubtarget *ST) {
17965 SDValue N0 = N->getOperand(0);
17966 EVT VT = N->getValueType(0);
17967 SDLoc DL(N);
17968
17969 // Check for sign- and zero-extensions of vector extract operations of 8- and
17970 // 16-bit vector elements. NEON and MVE support these directly. They are
17971 // handled during DAG combining because type legalization will promote them
17972 // to 32-bit types and it is messy to recognize the operations after that.
17973 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17975 SDValue Vec = N0.getOperand(0);
17976 SDValue Lane = N0.getOperand(1);
17977 EVT EltVT = N0.getValueType();
17978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17979
17980 if (VT == MVT::i32 &&
17981 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17982 TLI.isTypeLegal(Vec.getValueType()) &&
17983 isa<ConstantSDNode>(Lane)) {
17984
17985 unsigned Opc = 0;
17986 switch (N->getOpcode()) {
17987 default: llvm_unreachable("unexpected opcode");
17988 case ISD::SIGN_EXTEND:
17989 Opc = ARMISD::VGETLANEs;
17990 break;
17991 case ISD::ZERO_EXTEND:
17992 case ISD::ANY_EXTEND:
17993 Opc = ARMISD::VGETLANEu;
17994 break;
17995 }
17996 return DAG.getNode(Opc, DL, VT, Vec, Lane);
17997 }
17998 }
17999
18000 if (ST->hasMVEIntegerOps())
18001 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18002 return NewLoad;
18003
18004 // Combine sext(buildvector(..)) to buildvector(sext(..)) to help avoid
18005 // difficult to lower i1 buildvector.
18006 if (ST->hasMVEIntegerOps() && N0.getValueType().getScalarSizeInBits() == 1 &&
18007 N0.getOpcode() == ISD::BUILD_VECTOR && VT.getScalarSizeInBits() <= 32) {
18009 for (unsigned I = 0; I < N0.getNumOperands(); I++) {
18010 SDValue InReg = N0.getOperand(I);
18011 if (N->getOpcode() == ISD::ZERO_EXTEND)
18012 InReg = DAG.getNode(ISD::AND, DL, InReg.getValueType(), InReg,
18013 DAG.getConstant(1, DL, InReg.getValueType()));
18014 else if (N->getOpcode() == ISD::SIGN_EXTEND)
18015 InReg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InReg.getValueType(),
18016 InReg, DAG.getValueType(MVT::i1));
18017 SDValue Ext = DAG.getNode(N->getOpcode(), DL, MVT::i32, InReg);
18018 Ops.push_back(Ext);
18019 }
18020 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
18021 }
18022
18023 return SDValue();
18024}
18025
18027 const ARMSubtarget *ST) {
18028 if (ST->hasMVEFloatOps())
18029 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18030 return NewLoad;
18031
18032 return SDValue();
18033}
18034
18035// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
18036// constant bounds.
18038 const ARMSubtarget *Subtarget) {
18039 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
18040 !Subtarget->isThumb2())
18041 return SDValue();
18042
18043 EVT VT = Op.getValueType();
18044 SDValue Op0 = Op.getOperand(0);
18045
18046 if (VT != MVT::i32 ||
18047 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
18048 !isa<ConstantSDNode>(Op.getOperand(1)) ||
18050 return SDValue();
18051
18052 SDValue Min = Op;
18053 SDValue Max = Op0;
18054 SDValue Input = Op0.getOperand(0);
18055 if (Min.getOpcode() == ISD::SMAX)
18056 std::swap(Min, Max);
18057
18058 APInt MinC = Min.getConstantOperandAPInt(1);
18059 APInt MaxC = Max.getConstantOperandAPInt(1);
18060
18061 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
18062 !(MinC + 1).isPowerOf2())
18063 return SDValue();
18064
18065 SDLoc DL(Op);
18066 if (MinC == ~MaxC)
18067 return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
18068 DAG.getConstant(MinC.countr_one(), DL, VT));
18069 if (MaxC == 0)
18070 return DAG.getNode(ARMISD::USAT, DL, VT, Input,
18071 DAG.getConstant(MinC.countr_one(), DL, VT));
18072
18073 return SDValue();
18074}
18075
18076/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
18077/// saturates.
18079 const ARMSubtarget *ST) {
18080 EVT VT = N->getValueType(0);
18081 SDValue N0 = N->getOperand(0);
18082
18083 if (VT == MVT::i32)
18084 return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
18085
18086 if (!ST->hasMVEIntegerOps())
18087 return SDValue();
18088
18089 if (SDValue V = PerformVQDMULHCombine(N, DAG))
18090 return V;
18091
18092 if (VT != MVT::v4i32 && VT != MVT::v8i16)
18093 return SDValue();
18094
18095 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
18096 // Check one is a smin and the other is a smax
18097 if (Min->getOpcode() != ISD::SMIN)
18098 std::swap(Min, Max);
18099 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
18100 return false;
18101
18102 APInt SaturateC;
18103 if (VT == MVT::v4i32)
18104 SaturateC = APInt(32, (1 << 15) - 1, true);
18105 else //if (VT == MVT::v8i16)
18106 SaturateC = APInt(16, (1 << 7) - 1, true);
18107
18108 APInt MinC, MaxC;
18109 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
18110 MinC != SaturateC)
18111 return false;
18112 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
18113 MaxC != ~SaturateC)
18114 return false;
18115 return true;
18116 };
18117
18118 if (IsSignedSaturate(N, N0.getNode())) {
18119 SDLoc DL(N);
18120 MVT ExtVT, HalfVT;
18121 if (VT == MVT::v4i32) {
18122 HalfVT = MVT::v8i16;
18123 ExtVT = MVT::v4i16;
18124 } else { // if (VT == MVT::v8i16)
18125 HalfVT = MVT::v16i8;
18126 ExtVT = MVT::v8i8;
18127 }
18128
18129 // Create a VQMOVNB with undef top lanes, then signed extended into the top
18130 // half. That extend will hopefully be removed if only the bottom bits are
18131 // demanded (though a truncating store, for example).
18132 SDValue VQMOVN =
18133 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
18134 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
18135 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18136 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
18137 DAG.getValueType(ExtVT));
18138 }
18139
18140 auto IsUnsignedSaturate = [&](SDNode *Min) {
18141 // For unsigned, we just need to check for <= 0xffff
18142 if (Min->getOpcode() != ISD::UMIN)
18143 return false;
18144
18145 APInt SaturateC;
18146 if (VT == MVT::v4i32)
18147 SaturateC = APInt(32, (1 << 16) - 1, true);
18148 else //if (VT == MVT::v8i16)
18149 SaturateC = APInt(16, (1 << 8) - 1, true);
18150
18151 APInt MinC;
18152 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
18153 MinC != SaturateC)
18154 return false;
18155 return true;
18156 };
18157
18158 if (IsUnsignedSaturate(N)) {
18159 SDLoc DL(N);
18160 MVT HalfVT;
18161 unsigned ExtConst;
18162 if (VT == MVT::v4i32) {
18163 HalfVT = MVT::v8i16;
18164 ExtConst = 0x0000FFFF;
18165 } else { //if (VT == MVT::v8i16)
18166 HalfVT = MVT::v16i8;
18167 ExtConst = 0x00FF;
18168 }
18169
18170 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18171 // an AND. That extend will hopefully be removed if only the bottom bits are
18172 // demanded (though a truncating store, for example).
18173 SDValue VQMOVN =
18174 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
18175 DAG.getConstant(0, DL, MVT::i32));
18176 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18177 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
18178 DAG.getConstant(ExtConst, DL, VT));
18179 }
18180
18181 return SDValue();
18182}
18183
18186 if (!C)
18187 return nullptr;
18188 const APInt *CV = &C->getAPIntValue();
18189 return CV->isPowerOf2() ? CV : nullptr;
18190}
18191
18193 // If we have a CMOV, OR and AND combination such as:
18194 // if (x & CN)
18195 // y |= CM;
18196 //
18197 // And:
18198 // * CN is a single bit;
18199 // * All bits covered by CM are known zero in y
18200 //
18201 // Then we can convert this into a sequence of BFI instructions. This will
18202 // always be a win if CM is a single bit, will always be no worse than the
18203 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18204 // three bits (due to the extra IT instruction).
18205
18206 SDValue Op0 = CMOV->getOperand(0);
18207 SDValue Op1 = CMOV->getOperand(1);
18208 auto CC = CMOV->getConstantOperandAPInt(2).getLimitedValue();
18209 SDValue CmpZ = CMOV->getOperand(3);
18210
18211 // The compare must be against zero.
18212 if (!isNullConstant(CmpZ->getOperand(1)))
18213 return SDValue();
18214
18215 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18216 SDValue And = CmpZ->getOperand(0);
18217 if (And->getOpcode() != ISD::AND)
18218 return SDValue();
18219 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
18220 if (!AndC)
18221 return SDValue();
18222 SDValue X = And->getOperand(0);
18223
18224 if (CC == ARMCC::EQ) {
18225 // We're performing an "equal to zero" compare. Swap the operands so we
18226 // canonicalize on a "not equal to zero" compare.
18227 std::swap(Op0, Op1);
18228 } else {
18229 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18230 }
18231
18232 if (Op1->getOpcode() != ISD::OR)
18233 return SDValue();
18234
18236 if (!OrC)
18237 return SDValue();
18238 SDValue Y = Op1->getOperand(0);
18239
18240 if (Op0 != Y)
18241 return SDValue();
18242
18243 // Now, is it profitable to continue?
18244 APInt OrCI = OrC->getAPIntValue();
18245 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18246 if (OrCI.popcount() > Heuristic)
18247 return SDValue();
18248
18249 // Lastly, can we determine that the bits defined by OrCI
18250 // are zero in Y?
18251 KnownBits Known = DAG.computeKnownBits(Y);
18252 if ((OrCI & Known.Zero) != OrCI)
18253 return SDValue();
18254
18255 // OK, we can do the combine.
18256 SDValue V = Y;
18257 SDLoc dl(X);
18258 EVT VT = X.getValueType();
18259 unsigned BitInX = AndC->logBase2();
18260
18261 if (BitInX != 0) {
18262 // We must shift X first.
18263 X = DAG.getNode(ISD::SRL, dl, VT, X,
18264 DAG.getConstant(BitInX, dl, VT));
18265 }
18266
18267 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18268 BitInY < NumActiveBits; ++BitInY) {
18269 if (OrCI[BitInY] == 0)
18270 continue;
18271 APInt Mask(VT.getSizeInBits(), 0);
18272 Mask.setBit(BitInY);
18273 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
18274 // Confusingly, the operand is an *inverted* mask.
18275 DAG.getConstant(~Mask, dl, VT));
18276 }
18277
18278 return V;
18279}
18280
18281// Given N, the value controlling the conditional branch, search for the loop
18282// intrinsic, returning it, along with how the value is used. We need to handle
18283// patterns such as the following:
18284// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18285// (brcond (setcc (loop.decrement), 0, eq), exit)
18286// (brcond (setcc (loop.decrement), 0, ne), header)
18288 bool &Negate) {
18289 switch (N->getOpcode()) {
18290 default:
18291 break;
18292 case ISD::XOR: {
18293 if (!isa<ConstantSDNode>(N.getOperand(1)))
18294 return SDValue();
18295 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
18296 return SDValue();
18297 Negate = !Negate;
18298 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
18299 }
18300 case ISD::SETCC: {
18301 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
18302 if (!Const)
18303 return SDValue();
18304 if (Const->isZero())
18305 Imm = 0;
18306 else if (Const->isOne())
18307 Imm = 1;
18308 else
18309 return SDValue();
18310 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
18311 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
18312 }
18314 unsigned IntOp = N.getConstantOperandVal(1);
18315 if (IntOp != Intrinsic::test_start_loop_iterations &&
18316 IntOp != Intrinsic::loop_decrement_reg)
18317 return SDValue();
18318 return N;
18319 }
18320 }
18321 return SDValue();
18322}
18323
18326 const ARMSubtarget *ST) {
18327
18328 // The hwloop intrinsics that we're interested are used for control-flow,
18329 // either for entering or exiting the loop:
18330 // - test.start.loop.iterations will test whether its operand is zero. If it
18331 // is zero, the proceeding branch should not enter the loop.
18332 // - loop.decrement.reg also tests whether its operand is zero. If it is
18333 // zero, the proceeding branch should not branch back to the beginning of
18334 // the loop.
18335 // So here, we need to check that how the brcond is using the result of each
18336 // of the intrinsics to ensure that we're branching to the right place at the
18337 // right time.
18338
18339 ISD::CondCode CC;
18340 SDValue Cond;
18341 int Imm = 1;
18342 bool Negate = false;
18343 SDValue Chain = N->getOperand(0);
18344 SDValue Dest;
18345
18346 if (N->getOpcode() == ISD::BRCOND) {
18347 CC = ISD::SETEQ;
18348 Cond = N->getOperand(1);
18349 Dest = N->getOperand(2);
18350 } else {
18351 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18352 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18353 Cond = N->getOperand(2);
18354 Dest = N->getOperand(4);
18355 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
18356 if (!Const->isOne() && !Const->isZero())
18357 return SDValue();
18358 Imm = Const->getZExtValue();
18359 } else
18360 return SDValue();
18361 }
18362
18363 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
18364 if (!Int)
18365 return SDValue();
18366
18367 if (Negate)
18368 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
18369
18370 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18371 return (CC == ISD::SETEQ && Imm == 0) ||
18372 (CC == ISD::SETNE && Imm == 1) ||
18373 (CC == ISD::SETLT && Imm == 1) ||
18374 (CC == ISD::SETULT && Imm == 1);
18375 };
18376
18377 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18378 return (CC == ISD::SETEQ && Imm == 1) ||
18379 (CC == ISD::SETNE && Imm == 0) ||
18380 (CC == ISD::SETGT && Imm == 0) ||
18381 (CC == ISD::SETUGT && Imm == 0) ||
18382 (CC == ISD::SETGE && Imm == 1) ||
18383 (CC == ISD::SETUGE && Imm == 1);
18384 };
18385
18386 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18387 "unsupported condition");
18388
18389 SDLoc dl(Int);
18390 SelectionDAG &DAG = DCI.DAG;
18391 SDValue Elements = Int.getOperand(2);
18392 unsigned IntOp = Int->getConstantOperandVal(1);
18393 assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18394 "expected single br user");
18395 SDNode *Br = *N->user_begin();
18396 SDValue OtherTarget = Br->getOperand(1);
18397
18398 // Update the unconditional branch to branch to the given Dest.
18399 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18400 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
18401 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
18402 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
18403 };
18404
18405 if (IntOp == Intrinsic::test_start_loop_iterations) {
18406 SDValue Res;
18407 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
18408 // We expect this 'instruction' to branch when the counter is zero.
18409 if (IsTrueIfZero(CC, Imm)) {
18410 SDValue Ops[] = {Chain, Setup, Dest};
18411 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18412 } else {
18413 // The logic is the reverse of what we need for WLS, so find the other
18414 // basic block target: the target of the proceeding br.
18415 UpdateUncondBr(Br, Dest, DAG);
18416
18417 SDValue Ops[] = {Chain, Setup, OtherTarget};
18418 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18419 }
18420 // Update LR count to the new value
18421 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18422 // Update chain
18423 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18424 return Res;
18425 } else {
18426 SDValue Size =
18427 DAG.getTargetConstant(Int.getConstantOperandVal(3), dl, MVT::i32);
18428 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18429 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18430 DAG.getVTList(MVT::i32, MVT::Other), Args);
18431 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18432
18433 // We expect this instruction to branch when the count is not zero.
18434 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18435
18436 // Update the unconditional branch to target the loop preheader if we've
18437 // found the condition has been reversed.
18438 if (Target == OtherTarget)
18439 UpdateUncondBr(Br, Dest, DAG);
18440
18441 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18442 SDValue(LoopDec.getNode(), 1), Chain);
18443
18444 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18445 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18446 }
18447 return SDValue();
18448}
18449
18450/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18451SDValue
18453 SDValue Cmp = N->getOperand(3);
18454 if (Cmp.getOpcode() != ARMISD::CMPZ)
18455 // Only looking at NE cases.
18456 return SDValue();
18457
18458 SDLoc dl(N);
18459 SDValue LHS = Cmp.getOperand(0);
18460 SDValue RHS = Cmp.getOperand(1);
18461 SDValue Chain = N->getOperand(0);
18462 SDValue BB = N->getOperand(1);
18463 SDValue ARMcc = N->getOperand(2);
18465
18466 // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18467 // -> (brcond Chain BB CC Flags)
18468 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18469 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18470 LHS->getOperand(0)->hasOneUse() &&
18471 isNullConstant(LHS->getOperand(0)->getOperand(0)) &&
18472 isOneConstant(LHS->getOperand(0)->getOperand(1)) &&
18473 isOneConstant(LHS->getOperand(1)) && isNullConstant(RHS)) {
18474 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, BB,
18475 LHS->getOperand(0)->getOperand(2),
18476 LHS->getOperand(0)->getOperand(3));
18477 }
18478
18479 return SDValue();
18480}
18481
18482/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18483SDValue
18485 SDLoc dl(N);
18486 EVT VT = N->getValueType(0);
18487 SDValue FalseVal = N->getOperand(0);
18488 SDValue TrueVal = N->getOperand(1);
18489 SDValue ARMcc = N->getOperand(2);
18490 SDValue Cmp = N->getOperand(3);
18491
18492 // Try to form CSINV etc.
18493 unsigned Opcode;
18494 bool InvertCond;
18495 if (SDValue CSetOp =
18496 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
18497 if (InvertCond) {
18498 ARMCC::CondCodes CondCode =
18499 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
18500 CondCode = ARMCC::getOppositeCondition(CondCode);
18501 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
18502 }
18503 return DAG.getNode(Opcode, dl, VT, CSetOp, CSetOp, ARMcc, Cmp);
18504 }
18505
18506 if (Cmp.getOpcode() != ARMISD::CMPZ)
18507 // Only looking at EQ and NE cases.
18508 return SDValue();
18509
18510 SDValue LHS = Cmp.getOperand(0);
18511 SDValue RHS = Cmp.getOperand(1);
18513
18514 // BFI is only available on V6T2+.
18515 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18517 if (R)
18518 return R;
18519 }
18520
18521 // Simplify
18522 // mov r1, r0
18523 // cmp r1, x
18524 // mov r0, y
18525 // moveq r0, x
18526 // to
18527 // cmp r0, x
18528 // movne r0, y
18529 //
18530 // mov r1, r0
18531 // cmp r1, x
18532 // mov r0, x
18533 // movne r0, y
18534 // to
18535 // cmp r0, x
18536 // movne r0, y
18537 /// FIXME: Turn this into a target neutral optimization?
18538 SDValue Res;
18539 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18540 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, Cmp);
18541 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18542 SDValue ARMcc;
18543 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
18544 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, NewCmp);
18545 }
18546
18547 // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
18548 // -> (cmov F T CC Flags)
18549 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18550 isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
18551 isNullConstant(RHS)) {
18552 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
18553 LHS->getOperand(2), LHS->getOperand(3));
18554 }
18555
18556 if (!VT.isInteger())
18557 return SDValue();
18558
18559 // Fold away an unnecessary CMPZ/CMOV
18560 // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18561 // if C1==EQ -> CMOV A, B, C2, D
18562 // if C1==NE -> CMOV A, B, NOT(C2), D
18563 if (N->getConstantOperandVal(2) == ARMCC::EQ ||
18564 N->getConstantOperandVal(2) == ARMCC::NE) {
18566 if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
18567 if (N->getConstantOperandVal(2) == ARMCC::NE)
18569 return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
18570 N->getOperand(1),
18571 DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
18572 }
18573 }
18574
18575 // Materialize a boolean comparison for integers so we can avoid branching.
18576 if (isNullConstant(FalseVal)) {
18577 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
18578 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18579 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18580 // right 5 bits will make that 32 be 1, otherwise it will be 0.
18581 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18582 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18583 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
18584 DAG.getConstant(5, dl, MVT::i32));
18585 } else {
18586 // CMOV 0, 1, ==, (CMPZ x, y) ->
18587 // (UADDO_CARRY (SUB x, y), t:0, t:1)
18588 // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18589 //
18590 // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18591 // x != y. In other words, a carry C == 1 when x == y, C == 0
18592 // otherwise.
18593 // The final UADDO_CARRY computes
18594 // x - y + (0 - (x - y)) + C == C
18595 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18596 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18597 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
18598 // ISD::USUBO_CARRY returns a borrow but we want the carry here
18599 // actually.
18600 SDValue Carry =
18601 DAG.getNode(ISD::SUB, dl, MVT::i32,
18602 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
18603 Res = DAG.getNode(ISD::UADDO_CARRY, dl, VTs, Sub, Neg, Carry);
18604 }
18605 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
18606 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
18607 // This seems pointless but will allow us to combine it further below.
18608 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18609 SDValue Sub =
18610 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18611 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
18612 Sub.getValue(1));
18613 FalseVal = Sub;
18614 }
18615 } else if (isNullConstant(TrueVal)) {
18616 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
18617 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
18618 // This seems pointless but will allow us to combine it further below
18619 // Note that we change == for != as this is the dual for the case above.
18620 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18621 SDValue Sub =
18622 DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18623 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
18624 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
18625 Sub.getValue(1));
18626 FalseVal = Sub;
18627 }
18628 }
18629
18630 // On Thumb1, the DAG above may be further combined if z is a power of 2
18631 // (z == 2 ^ K).
18632 // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
18633 // t1 = (USUBO (SUB x, y), 1)
18634 // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
18635 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18636 //
18637 // This also handles the special case of comparing against zero; it's
18638 // essentially, the same pattern, except there's no SUBC:
18639 // CMOV x, z, !=, (CMPZ x, 0) ->
18640 // t1 = (USUBO x, 1)
18641 // t2 = (USUBO_CARRY x, t1:0, t1:1)
18642 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18643 const APInt *TrueConst;
18644 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18645 ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(0) == LHS &&
18646 FalseVal.getOperand(1) == RHS) ||
18647 (FalseVal == LHS && isNullConstant(RHS))) &&
18648 (TrueConst = isPowerOf2Constant(TrueVal))) {
18649 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18650 unsigned ShiftAmount = TrueConst->logBase2();
18651 if (ShiftAmount)
18652 TrueVal = DAG.getConstant(1, dl, VT);
18653 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
18654 Res = DAG.getNode(ISD::USUBO_CARRY, dl, VTs, FalseVal, Subc,
18655 Subc.getValue(1));
18656
18657 if (ShiftAmount)
18658 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
18659 DAG.getConstant(ShiftAmount, dl, MVT::i32));
18660 }
18661
18662 if (Res.getNode()) {
18663 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
18664 // Capture demanded bits information that would be otherwise lost.
18665 if (Known.Zero == 0xfffffffe)
18666 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18667 DAG.getValueType(MVT::i1));
18668 else if (Known.Zero == 0xffffff00)
18669 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18670 DAG.getValueType(MVT::i8));
18671 else if (Known.Zero == 0xffff0000)
18672 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18673 DAG.getValueType(MVT::i16));
18674 }
18675
18676 return Res;
18677}
18678
18681 const ARMSubtarget *ST) {
18682 SelectionDAG &DAG = DCI.DAG;
18683 SDValue Src = N->getOperand(0);
18684 EVT DstVT = N->getValueType(0);
18685
18686 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18687 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18688 EVT SrcVT = Src.getValueType();
18689 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18690 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
18691 }
18692
18693 // We may have a bitcast of something that has already had this bitcast
18694 // combine performed on it, so skip past any VECTOR_REG_CASTs.
18695 if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
18696 Src.getOperand(0).getValueType().getScalarSizeInBits() <=
18697 Src.getValueType().getScalarSizeInBits())
18698 Src = Src.getOperand(0);
18699
18700 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18701 // would be generated is at least the width of the element type.
18702 EVT SrcVT = Src.getValueType();
18703 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18704 Src.getOpcode() == ARMISD::VMVNIMM ||
18705 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18706 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18707 DAG.getDataLayout().isBigEndian())
18708 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
18709
18710 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
18711 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18712 return R;
18713
18714 return SDValue();
18715}
18716
18717// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18718// node into stack operations after legalizeOps.
18721 SelectionDAG &DAG = DCI.DAG;
18722 EVT VT = N->getValueType(0);
18723 SDLoc DL(N);
18724
18725 // MVETrunc(Undef, Undef) -> Undef
18726 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
18727 return DAG.getUNDEF(VT);
18728
18729 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18730 if (N->getNumOperands() == 2 &&
18731 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
18732 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
18733 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
18734 N->getOperand(0).getOperand(1),
18735 N->getOperand(1).getOperand(0),
18736 N->getOperand(1).getOperand(1));
18737
18738 // MVETrunc(shuffle, shuffle) -> VMOVN
18739 if (N->getNumOperands() == 2 &&
18740 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18741 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18742 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
18743 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
18744
18745 if (S0->getOperand(0) == S1->getOperand(0) &&
18746 S0->getOperand(1) == S1->getOperand(1)) {
18747 // Construct complete shuffle mask
18748 SmallVector<int, 8> Mask(S0->getMask());
18749 Mask.append(S1->getMask().begin(), S1->getMask().end());
18750
18751 if (isVMOVNTruncMask(Mask, VT, false))
18752 return DAG.getNode(
18753 ARMISD::VMOVN, DL, VT,
18754 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18755 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18756 DAG.getConstant(1, DL, MVT::i32));
18757 if (isVMOVNTruncMask(Mask, VT, true))
18758 return DAG.getNode(
18759 ARMISD::VMOVN, DL, VT,
18760 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18761 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18762 DAG.getConstant(1, DL, MVT::i32));
18763 }
18764 }
18765
18766 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18767 // truncate to a buildvector to allow the generic optimisations to kick in.
18768 if (all_of(N->ops(), [](SDValue Op) {
18769 return Op.getOpcode() == ISD::BUILD_VECTOR ||
18770 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18771 (Op.getOpcode() == ISD::BITCAST &&
18772 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
18773 })) {
18774 SmallVector<SDValue, 8> Extracts;
18775 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18776 SDValue O = N->getOperand(Op);
18777 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18778 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
18779 DAG.getConstant(i, DL, MVT::i32));
18780 Extracts.push_back(Ext);
18781 }
18782 }
18783 return DAG.getBuildVector(VT, DL, Extracts);
18784 }
18785
18786 // If we are late in the legalization process and nothing has optimised
18787 // the trunc to anything better, lower it to a stack store and reload,
18788 // performing the truncation whilst keeping the lanes in the correct order:
18789 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18790 if (!DCI.isAfterLegalizeDAG())
18791 return SDValue();
18792
18793 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18794 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18795 int NumIns = N->getNumOperands();
18796 assert((NumIns == 2 || NumIns == 4) &&
18797 "Expected 2 or 4 inputs to an MVETrunc");
18798 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18799 if (N->getNumOperands() == 4)
18800 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
18801
18802 SmallVector<SDValue> Chains;
18803 for (int I = 0; I < NumIns; I++) {
18804 SDValue Ptr = DAG.getNode(
18805 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18806 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
18808 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
18809 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
18810 Ptr, MPI, StoreVT, Align(4));
18811 Chains.push_back(Ch);
18812 }
18813
18814 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18815 MachinePointerInfo MPI =
18817 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
18818}
18819
18820// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18822 SelectionDAG &DAG) {
18823 SDValue N0 = N->getOperand(0);
18825 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18826 return SDValue();
18827
18828 EVT FromVT = LD->getMemoryVT();
18829 EVT ToVT = N->getValueType(0);
18830 if (!ToVT.isVector())
18831 return SDValue();
18832 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
18833 EVT ToEltVT = ToVT.getVectorElementType();
18834 EVT FromEltVT = FromVT.getVectorElementType();
18835
18836 unsigned NumElements = 0;
18837 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18838 NumElements = 4;
18839 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18840 NumElements = 8;
18841 assert(NumElements != 0);
18842
18843 ISD::LoadExtType NewExtType =
18844 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18845 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18846 LD->getExtensionType() != ISD::EXTLOAD &&
18847 LD->getExtensionType() != NewExtType)
18848 return SDValue();
18849
18850 LLVMContext &C = *DAG.getContext();
18851 SDLoc DL(LD);
18852 // Details about the old load
18853 SDValue Ch = LD->getChain();
18854 SDValue BasePtr = LD->getBasePtr();
18855 Align Alignment = LD->getBaseAlign();
18856 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18857 AAMDNodes AAInfo = LD->getAAInfo();
18858
18859 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
18860 EVT NewFromVT = EVT::getVectorVT(
18861 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18862 EVT NewToVT = EVT::getVectorVT(
18863 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18864
18867 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18868 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18869 SDValue NewPtr =
18870 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
18871
18872 SDValue NewLoad =
18873 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18874 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18875 Alignment, MMOFlags, AAInfo);
18876 Loads.push_back(NewLoad);
18877 Chains.push_back(SDValue(NewLoad.getNode(), 1));
18878 }
18879
18880 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18881 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18882 return DAG.getMergeValues(Loads, DL);
18883}
18884
18885// Perform combines for MVEEXT. If it has not be optimized to anything better
18886// before lowering, it gets converted to stack store and extloads performing the
18887// extend whilst still keeping the same lane ordering.
18890 SelectionDAG &DAG = DCI.DAG;
18891 EVT VT = N->getValueType(0);
18892 SDLoc DL(N);
18893 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
18894 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
18895
18896 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18897 *DAG.getContext());
18898 auto Extend = [&](SDValue V) {
18899 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
18900 return N->getOpcode() == ARMISD::MVESEXT
18901 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
18902 DAG.getValueType(ExtVT))
18903 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
18904 };
18905
18906 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18907 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
18908 SDValue Ext = Extend(N->getOperand(0));
18909 return DAG.getMergeValues({Ext, Ext}, DL);
18910 }
18911
18912 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18913 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
18914 ArrayRef<int> Mask = SVN->getMask();
18915 assert(Mask.size() == 2 * VT.getVectorNumElements());
18916 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
18917 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18918 SDValue Op0 = SVN->getOperand(0);
18919 SDValue Op1 = SVN->getOperand(1);
18920
18921 auto CheckInregMask = [&](int Start, int Offset) {
18922 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18923 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18924 return false;
18925 return true;
18926 };
18927 SDValue V0 = SDValue(N, 0);
18928 SDValue V1 = SDValue(N, 1);
18929 if (CheckInregMask(0, 0))
18930 V0 = Extend(Op0);
18931 else if (CheckInregMask(0, 1))
18932 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18933 else if (CheckInregMask(0, Mask.size()))
18934 V0 = Extend(Op1);
18935 else if (CheckInregMask(0, Mask.size() + 1))
18936 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18937
18938 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18939 V1 = Extend(Op1);
18940 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18941 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18942 else if (CheckInregMask(VT.getVectorNumElements(), 0))
18943 V1 = Extend(Op0);
18944 else if (CheckInregMask(VT.getVectorNumElements(), 1))
18945 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18946
18947 if (V0.getNode() != N || V1.getNode() != N)
18948 return DAG.getMergeValues({V0, V1}, DL);
18949 }
18950
18951 // MVEEXT(load) -> extload, extload
18952 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
18954 return L;
18955
18956 if (!DCI.isAfterLegalizeDAG())
18957 return SDValue();
18958
18959 // Lower to a stack store and reload:
18960 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18961 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18962 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18963 int NumOuts = N->getNumValues();
18964 assert((NumOuts == 2 || NumOuts == 4) &&
18965 "Expected 2 or 4 outputs to an MVEEXT");
18966 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18967 *DAG.getContext());
18968 if (N->getNumOperands() == 4)
18969 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
18970
18971 MachinePointerInfo MPI =
18973 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
18974 StackPtr, MPI, Align(4));
18975
18977 for (int I = 0; I < NumOuts; I++) {
18978 SDValue Ptr = DAG.getNode(
18979 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18980 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
18982 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
18983 SDValue Load = DAG.getExtLoad(
18984 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
18985 VT, Chain, Ptr, MPI, LoadVT, Align(4));
18986 Loads.push_back(Load);
18987 }
18988
18989 return DAG.getMergeValues(Loads, DL);
18990}
18991
18993 DAGCombinerInfo &DCI) const {
18994 switch (N->getOpcode()) {
18995 default: break;
18996 case ISD::SELECT_CC:
18997 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
18998 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
18999 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
19000 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
19001 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
19002 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
19003 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
19004 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
19005 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
19006 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
19007 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
19008 case ISD::BRCOND:
19009 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
19010 case ARMISD::ADDC:
19011 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
19012 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
19013 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
19014 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
19015 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
19016 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
19017 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
19018 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
19019 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
19022 return PerformExtractEltCombine(N, DCI, Subtarget);
19026 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
19027 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
19028 case ISD::FP_TO_SINT:
19029 case ISD::FP_TO_UINT:
19030 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
19031 case ISD::FADD:
19032 return PerformFADDCombine(N, DCI.DAG, Subtarget);
19033 case ISD::FMUL:
19034 return PerformVMulVCTPCombine(N, DCI.DAG, Subtarget);
19036 return PerformIntrinsicCombine(N, DCI);
19037 case ISD::SHL:
19038 case ISD::SRA:
19039 case ISD::SRL:
19040 return PerformShiftCombine(N, DCI, Subtarget);
19041 case ISD::SIGN_EXTEND:
19042 case ISD::ZERO_EXTEND:
19043 case ISD::ANY_EXTEND:
19044 return PerformExtendCombine(N, DCI.DAG, Subtarget);
19045 case ISD::FP_EXTEND:
19046 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
19047 case ISD::SMIN:
19048 case ISD::UMIN:
19049 case ISD::SMAX:
19050 case ISD::UMAX:
19051 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
19052 case ARMISD::CMOV:
19053 return PerformCMOVCombine(N, DCI.DAG);
19054 case ARMISD::BRCOND:
19055 return PerformBRCONDCombine(N, DCI.DAG);
19056 case ARMISD::CMPZ:
19057 return PerformCMPZCombine(N, DCI.DAG);
19058 case ARMISD::CSINC:
19059 case ARMISD::CSINV:
19060 case ARMISD::CSNEG:
19061 return PerformCSETCombine(N, DCI.DAG);
19062 case ISD::LOAD:
19063 return PerformLOADCombine(N, DCI, Subtarget);
19064 case ARMISD::VLD1DUP:
19065 case ARMISD::VLD2DUP:
19066 case ARMISD::VLD3DUP:
19067 case ARMISD::VLD4DUP:
19068 return PerformVLDCombine(N, DCI);
19070 return PerformARMBUILD_VECTORCombine(N, DCI);
19071 case ISD::BITCAST:
19072 return PerformBITCASTCombine(N, DCI, Subtarget);
19073 case ARMISD::PREDICATE_CAST:
19074 return PerformPREDICATE_CASTCombine(N, DCI);
19075 case ARMISD::VECTOR_REG_CAST:
19076 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
19077 case ARMISD::MVETRUNC:
19078 return PerformMVETruncCombine(N, DCI);
19079 case ARMISD::MVESEXT:
19080 case ARMISD::MVEZEXT:
19081 return PerformMVEExtCombine(N, DCI);
19082 case ARMISD::VCMP:
19083 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
19084 case ISD::VECREDUCE_ADD:
19085 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
19086 case ARMISD::VADDVs:
19087 case ARMISD::VADDVu:
19088 case ARMISD::VADDLVs:
19089 case ARMISD::VADDLVu:
19090 case ARMISD::VADDLVAs:
19091 case ARMISD::VADDLVAu:
19092 case ARMISD::VMLAVs:
19093 case ARMISD::VMLAVu:
19094 case ARMISD::VMLALVs:
19095 case ARMISD::VMLALVu:
19096 case ARMISD::VMLALVAs:
19097 case ARMISD::VMLALVAu:
19098 return PerformReduceShuffleCombine(N, DCI.DAG);
19099 case ARMISD::VMOVN:
19100 return PerformVMOVNCombine(N, DCI);
19101 case ARMISD::VQMOVNs:
19102 case ARMISD::VQMOVNu:
19103 return PerformVQMOVNCombine(N, DCI);
19104 case ARMISD::VQDMULH:
19105 return PerformVQDMULHCombine(N, DCI);
19106 case ARMISD::ASRL:
19107 case ARMISD::LSRL:
19108 case ARMISD::LSLL:
19109 return PerformLongShiftCombine(N, DCI.DAG);
19110 case ARMISD::SMULWB: {
19111 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19112 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19113 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19114 return SDValue();
19115 break;
19116 }
19117 case ARMISD::SMULWT: {
19118 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19119 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19120 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19121 return SDValue();
19122 break;
19123 }
19124 case ARMISD::SMLALBB:
19125 case ARMISD::QADD16b:
19126 case ARMISD::QSUB16b:
19127 case ARMISD::UQADD16b:
19128 case ARMISD::UQSUB16b: {
19129 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19130 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19131 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19132 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19133 return SDValue();
19134 break;
19135 }
19136 case ARMISD::SMLALBT: {
19137 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
19138 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19139 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
19140 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19141 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
19142 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
19143 return SDValue();
19144 break;
19145 }
19146 case ARMISD::SMLALTB: {
19147 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
19148 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19149 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
19150 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19151 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
19152 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
19153 return SDValue();
19154 break;
19155 }
19156 case ARMISD::SMLALTT: {
19157 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19158 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19159 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19160 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19161 return SDValue();
19162 break;
19163 }
19164 case ARMISD::QADD8b:
19165 case ARMISD::QSUB8b:
19166 case ARMISD::UQADD8b:
19167 case ARMISD::UQSUB8b: {
19168 unsigned BitWidth = N->getValueType(0).getSizeInBits();
19169 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
19170 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19171 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19172 return SDValue();
19173 break;
19174 }
19175 case ARMISD::VBSP:
19176 if (N->getOperand(1) == N->getOperand(2))
19177 return N->getOperand(1);
19178 return SDValue();
19181 switch (N->getConstantOperandVal(1)) {
19182 case Intrinsic::arm_neon_vld1:
19183 case Intrinsic::arm_neon_vld1x2:
19184 case Intrinsic::arm_neon_vld1x3:
19185 case Intrinsic::arm_neon_vld1x4:
19186 case Intrinsic::arm_neon_vld2:
19187 case Intrinsic::arm_neon_vld3:
19188 case Intrinsic::arm_neon_vld4:
19189 case Intrinsic::arm_neon_vld2lane:
19190 case Intrinsic::arm_neon_vld3lane:
19191 case Intrinsic::arm_neon_vld4lane:
19192 case Intrinsic::arm_neon_vld2dup:
19193 case Intrinsic::arm_neon_vld3dup:
19194 case Intrinsic::arm_neon_vld4dup:
19195 case Intrinsic::arm_neon_vst1:
19196 case Intrinsic::arm_neon_vst1x2:
19197 case Intrinsic::arm_neon_vst1x3:
19198 case Intrinsic::arm_neon_vst1x4:
19199 case Intrinsic::arm_neon_vst2:
19200 case Intrinsic::arm_neon_vst3:
19201 case Intrinsic::arm_neon_vst4:
19202 case Intrinsic::arm_neon_vst2lane:
19203 case Intrinsic::arm_neon_vst3lane:
19204 case Intrinsic::arm_neon_vst4lane:
19205 return PerformVLDCombine(N, DCI);
19206 case Intrinsic::arm_mve_vld2q:
19207 case Intrinsic::arm_mve_vld4q:
19208 case Intrinsic::arm_mve_vst2q:
19209 case Intrinsic::arm_mve_vst4q:
19210 return PerformMVEVLDCombine(N, DCI);
19211 default: break;
19212 }
19213 break;
19214 }
19215 return SDValue();
19216}
19217
19219 EVT VT) const {
19220 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19221}
19222
19224 Align Alignment,
19226 unsigned *Fast) const {
19227 // Depends what it gets converted into if the type is weird.
19228 if (!VT.isSimple())
19229 return false;
19230
19231 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19232 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19233 auto Ty = VT.getSimpleVT().SimpleTy;
19234
19235 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19236 // Unaligned access can use (for example) LRDB, LRDH, LDR
19237 if (AllowsUnaligned) {
19238 if (Fast)
19239 *Fast = Subtarget->hasV7Ops();
19240 return true;
19241 }
19242 }
19243
19244 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19245 // For any little-endian targets with neon, we can support unaligned ld/st
19246 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19247 // A big-endian target may also explicitly support unaligned accesses
19248 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19249 if (Fast)
19250 *Fast = 1;
19251 return true;
19252 }
19253 }
19254
19255 if (!Subtarget->hasMVEIntegerOps())
19256 return false;
19257
19258 // These are for predicates
19259 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19260 Ty == MVT::v2i1)) {
19261 if (Fast)
19262 *Fast = 1;
19263 return true;
19264 }
19265
19266 // These are for truncated stores/narrowing loads. They are fine so long as
19267 // the alignment is at least the size of the item being loaded
19268 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19269 Alignment >= VT.getScalarSizeInBits() / 8) {
19270 if (Fast)
19271 *Fast = true;
19272 return true;
19273 }
19274
19275 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19276 // VSTRW.U32 all store the vector register in exactly the same format, and
19277 // differ only in the range of their immediate offset field and the required
19278 // alignment. So there is always a store that can be used, regardless of
19279 // actual type.
19280 //
19281 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19282 // VREV64.8) pair and get the same effect. This will likely be better than
19283 // aligning the vector through the stack.
19284 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19285 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19286 Ty == MVT::v2f64) {
19287 if (Fast)
19288 *Fast = 1;
19289 return true;
19290 }
19291
19292 return false;
19293}
19294
19296 LLVMContext &Context, const MemOp &Op,
19297 const AttributeList &FuncAttributes) const {
19298 // See if we can use NEON instructions for this...
19299 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19300 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
19301 unsigned Fast;
19302 if (Op.size() >= 16 &&
19303 (Op.isAligned(Align(16)) ||
19304 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
19306 Fast))) {
19307 return MVT::v2f64;
19308 } else if (Op.size() >= 8 &&
19309 (Op.isAligned(Align(8)) ||
19311 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
19312 Fast))) {
19313 return MVT::f64;
19314 }
19315 }
19316
19317 // Let the target-independent logic figure it out.
19318 return MVT::Other;
19319}
19320
19321// 64-bit integers are split into their high and low parts and held in two
19322// different registers, so the trunc is free since the low register can just
19323// be used.
19324bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19325 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19326 return false;
19327 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19328 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19329 return (SrcBits == 64 && DestBits == 32);
19330}
19331
19333 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19334 !DstVT.isInteger())
19335 return false;
19336 unsigned SrcBits = SrcVT.getSizeInBits();
19337 unsigned DestBits = DstVT.getSizeInBits();
19338 return (SrcBits == 64 && DestBits == 32);
19339}
19340
19342 if (Val.getOpcode() != ISD::LOAD)
19343 return false;
19344
19345 EVT VT1 = Val.getValueType();
19346 if (!VT1.isSimple() || !VT1.isInteger() ||
19347 !VT2.isSimple() || !VT2.isInteger())
19348 return false;
19349
19350 switch (VT1.getSimpleVT().SimpleTy) {
19351 default: break;
19352 case MVT::i1:
19353 case MVT::i8:
19354 case MVT::i16:
19355 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19356 return true;
19357 }
19358
19359 return false;
19360}
19361
19363 if (!VT.isSimple())
19364 return false;
19365
19366 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19367 // negate values directly (fneg is free). So, we don't want to let the DAG
19368 // combiner rewrite fneg into xors and some other instructions. For f16 and
19369 // FullFP16 argument passing, some bitcast nodes may be introduced,
19370 // triggering this DAG combine rewrite, so we are avoiding that with this.
19371 switch (VT.getSimpleVT().SimpleTy) {
19372 default: break;
19373 case MVT::f16:
19374 return Subtarget->hasFullFP16();
19375 }
19376
19377 return false;
19378}
19379
19381 if (!Subtarget->hasMVEIntegerOps())
19382 return nullptr;
19383 Type *SVIType = SVI->getType();
19384 Type *ScalarType = SVIType->getScalarType();
19385
19386 if (ScalarType->isFloatTy())
19387 return Type::getInt32Ty(SVIType->getContext());
19388 if (ScalarType->isHalfTy())
19389 return Type::getInt16Ty(SVIType->getContext());
19390 return nullptr;
19391}
19392
19394 EVT VT = ExtVal.getValueType();
19395
19396 if (!isTypeLegal(VT))
19397 return false;
19398
19399 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19400 if (Ld->isExpandingLoad())
19401 return false;
19402 }
19403
19404 if (Subtarget->hasMVEIntegerOps())
19405 return true;
19406
19407 // Don't create a loadext if we can fold the extension into a wide/long
19408 // instruction.
19409 // If there's more than one user instruction, the loadext is desirable no
19410 // matter what. There can be two uses by the same instruction.
19411 if (ExtVal->use_empty() ||
19412 !ExtVal->user_begin()->isOnlyUserOf(ExtVal.getNode()))
19413 return true;
19414
19415 SDNode *U = *ExtVal->user_begin();
19416 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19417 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19418 return false;
19419
19420 return true;
19421}
19422
19424 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19425 return false;
19426
19427 if (!isTypeLegal(EVT::getEVT(Ty1)))
19428 return false;
19429
19430 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19431
19432 // Assuming the caller doesn't have a zeroext or signext return parameter,
19433 // truncation all the way down to i1 is valid.
19434 return true;
19435}
19436
19437/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19438/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19439/// expanded to FMAs when this method returns true, otherwise fmuladd is
19440/// expanded to fmul + fadd.
19441///
19442/// ARM supports both fused and unfused multiply-add operations; we already
19443/// lower a pair of fmul and fadd to the latter so it's not clear that there
19444/// would be a gain or that the gain would be worthwhile enough to risk
19445/// correctness bugs.
19446///
19447/// For MVE, we set this to true as it helps simplify the need for some
19448/// patterns (and we don't have the non-fused floating point instruction).
19449bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19450 EVT VT) const {
19451 if (Subtarget->useSoftFloat())
19452 return false;
19453
19454 if (!VT.isSimple())
19455 return false;
19456
19457 switch (VT.getSimpleVT().SimpleTy) {
19458 case MVT::v4f32:
19459 case MVT::v8f16:
19460 return Subtarget->hasMVEFloatOps();
19461 case MVT::f16:
19462 return Subtarget->useFPVFMx16();
19463 case MVT::f32:
19464 return Subtarget->useFPVFMx();
19465 case MVT::f64:
19466 return Subtarget->useFPVFMx64();
19467 default:
19468 break;
19469 }
19470
19471 return false;
19472}
19473
19474static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19475 if (V < 0)
19476 return false;
19477
19478 unsigned Scale = 1;
19479 switch (VT.getSimpleVT().SimpleTy) {
19480 case MVT::i1:
19481 case MVT::i8:
19482 // Scale == 1;
19483 break;
19484 case MVT::i16:
19485 // Scale == 2;
19486 Scale = 2;
19487 break;
19488 default:
19489 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19490 // Scale == 4;
19491 Scale = 4;
19492 break;
19493 }
19494
19495 if ((V & (Scale - 1)) != 0)
19496 return false;
19497 return isUInt<5>(V / Scale);
19498}
19499
19500static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19501 const ARMSubtarget *Subtarget) {
19502 if (!VT.isInteger() && !VT.isFloatingPoint())
19503 return false;
19504 if (VT.isVector() && Subtarget->hasNEON())
19505 return false;
19506 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19507 !Subtarget->hasMVEFloatOps())
19508 return false;
19509
19510 bool IsNeg = false;
19511 if (V < 0) {
19512 IsNeg = true;
19513 V = -V;
19514 }
19515
19516 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
19517
19518 // MVE: size * imm7
19519 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19520 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19521 case MVT::i32:
19522 case MVT::f32:
19523 return isShiftedUInt<7,2>(V);
19524 case MVT::i16:
19525 case MVT::f16:
19526 return isShiftedUInt<7,1>(V);
19527 case MVT::i8:
19528 return isUInt<7>(V);
19529 default:
19530 return false;
19531 }
19532 }
19533
19534 // half VLDR: 2 * imm8
19535 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19536 return isShiftedUInt<8, 1>(V);
19537 // VLDR and LDRD: 4 * imm8
19538 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19539 return isShiftedUInt<8, 2>(V);
19540
19541 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19542 // + imm12 or - imm8
19543 if (IsNeg)
19544 return isUInt<8>(V);
19545 return isUInt<12>(V);
19546 }
19547
19548 return false;
19549}
19550
19551/// isLegalAddressImmediate - Return true if the integer value can be used
19552/// as the offset of the target addressing mode for load / store of the
19553/// given type.
19554static bool isLegalAddressImmediate(int64_t V, EVT VT,
19555 const ARMSubtarget *Subtarget) {
19556 if (V == 0)
19557 return true;
19558
19559 if (!VT.isSimple())
19560 return false;
19561
19562 if (Subtarget->isThumb1Only())
19563 return isLegalT1AddressImmediate(V, VT);
19564 else if (Subtarget->isThumb2())
19565 return isLegalT2AddressImmediate(V, VT, Subtarget);
19566
19567 // ARM mode.
19568 if (V < 0)
19569 V = - V;
19570 switch (VT.getSimpleVT().SimpleTy) {
19571 default: return false;
19572 case MVT::i1:
19573 case MVT::i8:
19574 case MVT::i32:
19575 // +- imm12
19576 return isUInt<12>(V);
19577 case MVT::i16:
19578 // +- imm8
19579 return isUInt<8>(V);
19580 case MVT::f32:
19581 case MVT::f64:
19582 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19583 return false;
19584 return isShiftedUInt<8, 2>(V);
19585 }
19586}
19587
19589 EVT VT) const {
19590 int Scale = AM.Scale;
19591 if (Scale < 0)
19592 return false;
19593
19594 switch (VT.getSimpleVT().SimpleTy) {
19595 default: return false;
19596 case MVT::i1:
19597 case MVT::i8:
19598 case MVT::i16:
19599 case MVT::i32:
19600 if (Scale == 1)
19601 return true;
19602 // r + r << imm
19603 Scale = Scale & ~1;
19604 return Scale == 2 || Scale == 4 || Scale == 8;
19605 case MVT::i64:
19606 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19607 // version in Thumb mode.
19608 // r + r
19609 if (Scale == 1)
19610 return true;
19611 // r * 2 (this can be lowered to r + r).
19612 if (!AM.HasBaseReg && Scale == 2)
19613 return true;
19614 return false;
19615 case MVT::isVoid:
19616 // Note, we allow "void" uses (basically, uses that aren't loads or
19617 // stores), because arm allows folding a scale into many arithmetic
19618 // operations. This should be made more precise and revisited later.
19619
19620 // Allow r << imm, but the imm has to be a multiple of two.
19621 if (Scale & 1) return false;
19622 return isPowerOf2_32(Scale);
19623 }
19624}
19625
19627 EVT VT) const {
19628 const int Scale = AM.Scale;
19629
19630 // Negative scales are not supported in Thumb1.
19631 if (Scale < 0)
19632 return false;
19633
19634 // Thumb1 addressing modes do not support register scaling excepting the
19635 // following cases:
19636 // 1. Scale == 1 means no scaling.
19637 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19638 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19639}
19640
19641/// isLegalAddressingMode - Return true if the addressing mode represented
19642/// by AM is legal for this target, for a load/store of the specified type.
19644 const AddrMode &AM, Type *Ty,
19645 unsigned AS, Instruction *I) const {
19646 EVT VT = getValueType(DL, Ty, true);
19647 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
19648 return false;
19649
19650 // Can never fold addr of global into load/store.
19651 if (AM.BaseGV)
19652 return false;
19653
19654 switch (AM.Scale) {
19655 case 0: // no scale reg, must be "r+i" or "r", or "i".
19656 break;
19657 default:
19658 // ARM doesn't support any R+R*scale+imm addr modes.
19659 if (AM.BaseOffs)
19660 return false;
19661
19662 if (!VT.isSimple())
19663 return false;
19664
19665 if (Subtarget->isThumb1Only())
19666 return isLegalT1ScaledAddressingMode(AM, VT);
19667
19668 if (Subtarget->isThumb2())
19669 return isLegalT2ScaledAddressingMode(AM, VT);
19670
19671 int Scale = AM.Scale;
19672 switch (VT.getSimpleVT().SimpleTy) {
19673 default: return false;
19674 case MVT::i1:
19675 case MVT::i8:
19676 case MVT::i32:
19677 if (Scale < 0) Scale = -Scale;
19678 if (Scale == 1)
19679 return true;
19680 // r + r << imm
19681 return isPowerOf2_32(Scale & ~1);
19682 case MVT::i16:
19683 case MVT::i64:
19684 // r +/- r
19685 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19686 return true;
19687 // r * 2 (this can be lowered to r + r).
19688 if (!AM.HasBaseReg && Scale == 2)
19689 return true;
19690 return false;
19691
19692 case MVT::isVoid:
19693 // Note, we allow "void" uses (basically, uses that aren't loads or
19694 // stores), because arm allows folding a scale into many arithmetic
19695 // operations. This should be made more precise and revisited later.
19696
19697 // Allow r << imm, but the imm has to be a multiple of two.
19698 if (Scale & 1) return false;
19699 return isPowerOf2_32(Scale);
19700 }
19701 }
19702 return true;
19703}
19704
19705/// isLegalICmpImmediate - Return true if the specified immediate is legal
19706/// icmp immediate, that is the target has icmp instructions which can compare
19707/// a register against the immediate without having to materialize the
19708/// immediate into a register.
19710 // Thumb2 and ARM modes can use cmn for negative immediates.
19711 if (!Subtarget->isThumb())
19712 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
19713 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
19714 if (Subtarget->isThumb2())
19715 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
19716 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
19717 // Thumb1 doesn't have cmn, and only 8-bit immediates.
19718 return Imm >= 0 && Imm <= 255;
19719}
19720
19721/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19722/// *or sub* immediate, that is the target has add or sub instructions which can
19723/// add a register with the immediate without having to materialize the
19724/// immediate into a register.
19726 // Same encoding for add/sub, just flip the sign.
19727 uint64_t AbsImm = AbsoluteValue(Imm);
19728 if (!Subtarget->isThumb())
19729 return ARM_AM::getSOImmVal(AbsImm) != -1;
19730 if (Subtarget->isThumb2())
19731 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
19732 // Thumb1 only has 8-bit unsigned immediate.
19733 return AbsImm <= 255;
19734}
19735
19736// Return false to prevent folding
19737// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19738// if the folding leads to worse code.
19740 SDValue ConstNode) const {
19741 // Let the DAGCombiner decide for vector types and large types.
19742 const EVT VT = AddNode.getValueType();
19743 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19744 return true;
19745
19746 // It is worse if c0 is legal add immediate, while c1*c0 is not
19747 // and has to be composed by at least two instructions.
19748 const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
19749 const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
19750 const int64_t C0 = C0Node->getSExtValue();
19751 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19753 return true;
19754 if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
19755 return false;
19756
19757 // Default to true and let the DAGCombiner decide.
19758 return true;
19759}
19760
19762 bool isSEXTLoad, SDValue &Base,
19763 SDValue &Offset, bool &isInc,
19764 SelectionDAG &DAG) {
19765 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19766 return false;
19767
19768 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19769 // AddressingMode 3
19770 Base = Ptr->getOperand(0);
19772 int RHSC = (int)RHS->getZExtValue();
19773 if (RHSC < 0 && RHSC > -256) {
19774 assert(Ptr->getOpcode() == ISD::ADD);
19775 isInc = false;
19776 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19777 return true;
19778 }
19779 }
19780 isInc = (Ptr->getOpcode() == ISD::ADD);
19781 Offset = Ptr->getOperand(1);
19782 return true;
19783 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19784 // AddressingMode 2
19786 int RHSC = (int)RHS->getZExtValue();
19787 if (RHSC < 0 && RHSC > -0x1000) {
19788 assert(Ptr->getOpcode() == ISD::ADD);
19789 isInc = false;
19790 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19791 Base = Ptr->getOperand(0);
19792 return true;
19793 }
19794 }
19795
19796 if (Ptr->getOpcode() == ISD::ADD) {
19797 isInc = true;
19798 ARM_AM::ShiftOpc ShOpcVal=
19800 if (ShOpcVal != ARM_AM::no_shift) {
19801 Base = Ptr->getOperand(1);
19802 Offset = Ptr->getOperand(0);
19803 } else {
19804 Base = Ptr->getOperand(0);
19805 Offset = Ptr->getOperand(1);
19806 }
19807 return true;
19808 }
19809
19810 isInc = (Ptr->getOpcode() == ISD::ADD);
19811 Base = Ptr->getOperand(0);
19812 Offset = Ptr->getOperand(1);
19813 return true;
19814 }
19815
19816 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19817 return false;
19818}
19819
19821 bool isSEXTLoad, SDValue &Base,
19822 SDValue &Offset, bool &isInc,
19823 SelectionDAG &DAG) {
19824 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19825 return false;
19826
19827 Base = Ptr->getOperand(0);
19829 int RHSC = (int)RHS->getZExtValue();
19830 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19831 assert(Ptr->getOpcode() == ISD::ADD);
19832 isInc = false;
19833 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19834 return true;
19835 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19836 isInc = Ptr->getOpcode() == ISD::ADD;
19837 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19838 return true;
19839 }
19840 }
19841
19842 return false;
19843}
19844
19845static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19846 bool isSEXTLoad, bool IsMasked, bool isLE,
19848 bool &isInc, SelectionDAG &DAG) {
19849 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19850 return false;
19851 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
19852 return false;
19853
19854 // We allow LE non-masked loads to change the type (for example use a vldrb.8
19855 // as opposed to a vldrw.32). This can allow extra addressing modes or
19856 // alignments for what is otherwise an equivalent instruction.
19857 bool CanChangeType = isLE && !IsMasked;
19858
19860 int RHSC = (int)RHS->getZExtValue();
19861
19862 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19863 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19864 assert(Ptr->getOpcode() == ISD::ADD);
19865 isInc = false;
19866 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19867 return true;
19868 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19869 isInc = Ptr->getOpcode() == ISD::ADD;
19870 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19871 return true;
19872 }
19873 return false;
19874 };
19875
19876 // Try to find a matching instruction based on s/zext, Alignment, Offset and
19877 // (in BE/masked) type.
19878 Base = Ptr->getOperand(0);
19879 if (VT == MVT::v4i16) {
19880 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19881 return true;
19882 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19883 if (IsInRange(RHSC, 0x80, 1))
19884 return true;
19885 } else if (Alignment >= 4 &&
19886 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19887 IsInRange(RHSC, 0x80, 4))
19888 return true;
19889 else if (Alignment >= 2 &&
19890 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19891 IsInRange(RHSC, 0x80, 2))
19892 return true;
19893 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19894 return true;
19895 return false;
19896}
19897
19898/// getPreIndexedAddressParts - returns true by value, base pointer and
19899/// offset pointer and addressing mode by reference if the node's address
19900/// can be legally represented as pre-indexed load / store address.
19901bool
19903 SDValue &Offset,
19905 SelectionDAG &DAG) const {
19906 if (Subtarget->isThumb1Only())
19907 return false;
19908
19909 EVT VT;
19910 SDValue Ptr;
19911 Align Alignment;
19912 unsigned AS = 0;
19913 bool isSEXTLoad = false;
19914 bool IsMasked = false;
19915 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19916 Ptr = LD->getBasePtr();
19917 VT = LD->getMemoryVT();
19918 Alignment = LD->getAlign();
19919 AS = LD->getAddressSpace();
19920 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19921 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19922 Ptr = ST->getBasePtr();
19923 VT = ST->getMemoryVT();
19924 Alignment = ST->getAlign();
19925 AS = ST->getAddressSpace();
19926 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19927 Ptr = LD->getBasePtr();
19928 VT = LD->getMemoryVT();
19929 Alignment = LD->getAlign();
19930 AS = LD->getAddressSpace();
19931 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19932 IsMasked = true;
19934 Ptr = ST->getBasePtr();
19935 VT = ST->getMemoryVT();
19936 Alignment = ST->getAlign();
19937 AS = ST->getAddressSpace();
19938 IsMasked = true;
19939 } else
19940 return false;
19941
19942 unsigned Fast = 0;
19943 if (!allowsMisalignedMemoryAccesses(VT, AS, Alignment,
19945 // Only generate post-increment or pre-increment forms when a real
19946 // hardware instruction exists for them. Do not emit postinc/preinc
19947 // if the operation will end up as a libcall.
19948 return false;
19949 }
19950
19951 bool isInc;
19952 bool isLegal = false;
19953 if (VT.isVector())
19954 isLegal = Subtarget->hasMVEIntegerOps() &&
19956 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19957 Subtarget->isLittle(), Base, Offset, isInc, DAG);
19958 else {
19959 if (Subtarget->isThumb2())
19960 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19961 Offset, isInc, DAG);
19962 else
19963 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19964 Offset, isInc, DAG);
19965 }
19966 if (!isLegal)
19967 return false;
19968
19969 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19970 return true;
19971}
19972
19973/// getPostIndexedAddressParts - returns true by value, base pointer and
19974/// offset pointer and addressing mode by reference if this node can be
19975/// combined with a load / store to form a post-indexed load / store.
19977 SDValue &Base,
19978 SDValue &Offset,
19980 SelectionDAG &DAG) const {
19981 EVT VT;
19982 SDValue Ptr;
19983 Align Alignment;
19984 bool isSEXTLoad = false, isNonExt;
19985 bool IsMasked = false;
19986 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19987 VT = LD->getMemoryVT();
19988 Ptr = LD->getBasePtr();
19989 Alignment = LD->getAlign();
19990 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19991 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19992 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19993 VT = ST->getMemoryVT();
19994 Ptr = ST->getBasePtr();
19995 Alignment = ST->getAlign();
19996 isNonExt = !ST->isTruncatingStore();
19997 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19998 VT = LD->getMemoryVT();
19999 Ptr = LD->getBasePtr();
20000 Alignment = LD->getAlign();
20001 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
20002 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
20003 IsMasked = true;
20005 VT = ST->getMemoryVT();
20006 Ptr = ST->getBasePtr();
20007 Alignment = ST->getAlign();
20008 isNonExt = !ST->isTruncatingStore();
20009 IsMasked = true;
20010 } else
20011 return false;
20012
20013 if (Subtarget->isThumb1Only()) {
20014 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
20015 // must be non-extending/truncating, i32, with an offset of 4.
20016 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
20017 if (Op->getOpcode() != ISD::ADD || !isNonExt)
20018 return false;
20019 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
20020 if (!RHS || RHS->getZExtValue() != 4)
20021 return false;
20022 if (Alignment < Align(4))
20023 return false;
20024
20025 Offset = Op->getOperand(1);
20026 Base = Op->getOperand(0);
20027 AM = ISD::POST_INC;
20028 return true;
20029 }
20030
20031 bool isInc;
20032 bool isLegal = false;
20033 if (VT.isVector())
20034 isLegal = Subtarget->hasMVEIntegerOps() &&
20035 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
20036 Subtarget->isLittle(), Base, Offset,
20037 isInc, DAG);
20038 else {
20039 if (Subtarget->isThumb2())
20040 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20041 isInc, DAG);
20042 else
20043 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20044 isInc, DAG);
20045 }
20046 if (!isLegal)
20047 return false;
20048
20049 if (Ptr != Base) {
20050 // Swap base ptr and offset to catch more post-index load / store when
20051 // it's legal. In Thumb2 mode, offset must be an immediate.
20052 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
20053 !Subtarget->isThumb2())
20055
20056 // Post-indexed load / store update the base pointer.
20057 if (Ptr != Base)
20058 return false;
20059 }
20060
20061 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
20062 return true;
20063}
20064
20066 KnownBits &Known,
20067 const APInt &DemandedElts,
20068 const SelectionDAG &DAG,
20069 unsigned Depth) const {
20070 unsigned BitWidth = Known.getBitWidth();
20071 Known.resetAll();
20072 switch (Op.getOpcode()) {
20073 default: break;
20074 case ARMISD::ADDC:
20075 case ARMISD::ADDE:
20076 case ARMISD::SUBC:
20077 case ARMISD::SUBE:
20078 // Special cases when we convert a carry to a boolean.
20079 if (Op.getResNo() == 0) {
20080 SDValue LHS = Op.getOperand(0);
20081 SDValue RHS = Op.getOperand(1);
20082 // (ADDE 0, 0, C) will give us a single bit.
20083 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
20084 isNullConstant(RHS)) {
20086 return;
20087 }
20088 }
20089 break;
20090 case ARMISD::CMOV: {
20091 // Bits are known zero/one if known on the LHS and RHS.
20092 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
20093 if (Known.isUnknown())
20094 return;
20095
20096 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
20097 Known = Known.intersectWith(KnownRHS);
20098 return;
20099 }
20101 Intrinsic::ID IntID =
20102 static_cast<Intrinsic::ID>(Op->getConstantOperandVal(1));
20103 switch (IntID) {
20104 default: return;
20105 case Intrinsic::arm_ldaex:
20106 case Intrinsic::arm_ldrex: {
20107 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
20108 unsigned MemBits = VT.getScalarSizeInBits();
20109 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
20110 return;
20111 }
20112 }
20113 }
20114 case ARMISD::BFI: {
20115 // Conservatively, we can recurse down the first operand
20116 // and just mask out all affected bits.
20117 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20118
20119 // The operand to BFI is already a mask suitable for removing the bits it
20120 // sets.
20121 const APInt &Mask = Op.getConstantOperandAPInt(2);
20122 Known.Zero &= Mask;
20123 Known.One &= Mask;
20124 return;
20125 }
20126 case ARMISD::VGETLANEs:
20127 case ARMISD::VGETLANEu: {
20128 const SDValue &SrcSV = Op.getOperand(0);
20129 EVT VecVT = SrcSV.getValueType();
20130 assert(VecVT.isVector() && "VGETLANE expected a vector type");
20131 const unsigned NumSrcElts = VecVT.getVectorNumElements();
20132 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
20133 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20134 "VGETLANE index out of bounds");
20135 unsigned Idx = Pos->getZExtValue();
20136 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
20137 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
20138
20139 EVT VT = Op.getValueType();
20140 const unsigned DstSz = VT.getScalarSizeInBits();
20141 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20142 (void)SrcSz;
20143 assert(SrcSz == Known.getBitWidth());
20144 assert(DstSz > SrcSz);
20145 if (Op.getOpcode() == ARMISD::VGETLANEs)
20146 Known = Known.sext(DstSz);
20147 else {
20148 Known = Known.zext(DstSz);
20149 }
20150 assert(DstSz == Known.getBitWidth());
20151 break;
20152 }
20153 case ARMISD::VMOVrh: {
20154 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20155 assert(KnownOp.getBitWidth() == 16);
20156 Known = KnownOp.zext(32);
20157 break;
20158 }
20159 case ARMISD::CSINC:
20160 case ARMISD::CSINV:
20161 case ARMISD::CSNEG: {
20162 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20163 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
20164
20165 // The result is either:
20166 // CSINC: KnownOp0 or KnownOp1 + 1
20167 // CSINV: KnownOp0 or ~KnownOp1
20168 // CSNEG: KnownOp0 or KnownOp1 * -1
20169 if (Op.getOpcode() == ARMISD::CSINC)
20170 KnownOp1 =
20171 KnownBits::add(KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
20172 else if (Op.getOpcode() == ARMISD::CSINV)
20173 std::swap(KnownOp1.Zero, KnownOp1.One);
20174 else if (Op.getOpcode() == ARMISD::CSNEG)
20175 KnownOp1 = KnownBits::mul(KnownOp1,
20177
20178 Known = KnownOp0.intersectWith(KnownOp1);
20179 break;
20180 }
20181 case ARMISD::VORRIMM:
20182 case ARMISD::VBICIMM: {
20183 unsigned Encoded = Op.getConstantOperandVal(1);
20184 unsigned DecEltBits = 0;
20185 uint64_t DecodedVal = ARM_AM::decodeVMOVModImm(Encoded, DecEltBits);
20186
20187 unsigned EltBits = Op.getScalarValueSizeInBits();
20188 if (EltBits != DecEltBits) {
20189 // Be conservative: only update Known when EltBits == DecEltBits.
20190 // This is believed to always be true for VORRIMM/VBICIMM today, but if
20191 // that changes in the future, doing nothing here is safer than risking
20192 // subtle bugs.
20193 break;
20194 }
20195
20196 KnownBits KnownLHS = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20197 bool IsVORR = Op.getOpcode() == ARMISD::VORRIMM;
20198 APInt Imm(DecEltBits, DecodedVal);
20199
20200 Known.One = IsVORR ? (KnownLHS.One | Imm) : (KnownLHS.One & ~Imm);
20201 Known.Zero = IsVORR ? (KnownLHS.Zero & ~Imm) : (KnownLHS.Zero | Imm);
20202 break;
20203 }
20204 }
20205}
20206
20207static bool isLegalLogicalImmediate(unsigned Imm,
20208 const ARMSubtarget *Subtarget) {
20209 if (!Subtarget->isThumb())
20210 return ARM_AM::getSOImmVal(Imm) != -1;
20211 if (Subtarget->isThumb2())
20212 return ARM_AM::getT2SOImmVal(Imm) != -1;
20213 // Thumb1 only has 8-bit unsigned immediate.
20214 return Imm <= 255;
20215}
20216
20217/// Refine i32 AND/OR/XOR with a constant RHS using demanded bits: replace the
20218/// immediate with an equivalent constant that ARM/Thumb can encode as a
20219/// logical immediate (or that selects better lowering), without changing the
20220/// computed result on those demanded bits.
20221static bool optimizeLogicalImm(SDValue Op, unsigned Imm,
20222 const APInt &DemandedBits,
20223 const ARMSubtarget *Subtarget,
20225
20226 if (Imm == 0 || Imm == ~0U)
20227 return false;
20228
20229 unsigned Opc = Op.getOpcode();
20230 unsigned Demanded = DemandedBits.getZExtValue();
20231 EVT VT = Op.getValueType();
20232
20233 unsigned ShrunkImm = Imm & Demanded;
20234 unsigned ExpandedImm = Imm | ~Demanded;
20235
20236 auto IsLegalImm = [ShrunkImm, ExpandedImm](unsigned CandidateImm) -> bool {
20237 return (ShrunkImm & CandidateImm) == ShrunkImm &&
20238 (~ExpandedImm & CandidateImm) == 0;
20239 };
20240 auto UseImm = [Imm, Opc, Op, VT, &TLO](unsigned NewImm) -> bool {
20241 if (NewImm == Imm)
20242 return true;
20243 SDLoc DL(Op);
20244 SDValue NewC = TLO.DAG.getConstant(NewImm, DL, VT);
20245 SDValue NewOp =
20246 TLO.DAG.getNode(Opc, DL, VT, Op.getOperand(0), NewC, Op->getFlags());
20247 return TLO.CombineTo(Op, NewOp);
20248 };
20249
20250 // Shrunk immediate is 0: AND becomes zero; OR/XOR with 0 leaves the other
20251 // operand (still valid on demanded bits).
20252 if (ShrunkImm == 0) {
20253 ++NumOptimizedImms;
20254 return UseImm(ShrunkImm);
20255 }
20256
20257 // If the immediate is all ones: for AND this removes the operation; for
20258 // OR/XOR it remains a transform valid on demanded bits. (Target-independent
20259 // shrink may not fold this, so keep it to avoid obscure combine loops.)
20260 if (ExpandedImm == ~0U) {
20261 ++NumOptimizedImms;
20262 return UseImm(ExpandedImm);
20263 }
20264
20265 // Thumb1: prefer 0xFF / 0xFFFF when they fit the demanded-bit envelope so
20266 // lowering can match uxtb / uxth (AND immediates only; OR/XOR do not use
20267 // that). Run this before strict ShrunkImm: a tight 8-bit ShrunkImm can be
20268 // legal while 0xFF still matches the envelope and yields better isel (uxtb).
20269 if (Opc == ISD::AND && Subtarget->hasV6Ops()) {
20270 if (IsLegalImm(0xFF)) {
20271 ++NumOptimizedImms;
20272 return UseImm(0xFF);
20273 }
20274
20275 if (IsLegalImm(0xFFFF)) {
20276 ++NumOptimizedImms;
20277 return UseImm(0xFFFF);
20278 }
20279 }
20280
20281 // Don't optimize if it is legal.
20282 if (isLegalLogicalImmediate(Imm, Subtarget))
20283 return false;
20284
20285 // FIXME: Check for BIC being legal causes infinite loop due to target
20286 // independent DAG combine undoing this.
20287
20288 // Prefer strict shrink when ShrunkImm encodes for this target, before
20289 // complement expansion.
20290 if (isLegalLogicalImmediate(ShrunkImm, Subtarget)) {
20291 ++NumOptimizedImms;
20292 return UseImm(ShrunkImm);
20293 }
20294
20295 // Complement expansion: if all undemanded bits are already one, ExpandedImm
20296 // is Imm with every non-demanded bit set. When (~ExpandedImm) < 256, the
20297 // complement fits in an 8-bit unsigned value, i.e. bits 8–31 of ExpandedImm
20298 // are all ones; only the low byte may differ from ~0. Use that expanded
20299 // constant so isel sees a mask shape that fits logical-immediate patterns.
20300 if ((~ExpandedImm) < 256) {
20301 ++NumOptimizedImms;
20302 return UseImm(ExpandedImm);
20303 }
20304
20305 // FIXME: The check for v6 is because this interferes with some ubfx
20306 // optimizations.
20307 if (Opc == ISD::AND && isLegalLogicalImmediate(~ExpandedImm, Subtarget) &&
20308 !Subtarget->hasV6Ops()) {
20309 ++NumOptimizedImms;
20310 return UseImm(ExpandedImm);
20311 }
20312
20313 // Potential improvements:
20314 //
20315 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20316 // We could try to prefer Thumb1 immediates which can be lowered to a
20317 // two-instruction sequence.
20318
20319 return false;
20320}
20321
20323 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20324 TargetLoweringOpt &TLO) const {
20325 // Delay this optimization to as late as possible.
20326 if (!TLO.LegalOps)
20327 return false;
20328
20329 EVT VT = Op.getValueType();
20330
20331 // Ignore vectors.
20332 if (VT.isVector())
20333 return false;
20334
20335 unsigned Size = VT.getSizeInBits();
20336
20337 if (Size != 32)
20338 return false;
20339
20340 // Exit early if we demand all bits.
20341 if (DemandedBits.isAllOnes())
20342 return false;
20343
20344 switch (Op.getOpcode()) {
20345 default:
20346 return false;
20347 case ISD::AND:
20348 case ISD::OR:
20349 case ISD::XOR:
20350 break;
20351 }
20352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
20353 if (!C)
20354 return false;
20355 unsigned Imm = C->getZExtValue();
20356 return optimizeLogicalImm(Op, Imm, DemandedBits, Subtarget, TLO);
20357}
20358
20360 SDValue Op, const APInt &OriginalDemandedBits,
20361 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20362 unsigned Depth) const {
20363 unsigned Opc = Op.getOpcode();
20364
20365 switch (Opc) {
20366 case ARMISD::ASRL:
20367 case ARMISD::LSRL: {
20368 // If this is result 0 and the other result is unused, see if the demand
20369 // bits allow us to shrink this long shift into a standard small shift in
20370 // the opposite direction.
20371 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
20372 isa<ConstantSDNode>(Op->getOperand(2))) {
20373 unsigned ShAmt = Op->getConstantOperandVal(2);
20374 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
20375 << (32 - ShAmt)))
20376 return TLO.CombineTo(
20377 Op, TLO.DAG.getNode(
20378 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
20379 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
20380 }
20381 break;
20382 }
20383 case ARMISD::VBICIMM: {
20384 SDValue Op0 = Op.getOperand(0);
20385 unsigned ModImm = Op.getConstantOperandVal(1);
20386 unsigned EltBits = 0;
20387 uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20388 if ((OriginalDemandedBits & Mask) == 0)
20389 return TLO.CombineTo(Op, Op0);
20390 }
20391 }
20392
20394 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20395}
20396
20397//===----------------------------------------------------------------------===//
20398// ARM Inline Assembly Support
20399//===----------------------------------------------------------------------===//
20400
20401const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20402 // At this point, we have to lower this constraint to something else, so we
20403 // lower it to an "r" or "w". However, by doing this we will force the result
20404 // to be in register, while the X constraint is much more permissive.
20405 //
20406 // Although we are correct (we are free to emit anything, without
20407 // constraints), we might break use cases that would expect us to be more
20408 // efficient and emit something else.
20409 if (!Subtarget->hasVFP2Base())
20410 return "r";
20411 if (ConstraintVT.isFloatingPoint())
20412 return "w";
20413 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20414 (ConstraintVT.getSizeInBits() == 64 ||
20415 ConstraintVT.getSizeInBits() == 128))
20416 return "w";
20417
20418 return "r";
20419}
20420
20421/// getConstraintType - Given a constraint letter, return the type of
20422/// constraint it is for this target.
20425 unsigned S = Constraint.size();
20426 if (S == 1) {
20427 switch (Constraint[0]) {
20428 default: break;
20429 case 'l': return C_RegisterClass;
20430 case 'w': return C_RegisterClass;
20431 case 'h': return C_RegisterClass;
20432 case 'x': return C_RegisterClass;
20433 case 't': return C_RegisterClass;
20434 case 'j': return C_Immediate; // Constant for movw.
20435 // An address with a single base register. Due to the way we
20436 // currently handle addresses it is the same as an 'r' memory constraint.
20437 case 'Q': return C_Memory;
20438 }
20439 } else if (S == 2) {
20440 switch (Constraint[0]) {
20441 default: break;
20442 case 'T': return C_RegisterClass;
20443 // All 'U+' constraints are addresses.
20444 case 'U': return C_Memory;
20445 }
20446 }
20447 return TargetLowering::getConstraintType(Constraint);
20448}
20449
20450/// Examine constraint type and operand type and determine a weight value.
20451/// This object must already have been set up with the operand type
20452/// and the current alternative constraint selected.
20455 AsmOperandInfo &info, const char *constraint) const {
20457 Value *CallOperandVal = info.CallOperandVal;
20458 // If we don't have a value, we can't do a match,
20459 // but allow it at the lowest weight.
20460 if (!CallOperandVal)
20461 return CW_Default;
20462 Type *type = CallOperandVal->getType();
20463 // Look at the constraint type.
20464 switch (*constraint) {
20465 default:
20467 break;
20468 case 'l':
20469 if (type->isIntegerTy()) {
20470 if (Subtarget->isThumb())
20471 weight = CW_SpecificReg;
20472 else
20473 weight = CW_Register;
20474 }
20475 break;
20476 case 'w':
20477 if (type->isFloatingPointTy())
20478 weight = CW_Register;
20479 break;
20480 }
20481 return weight;
20482}
20483
20484static bool isIncompatibleReg(const MCPhysReg &PR, MVT VT) {
20485 if (PR == 0 || VT == MVT::Other)
20486 return false;
20487 if (ARM::SPRRegClass.contains(PR))
20488 return VT != MVT::f32 && VT != MVT::f16 && VT != MVT::i32;
20489 if (ARM::DPRRegClass.contains(PR))
20490 return VT != MVT::f64 && !VT.is64BitVector();
20491 return false;
20492}
20493
20494using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20495
20497 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20498 switch (Constraint.size()) {
20499 case 1:
20500 // GCC ARM Constraint Letters
20501 switch (Constraint[0]) {
20502 case 'l': // Low regs or general regs.
20503 if (Subtarget->isThumb())
20504 return RCPair(0U, &ARM::tGPRRegClass);
20505 return RCPair(0U, &ARM::GPRRegClass);
20506 case 'h': // High regs or no regs.
20507 if (Subtarget->isThumb())
20508 return RCPair(0U, &ARM::hGPRRegClass);
20509 break;
20510 case 'r':
20511 if (Subtarget->isThumb1Only())
20512 return RCPair(0U, &ARM::tGPRRegClass);
20513 return RCPair(0U, &ARM::GPRRegClass);
20514 case 'w':
20515 if (VT == MVT::Other)
20516 break;
20517 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20518 return RCPair(0U, &ARM::SPRRegClass);
20519 if (VT.getSizeInBits() == 64)
20520 return RCPair(0U, &ARM::DPRRegClass);
20521 if (VT.getSizeInBits() == 128)
20522 return RCPair(0U, &ARM::QPRRegClass);
20523 break;
20524 case 'x':
20525 if (VT == MVT::Other)
20526 break;
20527 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20528 return RCPair(0U, &ARM::SPR_8RegClass);
20529 if (VT.getSizeInBits() == 64)
20530 return RCPair(0U, &ARM::DPR_8RegClass);
20531 if (VT.getSizeInBits() == 128)
20532 return RCPair(0U, &ARM::QPR_8RegClass);
20533 break;
20534 case 't':
20535 if (VT == MVT::Other)
20536 break;
20537 if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
20538 return RCPair(0U, &ARM::SPRRegClass);
20539 if (VT.getSizeInBits() == 64)
20540 return RCPair(0U, &ARM::DPR_VFP2RegClass);
20541 if (VT.getSizeInBits() == 128)
20542 return RCPair(0U, &ARM::QPR_VFP2RegClass);
20543 break;
20544 }
20545 break;
20546
20547 case 2:
20548 if (Constraint[0] == 'T') {
20549 switch (Constraint[1]) {
20550 default:
20551 break;
20552 case 'e':
20553 return RCPair(0U, &ARM::tGPREvenRegClass);
20554 case 'o':
20555 return RCPair(0U, &ARM::tGPROddRegClass);
20556 }
20557 }
20558 break;
20559
20560 default:
20561 break;
20562 }
20563
20564 if (StringRef("{cc}").equals_insensitive(Constraint))
20565 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
20566
20567 // r14 is an alias of lr.
20568 if (StringRef("{r14}").equals_insensitive(Constraint))
20569 return std::make_pair(unsigned(ARM::LR), getRegClassFor(MVT::i32));
20570
20571 auto RCP = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20572 if (isIncompatibleReg(RCP.first, VT))
20573 return {0, nullptr};
20574 return RCP;
20575}
20576
20577/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20578/// vector. If it is invalid, don't add anything to Ops.
20580 StringRef Constraint,
20581 std::vector<SDValue> &Ops,
20582 SelectionDAG &DAG) const {
20583 SDValue Result;
20584
20585 // Currently only support length 1 constraints.
20586 if (Constraint.size() != 1)
20587 return;
20588
20589 char ConstraintLetter = Constraint[0];
20590 switch (ConstraintLetter) {
20591 default: break;
20592 case 'j':
20593 case 'I': case 'J': case 'K': case 'L':
20594 case 'M': case 'N': case 'O':
20596 if (!C)
20597 return;
20598
20599 int64_t CVal64 = C->getSExtValue();
20600 int CVal = (int) CVal64;
20601 // None of these constraints allow values larger than 32 bits. Check
20602 // that the value fits in an int.
20603 if (CVal != CVal64)
20604 return;
20605
20606 switch (ConstraintLetter) {
20607 case 'j':
20608 // Constant suitable for movw, must be between 0 and
20609 // 65535.
20610 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20611 if (CVal >= 0 && CVal <= 65535)
20612 break;
20613 return;
20614 case 'I':
20615 if (Subtarget->isThumb1Only()) {
20616 // This must be a constant between 0 and 255, for ADD
20617 // immediates.
20618 if (CVal >= 0 && CVal <= 255)
20619 break;
20620 } else if (Subtarget->isThumb2()) {
20621 // A constant that can be used as an immediate value in a
20622 // data-processing instruction.
20623 if (ARM_AM::getT2SOImmVal(CVal) != -1)
20624 break;
20625 } else {
20626 // A constant that can be used as an immediate value in a
20627 // data-processing instruction.
20628 if (ARM_AM::getSOImmVal(CVal) != -1)
20629 break;
20630 }
20631 return;
20632
20633 case 'J':
20634 if (Subtarget->isThumb1Only()) {
20635 // This must be a constant between -255 and -1, for negated ADD
20636 // immediates. This can be used in GCC with an "n" modifier that
20637 // prints the negated value, for use with SUB instructions. It is
20638 // not useful otherwise but is implemented for compatibility.
20639 if (CVal >= -255 && CVal <= -1)
20640 break;
20641 } else {
20642 // This must be a constant between -4095 and 4095. This is suitable
20643 // for use as the immediate offset field in LDR and STR instructions
20644 // such as LDR r0,[r1,#offset].
20645 if (CVal >= -4095 && CVal <= 4095)
20646 break;
20647 }
20648 return;
20649
20650 case 'K':
20651 if (Subtarget->isThumb1Only()) {
20652 // A 32-bit value where only one byte has a nonzero value. Exclude
20653 // zero to match GCC. This constraint is used by GCC internally for
20654 // constants that can be loaded with a move/shift combination.
20655 // It is not useful otherwise but is implemented for compatibility.
20656 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
20657 break;
20658 } else if (Subtarget->isThumb2()) {
20659 // A constant whose bitwise inverse can be used as an immediate
20660 // value in a data-processing instruction. This can be used in GCC
20661 // with a "B" modifier that prints the inverted value, for use with
20662 // BIC and MVN instructions. It is not useful otherwise but is
20663 // implemented for compatibility.
20664 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
20665 break;
20666 } else {
20667 // A constant whose bitwise inverse can be used as an immediate
20668 // value in a data-processing instruction. This can be used in GCC
20669 // with a "B" modifier that prints the inverted value, for use with
20670 // BIC and MVN instructions. It is not useful otherwise but is
20671 // implemented for compatibility.
20672 if (ARM_AM::getSOImmVal(~CVal) != -1)
20673 break;
20674 }
20675 return;
20676
20677 case 'L':
20678 if (Subtarget->isThumb1Only()) {
20679 // This must be a constant between -7 and 7,
20680 // for 3-operand ADD/SUB immediate instructions.
20681 if (CVal >= -7 && CVal < 7)
20682 break;
20683 } else if (Subtarget->isThumb2()) {
20684 // A constant whose negation can be used as an immediate value in a
20685 // data-processing instruction. This can be used in GCC with an "n"
20686 // modifier that prints the negated value, for use with SUB
20687 // instructions. It is not useful otherwise but is implemented for
20688 // compatibility.
20689 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
20690 break;
20691 } else {
20692 // A constant whose negation can be used as an immediate value in a
20693 // data-processing instruction. This can be used in GCC with an "n"
20694 // modifier that prints the negated value, for use with SUB
20695 // instructions. It is not useful otherwise but is implemented for
20696 // compatibility.
20697 if (ARM_AM::getSOImmVal(-CVal) != -1)
20698 break;
20699 }
20700 return;
20701
20702 case 'M':
20703 if (Subtarget->isThumb1Only()) {
20704 // This must be a multiple of 4 between 0 and 1020, for
20705 // ADD sp + immediate.
20706 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20707 break;
20708 } else {
20709 // A power of two or a constant between 0 and 32. This is used in
20710 // GCC for the shift amount on shifted register operands, but it is
20711 // useful in general for any shift amounts.
20712 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20713 break;
20714 }
20715 return;
20716
20717 case 'N':
20718 if (Subtarget->isThumb1Only()) {
20719 // This must be a constant between 0 and 31, for shift amounts.
20720 if (CVal >= 0 && CVal <= 31)
20721 break;
20722 }
20723 return;
20724
20725 case 'O':
20726 if (Subtarget->isThumb1Only()) {
20727 // This must be a multiple of 4 between -508 and 508, for
20728 // ADD/SUB sp = sp + immediate.
20729 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20730 break;
20731 }
20732 return;
20733 }
20734 Result = DAG.getSignedTargetConstant(CVal, SDLoc(Op), Op.getValueType());
20735 break;
20736 }
20737
20738 if (Result.getNode()) {
20739 Ops.push_back(Result);
20740 return;
20741 }
20742 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20743}
20744
20745static RTLIB::Libcall getDivRemLibcall(
20746 const SDNode *N, MVT::SimpleValueType SVT) {
20747 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20748 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20749 "Unhandled Opcode in getDivRemLibcall");
20750 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20751 N->getOpcode() == ISD::SREM;
20752 RTLIB::Libcall LC;
20753 switch (SVT) {
20754 default: llvm_unreachable("Unexpected request for libcall!");
20755 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
20756 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20757 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20758 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20759 }
20760 return LC;
20761}
20762
20764 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20765 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20766 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20767 "Unhandled Opcode in getDivRemArgList");
20768 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20769 N->getOpcode() == ISD::SREM;
20771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20772 EVT ArgVT = N->getOperand(i).getValueType();
20773 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
20774 TargetLowering::ArgListEntry Entry(N->getOperand(i), ArgTy);
20775 Entry.IsSExt = isSigned;
20776 Entry.IsZExt = !isSigned;
20777 Args.push_back(Entry);
20778 }
20779 if (Subtarget->getTargetTriple().isOSWindows() && Args.size() >= 2)
20780 std::swap(Args[0], Args[1]);
20781 return Args;
20782}
20783
20784SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20785 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
20786 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
20787 Subtarget->isTargetFuchsia() || Subtarget->isTargetWindows()) &&
20788 "Register-based DivRem lowering only");
20789 unsigned Opcode = Op->getOpcode();
20790 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
20791 "Invalid opcode for Div/Rem lowering");
20792 bool isSigned = (Opcode == ISD::SDIVREM);
20793 EVT VT = Op->getValueType(0);
20794 SDLoc dl(Op);
20795
20796 if (VT == MVT::i64 && isa<ConstantSDNode>(Op.getOperand(1))) {
20798 if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i32, DAG)) {
20799 SDValue Res0 =
20800 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[0], Result[1]);
20801 SDValue Res1 =
20802 DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[2], Result[3]);
20803 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
20804 {Res0, Res1});
20805 }
20806 }
20807
20808 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
20809
20810 // If the target has hardware divide, use divide + multiply + subtract:
20811 // div = a / b
20812 // rem = a - b * div
20813 // return {div, rem}
20814 // This should be lowered into UDIV/SDIV + MLS later on.
20815 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20816 : Subtarget->hasDivideInARMMode();
20817 if (hasDivide && Op->getValueType(0).isSimple() &&
20818 Op->getSimpleValueType(0) == MVT::i32) {
20819 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20820 const SDValue Dividend = Op->getOperand(0);
20821 const SDValue Divisor = Op->getOperand(1);
20822 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
20823 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
20824 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
20825
20826 SDValue Values[2] = {Div, Rem};
20827 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
20828 }
20829
20830 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
20831 VT.getSimpleVT().SimpleTy);
20832 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
20833
20834 SDValue InChain = DAG.getEntryNode();
20835
20837 DAG.getContext(),
20838 Subtarget);
20839
20840 SDValue Callee =
20841 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
20842
20843 Type *RetTy = StructType::get(Ty, Ty);
20844
20845 if (getTM().getTargetTriple().isOSWindows())
20846 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
20847
20848 TargetLowering::CallLoweringInfo CLI(DAG);
20849 CLI.setDebugLoc(dl)
20850 .setChain(InChain)
20851 .setCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
20852 Callee, std::move(Args))
20853 .setInRegister()
20856
20857 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20858 return CallInfo.first;
20859}
20860
20861// Lowers REM using divmod helpers
20862// see RTABI section 4.2/4.3
20863SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20864 EVT VT = N->getValueType(0);
20865
20866 if (VT == MVT::i64 && isa<ConstantSDNode>(N->getOperand(1))) {
20868 if (expandDIVREMByConstant(N, Result, MVT::i32, DAG))
20869 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), N->getValueType(0),
20870 Result[0], Result[1]);
20871 }
20872
20873 // Build return types (div and rem)
20874 std::vector<Type*> RetTyParams;
20875 Type *RetTyElement;
20876
20877 switch (VT.getSimpleVT().SimpleTy) {
20878 default: llvm_unreachable("Unexpected request for libcall!");
20879 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
20880 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
20881 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
20882 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
20883 }
20884
20885 RetTyParams.push_back(RetTyElement);
20886 RetTyParams.push_back(RetTyElement);
20887 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20888 Type *RetTy = StructType::get(*DAG.getContext(), ret);
20889
20890 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
20891 SimpleTy);
20892 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
20893 SDValue InChain = DAG.getEntryNode();
20895 Subtarget);
20896 bool isSigned = N->getOpcode() == ISD::SREM;
20897
20898 SDValue Callee =
20899 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
20900
20901 if (getTM().getTargetTriple().isOSWindows())
20902 InChain = WinDBZCheckDenominator(DAG, N, InChain);
20903
20904 // Lower call
20905 CallLoweringInfo CLI(DAG);
20906 CLI.setChain(InChain)
20907 .setCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
20908 Callee, std::move(Args))
20911 .setDebugLoc(SDLoc(N));
20912 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20913
20914 // Return second (rem) result operand (first contains div)
20915 SDNode *ResNode = CallResult.first.getNode();
20916 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
20917 return ResNode->getOperand(1);
20918}
20919
20920SDValue
20921ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20922 assert(getTM().getTargetTriple().isOSWindows() &&
20923 "unsupported target platform");
20924 SDLoc DL(Op);
20925
20926 // Get the inputs.
20927 SDValue Chain = Op.getOperand(0);
20928 SDValue Size = Op.getOperand(1);
20929
20931 "no-stack-arg-probe")) {
20932 MaybeAlign Align =
20933 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
20934 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20935 Chain = SP.getValue(1);
20936 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
20937 if (Align)
20938 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
20939 DAG.getSignedConstant(-Align->value(), DL, MVT::i32));
20940 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
20941 SDValue Ops[2] = { SP, Chain };
20942 return DAG.getMergeValues(Ops, DL);
20943 }
20944
20945 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
20946 DAG.getConstant(2, DL, MVT::i32));
20947
20948 SDValue Glue;
20949 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Glue);
20950 Glue = Chain.getValue(1);
20951
20952 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20953 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Glue);
20954
20955 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20956 Chain = NewSP.getValue(1);
20957
20958 SDValue Ops[2] = { NewSP, Chain };
20959 return DAG.getMergeValues(Ops, DL);
20960}
20961
20962SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20963 bool IsStrict = Op->isStrictFPOpcode();
20964 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20965 const unsigned DstSz = Op.getValueType().getSizeInBits();
20966 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20967 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
20968 "Unexpected type for custom-lowering FP_EXTEND");
20969
20970 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20971 "With both FP DP and 16, any FP conversion is legal!");
20972
20973 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
20974 "With FP16, 16 to 32 conversion is legal!");
20975
20976 // Converting from 32 -> 64 is valid if we have FP64.
20977 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20978 // FIXME: Remove this when we have strict fp instruction selection patterns
20979 if (IsStrict) {
20980 SDLoc Loc(Op);
20982 Loc, Op.getValueType(), SrcVal);
20983 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
20984 }
20985 return Op;
20986 }
20987
20988 // Either we are converting from 16 -> 64, without FP16 and/or
20989 // FP.double-precision or without Armv8-fp. So we must do it in two
20990 // steps.
20991 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20992 // without FP16. So we must do a function call.
20993 SDLoc Loc(Op);
20994 RTLIB::Libcall LC;
20995 MakeLibCallOptions CallOptions;
20996 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20997 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20998 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20999 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
21000 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
21001 if (Supported) {
21002 if (IsStrict) {
21003 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
21004 {DstVT, MVT::Other}, {Chain, SrcVal});
21005 Chain = SrcVal.getValue(1);
21006 } else {
21007 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
21008 }
21009 } else {
21010 LC = RTLIB::getFPEXT(SrcVT, DstVT);
21011 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
21012 "Unexpected type for custom-lowering FP_EXTEND");
21013 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
21014 Loc, Chain);
21015 }
21016 }
21017
21018 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
21019}
21020
21021SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21022 bool IsStrict = Op->isStrictFPOpcode();
21023
21024 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
21025 EVT SrcVT = SrcVal.getValueType();
21026 EVT DstVT = Op.getValueType();
21027 const unsigned DstSz = Op.getValueType().getSizeInBits();
21028 const unsigned SrcSz = SrcVT.getSizeInBits();
21029 (void)DstSz;
21030 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
21031 "Unexpected type for custom-lowering FP_ROUND");
21032
21033 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
21034 "With both FP DP and 16, any FP conversion is legal!");
21035
21036 SDLoc Loc(Op);
21037
21038 // Instruction from 32 -> 16 if hasFP16 is valid
21039 if (SrcSz == 32 && Subtarget->hasFP16())
21040 return Op;
21041
21042 // Lib call from 32 -> 16 / 64 -> [32, 16]
21043 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
21044 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
21045 "Unexpected type for custom-lowering FP_ROUND");
21046 MakeLibCallOptions CallOptions;
21047 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21049 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
21050 Loc, Chain);
21051 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
21052}
21053
21054bool
21056 // The ARM target isn't yet aware of offsets.
21057 return false;
21058}
21059
21061 if (v == 0xffffffff)
21062 return false;
21063
21064 // there can be 1's on either or both "outsides", all the "inside"
21065 // bits must be 0's
21066 return isShiftedMask_32(~v);
21067}
21068
21069/// isFPImmLegal - Returns true if the target can instruction select the
21070/// specified FP immediate natively. If false, the legalizer will
21071/// materialize the FP immediate as a load from a constant pool.
21073 bool ForCodeSize) const {
21074 if (!Subtarget->hasVFP3Base())
21075 return false;
21076 if (VT == MVT::f16 && Subtarget->hasFullFP16())