LLVM 24.0.0git
PPCISelLowering.cpp
Go to the documentation of this file.
1//===-- PPCISelLowering.cpp - PPC 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 implements the PPCISelLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCISelLowering.h"
16#include "PPC.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSelectionDAGInfo.h"
24#include "PPCSubtarget.h"
25#include "PPCTargetMachine.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
58#include "llvm/IR/CallingConv.h"
59#include "llvm/IR/Constant.h"
60#include "llvm/IR/Constants.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalValue.h"
66#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/IntrinsicsPowerPC.h"
70#include "llvm/IR/Module.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/Value.h"
74#include "llvm/MC/MCContext.h"
75#include "llvm/MC/MCExpr.h"
84#include "llvm/Support/Debug.h"
86#include "llvm/Support/Format.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <iterator>
96#include <list>
97#include <optional>
98#include <utility>
99#include <vector>
100
101using namespace llvm;
102
103#define DEBUG_TYPE "ppc-lowering"
104
106 "disable-p10-store-forward",
107 cl::desc("disable P10 store forward-friendly conversion"), cl::Hidden,
108 cl::init(false));
109
110static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
111cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
112
113static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
114cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
115
116static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
117cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
118
119static cl::opt<bool> DisableSCO("disable-ppc-sco",
120cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
121
122static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
123cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
124
125static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
126cl::desc("use absolute jump tables on ppc"), cl::Hidden);
127
128static cl::opt<bool>
129 DisablePerfectShuffle("ppc-disable-perfect-shuffle",
130 cl::desc("disable vector permute decomposition"),
131 cl::init(true), cl::Hidden);
132
134 "disable-auto-paired-vec-st",
135 cl::desc("disable automatically generated 32byte paired vector stores"),
136 cl::init(true), cl::Hidden);
137
139 "ppc-min-jump-table-entries", cl::init(64), cl::Hidden,
140 cl::desc("Set minimum number of entries to use a jump table on PPC"));
141
143 "ppc-min-bit-test-cmps", cl::init(3), cl::Hidden,
144 cl::desc("Set minimum of largest number of comparisons to use bit test for "
145 "switch on PPC."));
146
148 "ppc-gather-alias-max-depth", cl::init(18), cl::Hidden,
149 cl::desc("max depth when checking alias info in GatherAllAliases()"));
150
152 "ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden,
153 cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a "
154 "function to use initial-exec"));
155
156STATISTIC(NumTailCalls, "Number of tail calls");
157STATISTIC(NumSiblingCalls, "Number of sibling calls");
158STATISTIC(ShufflesHandledWithVPERM,
159 "Number of shuffles lowered to a VPERM or XXPERM");
160STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
161
162static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
163
164static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
165
167 unsigned OpIdx, bool IsByte,
168 const PPCInstrInfo *TII);
169
170// A faster local-[exec|dynamic] TLS access sequence (enabled with the
171// -maix-small-local-[exec|dynamic]-tls option) can be produced for TLS
172// variables; consistent with the IBM XL compiler, we apply a max size of
173// slightly under 32KB.
175
176// FIXME: Remove this once the bug has been fixed!
178
180 const PPCSubtarget &STI)
181 : TargetLowering(TM, STI), Subtarget(STI) {
182 // Initialize map that relates the PPC addressing modes to the computed flags
183 // of a load/store instruction. The map is used to determine the optimal
184 // addressing mode when selecting load and stores.
185 initializeAddrModeMap();
186 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
187 // arguments are at least 4/8 bytes aligned.
188 bool isPPC64 = Subtarget.isPPC64();
189 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
190 const MVT RegVT = Subtarget.getScalarIntVT();
191
192 // Set up the register classes.
193 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
194 if (!useSoftFloat()) {
195 if (hasSPE()) {
196 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
197 // EFPU2 APU only supports f32
198 if (!Subtarget.hasEFPU2())
199 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
200 } else {
201 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
202 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
203 }
204 }
205
208
209 // PowerPC uses addo_carry,subo_carry to propagate carry.
212
213 // On P10, the default lowering generates better code using the
214 // setbc instruction.
215 if (!Subtarget.hasP10Vector()) {
218 if (isPPC64) {
221 }
222 }
223
224 // Match BITREVERSE to customized fast code sequence in the td file.
227
228 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
230
231 // Custom lower inline assembly to check for special registers.
234
235 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
236 for (MVT VT : MVT::integer_valuetypes()) {
239 }
240
241 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
243
244 if (Subtarget.isISA3_0()) {
245 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Legal);
246 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
247 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
248 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
249 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
250 } else {
251 // No extending loads from f16 or HW conversions back and forth.
252 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
254 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
257 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
260 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
261 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
262 }
263
264 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
265
266 // PowerPC has pre-inc load and store's.
277 if (!Subtarget.hasSPE()) {
282 }
283
284 if (Subtarget.useCRBits()) {
286
287 if (isPPC64 || Subtarget.hasFPCVT()) {
292
294 AddPromotedToType(ISD::SINT_TO_FP, MVT::i1, RegVT);
296 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, RegVT);
297
302
304 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, RegVT);
306 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, RegVT);
307 } else {
312 }
313
314 // PowerPC does not support direct load/store of condition registers.
317
318 // FIXME: Remove this once the ANDI glue bug is fixed:
319 if (ANDIGlueBug)
321
322 for (MVT VT : MVT::integer_valuetypes()) {
325 setTruncStoreAction(VT, MVT::i1, Expand);
326 }
327
328 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
329 }
330
331 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
332 // PPC (the libcall is not available).
337
338 // We do not currently implement these libm ops for PowerPC.
339 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
340 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
341 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
342 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
344 setOperationAction(ISD::FREM, MVT::ppcf128, LibCall);
345
346 // PowerPC has no SREM/UREM instructions unless we are on P9
347 // On P9 we may use a hardware instruction to compute the remainder.
348 // When the result of both the remainder and the division is required it is
349 // more efficient to compute the remainder from the result of the division
350 // rather than use the remainder instruction. The instructions are legalized
351 // directly because the DivRemPairsPass performs the transformation at the IR
352 // level.
353 if (Subtarget.isISA3_0()) {
358 } else {
363 }
364
365 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
374
375 // Handle constrained floating-point operations of scalar.
376 // TODO: Handle SPE specific operation.
382
387
388 if (!Subtarget.hasSPE()) {
391 }
392
393 if (Subtarget.hasVSX()) {
396 }
397
398 if (Subtarget.hasFSQRT()) {
401 }
402
403 if (Subtarget.hasFPRND()) {
408
413 }
414
415 // We don't support sin/cos/sqrt/fmod/pow
426
427 // MASS transformation for LLVM intrinsics with replicating fast-math flag
428 // to be consistent to PPCGenScalarMASSEntries pass
429 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive) {
442 }
443
444 if (Subtarget.hasSPE()) {
447 } else {
448 setOperationAction(ISD::FMA , MVT::f64, Legal);
449 setOperationAction(ISD::FMA , MVT::f32, Legal);
452 }
453
454 if (Subtarget.hasSPE())
455 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
456
457 // If we're enabling GP optimizations, use hardware square root
458 if (!Subtarget.hasFSQRT() && !(Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
460
461 if (!Subtarget.hasFSQRT() &&
462 !(Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
464
465 if (Subtarget.hasFCPSGN()) {
468 } else {
471 }
472
473 if (Subtarget.hasFPRND()) {
478
483 }
484
485 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
486 // instruction xxbrd to speed up scalar BSWAP64.
487 if (Subtarget.isISA3_1()) {
490 } else {
493 ((Subtarget.hasP8Vector()) && isPPC64) ? Custom
494 : Expand);
495 }
496
497 // CTPOP or CTTZ were introduced in P8/P9 respectively
498 if (Subtarget.isISA3_0()) {
499 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
500 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
501 } else {
502 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
503 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
504 }
505
506 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
509 } else {
512 }
513
514 // PowerPC does not have ROTR
517
518 if (!Subtarget.useCRBits()) {
519 // PowerPC does not have Select
524 }
525
526 // PowerPC wants to turn select_cc of FP into fsel when possible.
529
530 // PowerPC wants to optimize integer setcc a bit
531 if (!Subtarget.useCRBits())
533
534 if (Subtarget.hasFPU()) {
538
542 }
543
544 // PowerPC does not have BRCOND which requires SetCC
545 if (!Subtarget.useCRBits())
547
549
550 if (Subtarget.hasSPE()) {
551 // SPE has built-in conversions
558
559 // SPE supports signaling compare of f32/f64.
560 // But it doesn't comply IEEE-754 rules for comparing
561 // special values like NaNs, Infs.
570 } else {
571 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
574
575 // PowerPC does not have [U|S]INT_TO_FP
580 }
581
582 if (Subtarget.hasDirectMove() && isPPC64) {
587
596 } else {
601 }
602
603 // We cannot sextinreg(i1). Expand to shifts.
605
606 // Custom handling for PowerPC ucmp instruction
608 setOperationAction(ISD::UCMP, MVT::i64, isPPC64 ? Custom : Expand);
610 setOperationAction(ISD::ABDU, MVT::i64, isPPC64 ? Custom : Expand);
611
612 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
613 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
614 // support continuation, user-level threading, and etc.. As a result, no
615 // other SjLj exception interfaces are implemented and please don't build
616 // your own exception handling based on them.
617 // LLVM/Clang supports zero-cost DWARF exception handling.
620
621 // We want to legalize GlobalAddress and ConstantPool nodes into the
622 // appropriate instructions to materialize the address.
633
634 // TRAP is legal.
635 setOperationAction(ISD::TRAP, MVT::Other, Legal);
636
637 // TRAMPOLINE is custom lowered.
640
641 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
643
644 if (Subtarget.is64BitELFABI()) {
645 // VAARG always uses double-word chunks, so promote anything smaller.
647 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
649 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
651 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
653 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
655 } else if (Subtarget.is32BitELFABI()) {
656 // VAARG is custom lowered with the 32-bit SVR4 ABI.
659 } else
661
662 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
663 if (Subtarget.is32BitELFABI())
665 else
667
668 // Use the default implementation.
669 setOperationAction(ISD::VAEND , MVT::Other, Expand);
678
679 if (Subtarget.isISA3_0() && isPPC64) {
680 setOperationAction(ISD::VP_STORE, MVT::v16i1, Custom);
681 setOperationAction(ISD::VP_STORE, MVT::v8i1, Custom);
682 setOperationAction(ISD::VP_STORE, MVT::v4i1, Custom);
683 setOperationAction(ISD::VP_STORE, MVT::v2i1, Custom);
684 setOperationAction(ISD::VP_LOAD, MVT::v16i1, Custom);
685 setOperationAction(ISD::VP_LOAD, MVT::v8i1, Custom);
686 setOperationAction(ISD::VP_LOAD, MVT::v4i1, Custom);
687 setOperationAction(ISD::VP_LOAD, MVT::v2i1, Custom);
688 }
689
690 // We want to custom lower some of our intrinsics.
696
697 // To handle counter-based loop conditions.
700
705
706 // Comparisons that require checking two conditions.
707 if (Subtarget.hasSPE()) {
712 }
725
728
729 if (Subtarget.has64BitSupport()) {
730 // They also have instructions for converting between i64 and fp.
739 // This is just the low 32 bits of a (signed) fp->i64 conversion.
740 // We cannot do this with Promote because i64 is not a legal type.
743
744 if (Subtarget.hasLFIWAX() || isPPC64) {
747 }
748 } else {
749 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
750 if (Subtarget.hasSPE()) {
753 } else {
756 }
757 }
758
759 // With the instructions enabled under FPCVT, we can do everything.
760 if (Subtarget.hasFPCVT()) {
761 if (Subtarget.has64BitSupport()) {
770 }
771
780 }
781
782 if (Subtarget.use64BitRegs()) {
783 // 64-bit PowerPC implementations can support i64 types directly
784 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
785 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
787 // 64-bit PowerPC wants to expand i128 shifts itself.
791 } else {
792 // 32-bit PowerPC wants to expand i64 shifts itself.
796 }
797
798 // PowerPC has better expansions for funnel shifts than the generic
799 // TargetLowering::expandFunnelShift.
800 if (Subtarget.has64BitSupport()) {
803 }
806
807 if (Subtarget.hasVSX()) {
818 }
819
820 if (Subtarget.hasAltivec()) {
821 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
828 }
829 // First set operation action for all vector types to expand. Then we
830 // will selectively turn on ones that can be effectively codegen'd.
832 // add/sub are legal for all supported vector VT's.
835
836 // For v2i64, these are only valid with P8Vector. This is corrected after
837 // the loop.
838 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
843 }
844 else {
849 }
850
851 if (Subtarget.hasVSX()) {
857 }
858
859 // Vector instructions introduced in P8
860 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
863 }
864 else {
867 }
868
869 // Vector instructions introduced in P9
870 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
872 else
874
875 // We promote all shuffles to v16i8.
877 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
878
879 // We promote all non-typed operations to v4i32.
881 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
883 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
885 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
887 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
889 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
892 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
894 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
895
896 // No other operations are legal.
935
936 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
937 setTruncStoreAction(VT, InnerVT, Expand);
940 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
941 }
942 }
944 if (!Subtarget.hasP8Vector()) {
945 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
946 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
947 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
948 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
949 }
950
951 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
952 // with merges, splats, etc.
954
955 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
956 // are cheap, so handle them before they get expanded to scalar.
962
963 setOperationAction(ISD::AND , MVT::v4i32, Legal);
964 setOperationAction(ISD::OR , MVT::v4i32, Legal);
965 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
966 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
968 Subtarget.useCRBits() ? Legal : Expand);
969 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
979 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
982
983 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
984 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
985 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
986 if (Subtarget.hasAltivec())
987 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
989 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
990 if (Subtarget.hasP8Altivec())
991 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
992
993 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
994 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
995 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
996 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
997
998 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
999 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1000
1001 if (Subtarget.hasVSX()) {
1002 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1003 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1005 }
1006
1007 if (Subtarget.hasP8Altivec())
1008 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1009 else
1010 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1011
1012 if (Subtarget.isISA3_1()) {
1013 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1014 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
1015 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
1016 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
1017 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
1018 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
1019 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
1020 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
1021 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
1022 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
1023 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
1024 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
1026 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
1027 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
1028 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
1029 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
1030 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
1031 }
1032
1033 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1034 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1035
1038 // LE is P8+/64-bit so direct moves are supported and these operations
1039 // are legal. The custom transformation requires 64-bit since we need a
1040 // pair of stores that will cover a 128-bit load for P10.
1041 if (!DisableP10StoreForward && isPPC64 && !Subtarget.isLittleEndian()) {
1045 }
1046
1051
1052 // Altivec does not contain unordered floating-point compare instructions
1053 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
1054 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
1055 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
1056 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
1057
1058 if (Subtarget.hasVSX()) {
1061 if (Subtarget.hasP8Vector()) {
1064 }
1065 if (Subtarget.hasDirectMove() && isPPC64) {
1074 }
1076
1077 // The nearbyint variants are not allowed to raise the inexact exception
1078 // so we can only code-gen them with fpexcept.ignore.
1083
1084 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1085 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1086 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1087 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1088 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1091
1092 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1093 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1096
1097 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1098 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1099
1100 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1101 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1102
1103 // Share the Altivec comparison restrictions.
1104 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1105 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1106 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
1107 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1108
1109 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1110 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1111
1113
1114 if (Subtarget.hasP8Vector())
1115 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1116
1117 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1118
1119 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1120 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1121 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1122
1123 if (Subtarget.hasP8Altivec()) {
1124 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1125 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1126 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1127
1128 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1129 // SRL, but not for SRA because of the instructions available:
1130 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1131 // doing
1132 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1133 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1134 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1135
1136 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1137 }
1138 else {
1139 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1140 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1141 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1142
1143 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1144
1145 // VSX v2i64 only supports non-arithmetic operations.
1146 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1147 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1148 }
1149
1150 if (Subtarget.isISA3_1())
1151 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1152 else
1153 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1154
1155 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1156 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1158 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1159
1161
1170
1171 // Custom handling for partial vectors of integers converted to
1172 // floating point. We already have optimal handling for v2i32 through
1173 // the DAG combine, so those aren't necessary.
1190
1191 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1192 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1193 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1194 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1197
1200
1201 // Handle constrained floating-point operations of vector.
1202 // The predictor is `hasVSX` because altivec instruction has
1203 // no exception but VSX vector instruction has.
1217
1231
1232 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1233 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1234
1235 for (MVT FPT : MVT::fp_valuetypes())
1236 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1237
1238 // Expand the SELECT to SELECT_CC
1240
1241 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1242 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1243
1244 // No implementation for these ops for PowerPC.
1246 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1247 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1248 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1251 }
1252
1253 if (Subtarget.hasP8Altivec()) {
1254 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1255 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1256 }
1257
1258 if (Subtarget.hasP9Vector()) {
1261
1262 // Test data class instructions store results in CR bits.
1263 if (Subtarget.useCRBits()) {
1268 }
1269
1270 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1271 // SRL, but not for SRA because of the instructions available:
1272 // VS{RL} and VS{RL}O.
1273 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1274 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1275 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1276
1277 setOperationAction(ISD::FADD, MVT::f128, Legal);
1278 setOperationAction(ISD::FSUB, MVT::f128, Legal);
1279 setOperationAction(ISD::FDIV, MVT::f128, Legal);
1280 setOperationAction(ISD::FMUL, MVT::f128, Legal);
1282
1283 setOperationAction(ISD::FMA, MVT::f128, Legal);
1290
1292 setOperationAction(ISD::FRINT, MVT::f128, Legal);
1294 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1297
1301
1302 // Handle constrained floating-point operations of fp128
1319 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1320 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1321 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1322 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1323 } else if (Subtarget.hasVSX()) {
1326
1327 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1328 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1329
1330 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1331 // fp_to_uint and int_to_fp.
1334
1335 setOperationAction(ISD::FMUL, MVT::f128, Expand);
1336 setOperationAction(ISD::FDIV, MVT::f128, Expand);
1337 setOperationAction(ISD::FNEG, MVT::f128, Expand);
1338 setOperationAction(ISD::FABS, MVT::f128, Expand);
1340 setOperationAction(ISD::FMA, MVT::f128, Expand);
1342
1343 // Expand the fp_extend if the target type is fp128.
1346
1347 // Expand the fp_round if the source type is fp128.
1348 for (MVT VT : {MVT::f32, MVT::f64}) {
1351 }
1352
1357
1358 // Lower following f128 select_cc pattern:
1359 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1361
1362 // We need to handle f128 SELECT_CC with integer result type.
1364 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1365 }
1366
1367 if (Subtarget.hasP9Altivec()) {
1368 if (Subtarget.isISA3_1()) {
1373 } else {
1376 }
1384
1385 setOperationAction(ISD::ABDU, MVT::v16i8, Legal);
1386 setOperationAction(ISD::ABDU, MVT::v8i16, Legal);
1387 setOperationAction(ISD::ABDU, MVT::v4i32, Legal);
1388 setOperationAction(ISD::ABDS, MVT::v4i32, Legal);
1389 }
1390
1391 if (Subtarget.hasP10Vector()) {
1393 }
1394
1397 Legal);
1399 Legal);
1401 Legal);
1403 Legal);
1404 }
1405
1406 if (Subtarget.pairedVectorMemops()) {
1407 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1408 setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1409 setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1410 }
1411 if (Subtarget.hasMMA()) {
1412 if (Subtarget.isISAFuture()) {
1413 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
1414 addRegisterClass(MVT::v1024i1, &PPC::DMRRCRegClass);
1415 addRegisterClass(MVT::v2048i1, &PPC::DMRpRCRegClass);
1416 setOperationAction(ISD::LOAD, MVT::v1024i1, Custom);
1417 setOperationAction(ISD::STORE, MVT::v1024i1, Custom);
1418 setOperationAction(ISD::LOAD, MVT::v2048i1, Custom);
1419 setOperationAction(ISD::STORE, MVT::v2048i1, Custom);
1420 } else {
1421 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1422 }
1423 setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1424 setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1426 }
1427
1428 if (Subtarget.has64BitSupport())
1430
1431 if (Subtarget.isISA3_1())
1432 setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1433
1434 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1435
1436 if (!isPPC64) {
1439 }
1440
1445 }
1446
1448
1449 if (Subtarget.hasAltivec()) {
1450 // Altivec instructions set fields to all zeros or all ones.
1452 }
1453
1456 else if (isPPC64)
1458 else
1460
1461 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1462
1463 // We have target-specific dag combine patterns for the following nodes:
1467 if (Subtarget.hasFPCVT())
1470 if (Subtarget.useCRBits())
1474
1476
1478
1479 if (Subtarget.useCRBits()) {
1481 }
1482
1483 if (Subtarget.hasP8Vector())
1485
1486 // With 32 condition bits, we don't need to sink (and duplicate) compares
1487 // aggressively in CodeGenPrep.
1488 if (Subtarget.useCRBits()) {
1490 }
1491
1492 // TODO: The default entry number is set to 64. This stops most jump table
1493 // generation on PPC. But it is good for current PPC HWs because the indirect
1494 // branch instruction mtctr to the jump table may lead to bad branch predict.
1495 // Re-evaluate this value on future HWs that can do better with mtctr.
1497
1498 // The default minimum of largest number in a BitTest cluster is 3.
1500
1502 setMinCmpXchgSizeInBits(Subtarget.hasPartwordAtomics() ? 8 : 32);
1503
1504 auto CPUDirective = Subtarget.getCPUDirective();
1505 switch (CPUDirective) {
1506 default: break;
1507 case PPC::DIR_970:
1508 case PPC::DIR_A2:
1509 case PPC::DIR_E500:
1510 case PPC::DIR_E500mc:
1511 case PPC::DIR_E5500:
1512 case PPC::DIR_PWR4:
1513 case PPC::DIR_PWR5:
1514 case PPC::DIR_PWR5X:
1515 case PPC::DIR_PWR6:
1516 case PPC::DIR_PWR6X:
1517 case PPC::DIR_PWR7:
1518 case PPC::DIR_PWR8:
1519 case PPC::DIR_PWR9:
1520 case PPC::DIR_PWR10:
1521 case PPC::DIR_PWR11:
1525 break;
1526 }
1527
1528 if (Subtarget.enableMachineScheduler())
1530 else
1532
1534
1535 // The Freescale cores do better with aggressive inlining of memcpy and
1536 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1537 if (CPUDirective == PPC::DIR_E500mc || CPUDirective == PPC::DIR_E5500) {
1538 MaxStoresPerMemset = 32;
1540 MaxStoresPerMemcpy = 32;
1544 } else if (CPUDirective == PPC::DIR_A2) {
1545 // The A2 also benefits from (very) aggressive inlining of memcpy and
1546 // friends. The overhead of a the function call, even when warm, can be
1547 // over one hundred cycles.
1548 MaxStoresPerMemset = 128;
1549 MaxStoresPerMemcpy = 128;
1550 MaxStoresPerMemmove = 128;
1551 MaxLoadsPerMemcmp = 128;
1552 } else {
1555 }
1556
1557 // Enable generation of STXVP instructions by default for mcpu=future.
1558 if (CPUDirective == PPC::DIR_PWR_FUTURE &&
1559 DisableAutoPairedVecSt.getNumOccurrences() == 0)
1560 DisableAutoPairedVecSt = false;
1561
1562 IsStrictFPEnabled = true;
1563
1564 // Let the subtarget (CPU) decide if a predictable select is more expensive
1565 // than the corresponding branch. This information is used in CGP to decide
1566 // when to convert selects into branches.
1567 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1568
1570}
1571
1572// *********************************** NOTE ************************************
1573// For selecting load and store instructions, the addressing modes are defined
1574// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1575// patterns to match the load the store instructions.
1576//
1577// The TD definitions for the addressing modes correspond to their respective
1578// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1579// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1580// address mode flags of a particular node. Afterwards, the computed address
1581// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1582// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1583// accordingly, based on the preferred addressing mode.
1584//
1585// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1586// MemOpFlags contains all the possible flags that can be used to compute the
1587// optimal addressing mode for load and store instructions.
1588// AddrMode contains all the possible load and store addressing modes available
1589// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1590//
1591// When adding new load and store instructions, it is possible that new address
1592// flags may need to be added into MemOpFlags, and a new addressing mode will
1593// need to be added to AddrMode. An entry of the new addressing mode (consisting
1594// of the minimal and main distinguishing address flags for the new load/store
1595// instructions) will need to be added into initializeAddrModeMap() below.
1596// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1597// need to be updated to account for selecting the optimal addressing mode.
1598// *****************************************************************************
1599/// Initialize the map that relates the different addressing modes of the load
1600/// and store instructions to a set of flags. This ensures the load/store
1601/// instruction is correctly matched during instruction selection.
1602void PPCTargetLowering::initializeAddrModeMap() {
1603 AddrModesMap[PPC::AM_DForm] = {
1604 // LWZ, STW
1609 // LBZ, LHZ, STB, STH
1614 // LHA
1619 // LFS, LFD, STFS, STFD
1624 };
1625 AddrModesMap[PPC::AM_DSForm] = {
1626 // LWA
1630 // LD, STD
1634 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1638 };
1639 AddrModesMap[PPC::AM_DQForm] = {
1640 // LXV, STXV
1644 };
1645 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1647 // TODO: Add mapping for quadword load/store.
1648}
1649
1650/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1651/// the desired ByVal argument alignment.
1652static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1653 if (MaxAlign == MaxMaxAlign)
1654 return;
1655 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1656 if (MaxMaxAlign >= 32 &&
1657 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
1658 MaxAlign = Align(32);
1659 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
1660 MaxAlign < 16)
1661 MaxAlign = Align(16);
1662 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1663 Align EltAlign;
1664 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1665 if (EltAlign > MaxAlign)
1666 MaxAlign = EltAlign;
1667 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1668 for (auto *EltTy : STy->elements()) {
1669 Align EltAlign;
1670 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1671 if (EltAlign > MaxAlign)
1672 MaxAlign = EltAlign;
1673 if (MaxAlign == MaxMaxAlign)
1674 break;
1675 }
1676 }
1677}
1678
1679/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1680/// function arguments in the caller parameter area.
1682 const DataLayout &DL) const {
1683 // 16byte and wider vectors are passed on 16byte boundary.
1684 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1685 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1686 if (Subtarget.hasAltivec())
1687 getMaxByValAlign(Ty, Alignment, Align(16));
1688 return Alignment;
1689}
1690
1692 return Subtarget.useSoftFloat();
1693}
1694
1696 return Subtarget.hasSPE();
1697}
1698
1700 return VT.isScalarInteger();
1701}
1702
1704 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
1705 if (!Subtarget.isPPC64() || !Subtarget.hasVSX())
1706 return false;
1707
1708 if (auto *VTy = dyn_cast<VectorType>(VectorTy)) {
1709 if (VTy->getScalarType()->isIntegerTy()) {
1710 // ElemSizeInBits 8/16 can fit in immediate field, not needed here.
1711 if (ElemSizeInBits == 32) {
1712 Index = Subtarget.isLittleEndian() ? 2 : 1;
1713 return true;
1714 }
1715 if (ElemSizeInBits == 64) {
1716 Index = Subtarget.isLittleEndian() ? 1 : 0;
1717 return true;
1718 }
1719 }
1720 }
1721 return false;
1722}
1723
1725 EVT VT) const {
1726 if (!VT.isVector())
1727 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1728
1730}
1731
1733 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1734 return true;
1735}
1736
1737//===----------------------------------------------------------------------===//
1738// Node matching predicates, for use by the tblgen matching code.
1739//===----------------------------------------------------------------------===//
1740
1741/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1744 return CFP->getValueAPF().isZero();
1745 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1746 // Maybe this has already been legalized into the constant pool?
1747 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1748 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1749 return CFP->getValueAPF().isZero();
1750 }
1751 return false;
1752}
1753
1754/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1755/// true if Op is undef or if it matches the specified value.
1756static bool isConstantOrUndef(int Op, int Val) {
1757 return Op < 0 || Op == Val;
1758}
1759
1760/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1761/// VPKUHUM instruction.
1762/// The ShuffleKind distinguishes between big-endian operations with
1763/// two different inputs (0), either-endian operations with two identical
1764/// inputs (1), and little-endian operations with two different inputs (2).
1765/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1767 SelectionDAG &DAG) {
1768 bool IsLE = DAG.getDataLayout().isLittleEndian();
1769 if (ShuffleKind == 0) {
1770 if (IsLE)
1771 return false;
1772 for (unsigned i = 0; i != 16; ++i)
1773 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1774 return false;
1775 } else if (ShuffleKind == 2) {
1776 if (!IsLE)
1777 return false;
1778 for (unsigned i = 0; i != 16; ++i)
1779 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1780 return false;
1781 } else if (ShuffleKind == 1) {
1782 unsigned j = IsLE ? 0 : 1;
1783 for (unsigned i = 0; i != 8; ++i)
1784 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1785 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1786 return false;
1787 }
1788 return true;
1789}
1790
1791/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1792/// VPKUWUM instruction.
1793/// The ShuffleKind distinguishes between big-endian operations with
1794/// two different inputs (0), either-endian operations with two identical
1795/// inputs (1), and little-endian operations with two different inputs (2).
1796/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1798 SelectionDAG &DAG) {
1799 bool IsLE = DAG.getDataLayout().isLittleEndian();
1800 if (ShuffleKind == 0) {
1801 if (IsLE)
1802 return false;
1803 for (unsigned i = 0; i != 16; i += 2)
1804 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1805 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1806 return false;
1807 } else if (ShuffleKind == 2) {
1808 if (!IsLE)
1809 return false;
1810 for (unsigned i = 0; i != 16; i += 2)
1811 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1812 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1813 return false;
1814 } else if (ShuffleKind == 1) {
1815 unsigned j = IsLE ? 0 : 2;
1816 for (unsigned i = 0; i != 8; i += 2)
1817 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1818 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1819 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1820 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1821 return false;
1822 }
1823 return true;
1824}
1825
1826/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1827/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1828/// current subtarget.
1829///
1830/// The ShuffleKind distinguishes between big-endian operations with
1831/// two different inputs (0), either-endian operations with two identical
1832/// inputs (1), and little-endian operations with two different inputs (2).
1833/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1835 SelectionDAG &DAG) {
1836 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1837 if (!Subtarget.hasP8Vector())
1838 return false;
1839
1840 bool IsLE = DAG.getDataLayout().isLittleEndian();
1841 if (ShuffleKind == 0) {
1842 if (IsLE)
1843 return false;
1844 for (unsigned i = 0; i != 16; i += 4)
1845 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1846 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1847 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1848 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1849 return false;
1850 } else if (ShuffleKind == 2) {
1851 if (!IsLE)
1852 return false;
1853 for (unsigned i = 0; i != 16; i += 4)
1854 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1855 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1856 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1857 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1858 return false;
1859 } else if (ShuffleKind == 1) {
1860 unsigned j = IsLE ? 0 : 4;
1861 for (unsigned i = 0; i != 8; i += 4)
1862 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1863 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1864 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1865 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1866 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1867 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1868 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1869 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1870 return false;
1871 }
1872 return true;
1873}
1874
1875/// isVMerge - Common function, used to match vmrg* shuffles.
1876///
1877static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1878 unsigned LHSStart, unsigned RHSStart) {
1879 if (N->getValueType(0) != MVT::v16i8)
1880 return false;
1881 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1882 "Unsupported merge size!");
1883
1884 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1885 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1886 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1887 LHSStart+j+i*UnitSize) ||
1888 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1889 RHSStart+j+i*UnitSize))
1890 return false;
1891 }
1892 return true;
1893}
1894
1895/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1896/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1897/// The ShuffleKind distinguishes between big-endian merges with two
1898/// different inputs (0), either-endian merges with two identical inputs (1),
1899/// and little-endian merges with two different inputs (2). For the latter,
1900/// the input operands are swapped (see PPCInstrAltivec.td).
1902 unsigned ShuffleKind, SelectionDAG &DAG) {
1903 if (DAG.getDataLayout().isLittleEndian()) {
1904 if (ShuffleKind == 1) // unary
1905 return isVMerge(N, UnitSize, 0, 0);
1906 else if (ShuffleKind == 2) // swapped
1907 return isVMerge(N, UnitSize, 0, 16);
1908 else
1909 return false;
1910 } else {
1911 if (ShuffleKind == 1) // unary
1912 return isVMerge(N, UnitSize, 8, 8);
1913 else if (ShuffleKind == 0) // normal
1914 return isVMerge(N, UnitSize, 8, 24);
1915 else
1916 return false;
1917 }
1918}
1919
1920/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1921/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1922/// The ShuffleKind distinguishes between big-endian merges with two
1923/// different inputs (0), either-endian merges with two identical inputs (1),
1924/// and little-endian merges with two different inputs (2). For the latter,
1925/// the input operands are swapped (see PPCInstrAltivec.td).
1927 unsigned ShuffleKind, SelectionDAG &DAG) {
1928 if (DAG.getDataLayout().isLittleEndian()) {
1929 if (ShuffleKind == 1) // unary
1930 return isVMerge(N, UnitSize, 8, 8);
1931 else if (ShuffleKind == 2) // swapped
1932 return isVMerge(N, UnitSize, 8, 24);
1933 else
1934 return false;
1935 } else {
1936 if (ShuffleKind == 1) // unary
1937 return isVMerge(N, UnitSize, 0, 0);
1938 else if (ShuffleKind == 0) // normal
1939 return isVMerge(N, UnitSize, 0, 16);
1940 else
1941 return false;
1942 }
1943}
1944
1945/**
1946 * Common function used to match vmrgew and vmrgow shuffles
1947 *
1948 * The indexOffset determines whether to look for even or odd words in
1949 * the shuffle mask. This is based on the of the endianness of the target
1950 * machine.
1951 * - Little Endian:
1952 * - Use offset of 0 to check for odd elements
1953 * - Use offset of 4 to check for even elements
1954 * - Big Endian:
1955 * - Use offset of 0 to check for even elements
1956 * - Use offset of 4 to check for odd elements
1957 * A detailed description of the vector element ordering for little endian and
1958 * big endian can be found at
1959 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1960 * Targeting your applications - what little endian and big endian IBM XL C/C++
1961 * compiler differences mean to you
1962 *
1963 * The mask to the shuffle vector instruction specifies the indices of the
1964 * elements from the two input vectors to place in the result. The elements are
1965 * numbered in array-access order, starting with the first vector. These vectors
1966 * are always of type v16i8, thus each vector will contain 16 elements of size
1967 * 8. More info on the shuffle vector can be found in the
1968 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1969 * Language Reference.
1970 *
1971 * The RHSStartValue indicates whether the same input vectors are used (unary)
1972 * or two different input vectors are used, based on the following:
1973 * - If the instruction uses the same vector for both inputs, the range of the
1974 * indices will be 0 to 15. In this case, the RHSStart value passed should
1975 * be 0.
1976 * - If the instruction has two different vectors then the range of the
1977 * indices will be 0 to 31. In this case, the RHSStart value passed should
1978 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1979 * to 31 specify elements in the second vector).
1980 *
1981 * \param[in] N The shuffle vector SD Node to analyze
1982 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1983 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1984 * vector to the shuffle_vector instruction
1985 * \return true iff this shuffle vector represents an even or odd word merge
1986 */
1987static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1988 unsigned RHSStartValue) {
1989 if (N->getValueType(0) != MVT::v16i8)
1990 return false;
1991
1992 for (unsigned i = 0; i < 2; ++i)
1993 for (unsigned j = 0; j < 4; ++j)
1994 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1995 i*RHSStartValue+j+IndexOffset) ||
1996 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1997 i*RHSStartValue+j+IndexOffset+8))
1998 return false;
1999 return true;
2000}
2001
2002/**
2003 * Determine if the specified shuffle mask is suitable for the vmrgew or
2004 * vmrgow instructions.
2005 *
2006 * \param[in] N The shuffle vector SD Node to analyze
2007 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2008 * \param[in] ShuffleKind Identify the type of merge:
2009 * - 0 = big-endian merge with two different inputs;
2010 * - 1 = either-endian merge with two identical inputs;
2011 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2012 * little-endian merges).
2013 * \param[in] DAG The current SelectionDAG
2014 * \return true iff this shuffle mask
2015 */
2017 unsigned ShuffleKind, SelectionDAG &DAG) {
2018 if (DAG.getDataLayout().isLittleEndian()) {
2019 unsigned indexOffset = CheckEven ? 4 : 0;
2020 if (ShuffleKind == 1) // Unary
2021 return isVMerge(N, indexOffset, 0);
2022 else if (ShuffleKind == 2) // swapped
2023 return isVMerge(N, indexOffset, 16);
2024 else
2025 return false;
2026 }
2027 else {
2028 unsigned indexOffset = CheckEven ? 0 : 4;
2029 if (ShuffleKind == 1) // Unary
2030 return isVMerge(N, indexOffset, 0);
2031 else if (ShuffleKind == 0) // Normal
2032 return isVMerge(N, indexOffset, 16);
2033 else
2034 return false;
2035 }
2036 return false;
2037}
2038
2039/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2040/// amount, otherwise return -1.
2041/// The ShuffleKind distinguishes between big-endian operations with two
2042/// different inputs (0), either-endian operations with two identical inputs
2043/// (1), and little-endian operations with two different inputs (2). For the
2044/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2045int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2046 SelectionDAG &DAG) {
2047 if (N->getValueType(0) != MVT::v16i8)
2048 return -1;
2049
2051
2052 // Find the first non-undef value in the shuffle mask.
2053 unsigned i;
2054 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2055 /*search*/;
2056
2057 if (i == 16) return -1; // all undef.
2058
2059 // Otherwise, check to see if the rest of the elements are consecutively
2060 // numbered from this value.
2061 unsigned ShiftAmt = SVOp->getMaskElt(i);
2062 if (ShiftAmt < i) return -1;
2063
2064 ShiftAmt -= i;
2065 bool isLE = DAG.getDataLayout().isLittleEndian();
2066
2067 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2068 // Check the rest of the elements to see if they are consecutive.
2069 for (++i; i != 16; ++i)
2070 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2071 return -1;
2072 } else if (ShuffleKind == 1) {
2073 // Check the rest of the elements to see if they are consecutive.
2074 for (++i; i != 16; ++i)
2075 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2076 return -1;
2077 } else
2078 return -1;
2079
2080 if (isLE)
2081 ShiftAmt = 16 - ShiftAmt;
2082
2083 return ShiftAmt;
2084}
2085
2086/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2087/// specifies a splat of a single element that is suitable for input to
2088/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2090 EVT VT = N->getValueType(0);
2091 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2092 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2093
2094 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2095 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2096
2097 // The consecutive indices need to specify an element, not part of two
2098 // different elements. So abandon ship early if this isn't the case.
2099 if (N->getMaskElt(0) % EltSize != 0)
2100 return false;
2101
2102 // This is a splat operation if each element of the permute is the same, and
2103 // if the value doesn't reference the second vector.
2104 unsigned ElementBase = N->getMaskElt(0);
2105
2106 // FIXME: Handle UNDEF elements too!
2107 if (ElementBase >= 16)
2108 return false;
2109
2110 // Check that the indices are consecutive, in the case of a multi-byte element
2111 // splatted with a v16i8 mask.
2112 for (unsigned i = 1; i != EltSize; ++i)
2113 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2114 return false;
2115
2116 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2117 // An UNDEF element is a sequence of UNDEF bytes.
2118 if (N->getMaskElt(i) < 0) {
2119 for (unsigned j = 1; j != EltSize; ++j)
2120 if (N->getMaskElt(i + j) >= 0)
2121 return false;
2122 } else
2123 for (unsigned j = 0; j != EltSize; ++j)
2124 if (N->getMaskElt(i + j) != N->getMaskElt(j))
2125 return false;
2126 }
2127 return true;
2128}
2129
2130/// Check that the mask is shuffling N byte elements. Within each N byte
2131/// element of the mask, the indices could be either in increasing or
2132/// decreasing order as long as they are consecutive.
2133/// \param[in] N the shuffle vector SD Node to analyze
2134/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2135/// Word/DoubleWord/QuadWord).
2136/// \param[in] StepLen the delta indices number among the N byte element, if
2137/// the mask is in increasing/decreasing order then it is 1/-1.
2138/// \return true iff the mask is shuffling N byte elements.
2139static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2140 int StepLen) {
2141 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2142 "Unexpected element width.");
2143 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2144
2145 unsigned NumOfElem = 16 / Width;
2146 unsigned MaskVal[16]; // Width is never greater than 16
2147 for (unsigned i = 0; i < NumOfElem; ++i) {
2148 MaskVal[0] = N->getMaskElt(i * Width);
2149 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2150 return false;
2151 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2152 return false;
2153 }
2154
2155 for (unsigned int j = 1; j < Width; ++j) {
2156 MaskVal[j] = N->getMaskElt(i * Width + j);
2157 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2158 return false;
2159 }
2160 }
2161 }
2162
2163 return true;
2164}
2165
2166bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2167 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2168 if (!isNByteElemShuffleMask(N, 4, 1))
2169 return false;
2170
2171 // Now we look at mask elements 0,4,8,12
2172 unsigned M0 = N->getMaskElt(0) / 4;
2173 unsigned M1 = N->getMaskElt(4) / 4;
2174 unsigned M2 = N->getMaskElt(8) / 4;
2175 unsigned M3 = N->getMaskElt(12) / 4;
2176 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2177 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2178
2179 // Below, let H and L be arbitrary elements of the shuffle mask
2180 // where H is in the range [4,7] and L is in the range [0,3].
2181 // H, 1, 2, 3 or L, 5, 6, 7
2182 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2183 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2184 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2185 InsertAtByte = IsLE ? 12 : 0;
2186 Swap = M0 < 4;
2187 return true;
2188 }
2189 // 0, H, 2, 3 or 4, L, 6, 7
2190 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2191 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2192 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2193 InsertAtByte = IsLE ? 8 : 4;
2194 Swap = M1 < 4;
2195 return true;
2196 }
2197 // 0, 1, H, 3 or 4, 5, L, 7
2198 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2199 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2200 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2201 InsertAtByte = IsLE ? 4 : 8;
2202 Swap = M2 < 4;
2203 return true;
2204 }
2205 // 0, 1, 2, H or 4, 5, 6, L
2206 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2207 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2208 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2209 InsertAtByte = IsLE ? 0 : 12;
2210 Swap = M3 < 4;
2211 return true;
2212 }
2213
2214 // If both vector operands for the shuffle are the same vector, the mask will
2215 // contain only elements from the first one and the second one will be undef.
2216 if (N->getOperand(1).isUndef()) {
2217 ShiftElts = 0;
2218 Swap = true;
2219 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2220 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2221 InsertAtByte = IsLE ? 12 : 0;
2222 return true;
2223 }
2224 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2225 InsertAtByte = IsLE ? 8 : 4;
2226 return true;
2227 }
2228 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2229 InsertAtByte = IsLE ? 4 : 8;
2230 return true;
2231 }
2232 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2233 InsertAtByte = IsLE ? 0 : 12;
2234 return true;
2235 }
2236 }
2237
2238 return false;
2239}
2240
2242 bool &Swap, bool IsLE) {
2243 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2244 // Ensure each byte index of the word is consecutive.
2245 if (!isNByteElemShuffleMask(N, 4, 1))
2246 return false;
2247
2248 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2249 unsigned M0 = N->getMaskElt(0) / 4;
2250 unsigned M1 = N->getMaskElt(4) / 4;
2251 unsigned M2 = N->getMaskElt(8) / 4;
2252 unsigned M3 = N->getMaskElt(12) / 4;
2253
2254 // If both vector operands for the shuffle are the same vector, the mask will
2255 // contain only elements from the first one and the second one will be undef.
2256 if (N->getOperand(1).isUndef()) {
2257 assert(M0 < 4 && "Indexing into an undef vector?");
2258 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2259 return false;
2260
2261 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2262 Swap = false;
2263 return true;
2264 }
2265
2266 // Ensure each word index of the ShuffleVector Mask is consecutive.
2267 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2268 return false;
2269
2270 if (IsLE) {
2271 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2272 // Input vectors don't need to be swapped if the leading element
2273 // of the result is one of the 3 left elements of the second vector
2274 // (or if there is no shift to be done at all).
2275 Swap = false;
2276 ShiftElts = (8 - M0) % 8;
2277 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2278 // Input vectors need to be swapped if the leading element
2279 // of the result is one of the 3 left elements of the first vector
2280 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2281 Swap = true;
2282 ShiftElts = (4 - M0) % 4;
2283 }
2284
2285 return true;
2286 } else { // BE
2287 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2288 // Input vectors don't need to be swapped if the leading element
2289 // of the result is one of the 4 elements of the first vector.
2290 Swap = false;
2291 ShiftElts = M0;
2292 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2293 // Input vectors need to be swapped if the leading element
2294 // of the result is one of the 4 elements of the right vector.
2295 Swap = true;
2296 ShiftElts = M0 - 4;
2297 }
2298
2299 return true;
2300 }
2301}
2302
2304 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2305
2306 if (!isNByteElemShuffleMask(N, Width, -1))
2307 return false;
2308
2309 for (int i = 0; i < 16; i += Width)
2310 if (N->getMaskElt(i) != i + Width - 1)
2311 return false;
2312
2313 return true;
2314}
2315
2319
2323
2327
2331
2332/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2333/// if the inputs to the instruction should be swapped and set \p DM to the
2334/// value for the immediate.
2335/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2336/// AND element 0 of the result comes from the first input (LE) or second input
2337/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2338/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2339/// mask.
2341 bool &Swap, bool IsLE) {
2342 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2343
2344 // Ensure each byte index of the double word is consecutive.
2345 if (!isNByteElemShuffleMask(N, 8, 1))
2346 return false;
2347
2348 unsigned M0 = N->getMaskElt(0) / 8;
2349 unsigned M1 = N->getMaskElt(8) / 8;
2350 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2351
2352 // If both vector operands for the shuffle are the same vector, the mask will
2353 // contain only elements from the first one and the second one will be undef.
2354 if (N->getOperand(1).isUndef()) {
2355 if ((M0 | M1) < 2) {
2356 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2357 Swap = false;
2358 return true;
2359 } else
2360 return false;
2361 }
2362
2363 if (IsLE) {
2364 if (M0 > 1 && M1 < 2) {
2365 Swap = false;
2366 } else if (M0 < 2 && M1 > 1) {
2367 M0 = (M0 + 2) % 4;
2368 M1 = (M1 + 2) % 4;
2369 Swap = true;
2370 } else
2371 return false;
2372
2373 // Note: if control flow comes here that means Swap is already set above
2374 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2375 return true;
2376 } else { // BE
2377 if (M0 < 2 && M1 > 1) {
2378 Swap = false;
2379 } else if (M0 > 1 && M1 < 2) {
2380 M0 = (M0 + 2) % 4;
2381 M1 = (M1 + 2) % 4;
2382 Swap = true;
2383 } else
2384 return false;
2385
2386 // Note: if control flow comes here that means Swap is already set above
2387 DM = (M0 << 1) + (M1 & 1);
2388 return true;
2389 }
2390}
2391
2392
2393/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2394/// appropriate for PPC mnemonics (which have a big endian bias - namely
2395/// elements are counted from the left of the vector register).
2396unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2397 SelectionDAG &DAG) {
2399 assert(isSplatShuffleMask(SVOp, EltSize));
2400 EVT VT = SVOp->getValueType(0);
2401
2402 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2403 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2404 : SVOp->getMaskElt(0);
2405
2406 if (DAG.getDataLayout().isLittleEndian())
2407 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2408 else
2409 return SVOp->getMaskElt(0) / EltSize;
2410}
2411
2412/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2413/// by using a vspltis[bhw] instruction of the specified element size, return
2414/// the constant being splatted. The ByteSize field indicates the number of
2415/// bytes of each element [124] -> [bhw].
2417 SDValue OpVal;
2418
2419 // If ByteSize of the splat is bigger than the element size of the
2420 // build_vector, then we have a case where we are checking for a splat where
2421 // multiple elements of the buildvector are folded together into a single
2422 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2423 unsigned EltSize = 16/N->getNumOperands();
2424 if (EltSize < ByteSize) {
2425 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2426 SDValue UniquedVals[4];
2427 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2428
2429 // See if all of the elements in the buildvector agree across.
2430 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2431 if (N->getOperand(i).isUndef()) continue;
2432 // If the element isn't a constant, bail fully out.
2433 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2434
2435 if (!UniquedVals[i&(Multiple-1)].getNode())
2436 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2437 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2438 return SDValue(); // no match.
2439 }
2440
2441 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2442 // either constant or undef values that are identical for each chunk. See
2443 // if these chunks can form into a larger vspltis*.
2444
2445 // Check to see if all of the leading entries are either 0 or -1. If
2446 // neither, then this won't fit into the immediate field.
2447 bool LeadingZero = true;
2448 bool LeadingOnes = true;
2449 for (unsigned i = 0; i != Multiple-1; ++i) {
2450 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2451
2452 LeadingZero &= isNullConstant(UniquedVals[i]);
2453 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2454 }
2455 // Finally, check the least significant entry.
2456 if (LeadingZero) {
2457 if (!UniquedVals[Multiple-1].getNode())
2458 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2459 int Val = UniquedVals[Multiple - 1]->getAsZExtVal();
2460 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2461 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2462 }
2463 if (LeadingOnes) {
2464 if (!UniquedVals[Multiple-1].getNode())
2465 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2466 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2467 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2468 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2469 }
2470
2471 return SDValue();
2472 }
2473
2474 // Check to see if this buildvec has a single non-undef value in its elements.
2475 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2476 if (N->getOperand(i).isUndef()) continue;
2477 if (!OpVal.getNode())
2478 OpVal = N->getOperand(i);
2479 else if (OpVal != N->getOperand(i))
2480 return SDValue();
2481 }
2482
2483 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2484
2485 unsigned ValSizeInBytes = EltSize;
2486 uint64_t Value = 0;
2487 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2488 Value = CN->getZExtValue();
2489 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2490 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2491 Value = llvm::bit_cast<uint32_t>(CN->getValueAPF().convertToFloat());
2492 }
2493
2494 // If the splat value is larger than the element value, then we can never do
2495 // this splat. The only case that we could fit the replicated bits into our
2496 // immediate field for would be zero, and we prefer to use vxor for it.
2497 if (ValSizeInBytes < ByteSize) return SDValue();
2498
2499 // If the element value is larger than the splat value, check if it consists
2500 // of a repeated bit pattern of size ByteSize.
2501 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2502 return SDValue();
2503
2504 // Properly sign extend the value.
2505 int MaskVal = SignExtend32(Value, ByteSize * 8);
2506
2507 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2508 if (MaskVal == 0) return SDValue();
2509
2510 // Finally, if this value fits in a 5 bit sext field, return it
2511 if (SignExtend32<5>(MaskVal) == MaskVal)
2512 return DAG.getSignedTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2513 return SDValue();
2514}
2515
2516//===----------------------------------------------------------------------===//
2517// Addressing Mode Selection
2518//===----------------------------------------------------------------------===//
2519
2520/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2521/// or 64-bit immediate, and if the value can be accurately represented as a
2522/// sign extension from a 16-bit value. If so, this returns true and the
2523/// immediate.
2524bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2525 if (!isa<ConstantSDNode>(N))
2526 return false;
2527
2528 Imm = (int16_t)N->getAsZExtVal();
2529 if (N->getValueType(0) == MVT::i32)
2530 return Imm == (int32_t)N->getAsZExtVal();
2531 else
2532 return Imm == (int64_t)N->getAsZExtVal();
2533}
2535 return isIntS16Immediate(Op.getNode(), Imm);
2536}
2537
2538/// Used when computing address flags for selecting loads and stores.
2539/// If we have an OR, check if the LHS and RHS are provably disjoint.
2540/// An OR of two provably disjoint values is equivalent to an ADD.
2541/// Most PPC load/store instructions compute the effective address as a sum,
2542/// so doing this conversion is useful.
2543static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2544 if (N.getOpcode() != ISD::OR)
2545 return false;
2546 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2547 if (!LHSKnown.Zero.getBoolValue())
2548 return false;
2549 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2550 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2551}
2552
2553/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2554/// be represented as an indexed [r+r] operation.
2556 SDValue &Index,
2557 SelectionDAG &DAG) const {
2558 for (SDNode *U : N->users()) {
2559 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2560 if (Memop->getMemoryVT() == MVT::f64) {
2561 Base = N.getOperand(0);
2562 Index = N.getOperand(1);
2563 return true;
2564 }
2565 }
2566 }
2567 return false;
2568}
2569
2570/// isIntS34Immediate - This method tests if value of node given can be
2571/// accurately represented as a sign extension from a 34-bit value. If so,
2572/// this returns true and the immediate.
2573bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2574 if (!isa<ConstantSDNode>(N))
2575 return false;
2576
2577 Imm = cast<ConstantSDNode>(N)->getSExtValue();
2578 return isInt<34>(Imm);
2579}
2581 return isIntS34Immediate(Op.getNode(), Imm);
2582}
2583
2584/// SelectAddressRegReg - Given the specified addressed, check to see if it
2585/// can be represented as an indexed [r+r] operation. Returns false if it
2586/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2587/// non-zero and N can be represented by a base register plus a signed 16-bit
2588/// displacement, make a more precise judgement by checking (displacement % \p
2589/// EncodingAlignment).
2591 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2592 MaybeAlign EncodingAlignment) const {
2593 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2594 // a [pc+imm].
2596 return false;
2597
2598 int16_t Imm = 0;
2599 if (N.getOpcode() == ISD::ADD) {
2600 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2601 // SPE load/store can only handle 8-bit offsets.
2602 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2603 return true;
2604 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2605 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2606 return false; // r+i
2607 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2608 return false; // r+i
2609
2610 Base = N.getOperand(0);
2611 Index = N.getOperand(1);
2612 return true;
2613 } else if (N.getOpcode() == ISD::OR) {
2614 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2615 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2616 return false; // r+i can fold it if we can.
2617
2618 // If this is an or of disjoint bitfields, we can codegen this as an add
2619 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2620 // disjoint.
2621 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2622
2623 if (LHSKnown.Zero.getBoolValue()) {
2624 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2625 // If all of the bits are known zero on the LHS or RHS, the add won't
2626 // carry.
2627 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2628 Base = N.getOperand(0);
2629 Index = N.getOperand(1);
2630 return true;
2631 }
2632 }
2633 }
2634
2635 return false;
2636}
2637
2638// If we happen to be doing an i64 load or store into a stack slot that has
2639// less than a 4-byte alignment, then the frame-index elimination may need to
2640// use an indexed load or store instruction (because the offset may not be a
2641// multiple of 4). The extra register needed to hold the offset comes from the
2642// register scavenger, and it is possible that the scavenger will need to use
2643// an emergency spill slot. As a result, we need to make sure that a spill slot
2644// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2645// stack slot.
2646static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2647 // FIXME: This does not handle the LWA case.
2648 if (VT != MVT::i64)
2649 return;
2650
2651 // NOTE: We'll exclude negative FIs here, which come from argument
2652 // lowering, because there are no known test cases triggering this problem
2653 // using packed structures (or similar). We can remove this exclusion if
2654 // we find such a test case. The reason why this is so test-case driven is
2655 // because this entire 'fixup' is only to prevent crashes (from the
2656 // register scavenger) on not-really-valid inputs. For example, if we have:
2657 // %a = alloca i1
2658 // %b = bitcast i1* %a to i64*
2659 // store i64* a, i64 b
2660 // then the store should really be marked as 'align 1', but is not. If it
2661 // were marked as 'align 1' then the indexed form would have been
2662 // instruction-selected initially, and the problem this 'fixup' is preventing
2663 // won't happen regardless.
2664 if (FrameIdx < 0)
2665 return;
2666
2668 MachineFrameInfo &MFI = MF.getFrameInfo();
2669
2670 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2671 return;
2672
2673 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2674 FuncInfo->setHasNonRISpills();
2675}
2676
2677/// Returns true if the address N can be represented by a base register plus
2678/// a signed 16-bit displacement [r+imm], and if it is not better
2679/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2680/// displacements that are multiples of that value.
2682 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2683 MaybeAlign EncodingAlignment) const {
2684 // FIXME dl should come from parent load or store, not from address
2685 SDLoc dl(N);
2686
2687 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2688 // a [pc+imm].
2690 return false;
2691
2692 // If this can be more profitably realized as r+r, fail.
2693 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2694 return false;
2695
2696 if (N.getOpcode() == ISD::ADD) {
2697 int16_t imm = 0;
2698 if (isIntS16Immediate(N.getOperand(1), imm) &&
2699 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2700 Disp = DAG.getSignedTargetConstant(imm, dl, N.getValueType());
2701 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2702 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2703 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2704 } else {
2705 Base = N.getOperand(0);
2706 }
2707 return true; // [r+i]
2708 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2709 // Match LOAD (ADD (X, Lo(G))).
2710 assert(!N.getOperand(1).getConstantOperandVal(1) &&
2711 "Cannot handle constant offsets yet!");
2712 Disp = N.getOperand(1).getOperand(0); // The global address.
2717 Base = N.getOperand(0);
2718 return true; // [&g+r]
2719 }
2720 } else if (N.getOpcode() == ISD::OR) {
2721 int16_t imm = 0;
2722 if (isIntS16Immediate(N.getOperand(1), imm) &&
2723 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2724 // If this is an or of disjoint bitfields, we can codegen this as an add
2725 // (for better address arithmetic) if the LHS and RHS of the OR are
2726 // provably disjoint.
2727 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2728
2729 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2730 // If all of the bits are known zero on the LHS or RHS, the add won't
2731 // carry.
2732 if (FrameIndexSDNode *FI =
2733 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2734 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2735 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2736 } else {
2737 Base = N.getOperand(0);
2738 }
2739 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2740 return true;
2741 }
2742 }
2743 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2744 // Loading from a constant address.
2745
2746 // If this address fits entirely in a 16-bit sext immediate field, codegen
2747 // this as "d, 0"
2748 int16_t Imm;
2749 if (isIntS16Immediate(CN, Imm) &&
2750 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2751 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2752 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2753 CN->getValueType(0));
2754 return true;
2755 }
2756
2757 // Handle 32-bit sext immediates with LIS + addr mode.
2758 if ((CN->getValueType(0) == MVT::i32 ||
2759 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2760 (!EncodingAlignment ||
2761 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2762 int Addr = (int)CN->getZExtValue();
2763
2764 // Otherwise, break this down into an LIS + disp.
2765 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2766
2767 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2768 MVT::i32);
2769 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2770 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2771 return true;
2772 }
2773 }
2774
2775 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2777 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2778 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2779 } else
2780 Base = N;
2781 return true; // [r+0]
2782}
2783
2784/// Similar to the 16-bit case but for instructions that take a 34-bit
2785/// displacement field (prefixed loads/stores).
2787 SDValue &Base,
2788 SelectionDAG &DAG) const {
2789 // Only on 64-bit targets.
2790 if (N.getValueType() != MVT::i64)
2791 return false;
2792
2793 SDLoc dl(N);
2794 int64_t Imm = 0;
2795
2796 if (N.getOpcode() == ISD::ADD) {
2797 if (!isIntS34Immediate(N.getOperand(1), Imm))
2798 return false;
2799 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2800 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2801 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2802 else
2803 Base = N.getOperand(0);
2804 return true;
2805 }
2806
2807 if (N.getOpcode() == ISD::OR) {
2808 if (!isIntS34Immediate(N.getOperand(1), Imm))
2809 return false;
2810 // If this is an or of disjoint bitfields, we can codegen this as an add
2811 // (for better address arithmetic) if the LHS and RHS of the OR are
2812 // provably disjoint.
2813 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2814 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2815 return false;
2816 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2817 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2818 else
2819 Base = N.getOperand(0);
2820 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2821 return true;
2822 }
2823
2824 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2825 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2826 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2827 return true;
2828 }
2829
2830 return false;
2831}
2832
2833/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2834/// represented as an indexed [r+r] operation.
2836 SDValue &Index,
2837 SelectionDAG &DAG) const {
2838 // Check to see if we can easily represent this as an [r+r] address. This
2839 // will fail if it thinks that the address is more profitably represented as
2840 // reg+imm, e.g. where imm = 0.
2841 if (SelectAddressRegReg(N, Base, Index, DAG))
2842 return true;
2843
2844 // If the address is the result of an add, we will utilize the fact that the
2845 // address calculation includes an implicit add. However, we can reduce
2846 // register pressure if we do not materialize a constant just for use as the
2847 // index register. We only get rid of the add if it is not an add of a
2848 // value and a 16-bit signed constant and both have a single use.
2849 int16_t imm = 0;
2850 if (N.getOpcode() == ISD::ADD &&
2851 (!isIntS16Immediate(N.getOperand(1), imm) ||
2852 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2853 Base = N.getOperand(0);
2854 Index = N.getOperand(1);
2855 return true;
2856 }
2857
2858 // Otherwise, do it the hard way, using R0 as the base register.
2859 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2860 N.getValueType());
2861 Index = N;
2862 return true;
2863}
2864
2865template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2866 Ty *PCRelCand = dyn_cast<Ty>(N);
2867 return PCRelCand && (PPCInstrInfo::hasPCRelFlag(PCRelCand->getTargetFlags()));
2868}
2869
2870/// Returns true if this address is a PC Relative address.
2871/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2872/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2874 // This is a materialize PC Relative node. Always select this as PC Relative.
2875 Base = N;
2876 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2877 return true;
2882 return true;
2883 return false;
2884}
2885
2886/// Returns true if we should use a direct load into vector instruction
2887/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2888static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2889
2890 // If there are any other uses other than scalar to vector, then we should
2891 // keep it as a scalar load -> direct move pattern to prevent multiple
2892 // loads.
2894 if (!LD)
2895 return false;
2896
2897 EVT MemVT = LD->getMemoryVT();
2898 if (!MemVT.isSimple())
2899 return false;
2900 switch(MemVT.getSimpleVT().SimpleTy) {
2901 case MVT::i64:
2902 break;
2903 case MVT::i32:
2904 if (!ST.hasP8Vector())
2905 return false;
2906 break;
2907 case MVT::i16:
2908 case MVT::i8:
2909 if (!ST.hasP9Vector())
2910 return false;
2911 break;
2912 default:
2913 return false;
2914 }
2915
2916 SDValue LoadedVal(N, 0);
2917 if (!LoadedVal.hasOneUse())
2918 return false;
2919
2920 for (SDUse &Use : LD->uses())
2921 if (Use.getResNo() == 0 &&
2922 Use.getUser()->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2923 Use.getUser()->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2924 return false;
2925
2926 return true;
2927}
2928
2929/// getPreIndexedAddressParts - returns true by value, base pointer and
2930/// offset pointer and addressing mode by reference if the node's address
2931/// can be legally represented as pre-indexed load / store address.
2933 SDValue &Offset,
2935 SelectionDAG &DAG) const {
2936 if (DisablePPCPreinc) return false;
2937
2938 bool isLoad = true;
2939 SDValue Ptr;
2940 EVT VT;
2941 Align Alignment;
2942 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2943 Ptr = LD->getBasePtr();
2944 VT = LD->getMemoryVT();
2945 Alignment = LD->getAlign();
2946 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2947 Ptr = ST->getBasePtr();
2948 VT = ST->getMemoryVT();
2949 Alignment = ST->getAlign();
2950 isLoad = false;
2951 } else
2952 return false;
2953
2954 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2955 // instructions because we can fold these into a more efficient instruction
2956 // instead, (such as LXSD).
2957 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2958 return false;
2959 }
2960
2961 // PowerPC doesn't have preinc load/store instructions for vectors
2962 if (VT.isVector())
2963 return false;
2964
2965 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2966 // Common code will reject creating a pre-inc form if the base pointer
2967 // is a frame index, or if N is a store and the base pointer is either
2968 // the same as or a predecessor of the value being stored. Check for
2969 // those situations here, and try with swapped Base/Offset instead.
2970 bool Swap = false;
2971
2973 Swap = true;
2974 else if (!isLoad) {
2975 SDValue Val = cast<StoreSDNode>(N)->getValue();
2976 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2977 Swap = true;
2978 }
2979
2980 if (Swap)
2982
2983 AM = ISD::PRE_INC;
2984 return true;
2985 }
2986
2987 // LDU/STU can only handle immediates that are a multiple of 4.
2988 if (VT != MVT::i64) {
2989 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
2990 return false;
2991 } else {
2992 // LDU/STU need an address with at least 4-byte alignment.
2993 if (Alignment < Align(4))
2994 return false;
2995
2996 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2997 return false;
2998 }
2999
3000 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3001 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3002 // sext i32 to i64 when addr mode is r+i.
3003 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3004 LD->getExtensionType() == ISD::SEXTLOAD &&
3006 return false;
3007 }
3008
3009 AM = ISD::PRE_INC;
3010 return true;
3011}
3012
3013//===----------------------------------------------------------------------===//
3014// LowerOperation implementation
3015//===----------------------------------------------------------------------===//
3016
3017/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3018/// and LoOpFlags to the target MO flags.
3019static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3020 unsigned &HiOpFlags, unsigned &LoOpFlags,
3021 const GlobalValue *GV = nullptr) {
3022 HiOpFlags = PPCII::MO_HA;
3023 LoOpFlags = PPCII::MO_LO;
3024
3025 // Don't use the pic base if not in PIC relocation model.
3026 if (IsPIC) {
3027 HiOpFlags = PPCII::MO_PIC_HA_FLAG;
3028 LoOpFlags = PPCII::MO_PIC_LO_FLAG;
3029 }
3030}
3031
3032static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3033 SelectionDAG &DAG) {
3034 SDLoc DL(HiPart);
3035 EVT PtrVT = HiPart.getValueType();
3036 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3037
3038 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3039 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3040
3041 // With PIC, the first instruction is actually "GR+hi(&G)".
3042 if (isPIC)
3043 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3044 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3045
3046 // Generate non-pic code that has direct accesses to the constant pool.
3047 // The address of the global is just (hi(&g)+lo(&g)).
3048 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3049}
3050
3052 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3053 FuncInfo->setUsesTOCBasePtr();
3054}
3055
3059
3060SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3061 SDValue GA) const {
3062 EVT VT = Subtarget.getScalarIntVT();
3063 SDValue Reg = Subtarget.isPPC64() ? DAG.getRegister(PPC::X2, VT)
3064 : Subtarget.isAIXABI()
3065 ? DAG.getRegister(PPC::R2, VT)
3066 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3067 SDValue Ops[] = { GA, Reg };
3068 return DAG.getMemIntrinsicNode(
3069 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3072}
3073
3074SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3075 SelectionDAG &DAG) const {
3076 EVT PtrVT = Op.getValueType();
3077 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3078 const Constant *C = CP->getConstVal();
3079
3080 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3081 // The actual address of the GlobalValue is stored in the TOC.
3082 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3083 if (Subtarget.isUsingPCRelativeCalls()) {
3084 SDLoc DL(CP);
3085 EVT Ty = getPointerTy(DAG.getDataLayout());
3086 SDValue ConstPool = DAG.getTargetConstantPool(
3087 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3088 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3089 }
3090 setUsesTOCBasePtr(DAG);
3091 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3092 return getTOCEntry(DAG, SDLoc(CP), GA);
3093 }
3094
3095 unsigned MOHiFlag, MOLoFlag;
3096 bool IsPIC = isPositionIndependent();
3097 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3098
3099 if (IsPIC && Subtarget.isSVR4ABI()) {
3100 SDValue GA =
3102 return getTOCEntry(DAG, SDLoc(CP), GA);
3103 }
3104
3105 SDValue CPIHi =
3106 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3107 SDValue CPILo =
3108 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3109 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3110}
3111
3112// For 64-bit PowerPC, prefer the more compact relative encodings.
3113// This trades 32 bits per jump table entry for one or two instructions
3114// on the jump site.
3121
3124 return false;
3125 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3126 return true;
3128}
3129
3131 SelectionDAG &DAG) const {
3132 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3134
3135 switch (getTargetMachine().getCodeModel()) {
3136 case CodeModel::Small:
3137 case CodeModel::Medium:
3139 default:
3140 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3142 }
3143}
3144
3145const MCExpr *
3147 unsigned JTI,
3148 MCContext &Ctx) const {
3149 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3151
3152 switch (getTargetMachine().getCodeModel()) {
3153 case CodeModel::Small:
3154 case CodeModel::Medium:
3156 default:
3157 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3158 }
3159}
3160
3161SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3162 EVT PtrVT = Op.getValueType();
3164
3165 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3166 if (Subtarget.isUsingPCRelativeCalls()) {
3167 SDLoc DL(JT);
3168 EVT Ty = getPointerTy(DAG.getDataLayout());
3169 SDValue GA =
3171 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3172 return MatAddr;
3173 }
3174
3175 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3176 // The actual address of the GlobalValue is stored in the TOC.
3177 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3178 setUsesTOCBasePtr(DAG);
3179 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3180 return getTOCEntry(DAG, SDLoc(JT), GA);
3181 }
3182
3183 unsigned MOHiFlag, MOLoFlag;
3184 bool IsPIC = isPositionIndependent();
3185 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3186
3187 if (IsPIC && Subtarget.isSVR4ABI()) {
3188 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3190 return getTOCEntry(DAG, SDLoc(GA), GA);
3191 }
3192
3193 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3194 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3195 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3196}
3197
3198SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3199 SelectionDAG &DAG) const {
3200 EVT PtrVT = Op.getValueType();
3201 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3202 const BlockAddress *BA = BASDN->getBlockAddress();
3203
3204 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3205 if (Subtarget.isUsingPCRelativeCalls()) {
3206 SDLoc DL(BASDN);
3207 EVT Ty = getPointerTy(DAG.getDataLayout());
3208 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3210 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3211 return MatAddr;
3212 }
3213
3214 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3215 // The actual BlockAddress is stored in the TOC.
3216 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3217 setUsesTOCBasePtr(DAG);
3218 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3219 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3220 }
3221
3222 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3223 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3224 return getTOCEntry(
3225 DAG, SDLoc(BASDN),
3226 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3227
3228 unsigned MOHiFlag, MOLoFlag;
3229 bool IsPIC = isPositionIndependent();
3230 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3231 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3232 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3233 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3234}
3235
3236SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3237 SelectionDAG &DAG) const {
3238 if (Subtarget.isAIXABI())
3239 return LowerGlobalTLSAddressAIX(Op, DAG);
3240
3241 return LowerGlobalTLSAddressLinux(Op, DAG);
3242}
3243
3244/// updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings,
3245/// and then apply the update.
3247 SelectionDAG &DAG,
3248 const TargetMachine &TM) {
3249 // Initialize TLS model opt setting lazily:
3250 // (1) Use initial-exec for single TLS var references within current function.
3251 // (2) Use local-dynamic for multiple TLS var references within current
3252 // function.
3253 PPCFunctionInfo *FuncInfo =
3255 if (!FuncInfo->isAIXFuncTLSModelOptInitDone()) {
3257 // Iterate over all instructions within current function, collect all TLS
3258 // global variables (global variables taken as the first parameter to
3259 // Intrinsic::threadlocal_address).
3260 const Function &Func = DAG.getMachineFunction().getFunction();
3261 for (const BasicBlock &BB : Func)
3262 for (const Instruction &I : BB)
3263 if (I.getOpcode() == Instruction::Call)
3264 if (const CallInst *CI = dyn_cast<const CallInst>(&I))
3265 if (Function *CF = CI->getCalledFunction())
3266 if (CF->isDeclaration() &&
3267 CF->getIntrinsicID() == Intrinsic::threadlocal_address)
3268 if (const GlobalValue *GV =
3269 dyn_cast<GlobalValue>(I.getOperand(0))) {
3270 TLSModel::Model GVModel = TM.getTLSModel(GV);
3271 if (GVModel == TLSModel::LocalDynamic)
3272 TLSGV.insert(GV);
3273 }
3274
3275 unsigned TLSGVCnt = TLSGV.size();
3276 LLVM_DEBUG(dbgs() << format("LocalDynamic TLSGV count:%d\n", TLSGVCnt));
3277 if (TLSGVCnt <= PPCAIXTLSModelOptUseIEForLDLimit)
3278 FuncInfo->setAIXFuncUseTLSIEForLD();
3280 }
3281
3282 if (FuncInfo->isAIXFuncUseTLSIEForLD()) {
3283 LLVM_DEBUG(
3284 dbgs() << DAG.getMachineFunction().getName()
3285 << " function is using the TLS-IE model for TLS-LD access.\n");
3286 Model = TLSModel::InitialExec;
3287 }
3288}
3289
3290SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3291 SelectionDAG &DAG) const {
3292 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3293
3294 if (DAG.getTarget().useEmulatedTLS())
3295 report_fatal_error("Emulated TLS is not yet supported on AIX");
3296
3297 SDLoc dl(GA);
3298 const GlobalValue *GV = GA->getGlobal();
3299 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3300 bool Is64Bit = Subtarget.isPPC64();
3302
3303 // Apply update to the TLS model.
3304 if (Subtarget.hasAIXShLibTLSModelOpt())
3306
3307 // TLS variables are accessed through TOC entries.
3308 // To support this, set the DAG to use the TOC base pointer.
3309 setUsesTOCBasePtr(DAG);
3310
3311 bool IsTLSLocalExecModel = Model == TLSModel::LocalExec;
3312
3313 if (IsTLSLocalExecModel || Model == TLSModel::InitialExec) {
3314 bool HasAIXSmallLocalExecTLS = Subtarget.hasAIXSmallLocalExecTLS();
3315 bool HasAIXSmallTLSGlobalAttr = false;
3316 SDValue VariableOffsetTGA =
3317 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_FLAG);
3318 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3319 SDValue TLSReg;
3320
3321 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
3322 if (GVar->hasAttribute("aix-small-tls"))
3323 HasAIXSmallTLSGlobalAttr = true;
3324
3325 if (Is64Bit) {
3326 // For local-exec and initial-exec on AIX (64-bit), the sequence generated
3327 // involves a load of the variable offset (from the TOC), followed by an
3328 // add of the loaded variable offset to R13 (the thread pointer).
3329 // This code sequence looks like:
3330 // ld reg1,var[TC](2)
3331 // add reg2, reg1, r13 // r13 contains the thread pointer
3332 TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3333
3334 // With the -maix-small-local-exec-tls option, or with the "aix-small-tls"
3335 // global variable attribute, produce a faster access sequence for
3336 // local-exec TLS variables where the offset from the TLS base is encoded
3337 // as an immediate operand.
3338 //
3339 // We only utilize the faster local-exec access sequence when the TLS
3340 // variable has a size within the policy limit. We treat types that are
3341 // not sized or are empty as being over the policy size limit.
3342 if ((HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr) &&
3343 IsTLSLocalExecModel) {
3344 Type *GVType = GV->getValueType();
3345 if (GVType->isSized() && !GVType->isEmptyTy() &&
3346 GV->getDataLayout().getTypeAllocSize(GVType) <=
3348 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA, TLSReg);
3349 }
3350 } else {
3351 // For local-exec and initial-exec on AIX (32-bit), the sequence generated
3352 // involves loading the variable offset from the TOC, generating a call to
3353 // .__get_tpointer to get the thread pointer (which will be in R3), and
3354 // adding the two together:
3355 // lwz reg1,var[TC](2)
3356 // bla .__get_tpointer
3357 // add reg2, reg1, r3
3358 TLSReg = DAG.getNode(PPCISD::GET_TPOINTER, dl, PtrVT);
3359
3360 // We do not implement the 32-bit version of the faster access sequence
3361 // for local-exec that is controlled by the -maix-small-local-exec-tls
3362 // option, or the "aix-small-tls" global variable attribute.
3363 if (HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr)
3364 report_fatal_error("The small-local-exec TLS access sequence is "
3365 "currently only supported on AIX (64-bit mode).");
3366 }
3367 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, VariableOffset);
3368 }
3369
3370 if (Model == TLSModel::LocalDynamic) {
3371 bool HasAIXSmallLocalDynamicTLS = Subtarget.hasAIXSmallLocalDynamicTLS();
3372
3373 // We do not implement the 32-bit version of the faster access sequence
3374 // for local-dynamic that is controlled by -maix-small-local-dynamic-tls.
3375 if (!Is64Bit && HasAIXSmallLocalDynamicTLS)
3376 report_fatal_error("The small-local-dynamic TLS access sequence is "
3377 "currently only supported on AIX (64-bit mode).");
3378
3379 // For local-dynamic on AIX, we need to generate one TOC entry for each
3380 // variable offset, and a single module-handle TOC entry for the entire
3381 // file.
3382
3383 SDValue VariableOffsetTGA =
3384 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSLD_FLAG);
3385 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3386
3388 GlobalVariable *TLSGV =
3389 dyn_cast_or_null<GlobalVariable>(M->getOrInsertGlobal(
3390 StringRef("_$TLSML"), PointerType::getUnqual(*DAG.getContext())));
3392 assert(TLSGV && "Not able to create GV for _$TLSML.");
3393 SDValue ModuleHandleTGA =
3394 DAG.getTargetGlobalAddress(TLSGV, dl, PtrVT, 0, PPCII::MO_TLSLDM_FLAG);
3395 SDValue ModuleHandleTOC = getTOCEntry(DAG, dl, ModuleHandleTGA);
3396 SDValue ModuleHandle =
3397 DAG.getNode(PPCISD::TLSLD_AIX, dl, PtrVT, ModuleHandleTOC);
3398
3399 // With the -maix-small-local-dynamic-tls option, produce a faster access
3400 // sequence for local-dynamic TLS variables where the offset from the
3401 // module-handle is encoded as an immediate operand.
3402 //
3403 // We only utilize the faster local-dynamic access sequence when the TLS
3404 // variable has a size within the policy limit. We treat types that are
3405 // not sized or are empty as being over the policy size limit.
3406 if (HasAIXSmallLocalDynamicTLS) {
3407 Type *GVType = GV->getValueType();
3408 if (GVType->isSized() && !GVType->isEmptyTy() &&
3409 GV->getDataLayout().getTypeAllocSize(GVType) <=
3411 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA,
3412 ModuleHandle);
3413 }
3414
3415 return DAG.getNode(ISD::ADD, dl, PtrVT, ModuleHandle, VariableOffset);
3416 }
3417
3418 // If Local- or Initial-exec or Local-dynamic is not possible or specified,
3419 // all GlobalTLSAddress nodes are lowered using the general-dynamic model. We
3420 // need to generate two TOC entries, one for the variable offset, one for the
3421 // region handle. The global address for the TOC entry of the region handle is
3422 // created with the MO_TLSGDM_FLAG flag and the global address for the TOC
3423 // entry of the variable offset is created with MO_TLSGD_FLAG.
3424 SDValue VariableOffsetTGA =
3425 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3426 SDValue RegionHandleTGA =
3427 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3428 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3429 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3430 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3431 RegionHandle);
3432}
3433
3434SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3435 SelectionDAG &DAG) const {
3436 // FIXME: TLS addresses currently use medium model code sequences,
3437 // which is the most useful form. Eventually support for small and
3438 // large models could be added if users need it, at the cost of
3439 // additional complexity.
3440 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3441 if (DAG.getTarget().useEmulatedTLS())
3442 return LowerToTLSEmulatedModel(GA, DAG);
3443
3444 SDLoc dl(GA);
3445 const GlobalValue *GV = GA->getGlobal();
3446 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3447 bool is64bit = Subtarget.isPPC64();
3448 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3449 PICLevel::Level picLevel = M->getPICLevel();
3450
3451 const TargetMachine &TM = getTargetMachine();
3452 TLSModel::Model Model = TM.getTLSModel(GV);
3453
3454 if (Model == TLSModel::LocalExec) {
3455 if (Subtarget.isUsingPCRelativeCalls()) {
3456 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3457 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3459 SDValue MatAddr =
3460 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3461 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3462 }
3463
3464 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3466 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3468 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3469 : DAG.getRegister(PPC::R2, MVT::i32);
3470
3471 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3472 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3473 }
3474
3475 if (Model == TLSModel::InitialExec) {
3476 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3478 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3479 SDValue TGATLS = DAG.getTargetGlobalAddress(
3480 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_TLS_PCREL_FLAG : PPCII::MO_TLS);
3482 if (IsPCRel) {
3483 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3484 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3485 MachinePointerInfo());
3486 } else {
3487 SDValue GOTPtr;
3488 if (is64bit) {
3489 setUsesTOCBasePtr(DAG);
3490 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3491 GOTPtr =
3492 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3493 } else {
3494 if (!TM.isPositionIndependent())
3495 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3496 else if (picLevel == PICLevel::SmallPIC)
3497 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3498 else
3499 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3500 }
3501 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3502 }
3503 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3504 }
3505
3506 if (Model == TLSModel::GeneralDynamic) {
3507 if (Subtarget.isUsingPCRelativeCalls()) {
3508 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3510 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3511 }
3512
3513 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3514 SDValue GOTPtr;
3515 if (is64bit) {
3516 setUsesTOCBasePtr(DAG);
3517 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3518 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3519 GOTReg, TGA);
3520 } else {
3521 if (picLevel == PICLevel::SmallPIC)
3522 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3523 else
3524 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3525 }
3526 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3527 GOTPtr, TGA, TGA);
3528 }
3529
3530 if (Model == TLSModel::LocalDynamic) {
3531 if (Subtarget.isUsingPCRelativeCalls()) {
3532 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3534 SDValue MatPCRel =
3535 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3536 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3537 }
3538
3539 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3540 SDValue GOTPtr;
3541 if (is64bit) {
3542 setUsesTOCBasePtr(DAG);
3543 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3544 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3545 GOTReg, TGA);
3546 } else {
3547 if (picLevel == PICLevel::SmallPIC)
3548 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3549 else
3550 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3551 }
3552 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3553 PtrVT, GOTPtr, TGA, TGA);
3554 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3555 PtrVT, TLSAddr, TGA);
3556 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3557 }
3558
3559 llvm_unreachable("Unknown TLS model!");
3560}
3561
3562SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3563 SelectionDAG &DAG) const {
3564 EVT PtrVT = Op.getValueType();
3565 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3566 SDLoc DL(GSDN);
3567 const GlobalValue *GV = GSDN->getGlobal();
3568
3569 // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3570 // The actual address of the GlobalValue is stored in the TOC.
3571 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3572 if (Subtarget.isUsingPCRelativeCalls()) {
3573 EVT Ty = getPointerTy(DAG.getDataLayout());
3575 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3577 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3578 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3579 MachinePointerInfo());
3580 return Load;
3581 } else {
3582 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3584 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3585 }
3586 }
3587 setUsesTOCBasePtr(DAG);
3588 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3589 return getTOCEntry(DAG, DL, GA);
3590 }
3591
3592 unsigned MOHiFlag, MOLoFlag;
3593 bool IsPIC = isPositionIndependent();
3594 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3595
3596 if (IsPIC && Subtarget.isSVR4ABI()) {
3597 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3598 GSDN->getOffset(),
3600 return getTOCEntry(DAG, DL, GA);
3601 }
3602
3603 SDValue GAHi =
3604 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3605 SDValue GALo =
3606 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3607
3608 return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3609}
3610
3611SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3612 bool IsStrict = Op->isStrictFPOpcode();
3613 const SDNodeFlags Flags = Op.getNode()->getFlags();
3614 ISD::CondCode CC =
3615 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3616 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3617 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3618 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3619 EVT LHSVT = LHS.getValueType();
3620 SDLoc dl(Op);
3621
3622 // Soften the setcc with libcall if it is fp128 or it is SPE and fp32/fp64.
3623 if (LHSVT == MVT::f128 ||
3624 (Subtarget.hasSPE() && (LHSVT == MVT::f32 || LHSVT == MVT::f64) &&
3625 (!Flags.hasNoNaNs() || !Flags.hasNoInfs()))) {
3626 assert(!Subtarget.hasP9Vector() &&
3627 "SETCC for f128 is already legal under Power9!");
3628 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3629 Op->getOpcode() == ISD::STRICT_FSETCCS);
3630 if (RHS.getNode())
3631 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3632 DAG.getCondCode(CC));
3633 if (IsStrict)
3634 return DAG.getMergeValues({LHS, Chain}, dl);
3635 return LHS;
3636 } else if (LHSVT == MVT::f32 || LHSVT == MVT::f64) {
3637 return Op;
3638 }
3639
3640 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3641
3642 if (Op.getValueType() == MVT::v2i64) {
3643 // When the operands themselves are v2i64 values, we need to do something
3644 // special because VSX has no underlying comparison operations for these.
3645 if (LHS.getValueType() == MVT::v2i64) {
3646 // Equality can be handled by casting to the legal type for Altivec
3647 // comparisons, everything else needs to be expanded.
3648 if (CC != ISD::SETEQ && CC != ISD::SETNE)
3649 return SDValue();
3650 SDValue SetCC32 = DAG.getSetCC(
3651 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3652 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3653 int ShuffV[] = {1, 0, 3, 2};
3654 SDValue Shuff =
3655 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3656 return DAG.getBitcast(MVT::v2i64,
3657 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3658 dl, MVT::v4i32, Shuff, SetCC32));
3659 }
3660
3661 // We handle most of these in the usual way.
3662 return Op;
3663 }
3664
3665 // If we're comparing for equality to zero, expose the fact that this is
3666 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3667 // fold the new nodes.
3668 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3669 return V;
3670
3671 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3672 // Leave comparisons against 0 and -1 alone for now, since they're usually
3673 // optimized. FIXME: revisit this when we can custom lower all setcc
3674 // optimizations.
3675 if (C->isAllOnes() || C->isZero())
3676 return SDValue();
3677 }
3678
3679 // If we have an integer seteq/setne, turn it into a compare against zero
3680 // by xor'ing the rhs with the lhs, which is faster than setting a
3681 // condition register, reading it back out, and masking the correct bit. The
3682 // normal approach here uses sub to do this instead of xor. Using xor exposes
3683 // the result to other bit-twiddling opportunities.
3684 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3685 EVT VT = Op.getValueType();
3686 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3687 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3688 }
3689 return SDValue();
3690}
3691
3692SDValue PPCTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3693 const SDNodeFlags Flags = Op->getFlags();
3694 SDValue Chain = Op.getOperand(0);
3695 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3696 SDValue LHS = Op.getOperand(2);
3697 SDValue RHS = Op.getOperand(3);
3698 SDValue Dest = Op.getOperand(4);
3699 EVT LHSVT = LHS.getValueType();
3700 SDLoc dl(Op);
3701
3702 assert(Subtarget.hasSPE() && "LowerBR_CC used only for targets with SPE");
3703
3704 if ((LHSVT == MVT::f32 || LHSVT == MVT::f64) && Flags.hasNoNaNs() &&
3705 Flags.hasNoInfs())
3706 return Op;
3707
3708 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS);
3709
3710 // If softenSetCCOperands returned a scalar, we need to compare the result
3711 // against zero to select between true and false values.
3712 if (!RHS) {
3713 RHS = DAG.getConstant(0, dl, LHSVT);
3714 CC = ISD::SETNE;
3715 }
3716
3717 return DAG.getNode(ISD::BR_CC, dl, Op.getValueType(), Chain,
3718 DAG.getCondCode(CC), LHS, RHS, Dest);
3719}
3720
3721SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3722 SDNode *Node = Op.getNode();
3723 EVT VT = Node->getValueType(0);
3724 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3725 SDValue InChain = Node->getOperand(0);
3726 SDValue VAListPtr = Node->getOperand(1);
3727 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3728 SDLoc dl(Node);
3729
3730 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3731
3732 // gpr_index
3733 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3734 VAListPtr, MachinePointerInfo(SV), MVT::i8);
3735 InChain = GprIndex.getValue(1);
3736
3737 if (VT == MVT::i64) {
3738 // Check if GprIndex is even
3739 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3740 DAG.getConstant(1, dl, MVT::i32));
3741 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3742 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3743 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3744 DAG.getConstant(1, dl, MVT::i32));
3745 // Align GprIndex to be even if it isn't
3746 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3747 GprIndex);
3748 }
3749
3750 // fpr index is 1 byte after gpr
3751 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3752 DAG.getConstant(1, dl, MVT::i32));
3753
3754 // fpr
3755 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3756 FprPtr, MachinePointerInfo(SV), MVT::i8);
3757 InChain = FprIndex.getValue(1);
3758
3759 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3760 DAG.getConstant(8, dl, MVT::i32));
3761
3762 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3763 DAG.getConstant(4, dl, MVT::i32));
3764
3765 // areas
3766 SDValue OverflowArea =
3767 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3768 InChain = OverflowArea.getValue(1);
3769
3770 SDValue RegSaveArea =
3771 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3772 InChain = RegSaveArea.getValue(1);
3773
3774 // select overflow_area if index > 8
3775 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3776 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3777
3778 // adjustment constant gpr_index * 4/8
3779 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3780 VT.isInteger() ? GprIndex : FprIndex,
3781 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3782 MVT::i32));
3783
3784 // OurReg = RegSaveArea + RegConstant
3785 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3786 RegConstant);
3787
3788 // Floating types are 32 bytes into RegSaveArea
3789 if (VT.isFloatingPoint())
3790 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3791 DAG.getConstant(32, dl, MVT::i32));
3792
3793 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3794 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3795 VT.isInteger() ? GprIndex : FprIndex,
3796 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3797 MVT::i32));
3798
3799 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3800 VT.isInteger() ? VAListPtr : FprPtr,
3801 MachinePointerInfo(SV), MVT::i8);
3802
3803 // determine if we should load from reg_save_area or overflow_area
3804 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3805
3806 // increase overflow_area by 4/8 if gpr/fpr > 8
3807 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3808 DAG.getConstant(VT.isInteger() ? 4 : 8,
3809 dl, MVT::i32));
3810
3811 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3812 OverflowAreaPlusN);
3813
3814 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3815 MachinePointerInfo(), MVT::i32);
3816
3817 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3818}
3819
3820SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3821 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3822
3823 // We have to copy the entire va_list struct:
3824 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3825 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3826 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3827 Align(8), false, true, /*CI=*/nullptr, std::nullopt,
3828 MachinePointerInfo(), MachinePointerInfo());
3829}
3830
3831SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3832 SelectionDAG &DAG) const {
3833 return Op.getOperand(0);
3834}
3835
3836SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3837 MachineFunction &MF = DAG.getMachineFunction();
3838 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3839
3840 assert((Op.getOpcode() == ISD::INLINEASM ||
3841 Op.getOpcode() == ISD::INLINEASM_BR) &&
3842 "Expecting Inline ASM node.");
3843
3844 // If an LR store is already known to be required then there is not point in
3845 // checking this ASM as well.
3846 if (MFI.isLRStoreRequired())
3847 return Op;
3848
3849 // Inline ASM nodes have an optional last operand that is an incoming Flag of
3850 // type MVT::Glue. We want to ignore this last operand if that is the case.
3851 unsigned NumOps = Op.getNumOperands();
3852 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3853 --NumOps;
3854
3855 // Check all operands that may contain the LR.
3856 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3857 const InlineAsm::Flag Flags(Op.getConstantOperandVal(i));
3858 unsigned NumVals = Flags.getNumOperandRegisters();
3859 ++i; // Skip the ID value.
3860
3861 switch (Flags.getKind()) {
3862 default:
3863 llvm_unreachable("Bad flags!");
3867 i += NumVals;
3868 break;
3872 for (; NumVals; --NumVals, ++i) {
3873 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3874 if (Reg != PPC::LR && Reg != PPC::LR8)
3875 continue;
3876 MFI.setLRStoreRequired();
3877 return Op;
3878 }
3879 break;
3880 }
3881 }
3882 }
3883
3884 return Op;
3885}
3886
3887SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3888 SelectionDAG &DAG) const {
3889 SDValue Chain = Op.getOperand(0);
3890 SDValue Trmp = Op.getOperand(1); // trampoline
3891 SDValue FPtr = Op.getOperand(2); // nested function
3892 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3893 SDLoc dl(Op);
3894
3895 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3896
3897 if (Subtarget.isAIXABI()) {
3898 // On AIX we create a trampoline descriptor by combining the
3899 // entry point and TOC from the global descriptor (FPtr) with the
3900 // nest argument as the environment pointer.
3901 uint64_t PointerSize = Subtarget.isPPC64() ? 8 : 4;
3902 MaybeAlign PointerAlign(PointerSize);
3903 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
3906 : MachineMemOperand::MONone;
3907
3908 uint64_t TOCPointerOffset = 1 * PointerSize;
3909 uint64_t EnvPointerOffset = 2 * PointerSize;
3910 SDValue SDTOCPtrOffset = DAG.getConstant(TOCPointerOffset, dl, PtrVT);
3911 SDValue SDEnvPtrOffset = DAG.getConstant(EnvPointerOffset, dl, PtrVT);
3912
3913 const Value *TrampolineAddr =
3914 cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3915 const Function *Func =
3916 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
3917
3918 SDValue OutChains[3];
3919
3920 // Copy the entry point address from the global descriptor to the
3921 // trampoline buffer.
3922 SDValue LoadEntryPoint =
3923 DAG.getLoad(PtrVT, dl, Chain, FPtr, MachinePointerInfo(Func, 0),
3924 PointerAlign, MMOFlags);
3925 SDValue EPLoadChain = LoadEntryPoint.getValue(1);
3926 OutChains[0] = DAG.getStore(EPLoadChain, dl, LoadEntryPoint, Trmp,
3927 MachinePointerInfo(TrampolineAddr, 0));
3928
3929 // Copy the TOC pointer from the global descriptor to the trampoline
3930 // buffer.
3931 SDValue TOCFromDescriptorPtr =
3932 DAG.getNode(ISD::ADD, dl, PtrVT, FPtr, SDTOCPtrOffset);
3933 SDValue TOCReg = DAG.getLoad(PtrVT, dl, Chain, TOCFromDescriptorPtr,
3934 MachinePointerInfo(Func, TOCPointerOffset),
3935 PointerAlign, MMOFlags);
3936 SDValue TrampolineTOCPointer =
3937 DAG.getNode(ISD::ADD, dl, PtrVT, Trmp, SDTOCPtrOffset);
3938 SDValue TOCLoadChain = TOCReg.getValue(1);
3939 OutChains[1] =
3940 DAG.getStore(TOCLoadChain, dl, TOCReg, TrampolineTOCPointer,
3941 MachinePointerInfo(TrampolineAddr, TOCPointerOffset));
3942
3943 // Store the nest argument into the environment pointer in the trampoline
3944 // buffer.
3945 SDValue EnvPointer = DAG.getNode(ISD::ADD, dl, PtrVT, Trmp, SDEnvPtrOffset);
3946 OutChains[2] =
3947 DAG.getStore(Chain, dl, Nest, EnvPointer,
3948 MachinePointerInfo(TrampolineAddr, EnvPointerOffset));
3949
3951 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
3952 return TokenFactor;
3953 }
3954
3955 bool isPPC64 = (PtrVT == MVT::i64);
3957
3959 Args.emplace_back(Trmp, IntPtrTy);
3960 // TrampSize == (isPPC64 ? 48 : 40);
3961 Args.emplace_back(
3962 DAG.getConstant(isPPC64 ? 48 : 40, dl, Subtarget.getScalarIntVT()),
3963 IntPtrTy);
3964 Args.emplace_back(FPtr, IntPtrTy);
3965 Args.emplace_back(Nest, IntPtrTy);
3966
3967 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3968 TargetLowering::CallLoweringInfo CLI(DAG);
3969 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3971 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3972
3973 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3974 return CallResult.second;
3975}
3976
3977SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3978 MachineFunction &MF = DAG.getMachineFunction();
3979 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3980 EVT PtrVT = getPointerTy(MF.getDataLayout());
3981
3982 SDLoc dl(Op);
3983
3984 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3985 // vastart just stores the address of the VarArgsFrameIndex slot into the
3986 // memory location argument.
3987 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3988 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3989 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3990 MachinePointerInfo(SV));
3991 }
3992
3993 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3994 // We suppose the given va_list is already allocated.
3995 //
3996 // typedef struct {
3997 // char gpr; /* index into the array of 8 GPRs
3998 // * stored in the register save area
3999 // * gpr=0 corresponds to r3,
4000 // * gpr=1 to r4, etc.
4001 // */
4002 // char fpr; /* index into the array of 8 FPRs
4003 // * stored in the register save area
4004 // * fpr=0 corresponds to f1,
4005 // * fpr=1 to f2, etc.
4006 // */
4007 // char *overflow_arg_area;
4008 // /* location on stack that holds
4009 // * the next overflow argument
4010 // */
4011 // char *reg_save_area;
4012 // /* where r3:r10 and f1:f8 (if saved)
4013 // * are stored
4014 // */
4015 // } va_list[1];
4016
4017 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
4018 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
4019 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
4020 PtrVT);
4021 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4022 PtrVT);
4023
4024 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
4025 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
4026
4027 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
4028 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
4029
4030 uint64_t FPROffset = 1;
4031 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
4032
4033 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4034
4035 // Store first byte : number of int regs
4036 SDValue firstStore =
4037 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
4038 MachinePointerInfo(SV), MVT::i8);
4039 uint64_t nextOffset = FPROffset;
4040 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
4041 ConstFPROffset);
4042
4043 // Store second byte : number of float regs
4044 SDValue secondStore =
4045 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
4046 MachinePointerInfo(SV, nextOffset), MVT::i8);
4047 nextOffset += StackOffset;
4048 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
4049
4050 // Store second word : arguments given on stack
4051 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
4052 MachinePointerInfo(SV, nextOffset));
4053 nextOffset += FrameOffset;
4054 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
4055
4056 // Store third word : arguments given in registers
4057 return DAG.getStore(thirdStore, dl, FR, nextPtr,
4058 MachinePointerInfo(SV, nextOffset));
4059}
4060
4061/// FPR - The set of FP registers that should be allocated for arguments
4062/// on Darwin and AIX.
4063static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
4064 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
4065 PPC::F11, PPC::F12, PPC::F13};
4066
4067/// CalculateStackSlotSize - Calculates the size reserved for this argument on
4068/// the stack.
4069static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
4070 unsigned PtrByteSize) {
4071 unsigned ArgSize = ArgVT.getStoreSize();
4072 if (Flags.isByVal())
4073 ArgSize = Flags.getByValSize();
4074
4075 // Round up to multiples of the pointer size, except for array members,
4076 // which are always packed.
4077 if (!Flags.isInConsecutiveRegs())
4078 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4079
4080 return ArgSize;
4081}
4082
4083/// CalculateStackSlotAlignment - Calculates the alignment of this argument
4084/// on the stack.
4086 ISD::ArgFlagsTy Flags,
4087 unsigned PtrByteSize) {
4088 Align Alignment(PtrByteSize);
4089
4090 // Altivec parameters are padded to a 16 byte boundary.
4091 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4092 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4093 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
4094 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
4095 Alignment = Align(16);
4096
4097 // ByVal parameters are aligned as requested.
4098 if (Flags.isByVal()) {
4099 auto BVAlign = Flags.getNonZeroByValAlign();
4100 if (BVAlign > PtrByteSize) {
4101 if (BVAlign.value() % PtrByteSize != 0)
4103 "ByVal alignment is not a multiple of the pointer size");
4104
4105 Alignment = BVAlign;
4106 }
4107 }
4108
4109 // Array members are always packed to their original alignment.
4110 if (Flags.isInConsecutiveRegs()) {
4111 // If the array member was split into multiple registers, the first
4112 // needs to be aligned to the size of the full type. (Except for
4113 // ppcf128, which is only aligned as its f64 components.)
4114 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
4115 Alignment = Align(OrigVT.getStoreSize());
4116 else
4117 Alignment = Align(ArgVT.getStoreSize());
4118 }
4119
4120 return Alignment;
4121}
4122
4123/// CalculateStackSlotUsed - Return whether this argument will use its
4124/// stack slot (instead of being passed in registers). ArgOffset,
4125/// AvailableFPRs, and AvailableVRs must hold the current argument
4126/// position, and will be updated to account for this argument.
4127static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
4128 unsigned PtrByteSize, unsigned LinkageSize,
4129 unsigned ParamAreaSize, unsigned &ArgOffset,
4130 unsigned &AvailableFPRs,
4131 unsigned &AvailableVRs) {
4132 bool UseMemory = false;
4133
4134 // Respect alignment of argument on the stack.
4135 Align Alignment =
4136 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4137 ArgOffset = alignTo(ArgOffset, Alignment);
4138 // If there's no space left in the argument save area, we must
4139 // use memory (this check also catches zero-sized arguments).
4140 if (ArgOffset >= LinkageSize + ParamAreaSize)
4141 UseMemory = true;
4142
4143 // Allocate argument on the stack.
4144 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4145 if (Flags.isInConsecutiveRegsLast())
4146 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4147 // If we overran the argument save area, we must use memory
4148 // (this check catches arguments passed partially in memory)
4149 if (ArgOffset > LinkageSize + ParamAreaSize)
4150 UseMemory = true;
4151
4152 // However, if the argument is actually passed in an FPR or a VR,
4153 // we don't use memory after all.
4154 if (!Flags.isByVal()) {
4155 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
4156 if (AvailableFPRs > 0) {
4157 --AvailableFPRs;
4158 return false;
4159 }
4160 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4161 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4162 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
4163 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
4164 if (AvailableVRs > 0) {
4165 --AvailableVRs;
4166 return false;
4167 }
4168 }
4169
4170 return UseMemory;
4171}
4172
4173/// EnsureStackAlignment - Round stack frame size up from NumBytes to
4174/// ensure minimum alignment required for target.
4176 unsigned NumBytes) {
4177 return alignTo(NumBytes, Lowering->getStackAlign());
4178}
4179
4180SDValue PPCTargetLowering::LowerFormalArguments(
4181 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4182 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4183 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4184 if (Subtarget.isAIXABI())
4185 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
4186 InVals);
4187 if (Subtarget.is64BitELFABI())
4188 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4189 InVals);
4190 assert(Subtarget.is32BitELFABI());
4191 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4192 InVals);
4193}
4194
4195SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4196 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4197 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4198 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4199
4200 // 32-bit SVR4 ABI Stack Frame Layout:
4201 // +-----------------------------------+
4202 // +--> | Back chain |
4203 // | +-----------------------------------+
4204 // | | Floating-point register save area |
4205 // | +-----------------------------------+
4206 // | | General register save area |
4207 // | +-----------------------------------+
4208 // | | CR save word |
4209 // | +-----------------------------------+
4210 // | | VRSAVE save word |
4211 // | +-----------------------------------+
4212 // | | Alignment padding |
4213 // | +-----------------------------------+
4214 // | | Vector register save area |
4215 // | +-----------------------------------+
4216 // | | Local variable space |
4217 // | +-----------------------------------+
4218 // | | Parameter list area |
4219 // | +-----------------------------------+
4220 // | | LR save word |
4221 // | +-----------------------------------+
4222 // SP--> +--- | Back chain |
4223 // +-----------------------------------+
4224 //
4225 // Specifications:
4226 // System V Application Binary Interface PowerPC Processor Supplement
4227 // AltiVec Technology Programming Interface Manual
4228
4229 MachineFunction &MF = DAG.getMachineFunction();
4230 MachineFrameInfo &MFI = MF.getFrameInfo();
4231 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4232
4233 EVT PtrVT = getPointerTy(MF.getDataLayout());
4234 // Potential tail calls could cause overwriting of argument stack slots.
4235 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4236 (CallConv == CallingConv::Fast));
4237 const Align PtrAlign(4);
4238
4239 // Assign locations to all of the incoming arguments.
4241 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4242 *DAG.getContext());
4243
4244 // Reserve space for the linkage area on the stack.
4245 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4246 CCInfo.AllocateStack(LinkageSize, PtrAlign);
4247 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4248
4249 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4250 CCValAssign &VA = ArgLocs[i];
4251
4252 // Arguments stored in registers.
4253 if (VA.isRegLoc()) {
4254 const TargetRegisterClass *RC;
4255 EVT ValVT = VA.getValVT();
4256
4257 switch (ValVT.getSimpleVT().SimpleTy) {
4258 default:
4259 llvm_unreachable("ValVT not supported by formal arguments Lowering");
4260 case MVT::i1:
4261 case MVT::i32:
4262 RC = &PPC::GPRCRegClass;
4263 break;
4264 case MVT::f32:
4265 if (Subtarget.hasP8Vector())
4266 RC = &PPC::VSSRCRegClass;
4267 else if (Subtarget.hasSPE())
4268 RC = &PPC::GPRCRegClass;
4269 else
4270 RC = &PPC::F4RCRegClass;
4271 break;
4272 case MVT::f64:
4273 if (Subtarget.hasVSX())
4274 RC = &PPC::VSFRCRegClass;
4275 else if (Subtarget.hasSPE())
4276 // SPE passes doubles in GPR pairs.
4277 RC = &PPC::GPRCRegClass;
4278 else
4279 RC = &PPC::F8RCRegClass;
4280 break;
4281 case MVT::v16i8:
4282 case MVT::v8i16:
4283 case MVT::v4i32:
4284 RC = &PPC::VRRCRegClass;
4285 break;
4286 case MVT::v4f32:
4287 RC = &PPC::VRRCRegClass;
4288 break;
4289 case MVT::v2f64:
4290 case MVT::v2i64:
4291 RC = &PPC::VRRCRegClass;
4292 break;
4293 }
4294
4295 SDValue ArgValue;
4296 // Transform the arguments stored in physical registers into
4297 // virtual ones.
4298 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4299 assert(i + 1 < e && "No second half of double precision argument");
4300 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4301 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4302 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4303 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4304 if (!Subtarget.isLittleEndian())
4305 std::swap (ArgValueLo, ArgValueHi);
4306 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4307 ArgValueHi);
4308 } else {
4309 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4310 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4311 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4312 if (ValVT == MVT::i1)
4313 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4314 }
4315
4316 InVals.push_back(ArgValue);
4317 } else {
4318 // Argument stored in memory.
4319 assert(VA.isMemLoc());
4320
4321 // Get the extended size of the argument type in stack
4322 unsigned ArgSize = VA.getLocVT().getStoreSize();
4323 // Get the actual size of the argument type
4324 unsigned ObjSize = VA.getValVT().getStoreSize();
4325 unsigned ArgOffset = VA.getLocMemOffset();
4326 // Stack objects in PPC32 are right justified.
4327 ArgOffset += ArgSize - ObjSize;
4328 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4329
4330 // Create load nodes to retrieve arguments from the stack.
4331 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4332 InVals.push_back(
4333 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4334 }
4335 }
4336
4337 // Assign locations to all of the incoming aggregate by value arguments.
4338 // Aggregates passed by value are stored in the local variable space of the
4339 // caller's stack frame, right above the parameter list area.
4340 SmallVector<CCValAssign, 16> ByValArgLocs;
4341 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4342 ByValArgLocs, *DAG.getContext());
4343
4344 // Reserve stack space for the allocations in CCInfo.
4345 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
4346
4347 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4348
4349 // Area that is at least reserved in the caller of this function.
4350 unsigned MinReservedArea = CCByValInfo.getStackSize();
4351 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4352
4353 // Set the size that is at least reserved in caller of this function. Tail
4354 // call optimized function's reserved stack space needs to be aligned so that
4355 // taking the difference between two stack areas will result in an aligned
4356 // stack.
4357 MinReservedArea =
4358 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4359 FuncInfo->setMinReservedArea(MinReservedArea);
4360
4362
4363 // If the function takes variable number of arguments, make a frame index for
4364 // the start of the first vararg value... for expansion of llvm.va_start.
4365 if (isVarArg) {
4366 static const MCPhysReg GPArgRegs[] = {
4367 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4368 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4369 };
4370 const unsigned NumGPArgRegs = std::size(GPArgRegs);
4371
4372 static const MCPhysReg FPArgRegs[] = {
4373 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4374 PPC::F8
4375 };
4376 unsigned NumFPArgRegs = std::size(FPArgRegs);
4377
4378 if (useSoftFloat() || hasSPE())
4379 NumFPArgRegs = 0;
4380
4381 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4382 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4383
4384 // Make room for NumGPArgRegs and NumFPArgRegs.
4385 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4386 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4387
4389 PtrVT.getSizeInBits() / 8, CCInfo.getStackSize(), true));
4390
4391 FuncInfo->setVarArgsFrameIndex(
4392 MFI.CreateStackObject(Depth, Align(8), false));
4393 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4394
4395 // The fixed integer arguments of a variadic function are stored to the
4396 // VarArgsFrameIndex on the stack so that they may be loaded by
4397 // dereferencing the result of va_next.
4398 for (MCPhysReg GPArgReg : GPArgRegs) {
4399 // Get an existing live-in vreg, or add a new one.
4400 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgReg);
4401 if (!VReg)
4402 VReg = MF.addLiveIn(GPArgReg, &PPC::GPRCRegClass);
4403
4404 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4405 SDValue Store =
4406 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4407 MemOps.push_back(Store);
4408 // Increment the address by four for the next argument to store
4409 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4410 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4411 }
4412
4413 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4414 // is set.
4415 // The double arguments are stored to the VarArgsFrameIndex
4416 // on the stack.
4417 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4418 // Get an existing live-in vreg, or add a new one.
4419 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4420 if (!VReg)
4421 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4422
4423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4424 SDValue Store =
4425 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4426 MemOps.push_back(Store);
4427 // Increment the address by eight for the next argument to store
4428 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4429 PtrVT);
4430 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4431 }
4432 }
4433
4434 if (!MemOps.empty())
4435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4436
4437 return Chain;
4438}
4439
4440// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4441// value to MVT::i64 and then truncate to the correct register size.
4442SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4443 EVT ObjectVT, SelectionDAG &DAG,
4444 SDValue ArgVal,
4445 const SDLoc &dl) const {
4446 if (Flags.isSExt())
4447 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4448 DAG.getValueType(ObjectVT));
4449 else if (Flags.isZExt())
4450 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4451 DAG.getValueType(ObjectVT));
4452
4453 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4454}
4455
4456SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4457 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4458 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4459 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4460 // TODO: add description of PPC stack frame format, or at least some docs.
4461 //
4462 bool isELFv2ABI = Subtarget.isELFv2ABI();
4463 bool isLittleEndian = Subtarget.isLittleEndian();
4464 MachineFunction &MF = DAG.getMachineFunction();
4465 MachineFrameInfo &MFI = MF.getFrameInfo();
4466 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4467
4468 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4469 "fastcc not supported on varargs functions");
4470
4471 EVT PtrVT = getPointerTy(MF.getDataLayout());
4472 // Potential tail calls could cause overwriting of argument stack slots.
4473 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4474 (CallConv == CallingConv::Fast));
4475 unsigned PtrByteSize = 8;
4476 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4477
4478 static const MCPhysReg GPR[] = {
4479 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4480 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4481 };
4482 static const MCPhysReg VR[] = {
4483 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4484 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4485 };
4486
4487 const unsigned Num_GPR_Regs = std::size(GPR);
4488 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4489 const unsigned Num_VR_Regs = std::size(VR);
4490
4491 // Do a first pass over the arguments to determine whether the ABI
4492 // guarantees that our caller has allocated the parameter save area
4493 // on its stack frame. In the ELFv1 ABI, this is always the case;
4494 // in the ELFv2 ABI, it is true if this is a vararg function or if
4495 // any parameter is located in a stack slot.
4496
4497 bool HasParameterArea = !isELFv2ABI || isVarArg;
4498 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4499 unsigned NumBytes = LinkageSize;
4500 unsigned AvailableFPRs = Num_FPR_Regs;
4501 unsigned AvailableVRs = Num_VR_Regs;
4502 for (const ISD::InputArg &In : Ins) {
4503 if (In.Flags.isNest())
4504 continue;
4505
4506 if (CalculateStackSlotUsed(In.VT, In.ArgVT, In.Flags, PtrByteSize,
4507 LinkageSize, ParamAreaSize, NumBytes,
4508 AvailableFPRs, AvailableVRs))
4509 HasParameterArea = true;
4510 }
4511
4512 // Add DAG nodes to load the arguments or copy them out of registers. On
4513 // entry to a function on PPC, the arguments start after the linkage area,
4514 // although the first ones are often in registers.
4515
4516 unsigned ArgOffset = LinkageSize;
4517 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4520 unsigned CurArgIdx = 0;
4521 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4522 SDValue ArgVal;
4523 bool needsLoad = false;
4524 EVT ObjectVT = Ins[ArgNo].VT;
4525 EVT OrigVT = Ins[ArgNo].ArgVT;
4526 unsigned ObjSize = ObjectVT.getStoreSize();
4527 unsigned ArgSize = ObjSize;
4528 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4529 if (Ins[ArgNo].isOrigArg()) {
4530 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4531 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4532 }
4533 // We re-align the argument offset for each argument, except when using the
4534 // fast calling convention, when we need to make sure we do that only when
4535 // we'll actually use a stack slot.
4536 unsigned CurArgOffset;
4537 Align Alignment;
4538 auto ComputeArgOffset = [&]() {
4539 /* Respect alignment of argument on the stack. */
4540 Alignment =
4541 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4542 ArgOffset = alignTo(ArgOffset, Alignment);
4543 CurArgOffset = ArgOffset;
4544 };
4545
4546 if (CallConv != CallingConv::Fast) {
4547 ComputeArgOffset();
4548
4549 /* Compute GPR index associated with argument offset. */
4550 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4551 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4552 }
4553
4554 // FIXME the codegen can be much improved in some cases.
4555 // We do not have to keep everything in memory.
4556 if (Flags.isByVal()) {
4557 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4558
4559 if (CallConv == CallingConv::Fast)
4560 ComputeArgOffset();
4561
4562 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4563 ObjSize = Flags.getByValSize();
4564 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4565 // Empty aggregate parameters do not take up registers. Examples:
4566 // struct { } a;
4567 // union { } b;
4568 // int c[0];
4569 // etc. However, we have to provide a place-holder in InVals, so
4570 // pretend we have an 8-byte item at the current address for that
4571 // purpose.
4572 if (!ObjSize) {
4573 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4574 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4575 InVals.push_back(FIN);
4576 continue;
4577 }
4578
4579 // Create a stack object covering all stack doublewords occupied
4580 // by the argument. If the argument is (fully or partially) on
4581 // the stack, or if the argument is fully in registers but the
4582 // caller has allocated the parameter save anyway, we can refer
4583 // directly to the caller's stack frame. Otherwise, create a
4584 // local copy in our own frame.
4585 int FI;
4586 if (HasParameterArea ||
4587 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4588 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4589 else
4590 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4591 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4592
4593 // Handle aggregates smaller than 8 bytes.
4594 if (ObjSize < PtrByteSize) {
4595 // The value of the object is its address, which differs from the
4596 // address of the enclosing doubleword on big-endian systems.
4597 SDValue Arg = FIN;
4598 if (!isLittleEndian) {
4599 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4600 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4601 }
4602 InVals.push_back(Arg);
4603
4604 if (GPR_idx != Num_GPR_Regs) {
4605 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4606 FuncInfo->addLiveInAttr(VReg, Flags);
4607 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4608 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4609 SDValue Store =
4610 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4611 MachinePointerInfo(&*FuncArg), ObjType);
4612 MemOps.push_back(Store);
4613 }
4614 // Whether we copied from a register or not, advance the offset
4615 // into the parameter save area by a full doubleword.
4616 ArgOffset += PtrByteSize;
4617 continue;
4618 }
4619
4620 // The value of the object is its address, which is the address of
4621 // its first stack doubleword.
4622 InVals.push_back(FIN);
4623
4624 // Store whatever pieces of the object are in registers to memory.
4625 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4626 if (GPR_idx == Num_GPR_Regs)
4627 break;
4628
4629 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4630 FuncInfo->addLiveInAttr(VReg, Flags);
4631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4632 SDValue Addr = FIN;
4633 if (j) {
4634 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4635 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4636 }
4637 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4638 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4639 SDValue Store =
4640 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4641 MachinePointerInfo(&*FuncArg, j), ObjType);
4642 MemOps.push_back(Store);
4643 ++GPR_idx;
4644 }
4645 ArgOffset += ArgSize;
4646 continue;
4647 }
4648
4649 switch (ObjectVT.getSimpleVT().SimpleTy) {
4650 default: llvm_unreachable("Unhandled argument type!");
4651 case MVT::i1:
4652 case MVT::i32:
4653 case MVT::i64:
4654 if (Flags.isNest()) {
4655 // The 'nest' parameter, if any, is passed in R11.
4656 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4657 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4658
4659 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4660 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4661
4662 break;
4663 }
4664
4665 // These can be scalar arguments or elements of an integer array type
4666 // passed directly. Clang may use those instead of "byval" aggregate
4667 // types to avoid forcing arguments to memory unnecessarily.
4668 if (GPR_idx != Num_GPR_Regs) {
4669 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4670 FuncInfo->addLiveInAttr(VReg, Flags);
4671 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4672
4673 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4674 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4675 // value to MVT::i64 and then truncate to the correct register size.
4676 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4677 } else {
4678 if (CallConv == CallingConv::Fast)
4679 ComputeArgOffset();
4680
4681 needsLoad = true;
4682 ArgSize = PtrByteSize;
4683 }
4684 if (CallConv != CallingConv::Fast || needsLoad)
4685 ArgOffset += 8;
4686 break;
4687
4688 case MVT::f32:
4689 case MVT::f64:
4690 // These can be scalar arguments or elements of a float array type
4691 // passed directly. The latter are used to implement ELFv2 homogenous
4692 // float aggregates.
4693 if (FPR_idx != Num_FPR_Regs) {
4694 unsigned VReg;
4695
4696 if (ObjectVT == MVT::f32)
4697 VReg = MF.addLiveIn(FPR[FPR_idx],
4698 Subtarget.hasP8Vector()
4699 ? &PPC::VSSRCRegClass
4700 : &PPC::F4RCRegClass);
4701 else
4702 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4703 ? &PPC::VSFRCRegClass
4704 : &PPC::F8RCRegClass);
4705
4706 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4707 ++FPR_idx;
4708 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4709 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4710 // once we support fp <-> gpr moves.
4711
4712 // This can only ever happen in the presence of f32 array types,
4713 // since otherwise we never run out of FPRs before running out
4714 // of GPRs.
4715 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4716 FuncInfo->addLiveInAttr(VReg, Flags);
4717 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4718
4719 if (ObjectVT == MVT::f32) {
4720 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4721 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4722 DAG.getConstant(32, dl, MVT::i32));
4723 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4724 }
4725
4726 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4727 } else {
4728 if (CallConv == CallingConv::Fast)
4729 ComputeArgOffset();
4730
4731 needsLoad = true;
4732 }
4733
4734 // When passing an array of floats, the array occupies consecutive
4735 // space in the argument area; only round up to the next doubleword
4736 // at the end of the array. Otherwise, each float takes 8 bytes.
4737 if (CallConv != CallingConv::Fast || needsLoad) {
4738 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4739 ArgOffset += ArgSize;
4740 if (Flags.isInConsecutiveRegsLast())
4741 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4742 }
4743 break;
4744 case MVT::v4f32:
4745 case MVT::v4i32:
4746 case MVT::v8i16:
4747 case MVT::v16i8:
4748 case MVT::v2f64:
4749 case MVT::v2i64:
4750 case MVT::v1i128:
4751 case MVT::f128:
4752 // These can be scalar arguments or elements of a vector array type
4753 // passed directly. The latter are used to implement ELFv2 homogenous
4754 // vector aggregates.
4755 if (VR_idx != Num_VR_Regs) {
4756 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4757 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4758 ++VR_idx;
4759 } else {
4760 if (CallConv == CallingConv::Fast)
4761 ComputeArgOffset();
4762 needsLoad = true;
4763 }
4764 if (CallConv != CallingConv::Fast || needsLoad)
4765 ArgOffset += 16;
4766 break;
4767 }
4768
4769 // We need to load the argument to a virtual register if we determined
4770 // above that we ran out of physical registers of the appropriate type.
4771 if (needsLoad) {
4772 if (ObjSize < ArgSize && !isLittleEndian)
4773 CurArgOffset += ArgSize - ObjSize;
4774 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4775 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4776 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4777 }
4778
4779 InVals.push_back(ArgVal);
4780 }
4781
4782 // Area that is at least reserved in the caller of this function.
4783 unsigned MinReservedArea;
4784 if (HasParameterArea)
4785 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4786 else
4787 MinReservedArea = LinkageSize;
4788
4789 // Set the size that is at least reserved in caller of this function. Tail
4790 // call optimized functions' reserved stack space needs to be aligned so that
4791 // taking the difference between two stack areas will result in an aligned
4792 // stack.
4793 MinReservedArea =
4794 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4795 FuncInfo->setMinReservedArea(MinReservedArea);
4796
4797 // If the function takes variable number of arguments, make a frame index for
4798 // the start of the first vararg value... for expansion of llvm.va_start.
4799 // On ELFv2ABI spec, it writes:
4800 // C programs that are intended to be *portable* across different compilers
4801 // and architectures must use the header file <stdarg.h> to deal with variable
4802 // argument lists.
4803 if (isVarArg && MFI.hasVAStart()) {
4804 int Depth = ArgOffset;
4805
4806 FuncInfo->setVarArgsFrameIndex(
4807 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4808 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4809
4810 // If this function is vararg, store any remaining integer argument regs
4811 // to their spots on the stack so that they may be loaded by dereferencing
4812 // the result of va_next.
4813 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4814 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4815 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4816 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4817 SDValue Store =
4818 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4819 MemOps.push_back(Store);
4820 // Increment the address by four for the next argument to store
4821 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4822 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4823 }
4824 }
4825
4826 if (!MemOps.empty())
4827 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4828
4829 return Chain;
4830}
4831
4832/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4833/// adjusted to accommodate the arguments for the tailcall.
4834static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4835 unsigned ParamSize) {
4836
4837 if (!isTailCall) return 0;
4838
4840 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4841 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4842 // Remember only if the new adjustment is bigger.
4843 if (SPDiff < FI->getTailCallSPDelta())
4844 FI->setTailCallSPDelta(SPDiff);
4845
4846 return SPDiff;
4847}
4848
4849static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV);
4850
4851static bool callsShareTOCBase(const Function *Caller,
4852 const GlobalValue *CalleeGV,
4853 const TargetMachine &TM) {
4854 // It does not make sense to call callsShareTOCBase() with a caller that
4855 // is PC Relative since PC Relative callers do not have a TOC.
4856#ifndef NDEBUG
4857 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4858 assert(!STICaller->isUsingPCRelativeCalls() &&
4859 "PC Relative callers do not have a TOC and cannot share a TOC Base");
4860#endif
4861
4862 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4863 // don't have enough information to determine if the caller and callee share
4864 // the same TOC base, so we have to pessimistically assume they don't for
4865 // correctness.
4866 if (!CalleeGV)
4867 return false;
4868
4869 // If the callee is preemptable, then the static linker will use a plt-stub
4870 // which saves the toc to the stack, and needs a nop after the call
4871 // instruction to convert to a toc-restore.
4872 if (!TM.shouldAssumeDSOLocal(CalleeGV))
4873 return false;
4874
4875 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4876 // We may need a TOC restore in the situation where the caller requires a
4877 // valid TOC but the callee is PC Relative and does not.
4878 const Function *F = dyn_cast<Function>(CalleeGV);
4879 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(CalleeGV);
4880
4881 // If we have an Alias we can try to get the function from there.
4882 if (Alias) {
4883 const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4884 F = dyn_cast<Function>(GlobalObj);
4885 }
4886
4887 // If we still have no valid function pointer we do not have enough
4888 // information to determine if the callee uses PC Relative calls so we must
4889 // assume that it does.
4890 if (!F)
4891 return false;
4892
4893 // If the callee uses PC Relative we cannot guarantee that the callee won't
4894 // clobber the TOC of the caller and so we must assume that the two
4895 // functions do not share a TOC base.
4896 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4897 if (STICallee->isUsingPCRelativeCalls())
4898 return false;
4899
4900 // If the GV is not a strong definition then we need to assume it can be
4901 // replaced by another function at link time. The function that replaces
4902 // it may not share the same TOC as the caller since the callee may be
4903 // replaced by a PC Relative version of the same function.
4904 if (!CalleeGV->isStrongDefinitionForLinker())
4905 return false;
4906
4907 // The medium and large code models are expected to provide a sufficiently
4908 // large TOC to provide all data addressing needs of a module with a
4909 // single TOC.
4910 if (CodeModel::Medium == TM.getCodeModel() ||
4912 return true;
4913
4914 // Any explicitly-specified sections and section prefixes must also match.
4915 // Also, if we're using -ffunction-sections, then each function is always in
4916 // a different section (the same is true for COMDAT functions).
4917 if (TM.getFunctionSections() || CalleeGV->hasComdat() ||
4918 Caller->hasComdat() || CalleeGV->getSection() != Caller->getSection())
4919 return false;
4920 if (const auto *F = dyn_cast<Function>(CalleeGV)) {
4921 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4922 return false;
4923 }
4924
4925 return true;
4926}
4927
4928static bool
4930 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4931 assert(Subtarget.is64BitELFABI());
4932
4933 const unsigned PtrByteSize = 8;
4934 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4935
4936 static const MCPhysReg GPR[] = {
4937 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4938 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4939 };
4940 static const MCPhysReg VR[] = {
4941 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4942 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4943 };
4944
4945 const unsigned NumGPRs = std::size(GPR);
4946 const unsigned NumFPRs = 13;
4947 const unsigned NumVRs = std::size(VR);
4948 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4949
4950 unsigned NumBytes = LinkageSize;
4951 unsigned AvailableFPRs = NumFPRs;
4952 unsigned AvailableVRs = NumVRs;
4953
4954 for (const ISD::OutputArg& Param : Outs) {
4955 if (Param.Flags.isNest()) continue;
4956
4957 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4958 LinkageSize, ParamAreaSize, NumBytes,
4959 AvailableFPRs, AvailableVRs))
4960 return true;
4961 }
4962 return false;
4963}
4964
4965static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4966 if (CB.arg_size() != CallerFn->arg_size())
4967 return false;
4968
4969 auto CalleeArgIter = CB.arg_begin();
4970 auto CalleeArgEnd = CB.arg_end();
4971 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4972
4973 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4974 const Value* CalleeArg = *CalleeArgIter;
4975 const Value* CallerArg = &(*CallerArgIter);
4976 if (CalleeArg == CallerArg)
4977 continue;
4978
4979 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4980 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4981 // }
4982 // 1st argument of callee is undef and has the same type as caller.
4983 if (CalleeArg->getType() == CallerArg->getType() &&
4984 isa<UndefValue>(CalleeArg))
4985 continue;
4986
4987 return false;
4988 }
4989
4990 return true;
4991}
4992
4993// Returns true if TCO is possible between the callers and callees
4994// calling conventions.
4995static bool
4997 CallingConv::ID CalleeCC) {
4998 // Tail calls are possible with fastcc and ccc.
4999 auto isTailCallableCC = [] (CallingConv::ID CC){
5000 return CC == CallingConv::C || CC == CallingConv::Fast;
5001 };
5002 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
5003 return false;
5004
5005 // We can safely tail call both fastcc and ccc callees from a c calling
5006 // convention caller. If the caller is fastcc, we may have less stack space
5007 // than a non-fastcc caller with the same signature so disable tail-calls in
5008 // that case.
5009 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
5010}
5011
5012bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
5013 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5014 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5016 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5017 bool isCalleeExternalSymbol) const {
5018 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
5019
5020 if (DisableSCO && !TailCallOpt) return false;
5021
5022 // Variadic argument functions are not supported.
5023 if (isVarArg) return false;
5024
5025 // Check that the calling conventions are compatible for tco.
5026 if (!areCallingConvEligibleForTCO_64SVR4(CallerCC, CalleeCC))
5027 return false;
5028
5029 // Caller contains any byval parameter is not supported.
5030 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5031 return false;
5032
5033 // Callee contains any byval parameter is not supported, too.
5034 // Note: This is a quick work around, because in some cases, e.g.
5035 // caller's stack size > callee's stack size, we are still able to apply
5036 // sibling call optimization. For example, gcc is able to do SCO for caller1
5037 // in the following example, but not for caller2.
5038 // struct test {
5039 // long int a;
5040 // char ary[56];
5041 // } gTest;
5042 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
5043 // b->a = v.a;
5044 // return 0;
5045 // }
5046 // void caller1(struct test a, struct test c, struct test *b) {
5047 // callee(gTest, b); }
5048 // void caller2(struct test *b) { callee(gTest, b); }
5049 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
5050 return false;
5051
5052 // If callee and caller use different calling conventions, we cannot pass
5053 // parameters on stack since offsets for the parameter area may be different.
5054 if (CallerCC != CalleeCC && needStackSlotPassParameters(Subtarget, Outs))
5055 return false;
5056
5057 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
5058 // the caller and callee share the same TOC for TCO/SCO. If the caller and
5059 // callee potentially have different TOC bases then we cannot tail call since
5060 // we need to restore the TOC pointer after the call.
5061 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
5062 // We cannot guarantee this for indirect calls or calls to external functions.
5063 // When PC-Relative addressing is used, the concept of the TOC is no longer
5064 // applicable so this check is not required.
5065 // Check first for indirect calls.
5066 if (!Subtarget.isUsingPCRelativeCalls() &&
5067 !isFunctionGlobalAddress(CalleeGV) && !isCalleeExternalSymbol)
5068 return false;
5069
5070 // Check if we share the TOC base.
5071 if (!Subtarget.isUsingPCRelativeCalls() &&
5072 !callsShareTOCBase(CallerFunc, CalleeGV, getTargetMachine()))
5073 return false;
5074
5075 // TCO allows altering callee ABI, so we don't have to check further.
5076 if (CalleeCC == CallingConv::Fast && TailCallOpt)
5077 return true;
5078
5079 if (DisableSCO) return false;
5080
5081 // If callee use the same argument list that caller is using, then we can
5082 // apply SCO on this case. If it is not, then we need to check if callee needs
5083 // stack for passing arguments.
5084 // PC Relative tail calls may not have a CallBase.
5085 // If there is no CallBase we cannot verify if we have the same argument
5086 // list so assume that we don't have the same argument list.
5087 if (CB && !hasSameArgumentList(CallerFunc, *CB) &&
5088 needStackSlotPassParameters(Subtarget, Outs))
5089 return false;
5090 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5091 return false;
5092
5093 return true;
5094}
5095
5096/// IsEligibleForTailCallOptimization - Check whether the call is eligible
5097/// for tail call optimization. Targets which want to do tail call
5098/// optimization should implement this function.
5099bool PPCTargetLowering::IsEligibleForTailCallOptimization(
5100 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5101 CallingConv::ID CallerCC, bool isVarArg,
5102 const SmallVectorImpl<ISD::InputArg> &Ins) const {
5103 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5104 return false;
5105
5106 // Variable argument functions are not supported.
5107 if (isVarArg)
5108 return false;
5109
5110 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5111 // Functions containing by val parameters are not supported.
5112 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5113 return false;
5114
5115 // Non-PIC/GOT tail calls are supported.
5116 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5117 return true;
5118
5119 // At the moment we can only do local tail calls (in same module, hidden
5120 // or protected) if we are generating PIC.
5121 if (CalleeGV)
5122 return CalleeGV->hasHiddenVisibility() ||
5123 CalleeGV->hasProtectedVisibility();
5124 }
5125
5126 return false;
5127}
5128
5129/// isCallCompatibleAddress - Return the immediate to use if the specified
5130/// 32-bit value is representable in the immediate field of a BxA instruction.
5133 if (!C) return nullptr;
5134
5135 int Addr = C->getZExtValue();
5136 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
5137 SignExtend32<26>(Addr) != Addr)
5138 return nullptr; // Top 6 bits have to be sext of immediate.
5139
5140 return DAG
5142 (int)C->getZExtValue() >> 2, SDLoc(Op),
5144 .getNode();
5145}
5146
5147namespace {
5148
5149struct TailCallArgumentInfo {
5150 SDValue Arg;
5151 SDValue FrameIdxOp;
5152 int FrameIdx = 0;
5153
5154 TailCallArgumentInfo() = default;
5155};
5156
5157} // end anonymous namespace
5158
5159/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5161 SelectionDAG &DAG, SDValue Chain,
5162 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5163 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5164 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5165 SDValue Arg = TailCallArgs[i].Arg;
5166 SDValue FIN = TailCallArgs[i].FrameIdxOp;
5167 int FI = TailCallArgs[i].FrameIdx;
5168 // Store relative to framepointer.
5169 MemOpChains.push_back(DAG.getStore(
5170 Chain, dl, Arg, FIN,
5172 }
5173}
5174
5175/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5176/// the appropriate stack slot for the tail call optimized function call.
5178 SDValue OldRetAddr, SDValue OldFP,
5179 int SPDiff, const SDLoc &dl) {
5180 if (SPDiff) {
5181 // Calculate the new stack slot for the return address.
5183 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5184 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5185 int SlotSize = Subtarget.isPPC64() ? 8 : 4;
5186 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5187 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5188 NewRetAddrLoc, true);
5189 SDValue NewRetAddrFrIdx =
5190 DAG.getFrameIndex(NewRetAddr, Subtarget.getScalarIntVT());
5191 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5192 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5193 }
5194 return Chain;
5195}
5196
5197/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5198/// the position of the argument.
5200 SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg,
5201 int SPDiff, unsigned ArgOffset,
5202 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5203 int Offset = ArgOffset + SPDiff;
5204 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5205 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5206 EVT VT = IsPPC64 ? MVT::i64 : MVT::i32;
5207 SDValue FIN = DAG.getFrameIndex(FI, VT);
5208 TailCallArgumentInfo Info;
5209 Info.Arg = Arg;
5210 Info.FrameIdxOp = FIN;
5211 Info.FrameIdx = FI;
5212 TailCallArguments.push_back(Info);
5213}
5214
5215/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5216/// stack slot. Returns the chain as result and the loaded frame pointers in
5217/// LROpOut/FPOpout. Used when tail calling.
5218SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5219 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5220 SDValue &FPOpOut, const SDLoc &dl) const {
5221 if (SPDiff) {
5222 // Load the LR and FP stack slot for later adjusting.
5223 LROpOut = getReturnAddrFrameIndex(DAG);
5224 LROpOut = DAG.getLoad(Subtarget.getScalarIntVT(), dl, Chain, LROpOut,
5225 MachinePointerInfo());
5226 Chain = SDValue(LROpOut.getNode(), 1);
5227 }
5228 return Chain;
5229}
5230
5231/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5232/// by "Src" to address "Dst" of size "Size". Alignment information is
5233/// specified by the specific parameter attribute. The copy will be passed as
5234/// a byval function parameter.
5235/// Sometimes what we are copying is the end of a larger object, the part that
5236/// does not fit in registers.
5238 SDValue Chain, ISD::ArgFlagsTy Flags,
5239 SelectionDAG &DAG, const SDLoc &dl) {
5240 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5241 Align Alignment = Flags.getNonZeroByValAlign();
5242 return DAG.getMemcpy(
5243 Chain, dl, Dst, Src, SizeNode, Alignment, Alignment, false, false,
5244 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
5245}
5246
5247/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5248/// tail calls.
5250 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5251 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5252 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5253 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5255 if (!isTailCall) {
5256 if (isVector) {
5257 SDValue StackPtr;
5258 if (isPPC64)
5259 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5260 else
5261 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5262 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5263 DAG.getConstant(ArgOffset, dl, PtrVT));
5264 }
5265 MemOpChains.push_back(
5266 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5267 // Calculate and remember argument location.
5268 } else
5269 CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5270 TailCallArguments);
5271}
5272
5273static void
5275 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5276 SDValue FPOp,
5277 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5278 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5279 // might overwrite each other in case of tail call optimization.
5280 SmallVector<SDValue, 8> MemOpChains2;
5281 // Do not flag preceding copytoreg stuff together with the following stuff.
5282 InGlue = SDValue();
5283 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5284 MemOpChains2, dl);
5285 if (!MemOpChains2.empty())
5286 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5287
5288 // Store the return address to the appropriate stack slot.
5289 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5290
5291 // Emit callseq_end just before tailcall node.
5292 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
5293 InGlue = Chain.getValue(1);
5294}
5295
5296// Is this global address that of a function that can be called by name? (as
5297// opposed to something that must hold a descriptor for an indirect call).
5298static bool isFunctionGlobalAddress(const GlobalValue *GV) {
5299 if (GV) {
5300 if (GV->isThreadLocal())
5301 return false;
5302
5303 return GV->getValueType()->isFunctionTy();
5304 }
5305
5306 return false;
5307}
5308
5309SDValue PPCTargetLowering::LowerCallResult(
5310 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
5311 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5312 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5314 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5315 *DAG.getContext());
5316
5317 CCRetInfo.AnalyzeCallResult(
5318 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5320 : RetCC_PPC);
5321
5322 // Copy all of the result registers out of their specified physreg.
5323 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5324 CCValAssign &VA = RVLocs[i];
5325 assert(VA.isRegLoc() && "Can only return in registers!");
5326
5327 SDValue Val;
5328
5329 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5330 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5331 InGlue);
5332 Chain = Lo.getValue(1);
5333 InGlue = Lo.getValue(2);
5334 VA = RVLocs[++i]; // skip ahead to next loc
5335 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5336 InGlue);
5337 Chain = Hi.getValue(1);
5338 InGlue = Hi.getValue(2);
5339 if (!Subtarget.isLittleEndian())
5340 std::swap (Lo, Hi);
5341 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5342 } else {
5343 Val = DAG.getCopyFromReg(Chain, dl,
5344 VA.getLocReg(), VA.getLocVT(), InGlue);
5345 Chain = Val.getValue(1);
5346 InGlue = Val.getValue(2);
5347 }
5348
5349 switch (VA.getLocInfo()) {
5350 default: llvm_unreachable("Unknown loc info!");
5351 case CCValAssign::Full: break;
5352 case CCValAssign::AExt:
5353 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5354 break;
5355 case CCValAssign::ZExt:
5356 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5357 DAG.getValueType(VA.getValVT()));
5358 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5359 break;
5360 case CCValAssign::SExt:
5361 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5362 DAG.getValueType(VA.getValVT()));
5363 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5364 break;
5365 }
5366
5367 InVals.push_back(Val);
5368 }
5369
5370 return Chain;
5371}
5372
5373static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5374 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5375 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5376 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5377
5378 // PatchPoint calls are not indirect.
5379 if (isPatchPoint)
5380 return false;
5381
5383 return false;
5384
5385 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5386 // becuase the immediate function pointer points to a descriptor instead of
5387 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5388 // pointer immediate points to the global entry point, while the BLA would
5389 // need to jump to the local entry point (see rL211174).
5390 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5391 isBLACompatibleAddress(Callee, DAG))
5392 return false;
5393
5394 return true;
5395}
5396
5397// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5398static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5399 return Subtarget.isAIXABI() ||
5400 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5401}
5402
5404 const Function &Caller, const SDValue &Callee,
5405 const PPCSubtarget &Subtarget,
5406 const TargetMachine &TM,
5407 bool IsStrictFPCall = false) {
5408 if (CFlags.IsTailCall)
5409 return PPCISD::TC_RETURN;
5410
5411 unsigned RetOpc = 0;
5412 // This is a call through a function pointer.
5413 if (CFlags.IsIndirect) {
5414 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5415 // indirect calls. The save of the caller's TOC pointer to the stack will be
5416 // inserted into the DAG as part of call lowering. The restore of the TOC
5417 // pointer is modeled by using a pseudo instruction for the call opcode that
5418 // represents the 2 instruction sequence of an indirect branch and link,
5419 // immediately followed by a load of the TOC pointer from the stack save
5420 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5421 // as it is not saved or used.
5422 if (Subtarget.usePointerGlueHelper())
5423 RetOpc = PPCISD::BL_LOAD_TOC;
5424 else
5425 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5426 : PPCISD::BCTRL;
5427 } else if (Subtarget.isUsingPCRelativeCalls()) {
5428 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5429 RetOpc = PPCISD::CALL_NOTOC;
5430 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) {
5431 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5432 // immediately following the call instruction if the caller and callee may
5433 // have different TOC bases. At link time if the linker determines the calls
5434 // may not share a TOC base, the call is redirected to a trampoline inserted
5435 // by the linker. The trampoline will (among other things) save the callers
5436 // TOC pointer at an ABI designated offset in the linkage area and the
5437 // linker will rewrite the nop to be a load of the TOC pointer from the
5438 // linkage area into gpr2.
5439 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5440 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5441 RetOpc =
5442 callsShareTOCBase(&Caller, GV, TM) ? PPCISD::CALL : PPCISD::CALL_NOP;
5443 } else
5444 RetOpc = PPCISD::CALL;
5445 if (IsStrictFPCall) {
5446 switch (RetOpc) {
5447 default:
5448 llvm_unreachable("Unknown call opcode");
5449 case PPCISD::BCTRL_LOAD_TOC:
5450 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5451 break;
5452 case PPCISD::BCTRL:
5453 RetOpc = PPCISD::BCTRL_RM;
5454 break;
5455 case PPCISD::BL_LOAD_TOC:
5456 RetOpc = PPCISD::BL_LOAD_TOC_RM;
5457 break;
5458 case PPCISD::CALL_NOTOC:
5459 RetOpc = PPCISD::CALL_NOTOC_RM;
5460 break;
5461 case PPCISD::CALL:
5462 RetOpc = PPCISD::CALL_RM;
5463 break;
5464 case PPCISD::CALL_NOP:
5465 RetOpc = PPCISD::CALL_NOP_RM;
5466 break;
5467 }
5468 }
5469 return RetOpc;
5470}
5471
5472static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5473 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5474 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5475 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5476 return SDValue(Dest, 0);
5477
5478 // Returns true if the callee is local, and false otherwise.
5479 auto isLocalCallee = [&]() {
5481 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5482
5483 return DAG.getTarget().shouldAssumeDSOLocal(GV) &&
5485 };
5486
5487 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5488 // a static relocation model causes some versions of GNU LD (2.17.50, at
5489 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5490 // built with secure-PLT.
5491 bool UsePlt =
5492 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5494
5495 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5496 const TargetMachine &TM = Subtarget.getTargetMachine();
5498 auto *S =
5499 static_cast<MCSymbolXCOFF *>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5500
5502 return DAG.getMCSymbol(S, PtrVT);
5503 };
5504
5505 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5506 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5507 if (isFunctionGlobalAddress(GV)) {
5508 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5509
5510 if (Subtarget.isAIXABI()) {
5511 return getAIXFuncEntryPointSymbolSDNode(GV);
5512 }
5513 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5514 UsePlt ? PPCII::MO_PLT : 0);
5515 }
5516
5518 const char *SymName = S->getSymbol();
5519 if (Subtarget.isAIXABI()) {
5520 // If there exists a user-declared function whose name is the same as the
5521 // ExternalSymbol's, then we pick up the user-declared version.
5523 if (const Function *F =
5524 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5525 return getAIXFuncEntryPointSymbolSDNode(F);
5526
5527 // On AIX, direct function calls reference the symbol for the function's
5528 // entry point, which is named by prepending a "." before the function's
5529 // C-linkage name. A Qualname is returned here because an external
5530 // function entry point is a csect with XTY_ER property.
5531 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5532 auto &Context = DAG.getMachineFunction().getContext();
5533 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5534 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5536 return Sec->getQualNameSymbol();
5537 };
5538
5539 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5540 }
5541 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5542 UsePlt ? PPCII::MO_PLT : 0);
5543 }
5544
5545 // No transformation needed.
5546 assert(Callee.getNode() && "What no callee?");
5547 return Callee;
5548}
5549
5551 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5552 "Expected a CALLSEQ_STARTSDNode.");
5553
5554 // The last operand is the chain, except when the node has glue. If the node
5555 // has glue, then the last operand is the glue, and the chain is the second
5556 // last operand.
5557 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5558 if (LastValue.getValueType() != MVT::Glue)
5559 return LastValue;
5560
5561 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5562}
5563
5564// Creates the node that moves a functions address into the count register
5565// to prepare for an indirect call instruction.
5566static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5567 SDValue &Glue, SDValue &Chain,
5568 const SDLoc &dl) {
5569 SDValue MTCTROps[] = {Chain, Callee, Glue};
5570 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5571 Chain = DAG.getNode(PPCISD::MTCTR, dl, ReturnTypes,
5572 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5573 // The glue is the second value produced.
5574 Glue = Chain.getValue(1);
5575}
5576
5578 SDValue &Glue, SDValue &Chain,
5579 SDValue CallSeqStart,
5580 const CallBase *CB, const SDLoc &dl,
5581 bool hasNest,
5582 const PPCSubtarget &Subtarget) {
5583 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5584 // entry point, but to the function descriptor (the function entry point
5585 // address is part of the function descriptor though).
5586 // The function descriptor is a three doubleword structure with the
5587 // following fields: function entry point, TOC base address and
5588 // environment pointer.
5589 // Thus for a call through a function pointer, the following actions need
5590 // to be performed:
5591 // 1. Save the TOC of the caller in the TOC save area of its stack
5592 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5593 // 2. Load the address of the function entry point from the function
5594 // descriptor.
5595 // 3. Load the TOC of the callee from the function descriptor into r2.
5596 // 4. Load the environment pointer from the function descriptor into
5597 // r11.
5598 // 5. Branch to the function entry point address.
5599 // 6. On return of the callee, the TOC of the caller needs to be
5600 // restored (this is done in FinishCall()).
5601 //
5602 // The loads are scheduled at the beginning of the call sequence, and the
5603 // register copies are flagged together to ensure that no other
5604 // operations can be scheduled in between. E.g. without flagging the
5605 // copies together, a TOC access in the caller could be scheduled between
5606 // the assignment of the callee TOC and the branch to the callee, which leads
5607 // to incorrect code.
5608
5609 // Start by loading the function address from the descriptor.
5610 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5611 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5615
5616 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5617
5618 // Registers used in building the DAG.
5619 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5620 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5621
5622 // Offsets of descriptor members.
5623 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5624 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5625
5626 const MVT RegVT = Subtarget.getScalarIntVT();
5627 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
5628
5629 // One load for the functions entry point address.
5630 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5631 Alignment, MMOFlags);
5632
5633 // One for loading the TOC anchor for the module that contains the called
5634 // function.
5635 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5636 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5637 SDValue TOCPtr =
5638 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5639 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5640
5641 // One for loading the environment pointer.
5642 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5643 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5644 SDValue LoadEnvPtr =
5645 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5646 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5647
5648
5649 // Then copy the newly loaded TOC anchor to the TOC pointer.
5650 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5651 Chain = TOCVal.getValue(0);
5652 Glue = TOCVal.getValue(1);
5653
5654 // If the function call has an explicit 'nest' parameter, it takes the
5655 // place of the environment pointer.
5656 assert((!hasNest || !Subtarget.isAIXABI()) &&
5657 "Nest parameter is not supported on AIX.");
5658 if (!hasNest) {
5659 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5660 Chain = EnvVal.getValue(0);
5661 Glue = EnvVal.getValue(1);
5662 }
5663
5664 // The rest of the indirect call sequence is the same as the non-descriptor
5665 // DAG.
5666 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5667}
5668
5670 SDValue &Glue, SDValue &Chain,
5671 SDValue CallSeqStart, const CallBase *CB,
5672 const SDLoc &dl, bool hasNest,
5673 const PPCSubtarget &Subtarget) {
5674 // On AIX there is a feature ("out of line glue code") which uses a special
5675 // trampoline function ._ptrgl to do the indirect call. If this option is
5676 // enabled we instead simply load the address of the descriptor into gpr11,
5677 // with the arguments in the 'normal' registers and branch to the ._ptrgl
5678 // stub.
5679 const MCRegister PtrGlueReg = Subtarget.getGlueCodeDescriptorRegister();
5680 SDValue MoveToPhysicalReg =
5681 DAG.getCopyToReg(Chain, dl, PtrGlueReg, Callee, Glue);
5682 Chain = MoveToPhysicalReg.getValue(0);
5683 Glue = MoveToPhysicalReg.getValue(1);
5684}
5685
5686static void
5688 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5689 SelectionDAG &DAG,
5690 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5691 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5692 const PPCSubtarget &Subtarget) {
5693 const bool IsPPC64 = Subtarget.isPPC64();
5694 // MVT for a general purpose register.
5695 const MVT RegVT = Subtarget.getScalarIntVT();
5696
5697 // First operand is always the chain.
5698 Ops.push_back(Chain);
5699
5700 // If it's a direct call pass the callee as the second operand.
5701 if (!CFlags.IsIndirect)
5702 Ops.push_back(Callee);
5703 else if (Subtarget.usePointerGlueHelper()) {
5704 Ops.push_back(Callee);
5705 // Add the register used to pass the descriptor address.
5706 Ops.push_back(
5707 DAG.getRegister(Subtarget.getGlueCodeDescriptorRegister(), RegVT));
5708 } else {
5709 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5710
5711 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5712 // on the stack (this would have been done in `LowerCall_64SVR4` or
5713 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5714 // represents both the indirect branch and a load that restores the TOC
5715 // pointer from the linkage area. The operand for the TOC restore is an add
5716 // of the TOC save offset to the stack pointer. This must be the second
5717 // operand: after the chain input but before any other variadic arguments.
5718 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5719 // saved or used.
5720 if (isTOCSaveRestoreRequired(Subtarget)) {
5721 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5722
5723 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5724 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5725 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5726 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5727 Ops.push_back(AddTOC);
5728 }
5729
5730 // Add the register used for the environment pointer.
5731 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5732 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5733 RegVT));
5734
5735
5736 // Add CTR register as callee so a bctr can be emitted later.
5737 if (CFlags.IsTailCall)
5738 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5739 }
5740
5741 // If this is a tail call add stack pointer delta.
5742 if (CFlags.IsTailCall)
5743 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5744
5745 // Add argument registers to the end of the list so that they are known live
5746 // into the call.
5747 for (const auto &[Reg, N] : RegsToPass)
5748 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
5749
5750 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5751 // no way to mark dependencies as implicit here.
5752 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5753 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5754 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5755 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5756
5757 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5758 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5759 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5760
5761 // Add a register mask operand representing the call-preserved registers.
5762 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5763 const uint32_t *Mask =
5764 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5765 assert(Mask && "Missing call preserved mask for calling convention");
5766 Ops.push_back(DAG.getRegisterMask(Mask));
5767
5768 // If the glue is valid, it is the last operand.
5769 if (Glue.getNode())
5770 Ops.push_back(Glue);
5771}
5772
5773SDValue PPCTargetLowering::FinishCall(
5774 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5775 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5776 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5777 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5778 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5779
5780 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5781 Subtarget.isAIXABI())
5782 setUsesTOCBasePtr(DAG);
5783
5784 unsigned CallOpc =
5785 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5786 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5787
5788 if (!CFlags.IsIndirect)
5789 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5790 else if (Subtarget.usesFunctionDescriptors()) {
5791 if (Subtarget.usePointerGlueHelper()) {
5792 prepareOutOfLineGlueCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, dl,
5793 CFlags.HasNest, Subtarget);
5794 SDValue PtrGlueCallee =
5795 DAG.getExternalSymbol("_ptrgl", getPointerTy(DAG.getDataLayout()));
5796 Callee = transformCallee(PtrGlueCallee, DAG, dl, Subtarget);
5797 } else {
5798 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5799 dl, CFlags.HasNest, Subtarget);
5800 }
5801 } else {
5802 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5803 }
5804
5805 // Build the operand list for the call instruction.
5807 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5808 SPDiff, Subtarget);
5809
5810 // Emit tail call.
5811 if (CFlags.IsTailCall) {
5812 // Indirect tail call when using PC Relative calls do not have the same
5813 // constraints.
5814 assert(((Callee.getOpcode() == ISD::Register &&
5815 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5816 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5817 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5818 isa<ConstantSDNode>(Callee) ||
5819 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5820 "Expecting a global address, external symbol, absolute value, "
5821 "register or an indirect tail call when PC Relative calls are "
5822 "used.");
5823 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5824 assert(CallOpc == PPCISD::TC_RETURN &&
5825 "Unexpected call opcode for a tail call.");
5827 SDValue Ret = DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5828 DAG.addNoMergeSiteInfo(Ret.getNode(), CFlags.NoMerge);
5829 return Ret;
5830 }
5831
5832 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5833 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5834 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5835 Glue = Chain.getValue(1);
5836
5837 // When performing tail call optimization the callee pops its arguments off
5838 // the stack. Account for this here so these bytes can be pushed back on in
5839 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5840 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5842 ? NumBytes
5843 : 0;
5844
5845 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
5846 Glue = Chain.getValue(1);
5847
5848 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5849 DAG, InVals);
5850}
5851
5853 CallingConv::ID CalleeCC = CB->getCallingConv();
5854 const Function *CallerFunc = CB->getCaller();
5855 CallingConv::ID CallerCC = CallerFunc->getCallingConv();
5856 const Function *CalleeFunc = CB->getCalledFunction();
5857 if (!CalleeFunc)
5858 return false;
5859 const GlobalValue *CalleeGV = dyn_cast<GlobalValue>(CalleeFunc);
5860
5863
5864 GetReturnInfo(CalleeCC, CalleeFunc->getReturnType(),
5865 CalleeFunc->getAttributes(), Outs, *this,
5866 CalleeFunc->getDataLayout());
5867
5868 return isEligibleForTCO(CalleeGV, CalleeCC, CallerCC, CB,
5869 CalleeFunc->isVarArg(), Outs, Ins, CallerFunc,
5870 false /*isCalleeExternalSymbol*/);
5871}
5872
5873bool PPCTargetLowering::isEligibleForTCO(
5874 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5875 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5877 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5878 bool isCalleeExternalSymbol) const {
5879 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5880 return false;
5881
5882 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5883 return IsEligibleForTailCallOptimization_64SVR4(
5884 CalleeGV, CalleeCC, CallerCC, CB, isVarArg, Outs, Ins, CallerFunc,
5885 isCalleeExternalSymbol);
5886 else
5887 return IsEligibleForTailCallOptimization(CalleeGV, CalleeCC, CallerCC,
5888 isVarArg, Ins);
5889}
5890
5891SDValue
5892PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5893 SmallVectorImpl<SDValue> &InVals) const {
5894 SelectionDAG &DAG = CLI.DAG;
5895 SDLoc &dl = CLI.DL;
5897 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5899 SDValue Chain = CLI.Chain;
5900 SDValue Callee = CLI.Callee;
5901 bool &isTailCall = CLI.IsTailCall;
5902 CallingConv::ID CallConv = CLI.CallConv;
5903 bool isVarArg = CLI.IsVarArg;
5904 bool isPatchPoint = CLI.IsPatchPoint;
5905 const CallBase *CB = CLI.CB;
5906
5907 if (isTailCall) {
5909 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5910 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5911 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5912 bool IsCalleeExternalSymbol = isa<ExternalSymbolSDNode>(Callee);
5913
5914 isTailCall =
5915 isEligibleForTCO(GV, CallConv, CallerCC, CB, isVarArg, Outs, Ins,
5916 &(MF.getFunction()), IsCalleeExternalSymbol);
5917 if (isTailCall) {
5918 ++NumTailCalls;
5919 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5920 ++NumSiblingCalls;
5921
5922 // PC Relative calls no longer guarantee that the callee is a Global
5923 // Address Node. The callee could be an indirect tail call in which
5924 // case the SDValue for the callee could be a load (to load the address
5925 // of a function pointer) or it may be a register copy (to move the
5926 // address of the callee from a function parameter into a virtual
5927 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5928 assert((Subtarget.isUsingPCRelativeCalls() ||
5929 isa<GlobalAddressSDNode>(Callee)) &&
5930 "Callee should be an llvm::Function object.");
5931
5932 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5933 << "\nTCO callee: ");
5934 LLVM_DEBUG(Callee.dump());
5935 }
5936 }
5937
5938 if (!isTailCall && CB && CB->isMustTailCall())
5939 report_fatal_error("failed to perform tail call elimination on a call "
5940 "site marked musttail");
5941
5942 // When long calls (i.e. indirect calls) are always used, calls are always
5943 // made via function pointer. If we have a function name, first translate it
5944 // into a pointer.
5945 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5946 !isTailCall)
5947 Callee = LowerGlobalAddress(Callee, DAG);
5948
5949 CallFlags CFlags(
5950 CallConv, isTailCall, isVarArg, isPatchPoint,
5951 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5952 // hasNest
5953 Subtarget.is64BitELFABI() &&
5954 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5955 CLI.NoMerge);
5956
5957 if (Subtarget.isAIXABI())
5958 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5959 InVals, CB);
5960
5961 assert(Subtarget.isSVR4ABI());
5962 if (Subtarget.isPPC64())
5963 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5964 InVals, CB);
5965 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5966 InVals, CB);
5967}
5968
5969SDValue PPCTargetLowering::LowerCall_32SVR4(
5970 SDValue Chain, SDValue Callee, CallFlags CFlags,
5972 const SmallVectorImpl<SDValue> &OutVals,
5973 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5975 const CallBase *CB) const {
5976 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5977 // of the 32-bit SVR4 ABI stack frame layout.
5978
5979 const CallingConv::ID CallConv = CFlags.CallConv;
5980 const bool IsVarArg = CFlags.IsVarArg;
5981 const bool IsTailCall = CFlags.IsTailCall;
5982
5983 assert((CallConv == CallingConv::C ||
5984 CallConv == CallingConv::Cold ||
5985 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5986
5987 const Align PtrAlign(4);
5988
5989 MachineFunction &MF = DAG.getMachineFunction();
5990
5991 // Mark this function as potentially containing a function that contains a
5992 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5993 // and restoring the callers stack pointer in this functions epilog. This is
5994 // done because by tail calling the called function might overwrite the value
5995 // in this function's (MF) stack pointer stack slot 0(SP).
5996 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5997 CallConv == CallingConv::Fast)
5998 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5999
6000 // Count how many bytes are to be pushed on the stack, including the linkage
6001 // area, parameter list area and the part of the local variable space which
6002 // contains copies of aggregates which are passed by value.
6003
6004 // Assign locations to all of the outgoing arguments.
6006 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6007
6008 // Reserve space for the linkage area on the stack.
6009 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
6010 PtrAlign);
6011
6012 if (IsVarArg) {
6013 // Handle fixed and variable vector arguments differently.
6014 // Fixed vector arguments go into registers as long as registers are
6015 // available. Variable vector arguments always go into memory.
6016 unsigned NumArgs = Outs.size();
6017
6018 for (unsigned i = 0; i != NumArgs; ++i) {
6019 MVT ArgVT = Outs[i].VT;
6020 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6021 bool Result;
6022
6023 if (!ArgFlags.isVarArg()) {
6024 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
6025 Outs[i].OrigTy, CCInfo);
6026 } else {
6028 ArgFlags, Outs[i].OrigTy, CCInfo);
6029 }
6030
6031 if (Result) {
6032#ifndef NDEBUG
6033 errs() << "Call operand #" << i << " has unhandled type "
6034 << ArgVT << "\n";
6035#endif
6036 llvm_unreachable(nullptr);
6037 }
6038 }
6039 } else {
6040 // All arguments are treated the same.
6041 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
6042 }
6043
6044 // Assign locations to all of the outgoing aggregate by value arguments.
6045 SmallVector<CCValAssign, 16> ByValArgLocs;
6046 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
6047
6048 // Reserve stack space for the allocations in CCInfo.
6049 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
6050
6051 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
6052
6053 // Size of the linkage area, parameter list area and the part of the local
6054 // space variable where copies of aggregates which are passed by value are
6055 // stored.
6056 unsigned NumBytes = CCByValInfo.getStackSize();
6057
6058 // Calculate by how many bytes the stack has to be adjusted in case of tail
6059 // call optimization.
6060 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
6061
6062 // Adjust the stack pointer for the new arguments...
6063 // These operations are automatically eliminated by the prolog/epilog pass
6064 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6065 SDValue CallSeqStart = Chain;
6066
6067 // Load the return address and frame pointer so it can be moved somewhere else
6068 // later.
6069 SDValue LROp, FPOp;
6070 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6071
6072 // Set up a copy of the stack pointer for use loading and storing any
6073 // arguments that may not fit in the registers available for argument
6074 // passing.
6075 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6076
6078 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6079 SmallVector<SDValue, 8> MemOpChains;
6080
6081 bool seenFloatArg = false;
6082 // Walk the register/memloc assignments, inserting copies/loads.
6083 // i - Tracks the index into the list of registers allocated for the call
6084 // RealArgIdx - Tracks the index into the list of actual function arguments
6085 // j - Tracks the index into the list of byval arguments
6086 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
6087 i != e;
6088 ++i, ++RealArgIdx) {
6089 CCValAssign &VA = ArgLocs[i];
6090 SDValue Arg = OutVals[RealArgIdx];
6091 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
6092
6093 if (Flags.isByVal()) {
6094 // Argument is an aggregate which is passed by value, thus we need to
6095 // create a copy of it in the local variable space of the current stack
6096 // frame (which is the stack frame of the caller) and pass the address of
6097 // this copy to the callee.
6098 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
6099 CCValAssign &ByValVA = ByValArgLocs[j++];
6100 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
6101
6102 // Memory reserved in the local variable space of the callers stack frame.
6103 unsigned LocMemOffset = ByValVA.getLocMemOffset();
6104
6105 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6106 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6107 StackPtr, PtrOff);
6108
6109 // Create a copy of the argument in the local area of the current
6110 // stack frame.
6111 SDValue MemcpyCall =
6112 CreateCopyOfByValArgument(Arg, PtrOff,
6113 CallSeqStart.getNode()->getOperand(0),
6114 Flags, DAG, dl);
6115
6116 // This must go outside the CALLSEQ_START..END.
6117 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
6118 SDLoc(MemcpyCall));
6119 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6120 NewCallSeqStart.getNode());
6121 Chain = CallSeqStart = NewCallSeqStart;
6122
6123 // Pass the address of the aggregate copy on the stack either in a
6124 // physical register or in the parameter list area of the current stack
6125 // frame to the callee.
6126 Arg = PtrOff;
6127 }
6128
6129 // When useCRBits() is true, there can be i1 arguments.
6130 // It is because getRegisterType(MVT::i1) => MVT::i1,
6131 // and for other integer types getRegisterType() => MVT::i32.
6132 // Extend i1 and ensure callee will get i32.
6133 if (Arg.getValueType() == MVT::i1)
6134 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6135 dl, MVT::i32, Arg);
6136
6137 if (VA.isRegLoc()) {
6138 seenFloatArg |= VA.getLocVT().isFloatingPoint();
6139 // Put argument in a physical register.
6140 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
6141 bool IsLE = Subtarget.isLittleEndian();
6142 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6143 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
6144 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
6145 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6146 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
6147 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
6148 SVal.getValue(0)));
6149 } else
6150 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
6151 } else {
6152 // Put argument in the parameter list area of the current stack frame.
6153 assert(VA.isMemLoc());
6154 unsigned LocMemOffset = VA.getLocMemOffset();
6155
6156 if (!IsTailCall) {
6157 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6158 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6159 StackPtr, PtrOff);
6160
6161 MemOpChains.push_back(
6162 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6163 } else {
6164 // Calculate and remember argument location.
6165 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
6166 TailCallArguments);
6167 }
6168 }
6169 }
6170
6171 if (!MemOpChains.empty())
6172 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6173
6174 // Build a sequence of copy-to-reg nodes chained together with token chain
6175 // and flag operands which copy the outgoing args into the appropriate regs.
6176 SDValue InGlue;
6177 for (const auto &[Reg, N] : RegsToPass) {
6178 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6179 InGlue = Chain.getValue(1);
6180 }
6181
6182 // Set CR bit 6 to true if this is a vararg call with floating args passed in
6183 // registers.
6184 if (IsVarArg) {
6185 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6186 SDValue Ops[] = { Chain, InGlue };
6187
6188 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
6189 VTs, ArrayRef(Ops, InGlue.getNode() ? 2 : 1));
6190
6191 InGlue = Chain.getValue(1);
6192 }
6193
6194 if (IsTailCall)
6195 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6196 TailCallArguments);
6197
6198 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6199 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6200}
6201
6202// Copy an argument into memory, being careful to do this outside the
6203// call sequence for the call to which the argument belongs.
6204SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6205 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6206 SelectionDAG &DAG, const SDLoc &dl) const {
6207 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6208 CallSeqStart.getNode()->getOperand(0),
6209 Flags, DAG, dl);
6210 // The MEMCPY must go outside the CALLSEQ_START..END.
6211 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6212 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6213 SDLoc(MemcpyCall));
6214 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6215 NewCallSeqStart.getNode());
6216 return NewCallSeqStart;
6217}
6218
6219SDValue PPCTargetLowering::LowerCall_64SVR4(
6220 SDValue Chain, SDValue Callee, CallFlags CFlags,
6222 const SmallVectorImpl<SDValue> &OutVals,
6223 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6225 const CallBase *CB) const {
6226 bool isELFv2ABI = Subtarget.isELFv2ABI();
6227 bool isLittleEndian = Subtarget.isLittleEndian();
6228 unsigned NumOps = Outs.size();
6229 bool IsSibCall = false;
6230 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6231
6232 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6233 unsigned PtrByteSize = 8;
6234
6235 MachineFunction &MF = DAG.getMachineFunction();
6236
6237 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6238 IsSibCall = true;
6239
6240 // Mark this function as potentially containing a function that contains a
6241 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6242 // and restoring the callers stack pointer in this functions epilog. This is
6243 // done because by tail calling the called function might overwrite the value
6244 // in this function's (MF) stack pointer stack slot 0(SP).
6245 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6246 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6247
6248 assert(!(IsFastCall && CFlags.IsVarArg) &&
6249 "fastcc not supported on varargs functions");
6250
6251 // Count how many bytes are to be pushed on the stack, including the linkage
6252 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
6253 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6254 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6255 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6256 unsigned NumBytes = LinkageSize;
6257 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6258
6259 static const MCPhysReg GPR[] = {
6260 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6261 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6262 };
6263 static const MCPhysReg VR[] = {
6264 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6265 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6266 };
6267
6268 const unsigned NumGPRs = std::size(GPR);
6269 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6270 const unsigned NumVRs = std::size(VR);
6271
6272 // On ELFv2, we can avoid allocating the parameter area if all the arguments
6273 // can be passed to the callee in registers.
6274 // For the fast calling convention, there is another check below.
6275 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6276 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6277 if (!HasParameterArea) {
6278 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6279 unsigned AvailableFPRs = NumFPRs;
6280 unsigned AvailableVRs = NumVRs;
6281 unsigned NumBytesTmp = NumBytes;
6282 for (unsigned i = 0; i != NumOps; ++i) {
6283 if (Outs[i].Flags.isNest()) continue;
6284 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6285 PtrByteSize, LinkageSize, ParamAreaSize,
6286 NumBytesTmp, AvailableFPRs, AvailableVRs))
6287 HasParameterArea = true;
6288 }
6289 }
6290
6291 // When using the fast calling convention, we don't provide backing for
6292 // arguments that will be in registers.
6293 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6294
6295 // Avoid allocating parameter area for fastcc functions if all the arguments
6296 // can be passed in the registers.
6297 if (IsFastCall)
6298 HasParameterArea = false;
6299
6300 // Add up all the space actually used.
6301 for (unsigned i = 0; i != NumOps; ++i) {
6302 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6303 EVT ArgVT = Outs[i].VT;
6304 EVT OrigVT = Outs[i].ArgVT;
6305
6306 if (Flags.isNest())
6307 continue;
6308
6309 if (IsFastCall) {
6310 if (Flags.isByVal()) {
6311 NumGPRsUsed += (Flags.getByValSize()+7)/8;
6312 if (NumGPRsUsed > NumGPRs)
6313 HasParameterArea = true;
6314 } else {
6315 switch (ArgVT.getSimpleVT().SimpleTy) {
6316 default: llvm_unreachable("Unexpected ValueType for argument!");
6317 case MVT::i1:
6318 case MVT::i32:
6319 case MVT::i64:
6320 if (++NumGPRsUsed <= NumGPRs)
6321 continue;
6322 break;
6323 case MVT::v4i32:
6324 case MVT::v8i16:
6325 case MVT::v16i8:
6326 case MVT::v2f64:
6327 case MVT::v2i64:
6328 case MVT::v1i128:
6329 case MVT::f128:
6330 if (++NumVRsUsed <= NumVRs)
6331 continue;
6332 break;
6333 case MVT::v4f32:
6334 if (++NumVRsUsed <= NumVRs)
6335 continue;
6336 break;
6337 case MVT::f32:
6338 case MVT::f64:
6339 if (++NumFPRsUsed <= NumFPRs)
6340 continue;
6341 break;
6342 }
6343 HasParameterArea = true;
6344 }
6345 }
6346
6347 /* Respect alignment of argument on the stack. */
6348 auto Alignement =
6349 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6350 NumBytes = alignTo(NumBytes, Alignement);
6351
6352 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6353 if (Flags.isInConsecutiveRegsLast())
6354 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6355 }
6356
6357 unsigned NumBytesActuallyUsed = NumBytes;
6358
6359 // In the old ELFv1 ABI,
6360 // the prolog code of the callee may store up to 8 GPR argument registers to
6361 // the stack, allowing va_start to index over them in memory if its varargs.
6362 // Because we cannot tell if this is needed on the caller side, we have to
6363 // conservatively assume that it is needed. As such, make sure we have at
6364 // least enough stack space for the caller to store the 8 GPRs.
6365 // In the ELFv2 ABI, we allocate the parameter area iff a callee
6366 // really requires memory operands, e.g. a vararg function.
6367 if (HasParameterArea)
6368 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6369 else
6370 NumBytes = LinkageSize;
6371
6372 // Tail call needs the stack to be aligned.
6373 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6374 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6375
6376 int SPDiff = 0;
6377
6378 // Calculate by how many bytes the stack has to be adjusted in case of tail
6379 // call optimization.
6380 if (!IsSibCall)
6381 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6382
6383 // To protect arguments on the stack from being clobbered in a tail call,
6384 // force all the loads to happen before doing any other lowering.
6385 if (CFlags.IsTailCall)
6386 Chain = DAG.getStackArgumentTokenFactor(Chain);
6387
6388 // Adjust the stack pointer for the new arguments...
6389 // These operations are automatically eliminated by the prolog/epilog pass
6390 if (!IsSibCall)
6391 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6392 SDValue CallSeqStart = Chain;
6393
6394 // Load the return address and frame pointer so it can be move somewhere else
6395 // later.
6396 SDValue LROp, FPOp;
6397 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6398
6399 // Set up a copy of the stack pointer for use loading and storing any
6400 // arguments that may not fit in the registers available for argument
6401 // passing.
6402 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6403
6404 // Figure out which arguments are going to go in registers, and which in
6405 // memory. Also, if this is a vararg function, floating point operations
6406 // must be stored to our stack, and loaded into integer regs as well, if
6407 // any integer regs are available for argument passing.
6408 unsigned ArgOffset = LinkageSize;
6409
6411 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6412
6413 SmallVector<SDValue, 8> MemOpChains;
6414 for (unsigned i = 0; i != NumOps; ++i) {
6415 SDValue Arg = OutVals[i];
6416 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6417 EVT ArgVT = Outs[i].VT;
6418 EVT OrigVT = Outs[i].ArgVT;
6419
6420 // PtrOff will be used to store the current argument to the stack if a
6421 // register cannot be found for it.
6422 SDValue PtrOff;
6423
6424 // We re-align the argument offset for each argument, except when using the
6425 // fast calling convention, when we need to make sure we do that only when
6426 // we'll actually use a stack slot.
6427 auto ComputePtrOff = [&]() {
6428 /* Respect alignment of argument on the stack. */
6429 auto Alignment =
6430 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6431 ArgOffset = alignTo(ArgOffset, Alignment);
6432
6433 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6434
6435 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6436 };
6437
6438 if (!IsFastCall) {
6439 ComputePtrOff();
6440
6441 /* Compute GPR index associated with argument offset. */
6442 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6443 GPR_idx = std::min(GPR_idx, NumGPRs);
6444 }
6445
6446 // Promote integers to 64-bit values.
6447 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6448 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6449 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6450 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6451 }
6452
6453 // FIXME memcpy is used way more than necessary. Correctness first.
6454 // Note: "by value" is code for passing a structure by value, not
6455 // basic types.
6456 if (Flags.isByVal()) {
6457 // Note: Size includes alignment padding, so
6458 // struct x { short a; char b; }
6459 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
6460 // These are the proper values we need for right-justifying the
6461 // aggregate in a parameter register.
6462 unsigned Size = Flags.getByValSize();
6463
6464 // An empty aggregate parameter takes up no storage and no
6465 // registers.
6466 if (Size == 0)
6467 continue;
6468
6469 if (IsFastCall)
6470 ComputePtrOff();
6471
6472 // All aggregates smaller than 8 bytes must be passed right-justified.
6473 if (Size==1 || Size==2 || Size==4) {
6474 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6475 if (GPR_idx != NumGPRs) {
6476 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6477 MachinePointerInfo(), VT);
6478 MemOpChains.push_back(Load.getValue(1));
6479 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6480
6481 ArgOffset += PtrByteSize;
6482 continue;
6483 }
6484 }
6485
6486 if (GPR_idx == NumGPRs && Size < 8) {
6487 SDValue AddPtr = PtrOff;
6488 if (!isLittleEndian) {
6489 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6490 PtrOff.getValueType());
6491 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6492 }
6493 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6494 CallSeqStart,
6495 Flags, DAG, dl);
6496 ArgOffset += PtrByteSize;
6497 continue;
6498 }
6499 // Copy the object to parameter save area if it can not be entirely passed
6500 // by registers.
6501 // FIXME: we only need to copy the parts which need to be passed in
6502 // parameter save area. For the parts passed by registers, we don't need
6503 // to copy them to the stack although we need to allocate space for them
6504 // in parameter save area.
6505 if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6506 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6507 CallSeqStart,
6508 Flags, DAG, dl);
6509
6510 // When a register is available, pass a small aggregate right-justified.
6511 if (Size < 8 && GPR_idx != NumGPRs) {
6512 // The easiest way to get this right-justified in a register
6513 // is to copy the structure into the rightmost portion of a
6514 // local variable slot, then load the whole slot into the
6515 // register.
6516 // FIXME: The memcpy seems to produce pretty awful code for
6517 // small aggregates, particularly for packed ones.
6518 // FIXME: It would be preferable to use the slot in the
6519 // parameter save area instead of a new local variable.
6520 SDValue AddPtr = PtrOff;
6521 if (!isLittleEndian) {
6522 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6523 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6524 }
6525 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6526 CallSeqStart,
6527 Flags, DAG, dl);
6528
6529 // Load the slot into the register.
6530 SDValue Load =
6531 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6532 MemOpChains.push_back(Load.getValue(1));
6533 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6534
6535 // Done with this argument.
6536 ArgOffset += PtrByteSize;
6537 continue;
6538 }
6539
6540 // For aggregates larger than PtrByteSize, copy the pieces of the
6541 // object that fit into registers from the parameter save area.
6542 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6543 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6544 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6545 if (GPR_idx != NumGPRs) {
6546 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6547 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6548 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6549 MachinePointerInfo(), ObjType);
6550
6551 MemOpChains.push_back(Load.getValue(1));
6552 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6553 ArgOffset += PtrByteSize;
6554 } else {
6555 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6556 break;
6557 }
6558 }
6559 continue;
6560 }
6561
6562 switch (Arg.getSimpleValueType().SimpleTy) {
6563 default: llvm_unreachable("Unexpected ValueType for argument!");
6564 case MVT::i1:
6565 case MVT::i32:
6566 case MVT::i64:
6567 if (Flags.isNest()) {
6568 // The 'nest' parameter, if any, is passed in R11.
6569 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6570 break;
6571 }
6572
6573 // These can be scalar arguments or elements of an integer array type
6574 // passed directly. Clang may use those instead of "byval" aggregate
6575 // types to avoid forcing arguments to memory unnecessarily.
6576 if (GPR_idx != NumGPRs) {
6577 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6578 } else {
6579 if (IsFastCall)
6580 ComputePtrOff();
6581
6582 assert(HasParameterArea &&
6583 "Parameter area must exist to pass an argument in memory.");
6584 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6585 true, CFlags.IsTailCall, false, MemOpChains,
6586 TailCallArguments, dl);
6587 if (IsFastCall)
6588 ArgOffset += PtrByteSize;
6589 }
6590 if (!IsFastCall)
6591 ArgOffset += PtrByteSize;
6592 break;
6593 case MVT::f32:
6594 case MVT::f64: {
6595 // These can be scalar arguments or elements of a float array type
6596 // passed directly. The latter are used to implement ELFv2 homogenous
6597 // float aggregates.
6598
6599 // Named arguments go into FPRs first, and once they overflow, the
6600 // remaining arguments go into GPRs and then the parameter save area.
6601 // Unnamed arguments for vararg functions always go to GPRs and
6602 // then the parameter save area. For now, put all arguments to vararg
6603 // routines always in both locations (FPR *and* GPR or stack slot).
6604 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6605 bool NeededLoad = false;
6606
6607 // First load the argument into the next available FPR.
6608 if (FPR_idx != NumFPRs)
6609 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6610
6611 // Next, load the argument into GPR or stack slot if needed.
6612 if (!NeedGPROrStack)
6613 ;
6614 else if (GPR_idx != NumGPRs && !IsFastCall) {
6615 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6616 // once we support fp <-> gpr moves.
6617
6618 // In the non-vararg case, this can only ever happen in the
6619 // presence of f32 array types, since otherwise we never run
6620 // out of FPRs before running out of GPRs.
6621 SDValue ArgVal;
6622
6623 // Double values are always passed in a single GPR.
6624 if (Arg.getValueType() != MVT::f32) {
6625 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6626
6627 // Non-array float values are extended and passed in a GPR.
6628 } else if (!Flags.isInConsecutiveRegs()) {
6629 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6630 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6631
6632 // If we have an array of floats, we collect every odd element
6633 // together with its predecessor into one GPR.
6634 } else if (ArgOffset % PtrByteSize != 0) {
6635 SDValue Lo, Hi;
6636 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6637 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6638 if (!isLittleEndian)
6639 std::swap(Lo, Hi);
6640 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6641
6642 // The final element, if even, goes into the first half of a GPR.
6643 } else if (Flags.isInConsecutiveRegsLast()) {
6644 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6645 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6646 if (!isLittleEndian)
6647 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6648 DAG.getConstant(32, dl, MVT::i32));
6649
6650 // Non-final even elements are skipped; they will be handled
6651 // together the with subsequent argument on the next go-around.
6652 } else
6653 ArgVal = SDValue();
6654
6655 if (ArgVal.getNode())
6656 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6657 } else {
6658 if (IsFastCall)
6659 ComputePtrOff();
6660
6661 // Single-precision floating-point values are mapped to the
6662 // second (rightmost) word of the stack doubleword.
6663 if (Arg.getValueType() == MVT::f32 &&
6664 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6665 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6666 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6667 }
6668
6669 assert(HasParameterArea &&
6670 "Parameter area must exist to pass an argument in memory.");
6671 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6672 true, CFlags.IsTailCall, false, MemOpChains,
6673 TailCallArguments, dl);
6674
6675 NeededLoad = true;
6676 }
6677 // When passing an array of floats, the array occupies consecutive
6678 // space in the argument area; only round up to the next doubleword
6679 // at the end of the array. Otherwise, each float takes 8 bytes.
6680 if (!IsFastCall || NeededLoad) {
6681 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6682 Flags.isInConsecutiveRegs()) ? 4 : 8;
6683 if (Flags.isInConsecutiveRegsLast())
6684 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6685 }
6686 break;
6687 }
6688 case MVT::v4f32:
6689 case MVT::v4i32:
6690 case MVT::v8i16:
6691 case MVT::v16i8:
6692 case MVT::v2f64:
6693 case MVT::v2i64:
6694 case MVT::v1i128:
6695 case MVT::f128:
6696 // These can be scalar arguments or elements of a vector array type
6697 // passed directly. The latter are used to implement ELFv2 homogenous
6698 // vector aggregates.
6699
6700 // For a varargs call, named arguments go into VRs or on the stack as
6701 // usual; unnamed arguments always go to the stack or the corresponding
6702 // GPRs when within range. For now, we always put the value in both
6703 // locations (or even all three).
6704 if (CFlags.IsVarArg) {
6705 assert(HasParameterArea &&
6706 "Parameter area must exist if we have a varargs call.");
6707 // We could elide this store in the case where the object fits
6708 // entirely in R registers. Maybe later.
6709 SDValue Store =
6710 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6711 MemOpChains.push_back(Store);
6712 if (VR_idx != NumVRs) {
6713 SDValue Load =
6714 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6715 MemOpChains.push_back(Load.getValue(1));
6716 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6717 }
6718 ArgOffset += 16;
6719 for (unsigned i=0; i<16; i+=PtrByteSize) {
6720 if (GPR_idx == NumGPRs)
6721 break;
6722 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6723 DAG.getConstant(i, dl, PtrVT));
6724 SDValue Load =
6725 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6726 MemOpChains.push_back(Load.getValue(1));
6727 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6728 }
6729 break;
6730 }
6731
6732 // Non-varargs Altivec params go into VRs or on the stack.
6733 if (VR_idx != NumVRs) {
6734 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6735 } else {
6736 if (IsFastCall)
6737 ComputePtrOff();
6738
6739 assert(HasParameterArea &&
6740 "Parameter area must exist to pass an argument in memory.");
6741 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6742 true, CFlags.IsTailCall, true, MemOpChains,
6743 TailCallArguments, dl);
6744 if (IsFastCall)
6745 ArgOffset += 16;
6746 }
6747
6748 if (!IsFastCall)
6749 ArgOffset += 16;
6750 break;
6751 }
6752 }
6753
6754 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6755 "mismatch in size of parameter area");
6756 (void)NumBytesActuallyUsed;
6757
6758 if (!MemOpChains.empty())
6759 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6760
6761 // Check if this is an indirect call (MTCTR/BCTRL).
6762 // See prepareDescriptorIndirectCall and buildCallOperands for more
6763 // information about calls through function pointers in the 64-bit SVR4 ABI.
6764 if (CFlags.IsIndirect) {
6765 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6766 // caller in the TOC save area.
6767 if (isTOCSaveRestoreRequired(Subtarget)) {
6768 assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6769 // Load r2 into a virtual register and store it to the TOC save area.
6770 setUsesTOCBasePtr(DAG);
6771 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6772 // TOC save area offset.
6773 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6774 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6775 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6776 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6778 DAG.getMachineFunction(), TOCSaveOffset));
6779 }
6780 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6781 // This does not mean the MTCTR instruction must use R12; it's easier
6782 // to model this as an extra parameter, so do that.
6783 if (isELFv2ABI && !CFlags.IsPatchPoint)
6784 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6785 }
6786
6787 // Build a sequence of copy-to-reg nodes chained together with token chain
6788 // and flag operands which copy the outgoing args into the appropriate regs.
6789 SDValue InGlue;
6790 for (const auto &[Reg, N] : RegsToPass) {
6791 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6792 InGlue = Chain.getValue(1);
6793 }
6794
6795 if (CFlags.IsTailCall && !IsSibCall)
6796 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6797 TailCallArguments);
6798
6799 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6800 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6801}
6802
6803// Returns true when the shadow of a general purpose argument register
6804// in the parameter save area is aligned to at least 'RequiredAlign'.
6805static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6806 assert(RequiredAlign.value() <= 16 &&
6807 "Required alignment greater than stack alignment.");
6808 switch (Reg) {
6809 default:
6810 report_fatal_error("called on invalid register.");
6811 case PPC::R5:
6812 case PPC::R9:
6813 case PPC::X3:
6814 case PPC::X5:
6815 case PPC::X7:
6816 case PPC::X9:
6817 // These registers are 16 byte aligned which is the most strict aligment
6818 // we can support.
6819 return true;
6820 case PPC::R3:
6821 case PPC::R7:
6822 case PPC::X4:
6823 case PPC::X6:
6824 case PPC::X8:
6825 case PPC::X10:
6826 // The shadow of these registers in the PSA is 8 byte aligned.
6827 return RequiredAlign <= 8;
6828 case PPC::R4:
6829 case PPC::R6:
6830 case PPC::R8:
6831 case PPC::R10:
6832 return RequiredAlign <= 4;
6833 }
6834}
6835
6836static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6837 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6838 Type *OrigTy, CCState &State) {
6839 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6840 State.getMachineFunction().getSubtarget());
6841 const bool IsPPC64 = Subtarget.isPPC64();
6842 const unsigned PtrSize = IsPPC64 ? 8 : 4;
6843 const Align PtrAlign(PtrSize);
6844 const Align StackAlign(16);
6845 const MVT RegVT = Subtarget.getScalarIntVT();
6846
6847 if (ValVT == MVT::f128)
6848 report_fatal_error("f128 is unimplemented on AIX.");
6849
6850 static const MCPhysReg GPR_32[] = {// 32-bit registers.
6851 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6852 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6853 static const MCPhysReg GPR_64[] = {// 64-bit registers.
6854 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6855 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6856
6857 static const MCPhysReg VR[] = {// Vector registers.
6858 PPC::V2, PPC::V3, PPC::V4, PPC::V5,
6859 PPC::V6, PPC::V7, PPC::V8, PPC::V9,
6860 PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6861
6862 const ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6863
6864 if (ArgFlags.isNest()) {
6865 MCRegister EnvReg = State.AllocateReg(IsPPC64 ? PPC::X11 : PPC::R11);
6866 if (!EnvReg)
6867 report_fatal_error("More then one nest argument.");
6868 State.addLoc(CCValAssign::getReg(ValNo, ValVT, EnvReg, RegVT, LocInfo));
6869 return false;
6870 }
6871
6872 if (ArgFlags.isByVal()) {
6873 const Align ByValAlign(ArgFlags.getNonZeroByValAlign());
6874 if (ByValAlign > StackAlign)
6875 report_fatal_error("Pass-by-value arguments with alignment greater than "
6876 "16 are not supported.");
6877
6878 const unsigned ByValSize = ArgFlags.getByValSize();
6879 const Align ObjAlign = ByValAlign > PtrAlign ? ByValAlign : PtrAlign;
6880
6881 // An empty aggregate parameter takes up no storage and no registers,
6882 // but needs a MemLoc for a stack slot for the formal arguments side.
6883 if (ByValSize == 0) {
6885 State.getStackSize(), RegVT, LocInfo));
6886 return false;
6887 }
6888
6889 // Shadow allocate any registers that are not properly aligned.
6890 unsigned NextReg = State.getFirstUnallocated(GPRs);
6891 while (NextReg != GPRs.size() &&
6892 !isGPRShadowAligned(GPRs[NextReg], ObjAlign)) {
6893 // Shadow allocate next registers since its aligment is not strict enough.
6894 MCRegister Reg = State.AllocateReg(GPRs);
6895 // Allocate the stack space shadowed by said register.
6896 State.AllocateStack(PtrSize, PtrAlign);
6897 assert(Reg && "Alocating register unexpectedly failed.");
6898 (void)Reg;
6899 NextReg = State.getFirstUnallocated(GPRs);
6900 }
6901
6902 const unsigned StackSize = alignTo(ByValSize, ObjAlign);
6903 unsigned Offset = State.AllocateStack(StackSize, ObjAlign);
6904 for (const unsigned E = Offset + StackSize; Offset < E; Offset += PtrSize) {
6905 if (MCRegister Reg = State.AllocateReg(GPRs))
6906 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6907 else {
6910 LocInfo));
6911 break;
6912 }
6913 }
6914 return false;
6915 }
6916
6917 // Arguments always reserve parameter save area.
6918 switch (ValVT.SimpleTy) {
6919 default:
6920 report_fatal_error("Unhandled value type for argument.");
6921 case MVT::i64:
6922 // i64 arguments should have been split to i32 for PPC32.
6923 assert(IsPPC64 && "PPC32 should have split i64 values.");
6924 [[fallthrough]];
6925 case MVT::i1:
6926 case MVT::i32: {
6927 const unsigned Offset = State.AllocateStack(PtrSize, PtrAlign);
6928 // AIX integer arguments are always passed in register width.
6929 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6930 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6932 if (MCRegister Reg = State.AllocateReg(GPRs))
6933 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6934 else
6935 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6936
6937 return false;
6938 }
6939 case MVT::f32:
6940 case MVT::f64: {
6941 // Parameter save area (PSA) is reserved even if the float passes in fpr.
6942 const unsigned StoreSize = LocVT.getStoreSize();
6943 // Floats are always 4-byte aligned in the PSA on AIX.
6944 // This includes f64 in 64-bit mode for ABI compatibility.
6945 const unsigned Offset =
6946 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6947 MCRegister FReg = State.AllocateReg(FPR);
6948 if (FReg)
6949 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6950
6951 // Reserve and initialize GPRs or initialize the PSA as required.
6952 for (unsigned I = 0; I < StoreSize; I += PtrSize) {
6953 if (MCRegister Reg = State.AllocateReg(GPRs)) {
6954 assert(FReg && "An FPR should be available when a GPR is reserved.");
6955 if (State.isVarArg()) {
6956 // Successfully reserved GPRs are only initialized for vararg calls.
6957 // Custom handling is required for:
6958 // f64 in PPC32 needs to be split into 2 GPRs.
6959 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6960 State.addLoc(
6961 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6962 }
6963 } else {
6964 // If there are insufficient GPRs, the PSA needs to be initialized.
6965 // Initialization occurs even if an FPR was initialized for
6966 // compatibility with the AIX XL compiler. The full memory for the
6967 // argument will be initialized even if a prior word is saved in GPR.
6968 // A custom memLoc is used when the argument also passes in FPR so
6969 // that the callee handling can skip over it easily.
6970 State.addLoc(
6971 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6972 LocInfo)
6973 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6974 break;
6975 }
6976 }
6977
6978 return false;
6979 }
6980 case MVT::v4f32:
6981 case MVT::v4i32:
6982 case MVT::v8i16:
6983 case MVT::v16i8:
6984 case MVT::v2i64:
6985 case MVT::v2f64:
6986 case MVT::v1i128: {
6987 const unsigned VecSize = 16;
6988 const Align VecAlign(VecSize);
6989
6990 if (!State.isVarArg()) {
6991 // If there are vector registers remaining we don't consume any stack
6992 // space.
6993 if (MCRegister VReg = State.AllocateReg(VR)) {
6994 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6995 return false;
6996 }
6997 // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6998 // might be allocated in the portion of the PSA that is shadowed by the
6999 // GPRs.
7000 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7001 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7002 return false;
7003 }
7004
7005 unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
7006 // Burn any underaligned registers and their shadowed stack space until
7007 // we reach the required alignment.
7008 while (NextRegIndex != GPRs.size() &&
7009 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
7010 // Shadow allocate register and its stack shadow.
7011 MCRegister Reg = State.AllocateReg(GPRs);
7012 State.AllocateStack(PtrSize, PtrAlign);
7013 assert(Reg && "Allocating register unexpectedly failed.");
7014 (void)Reg;
7015 NextRegIndex = State.getFirstUnallocated(GPRs);
7016 }
7017
7018 // Vectors that are passed as fixed arguments are handled differently.
7019 // They are passed in VRs if any are available (unlike arguments passed
7020 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
7021 // functions)
7022 if (!ArgFlags.isVarArg()) {
7023 if (MCRegister VReg = State.AllocateReg(VR)) {
7024 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7025 // Shadow allocate GPRs and stack space even though we pass in a VR.
7026 for (unsigned I = 0; I != VecSize; I += PtrSize)
7027 State.AllocateReg(GPRs);
7028 State.AllocateStack(VecSize, VecAlign);
7029 return false;
7030 }
7031 // No vector registers remain so pass on the stack.
7032 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7033 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7034 return false;
7035 }
7036
7037 // If all GPRS are consumed then we pass the argument fully on the stack.
7038 if (NextRegIndex == GPRs.size()) {
7039 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7040 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7041 return false;
7042 }
7043
7044 // Corner case for 32-bit codegen. We have 2 registers to pass the first
7045 // half of the argument, and then need to pass the remaining half on the
7046 // stack.
7047 if (GPRs[NextRegIndex] == PPC::R9) {
7048 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7049 State.addLoc(
7050 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7051
7052 const MCRegister FirstReg = State.AllocateReg(PPC::R9);
7053 const MCRegister SecondReg = State.AllocateReg(PPC::R10);
7054 assert(FirstReg && SecondReg &&
7055 "Allocating R9 or R10 unexpectedly failed.");
7056 State.addLoc(
7057 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
7058 State.addLoc(
7059 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
7060 return false;
7061 }
7062
7063 // We have enough GPRs to fully pass the vector argument, and we have
7064 // already consumed any underaligned registers. Start with the custom
7065 // MemLoc and then the custom RegLocs.
7066 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7067 State.addLoc(
7068 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7069 for (unsigned I = 0; I != VecSize; I += PtrSize) {
7070 const MCRegister Reg = State.AllocateReg(GPRs);
7071 assert(Reg && "Failed to allocated register for vararg vector argument");
7072 State.addLoc(
7073 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7074 }
7075 return false;
7076 }
7077 }
7078 return true;
7079}
7080
7081// So far, this function is only used by LowerFormalArguments_AIX()
7083 bool IsPPC64,
7084 bool HasP8Vector,
7085 bool HasVSX) {
7086 assert((IsPPC64 || SVT != MVT::i64) &&
7087 "i64 should have been split for 32-bit codegen.");
7088
7089 switch (SVT) {
7090 default:
7091 report_fatal_error("Unexpected value type for formal argument");
7092 case MVT::i1:
7093 case MVT::i32:
7094 case MVT::i64:
7095 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7096 case MVT::f32:
7097 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
7098 case MVT::f64:
7099 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
7100 case MVT::v4f32:
7101 case MVT::v4i32:
7102 case MVT::v8i16:
7103 case MVT::v16i8:
7104 case MVT::v2i64:
7105 case MVT::v2f64:
7106 case MVT::v1i128:
7107 return &PPC::VRRCRegClass;
7108 }
7109}
7110
7112 SelectionDAG &DAG, SDValue ArgValue,
7113 MVT LocVT, const SDLoc &dl) {
7114 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7115 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7116
7117 if (Flags.isSExt())
7118 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7119 DAG.getValueType(ValVT));
7120 else if (Flags.isZExt())
7121 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7122 DAG.getValueType(ValVT));
7123
7124 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7125}
7126
7127static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7128 const unsigned LASize = FL->getLinkageSize();
7129
7130 if (PPC::GPRCRegClass.contains(Reg)) {
7131 assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7132 "Reg must be a valid argument register!");
7133 return LASize + 4 * (Reg - PPC::R3);
7134 }
7135
7136 if (PPC::G8RCRegClass.contains(Reg)) {
7137 assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7138 "Reg must be a valid argument register!");
7139 return LASize + 8 * (Reg - PPC::X3);
7140 }
7141
7142 llvm_unreachable("Only general purpose registers expected.");
7143}
7144
7145// AIX ABI Stack Frame Layout:
7146//
7147// Low Memory +--------------------------------------------+
7148// SP +---> | Back chain | ---+
7149// | +--------------------------------------------+ |
7150// | | Saved Condition Register | |
7151// | +--------------------------------------------+ |
7152// | | Saved Linkage Register | |
7153// | +--------------------------------------------+ | Linkage Area
7154// | | Reserved for compilers | |
7155// | +--------------------------------------------+ |
7156// | | Reserved for binders | |
7157// | +--------------------------------------------+ |
7158// | | Saved TOC pointer | ---+
7159// | +--------------------------------------------+
7160// | | Parameter save area |
7161// | +--------------------------------------------+
7162// | | Alloca space |
7163// | +--------------------------------------------+
7164// | | Local variable space |
7165// | +--------------------------------------------+
7166// | | Float/int conversion temporary |
7167// | +--------------------------------------------+
7168// | | Save area for AltiVec registers |
7169// | +--------------------------------------------+
7170// | | AltiVec alignment padding |
7171// | +--------------------------------------------+
7172// | | Save area for VRSAVE register |
7173// | +--------------------------------------------+
7174// | | Save area for General Purpose registers |
7175// | +--------------------------------------------+
7176// | | Save area for Floating Point registers |
7177// | +--------------------------------------------+
7178// +---- | Back chain |
7179// High Memory +--------------------------------------------+
7180//
7181// Specifications:
7182// AIX 7.2 Assembler Language Reference
7183// Subroutine linkage convention
7184
7185SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7186 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7187 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7188 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7189
7190 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7191 CallConv == CallingConv::Fast) &&
7192 "Unexpected calling convention!");
7193
7194 if (getTargetMachine().Options.GuaranteedTailCallOpt)
7195 report_fatal_error("Tail call support is unimplemented on AIX.");
7196
7197 if (useSoftFloat())
7198 report_fatal_error("Soft float support is unimplemented on AIX.");
7199
7200 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7201
7202 const bool IsPPC64 = Subtarget.isPPC64();
7203 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7204
7205 // Assign locations to all of the incoming arguments.
7207 MachineFunction &MF = DAG.getMachineFunction();
7208 MachineFrameInfo &MFI = MF.getFrameInfo();
7209 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7210 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7211
7212 const EVT PtrVT = getPointerTy(MF.getDataLayout());
7213 // Reserve space for the linkage area on the stack.
7214 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7215 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7216 uint64_t SaveStackPos = CCInfo.getStackSize();
7217 bool SaveParams = MF.getFunction().hasFnAttribute("save-reg-params");
7218 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7219
7221
7222 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7223 CCValAssign &VA = ArgLocs[I++];
7224 MVT LocVT = VA.getLocVT();
7225 MVT ValVT = VA.getValVT();
7226 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7227
7228 EVT ArgVT = Ins[VA.getValNo()].ArgVT;
7229 bool ArgSignExt = Ins[VA.getValNo()].Flags.isSExt();
7230 // For compatibility with the AIX XL compiler, the float args in the
7231 // parameter save area are initialized even if the argument is available
7232 // in register. The caller is required to initialize both the register
7233 // and memory, however, the callee can choose to expect it in either.
7234 // The memloc is dismissed here because the argument is retrieved from
7235 // the register.
7236 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
7237 continue;
7238
7239 if (SaveParams && VA.isRegLoc() && !Flags.isByVal() && !VA.needsCustom()) {
7240 const TargetRegisterClass *RegClass = getRegClassForSVT(
7241 LocVT.SimpleTy, IsPPC64, Subtarget.hasP8Vector(), Subtarget.hasVSX());
7242 // On PPC64, debugger assumes extended 8-byte values are stored from GPR.
7243 MVT SaveVT = RegClass == &PPC::G8RCRegClass ? MVT::i64 : LocVT;
7244 const Register VReg = MF.addLiveIn(VA.getLocReg(), RegClass);
7245 SDValue Parm = DAG.getCopyFromReg(Chain, dl, VReg, SaveVT);
7246 int FI = MFI.CreateFixedObject(SaveVT.getStoreSize(), SaveStackPos, true);
7247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7248 SDValue StoreReg = DAG.getStore(Chain, dl, Parm, FIN,
7249 MachinePointerInfo(), Align(PtrByteSize));
7250 SaveStackPos = alignTo(SaveStackPos + SaveVT.getStoreSize(), PtrByteSize);
7251 MemOps.push_back(StoreReg);
7252 }
7253
7254 if (SaveParams && (VA.isMemLoc() || Flags.isByVal()) && !VA.needsCustom()) {
7255 unsigned StoreSize =
7256 Flags.isByVal() ? Flags.getByValSize() : LocVT.getStoreSize();
7257 SaveStackPos = alignTo(SaveStackPos + StoreSize, PtrByteSize);
7258 }
7259
7260 auto HandleMemLoc = [&]() {
7261 const unsigned LocSize = LocVT.getStoreSize();
7262 const unsigned ValSize = ValVT.getStoreSize();
7263 assert((ValSize <= LocSize) &&
7264 "Object size is larger than size of MemLoc");
7265 int CurArgOffset = VA.getLocMemOffset();
7266 // Objects are right-justified because AIX is big-endian.
7267 if (LocSize > ValSize)
7268 CurArgOffset += LocSize - ValSize;
7269 // Potential tail calls could cause overwriting of argument stack slots.
7270 const bool IsImmutable =
7272 (CallConv == CallingConv::Fast));
7273 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7274 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7275 SDValue ArgValue =
7276 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7277
7278 // While the ABI specifies the argument type is (sign or zero) extended
7279 // out to register width, not all code is compliant. We truncate and
7280 // re-extend to be more forgiving of these callers when the argument type
7281 // is smaller than register width.
7282 if (!ArgVT.isVector() && !ValVT.isVector() && ArgVT.isInteger() &&
7283 ValVT.isInteger() &&
7284 ArgVT.getScalarSizeInBits() < ValVT.getScalarSizeInBits()) {
7285 // It is possible to have either real integer values
7286 // or integers that were not originally integers.
7287 // In the latter case, these could have came from structs,
7288 // and these integers would not have an extend on the parameter.
7289 // Since these types of integers do not have an extend specified
7290 // in the first place, the type of extend that we do should not matter.
7291 EVT TruncatedArgVT = ArgVT.isSimple() && ArgVT.getSimpleVT() == MVT::i1
7292 ? MVT::i8
7293 : ArgVT;
7294 SDValue ArgValueTrunc =
7295 DAG.getNode(ISD::TRUNCATE, dl, TruncatedArgVT, ArgValue);
7296 SDValue ArgValueExt =
7297 ArgSignExt ? DAG.getSExtOrTrunc(ArgValueTrunc, dl, ValVT)
7298 : DAG.getZExtOrTrunc(ArgValueTrunc, dl, ValVT);
7299 InVals.push_back(ArgValueExt);
7300 } else {
7301 InVals.push_back(ArgValue);
7302 }
7303 };
7304
7305 // Vector arguments to VaArg functions are passed both on the stack, and
7306 // in any available GPRs. Load the value from the stack and add the GPRs
7307 // as live ins.
7308 if (VA.isMemLoc() && VA.needsCustom()) {
7309 assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
7310 assert(isVarArg && "Only use custom memloc for vararg.");
7311 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
7312 // matching custom RegLocs.
7313 const unsigned OriginalValNo = VA.getValNo();
7314 (void)OriginalValNo;
7315
7316 auto HandleCustomVecRegLoc = [&]() {
7317 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7318 "Missing custom RegLoc.");
7319 VA = ArgLocs[I++];
7320 assert(VA.getValVT().isVector() &&
7321 "Unexpected Val type for custom RegLoc.");
7322 assert(VA.getValNo() == OriginalValNo &&
7323 "ValNo mismatch between custom MemLoc and RegLoc.");
7325 MF.addLiveIn(VA.getLocReg(),
7326 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7327 Subtarget.hasVSX()));
7328 };
7329
7330 HandleMemLoc();
7331 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7332 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7333 // R10.
7334 HandleCustomVecRegLoc();
7335 HandleCustomVecRegLoc();
7336
7337 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7338 // we passed the vector in R5, R6, R7 and R8.
7339 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7340 assert(!IsPPC64 &&
7341 "Only 2 custom RegLocs expected for 64-bit codegen.");
7342 HandleCustomVecRegLoc();
7343 HandleCustomVecRegLoc();
7344 }
7345
7346 continue;
7347 }
7348
7349 if (VA.isRegLoc()) {
7350 if (VA.getValVT().isScalarInteger())
7352 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7353 switch (VA.getValVT().SimpleTy) {
7354 default:
7355 report_fatal_error("Unhandled value type for argument.");
7356 case MVT::f32:
7358 break;
7359 case MVT::f64:
7361 break;
7362 }
7363 } else if (VA.getValVT().isVector()) {
7364 switch (VA.getValVT().SimpleTy) {
7365 default:
7366 report_fatal_error("Unhandled value type for argument.");
7367 case MVT::v16i8:
7369 break;
7370 case MVT::v8i16:
7372 break;
7373 case MVT::v4i32:
7374 case MVT::v2i64:
7375 case MVT::v1i128:
7377 break;
7378 case MVT::v4f32:
7379 case MVT::v2f64:
7381 break;
7382 }
7383 }
7384 }
7385
7386 if (Flags.isByVal() && VA.isMemLoc()) {
7387 const unsigned Size =
7388 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7389 PtrByteSize);
7390 const int FI = MF.getFrameInfo().CreateFixedObject(
7391 Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7392 /* IsAliased */ true);
7393 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7394 InVals.push_back(FIN);
7395
7396 continue;
7397 }
7398
7399 if (Flags.isByVal()) {
7400 assert(VA.isRegLoc() && "MemLocs should already be handled.");
7401
7402 const MCPhysReg ArgReg = VA.getLocReg();
7403 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7404
7405 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7406 const int FI = MF.getFrameInfo().CreateFixedObject(
7407 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7408 /* IsAliased */ true);
7409 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7410 InVals.push_back(FIN);
7411
7412 // Add live ins for all the RegLocs for the same ByVal.
7413 const TargetRegisterClass *RegClass =
7414 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7415
7416 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7417 unsigned Offset) {
7418 const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7419 // Since the callers side has left justified the aggregate in the
7420 // register, we can simply store the entire register into the stack
7421 // slot.
7422 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7423 // The store to the fixedstack object is needed becuase accessing a
7424 // field of the ByVal will use a gep and load. Ideally we will optimize
7425 // to extracting the value from the register directly, and elide the
7426 // stores when the arguments address is not taken, but that will need to
7427 // be future work.
7428 SDValue Store = DAG.getStore(
7429 CopyFrom.getValue(1), dl, CopyFrom,
7432
7433 MemOps.push_back(Store);
7434 };
7435
7436 unsigned Offset = 0;
7437 HandleRegLoc(VA.getLocReg(), Offset);
7438 Offset += PtrByteSize;
7439 for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7440 Offset += PtrByteSize) {
7441 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7442 "RegLocs should be for ByVal argument.");
7443
7444 const CCValAssign RL = ArgLocs[I++];
7445 HandleRegLoc(RL.getLocReg(), Offset);
7447 }
7448
7449 if (Offset != StackSize) {
7450 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7451 "Expected MemLoc for remaining bytes.");
7452 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7453 // Consume the MemLoc.The InVal has already been emitted, so nothing
7454 // more needs to be done.
7455 ++I;
7456 }
7457
7458 continue;
7459 }
7460
7461 if (VA.isRegLoc() && !VA.needsCustom()) {
7462 MVT::SimpleValueType SVT = ValVT.SimpleTy;
7463 Register VReg =
7464 MF.addLiveIn(VA.getLocReg(),
7465 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7466 Subtarget.hasVSX()));
7467 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7468 if (ValVT.isScalarInteger() &&
7469 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7470 ArgValue =
7471 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7472 }
7473 InVals.push_back(ArgValue);
7474 continue;
7475 }
7476 if (VA.isMemLoc()) {
7477 HandleMemLoc();
7478 continue;
7479 }
7480 }
7481
7482 // On AIX a minimum of 8 words is saved to the parameter save area.
7483 const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7484 // Area that is at least reserved in the caller of this function.
7485 unsigned CallerReservedArea = std::max<unsigned>(
7486 CCInfo.getStackSize(), LinkageSize + MinParameterSaveArea);
7487
7488 // Set the size that is at least reserved in caller of this function. Tail
7489 // call optimized function's reserved stack space needs to be aligned so
7490 // that taking the difference between two stack areas will result in an
7491 // aligned stack.
7492 CallerReservedArea =
7493 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7494 FuncInfo->setMinReservedArea(CallerReservedArea);
7495
7496 if (isVarArg) {
7497 int VAListIndex = 0;
7498 // If any of the optional arguments are passed in register then the fixed
7499 // stack object we spill into is not immutable. Create a fixed stack object
7500 // that overlaps the remainder of the parameter save area.
7501 if (CCInfo.getStackSize() < (LinkageSize + MinParameterSaveArea)) {
7502 unsigned FixedStackSize =
7503 LinkageSize + MinParameterSaveArea - CCInfo.getStackSize();
7504 VAListIndex =
7505 MFI.CreateFixedObject(FixedStackSize, CCInfo.getStackSize(),
7506 /* IsImmutable */ false, /* IsAliased */ true);
7507 } else {
7508 // All the arguments passed through ellipses are on the stack. Create a
7509 // dummy fixed stack object the same size as a pointer since we don't
7510 // know the actual size.
7511 VAListIndex =
7512 MFI.CreateFixedObject(PtrByteSize, CCInfo.getStackSize(),
7513 /* IsImmutable */ true, /* IsAliased */ true);
7514 }
7515
7516 FuncInfo->setVarArgsFrameIndex(VAListIndex);
7517 SDValue FIN = DAG.getFrameIndex(VAListIndex, PtrVT);
7518
7519 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7520 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7521
7522 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7523 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7524 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
7525
7526 // The fixed integer arguments of a variadic function are stored to the
7527 // VarArgsFrameIndex on the stack so that they may be loaded by
7528 // dereferencing the result of va_next.
7529 for (unsigned
7530 GPRIndex = (CCInfo.getStackSize() - LinkageSize) / PtrByteSize,
7531 Offset = 0;
7532 GPRIndex < NumGPArgRegs; ++GPRIndex, Offset += PtrByteSize) {
7533
7534 const Register VReg =
7535 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7536 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7537
7538 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7539 MachinePointerInfo MPI =
7540 MachinePointerInfo::getFixedStack(MF, VAListIndex, Offset);
7541 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MPI);
7542 MemOps.push_back(Store);
7543 // Increment the address for the next argument to store.
7544 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7545 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7546 }
7547 }
7548
7549 if (!MemOps.empty())
7550 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7551
7552 return Chain;
7553}
7554
7555SDValue PPCTargetLowering::LowerCall_AIX(
7556 SDValue Chain, SDValue Callee, CallFlags CFlags,
7558 const SmallVectorImpl<SDValue> &OutVals,
7559 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7561 const CallBase *CB) const {
7562 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7563 // AIX ABI stack frame layout.
7564
7565 assert((CFlags.CallConv == CallingConv::C ||
7566 CFlags.CallConv == CallingConv::Cold ||
7567 CFlags.CallConv == CallingConv::Fast) &&
7568 "Unexpected calling convention!");
7569
7570 if (CFlags.IsPatchPoint)
7571 report_fatal_error("This call type is unimplemented on AIX.");
7572
7573 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7574
7575 MachineFunction &MF = DAG.getMachineFunction();
7577 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7578 *DAG.getContext());
7579
7580 // Reserve space for the linkage save area (LSA) on the stack.
7581 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7582 // [SP][CR][LR][2 x reserved][TOC].
7583 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7584 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7585 const bool IsPPC64 = Subtarget.isPPC64();
7586 const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7587 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7588 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7589 CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7590
7591 // The prolog code of the callee may store up to 8 GPR argument registers to
7592 // the stack, allowing va_start to index over them in memory if the callee
7593 // is variadic.
7594 // Because we cannot tell if this is needed on the caller side, we have to
7595 // conservatively assume that it is needed. As such, make sure we have at
7596 // least enough stack space for the caller to store the 8 GPRs.
7597 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7598 const unsigned NumBytes = std::max<unsigned>(
7599 LinkageSize + MinParameterSaveAreaSize, CCInfo.getStackSize());
7600
7601 // Adjust the stack pointer for the new arguments...
7602 // These operations are automatically eliminated by the prolog/epilog pass.
7603 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7604 SDValue CallSeqStart = Chain;
7605
7607 SmallVector<SDValue, 8> MemOpChains;
7608
7609 // Set up a copy of the stack pointer for loading and storing any
7610 // arguments that may not fit in the registers available for argument
7611 // passing.
7612 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7613 : DAG.getRegister(PPC::R1, MVT::i32);
7614
7615 for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7616 const unsigned ValNo = ArgLocs[I].getValNo();
7617 SDValue Arg = OutVals[ValNo];
7618 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7619
7620 if (Flags.isByVal()) {
7621 const unsigned ByValSize = Flags.getByValSize();
7622
7623 // Nothing to do for zero-sized ByVals on the caller side.
7624 if (!ByValSize) {
7625 ++I;
7626 continue;
7627 }
7628
7629 auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7630 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7631 (LoadOffset != 0)
7632 ? DAG.getObjectPtrOffset(
7633 dl, Arg, TypeSize::getFixed(LoadOffset))
7634 : Arg,
7635 MachinePointerInfo(), VT);
7636 };
7637
7638 unsigned LoadOffset = 0;
7639
7640 // Initialize registers, which are fully occupied by the by-val argument.
7641 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7642 SDValue Load = GetLoad(PtrVT, LoadOffset);
7643 MemOpChains.push_back(Load.getValue(1));
7644 LoadOffset += PtrByteSize;
7645 const CCValAssign &ByValVA = ArgLocs[I++];
7646 assert(ByValVA.getValNo() == ValNo &&
7647 "Unexpected location for pass-by-value argument.");
7648 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7649 }
7650
7651 if (LoadOffset == ByValSize)
7652 continue;
7653
7654 // There must be one more loc to handle the remainder.
7655 assert(ArgLocs[I].getValNo() == ValNo &&
7656 "Expected additional location for by-value argument.");
7657
7658 if (ArgLocs[I].isMemLoc()) {
7659 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7660 const CCValAssign &ByValVA = ArgLocs[I++];
7661 ISD::ArgFlagsTy MemcpyFlags = Flags;
7662 // Only memcpy the bytes that don't pass in register.
7663 MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7664 Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7665 (LoadOffset != 0) ? DAG.getObjectPtrOffset(
7666 dl, Arg, TypeSize::getFixed(LoadOffset))
7667 : Arg,
7669 dl, StackPtr, TypeSize::getFixed(ByValVA.getLocMemOffset())),
7670 CallSeqStart, MemcpyFlags, DAG, dl);
7671 continue;
7672 }
7673
7674 // Initialize the final register residue.
7675 // Any residue that occupies the final by-val arg register must be
7676 // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7677 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7678 // 2 and 1 byte loads.
7679 const unsigned ResidueBytes = ByValSize % PtrByteSize;
7680 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7681 "Unexpected register residue for by-value argument.");
7682 SDValue ResidueVal;
7683 for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7684 const unsigned N = llvm::bit_floor(ResidueBytes - Bytes);
7685 const MVT VT =
7686 N == 1 ? MVT::i8
7687 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7688 SDValue Load = GetLoad(VT, LoadOffset);
7689 MemOpChains.push_back(Load.getValue(1));
7690 LoadOffset += N;
7691 Bytes += N;
7692
7693 // By-val arguments are passed left-justfied in register.
7694 // Every load here needs to be shifted, otherwise a full register load
7695 // should have been used.
7696 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7697 "Unexpected load emitted during handling of pass-by-value "
7698 "argument.");
7699 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7700 EVT ShiftAmountTy =
7701 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7702 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7703 SDValue ShiftedLoad =
7704 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7705 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7706 ShiftedLoad)
7707 : ShiftedLoad;
7708 }
7709
7710 const CCValAssign &ByValVA = ArgLocs[I++];
7711 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7712 continue;
7713 }
7714
7715 CCValAssign &VA = ArgLocs[I++];
7716 const MVT LocVT = VA.getLocVT();
7717 const MVT ValVT = VA.getValVT();
7718
7719 switch (VA.getLocInfo()) {
7720 default:
7721 report_fatal_error("Unexpected argument extension type.");
7722 case CCValAssign::Full:
7723 break;
7724 case CCValAssign::ZExt:
7725 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7726 break;
7727 case CCValAssign::SExt:
7728 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7729 break;
7730 }
7731
7732 if (VA.isRegLoc() && !VA.needsCustom()) {
7733 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7734 continue;
7735 }
7736
7737 // Vector arguments passed to VarArg functions need custom handling when
7738 // they are passed (at least partially) in GPRs.
7739 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7740 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7741 // Store value to its stack slot.
7742 SDValue PtrOff =
7743 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7744 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7745 SDValue Store =
7746 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7747 MemOpChains.push_back(Store);
7748 const unsigned OriginalValNo = VA.getValNo();
7749 // Then load the GPRs from the stack
7750 unsigned LoadOffset = 0;
7751 auto HandleCustomVecRegLoc = [&]() {
7752 assert(I != E && "Unexpected end of CCvalAssigns.");
7753 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7754 "Expected custom RegLoc.");
7755 CCValAssign RegVA = ArgLocs[I++];
7756 assert(RegVA.getValNo() == OriginalValNo &&
7757 "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7758 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7759 DAG.getConstant(LoadOffset, dl, PtrVT));
7760 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7761 MemOpChains.push_back(Load.getValue(1));
7762 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7763 LoadOffset += PtrByteSize;
7764 };
7765
7766 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7767 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7768 // R10.
7769 HandleCustomVecRegLoc();
7770 HandleCustomVecRegLoc();
7771
7772 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7773 ArgLocs[I].getValNo() == OriginalValNo) {
7774 assert(!IsPPC64 &&
7775 "Only 2 custom RegLocs expected for 64-bit codegen.");
7776 HandleCustomVecRegLoc();
7777 HandleCustomVecRegLoc();
7778 }
7779
7780 continue;
7781 }
7782
7783 if (VA.isMemLoc()) {
7784 SDValue PtrOff =
7785 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7786 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7787 MemOpChains.push_back(
7788 DAG.getStore(Chain, dl, Arg, PtrOff,
7790 Subtarget.getFrameLowering()->getStackAlign()));
7791
7792 continue;
7793 }
7794
7795 if (!ValVT.isFloatingPoint())
7797 "Unexpected register handling for calling convention.");
7798
7799 // Custom handling is used for GPR initializations for vararg float
7800 // arguments.
7801 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7802 LocVT.isInteger() &&
7803 "Custom register handling only expected for VarArg.");
7804
7805 SDValue ArgAsInt =
7806 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7807
7808 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7809 // f32 in 32-bit GPR
7810 // f64 in 64-bit GPR
7811 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7812 else if (Arg.getValueType().getFixedSizeInBits() <
7813 LocVT.getFixedSizeInBits())
7814 // f32 in 64-bit GPR.
7815 RegsToPass.push_back(std::make_pair(
7816 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7817 else {
7818 // f64 in two 32-bit GPRs
7819 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7820 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7821 "Unexpected custom register for argument!");
7822 CCValAssign &GPR1 = VA;
7823 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7824 DAG.getConstant(32, dl, MVT::i8));
7825 RegsToPass.push_back(std::make_pair(
7826 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7827
7828 if (I != E) {
7829 // If only 1 GPR was available, there will only be one custom GPR and
7830 // the argument will also pass in memory.
7831 CCValAssign &PeekArg = ArgLocs[I];
7832 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7833 assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7834 CCValAssign &GPR2 = ArgLocs[I++];
7835 RegsToPass.push_back(std::make_pair(
7836 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7837 }
7838 }
7839 }
7840 }
7841
7842 if (!MemOpChains.empty())
7843 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7844
7845 // For indirect calls, we need to save the TOC base to the stack for
7846 // restoration after the call.
7847 if (CFlags.IsIndirect && !Subtarget.usePointerGlueHelper()) {
7848 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7849 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7850 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7851 const MVT PtrVT = Subtarget.getScalarIntVT();
7852 const unsigned TOCSaveOffset =
7853 Subtarget.getFrameLowering()->getTOCSaveOffset();
7854
7855 setUsesTOCBasePtr(DAG);
7856 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7857 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7858 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7859 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7860 Chain = DAG.getStore(
7861 Val.getValue(1), dl, Val, AddPtr,
7862 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7863 }
7864
7865 // Build a sequence of copy-to-reg nodes chained together with token chain
7866 // and flag operands which copy the outgoing args into the appropriate regs.
7867 SDValue InGlue;
7868 for (auto Reg : RegsToPass) {
7869 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InGlue);
7870 InGlue = Chain.getValue(1);
7871 }
7872
7873 const int SPDiff = 0;
7874 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
7875 Callee, SPDiff, NumBytes, Ins, InVals, CB);
7876}
7877
7878bool
7879PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7880 MachineFunction &MF, bool isVarArg,
7883 const Type *RetTy) const {
7885 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7886 return CCInfo.CheckReturn(
7887 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7889 : RetCC_PPC);
7890}
7891
7892SDValue
7893PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7894 bool isVarArg,
7896 const SmallVectorImpl<SDValue> &OutVals,
7897 const SDLoc &dl, SelectionDAG &DAG) const {
7899 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7900 *DAG.getContext());
7901 CCInfo.AnalyzeReturn(Outs,
7902 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7904 : RetCC_PPC);
7905
7906 SDValue Glue;
7907 SmallVector<SDValue, 4> RetOps(1, Chain);
7908
7909 // Copy the result values into the output registers.
7910 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7911 CCValAssign &VA = RVLocs[i];
7912 assert(VA.isRegLoc() && "Can only return in registers!");
7913
7914 SDValue Arg = OutVals[RealResIdx];
7915
7916 switch (VA.getLocInfo()) {
7917 default: llvm_unreachable("Unknown loc info!");
7918 case CCValAssign::Full: break;
7919 case CCValAssign::AExt:
7920 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7921 break;
7922 case CCValAssign::ZExt:
7923 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7924 break;
7925 case CCValAssign::SExt:
7926 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7927 break;
7928 }
7929 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7930 bool isLittleEndian = Subtarget.isLittleEndian();
7931 // Legalize ret f64 -> ret 2 x i32.
7932 SDValue SVal =
7933 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7934 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7935 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7936 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7937 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7938 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7939 Glue = Chain.getValue(1);
7940 VA = RVLocs[++i]; // skip ahead to next loc
7941 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7942 } else
7943 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
7944 Glue = Chain.getValue(1);
7945 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7946 }
7947
7948 RetOps[0] = Chain; // Update chain.
7949
7950 // Add the glue if we have it.
7951 if (Glue.getNode())
7952 RetOps.push_back(Glue);
7953
7954 return DAG.getNode(PPCISD::RET_GLUE, dl, MVT::Other, RetOps);
7955}
7956
7957SDValue
7958PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7959 SelectionDAG &DAG) const {
7960 SDLoc dl(Op);
7961
7962 // Get the correct type for integers.
7963 EVT IntVT = Op.getValueType();
7964
7965 // Get the inputs.
7966 SDValue Chain = Op.getOperand(0);
7967 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7968 // Build a DYNAREAOFFSET node.
7969 SDValue Ops[2] = {Chain, FPSIdx};
7970 SDVTList VTs = DAG.getVTList(IntVT);
7971 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7972}
7973
7974SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7975 SelectionDAG &DAG) const {
7976 // When we pop the dynamic allocation we need to restore the SP link.
7977 SDLoc dl(Op);
7978
7979 // Get the correct type for pointers.
7980 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7981
7982 // Construct the stack pointer operand.
7983 bool isPPC64 = Subtarget.isPPC64();
7984 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7985 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7986
7987 // Get the operands for the STACKRESTORE.
7988 SDValue Chain = Op.getOperand(0);
7989 SDValue SaveSP = Op.getOperand(1);
7990
7991 // Load the old link SP.
7992 SDValue LoadLinkSP =
7993 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7994
7995 // Restore the stack pointer.
7996 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7997
7998 // Store the old link SP.
7999 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
8000}
8001
8002SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
8003 MachineFunction &MF = DAG.getMachineFunction();
8004 bool isPPC64 = Subtarget.isPPC64();
8005 EVT PtrVT = getPointerTy(MF.getDataLayout());
8006
8007 // Get current frame pointer save index. The users of this index will be
8008 // primarily DYNALLOC instructions.
8009 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8010 int RASI = FI->getReturnAddrSaveIndex();
8011
8012 // If the frame pointer save index hasn't been defined yet.
8013 if (!RASI) {
8014 // Find out what the fix offset of the frame pointer save area.
8015 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
8016 // Allocate the frame index for frame pointer save area.
8017 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
8018 // Save the result.
8019 FI->setReturnAddrSaveIndex(RASI);
8020 }
8021 return DAG.getFrameIndex(RASI, PtrVT);
8022}
8023
8024SDValue
8025PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
8026 MachineFunction &MF = DAG.getMachineFunction();
8027 bool isPPC64 = Subtarget.isPPC64();
8028 EVT PtrVT = getPointerTy(MF.getDataLayout());
8029
8030 // Get current frame pointer save index. The users of this index will be
8031 // primarily DYNALLOC instructions.
8032 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8033 int FPSI = FI->getFramePointerSaveIndex();
8034
8035 // If the frame pointer save index hasn't been defined yet.
8036 if (!FPSI) {
8037 // Find out what the fix offset of the frame pointer save area.
8038 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
8039 // Allocate the frame index for frame pointer save area.
8040 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
8041 // Save the result.
8042 FI->setFramePointerSaveIndex(FPSI);
8043 }
8044 return DAG.getFrameIndex(FPSI, PtrVT);
8045}
8046
8047SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8048 SelectionDAG &DAG) const {
8049 MachineFunction &MF = DAG.getMachineFunction();
8050 // Get the inputs.
8051 SDValue Chain = Op.getOperand(0);
8052 SDValue Size = Op.getOperand(1);
8053 SDLoc dl(Op);
8054
8055 // Get the correct type for pointers.
8056 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8057 // Negate the size.
8058 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
8059 DAG.getConstant(0, dl, PtrVT), Size);
8060 // Construct a node for the frame pointer save index.
8061 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
8062 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
8063 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
8064 if (hasInlineStackProbe(MF))
8065 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
8066 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
8067}
8068
8069SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
8070 SelectionDAG &DAG) const {
8071 MachineFunction &MF = DAG.getMachineFunction();
8072
8073 bool isPPC64 = Subtarget.isPPC64();
8074 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8075
8076 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
8077 return DAG.getFrameIndex(FI, PtrVT);
8078}
8079
8080SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
8081 SelectionDAG &DAG) const {
8082 SDLoc DL(Op);
8083 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
8084 DAG.getVTList(MVT::i32, MVT::Other),
8085 Op.getOperand(0), Op.getOperand(1));
8086}
8087
8088SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
8089 SelectionDAG &DAG) const {
8090 SDLoc DL(Op);
8091 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
8092 Op.getOperand(0), Op.getOperand(1));
8093}
8094
8095SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8096 if (Op.getValueType().isVector())
8097 return LowerVectorLoad(Op, DAG);
8098
8099 assert(Op.getValueType() == MVT::i1 &&
8100 "Custom lowering only for i1 loads");
8101
8102 // First, load 8 bits into 32 bits, then truncate to 1 bit.
8103
8104 SDLoc dl(Op);
8105 LoadSDNode *LD = cast<LoadSDNode>(Op);
8106
8107 SDValue Chain = LD->getChain();
8108 SDValue BasePtr = LD->getBasePtr();
8109 MachineMemOperand *MMO = LD->getMemOperand();
8110
8111 SDValue NewLD =
8112 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8113 BasePtr, MVT::i8, MMO);
8114 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8115
8116 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8117 return DAG.getMergeValues(Ops, dl);
8118}
8119
8120SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8121 if (Op.getOperand(1).getValueType().isVector())
8122 return LowerVectorStore(Op, DAG);
8123
8124 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8125 "Custom lowering only for i1 stores");
8126
8127 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8128
8129 SDLoc dl(Op);
8130 StoreSDNode *ST = cast<StoreSDNode>(Op);
8131
8132 SDValue Chain = ST->getChain();
8133 SDValue BasePtr = ST->getBasePtr();
8134 SDValue Value = ST->getValue();
8135 MachineMemOperand *MMO = ST->getMemOperand();
8136
8138 Value);
8139 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8140}
8141
8142// FIXME: Remove this once the ANDI glue bug is fixed:
8143SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8144 assert(Op.getValueType() == MVT::i1 &&
8145 "Custom lowering only for i1 results");
8146
8147 SDLoc DL(Op);
8148 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8149}
8150
8151SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8152 SelectionDAG &DAG) const {
8153
8154 // Implements a vector truncate that fits in a vector register as a shuffle.
8155 // We want to legalize vector truncates down to where the source fits in
8156 // a vector register (and target is therefore smaller than vector register
8157 // size). At that point legalization will try to custom lower the sub-legal
8158 // result and get here - where we can contain the truncate as a single target
8159 // operation.
8160
8161 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8162 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8163 //
8164 // We will implement it for big-endian ordering as this (where x denotes
8165 // undefined):
8166 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8167 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8168 //
8169 // The same operation in little-endian ordering will be:
8170 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8171 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8172
8173 EVT TrgVT = Op.getValueType();
8174 assert(TrgVT.isVector() && "Vector type expected.");
8175 unsigned TrgNumElts = TrgVT.getVectorNumElements();
8176 EVT EltVT = TrgVT.getVectorElementType();
8177 if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8178 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8180 return SDValue();
8181
8182 SDValue N1 = Op.getOperand(0);
8183 EVT SrcVT = N1.getValueType();
8184 unsigned SrcSize = SrcVT.getSizeInBits();
8185 if (SrcSize > 256 || !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8188 return SDValue();
8189 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8190 return SDValue();
8191
8192 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8193 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8194
8195 SDLoc DL(Op);
8196 SDValue Op1, Op2;
8197 if (SrcSize == 256) {
8198 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8199 EVT SplitVT =
8201 unsigned SplitNumElts = SplitVT.getVectorNumElements();
8202 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8203 DAG.getConstant(0, DL, VecIdxTy));
8204 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8205 DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8206 }
8207 else {
8208 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8209 Op2 = DAG.getUNDEF(WideVT);
8210 }
8211
8212 // First list the elements we want to keep.
8213 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8214 SmallVector<int, 16> ShuffV;
8215 if (Subtarget.isLittleEndian())
8216 for (unsigned i = 0; i < TrgNumElts; ++i)
8217 ShuffV.push_back(i * SizeMult);
8218 else
8219 for (unsigned i = 1; i <= TrgNumElts; ++i)
8220 ShuffV.push_back(i * SizeMult - 1);
8221
8222 // Populate the remaining elements with undefs.
8223 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8224 // ShuffV.push_back(i + WideNumElts);
8225 ShuffV.push_back(WideNumElts + 1);
8226
8227 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8228 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8229 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8230}
8231
8232/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8233/// possible.
8234SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8235 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8236 EVT ResVT = Op.getValueType();
8237 EVT CmpVT = Op.getOperand(0).getValueType();
8238 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8239 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
8240 SDLoc dl(Op);
8241
8242 // Without power9-vector, we don't have native instruction for f128 comparison.
8243 // Following transformation to libcall is needed for setcc:
8244 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
8245 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
8246 SDValue Z = DAG.getSetCC(
8247 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
8248 LHS, RHS, CC);
8249 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
8250 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
8251 }
8252
8253 // Not FP, or using SPE? Not a fsel.
8254 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
8255 Subtarget.hasSPE())
8256 return Op;
8257
8258 SDNodeFlags Flags = Op.getNode()->getFlags();
8259
8260 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
8261 // presence of infinities.
8262 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8263 switch (CC) {
8264 default:
8265 break;
8266 case ISD::SETOGT:
8267 case ISD::SETGT:
8268 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
8269 case ISD::SETOLT:
8270 case ISD::SETLT:
8271 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
8272 }
8273 }
8274
8275 // We might be able to do better than this under some circumstances, but in
8276 // general, fsel-based lowering of select is a finite-math-only optimization.
8277 // For more information, see section F.3 of the 2.06 ISA specification.
8278 // With ISA 3.0
8279 if (!Flags.hasNoInfs() || !Flags.hasNoNaNs() || ResVT == MVT::f128)
8280 return Op;
8281
8282 // If the RHS of the comparison is a 0.0, we don't need to do the
8283 // subtraction at all.
8284 SDValue Sel1;
8286 switch (CC) {
8287 default: break; // SETUO etc aren't handled by fsel.
8288 case ISD::SETNE:
8289 std::swap(TV, FV);
8290 [[fallthrough]];
8291 case ISD::SETEQ:
8292 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8293 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8294 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8295 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8296 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8297 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8298 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8299 case ISD::SETULT:
8300 case ISD::SETLT:
8301 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8302 [[fallthrough]];
8303 case ISD::SETOGE:
8304 case ISD::SETGE:
8305 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8306 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8307 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8308 case ISD::SETUGT:
8309 case ISD::SETGT:
8310 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8311 [[fallthrough]];
8312 case ISD::SETOLE:
8313 case ISD::SETLE:
8314 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8315 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8316 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8317 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8318 }
8319
8320 SDValue Cmp;
8321 switch (CC) {
8322 default: break; // SETUO etc aren't handled by fsel.
8323 case ISD::SETNE:
8324 std::swap(TV, FV);
8325 [[fallthrough]];
8326 case ISD::SETEQ:
8327 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8328 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8329 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8330 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8331 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8332 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8333 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8334 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8335 case ISD::SETULT:
8336 case ISD::SETLT:
8337 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8338 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8339 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8340 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8341 case ISD::SETOGE:
8342 case ISD::SETGE:
8343 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8344 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8345 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8346 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8347 case ISD::SETUGT:
8348 case ISD::SETGT:
8349 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8350 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8351 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8352 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8353 case ISD::SETOLE:
8354 case ISD::SETLE:
8355 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8356 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8357 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8358 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8359 }
8360 return Op;
8361}
8362
8363static unsigned getPPCStrictOpcode(unsigned Opc) {
8364 switch (Opc) {
8365 default:
8366 llvm_unreachable("No strict version of this opcode!");
8367 case PPCISD::FCTIDZ:
8368 return PPCISD::STRICT_FCTIDZ;
8369 case PPCISD::FCTIWZ:
8370 return PPCISD::STRICT_FCTIWZ;
8371 case PPCISD::FCTIDUZ:
8372 return PPCISD::STRICT_FCTIDUZ;
8373 case PPCISD::FCTIWUZ:
8374 return PPCISD::STRICT_FCTIWUZ;
8375 case PPCISD::FCFID:
8376 return PPCISD::STRICT_FCFID;
8377 case PPCISD::FCFIDU:
8378 return PPCISD::STRICT_FCFIDU;
8379 case PPCISD::FCFIDS:
8380 return PPCISD::STRICT_FCFIDS;
8381 case PPCISD::FCFIDUS:
8382 return PPCISD::STRICT_FCFIDUS;
8383 }
8384}
8385
8387 const PPCSubtarget &Subtarget) {
8388 SDLoc dl(Op);
8389 bool IsStrict = Op->isStrictFPOpcode();
8390 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8391 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8392
8393 // TODO: Any other flags to propagate?
8394 SDNodeFlags Flags;
8395 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8396
8397 // For strict nodes, source is the second operand.
8398 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8399 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8400 MVT DestTy = Op.getSimpleValueType();
8401 assert(Src.getValueType().isFloatingPoint() &&
8402 (DestTy == MVT::i8 || DestTy == MVT::i16 || DestTy == MVT::i32 ||
8403 DestTy == MVT::i64) &&
8404 "Invalid FP_TO_INT types");
8405 if (Src.getValueType() == MVT::f32) {
8406 if (IsStrict) {
8407 Src =
8409 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8410 Chain = Src.getValue(1);
8411 } else
8412 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8413 }
8414 if ((DestTy == MVT::i8 || DestTy == MVT::i16) && Subtarget.hasP9Vector())
8415 DestTy = Subtarget.getScalarIntVT();
8416 unsigned Opc = ISD::DELETED_NODE;
8417 switch (DestTy.SimpleTy) {
8418 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8419 case MVT::i32:
8420 Opc = IsSigned ? PPCISD::FCTIWZ
8421 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8422 break;
8423 case MVT::i64:
8424 assert((IsSigned || Subtarget.hasFPCVT()) &&
8425 "i64 FP_TO_UINT is supported only with FPCVT");
8426 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8427 }
8428 EVT ConvTy = Src.getValueType() == MVT::f128 ? MVT::f128 : MVT::f64;
8429 SDValue Conv;
8430 if (IsStrict) {
8432 Conv = DAG.getNode(Opc, dl, DAG.getVTList(ConvTy, MVT::Other), {Chain, Src},
8433 Flags);
8434 } else {
8435 Conv = DAG.getNode(Opc, dl, ConvTy, Src);
8436 }
8437 return Conv;
8438}
8439
8440void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8441 SelectionDAG &DAG,
8442 const SDLoc &dl) const {
8443 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8444 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8445 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8446 bool IsStrict = Op->isStrictFPOpcode();
8447
8448 // Convert the FP value to an int value through memory.
8449 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8450 (IsSigned || Subtarget.hasFPCVT());
8451 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8452 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8453 MachinePointerInfo MPI =
8455
8456 // Emit a store to the stack slot.
8457 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8458 Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8459 if (i32Stack) {
8460 MachineFunction &MF = DAG.getMachineFunction();
8461 Alignment = Align(4);
8462 MachineMemOperand *MMO =
8463 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8464 SDValue Ops[] = { Chain, Tmp, FIPtr };
8465 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8466 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8467 } else
8468 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8469
8470 // Result is a load from the stack slot. If loading 4 bytes, make sure to
8471 // add in a bias on big endian.
8472 if (Op.getValueType() == MVT::i32 && !i32Stack &&
8473 !Subtarget.isLittleEndian()) {
8474 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8475 DAG.getConstant(4, dl, FIPtr.getValueType()));
8476 MPI = MPI.getWithOffset(4);
8477 }
8478
8479 RLI.Chain = Chain;
8480 RLI.Ptr = FIPtr;
8481 RLI.MPI = MPI;
8482 RLI.Alignment = Alignment;
8483}
8484
8485/// Custom lowers floating point to integer conversions to use
8486/// the direct move instructions available in ISA 2.07 to avoid the
8487/// need for load/store combinations.
8488SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8489 SelectionDAG &DAG,
8490 const SDLoc &dl) const {
8491 SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8492 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8493 if (Op->isStrictFPOpcode())
8494 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8495 else
8496 return Mov;
8497}
8498
8499SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8500 const SDLoc &dl) const {
8501 bool IsStrict = Op->isStrictFPOpcode();
8502 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8503 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8504 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8505 EVT SrcVT = Src.getValueType();
8506 EVT DstVT = Op.getValueType();
8507
8508 // FP to INT conversions are legal for f128.
8509 if (SrcVT == MVT::f128)
8510 return Subtarget.hasP9Vector() ? Op : SDValue();
8511
8512 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8513 // PPC (the libcall is not available).
8514 if (SrcVT == MVT::ppcf128) {
8515 if (DstVT == MVT::i32) {
8516 // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8517 // set other fast-math flags to FP operations in both strict and
8518 // non-strict cases. (FP_TO_SINT, FSUB)
8519 SDNodeFlags Flags;
8520 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8521
8522 if (IsSigned) {
8523 SDValue Lo, Hi;
8524 std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::f64, MVT::f64);
8525
8526 // Add the two halves of the long double in round-to-zero mode, and use
8527 // a smaller FP_TO_SINT.
8528 if (IsStrict) {
8529 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8530 DAG.getVTList(MVT::f64, MVT::Other),
8531 {Op.getOperand(0), Lo, Hi}, Flags);
8532 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8533 DAG.getVTList(MVT::i32, MVT::Other),
8534 {Res.getValue(1), Res}, Flags);
8535 } else {
8536 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8537 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8538 }
8539 } else {
8540 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8541 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8542 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8543 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8544 if (IsStrict) {
8545 // Sel = Src < 0x80000000
8546 // FltOfs = select Sel, 0.0, 0x80000000
8547 // IntOfs = select Sel, 0, 0x80000000
8548 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8549 SDValue Chain = Op.getOperand(0);
8550 EVT SetCCVT =
8551 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8552 EVT DstSetCCVT =
8553 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8554 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8555 Chain, true);
8556 Chain = Sel.getValue(1);
8557
8558 SDValue FltOfs = DAG.getSelect(
8559 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8560 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8561
8562 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8563 DAG.getVTList(SrcVT, MVT::Other),
8564 {Chain, Src, FltOfs}, Flags);
8565 Chain = Val.getValue(1);
8566 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8567 DAG.getVTList(DstVT, MVT::Other),
8568 {Chain, Val}, Flags);
8569 Chain = SInt.getValue(1);
8570 SDValue IntOfs = DAG.getSelect(
8571 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8572 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8573 return DAG.getMergeValues({Result, Chain}, dl);
8574 } else {
8575 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8576 // FIXME: generated code sucks.
8577 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8578 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8579 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8580 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8581 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8582 }
8583 }
8584 }
8585
8586 return SDValue();
8587 }
8588
8589 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8590 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8591
8592 ReuseLoadInfo RLI;
8593 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8594
8595 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8596 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8597}
8598
8599// We're trying to insert a regular store, S, and then a load, L. If the
8600// incoming value, O, is a load, we might just be able to have our load use the
8601// address used by O. However, we don't know if anything else will store to
8602// that address before we can load from it. To prevent this situation, we need
8603// to insert our load, L, into the chain as a peer of O. To do this, we give L
8604// the same chain operand as O, we create a token factor from the chain results
8605// of O and L, and we replace all uses of O's chain result with that token
8606// factor (this last part is handled by makeEquivalentMemoryOrdering).
8607bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8608 ReuseLoadInfo &RLI,
8609 SelectionDAG &DAG,
8610 ISD::LoadExtType ET) const {
8611 // Conservatively skip reusing for constrained FP nodes.
8612 if (Op->isStrictFPOpcode())
8613 return false;
8614
8615 SDLoc dl(Op);
8616 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8617 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8618 if (ET == ISD::NON_EXTLOAD &&
8619 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8620 isOperationLegalOrCustom(Op.getOpcode(),
8621 Op.getOperand(0).getValueType())) {
8622
8623 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8624 return true;
8625 }
8626
8627 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8628 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8629 LD->isNonTemporal())
8630 return false;
8631 if (LD->getMemoryVT() != MemVT)
8632 return false;
8633
8634 // If the result of the load is an illegal type, then we can't build a
8635 // valid chain for reuse since the legalised loads and token factor node that
8636 // ties the legalised loads together uses a different output chain then the
8637 // illegal load.
8638 if (!isTypeLegal(LD->getValueType(0)))
8639 return false;
8640
8641 RLI.Ptr = LD->getBasePtr();
8642 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8643 assert(LD->getAddressingMode() == ISD::PRE_INC &&
8644 "Non-pre-inc AM on PPC?");
8645 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8646 LD->getOffset());
8647 }
8648
8649 RLI.Chain = LD->getChain();
8650 RLI.MPI = LD->getPointerInfo();
8651 RLI.IsDereferenceable = LD->isDereferenceable();
8652 RLI.IsInvariant = LD->isInvariant();
8653 RLI.Alignment = LD->getAlign();
8654 RLI.AAInfo = LD->getAAInfo();
8655 RLI.Ranges = LD->getRanges();
8656
8657 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8658 return true;
8659}
8660
8661/// Analyze profitability of direct move
8662/// prefer float load to int load plus direct move
8663/// when there is no integer use of int load
8664bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8665 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode();
8666 if (Origin->getOpcode() != ISD::LOAD)
8667 return true;
8668
8669 // If there is no LXSIBZX/LXSIHZX, like Power8,
8670 // prefer direct move if the memory size is 1 or 2 bytes.
8671 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8672 if (!Subtarget.hasP9Vector() &&
8673 (!MMO->getSize().hasValue() || MMO->getSize().getValue() <= 2))
8674 return true;
8675
8676 for (SDUse &Use : Origin->uses()) {
8677
8678 // Only look at the users of the loaded value.
8679 if (Use.getResNo() != 0)
8680 continue;
8681
8682 SDNode *User = Use.getUser();
8683 if (User->getOpcode() != ISD::SINT_TO_FP &&
8684 User->getOpcode() != ISD::UINT_TO_FP &&
8685 User->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8686 User->getOpcode() != ISD::STRICT_UINT_TO_FP)
8687 return true;
8688 }
8689
8690 return false;
8691}
8692
8694 const PPCSubtarget &Subtarget,
8695 SDValue Chain = SDValue()) {
8696 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8697 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8698 SDLoc dl(Op);
8699
8700 // TODO: Any other flags to propagate?
8701 SDNodeFlags Flags;
8702 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8703
8704 // If we have FCFIDS, then use it when converting to single-precision.
8705 // Otherwise, convert to double-precision and then round.
8706 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8707 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8708 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8709 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8710 if (Op->isStrictFPOpcode()) {
8711 if (!Chain)
8712 Chain = Op.getOperand(0);
8713 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8714 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8715 } else
8716 return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8717}
8718
8719/// Custom lowers integer to floating point conversions to use
8720/// the direct move instructions available in ISA 2.07 to avoid the
8721/// need for load/store combinations.
8722SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8723 SelectionDAG &DAG,
8724 const SDLoc &dl) const {
8725 assert((Op.getValueType() == MVT::f32 ||
8726 Op.getValueType() == MVT::f64) &&
8727 "Invalid floating point type as target of conversion");
8728 assert(Subtarget.hasFPCVT() &&
8729 "Int to FP conversions with direct moves require FPCVT");
8730 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8731 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8732 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8733 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8734 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8735 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8736 return convertIntToFP(Op, Mov, DAG, Subtarget);
8737}
8738
8739static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8740
8741 EVT VecVT = Vec.getValueType();
8742 assert(VecVT.isVector() && "Expected a vector type.");
8743 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8744
8745 EVT EltVT = VecVT.getVectorElementType();
8746 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8747 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8748
8749 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8750 SmallVector<SDValue, 16> Ops(NumConcat);
8751 Ops[0] = Vec;
8752 SDValue UndefVec = DAG.getUNDEF(VecVT);
8753 for (unsigned i = 1; i < NumConcat; ++i)
8754 Ops[i] = UndefVec;
8755
8756 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8757}
8758
8759SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8760 const SDLoc &dl) const {
8761 bool IsStrict = Op->isStrictFPOpcode();
8762 unsigned Opc = Op.getOpcode();
8763 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8766 "Unexpected conversion type");
8767 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8768 "Supports conversions to v2f64/v4f32 only.");
8769
8770 // TODO: Any other flags to propagate?
8771 SDNodeFlags Flags;
8772 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8773
8774 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8775 bool FourEltRes = Op.getValueType() == MVT::v4f32;
8776
8777 SDValue Wide = widenVec(DAG, Src, dl);
8778 EVT WideVT = Wide.getValueType();
8779 unsigned WideNumElts = WideVT.getVectorNumElements();
8780 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8781
8782 SmallVector<int, 16> ShuffV;
8783 for (unsigned i = 0; i < WideNumElts; ++i)
8784 ShuffV.push_back(i + WideNumElts);
8785
8786 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8787 int SaveElts = FourEltRes ? 4 : 2;
8788 if (Subtarget.isLittleEndian())
8789 for (int i = 0; i < SaveElts; i++)
8790 ShuffV[i * Stride] = i;
8791 else
8792 for (int i = 1; i <= SaveElts; i++)
8793 ShuffV[i * Stride - 1] = i - 1;
8794
8795 SDValue ShuffleSrc2 =
8796 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8797 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8798
8799 SDValue Extend;
8800 if (SignedConv) {
8801 Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8802 EVT ExtVT = Src.getValueType();
8803 if (Subtarget.hasP9Altivec())
8804 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8805 IntermediateVT.getVectorNumElements());
8806
8807 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8808 DAG.getValueType(ExtVT));
8809 } else
8810 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8811
8812 if (IsStrict)
8813 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8814 {Op.getOperand(0), Extend}, Flags);
8815
8816 return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8817}
8818
8819SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8820 SelectionDAG &DAG) const {
8821 SDLoc dl(Op);
8822 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8823 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8824 bool IsStrict = Op->isStrictFPOpcode();
8825 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8826 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8827
8828 // TODO: Any other flags to propagate?
8829 SDNodeFlags Flags;
8830 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8831
8832 EVT InVT = Src.getValueType();
8833 EVT OutVT = Op.getValueType();
8834 if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8835 isOperationCustom(Op.getOpcode(), InVT))
8836 return LowerINT_TO_FPVector(Op, DAG, dl);
8837
8838 // Conversions to f128 are legal.
8839 if (Op.getValueType() == MVT::f128)
8840 return Subtarget.hasP9Vector() ? Op : SDValue();
8841
8842 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8843 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8844 return SDValue();
8845
8846 if (Src.getValueType() == MVT::i1) {
8847 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8848 DAG.getConstantFP(1.0, dl, Op.getValueType()),
8849 DAG.getConstantFP(0.0, dl, Op.getValueType()));
8850 if (IsStrict)
8851 return DAG.getMergeValues({Sel, Chain}, dl);
8852 else
8853 return Sel;
8854 }
8855
8856 // If we have direct moves, we can do all the conversion, skip the store/load
8857 // however, without FPCVT we can't do most conversions.
8858 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8859 Subtarget.isPPC64() && Subtarget.hasFPCVT())
8860 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8861
8862 assert((IsSigned || Subtarget.hasFPCVT()) &&
8863 "UINT_TO_FP is supported only with FPCVT");
8864
8865 if (Src.getValueType() == MVT::i64) {
8866 SDValue SINT = Src;
8867 // When converting to single-precision, we actually need to convert
8868 // to double-precision first and then round to single-precision.
8869 // To avoid double-rounding effects during that operation, we have
8870 // to prepare the input operand. Bits that might be truncated when
8871 // converting to double-precision are replaced by a bit that won't
8872 // be lost at this stage, but is below the single-precision rounding
8873 // position.
8874 //
8875 // However, if afn is in effect, accept double
8876 // rounding to avoid the extra overhead.
8877 // FIXME: Currently INT_TO_FP can't support fast math flags because
8878 // of nneg flag, thus Op->getFlags().hasApproximateFuncs() is always
8879 // false.
8880 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT() &&
8881 !Op->getFlags().hasApproximateFuncs()) {
8882
8883 // Twiddle input to make sure the low 11 bits are zero. (If this
8884 // is the case, we are guaranteed the value will fit into the 53 bit
8885 // mantissa of an IEEE double-precision value without rounding.)
8886 // If any of those low 11 bits were not zero originally, make sure
8887 // bit 12 (value 2048) is set instead, so that the final rounding
8888 // to single-precision gets the correct result.
8889 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8890 SINT, DAG.getConstant(2047, dl, MVT::i64));
8891 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8892 Round, DAG.getConstant(2047, dl, MVT::i64));
8893 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8894 Round = DAG.getNode(ISD::AND, dl, MVT::i64, Round,
8895 DAG.getSignedConstant(-2048, dl, MVT::i64));
8896
8897 // However, we cannot use that value unconditionally: if the magnitude
8898 // of the input value is small, the bit-twiddling we did above might
8899 // end up visibly changing the output. Fortunately, in that case, we
8900 // don't need to twiddle bits since the original input will convert
8901 // exactly to double-precision floating-point already. Therefore,
8902 // construct a conditional to use the original value if the top 11
8903 // bits are all sign-bit copies, and use the rounded value computed
8904 // above otherwise.
8905 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8906 SINT, DAG.getConstant(53, dl, MVT::i32));
8907 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8908 Cond, DAG.getConstant(1, dl, MVT::i64));
8909 Cond = DAG.getSetCC(
8910 dl,
8911 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8912 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8913
8914 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8915 }
8916
8917 ReuseLoadInfo RLI;
8918 SDValue Bits;
8919
8920 MachineFunction &MF = DAG.getMachineFunction();
8921 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8922 // Drop range metadata, as this metadata becomes invalid for f64 bit
8923 // reinterpretation of i64 values.
8924 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8925 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, nullptr);
8926 if (RLI.ResChain)
8927 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8928 } else if (Subtarget.hasLFIWAX() &&
8929 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8930 MachineMemOperand *MMO =
8932 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8933 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8934 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8935 DAG.getVTList(MVT::f64, MVT::Other),
8936 Ops, MVT::i32, MMO);
8937 if (RLI.ResChain)
8938 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8939 } else if (Subtarget.hasFPCVT() &&
8940 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8941 MachineMemOperand *MMO =
8943 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8944 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8945 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8946 DAG.getVTList(MVT::f64, MVT::Other),
8947 Ops, MVT::i32, MMO);
8948 if (RLI.ResChain)
8949 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8950 } else if (((Subtarget.hasLFIWAX() &&
8951 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8952 (Subtarget.hasFPCVT() &&
8953 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8954 SINT.getOperand(0).getValueType() == MVT::i32) {
8955 MachineFrameInfo &MFI = MF.getFrameInfo();
8956 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8957
8958 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8959 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8960
8961 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8963 DAG.getMachineFunction(), FrameIdx));
8964 Chain = Store;
8965
8966 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8967 "Expected an i32 store");
8968
8969 RLI.Ptr = FIdx;
8970 RLI.Chain = Chain;
8971 RLI.MPI =
8973 RLI.Alignment = Align(4);
8974
8975 MachineMemOperand *MMO =
8977 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8978 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8980 PPCISD::LFIWZX : PPCISD::LFIWAX,
8981 dl, DAG.getVTList(MVT::f64, MVT::Other),
8982 Ops, MVT::i32, MMO);
8983 Chain = Bits.getValue(1);
8984 } else
8985 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8986
8987 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8988 if (IsStrict)
8989 Chain = FP.getValue(1);
8990
8991 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8992 if (IsStrict)
8993 FP = DAG.getNode(
8994 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
8995 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)},
8996 Flags);
8997 else
8998 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8999 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
9000 }
9001 return FP;
9002 }
9003
9004 assert(Src.getValueType() == MVT::i32 &&
9005 "Unhandled INT_TO_FP type in custom expander!");
9006 // Since we only generate this in 64-bit mode, we can take advantage of
9007 // 64-bit registers. In particular, sign extend the input value into the
9008 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
9009 // then lfd it and fcfid it.
9010 MachineFunction &MF = DAG.getMachineFunction();
9011 MachineFrameInfo &MFI = MF.getFrameInfo();
9012 EVT PtrVT = getPointerTy(MF.getDataLayout());
9013
9014 SDValue Ld;
9015 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
9016 ReuseLoadInfo RLI;
9017 bool ReusingLoad;
9018 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
9019 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
9020 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9021
9022 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
9024 DAG.getMachineFunction(), FrameIdx));
9025 Chain = Store;
9026
9027 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
9028 "Expected an i32 store");
9029
9030 RLI.Ptr = FIdx;
9031 RLI.Chain = Chain;
9032 RLI.MPI =
9034 RLI.Alignment = Align(4);
9035 }
9036
9037 MachineMemOperand *MMO =
9039 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
9040 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
9041 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
9042 DAG.getVTList(MVT::f64, MVT::Other), Ops,
9043 MVT::i32, MMO);
9044 Chain = Ld.getValue(1);
9045 if (ReusingLoad && RLI.ResChain) {
9046 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Ld.getValue(1));
9047 }
9048 } else {
9049 assert(Subtarget.isPPC64() &&
9050 "i32->FP without LFIWAX supported only on PPC64");
9051
9052 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
9053 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9054
9055 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
9056
9057 // STD the extended value into the stack slot.
9058 SDValue Store = DAG.getStore(
9059 Chain, dl, Ext64, FIdx,
9061 Chain = Store;
9062
9063 // Load the value as a double.
9064 Ld = DAG.getLoad(
9065 MVT::f64, dl, Chain, FIdx,
9067 Chain = Ld.getValue(1);
9068 }
9069
9070 // FCFID it and return it.
9071 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
9072 if (IsStrict)
9073 Chain = FP.getValue(1);
9074 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9075 if (IsStrict)
9076 FP = DAG.getNode(
9077 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
9078 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)}, Flags);
9079 else
9080 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
9081 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
9082 }
9083 return FP;
9084}
9085
9086SDValue PPCTargetLowering::LowerSET_ROUNDING(SDValue Op,
9087 SelectionDAG &DAG) const {
9088 SDLoc Dl(Op);
9089 MachineFunction &MF = DAG.getMachineFunction();
9090 EVT PtrVT = getPointerTy(MF.getDataLayout());
9091 SDValue Chain = Op.getOperand(0);
9092
9093 // If requested mode is constant, just use simpler mtfsb/mffscrni
9094 if (auto *CVal = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9095 uint64_t Mode = CVal->getZExtValue();
9096 assert(Mode < 4 && "Unsupported rounding mode!");
9097 unsigned InternalRnd = Mode ^ (~(Mode >> 1) & 1);
9098 if (Subtarget.isISA3_0())
9099 return SDValue(
9100 DAG.getMachineNode(
9101 PPC::MFFSCRNI, Dl, {MVT::f64, MVT::Other},
9102 {DAG.getConstant(InternalRnd, Dl, MVT::i32, true), Chain}),
9103 1);
9104 SDNode *SetHi = DAG.getMachineNode(
9105 (InternalRnd & 2) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9106 {DAG.getConstant(30, Dl, MVT::i32, true), Chain});
9107 SDNode *SetLo = DAG.getMachineNode(
9108 (InternalRnd & 1) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9109 {DAG.getConstant(31, Dl, MVT::i32, true), SDValue(SetHi, 0)});
9110 return SDValue(SetLo, 0);
9111 }
9112
9113 // Use x ^ (~(x >> 1) & 1) to transform LLVM rounding mode to Power format.
9114 SDValue One = DAG.getConstant(1, Dl, MVT::i32);
9115 SDValue SrcFlag = DAG.getNode(ISD::AND, Dl, MVT::i32, Op.getOperand(1),
9116 DAG.getConstant(3, Dl, MVT::i32));
9117 SDValue DstFlag = DAG.getNode(
9118 ISD::XOR, Dl, MVT::i32, SrcFlag,
9119 DAG.getNode(ISD::AND, Dl, MVT::i32,
9120 DAG.getNOT(Dl,
9121 DAG.getNode(ISD::SRL, Dl, MVT::i32, SrcFlag, One),
9122 MVT::i32),
9123 One));
9124 // For Power9, there's faster mffscrn, and we don't need to read FPSCR
9125 SDValue MFFS;
9126 if (!Subtarget.isISA3_0()) {
9127 MFFS = DAG.getNode(PPCISD::MFFS, Dl, {MVT::f64, MVT::Other}, Chain);
9128 Chain = MFFS.getValue(1);
9129 }
9130 SDValue NewFPSCR;
9131 if (Subtarget.isPPC64()) {
9132 if (Subtarget.isISA3_0()) {
9133 NewFPSCR = DAG.getAnyExtOrTrunc(DstFlag, Dl, MVT::i64);
9134 } else {
9135 // Set the last two bits (rounding mode) of bitcasted FPSCR.
9136 SDNode *InsertRN = DAG.getMachineNode(
9137 PPC::RLDIMI, Dl, MVT::i64,
9138 {DAG.getNode(ISD::BITCAST, Dl, MVT::i64, MFFS),
9139 DAG.getNode(ISD::ZERO_EXTEND, Dl, MVT::i64, DstFlag),
9140 DAG.getTargetConstant(0, Dl, MVT::i32),
9141 DAG.getTargetConstant(62, Dl, MVT::i32)});
9142 NewFPSCR = SDValue(InsertRN, 0);
9143 }
9144 NewFPSCR = DAG.getNode(ISD::BITCAST, Dl, MVT::f64, NewFPSCR);
9145 } else {
9146 // In 32-bit mode, store f64, load and update the lower half.
9147 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9148 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9149 SDValue Addr = Subtarget.isLittleEndian()
9150 ? StackSlot
9151 : DAG.getNode(ISD::ADD, Dl, PtrVT, StackSlot,
9152 DAG.getConstant(4, Dl, PtrVT));
9153 if (Subtarget.isISA3_0()) {
9154 Chain = DAG.getStore(Chain, Dl, DstFlag, Addr, MachinePointerInfo());
9155 } else {
9156 Chain = DAG.getStore(Chain, Dl, MFFS, StackSlot, MachinePointerInfo());
9157 SDValue Tmp =
9158 DAG.getLoad(MVT::i32, Dl, Chain, Addr, MachinePointerInfo());
9159 Chain = Tmp.getValue(1);
9160 Tmp = SDValue(DAG.getMachineNode(
9161 PPC::RLWIMI, Dl, MVT::i32,
9162 {Tmp, DstFlag, DAG.getTargetConstant(0, Dl, MVT::i32),
9163 DAG.getTargetConstant(30, Dl, MVT::i32),
9164 DAG.getTargetConstant(31, Dl, MVT::i32)}),
9165 0);
9166 Chain = DAG.getStore(Chain, Dl, Tmp, Addr, MachinePointerInfo());
9167 }
9168 NewFPSCR =
9169 DAG.getLoad(MVT::f64, Dl, Chain, StackSlot, MachinePointerInfo());
9170 Chain = NewFPSCR.getValue(1);
9171 }
9172 if (Subtarget.isISA3_0())
9173 return SDValue(DAG.getMachineNode(PPC::MFFSCRN, Dl, {MVT::f64, MVT::Other},
9174 {NewFPSCR, Chain}),
9175 1);
9176 SDValue Zero = DAG.getConstant(0, Dl, MVT::i32, true);
9177 SDNode *MTFSF = DAG.getMachineNode(
9178 PPC::MTFSF, Dl, MVT::Other,
9179 {DAG.getConstant(255, Dl, MVT::i32, true), NewFPSCR, Zero, Zero, Chain});
9180 return SDValue(MTFSF, 0);
9181}
9182
9183SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op,
9184 SelectionDAG &DAG) const {
9185 SDLoc dl(Op);
9186 /*
9187 The rounding mode is in bits 30:31 of FPSR, and has the following
9188 settings:
9189 00 Round to nearest
9190 01 Round to 0
9191 10 Round to +inf
9192 11 Round to -inf
9193
9194 GET_ROUNDING, on the other hand, expects the following:
9195 -1 Undefined
9196 0 Round to 0
9197 1 Round to nearest
9198 2 Round to +inf
9199 3 Round to -inf
9200
9201 To perform the conversion, we do:
9202 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
9203 */
9204
9205 MachineFunction &MF = DAG.getMachineFunction();
9206 EVT VT = Op.getValueType();
9207 EVT PtrVT = getPointerTy(MF.getDataLayout());
9208
9209 // Save FP Control Word to register
9210 SDValue Chain = Op.getOperand(0);
9211 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
9212 Chain = MFFS.getValue(1);
9213
9214 SDValue CWD;
9215 if (isTypeLegal(MVT::i64)) {
9216 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
9217 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
9218 } else {
9219 // Save FP register to stack slot
9220 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9221 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9222 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
9223
9224 // Load FP Control Word from low 32 bits of stack slot.
9226 "Stack slot adjustment is valid only on big endian subtargets!");
9227 SDValue Four = DAG.getConstant(4, dl, PtrVT);
9228 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
9229 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
9230 Chain = CWD.getValue(1);
9231 }
9232
9233 // Transform as necessary
9234 SDValue CWD1 =
9235 DAG.getNode(ISD::AND, dl, MVT::i32,
9236 CWD, DAG.getConstant(3, dl, MVT::i32));
9237 SDValue CWD2 =
9238 DAG.getNode(ISD::SRL, dl, MVT::i32,
9239 DAG.getNode(ISD::AND, dl, MVT::i32,
9240 DAG.getNode(ISD::XOR, dl, MVT::i32,
9241 CWD, DAG.getConstant(3, dl, MVT::i32)),
9242 DAG.getConstant(3, dl, MVT::i32)),
9243 DAG.getConstant(1, dl, MVT::i32));
9244
9245 SDValue RetVal =
9246 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
9247
9248 RetVal =
9250 dl, VT, RetVal);
9251
9252 return DAG.getMergeValues({RetVal, Chain}, dl);
9253}
9254
9255SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9256 EVT VT = Op.getValueType();
9257 uint64_t BitWidth = VT.getSizeInBits();
9258 SDLoc dl(Op);
9259 assert(Op.getNumOperands() == 3 &&
9260 VT == Op.getOperand(1).getValueType() &&
9261 "Unexpected SHL!");
9262
9263 // Expand into a bunch of logical ops. Note that these ops
9264 // depend on the PPC behavior for oversized shift amounts.
9265 SDValue Lo = Op.getOperand(0);
9266 SDValue Hi = Op.getOperand(1);
9267 SDValue Amt = Op.getOperand(2);
9268 EVT AmtVT = Amt.getValueType();
9269
9270 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9271 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9272 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
9273 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
9274 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
9275 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9276 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9277 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
9278 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9279 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
9280 SDValue OutOps[] = { OutLo, OutHi };
9281 return DAG.getMergeValues(OutOps, dl);
9282}
9283
9284SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9285 EVT VT = Op.getValueType();
9286 SDLoc dl(Op);
9287 uint64_t BitWidth = VT.getSizeInBits();
9288 assert(Op.getNumOperands() == 3 &&
9289 VT == Op.getOperand(1).getValueType() &&
9290 "Unexpected SRL!");
9291
9292 // Expand into a bunch of logical ops. Note that these ops
9293 // depend on the PPC behavior for oversized shift amounts.
9294 SDValue Lo = Op.getOperand(0);
9295 SDValue Hi = Op.getOperand(1);
9296 SDValue Amt = Op.getOperand(2);
9297 EVT AmtVT = Amt.getValueType();
9298
9299 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9300 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9301 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9302 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9303 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9304 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9305 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9306 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9307 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9308 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9309 SDValue OutOps[] = { OutLo, OutHi };
9310 return DAG.getMergeValues(OutOps, dl);
9311}
9312
9313SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9314 SDLoc dl(Op);
9315 EVT VT = Op.getValueType();
9316 uint64_t BitWidth = VT.getSizeInBits();
9317 assert(Op.getNumOperands() == 3 &&
9318 VT == Op.getOperand(1).getValueType() &&
9319 "Unexpected SRA!");
9320
9321 // Expand into a bunch of logical ops, followed by a select_cc.
9322 SDValue Lo = Op.getOperand(0);
9323 SDValue Hi = Op.getOperand(1);
9324 SDValue Amt = Op.getOperand(2);
9325 EVT AmtVT = Amt.getValueType();
9326
9327 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9328 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9329 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9330 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9331 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9332 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9333 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9334 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9335 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9336 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9337 Tmp4, Tmp6, ISD::SETLE);
9338 SDValue OutOps[] = { OutLo, OutHi };
9339 return DAG.getMergeValues(OutOps, dl);
9340}
9341
9342SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9343 SelectionDAG &DAG) const {
9344 SDLoc dl(Op);
9345 EVT VT = Op.getValueType();
9346 unsigned BitWidth = VT.getSizeInBits();
9347
9348 bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9349 SDValue X = Op.getOperand(0);
9350 SDValue Y = Op.getOperand(1);
9351 SDValue Z = Op.getOperand(2);
9352 EVT AmtVT = Z.getValueType();
9353
9354 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9355 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9356 // This is simpler than TargetLowering::expandFunnelShift because we can rely
9357 // on PowerPC shift by BW being well defined.
9358 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9359 DAG.getConstant(BitWidth - 1, dl, AmtVT));
9360 SDValue SubZ =
9361 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9362 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9363 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9364 return DAG.getNode(ISD::OR, dl, VT, X, Y);
9365}
9366
9367//===----------------------------------------------------------------------===//
9368// Vector related lowering.
9369//
9370
9371/// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9372/// element size of SplatSize. Cast the result to VT.
9373static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9374 SelectionDAG &DAG, const SDLoc &dl) {
9375 static const MVT VTys[] = { // canonical VT to use for each size.
9376 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9377 };
9378
9379 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9380
9381 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9382 if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
9383 SplatSize = 1;
9384 Val = 0xFF;
9385 }
9386
9387 EVT CanonicalVT = VTys[SplatSize-1];
9388
9389 // Build a canonical splat for this value.
9390 // Explicitly truncate APInt here, as this API is used with a mix of
9391 // signed and unsigned values.
9392 return DAG.getBitcast(
9393 ReqVT,
9394 DAG.getConstant(APInt(64, Val).trunc(SplatSize * 8), dl, CanonicalVT));
9395}
9396
9397/// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9398/// specified intrinsic ID.
9400 const SDLoc &dl, EVT DestVT = MVT::Other) {
9401 if (DestVT == MVT::Other) DestVT = Op.getValueType();
9402 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9403 DAG.getConstant(IID, dl, MVT::i32), Op);
9404}
9405
9406/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9407/// specified intrinsic ID.
9409 SelectionDAG &DAG, const SDLoc &dl,
9410 EVT DestVT = MVT::Other) {
9411 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9412 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9413 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9414}
9415
9416/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9417/// specified intrinsic ID.
9418static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9419 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9420 EVT DestVT = MVT::Other) {
9421 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9422 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9423 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9424}
9425
9426/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9427/// amount. The result has the specified value type.
9428static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9429 SelectionDAG &DAG, const SDLoc &dl) {
9430 // Force LHS/RHS to be the right type.
9431 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9432 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9433
9434 int Ops[16];
9435 for (unsigned i = 0; i != 16; ++i)
9436 Ops[i] = i + Amt;
9437 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9438 return DAG.getNode(ISD::BITCAST, dl, VT, T);
9439}
9440
9441/// Do we have an efficient pattern in a .td file for this node?
9442///
9443/// \param V - pointer to the BuildVectorSDNode being matched
9444/// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9445///
9446/// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9447/// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9448/// the opposite is true (expansion is beneficial) are:
9449/// - The node builds a vector out of integers that are not 32 or 64-bits
9450/// - The node builds a vector out of constants
9451/// - The node is a "load-and-splat"
9452/// In all other cases, we will choose to keep the BUILD_VECTOR.
9454 bool HasDirectMove,
9455 bool HasP8Vector) {
9456 EVT VecVT = V->getValueType(0);
9457 bool RightType = VecVT == MVT::v2f64 ||
9458 (HasP8Vector && VecVT == MVT::v4f32) ||
9459 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9460 if (!RightType)
9461 return false;
9462
9463 bool IsSplat = true;
9464 bool IsLoad = false;
9465 SDValue Op0 = V->getOperand(0);
9466
9467 // This function is called in a block that confirms the node is not a constant
9468 // splat. So a constant BUILD_VECTOR here means the vector is built out of
9469 // different constants.
9470 if (V->isConstant())
9471 return false;
9472 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9473 if (V->getOperand(i).isUndef())
9474 return false;
9475 // We want to expand nodes that represent load-and-splat even if the
9476 // loaded value is a floating point truncation or conversion to int.
9477 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9478 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9479 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9480 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9481 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9482 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9483 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9484 IsLoad = true;
9485 // If the operands are different or the input is not a load and has more
9486 // uses than just this BV node, then it isn't a splat.
9487 if (V->getOperand(i) != Op0 ||
9488 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9489 IsSplat = false;
9490 }
9491 return !(IsSplat && IsLoad);
9492}
9493
9494// Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9495SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9496
9497 SDLoc dl(Op);
9498 SDValue Op0 = Op->getOperand(0);
9499
9500 if (!Subtarget.isPPC64() || (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9501 (Op.getValueType() != MVT::f128))
9502 return SDValue();
9503
9504 SDValue Lo = Op0.getOperand(0);
9505 SDValue Hi = Op0.getOperand(1);
9506 if ((Lo.getValueType() != MVT::i64) || (Hi.getValueType() != MVT::i64))
9507 return SDValue();
9508
9509 if (!Subtarget.isLittleEndian())
9510 std::swap(Lo, Hi);
9511
9512 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Lo, Hi);
9513}
9514
9515static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9516 const SDValue *InputLoad = &Op;
9517 while (InputLoad->getOpcode() == ISD::BITCAST)
9518 InputLoad = &InputLoad->getOperand(0);
9519 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9520 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9521 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9522 InputLoad = &InputLoad->getOperand(0);
9523 }
9524 if (InputLoad->getOpcode() != ISD::LOAD)
9525 return nullptr;
9526 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9527 return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9528}
9529
9530// Convert the argument APFloat to a single precision APFloat if there is no
9531// loss in information during the conversion to single precision APFloat and the
9532// resulting number is not a denormal number. Return true if successful.
9534 APFloat APFloatToConvert = ArgAPFloat;
9535 bool LosesInfo = true;
9537 &LosesInfo);
9538 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9539 if (Success)
9540 ArgAPFloat = APFloatToConvert;
9541 return Success;
9542}
9543
9544// Bitcast the argument APInt to a double and convert it to a single precision
9545// APFloat, bitcast the APFloat to an APInt and assign it to the original
9546// argument if there is no loss in information during the conversion from
9547// double to single precision APFloat and the resulting number is not a denormal
9548// number. Return true if successful.
9550 double DpValue = ArgAPInt.bitsToDouble();
9551 APFloat APFloatDp(DpValue);
9552 bool Success = convertToNonDenormSingle(APFloatDp);
9553 if (Success)
9554 ArgAPInt = APFloatDp.bitcastToAPInt();
9555 return Success;
9556}
9557
9558// Nondestructive check for convertTonNonDenormSingle.
9560 // Only convert if it loses info, since XXSPLTIDP should
9561 // handle the other case.
9562 APFloat APFloatToConvert = ArgAPFloat;
9563 bool LosesInfo = true;
9565 &LosesInfo);
9566
9567 return (!LosesInfo && !APFloatToConvert.isDenormal());
9568}
9569
9570static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9571 unsigned &Opcode) {
9572 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9573 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9574 return false;
9575
9576 EVT Ty = Op->getValueType(0);
9577 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9578 // as we cannot handle extending loads for these types.
9579 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9580 ISD::isNON_EXTLoad(InputNode))
9581 return true;
9582
9583 EVT MemVT = InputNode->getMemoryVT();
9584 // For v8i16 and v16i8 types, extending loads can be handled as long as the
9585 // memory VT is the same vector element VT type.
9586 // The loads feeding into the v8i16 and v16i8 types will be extending because
9587 // scalar i8/i16 are not legal types.
9588 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9589 (MemVT == Ty.getVectorElementType()))
9590 return true;
9591
9592 if (Ty == MVT::v2i64) {
9593 // Check the extend type, when the input type is i32, and the output vector
9594 // type is v2i64.
9595 if (MemVT == MVT::i32) {
9596 if (ISD::isZEXTLoad(InputNode))
9597 Opcode = PPCISD::ZEXT_LD_SPLAT;
9598 if (ISD::isSEXTLoad(InputNode))
9599 Opcode = PPCISD::SEXT_LD_SPLAT;
9600 }
9601 return true;
9602 }
9603 return false;
9604}
9605
9607 bool IsLittleEndian) {
9608 assert(BVN.getNumOperands() > 0 && "Unexpected 0-size build vector");
9609
9610 BitMask.clearAllBits();
9611 EVT VT = BVN.getValueType(0);
9612 unsigned VTSize = VT.getSizeInBits();
9613 APInt ConstValue(VTSize, 0);
9614
9615 unsigned EltWidth = VT.getScalarSizeInBits();
9616
9617 unsigned BitPos = 0;
9618 for (auto OpVal : BVN.op_values()) {
9619 auto *CN = dyn_cast<ConstantSDNode>(OpVal);
9620
9621 if (!CN)
9622 return false;
9623 // The elements in a vector register are ordered in reverse byte order
9624 // between little-endian and big-endian modes.
9625 ConstValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth),
9626 IsLittleEndian ? BitPos : VTSize - EltWidth - BitPos);
9627 BitPos += EltWidth;
9628 }
9629
9630 for (unsigned J = 0; J < 16; ++J) {
9631 APInt ExtractValue = ConstValue.extractBits(8, J * 8);
9632 if (ExtractValue != 0x00 && ExtractValue != 0xFF)
9633 return false;
9634 if (ExtractValue == 0xFF)
9635 BitMask.setBit(J);
9636 }
9637 return true;
9638}
9639
9640// If this is a case we can't handle, return null and let the default
9641// expansion code take care of it. If we CAN select this case, and if it
9642// selects to a single instruction, return Op. Otherwise, if we can codegen
9643// this case more efficiently than a constant pool load, lower it to the
9644// sequence of ops that should be used.
9645SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9646 SelectionDAG &DAG) const {
9647 SDLoc dl(Op);
9648 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9649 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9650
9651 if (Subtarget.hasP10Vector()) {
9652 APInt BitMask(32, 0);
9653 // If the value of the vector is all zeros or all ones,
9654 // we do not convert it to MTVSRBMI.
9655 // The xxleqv instruction sets a vector with all ones.
9656 // The xxlxor instruction sets a vector with all zeros.
9657 if (isValidMtVsrBmi(BitMask, *BVN, Subtarget.isLittleEndian()) &&
9658 BitMask != 0 && BitMask != 0xffff) {
9659 SDValue SDConstant = DAG.getTargetConstant(BitMask, dl, MVT::i32);
9660 MachineSDNode *MSDNode =
9661 DAG.getMachineNode(PPC::MTVSRBMI, dl, MVT::v16i8, SDConstant);
9662 SDValue SDV = SDValue(MSDNode, 0);
9663 EVT DVT = BVN->getValueType(0);
9664 EVT SVT = SDV.getValueType();
9665 if (SVT != DVT) {
9666 SDV = DAG.getNode(ISD::BITCAST, dl, DVT, SDV);
9667 }
9668 return SDV;
9669 }
9670 // Recognize build vector patterns to emit VSX vector instructions
9671 // instead of loading value from memory.
9672 if (SDValue VecPat = combineBVLoadsSpecialValue(Op, DAG))
9673 return VecPat;
9674 }
9675 // Check if this is a splat of a constant value.
9676 APInt APSplatBits, APSplatUndef;
9677 unsigned SplatBitSize = 0;
9678 bool HasAnyUndefs;
9679 bool BVNIsConstantSplat =
9680 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9681 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9682
9683 // If it is a splat of a double, check if we can shrink it to a 32 bit
9684 // non-denormal float which when converted back to double gives us the same
9685 // double. This is to exploit the XXSPLTIDP instruction.
9686 // If we lose precision, we use XXSPLTI32DX.
9687 if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9688 Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
9689 // Check the type first to short-circuit so we don't modify APSplatBits if
9690 // this block isn't executed.
9691 if ((Op->getValueType(0) == MVT::v2f64) &&
9692 convertToNonDenormSingle(APSplatBits)) {
9693 SDValue SplatNode = DAG.getNode(
9694 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9695 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9696 return DAG.getBitcast(Op.getValueType(), SplatNode);
9697 } else {
9698 // We may lose precision, so we have to use XXSPLTI32DX.
9699
9700 uint32_t Hi = Hi_32(APSplatBits.getZExtValue());
9701 uint32_t Lo = Lo_32(APSplatBits.getZExtValue());
9702 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9703
9704 if (!Hi || !Lo)
9705 // If either load is 0, then we should generate XXLXOR to set to 0.
9706 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9707
9708 if (Hi)
9709 SplatNode = DAG.getNode(
9710 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9711 DAG.getTargetConstant(0, dl, MVT::i32),
9712 DAG.getTargetConstant(Hi, dl, MVT::i32));
9713
9714 if (Lo)
9715 SplatNode =
9716 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9717 DAG.getTargetConstant(1, dl, MVT::i32),
9718 DAG.getTargetConstant(Lo, dl, MVT::i32));
9719
9720 return DAG.getBitcast(Op.getValueType(), SplatNode);
9721 }
9722 }
9723
9724 if (SDValue V =
9725 LowerVecSplatSmallFP(Op, DAG, BVNIsConstantSplat, SplatBitSize))
9726 return V;
9727
9728 bool IsSplat64 = false;
9729 uint64_t SplatBits = 0;
9730 int32_t SextVal = 0;
9731 if (BVNIsConstantSplat && SplatBitSize <= 64) {
9732 SplatBits = APSplatBits.getZExtValue();
9733 if (SplatBitSize <= 32) {
9734 SextVal = SignExtend32(SplatBits, SplatBitSize);
9735 } else if (SplatBitSize == 64 && Subtarget.hasP8Altivec()) {
9736 int64_t Splat64Val = static_cast<int64_t>(SplatBits);
9737 bool P9Vector = Subtarget.hasP9Vector();
9738 int32_t Hi = P9Vector ? 127 : 15;
9739 int32_t Lo = P9Vector ? -128 : -16;
9740 IsSplat64 = Splat64Val >= Lo && Splat64Val <= Hi;
9741 SextVal = static_cast<int32_t>(SplatBits);
9742 }
9743 }
9744
9745 if (!BVNIsConstantSplat || (SplatBitSize > 32 && !IsSplat64)) {
9746 unsigned NewOpcode = PPCISD::LD_SPLAT;
9747
9748 // Handle load-and-splat patterns as we have instructions that will do this
9749 // in one go.
9750 if (DAG.isSplatValue(Op, true) &&
9751 isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9752 const SDValue *InputLoad = &Op.getOperand(0);
9753 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9754
9755 // If the input load is an extending load, it will be an i32 -> i64
9756 // extending load and isValidSplatLoad() will update NewOpcode.
9757 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9758 unsigned ElementSize =
9759 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9760
9761 assert(((ElementSize == 2 * MemorySize)
9762 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9763 NewOpcode == PPCISD::SEXT_LD_SPLAT)
9764 : (NewOpcode == PPCISD::LD_SPLAT)) &&
9765 "Unmatched element size and opcode!\n");
9766
9767 // Checking for a single use of this load, we have to check for vector
9768 // width (128 bits) / ElementSize uses (since each operand of the
9769 // BUILD_VECTOR is a separate use of the value.
9770 unsigned NumUsesOfInputLD = 128 / ElementSize;
9771 for (SDValue BVInOp : Op->ops())
9772 if (BVInOp.isUndef())
9773 NumUsesOfInputLD--;
9774
9775 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9776 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9777 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9778 // 15", but function IsValidSplatLoad() now will only return true when
9779 // the data at index 0 is not nullptr. So we will not get into trouble for
9780 // these cases.
9781 //
9782 // case 1 - lfiwzx/lfiwax
9783 // 1.1: load result is i32 and is sign/zero extend to i64;
9784 // 1.2: build a v2i64 vector type with above loaded value;
9785 // 1.3: the vector has only one value at index 0, others are all undef;
9786 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9787 if (NumUsesOfInputLD == 1 &&
9788 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9789 !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9790 Subtarget.hasLFIWAX()))
9791 return SDValue();
9792
9793 // case 2 - lxvr[hb]x
9794 // 2.1: load result is at most i16;
9795 // 2.2: build a vector with above loaded value;
9796 // 2.3: the vector has only one value at index 0, others are all undef;
9797 // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9798 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9799 Subtarget.isISA3_1() && ElementSize <= 16)
9800 return SDValue();
9801
9802 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9803 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9804 Subtarget.hasVSX()) {
9805 SDValue Ops[] = {
9806 LD->getChain(), // Chain
9807 LD->getBasePtr(), // Ptr
9808 DAG.getValueType(Op.getValueType()) // VT
9809 };
9810 SDValue LdSplt = DAG.getMemIntrinsicNode(
9811 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9812 LD->getMemoryVT(), LD->getMemOperand());
9813 // Replace all uses of the output chain of the original load with the
9814 // output chain of the new load.
9815 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9816 LdSplt.getValue(1));
9817 return LdSplt;
9818 }
9819 }
9820
9821 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9822 // 32-bits can be lowered to VSX instructions under certain conditions.
9823 // Without VSX, there is no pattern more efficient than expanding the node.
9824 if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9825 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9826 Subtarget.hasP8Vector()))
9827 return Op;
9828 return SDValue();
9829 }
9830
9831 uint64_t SplatUndef = APSplatUndef.getZExtValue();
9832 unsigned SplatSize = SplatBitSize / 8;
9833
9834 // First, handle single instruction cases.
9835
9836 // All zeros?
9837 if (SplatBits == 0) {
9838 // Canonicalize all zero vectors to be v4i32.
9839 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9840 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9841 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9842 }
9843 return Op;
9844 }
9845
9846 // We have XXSPLTIW for constant splats four bytes wide.
9847 // Given vector length is a multiple of 4, 2-byte splats can be replaced
9848 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9849 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9850 // turned into a 4-byte splat of 0xABABABAB.
9851 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 2)
9852 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9853 Op.getValueType(), DAG, dl);
9854
9855 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 4)
9856 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9857 dl);
9858
9859 // We have XXSPLTIB for constant splats one byte wide.
9860 if (Subtarget.hasP9Vector() && SplatSize == 1)
9861 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9862 dl);
9863
9864 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9865 // Use VSPLTIW/VUPKLSW for v2i64 in range [-16,15].
9866 if (SextVal >= -16 && SextVal <= 15) {
9867 // SplatSize may be 1, 2, 4, or 8. Use size 4 instead of 8 for the splat to
9868 // generate a splat word with extend for size 8.
9869 unsigned UseSize = SplatSize == 8 ? 4 : SplatSize;
9870 SDValue Res =
9871 getCanonicalConstSplat(SextVal, UseSize, Op.getValueType(), DAG, dl);
9872 if (SplatSize != 8)
9873 return Res;
9874 SDValue IntrinsicOp =
9875 BuildIntrinsicOp(Intrinsic::ppc_altivec_vupklsw,
9876 DAG.getBitcast(MVT::v4i32, Res), DAG, dl, MVT::v2i64);
9877 return DAG.getBitcast(Op.getValueType(), IntrinsicOp);
9878 }
9879
9880 // Two instruction sequences.
9881
9882 if (Subtarget.hasP9Vector() && SextVal >= -128 && SextVal <= 127) {
9883 SDValue C = DAG.getConstant((unsigned char)SextVal, dl, MVT::i32);
9885 SDValue BV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
9886 unsigned IID;
9887 EVT VT;
9888 switch (SplatSize) {
9889 default:
9890 llvm_unreachable("Unexpected type for vector constant.");
9891 case 2:
9892 IID = Intrinsic::ppc_altivec_vupklsb;
9893 VT = MVT::v8i16;
9894 break;
9895 case 4:
9896 IID = Intrinsic::ppc_altivec_vextsb2w;
9897 VT = MVT::v4i32;
9898 break;
9899 case 8:
9900 IID = Intrinsic::ppc_altivec_vextsb2d;
9901 VT = MVT::v2i64;
9902 break;
9903 }
9904 SDValue Extend = BuildIntrinsicOp(IID, BV, DAG, dl, VT);
9905 return DAG.getBitcast(Op->getValueType(0), Extend);
9906 }
9907 assert(!IsSplat64 && "Unhandled 64-bit splat pattern");
9908
9909 // If this value is in the range [-32,30] and is even, use:
9910 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9911 // If this value is in the range [17,31] and is odd, use:
9912 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9913 // If this value is in the range [-31,-17] and is odd, use:
9914 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9915 // Note the last two are three-instruction sequences.
9916 if (SextVal >= -32 && SextVal <= 31) {
9917 // To avoid having these optimizations undone by constant folding,
9918 // we convert to a pseudo that will be expanded later into one of
9919 // the above forms.
9920 SDValue Elt = DAG.getSignedConstant(SextVal, dl, MVT::i32);
9921 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9922 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9923 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9924 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9925 if (VT == Op.getValueType())
9926 return RetVal;
9927 else
9928 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9929 }
9930
9931 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
9932 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
9933 // for fneg/fabs.
9934 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9935 // Make -1 and vspltisw -1:
9936 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9937
9938 // Make the VSLW intrinsic, computing 0x8000_0000.
9939 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9940 OnesV, DAG, dl);
9941
9942 // xor by OnesV to invert it.
9943 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9944 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9945 }
9946
9947 // Check to see if this is a wide variety of vsplti*, binop self cases.
9948 static const signed char SplatCsts[] = {
9949 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9950 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9951 };
9952
9953 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) {
9954 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9955 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
9956 int i = SplatCsts[idx];
9957
9958 // Figure out what shift amount will be used by altivec if shifted by i in
9959 // this splat size.
9960 unsigned TypeShiftAmt = i & (SplatBitSize-1);
9961
9962 // vsplti + shl self.
9963 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9964 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9965 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9966 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9967 Intrinsic::ppc_altivec_vslw
9968 };
9969 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9970 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9971 }
9972
9973 // vsplti + srl self.
9974 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9975 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9976 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9977 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9978 Intrinsic::ppc_altivec_vsrw
9979 };
9980 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9981 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9982 }
9983
9984 // vsplti + rol self.
9985 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9986 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9987 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9988 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9989 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9990 Intrinsic::ppc_altivec_vrlw
9991 };
9992 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9993 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9994 }
9995
9996 // t = vsplti c, result = vsldoi t, t, 1
9997 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9998 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9999 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
10000 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10001 }
10002 // t = vsplti c, result = vsldoi t, t, 2
10003 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
10004 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10005 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
10006 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10007 }
10008 // t = vsplti c, result = vsldoi t, t, 3
10009 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
10010 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10011 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
10012 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10013 }
10014 }
10015
10016 return SDValue();
10017}
10018
10019/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
10020/// the specified operations to build the shuffle.
10022 SDValue RHS, SelectionDAG &DAG,
10023 const SDLoc &dl) {
10024 unsigned OpNum = (PFEntry >> 26) & 0x0F;
10025 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
10026 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
10027
10028 enum {
10029 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
10030 OP_VMRGHW,
10031 OP_VMRGLW,
10032 OP_VSPLTISW0,
10033 OP_VSPLTISW1,
10034 OP_VSPLTISW2,
10035 OP_VSPLTISW3,
10036 OP_VSLDOI4,
10037 OP_VSLDOI8,
10038 OP_VSLDOI12
10039 };
10040
10041 if (OpNum == OP_COPY) {
10042 if (LHSID == (1*9+2)*9+3) return LHS;
10043 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
10044 return RHS;
10045 }
10046
10047 SDValue OpLHS, OpRHS;
10048 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
10049 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
10050
10051 int ShufIdxs[16];
10052 switch (OpNum) {
10053 default: llvm_unreachable("Unknown i32 permute!");
10054 case OP_VMRGHW:
10055 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
10056 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
10057 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
10058 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
10059 break;
10060 case OP_VMRGLW:
10061 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
10062 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
10063 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
10064 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
10065 break;
10066 case OP_VSPLTISW0:
10067 for (unsigned i = 0; i != 16; ++i)
10068 ShufIdxs[i] = (i&3)+0;
10069 break;
10070 case OP_VSPLTISW1:
10071 for (unsigned i = 0; i != 16; ++i)
10072 ShufIdxs[i] = (i&3)+4;
10073 break;
10074 case OP_VSPLTISW2:
10075 for (unsigned i = 0; i != 16; ++i)
10076 ShufIdxs[i] = (i&3)+8;
10077 break;
10078 case OP_VSPLTISW3:
10079 for (unsigned i = 0; i != 16; ++i)
10080 ShufIdxs[i] = (i&3)+12;
10081 break;
10082 case OP_VSLDOI4:
10083 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
10084 case OP_VSLDOI8:
10085 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
10086 case OP_VSLDOI12:
10087 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
10088 }
10089 EVT VT = OpLHS.getValueType();
10090 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
10091 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
10092 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
10093 return DAG.getNode(ISD::BITCAST, dl, VT, T);
10094}
10095
10096/// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
10097/// by the VINSERTB instruction introduced in ISA 3.0, else just return default
10098/// SDValue.
10099SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
10100 SelectionDAG &DAG) const {
10101 const unsigned BytesInVector = 16;
10102 bool IsLE = Subtarget.isLittleEndian();
10103 SDLoc dl(N);
10104 SDValue V1 = N->getOperand(0);
10105 SDValue V2 = N->getOperand(1);
10106 unsigned ShiftElts = 0, InsertAtByte = 0;
10107 bool Swap = false;
10108
10109 // Shifts required to get the byte we want at element 7.
10110 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
10111 0, 15, 14, 13, 12, 11, 10, 9};
10112 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
10113 1, 2, 3, 4, 5, 6, 7, 8};
10114
10115 ArrayRef<int> Mask = N->getMask();
10116 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
10117
10118 // For each mask element, find out if we're just inserting something
10119 // from V2 into V1 or vice versa.
10120 // Possible permutations inserting an element from V2 into V1:
10121 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10122 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10123 // ...
10124 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
10125 // Inserting from V1 into V2 will be similar, except mask range will be
10126 // [16,31].
10127
10128 bool FoundCandidate = false;
10129 // If both vector operands for the shuffle are the same vector, the mask
10130 // will contain only elements from the first one and the second one will be
10131 // undef.
10132 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
10133 // Go through the mask of half-words to find an element that's being moved
10134 // from one vector to the other.
10135 for (unsigned i = 0; i < BytesInVector; ++i) {
10136 unsigned CurrentElement = Mask[i];
10137 // If 2nd operand is undefined, we should only look for element 7 in the
10138 // Mask.
10139 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
10140 continue;
10141
10142 bool OtherElementsInOrder = true;
10143 // Examine the other elements in the Mask to see if they're in original
10144 // order.
10145 for (unsigned j = 0; j < BytesInVector; ++j) {
10146 if (j == i)
10147 continue;
10148 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
10149 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
10150 // in which we always assume we're always picking from the 1st operand.
10151 int MaskOffset =
10152 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
10153 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
10154 OtherElementsInOrder = false;
10155 break;
10156 }
10157 }
10158 // If other elements are in original order, we record the number of shifts
10159 // we need to get the element we want into element 7. Also record which byte
10160 // in the vector we should insert into.
10161 if (OtherElementsInOrder) {
10162 // If 2nd operand is undefined, we assume no shifts and no swapping.
10163 if (V2.isUndef()) {
10164 ShiftElts = 0;
10165 Swap = false;
10166 } else {
10167 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
10168 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
10169 : BigEndianShifts[CurrentElement & 0xF];
10170 Swap = CurrentElement < BytesInVector;
10171 }
10172 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
10173 FoundCandidate = true;
10174 break;
10175 }
10176 }
10177
10178 if (!FoundCandidate)
10179 return SDValue();
10180
10181 // Candidate found, construct the proper SDAG sequence with VINSERTB,
10182 // optionally with VECSHL if shift is required.
10183 if (Swap)
10184 std::swap(V1, V2);
10185 if (V2.isUndef())
10186 V2 = V1;
10187 if (ShiftElts) {
10188 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10189 DAG.getConstant(ShiftElts, dl, MVT::i32));
10190 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
10191 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10192 }
10193 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
10194 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10195}
10196
10197/// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
10198/// by the VINSERTH instruction introduced in ISA 3.0, else just return default
10199/// SDValue.
10200SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
10201 SelectionDAG &DAG) const {
10202 const unsigned NumHalfWords = 8;
10203 const unsigned BytesInVector = NumHalfWords * 2;
10204 // Check that the shuffle is on half-words.
10205 if (!isNByteElemShuffleMask(N, 2, 1))
10206 return SDValue();
10207
10208 bool IsLE = Subtarget.isLittleEndian();
10209 SDLoc dl(N);
10210 SDValue V1 = N->getOperand(0);
10211 SDValue V2 = N->getOperand(1);
10212 unsigned ShiftElts = 0, InsertAtByte = 0;
10213 bool Swap = false;
10214
10215 // Shifts required to get the half-word we want at element 3.
10216 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
10217 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
10218
10219 uint32_t Mask = 0;
10220 uint32_t OriginalOrderLow = 0x1234567;
10221 uint32_t OriginalOrderHigh = 0x89ABCDEF;
10222 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
10223 // 32-bit space, only need 4-bit nibbles per element.
10224 for (unsigned i = 0; i < NumHalfWords; ++i) {
10225 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10226 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
10227 }
10228
10229 // For each mask element, find out if we're just inserting something
10230 // from V2 into V1 or vice versa. Possible permutations inserting an element
10231 // from V2 into V1:
10232 // X, 1, 2, 3, 4, 5, 6, 7
10233 // 0, X, 2, 3, 4, 5, 6, 7
10234 // 0, 1, X, 3, 4, 5, 6, 7
10235 // 0, 1, 2, X, 4, 5, 6, 7
10236 // 0, 1, 2, 3, X, 5, 6, 7
10237 // 0, 1, 2, 3, 4, X, 6, 7
10238 // 0, 1, 2, 3, 4, 5, X, 7
10239 // 0, 1, 2, 3, 4, 5, 6, X
10240 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
10241
10242 bool FoundCandidate = false;
10243 // Go through the mask of half-words to find an element that's being moved
10244 // from one vector to the other.
10245 for (unsigned i = 0; i < NumHalfWords; ++i) {
10246 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10247 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
10248 uint32_t MaskOtherElts = ~(0xF << MaskShift);
10249 uint32_t TargetOrder = 0x0;
10250
10251 // If both vector operands for the shuffle are the same vector, the mask
10252 // will contain only elements from the first one and the second one will be
10253 // undef.
10254 if (V2.isUndef()) {
10255 ShiftElts = 0;
10256 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
10257 TargetOrder = OriginalOrderLow;
10258 Swap = false;
10259 // Skip if not the correct element or mask of other elements don't equal
10260 // to our expected order.
10261 if (MaskOneElt == VINSERTHSrcElem &&
10262 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10263 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10264 FoundCandidate = true;
10265 break;
10266 }
10267 } else { // If both operands are defined.
10268 // Target order is [8,15] if the current mask is between [0,7].
10269 TargetOrder =
10270 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
10271 // Skip if mask of other elements don't equal our expected order.
10272 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10273 // We only need the last 3 bits for the number of shifts.
10274 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
10275 : BigEndianShifts[MaskOneElt & 0x7];
10276 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10277 Swap = MaskOneElt < NumHalfWords;
10278 FoundCandidate = true;
10279 break;
10280 }
10281 }
10282 }
10283
10284 if (!FoundCandidate)
10285 return SDValue();
10286
10287 // Candidate found, construct the proper SDAG sequence with VINSERTH,
10288 // optionally with VECSHL if shift is required.
10289 if (Swap)
10290 std::swap(V1, V2);
10291 if (V2.isUndef())
10292 V2 = V1;
10293 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10294 if (ShiftElts) {
10295 // Double ShiftElts because we're left shifting on v16i8 type.
10296 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10297 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
10298 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
10299 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10300 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10301 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10302 }
10303 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
10304 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10305 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10306 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10307}
10308
10309/// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
10310/// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
10311/// return the default SDValue.
10312SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
10313 SelectionDAG &DAG) const {
10314 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
10315 // to v16i8. Peek through the bitcasts to get the actual operands.
10318
10319 auto ShuffleMask = SVN->getMask();
10320 SDValue VecShuffle(SVN, 0);
10321 SDLoc DL(SVN);
10322
10323 // Check that we have a four byte shuffle.
10324 if (!isNByteElemShuffleMask(SVN, 4, 1))
10325 return SDValue();
10326
10327 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
10328 if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
10329 std::swap(LHS, RHS);
10331 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle);
10332 if (!CommutedSV)
10333 return SDValue();
10334 ShuffleMask = CommutedSV->getMask();
10335 }
10336
10337 // Ensure that the RHS is a vector of constants.
10338 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
10339 if (!BVN)
10340 return SDValue();
10341
10342 // Check if RHS is a splat of 4-bytes (or smaller).
10343 APInt APSplatValue, APSplatUndef;
10344 unsigned SplatBitSize;
10345 bool HasAnyUndefs;
10346 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
10347 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
10348 SplatBitSize > 32)
10349 return SDValue();
10350
10351 // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
10352 // The instruction splats a constant C into two words of the source vector
10353 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
10354 // Thus we check that the shuffle mask is the equivalent of
10355 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
10356 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
10357 // within each word are consecutive, so we only need to check the first byte.
10358 SDValue Index;
10359 bool IsLE = Subtarget.isLittleEndian();
10360 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
10361 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
10362 ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
10363 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
10364 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
10365 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
10366 ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
10367 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
10368 else
10369 return SDValue();
10370
10371 // If the splat is narrower than 32-bits, we need to get the 32-bit value
10372 // for XXSPLTI32DX.
10373 unsigned SplatVal = APSplatValue.getZExtValue();
10374 for (; SplatBitSize < 32; SplatBitSize <<= 1)
10375 SplatVal |= (SplatVal << SplatBitSize);
10376
10377 SDValue SplatNode = DAG.getNode(
10378 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
10379 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
10380 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
10381}
10382
10383/// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
10384/// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
10385/// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
10386/// i.e (or (shl x, C1), (srl x, 128-C1)).
10387SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
10388 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
10389 assert(Op.getValueType() == MVT::v1i128 &&
10390 "Only set v1i128 as custom, other type shouldn't reach here!");
10391 SDLoc dl(Op);
10392 SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
10393 SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
10394 unsigned SHLAmt = N1.getConstantOperandVal(0);
10395 if (SHLAmt % 8 == 0) {
10396 std::array<int, 16> Mask;
10397 std::iota(Mask.begin(), Mask.end(), 0);
10398 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
10399 if (SDValue Shuffle =
10400 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
10401 DAG.getUNDEF(MVT::v16i8), Mask))
10402 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
10403 }
10404 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
10405 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
10406 DAG.getConstant(SHLAmt, dl, MVT::i32));
10407 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
10408 DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
10409 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
10410 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
10411}
10412
10413/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
10414/// is a shuffle we can handle in a single instruction, return it. Otherwise,
10415/// return the code it can be lowered into. Worst case, it can always be
10416/// lowered into a vperm.
10417SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
10418 SelectionDAG &DAG) const {
10419 SDLoc dl(Op);
10420 SDValue V1 = Op.getOperand(0);
10421 SDValue V2 = Op.getOperand(1);
10422 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10423
10424 // Any nodes that were combined in the target-independent combiner prior
10425 // to vector legalization will not be sent to the target combine. Try to
10426 // combine it here.
10427 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
10428 if (!isa<ShuffleVectorSDNode>(NewShuffle))
10429 return NewShuffle;
10430 Op = NewShuffle;
10432 V1 = Op.getOperand(0);
10433 V2 = Op.getOperand(1);
10434 }
10435 EVT VT = Op.getValueType();
10436 bool isLittleEndian = Subtarget.isLittleEndian();
10437
10438 unsigned ShiftElts, InsertAtByte;
10439 bool Swap = false;
10440
10441 // If this is a load-and-splat, we can do that with a single instruction
10442 // in some cases. However if the load has multiple uses, we don't want to
10443 // combine it because that will just produce multiple loads.
10444 bool IsPermutedLoad = false;
10445 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
10446 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
10447 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
10448 InputLoad->hasOneUse()) {
10449 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
10450 int SplatIdx =
10451 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
10452
10453 // The splat index for permuted loads will be in the left half of the vector
10454 // which is strictly wider than the loaded value by 8 bytes. So we need to
10455 // adjust the splat index to point to the correct address in memory.
10456 if (IsPermutedLoad) {
10457 assert((isLittleEndian || IsFourByte) &&
10458 "Unexpected size for permuted load on big endian target");
10459 SplatIdx += IsFourByte ? 2 : 1;
10460 assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
10461 "Splat of a value outside of the loaded memory");
10462 }
10463
10464 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
10465 // For 4-byte load-and-splat, we need Power9.
10466 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
10467 uint64_t Offset = 0;
10468 if (IsFourByte)
10469 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
10470 else
10471 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
10472
10473 // If the width of the load is the same as the width of the splat,
10474 // loading with an offset would load the wrong memory.
10475 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
10476 Offset = 0;
10477
10478 SDValue BasePtr = LD->getBasePtr();
10479 if (Offset != 0)
10481 BasePtr, DAG.getIntPtrConstant(Offset, dl));
10482 SDValue Ops[] = {
10483 LD->getChain(), // Chain
10484 BasePtr, // BasePtr
10485 DAG.getValueType(Op.getValueType()) // VT
10486 };
10487 SDVTList VTL =
10488 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
10489 SDValue LdSplt =
10490 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
10491 Ops, LD->getMemoryVT(), LD->getMemOperand());
10492 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
10493 if (LdSplt.getValueType() != SVOp->getValueType(0))
10494 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10495 return LdSplt;
10496 }
10497 }
10498
10499 // All v2i64 and v2f64 shuffles are legal
10500 if (VT == MVT::v2i64 || VT == MVT::v2f64)
10501 return Op;
10502
10503 if (Subtarget.hasP9Vector() &&
10504 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10505 isLittleEndian)) {
10506 if (V2.isUndef())
10507 V2 = V1;
10508 else if (Swap)
10509 std::swap(V1, V2);
10510 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10511 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10512 if (ShiftElts) {
10513 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10514 DAG.getConstant(ShiftElts, dl, MVT::i32));
10515 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10516 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10517 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10518 }
10519 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10520 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10521 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10522 }
10523
10524 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
10525 SDValue SplatInsertNode;
10526 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10527 return SplatInsertNode;
10528 }
10529
10530 if (Subtarget.hasP9Altivec()) {
10531 SDValue NewISDNode;
10532 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10533 return NewISDNode;
10534
10535 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10536 return NewISDNode;
10537 }
10538
10539 if (Subtarget.hasVSX() &&
10540 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10541 if (Swap)
10542 std::swap(V1, V2);
10543 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10544 SDValue Conv2 =
10545 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10546
10547 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10548 DAG.getConstant(ShiftElts, dl, MVT::i32));
10549 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10550 }
10551
10552 if (Subtarget.hasVSX() &&
10553 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10554 if (Swap)
10555 std::swap(V1, V2);
10556 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10557 SDValue Conv2 =
10558 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10559
10560 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10561 DAG.getConstant(ShiftElts, dl, MVT::i32));
10562 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10563 }
10564
10565 if (Subtarget.hasP9Vector()) {
10566 if (PPC::isXXBRHShuffleMask(SVOp)) {
10567 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10568 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10569 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10570 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10571 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10572 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10573 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10574 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10575 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10576 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10577 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10578 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10579 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10580 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10581 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10582 }
10583 }
10584
10585 if (Subtarget.hasVSX()) {
10586 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10587 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10588
10589 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10590 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10591 DAG.getConstant(SplatIdx, dl, MVT::i32));
10592 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10593 }
10594
10595 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10596 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10597 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10598 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10599 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10600 }
10601 }
10602
10603 // Cases that are handled by instructions that take permute immediates
10604 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10605 // selected by the instruction selector.
10606 if (V2.isUndef()) {
10607 if (PPC::isSplatShuffleMask(SVOp, 1) ||
10608 PPC::isSplatShuffleMask(SVOp, 2) ||
10609 PPC::isSplatShuffleMask(SVOp, 4) ||
10610 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10611 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10612 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10613 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10614 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10615 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10616 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10617 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10618 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10619 (Subtarget.hasP8Altivec() && (
10620 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10621 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10622 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10623 return Op;
10624 }
10625 }
10626
10627 // Altivec has a variety of "shuffle immediates" that take two vector inputs
10628 // and produce a fixed permutation. If any of these match, do not lower to
10629 // VPERM.
10630 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10631 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10632 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10633 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10634 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10635 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10636 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10637 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10638 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10639 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10640 (Subtarget.hasP8Altivec() && (
10641 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10642 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10643 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10644 return Op;
10645
10646 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
10647 // perfect shuffle table to emit an optimal matching sequence.
10648 ArrayRef<int> PermMask = SVOp->getMask();
10649
10650 if (!DisablePerfectShuffle && !isLittleEndian) {
10651 unsigned PFIndexes[4];
10652 bool isFourElementShuffle = true;
10653 for (unsigned i = 0; i != 4 && isFourElementShuffle;
10654 ++i) { // Element number
10655 unsigned EltNo = 8; // Start out undef.
10656 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10657 if (PermMask[i * 4 + j] < 0)
10658 continue; // Undef, ignore it.
10659
10660 unsigned ByteSource = PermMask[i * 4 + j];
10661 if ((ByteSource & 3) != j) {
10662 isFourElementShuffle = false;
10663 break;
10664 }
10665
10666 if (EltNo == 8) {
10667 EltNo = ByteSource / 4;
10668 } else if (EltNo != ByteSource / 4) {
10669 isFourElementShuffle = false;
10670 break;
10671 }
10672 }
10673 PFIndexes[i] = EltNo;
10674 }
10675
10676 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10677 // perfect shuffle vector to determine if it is cost effective to do this as
10678 // discrete instructions, or whether we should use a vperm.
10679 // For now, we skip this for little endian until such time as we have a
10680 // little-endian perfect shuffle table.
10681 if (isFourElementShuffle) {
10682 // Compute the index in the perfect shuffle table.
10683 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10684 PFIndexes[2] * 9 + PFIndexes[3];
10685
10686 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10687 unsigned Cost = (PFEntry >> 30);
10688
10689 // Determining when to avoid vperm is tricky. Many things affect the cost
10690 // of vperm, particularly how many times the perm mask needs to be
10691 // computed. For example, if the perm mask can be hoisted out of a loop or
10692 // is already used (perhaps because there are multiple permutes with the
10693 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the
10694 // permute mask out of the loop requires an extra register.
10695 //
10696 // As a compromise, we only emit discrete instructions if the shuffle can
10697 // be generated in 3 or fewer operations. When we have loop information
10698 // available, if this block is within a loop, we should avoid using vperm
10699 // for 3-operation perms and use a constant pool load instead.
10700 if (Cost < 3)
10701 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10702 }
10703 }
10704
10705 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10706 // vector that will get spilled to the constant pool.
10707 if (V2.isUndef()) V2 = V1;
10708
10709 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2);
10710}
10711
10712SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG,
10713 ArrayRef<int> PermMask, EVT VT,
10714 SDValue V1, SDValue V2) const {
10715 unsigned Opcode = PPCISD::VPERM;
10716 EVT ValType = V1.getValueType();
10717 SDLoc dl(Op);
10718 bool NeedSwap = false;
10719 bool isLittleEndian = Subtarget.isLittleEndian();
10720 bool isPPC64 = Subtarget.isPPC64();
10721
10722 if (Subtarget.hasVSX() && Subtarget.hasP9Vector() &&
10723 (V1->hasOneUse() || V2->hasOneUse())) {
10724 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using "
10725 "XXPERM instead\n");
10726 Opcode = PPCISD::XXPERM;
10727
10728 // The second input to XXPERM is also an output so if the second input has
10729 // multiple uses then copying is necessary, as a result we want the
10730 // single-use operand to be used as the second input to prevent copying.
10731 if ((!isLittleEndian && !V2->hasOneUse() && V1->hasOneUse()) ||
10732 (isLittleEndian && !V1->hasOneUse() && V2->hasOneUse())) {
10733 std::swap(V1, V2);
10734 NeedSwap = !NeedSwap;
10735 }
10736 }
10737
10738 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10739 // that it is in input element units, not in bytes. Convert now.
10740
10741 // For little endian, the order of the input vectors is reversed, and
10742 // the permutation mask is complemented with respect to 31. This is
10743 // necessary to produce proper semantics with the big-endian-based vperm
10744 // instruction.
10745 EVT EltVT = V1.getValueType().getVectorElementType();
10746 unsigned BytesPerElement = EltVT.getSizeInBits() / 8;
10747
10748 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10749 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10750
10751 /*
10752 Vectors will be appended like so: [ V1 | v2 ]
10753 XXSWAPD on V1:
10754 [ A | B | C | D ] -> [ C | D | A | B ]
10755 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15
10756 i.e. index of A, B += 8, and index of C, D -= 8.
10757 XXSWAPD on V2:
10758 [ E | F | G | H ] -> [ G | H | E | F ]
10759 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31
10760 i.e. index of E, F += 8, index of G, H -= 8
10761 Swap V1 and V2:
10762 [ V1 | V2 ] -> [ V2 | V1 ]
10763 0-15 16-31 0-15 16-31
10764 i.e. index of V1 += 16, index of V2 -= 16
10765 */
10766
10767 SmallVector<SDValue, 16> ResultMask;
10768 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10769 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10770
10771 if (V1HasXXSWAPD) {
10772 if (SrcElt < 8)
10773 SrcElt += 8;
10774 else if (SrcElt < 16)
10775 SrcElt -= 8;
10776 }
10777 if (V2HasXXSWAPD) {
10778 if (SrcElt > 23)
10779 SrcElt -= 8;
10780 else if (SrcElt > 15)
10781 SrcElt += 8;
10782 }
10783 if (NeedSwap) {
10784 if (SrcElt < 16)
10785 SrcElt += 16;
10786 else
10787 SrcElt -= 16;
10788 }
10789 for (unsigned j = 0; j != BytesPerElement; ++j)
10790 if (isLittleEndian)
10791 ResultMask.push_back(
10792 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32));
10793 else
10794 ResultMask.push_back(
10795 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32));
10796 }
10797
10798 if (V1HasXXSWAPD) {
10799 dl = SDLoc(V1->getOperand(0));
10800 V1 = V1->getOperand(0)->getOperand(1);
10801 }
10802 if (V2HasXXSWAPD) {
10803 dl = SDLoc(V2->getOperand(0));
10804 V2 = V2->getOperand(0)->getOperand(1);
10805 }
10806
10807 if (isPPC64 && (V1HasXXSWAPD || V2HasXXSWAPD)) {
10808 if (ValType != MVT::v2f64)
10809 V1 = DAG.getBitcast(MVT::v2f64, V1);
10810 if (V2.getValueType() != MVT::v2f64)
10811 V2 = DAG.getBitcast(MVT::v2f64, V2);
10812 }
10813
10814 ShufflesHandledWithVPERM++;
10815 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10816 LLVM_DEBUG({
10817 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10818 if (Opcode == PPCISD::XXPERM) {
10819 dbgs() << "Emitting a XXPERM for the following shuffle:\n";
10820 } else {
10821 dbgs() << "Emitting a VPERM for the following shuffle:\n";
10822 }
10823 SVOp->dump();
10824 dbgs() << "With the following permute control vector:\n";
10825 VPermMask.dump();
10826 });
10827
10828 if (Opcode == PPCISD::XXPERM)
10829 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask);
10830
10831 // Only need to place items backwards in LE,
10832 // the mask was properly calculated.
10833 if (isLittleEndian)
10834 std::swap(V1, V2);
10835
10836 SDValue VPERMNode =
10837 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask);
10838
10839 VPERMNode = DAG.getBitcast(ValType, VPERMNode);
10840 return VPERMNode;
10841}
10842
10843/// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10844/// vector comparison. If it is, return true and fill in Opc/isDot with
10845/// information about the intrinsic.
10846static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10847 bool &isDot, const PPCSubtarget &Subtarget) {
10848 unsigned IntrinsicID = Intrin.getConstantOperandVal(0);
10849 CompareOpc = -1;
10850 isDot = false;
10851 switch (IntrinsicID) {
10852 default:
10853 return false;
10854 // Comparison predicates.
10855 case Intrinsic::ppc_altivec_vcmpbfp_p:
10856 CompareOpc = 966;
10857 isDot = true;
10858 break;
10859 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10860 CompareOpc = 198;
10861 isDot = true;
10862 break;
10863 case Intrinsic::ppc_altivec_vcmpequb_p:
10864 CompareOpc = 6;
10865 isDot = true;
10866 break;
10867 case Intrinsic::ppc_altivec_vcmpequh_p:
10868 CompareOpc = 70;
10869 isDot = true;
10870 break;
10871 case Intrinsic::ppc_altivec_vcmpequw_p:
10872 CompareOpc = 134;
10873 isDot = true;
10874 break;
10875 case Intrinsic::ppc_altivec_vcmpequd_p:
10876 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10877 CompareOpc = 199;
10878 isDot = true;
10879 } else
10880 return false;
10881 break;
10882 case Intrinsic::ppc_altivec_vcmpneb_p:
10883 case Intrinsic::ppc_altivec_vcmpneh_p:
10884 case Intrinsic::ppc_altivec_vcmpnew_p:
10885 case Intrinsic::ppc_altivec_vcmpnezb_p:
10886 case Intrinsic::ppc_altivec_vcmpnezh_p:
10887 case Intrinsic::ppc_altivec_vcmpnezw_p:
10888 if (Subtarget.hasP9Altivec()) {
10889 switch (IntrinsicID) {
10890 default:
10891 llvm_unreachable("Unknown comparison intrinsic.");
10892 case Intrinsic::ppc_altivec_vcmpneb_p:
10893 CompareOpc = 7;
10894 break;
10895 case Intrinsic::ppc_altivec_vcmpneh_p:
10896 CompareOpc = 71;
10897 break;
10898 case Intrinsic::ppc_altivec_vcmpnew_p:
10899 CompareOpc = 135;
10900 break;
10901 case Intrinsic::ppc_altivec_vcmpnezb_p:
10902 CompareOpc = 263;
10903 break;
10904 case Intrinsic::ppc_altivec_vcmpnezh_p:
10905 CompareOpc = 327;
10906 break;
10907 case Intrinsic::ppc_altivec_vcmpnezw_p:
10908 CompareOpc = 391;
10909 break;
10910 }
10911 isDot = true;
10912 } else
10913 return false;
10914 break;
10915 case Intrinsic::ppc_altivec_vcmpgefp_p:
10916 CompareOpc = 454;
10917 isDot = true;
10918 break;
10919 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10920 CompareOpc = 710;
10921 isDot = true;
10922 break;
10923 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10924 CompareOpc = 774;
10925 isDot = true;
10926 break;
10927 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10928 CompareOpc = 838;
10929 isDot = true;
10930 break;
10931 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10932 CompareOpc = 902;
10933 isDot = true;
10934 break;
10935 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10936 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10937 CompareOpc = 967;
10938 isDot = true;
10939 } else
10940 return false;
10941 break;
10942 case Intrinsic::ppc_altivec_vcmpgtub_p:
10943 CompareOpc = 518;
10944 isDot = true;
10945 break;
10946 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10947 CompareOpc = 582;
10948 isDot = true;
10949 break;
10950 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10951 CompareOpc = 646;
10952 isDot = true;
10953 break;
10954 case Intrinsic::ppc_altivec_vcmpgtud_p:
10955 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10956 CompareOpc = 711;
10957 isDot = true;
10958 } else
10959 return false;
10960 break;
10961
10962 case Intrinsic::ppc_altivec_vcmpequq:
10963 case Intrinsic::ppc_altivec_vcmpgtsq:
10964 case Intrinsic::ppc_altivec_vcmpgtuq:
10965 if (!Subtarget.isISA3_1())
10966 return false;
10967 switch (IntrinsicID) {
10968 default:
10969 llvm_unreachable("Unknown comparison intrinsic.");
10970 case Intrinsic::ppc_altivec_vcmpequq:
10971 CompareOpc = 455;
10972 break;
10973 case Intrinsic::ppc_altivec_vcmpgtsq:
10974 CompareOpc = 903;
10975 break;
10976 case Intrinsic::ppc_altivec_vcmpgtuq:
10977 CompareOpc = 647;
10978 break;
10979 }
10980 break;
10981
10982 // VSX predicate comparisons use the same infrastructure
10983 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10984 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10985 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10986 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10987 case Intrinsic::ppc_vsx_xvcmpgesp_p:
10988 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10989 if (Subtarget.hasVSX()) {
10990 switch (IntrinsicID) {
10991 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10992 CompareOpc = 99;
10993 break;
10994 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10995 CompareOpc = 115;
10996 break;
10997 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10998 CompareOpc = 107;
10999 break;
11000 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
11001 CompareOpc = 67;
11002 break;
11003 case Intrinsic::ppc_vsx_xvcmpgesp_p:
11004 CompareOpc = 83;
11005 break;
11006 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
11007 CompareOpc = 75;
11008 break;
11009 }
11010 isDot = true;
11011 } else
11012 return false;
11013 break;
11014
11015 // Normal Comparisons.
11016 case Intrinsic::ppc_altivec_vcmpbfp:
11017 CompareOpc = 966;
11018 break;
11019 case Intrinsic::ppc_altivec_vcmpeqfp:
11020 CompareOpc = 198;
11021 break;
11022 case Intrinsic::ppc_altivec_vcmpequb:
11023 CompareOpc = 6;
11024 break;
11025 case Intrinsic::ppc_altivec_vcmpequh:
11026 CompareOpc = 70;
11027 break;
11028 case Intrinsic::ppc_altivec_vcmpequw:
11029 CompareOpc = 134;
11030 break;
11031 case Intrinsic::ppc_altivec_vcmpequd:
11032 if (Subtarget.hasP8Altivec())
11033 CompareOpc = 199;
11034 else
11035 return false;
11036 break;
11037 case Intrinsic::ppc_altivec_vcmpneb:
11038 case Intrinsic::ppc_altivec_vcmpneh:
11039 case Intrinsic::ppc_altivec_vcmpnew:
11040 case Intrinsic::ppc_altivec_vcmpnezb:
11041 case Intrinsic::ppc_altivec_vcmpnezh:
11042 case Intrinsic::ppc_altivec_vcmpnezw:
11043 if (Subtarget.hasP9Altivec())
11044 switch (IntrinsicID) {
11045 default:
11046 llvm_unreachable("Unknown comparison intrinsic.");
11047 case Intrinsic::ppc_altivec_vcmpneb:
11048 CompareOpc = 7;
11049 break;
11050 case Intrinsic::ppc_altivec_vcmpneh:
11051 CompareOpc = 71;
11052 break;
11053 case Intrinsic::ppc_altivec_vcmpnew:
11054 CompareOpc = 135;
11055 break;
11056 case Intrinsic::ppc_altivec_vcmpnezb:
11057 CompareOpc = 263;
11058 break;
11059 case Intrinsic::ppc_altivec_vcmpnezh:
11060 CompareOpc = 327;
11061 break;
11062 case Intrinsic::ppc_altivec_vcmpnezw:
11063 CompareOpc = 391;
11064 break;
11065 }
11066 else
11067 return false;
11068 break;
11069 case Intrinsic::ppc_altivec_vcmpgefp:
11070 CompareOpc = 454;
11071 break;
11072 case Intrinsic::ppc_altivec_vcmpgtfp:
11073 CompareOpc = 710;
11074 break;
11075 case Intrinsic::ppc_altivec_vcmpgtsb:
11076 CompareOpc = 774;
11077 break;
11078 case Intrinsic::ppc_altivec_vcmpgtsh:
11079 CompareOpc = 838;
11080 break;
11081 case Intrinsic::ppc_altivec_vcmpgtsw:
11082 CompareOpc = 902;
11083 break;
11084 case Intrinsic::ppc_altivec_vcmpgtsd:
11085 if (Subtarget.hasP8Altivec())
11086 CompareOpc = 967;
11087 else
11088 return false;
11089 break;
11090 case Intrinsic::ppc_altivec_vcmpgtub:
11091 CompareOpc = 518;
11092 break;
11093 case Intrinsic::ppc_altivec_vcmpgtuh:
11094 CompareOpc = 582;
11095 break;
11096 case Intrinsic::ppc_altivec_vcmpgtuw:
11097 CompareOpc = 646;
11098 break;
11099 case Intrinsic::ppc_altivec_vcmpgtud:
11100 if (Subtarget.hasP8Altivec())
11101 CompareOpc = 711;
11102 else
11103 return false;
11104 break;
11105 case Intrinsic::ppc_altivec_vcmpequq_p:
11106 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11107 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11108 if (!Subtarget.isISA3_1())
11109 return false;
11110 switch (IntrinsicID) {
11111 default:
11112 llvm_unreachable("Unknown comparison intrinsic.");
11113 case Intrinsic::ppc_altivec_vcmpequq_p:
11114 CompareOpc = 455;
11115 break;
11116 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11117 CompareOpc = 903;
11118 break;
11119 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11120 CompareOpc = 647;
11121 break;
11122 }
11123 isDot = true;
11124 break;
11125 }
11126 return true;
11127}
11128
11129/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
11130/// lower, do it, otherwise return null.
11131SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11132 SelectionDAG &DAG) const {
11133 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11134
11135 SDLoc dl(Op);
11136 // Note: BCD instructions expect the immediate operand in vector form (v4i32),
11137 // but the builtin provides it as a scalar. To satisfy the instruction
11138 // encoding, we splat the scalar across all lanes using SPLAT_VECTOR.
11139 auto MapNodeWithSplatVector =
11140 [&](unsigned Opcode,
11141 std::initializer_list<SDValue> ExtraOps = {}) -> SDValue {
11142 SDValue SplatVal =
11143 DAG.getNode(ISD::SPLAT_VECTOR, dl, MVT::v4i32, Op.getOperand(2));
11144
11145 SmallVector<SDValue, 4> Ops{SplatVal, Op.getOperand(1)};
11146 Ops.append(ExtraOps.begin(), ExtraOps.end());
11147 return DAG.getNode(Opcode, dl, MVT::v16i8, Ops);
11148 };
11149
11150 switch (IntrinsicID) {
11151 case Intrinsic::thread_pointer:
11152 // Reads the thread pointer register, used for __builtin_thread_pointer.
11153 if (Subtarget.isPPC64())
11154 return DAG.getRegister(PPC::X13, MVT::i64);
11155 return DAG.getRegister(PPC::R2, MVT::i32);
11156
11157 case Intrinsic::ppc_rldimi: {
11158 assert(Subtarget.isPPC64() && "rldimi is only available in 64-bit!");
11159 SDValue Src = Op.getOperand(1);
11160 APInt Mask = Op.getConstantOperandAPInt(4);
11161 if (Mask.isZero())
11162 return Op.getOperand(2);
11163 if (Mask.isAllOnes())
11164 return DAG.getNode(ISD::ROTL, dl, MVT::i64, Src, Op.getOperand(3));
11165 uint64_t SH = Op.getConstantOperandVal(3);
11166 unsigned MB = 0, ME = 0;
11167 if (!isRunOfOnes64(Mask.getZExtValue(), MB, ME))
11168 report_fatal_error("invalid rldimi mask!");
11169 // rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
11170 if (ME < 63 - SH) {
11171 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11172 DAG.getConstant(ME + SH + 1, dl, MVT::i32));
11173 } else if (ME > 63 - SH) {
11174 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11175 DAG.getConstant(ME + SH - 63, dl, MVT::i32));
11176 }
11177 return SDValue(
11178 DAG.getMachineNode(PPC::RLDIMI, dl, MVT::i64,
11179 {Op.getOperand(2), Src,
11180 DAG.getTargetConstant(63 - ME, dl, MVT::i32),
11181 DAG.getTargetConstant(MB, dl, MVT::i32)}),
11182 0);
11183 }
11184
11185 case Intrinsic::ppc_rlwimi: {
11186 APInt Mask = Op.getConstantOperandAPInt(4);
11187 if (Mask.isZero())
11188 return Op.getOperand(2);
11189 if (Mask.isAllOnes())
11190 return DAG.getNode(ISD::ROTL, dl, MVT::i32, Op.getOperand(1),
11191 Op.getOperand(3));
11192 unsigned MB = 0, ME = 0;
11193 if (!isRunOfOnes(Mask.getZExtValue(), MB, ME))
11194 report_fatal_error("invalid rlwimi mask!");
11195 return SDValue(DAG.getMachineNode(
11196 PPC::RLWIMI, dl, MVT::i32,
11197 {Op.getOperand(2), Op.getOperand(1), Op.getOperand(3),
11198 DAG.getTargetConstant(MB, dl, MVT::i32),
11199 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11200 0);
11201 }
11202
11203 case Intrinsic::ppc_bcdshift:
11204 return MapNodeWithSplatVector(PPCISD::BCDSHIFT, {Op.getOperand(3)});
11205 case Intrinsic::ppc_bcdshiftround:
11206 return MapNodeWithSplatVector(PPCISD::BCDSHIFTROUND, {Op.getOperand(3)});
11207 case Intrinsic::ppc_bcdtruncate:
11208 return MapNodeWithSplatVector(PPCISD::BCDTRUNC, {Op.getOperand(3)});
11209 case Intrinsic::ppc_bcdunsignedtruncate:
11210 return MapNodeWithSplatVector(PPCISD::BCDUTRUNC);
11211 case Intrinsic::ppc_bcdunsignedshift:
11212 return MapNodeWithSplatVector(PPCISD::BCDUSHIFT);
11213
11214 case Intrinsic::ppc_rlwnm: {
11215 if (Op.getConstantOperandVal(3) == 0)
11216 return DAG.getConstant(0, dl, MVT::i32);
11217 unsigned MB = 0, ME = 0;
11218 if (!isRunOfOnes(Op.getConstantOperandVal(3), MB, ME))
11219 report_fatal_error("invalid rlwnm mask!");
11220 return SDValue(
11221 DAG.getMachineNode(PPC::RLWNM, dl, MVT::i32,
11222 {Op.getOperand(1), Op.getOperand(2),
11223 DAG.getTargetConstant(MB, dl, MVT::i32),
11224 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11225 0);
11226 }
11227
11228 case Intrinsic::ppc_mma_disassemble_acc: {
11229 if (Subtarget.isISAFuture()) {
11230 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11231 SDValue WideVec =
11232 SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes,
11233 Op.getOperand(1)),
11234 0);
11236 SDValue Value = SDValue(WideVec.getNode(), 0);
11237 SDValue Value2 = SDValue(WideVec.getNode(), 1);
11238
11239 SDValue Extract;
11240 Extract = DAG.getNode(
11241 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11242 Subtarget.isLittleEndian() ? Value2 : Value,
11243 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11244 dl, getPointerTy(DAG.getDataLayout())));
11245 RetOps.push_back(Extract);
11246 Extract = DAG.getNode(
11247 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11248 Subtarget.isLittleEndian() ? Value2 : Value,
11249 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11250 dl, getPointerTy(DAG.getDataLayout())));
11251 RetOps.push_back(Extract);
11252 Extract = DAG.getNode(
11253 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11254 Subtarget.isLittleEndian() ? Value : Value2,
11255 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11256 dl, getPointerTy(DAG.getDataLayout())));
11257 RetOps.push_back(Extract);
11258 Extract = DAG.getNode(
11259 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11260 Subtarget.isLittleEndian() ? Value : Value2,
11261 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11262 dl, getPointerTy(DAG.getDataLayout())));
11263 RetOps.push_back(Extract);
11264 return DAG.getMergeValues(RetOps, dl);
11265 }
11266 [[fallthrough]];
11267 }
11268 case Intrinsic::ppc_vsx_disassemble_pair: {
11269 int NumVecs = 2;
11270 SDValue WideVec = Op.getOperand(1);
11271 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
11272 NumVecs = 4;
11273 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
11274 }
11276 for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
11277 SDValue Extract = DAG.getNode(
11278 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
11279 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
11280 : VecNo,
11281 dl, getPointerTy(DAG.getDataLayout())));
11282 RetOps.push_back(Extract);
11283 }
11284 return DAG.getMergeValues(RetOps, dl);
11285 }
11286
11287 case Intrinsic::ppc_build_dmr: {
11290 for (int i = 1; i < 9; i += 2) {
11291 SDValue Hi = Op.getOperand(i);
11292 SDValue Lo = Op.getOperand(i + 1);
11293 if (Hi->getOpcode() == ISD::LOAD)
11294 Chains.push_back(Hi.getValue(1));
11295 if (Lo->getOpcode() == ISD::LOAD)
11296 Chains.push_back(Lo.getValue(1));
11297 Pairs.push_back(
11298 DAG.getNode(PPCISD::PAIR_BUILD, dl, MVT::v256i1, {Hi, Lo}));
11299 }
11300 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11301 SDValue Value = DMFInsert1024(Pairs, SDLoc(Op), DAG);
11302 return DAG.getMergeValues({Value, TF}, dl);
11303 }
11304
11305 case Intrinsic::ppc_mma_dmxxextfdmr512: {
11306 assert(Subtarget.isISAFuture() && "dmxxextfdmr512 requires ISA Future");
11307 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11308 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11309 "Specify P of 0 or 1 for lower or upper 512 bytes");
11310 unsigned HiLo = Idx->getSExtValue();
11311 unsigned Opcode;
11312 unsigned Subx;
11313 if (HiLo == 0) {
11314 Opcode = PPC::DMXXEXTFDMR512;
11315 Subx = PPC::sub_wacc_lo;
11316 } else {
11317 Opcode = PPC::DMXXEXTFDMR512_HI;
11318 Subx = PPC::sub_wacc_hi;
11319 }
11320 SDValue Subreg(
11321 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
11322 Op.getOperand(1),
11323 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11324 0);
11325 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11326 return SDValue(DAG.getMachineNode(Opcode, dl, ReturnTypes, Subreg), 0);
11327 }
11328
11329 case Intrinsic::ppc_mma_dmxxextfdmr256: {
11330 assert(Subtarget.isISAFuture() && "dmxxextfdmr256 requires ISA Future");
11331 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11332 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11333 "Specify a dmr row pair 0-3");
11334 unsigned IdxVal = Idx->getSExtValue();
11335 unsigned Subx;
11336 switch (IdxVal) {
11337 case 0:
11338 Subx = PPC::sub_dmrrowp0;
11339 break;
11340 case 1:
11341 Subx = PPC::sub_dmrrowp1;
11342 break;
11343 case 2:
11344 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11345 break;
11346 case 3:
11347 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11348 break;
11349 }
11350 SDValue Subreg(
11351 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v256i1,
11352 Op.getOperand(1),
11353 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11354 0);
11355 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11356 return SDValue(
11357 DAG.getMachineNode(PPC::DMXXEXTFDMR256, dl, MVT::v256i1, {Subreg, P}),
11358 0);
11359 }
11360
11361 case Intrinsic::ppc_mma_dmxxinstdmr512: {
11362 assert(Subtarget.isISAFuture() && "dmxxinstdmr512 requires ISA Future");
11363 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4));
11364 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11365 "Specify P of 0 or 1 for lower or upper 512 bytes");
11366 unsigned HiLo = Idx->getSExtValue();
11367 unsigned Opcode;
11368 unsigned Subx;
11369 if (HiLo == 0) {
11370 Opcode = PPCISD::INST512;
11371 Subx = PPC::sub_wacc_lo;
11372 } else {
11373 Opcode = PPCISD::INST512HI;
11374 Subx = PPC::sub_wacc_hi;
11375 }
11376 SDValue Wacc = DAG.getNode(Opcode, dl, MVT::v512i1, Op.getOperand(2),
11377 Op.getOperand(3));
11378 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11379 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11380 Op.getOperand(1), Wacc, SubReg),
11381 0);
11382 }
11383
11384 case Intrinsic::ppc_mma_dmxxinstdmr256: {
11385 assert(Subtarget.isISAFuture() && "dmxxinstdmr256 requires ISA Future");
11386 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3));
11387 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11388 "Specify a dmr row pair 0-3");
11389 unsigned IdxVal = Idx->getSExtValue();
11390 unsigned Subx;
11391 switch (IdxVal) {
11392 case 0:
11393 Subx = PPC::sub_dmrrowp0;
11394 break;
11395 case 1:
11396 Subx = PPC::sub_dmrrowp1;
11397 break;
11398 case 2:
11399 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11400 break;
11401 case 3:
11402 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11403 break;
11404 }
11405 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11406 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11407 SDValue DMRRowp =
11408 DAG.getNode(PPCISD::INST256, dl, MVT::v256i1, Op.getOperand(2), P);
11409 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11410 Op.getOperand(1), DMRRowp, SubReg),
11411 0);
11412 }
11413
11414 case Intrinsic::ppc_mma_xxmfacc:
11415 case Intrinsic::ppc_mma_xxmtacc: {
11416 // Allow pre-isa-future subtargets to lower as normal.
11417 if (!Subtarget.isISAFuture())
11418 return SDValue();
11419 // The intrinsics for xxmtacc and xxmfacc take one argument of
11420 // type v512i1, for future cpu the corresponding wacc instruction
11421 // dmxx[inst|extf]dmr512 is always generated for type v512i1, negating
11422 // the need to produce the xxm[t|f]acc.
11423 SDValue WideVec = Op.getOperand(1);
11424 DAG.ReplaceAllUsesWith(Op, WideVec);
11425 return SDValue();
11426 }
11427
11428 case Intrinsic::ppc_unpack_longdouble: {
11429 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11430 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11431 "Argument of long double unpack must be 0 or 1!");
11432 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
11433 DAG.getConstant(!!(Idx->getSExtValue()), dl,
11434 Idx->getValueType(0)));
11435 }
11436
11437 case Intrinsic::ppc_compare_exp_lt:
11438 case Intrinsic::ppc_compare_exp_gt:
11439 case Intrinsic::ppc_compare_exp_eq:
11440 case Intrinsic::ppc_compare_exp_uo: {
11441 unsigned Pred;
11442 switch (IntrinsicID) {
11443 case Intrinsic::ppc_compare_exp_lt:
11444 Pred = PPC::PRED_LT;
11445 break;
11446 case Intrinsic::ppc_compare_exp_gt:
11447 Pred = PPC::PRED_GT;
11448 break;
11449 case Intrinsic::ppc_compare_exp_eq:
11450 Pred = PPC::PRED_EQ;
11451 break;
11452 case Intrinsic::ppc_compare_exp_uo:
11453 Pred = PPC::PRED_UN;
11454 break;
11455 }
11456 return SDValue(
11457 DAG.getMachineNode(
11458 PPC::SELECT_CC_I4, dl, MVT::i32,
11459 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
11460 Op.getOperand(1), Op.getOperand(2)),
11461 0),
11462 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
11463 DAG.getTargetConstant(Pred, dl, MVT::i32)}),
11464 0);
11465 }
11466 case Intrinsic::ppc_test_data_class: {
11467 EVT OpVT = Op.getOperand(1).getValueType();
11468 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP
11469 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP
11470 : PPC::XSTSTDCSP);
11471 // Lower __builtin_ppc_test_data_class(value, mask) to XSTSTDC* instruction.
11472 // The XSTSTDC* instructions test if a floating-point value matches any of
11473 // the data classes specified in the mask, setting CR field bits
11474 // accordingly. We need to extract the EQ bit (bit 2) from the CR field and
11475 // convert it to an integer result (1 if match, 0 if no match).
11476 //
11477 // Note: Operands are swapped because XSTSTDC* expects (mask, value) but the
11478 // intrinsic provides (value, mask) as Op.getOperand(1) and
11479 // Op.getOperand(2).
11480 SDValue TestDataClass =
11481 SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32,
11482 {Op.getOperand(2), Op.getOperand(1)}),
11483 0);
11484 if (Subtarget.isISA3_1()) {
11485 // ISA 3.1+: Use SETBC instruction to directly convert CR bit to integer.
11486 // This is more efficient than the SELECT_CC approach used in earlier
11487 // ISAs.
11488 SDValue SubRegIdx = DAG.getTargetConstant(PPC::sub_eq, dl, MVT::i32);
11489 SDValue CRBit =
11490 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11491 TestDataClass, SubRegIdx),
11492 0);
11493
11494 return DAG.getNode(PPCISD::SETBC, dl, MVT::i32, CRBit);
11495 }
11496
11497 // Pre-ISA 3.1: Use SELECT_CC to convert CR field to integer (1 or 0).
11498 return SDValue(
11499 DAG.getMachineNode(PPC::SELECT_CC_I4, dl, MVT::i32,
11500 {TestDataClass, DAG.getConstant(1, dl, MVT::i32),
11501 DAG.getConstant(0, dl, MVT::i32),
11502 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
11503 0);
11504 }
11505 case Intrinsic::ppc_fnmsub: {
11506 EVT VT = Op.getOperand(1).getValueType();
11507 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
11508 return DAG.getNode(
11509 ISD::FNEG, dl, VT,
11510 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
11511 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
11512 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
11513 Op.getOperand(2), Op.getOperand(3));
11514 }
11515 case Intrinsic::ppc_convert_f128_to_ppcf128:
11516 case Intrinsic::ppc_convert_ppcf128_to_f128: {
11517 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
11518 ? RTLIB::CONVERT_PPCF128_F128
11519 : RTLIB::CONVERT_F128_PPCF128;
11520 MakeLibCallOptions CallOptions;
11521 std::pair<SDValue, SDValue> Result =
11522 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
11523 dl, SDValue());
11524 return Result.first;
11525 }
11526 case Intrinsic::ppc_maxfe:
11527 case Intrinsic::ppc_maxfl:
11528 case Intrinsic::ppc_maxfs:
11529 case Intrinsic::ppc_minfe:
11530 case Intrinsic::ppc_minfl:
11531 case Intrinsic::ppc_minfs: {
11532 EVT VT = Op.getValueType();
11533 assert(
11534 all_of(Op->ops().drop_front(4),
11535 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
11536 "ppc_[max|min]f[e|l|s] must have uniform type arguments");
11537 (void)VT;
11539 if (IntrinsicID == Intrinsic::ppc_minfe ||
11540 IntrinsicID == Intrinsic::ppc_minfl ||
11541 IntrinsicID == Intrinsic::ppc_minfs)
11542 CC = ISD::SETLT;
11543 unsigned I = Op.getNumOperands() - 2, Cnt = I;
11544 SDValue Res = Op.getOperand(I);
11545 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
11546 Res =
11547 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
11548 }
11549 return Res;
11550 }
11551 }
11552
11553 // If this is a lowered altivec predicate compare, CompareOpc is set to the
11554 // opcode number of the comparison.
11555 int CompareOpc;
11556 bool isDot;
11557 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
11558 return SDValue(); // Don't custom lower most intrinsics.
11559
11560 // If this is a non-dot comparison, make the VCMP node and we are done.
11561 if (!isDot) {
11562 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
11563 Op.getOperand(1), Op.getOperand(2),
11564 DAG.getConstant(CompareOpc, dl, MVT::i32));
11565 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
11566 }
11567
11568 // Create the PPCISD altivec 'dot' comparison node.
11569 SDValue Ops[] = {
11570 Op.getOperand(2), // LHS
11571 Op.getOperand(3), // RHS
11572 DAG.getConstant(CompareOpc, dl, MVT::i32)
11573 };
11574 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
11575 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
11576
11577 // Unpack the result based on how the target uses it.
11578 unsigned BitNo; // Bit # of CR6.
11579 bool InvertBit; // Invert result?
11580 unsigned Bitx;
11581 unsigned SetOp;
11582 switch (Op.getConstantOperandVal(1)) {
11583 default: // Can't happen, don't crash on invalid number though.
11584 case 0: // Return the value of the EQ bit of CR6.
11585 BitNo = 0;
11586 InvertBit = false;
11587 Bitx = PPC::sub_eq;
11588 SetOp = PPCISD::SETBC;
11589 break;
11590 case 1: // Return the inverted value of the EQ bit of CR6.
11591 BitNo = 0;
11592 InvertBit = true;
11593 Bitx = PPC::sub_eq;
11594 SetOp = PPCISD::SETBCR;
11595 break;
11596 case 2: // Return the value of the LT bit of CR6.
11597 BitNo = 2;
11598 InvertBit = false;
11599 Bitx = PPC::sub_lt;
11600 SetOp = PPCISD::SETBC;
11601 break;
11602 case 3: // Return the inverted value of the LT bit of CR6.
11603 BitNo = 2;
11604 InvertBit = true;
11605 Bitx = PPC::sub_lt;
11606 SetOp = PPCISD::SETBCR;
11607 break;
11608 }
11609
11610 SDValue GlueOp = CompNode.getValue(1);
11611 if (Subtarget.isISA3_1()) {
11612 SDValue SubRegIdx = DAG.getTargetConstant(Bitx, dl, MVT::i32);
11613 SDValue CR6Reg = DAG.getRegister(PPC::CR6, MVT::i32);
11614 SDValue CRBit =
11615 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11616 CR6Reg, SubRegIdx, GlueOp),
11617 0);
11618 return DAG.getNode(SetOp, dl, MVT::i32, CRBit);
11619 }
11620
11621 // Now that we have the comparison, emit a copy from the CR to a GPR.
11622 // This is flagged to the above dot comparison.
11623 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
11624 DAG.getRegister(PPC::CR6, MVT::i32), GlueOp);
11625
11626 // Shift the bit into the low position.
11627 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
11628 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
11629 // Isolate the bit.
11630 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
11631 DAG.getConstant(1, dl, MVT::i32));
11632
11633 // If we are supposed to, toggle the bit.
11634 if (InvertBit)
11635 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
11636 DAG.getConstant(1, dl, MVT::i32));
11637 return Flags;
11638}
11639
11640SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
11641 SelectionDAG &DAG) const {
11642 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
11643 // the beginning of the argument list.
11644 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
11645 SDLoc DL(Op);
11646 switch (Op.getConstantOperandVal(ArgStart)) {
11647 case Intrinsic::ppc_cfence: {
11648 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
11649 SDValue Val = Op.getOperand(ArgStart + 1);
11650 EVT Ty = Val.getValueType();
11651 if (Ty == MVT::i128) {
11652 // FIXME: Testing one of two paired registers is sufficient to guarantee
11653 // ordering?
11654 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
11655 }
11656 unsigned Opcode = Subtarget.isPPC64() ? PPC::CFENCE8 : PPC::CFENCE;
11657 return SDValue(
11658 DAG.getMachineNode(
11659 Opcode, DL, MVT::Other,
11660 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getScalarIntVT(), Val),
11661 Op.getOperand(0)),
11662 0);
11663 }
11664 case Intrinsic::ppc_disassemble_dmr: {
11665 assert(ArgStart == 1 &&
11666 "llvm.ppc.disassemble.dmr must carry a chain argument.");
11667 return DAG.getStore(Op.getOperand(0), DL, Op.getOperand(ArgStart + 2),
11668 Op.getOperand(ArgStart + 1), MachinePointerInfo());
11669 }
11670 default:
11671 break;
11672 }
11673 return SDValue();
11674}
11675
11676// Lower scalar BSWAP64 to xxbrd.
11677SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
11678 SDLoc dl(Op);
11679 if (!Subtarget.isPPC64())
11680 return Op;
11681
11682 if (Subtarget.hasP9Vector()) {
11683 // MTVSRDD
11684 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
11685 Op.getOperand(0));
11686 // XXBRD
11687 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
11688 // MFVSRD
11689 int VectorIndex = 0;
11690 if (Subtarget.isLittleEndian())
11691 VectorIndex = 1;
11692 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
11693 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
11694 return Op;
11695 }
11696
11697 // For Power8, use parallel rotate instructions for faster bswap64.
11698 SDValue Input = Op.getOperand(0);
11699 // Helper to create rotate-and-insert operations (RLWIMI/RLDIMI).
11700 auto CreateRotateInsert =
11701 [&](unsigned Opcode, MVT VT, SDValue Dest, SDValue Src, unsigned RotAmt,
11702 unsigned MaskBegin,
11703 std::optional<unsigned> MaskEnd = std::nullopt) -> SDValue {
11705 Dest, Src, DAG.getTargetConstant(RotAmt, dl, MVT::i32),
11706 DAG.getTargetConstant(MaskBegin, dl, MVT::i32)};
11707 if (MaskEnd.has_value())
11708 Ops.push_back(DAG.getTargetConstant(*MaskEnd, dl, MVT::i32));
11709
11710 return SDValue(DAG.getMachineNode(Opcode, dl, VT, Ops), 0);
11711 };
11712
11713 // Helper to perform 32-bit byte swap using rotl(8) + 2x rlwimi.
11714 auto Swap32 = [&](SDValue Val32) -> SDValue {
11715 SDValue Rot = DAG.getNode(ISD::ROTL, dl, MVT::i32, Val32,
11716 DAG.getConstant(8, dl, MVT::i32));
11717 // Insert bits [24:31] from Val32 into Rot at position [0:7].
11718 SDValue Swap =
11719 CreateRotateInsert(PPC::RLWIMI, MVT::i32, Rot, Val32, 24, 0, 7);
11720 // Insert bits [16:23] from Val32 into Swap at position [16:23].
11721 return CreateRotateInsert(PPC::RLWIMI, MVT::i32, Swap, Val32, 24, 16, 23);
11722 };
11723 // Extract and swap high and low 32-bit halves independently for parallelism.
11724 SDValue Hi32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
11725 DAG.getNode(ISD::SRL, dl, MVT::i64, Input,
11726 DAG.getConstant(32, dl, MVT::i64)));
11727 SDValue Lo32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Input);
11728
11729 // Combine swapped halves: rotate LoSwap left by 32 bits and insert into
11730 // HiSwap to swap their positions, completing the 64-bit byte reversal.
11731 SDValue HiSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Hi32));
11732 SDValue LoSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Lo32));
11733
11734 return CreateRotateInsert(PPC::RLDIMI, MVT::i64, HiSwap, LoSwap, 32, 0);
11735}
11736
11737// ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
11738// compared to a value that is atomically loaded (atomic loads zero-extend).
11739SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
11740 SelectionDAG &DAG) const {
11741 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
11742 "Expecting an atomic compare-and-swap here.");
11743 SDLoc dl(Op);
11744 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
11745 EVT MemVT = AtomicNode->getMemoryVT();
11746 if (MemVT.getSizeInBits() >= 32)
11747 return Op;
11748
11749 SDValue CmpOp = Op.getOperand(2);
11750 // If this is already correctly zero-extended, leave it alone.
11751 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
11752 if (DAG.MaskedValueIsZero(CmpOp, HighBits))
11753 return Op;
11754
11755 // Clear the high bits of the compare operand.
11756 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
11757 SDValue NewCmpOp =
11758 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
11759 DAG.getConstant(MaskVal, dl, MVT::i32));
11760
11761 // Replace the existing compare operand with the properly zero-extended one.
11763 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
11764 Ops.push_back(AtomicNode->getOperand(i));
11765 Ops[2] = NewCmpOp;
11766 MachineMemOperand *MMO = AtomicNode->getMemOperand();
11767 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
11768 auto NodeTy =
11769 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
11770 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
11771}
11772
11773SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
11774 SelectionDAG &DAG) const {
11775 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
11776 EVT MemVT = N->getMemoryVT();
11777 assert(MemVT.getSimpleVT() == MVT::i128 &&
11778 "Expect quadword atomic operations");
11779 SDLoc dl(N);
11780 unsigned Opc = N->getOpcode();
11781 switch (Opc) {
11782 case ISD::ATOMIC_LOAD: {
11783 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
11784 // lowered to ppc instructions by pattern matching instruction selector.
11785 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
11787 N->getOperand(0),
11788 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
11789 for (int I = 1, E = N->getNumOperands(); I < E; ++I)
11790 Ops.push_back(N->getOperand(I));
11791 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
11792 Ops, MemVT, N->getMemOperand());
11793 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
11794 SDValue ValHi =
11795 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
11796 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
11797 DAG.getConstant(64, dl, MVT::i32));
11798 SDValue Val =
11799 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
11800 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
11801 {Val, LoadedVal.getValue(2)});
11802 }
11803 case ISD::ATOMIC_STORE: {
11804 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
11805 // lowered to ppc instructions by pattern matching instruction selector.
11806 SDVTList Tys = DAG.getVTList(MVT::Other);
11808 N->getOperand(0),
11809 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
11810 SDValue Val = N->getOperand(1);
11811 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
11812 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
11813 DAG.getConstant(64, dl, MVT::i32));
11814 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
11815 Ops.push_back(ValLo);
11816 Ops.push_back(ValHi);
11817 Ops.push_back(N->getOperand(2));
11818 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
11819 N->getMemOperand());
11820 }
11821 default:
11822 llvm_unreachable("Unexpected atomic opcode");
11823 }
11824}
11825
11827 SelectionDAG &DAG,
11828 const PPCSubtarget &Subtarget) {
11829 assert(Mask <= fcAllFlags && "Invalid fp_class flags!");
11830
11831 enum DataClassMask {
11832 DC_NAN = 1 << 6,
11833 DC_NEG_INF = 1 << 4,
11834 DC_POS_INF = 1 << 5,
11835 DC_NEG_ZERO = 1 << 2,
11836 DC_POS_ZERO = 1 << 3,
11837 DC_NEG_SUBNORM = 1,
11838 DC_POS_SUBNORM = 1 << 1,
11839 };
11840
11841 EVT VT = Op.getValueType();
11842
11843 unsigned TestOp = VT == MVT::f128 ? PPC::XSTSTDCQP
11844 : VT == MVT::f64 ? PPC::XSTSTDCDP
11845 : PPC::XSTSTDCSP;
11846
11847 if (Mask == fcAllFlags)
11848 return DAG.getBoolConstant(true, Dl, MVT::i1, VT);
11849 if (Mask == 0)
11850 return DAG.getBoolConstant(false, Dl, MVT::i1, VT);
11851
11852 // When it's cheaper or necessary to test reverse flags.
11853 if ((Mask & fcNormal) == fcNormal || Mask == ~fcQNan || Mask == ~fcSNan) {
11854 SDValue Rev = getDataClassTest(Op, ~Mask, Dl, DAG, Subtarget);
11855 return DAG.getNOT(Dl, Rev, MVT::i1);
11856 }
11857
11858 // Power doesn't support testing whether a value is 'normal'. Test the rest
11859 // first, and test if it's 'not not-normal' with expected sign.
11860 if (Mask & fcNormal) {
11861 SDValue Rev(DAG.getMachineNode(
11862 TestOp, Dl, MVT::i32,
11863 DAG.getTargetConstant(DC_NAN | DC_NEG_INF | DC_POS_INF |
11864 DC_NEG_ZERO | DC_POS_ZERO |
11865 DC_NEG_SUBNORM | DC_POS_SUBNORM,
11866 Dl, MVT::i32),
11867 Op),
11868 0);
11869 // Sign are stored in CR bit 0, result are in CR bit 2.
11870 SDValue Sign(
11871 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11872 DAG.getTargetConstant(PPC::sub_lt, Dl, MVT::i32)),
11873 0);
11874 SDValue Normal(DAG.getNOT(
11875 Dl,
11877 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11878 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11879 0),
11880 MVT::i1));
11881 if (Mask & fcPosNormal)
11882 Sign = DAG.getNOT(Dl, Sign, MVT::i1);
11883 SDValue Result = DAG.getNode(ISD::AND, Dl, MVT::i1, Sign, Normal);
11884 if (Mask == fcPosNormal || Mask == fcNegNormal)
11885 return Result;
11886
11887 return DAG.getNode(
11888 ISD::OR, Dl, MVT::i1,
11889 getDataClassTest(Op, Mask & ~fcNormal, Dl, DAG, Subtarget), Result);
11890 }
11891
11892 // The instruction doesn't differentiate between signaling or quiet NaN. Test
11893 // the rest first, and test if it 'is NaN and is signaling/quiet'.
11894 if ((Mask & fcNan) == fcQNan || (Mask & fcNan) == fcSNan) {
11895 bool IsQuiet = Mask & fcQNan;
11896 SDValue NanCheck = getDataClassTest(Op, fcNan, Dl, DAG, Subtarget);
11897
11898 // Quietness is determined by the first bit in fraction field.
11899 uint64_t QuietMask = 0;
11900 SDValue HighWord;
11901 if (VT == MVT::f128) {
11902 HighWord = DAG.getNode(
11903 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, DAG.getBitcast(MVT::v4i32, Op),
11904 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 3 : 0, Dl));
11905 QuietMask = 0x8000;
11906 } else if (VT == MVT::f64) {
11907 if (Subtarget.isPPC64()) {
11908 HighWord = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32,
11909 DAG.getBitcast(MVT::i64, Op),
11910 DAG.getConstant(1, Dl, MVT::i32));
11911 } else {
11912 SDValue Vec = DAG.getBitcast(
11913 MVT::v4i32, DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v2f64, Op));
11914 HighWord = DAG.getNode(
11915 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, Vec,
11916 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 1 : 0, Dl));
11917 }
11918 QuietMask = 0x80000;
11919 } else if (VT == MVT::f32) {
11920 HighWord = DAG.getBitcast(MVT::i32, Op);
11921 QuietMask = 0x400000;
11922 }
11923 SDValue NanRes = DAG.getSetCC(
11924 Dl, MVT::i1,
11925 DAG.getNode(ISD::AND, Dl, MVT::i32, HighWord,
11926 DAG.getConstant(QuietMask, Dl, MVT::i32)),
11927 DAG.getConstant(0, Dl, MVT::i32), IsQuiet ? ISD::SETNE : ISD::SETEQ);
11928 NanRes = DAG.getNode(ISD::AND, Dl, MVT::i1, NanCheck, NanRes);
11929 if (Mask == fcQNan || Mask == fcSNan)
11930 return NanRes;
11931
11932 return DAG.getNode(ISD::OR, Dl, MVT::i1,
11933 getDataClassTest(Op, Mask & ~fcNan, Dl, DAG, Subtarget),
11934 NanRes);
11935 }
11936
11937 unsigned NativeMask = 0;
11938 if ((Mask & fcNan) == fcNan)
11939 NativeMask |= DC_NAN;
11940 if (Mask & fcNegInf)
11941 NativeMask |= DC_NEG_INF;
11942 if (Mask & fcPosInf)
11943 NativeMask |= DC_POS_INF;
11944 if (Mask & fcNegZero)
11945 NativeMask |= DC_NEG_ZERO;
11946 if (Mask & fcPosZero)
11947 NativeMask |= DC_POS_ZERO;
11948 if (Mask & fcNegSubnormal)
11949 NativeMask |= DC_NEG_SUBNORM;
11950 if (Mask & fcPosSubnormal)
11951 NativeMask |= DC_POS_SUBNORM;
11952 return SDValue(
11953 DAG.getMachineNode(
11954 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1,
11956 TestOp, Dl, MVT::i32,
11957 DAG.getTargetConstant(NativeMask, Dl, MVT::i32), Op),
11958 0),
11959 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11960 0);
11961}
11962
11963SDValue PPCTargetLowering::LowerIS_FPCLASS(SDValue Op,
11964 SelectionDAG &DAG) const {
11965 assert(Subtarget.hasP9Vector() && "Test data class requires Power9");
11966 SDValue LHS = Op.getOperand(0);
11967 uint64_t RHSC = Op.getConstantOperandVal(1);
11968 SDLoc Dl(Op);
11969 FPClassTest Category = static_cast<FPClassTest>(RHSC);
11970 if (LHS.getValueType() == MVT::ppcf128) {
11971 // The higher part determines the value class.
11972 LHS = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::f64, LHS,
11973 DAG.getConstant(1, Dl, MVT::i32));
11974 }
11975
11976 return getDataClassTest(LHS, Category, Dl, DAG, Subtarget);
11977}
11978
11979// Adjust the length value for a load/store with length to account for the
11980// instructions requiring a left justified length, and for non-byte element
11981// types requiring scaling by element size.
11982static SDValue AdjustLength(SDValue Val, unsigned Bits, bool Left,
11983 SelectionDAG &DAG) {
11984 SDLoc dl(Val);
11985 EVT VT = Val->getValueType(0);
11986 unsigned LeftAdj = Left ? VT.getSizeInBits() - 8 : 0;
11987 unsigned TypeAdj = llvm::countr_zero<uint32_t>(Bits / 8);
11988 SDValue SHLAmt = DAG.getConstant(LeftAdj + TypeAdj, dl, VT);
11989 return DAG.getNode(ISD::SHL, dl, VT, Val, SHLAmt);
11990}
11991
11992SDValue PPCTargetLowering::LowerVP_LOAD(SDValue Op, SelectionDAG &DAG) const {
11993 auto VPLD = cast<VPLoadSDNode>(Op);
11994 bool Future = Subtarget.isISAFuture();
11995 SDLoc dl(Op);
11996 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(3).getNode(), true) &&
11997 "Mask predication not supported");
11998 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11999 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPLD->getOperand(4));
12000 unsigned IID = Future ? Intrinsic::ppc_vsx_lxvrl : Intrinsic::ppc_vsx_lxvl;
12001 unsigned EltBits = Op->getValueType(0).getScalarType().getSizeInBits();
12002 Len = AdjustLength(Len, EltBits, !Future, DAG);
12003 SDValue Ops[] = {VPLD->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12004 VPLD->getOperand(1), Len};
12005 SDVTList Tys = DAG.getVTList(Op->getValueType(0), MVT::Other);
12006 SDValue VPL =
12008 VPLD->getMemoryVT(), VPLD->getMemOperand());
12009 return VPL;
12010}
12011
12012SDValue PPCTargetLowering::LowerVP_STORE(SDValue Op, SelectionDAG &DAG) const {
12013 auto VPST = cast<VPStoreSDNode>(Op);
12014 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(4).getNode(), true) &&
12015 "Mask predication not supported");
12016 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12017 SDLoc dl(Op);
12018 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPST->getOperand(5));
12019 unsigned EltBits =
12020 Op->getOperand(1).getValueType().getScalarType().getSizeInBits();
12021 bool Future = Subtarget.isISAFuture();
12022 unsigned IID = Future ? Intrinsic::ppc_vsx_stxvrl : Intrinsic::ppc_vsx_stxvl;
12023 Len = AdjustLength(Len, EltBits, !Future, DAG);
12024 SDValue Ops[] = {
12025 VPST->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12026 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, VPST->getOperand(1)),
12027 VPST->getOperand(2), Len};
12028 SDVTList Tys = DAG.getVTList(MVT::Other);
12029 SDValue VPS =
12031 VPST->getMemoryVT(), VPST->getMemOperand());
12032 return VPS;
12033}
12034
12035SDValue PPCTargetLowering::LowerPartialReduce(SDValue Op,
12036 SelectionDAG &DAG) const {
12037 SDValue Acc = Op.getOperand(0);
12038 SDValue Op1 = Op.getOperand(1);
12039 SDValue Op2 = Op.getOperand(2);
12040
12041 assert(Op.getOpcode() == ISD::PARTIAL_REDUCE_UMLA &&
12042 "Unexpected partial reduction");
12043
12044 if (Acc.getValueType() != MVT::v4i32)
12045 return SDValue();
12046 if (Op1.getValueType() != MVT::v16i32 || Op1.getOpcode() != ISD::SIGN_EXTEND)
12047 return SDValue();
12048 SDValue Op1Input = Op1.getOperand(0);
12049 if (Op1Input.getValueType() != MVT::v16i8 || !llvm::isOneOrOneSplat(Op2))
12050 return SDValue();
12051
12052 SDLoc dl(Op);
12053 SDValue Ones = DAG.getConstant(1, dl, MVT::v16i8);
12054 return DAG.getNode(ISD::PARTIAL_REDUCE_SUMLA, dl, MVT::v4i32, Acc, Op1Input,
12055 Ones);
12056}
12057
12058SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
12059 SelectionDAG &DAG) const {
12060 SDLoc dl(Op);
12061
12062 MachineFunction &MF = DAG.getMachineFunction();
12063 SDValue Op0 = Op.getOperand(0);
12064 EVT ValVT = Op0.getValueType();
12065 unsigned EltSize = Op.getValueType().getScalarSizeInBits();
12066 if (isa<ConstantSDNode>(Op0) && EltSize <= 32) {
12067 int64_t IntVal = Op.getConstantOperandVal(0);
12068 if (IntVal >= -16 && IntVal <= 15)
12069 return getCanonicalConstSplat(IntVal, EltSize / 8, Op.getValueType(), DAG,
12070 dl);
12071 }
12072
12073 ReuseLoadInfo RLI;
12074 if (Subtarget.hasLFIWAX() && Subtarget.hasVSX() &&
12075 Op.getValueType() == MVT::v4i32 && Op0.getOpcode() == ISD::LOAD &&
12076 Op0.getValueType() == MVT::i32 && Op0.hasOneUse() &&
12077 canReuseLoadAddress(Op0, MVT::i32, RLI, DAG, ISD::NON_EXTLOAD)) {
12078
12079 MachineMemOperand *MMO =
12081 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
12082 SDValue Ops[] = {RLI.Chain, RLI.Ptr, DAG.getValueType(Op.getValueType())};
12084 PPCISD::LD_SPLAT, dl, DAG.getVTList(MVT::v4i32, MVT::Other), Ops,
12085 MVT::i32, MMO);
12086 if (RLI.ResChain)
12087 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
12088 return Bits.getValue(0);
12089 }
12090
12091 // Create a stack slot that is 16-byte aligned.
12092 MachineFrameInfo &MFI = MF.getFrameInfo();
12093 int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
12094 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12095 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
12096
12097 SDValue Val = Op0;
12098 // P10 hardware store forwarding requires that a single store contains all
12099 // the data for the load. P10 is able to merge a pair of adjacent stores. Try
12100 // to avoid load hit store on P10 when running binaries compiled for older
12101 // processors by generating two mergeable scalar stores to forward with the
12102 // vector load.
12103 if (!DisableP10StoreForward && Subtarget.isPPC64() &&
12104 !Subtarget.isLittleEndian() && ValVT.isInteger() &&
12105 ValVT.getSizeInBits() <= 64) {
12106 Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, Val);
12107 EVT ShiftAmountTy = getShiftAmountTy(MVT::i64, DAG.getDataLayout());
12108 SDValue ShiftBy = DAG.getConstant(
12109 64 - Op.getValueType().getScalarSizeInBits(), dl, ShiftAmountTy);
12110 Val = DAG.getNode(ISD::SHL, dl, MVT::i64, Val, ShiftBy);
12111 SDValue Plus8 =
12112 DAG.getNode(ISD::ADD, dl, PtrVT, FIdx, DAG.getConstant(8, dl, PtrVT));
12113 SDValue Store2 =
12114 DAG.getStore(DAG.getEntryNode(), dl, Val, Plus8, MachinePointerInfo());
12115 SDValue Store = DAG.getStore(Store2, dl, Val, FIdx, MachinePointerInfo());
12116 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx,
12117 MachinePointerInfo());
12118 }
12119
12120 // Store the input value into Value#0 of the stack slot.
12121 SDValue Store =
12122 DAG.getStore(DAG.getEntryNode(), dl, Val, FIdx, MachinePointerInfo());
12123 // Load it out.
12124 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
12125}
12126
12127SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12128 SelectionDAG &DAG) const {
12129 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12130 "Should only be called for ISD::INSERT_VECTOR_ELT");
12131
12132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
12133
12134 EVT VT = Op.getValueType();
12135 SDLoc dl(Op);
12136 SDValue V1 = Op.getOperand(0);
12137 SDValue V2 = Op.getOperand(1);
12138
12139 if (VT == MVT::v2f64 && C)
12140 return Op;
12141
12142 if (Subtarget.hasP9Vector()) {
12143 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
12144 // because on P10, it allows this specific insert_vector_elt load pattern to
12145 // utilize the refactored load and store infrastructure in order to exploit
12146 // prefixed loads.
12147 // On targets with inexpensive direct moves (Power9 and up), a
12148 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
12149 // load since a single precision load will involve conversion to double
12150 // precision on the load followed by another conversion to single precision.
12151 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
12152 (isa<LoadSDNode>(V2))) {
12153 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
12154 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
12155 SDValue InsVecElt =
12156 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
12157 BitcastLoad, Op.getOperand(2));
12158 return DAG.getBitcast(MVT::v4f32, InsVecElt);
12159 }
12160 }
12161
12162 if (Subtarget.isISA3_1()) {
12163 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
12164 return SDValue();
12165 // On P10, we have legal lowering for constant and variable indices for
12166 // all vectors.
12167 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
12168 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
12169 return Op;
12170 }
12171
12172 // Before P10, we have legal lowering for constant indices but not for
12173 // variable ones.
12174 if (!C)
12175 return SDValue();
12176
12177 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
12178 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
12179 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
12180 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
12181 unsigned InsertAtElement = C->getZExtValue();
12182 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
12183 if (Subtarget.isLittleEndian()) {
12184 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
12185 }
12186 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
12187 DAG.getConstant(InsertAtByte, dl, MVT::i32));
12188 }
12189 return Op;
12190}
12191
12192SDValue PPCTargetLowering::LowerDMFVectorLoad(SDValue Op,
12193 SelectionDAG &DAG) const {
12194 SDLoc dl(Op);
12195 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12196 SDValue LoadChain = LN->getChain();
12197 SDValue BasePtr = LN->getBasePtr();
12198 EVT VT = Op.getValueType();
12199 bool IsV1024i1 = VT == MVT::v1024i1;
12200 bool IsV2048i1 = VT == MVT::v2048i1;
12201
12202 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12203 // Dense Math dmr pair registers, respectively.
12204 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12205 (void)IsV2048i1;
12206 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12207 "Dense Math support required.");
12208 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12209
12211 SmallVector<SDValue, 8> LoadChains;
12212
12213 SDValue IntrinID = DAG.getConstant(Intrinsic::ppc_vsx_lxvp, dl, MVT::i32);
12214 SDValue LoadOps[] = {LoadChain, IntrinID, BasePtr};
12215 MachineMemOperand *MMO = LN->getMemOperand();
12216 unsigned NumVecs = VT.getSizeInBits() / 256;
12217 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12218 MachineMemOperand *NewMMO =
12219 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12220 if (Idx > 0) {
12221 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12222 DAG.getConstant(32, dl, BasePtr.getValueType()));
12223 LoadOps[2] = BasePtr;
12224 }
12226 DAG.getVTList(MVT::v256i1, MVT::Other),
12227 LoadOps, MVT::v256i1, NewMMO);
12228 LoadChains.push_back(Ld.getValue(1));
12229 Loads.push_back(Ld);
12230 }
12231
12232 if (Subtarget.isLittleEndian()) {
12233 std::reverse(Loads.begin(), Loads.end());
12234 std::reverse(LoadChains.begin(), LoadChains.end());
12235 }
12236
12237 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12238 SDValue Value = DMFInsert1024(Loads, dl, DAG);
12239
12240 if (IsV1024i1) {
12241 return DAG.getMergeValues({Value, TF}, dl);
12242 }
12243
12244 // Handle Loads for V2048i1 which represents a dmr pair.
12245 SmallVector<SDValue, 4> MoreLoads{Loads[4], Loads[5], Loads[6], Loads[7]};
12246 SDValue Dmr1Value = DMFInsert1024(MoreLoads, dl, DAG);
12247
12248 SDValue Dmr0Sub = DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32);
12249 SDValue Dmr1Sub = DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32);
12250
12251 SDValue DmrPRC = DAG.getTargetConstant(PPC::DMRpRCRegClassID, dl, MVT::i32);
12252 const SDValue DmrPOps[] = {DmrPRC, Value, Dmr0Sub, Dmr1Value, Dmr1Sub};
12253
12254 SDValue DmrPValue = SDValue(
12255 DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v2048i1, DmrPOps), 0);
12256
12257 return DAG.getMergeValues({DmrPValue, TF}, dl);
12258}
12259
12260SDValue PPCTargetLowering::DMFInsert1024(const SmallVectorImpl<SDValue> &Pairs,
12261 const SDLoc &dl,
12262 SelectionDAG &DAG) const {
12263 SDValue Lo =
12264 DAG.getNode(PPCISD::INST512, dl, MVT::v512i1, Pairs[0], Pairs[1]);
12265 SDValue LoSub = DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32);
12266 SDValue Hi =
12267 DAG.getNode(PPCISD::INST512HI, dl, MVT::v512i1, Pairs[2], Pairs[3]);
12268 SDValue HiSub = DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32);
12269 SDValue RC = DAG.getTargetConstant(PPC::DMRRCRegClassID, dl, MVT::i32);
12270
12271 return SDValue(DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v1024i1,
12272 {RC, Lo, LoSub, Hi, HiSub}),
12273 0);
12274}
12275
12276SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
12277 SelectionDAG &DAG) const {
12278 SDLoc dl(Op);
12279 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12280 SDValue LoadChain = LN->getChain();
12281 SDValue BasePtr = LN->getBasePtr();
12282 EVT VT = Op.getValueType();
12283
12284 if (VT == MVT::v1024i1 || VT == MVT::v2048i1)
12285 return LowerDMFVectorLoad(Op, DAG);
12286
12287 if (VT != MVT::v256i1 && VT != MVT::v512i1)
12288 return Op;
12289
12290 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12291 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
12292 "Type unsupported without MMA");
12293 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12294 "Type unsupported without paired vector support");
12295
12296 // For v256i1 on ISA Future, let the load go through to instruction selection
12297 // where it will be matched to lxvp/plxvp by the instruction patterns.
12298 if (VT == MVT::v256i1 && Subtarget.isISAFuture())
12299 return Op;
12300
12301 // For other cases, create 2 or 4 v16i8 loads to load the pair or accumulator
12302 // value in 2 or 4 vsx registers.
12303 Align Alignment = LN->getAlign();
12305 SmallVector<SDValue, 4> LoadChains;
12306 unsigned NumVecs = VT.getSizeInBits() / 128;
12307 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12308 SDValue Load =
12309 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
12310 LN->getPointerInfo().getWithOffset(Idx * 16),
12311 commonAlignment(Alignment, Idx * 16),
12312 LN->getMemOperand()->getFlags(), LN->getAAInfo());
12313 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12314 DAG.getConstant(16, dl, BasePtr.getValueType()));
12315 Loads.push_back(Load);
12316 LoadChains.push_back(Load.getValue(1));
12317 }
12318 if (Subtarget.isLittleEndian()) {
12319 std::reverse(Loads.begin(), Loads.end());
12320 std::reverse(LoadChains.begin(), LoadChains.end());
12321 }
12322 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12323 SDValue Value =
12324 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
12325 dl, VT, Loads);
12326 SDValue RetOps[] = {Value, TF};
12327 return DAG.getMergeValues(RetOps, dl);
12328}
12329
12330SDValue PPCTargetLowering::LowerDMFVectorStore(SDValue Op,
12331 SelectionDAG &DAG) const {
12332
12333 SDLoc dl(Op);
12334 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12335 SDValue StoreChain = SN->getChain();
12336 SDValue BasePtr = SN->getBasePtr();
12339 EVT VT = SN->getValue().getValueType();
12340 bool IsV1024i1 = VT == MVT::v1024i1;
12341 bool IsV2048i1 = VT == MVT::v2048i1;
12342
12343 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12344 // Dense Math dmr pair registers, respectively.
12345 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12346 (void)IsV2048i1;
12347 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12348 "Dense Math support required.");
12349 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12350
12351 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12352 if (IsV1024i1) {
12354 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12355 Op.getOperand(1),
12356 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12357 0);
12359 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12360 Op.getOperand(1),
12361 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12362 0);
12363 MachineSDNode *ExtNode =
12364 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Lo);
12365 Values.push_back(SDValue(ExtNode, 0));
12366 Values.push_back(SDValue(ExtNode, 1));
12367 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Hi);
12368 Values.push_back(SDValue(ExtNode, 0));
12369 Values.push_back(SDValue(ExtNode, 1));
12370 } else {
12371 // This corresponds to v2048i1 which represents a dmr pair.
12372 SDValue Dmr0(
12373 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12374 Op.getOperand(1),
12375 DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32)),
12376 0);
12377
12378 SDValue Dmr1(
12379 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12380 Op.getOperand(1),
12381 DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32)),
12382 0);
12383
12384 SDValue Dmr0Lo(DAG.getMachineNode(
12385 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12386 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12387 0);
12388
12389 SDValue Dmr0Hi(DAG.getMachineNode(
12390 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12391 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12392 0);
12393
12394 SDValue Dmr1Lo(DAG.getMachineNode(
12395 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12396 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12397 0);
12398
12399 SDValue Dmr1Hi(DAG.getMachineNode(
12400 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12401 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12402 0);
12403
12404 MachineSDNode *ExtNode =
12405 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr0Lo);
12406 Values.push_back(SDValue(ExtNode, 0));
12407 Values.push_back(SDValue(ExtNode, 1));
12408 ExtNode =
12409 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr0Hi);
12410 Values.push_back(SDValue(ExtNode, 0));
12411 Values.push_back(SDValue(ExtNode, 1));
12412 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr1Lo);
12413 Values.push_back(SDValue(ExtNode, 0));
12414 Values.push_back(SDValue(ExtNode, 1));
12415 ExtNode =
12416 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr1Hi);
12417 Values.push_back(SDValue(ExtNode, 0));
12418 Values.push_back(SDValue(ExtNode, 1));
12419 }
12420
12421 if (Subtarget.isLittleEndian())
12422 std::reverse(Values.begin(), Values.end());
12423
12424 SDVTList Tys = DAG.getVTList(MVT::Other);
12426 StoreChain, DAG.getConstant(Intrinsic::ppc_vsx_stxvp, dl, MVT::i32),
12427 Values[0], BasePtr};
12428 MachineMemOperand *MMO = SN->getMemOperand();
12429 unsigned NumVecs = VT.getSizeInBits() / 256;
12430 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12431 MachineMemOperand *NewMMO =
12432 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12433 if (Idx > 0) {
12434 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12435 DAG.getConstant(32, dl, BasePtr.getValueType()));
12436 Ops[3] = BasePtr;
12437 }
12438 Ops[2] = Values[Idx];
12440 MVT::v256i1, NewMMO);
12441 Stores.push_back(St);
12442 }
12443
12444 SDValue TF = DAG.getTokenFactor(dl, Stores);
12445 return TF;
12446}
12447
12448SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
12449 SelectionDAG &DAG) const {
12450 SDLoc dl(Op);
12451 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12452 SDValue StoreChain = SN->getChain();
12453 SDValue BasePtr = SN->getBasePtr();
12454 SDValue Value = SN->getValue();
12455 SDValue Value2 = SN->getValue();
12456 EVT StoreVT = Value.getValueType();
12457
12458 if (StoreVT == MVT::v1024i1 || StoreVT == MVT::v2048i1)
12459 return LowerDMFVectorStore(Op, DAG);
12460
12461 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
12462 return Op;
12463
12464 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12465 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
12466 "Type unsupported without MMA");
12467 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12468 "Type unsupported without paired vector support");
12469
12470 // For v256i1 on ISA Future, let the store go through to instruction selection
12471 // where it will be matched to stxvp/pstxvp by the instruction patterns.
12472 if (StoreVT == MVT::v256i1 && Subtarget.isISAFuture() &&
12474 return Op;
12475
12476 // For other cases, create 2 or 4 v16i8 stores to store the pair or
12477 // accumulator underlying registers individually.
12478 Align Alignment = SN->getAlign();
12480 unsigned NumVecs = 2;
12481 if (StoreVT == MVT::v512i1) {
12482 if (Subtarget.isISAFuture()) {
12483 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12484 MachineSDNode *ExtNode = DAG.getMachineNode(
12485 PPC::DMXXEXTFDMR512, dl, ReturnTypes, Op.getOperand(1));
12486
12487 Value = SDValue(ExtNode, 0);
12488 Value2 = SDValue(ExtNode, 1);
12489 } else
12490 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
12491 NumVecs = 4;
12492 }
12493 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12494 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
12495 SDValue Elt;
12496 if (Subtarget.isISAFuture()) {
12497 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2);
12498 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
12499 Idx > 1 ? Value2 : Value,
12500 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12501 } else
12502 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
12503 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12504
12505 SDValue Store =
12506 DAG.getStore(StoreChain, dl, Elt, BasePtr,
12507 SN->getPointerInfo().getWithOffset(Idx * 16),
12508 commonAlignment(Alignment, Idx * 16),
12509 SN->getMemOperand()->getFlags(), SN->getAAInfo());
12510 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12511 DAG.getConstant(16, dl, BasePtr.getValueType()));
12512 Stores.push_back(Store);
12513 }
12514 SDValue TF = DAG.getTokenFactor(dl, Stores);
12515 return TF;
12516}
12517
12518SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
12519 SDLoc dl(Op);
12520 if (Op.getValueType() == MVT::v4i32) {
12521 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12522
12523 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
12524 // +16 as shift amt.
12525 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
12526 SDValue RHSSwap = // = vrlw RHS, 16
12527 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
12528
12529 // Shrinkify inputs to v8i16.
12530 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
12531 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
12532 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
12533
12534 // Low parts multiplied together, generating 32-bit results (we ignore the
12535 // top parts).
12536 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
12537 LHS, RHS, DAG, dl, MVT::v4i32);
12538
12539 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
12540 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
12541 // Shift the high parts up 16 bits.
12542 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
12543 Neg16, DAG, dl);
12544 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
12545 } else if (Op.getValueType() == MVT::v16i8) {
12546 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12547 bool isLittleEndian = Subtarget.isLittleEndian();
12548
12549 // Multiply the even 8-bit parts, producing 16-bit sums.
12550 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
12551 LHS, RHS, DAG, dl, MVT::v8i16);
12552 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
12553
12554 // Multiply the odd 8-bit parts, producing 16-bit sums.
12555 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
12556 LHS, RHS, DAG, dl, MVT::v8i16);
12557 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
12558
12559 // Merge the results together. Because vmuleub and vmuloub are
12560 // instructions with a big-endian bias, we must reverse the
12561 // element numbering and reverse the meaning of "odd" and "even"
12562 // when generating little endian code.
12563 int Ops[16];
12564 for (unsigned i = 0; i != 8; ++i) {
12565 if (isLittleEndian) {
12566 Ops[i*2 ] = 2*i;
12567 Ops[i*2+1] = 2*i+16;
12568 } else {
12569 Ops[i*2 ] = 2*i+1;
12570 Ops[i*2+1] = 2*i+1+16;
12571 }
12572 }
12573 if (isLittleEndian)
12574 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
12575 else
12576 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
12577 } else {
12578 llvm_unreachable("Unknown mul to lower!");
12579 }
12580}
12581
12582SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12583 bool IsStrict = Op->isStrictFPOpcode();
12584 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
12585 !Subtarget.hasP9Vector())
12586 return SDValue();
12587
12588 return Op;
12589}
12590
12591// Custom lowering for fpext vf32 to v2f64
12592SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12593
12594 assert(Op.getOpcode() == ISD::FP_EXTEND &&
12595 "Should only be called for ISD::FP_EXTEND");
12596
12597 // FIXME: handle extends from half precision float vectors on P9.
12598 // We only want to custom lower an extend from v2f32 to v2f64.
12599 if (Op.getValueType() != MVT::v2f64 ||
12600 Op.getOperand(0).getValueType() != MVT::v2f32)
12601 return SDValue();
12602
12603 SDLoc dl(Op);
12604 SDValue Op0 = Op.getOperand(0);
12605
12606 switch (Op0.getOpcode()) {
12607 default:
12608 return SDValue();
12610 assert(Op0.getNumOperands() == 2 &&
12612 "Node should have 2 operands with second one being a constant!");
12613
12614 if (Op0.getOperand(0).getValueType() != MVT::v4f32)
12615 return SDValue();
12616
12617 // Custom lower is only done for high or low doubleword.
12618 int Idx = Op0.getConstantOperandVal(1);
12619 if (Idx % 2 != 0)
12620 return SDValue();
12621
12622 // Since input is v4f32, at this point Idx is either 0 or 2.
12623 // Shift to get the doubleword position we want.
12624 int DWord = Idx >> 1;
12625
12626 // High and low word positions are different on little endian.
12627 if (Subtarget.isLittleEndian())
12628 DWord ^= 0x1;
12629
12630 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
12631 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
12632 }
12633 case ISD::FADD:
12634 case ISD::FMUL:
12635 case ISD::FSUB: {
12636 SDValue NewLoad[2];
12637 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
12638 // Ensure both input are loads.
12639 SDValue LdOp = Op0.getOperand(i);
12640 if (LdOp.getOpcode() != ISD::LOAD)
12641 return SDValue();
12642 // Generate new load node.
12643 LoadSDNode *LD = cast<LoadSDNode>(LdOp);
12644 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12645 NewLoad[i] = DAG.getMemIntrinsicNode(
12646 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12647 LD->getMemoryVT(), LD->getMemOperand());
12648 }
12649 SDValue NewOp =
12650 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
12651 NewLoad[1], Op0.getNode()->getFlags());
12652 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
12653 DAG.getConstant(0, dl, MVT::i32));
12654 }
12655 case ISD::LOAD: {
12656 LoadSDNode *LD = cast<LoadSDNode>(Op0);
12657 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12658 SDValue NewLd = DAG.getMemIntrinsicNode(
12659 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12660 LD->getMemoryVT(), LD->getMemOperand());
12661 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
12662 DAG.getConstant(0, dl, MVT::i32));
12663 }
12664 }
12665 llvm_unreachable("ERROR:Should return for all cases within swtich.");
12666}
12667
12669 SelectionDAG &DAG,
12670 const PPCSubtarget &STI) {
12671 SDLoc DL(Value);
12672 if (STI.useCRBits())
12673 Value = DAG.getNode(ISD::SELECT, DL, SumType, Value,
12674 DAG.getConstant(1, DL, SumType),
12675 DAG.getConstant(0, DL, SumType));
12676 else
12677 Value = DAG.getZExtOrTrunc(Value, DL, SumType);
12678 SDValue Sum = DAG.getNode(PPCISD::ADDC, DL, DAG.getVTList(SumType, MVT::i32),
12679 Value, DAG.getAllOnesConstant(DL, SumType));
12680 return Sum.getValue(1);
12681}
12682
12684 EVT CarryType, SelectionDAG &DAG,
12685 const PPCSubtarget &STI) {
12686 SDLoc DL(Flag);
12687 SDValue Zero = DAG.getConstant(0, DL, SumType);
12688 SDValue Carry = DAG.getNode(
12689 PPCISD::ADDE, DL, DAG.getVTList(SumType, MVT::i32), Zero, Zero, Flag);
12690 if (STI.useCRBits())
12691 return DAG.getSetCC(DL, CarryType, Carry, Zero, ISD::SETNE);
12692 return DAG.getZExtOrTrunc(Carry, DL, CarryType);
12693}
12694
12695SDValue PPCTargetLowering::LowerADDSUBO(SDValue Op, SelectionDAG &DAG) const {
12696
12697 SDLoc DL(Op);
12698 SDNode *N = Op.getNode();
12699 EVT VT = N->getValueType(0);
12700 EVT CarryType = N->getValueType(1);
12701 unsigned Opc = N->getOpcode();
12702 bool IsAdd = Opc == ISD::UADDO;
12703 Opc = IsAdd ? PPCISD::ADDC : PPCISD::SUBC;
12704 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12705 N->getOperand(0), N->getOperand(1));
12706 SDValue Carry = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType,
12707 DAG, Subtarget);
12708 if (!IsAdd)
12709 Carry = DAG.getNode(ISD::XOR, DL, CarryType, Carry,
12710 DAG.getConstant(1UL, DL, CarryType));
12711 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, Carry);
12712}
12713
12714SDValue PPCTargetLowering::LowerADDSUBO_CARRY(SDValue Op,
12715 SelectionDAG &DAG) const {
12716 SDLoc DL(Op);
12717 SDNode *N = Op.getNode();
12718 unsigned Opc = N->getOpcode();
12719 EVT VT = N->getValueType(0);
12720 EVT CarryType = N->getValueType(1);
12721 SDValue CarryOp = N->getOperand(2);
12722 bool IsAdd = Opc == ISD::UADDO_CARRY;
12723 Opc = IsAdd ? PPCISD::ADDE : PPCISD::SUBE;
12724 if (!IsAdd)
12725 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12726 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12727 CarryOp = ConvertCarryValueToCarryFlag(VT, CarryOp, DAG, Subtarget);
12728 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12729 Op.getOperand(0), Op.getOperand(1), CarryOp);
12730 CarryOp = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType, DAG,
12731 Subtarget);
12732 if (!IsAdd)
12733 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12734 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12735 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, CarryOp);
12736}
12737
12738SDValue PPCTargetLowering::LowerSSUBO(SDValue Op, SelectionDAG &DAG) const {
12739
12740 SDLoc dl(Op);
12741 SDValue LHS = Op.getOperand(0);
12742 SDValue RHS = Op.getOperand(1);
12743 EVT VT = Op.getNode()->getValueType(0);
12744
12745 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12746
12747 SDValue Xor1 = DAG.getNode(ISD::XOR, dl, VT, RHS, LHS);
12748 SDValue Xor2 = DAG.getNode(ISD::XOR, dl, VT, Sub, LHS);
12749
12750 SDValue And = DAG.getNode(ISD::AND, dl, VT, Xor1, Xor2);
12751
12752 SDValue Overflow =
12753 DAG.getNode(ISD::SRL, dl, VT, And,
12754 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12755
12756 SDValue OverflowTrunc =
12757 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12758
12759 return DAG.getMergeValues({Sub, OverflowTrunc}, dl);
12760}
12761
12762/// Implements signed add with overflow detection using the rule:
12763/// (x eqv y) & (sum xor x), where the overflow bit is extracted from the sign
12764SDValue PPCTargetLowering::LowerSADDO(SDValue Op, SelectionDAG &DAG) const {
12765
12766 SDLoc dl(Op);
12767 SDValue LHS = Op.getOperand(0);
12768 SDValue RHS = Op.getOperand(1);
12769 EVT VT = Op.getNode()->getValueType(0);
12770
12771 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
12772
12773 // Compute ~(x xor y)
12774 SDValue XorXY = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12775 SDValue EqvXY = DAG.getNOT(dl, XorXY, VT);
12776 // Compute (s xor x)
12777 SDValue SumXorX = DAG.getNode(ISD::XOR, dl, VT, Sum, LHS);
12778
12779 // overflow = (x eqv y) & (s xor x)
12780 SDValue OverflowInSign = DAG.getNode(ISD::AND, dl, VT, EqvXY, SumXorX);
12781
12782 // Shift sign bit down to LSB
12783 SDValue Overflow =
12784 DAG.getNode(ISD::SRL, dl, VT, OverflowInSign,
12785 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12786 // Truncate to the overflow type (i1)
12787 SDValue OverflowTrunc =
12788 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12789
12790 return DAG.getMergeValues({Sum, OverflowTrunc}, dl);
12791}
12792
12793/// Lower ABDU with negation pattern using branchless carry arithmetic.
12794/// Recognizes: abdu(a, sub(0, x)) and transforms to:
12795/// a - (0 - x) = a + x (mod 2^n)
12796/// Uses SUBC to compute result without branches.
12797SDValue PPCTargetLowering::LowerABDU(SDValue Op, SelectionDAG &DAG) const {
12798 SDLoc DL(Op);
12799 SDValue LHS = Op.getOperand(0);
12800 SDValue RHS = Op.getOperand(1);
12801 EVT OpVT = LHS.getValueType();
12802 EVT VT = Op.getValueType();
12803 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
12804
12805 // If the subtract doesn't overflow then just use abs(sub()).
12806 if (DAG.willNotOverflowSub(IsNonNegative, LHS, RHS))
12807 return DAG.getNode(ISD::ABS, DL, VT,
12808 DAG.getNode(ISD::SUB, DL, VT, LHS, RHS));
12809
12810 if (DAG.willNotOverflowSub(IsNonNegative, RHS, LHS))
12811 return DAG.getNode(ISD::ABS, DL, VT,
12812 DAG.getNode(ISD::SUB, DL, VT, RHS, LHS));
12813
12814 // General path: use SUBC (or ADDC when RHS is 0-X) to get
12815 // subtract-with-flags, then CMOV to select a-b or b-a. ADDC/SUBC produce the
12816 // flags we need.
12817 unsigned Opcode = PPCISD::SUBC;
12818
12819 // Check if RHS is a negation (0 - X). If so, we can use ADDC instead of SUBC:
12820 // a - (0 - x) = a + x (mod 2^n)
12821 // Same semantics as in LowerCMP; apply same safety checks.
12822 if (RHS.getOpcode() == ISD::SUB) {
12823 SDValue SubLHS = RHS.getOperand(0);
12824 SDValue SubRHS = RHS.getOperand(1);
12825
12826 if (isNullConstant(SubLHS) && DAG.isKnownNeverZero(SubRHS)) {
12827 Opcode = PPCISD::ADDC;
12828 RHS = SubRHS;
12829 }
12830 }
12831
12832 // On PPC64, carry ops use the full 64-bit register. Operands are type-legal
12833 // i32 here; widen only for the carry path (fast abs(sub) stays at VT).
12834 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12835 LHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, LHS);
12836 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RHS);
12837 OpVT = MVT::i64;
12838 }
12839
12840 // Calculate LHS - RHS and capture the carry (CA)
12841 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12842 SDValue Res = DAG.getNode(Opcode, DL, VTs, LHS, RHS);
12843 SDValue CA0 = Res.getValue(1);
12844
12845 // t2 = A - B + CA0 using SUBE.
12846 SDValue ZeroOrNeg1 = DAG.getNode(PPCISD::SUBE, DL, VTs, Res, Res, CA0);
12847
12848 SDValue Xor = DAG.getNode(ISD::XOR, DL, OpVT, Res, ZeroOrNeg1);
12849
12850 Res = DAG.getNode(ISD::SUB, DL, OpVT, Xor, ZeroOrNeg1);
12851
12852 Res = DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
12853 return Res;
12854}
12855
12856// Lower unsigned 3-way compare producing -1/0/1.
12857SDValue PPCTargetLowering::LowerUCMP(SDValue Op, SelectionDAG &DAG) const {
12858 SDLoc DL(Op);
12859 SDValue A = DAG.getFreeze(Op.getOperand(0));
12860 SDValue B = DAG.getFreeze(Op.getOperand(1));
12861 EVT OpVT = A.getValueType();
12862 EVT ResVT = Op.getValueType();
12863
12864 // On PPC64, i32 carries are affected by the upper 32 bits of the registers.
12865 // We must zero-extend to i64 to ensure the carry reflects the 32-bit unsigned
12866 // comparison.
12867 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12868 A = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, A);
12869 B = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, B);
12870 OpVT = MVT::i64;
12871 }
12872
12873 // First compute diff = A - B.
12874 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, A, B);
12875
12876 // Generate B - A using SUBC to capture carry.
12877 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12878 SDValue SubC = DAG.getNode(PPCISD::SUBC, DL, VTs, B, A);
12879 SDValue CA0 = SubC.getValue(1);
12880
12881 // t2 = A - B + CA0 using SUBE.
12882 SDValue SubE1 = DAG.getNode(PPCISD::SUBE, DL, VTs, A, B, CA0);
12883 SDValue CA1 = SubE1.getValue(1);
12884
12885 // res = diff - t2 + CA1 using SUBE (produces desired -1/0/1).
12886 SDValue ResPair = DAG.getNode(PPCISD::SUBE, DL, VTs, Diff, SubE1, CA1);
12887
12888 // Extract the first result and truncate to result type if needed.
12889 return DAG.getSExtOrTrunc(ResPair.getValue(0), DL, ResVT);
12890}
12891
12892/// LowerOperation - Provide custom lowering hooks for some operations.
12893///
12895 switch (Op.getOpcode()) {
12896 default:
12897 llvm_unreachable("Wasn't expecting to be able to lower this!");
12898 case ISD::FPOW: return lowerPow(Op, DAG);
12899 case ISD::FSIN: return lowerSin(Op, DAG);
12900 case ISD::FCOS: return lowerCos(Op, DAG);
12901 case ISD::FLOG: return lowerLog(Op, DAG);
12902 case ISD::FLOG10: return lowerLog10(Op, DAG);
12903 case ISD::FEXP: return lowerExp(Op, DAG);
12904 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12905 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12906 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12907 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12908 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12909 case ISD::STRICT_FSETCC:
12911 case ISD::SETCC: return LowerSETCC(Op, DAG);
12912 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
12913 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12914 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12915 case ISD::SSUBO:
12916 return LowerSSUBO(Op, DAG);
12917 case ISD::SADDO:
12918 return LowerSADDO(Op, DAG);
12919
12920 case ISD::INLINEASM:
12921 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
12922 // Variable argument lowering.
12923 case ISD::VASTART: return LowerVASTART(Op, DAG);
12924 case ISD::VAARG: return LowerVAARG(Op, DAG);
12925 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
12926
12927 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
12928 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12930 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
12931
12932 // Exception handling lowering.
12933 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
12934 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12935 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12936
12937 case ISD::LOAD: return LowerLOAD(Op, DAG);
12938 case ISD::STORE: return LowerSTORE(Op, DAG);
12939 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12940 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
12943 case ISD::FP_TO_UINT:
12944 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
12947 case ISD::UINT_TO_FP:
12948 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
12949 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
12950 case ISD::SET_ROUNDING:
12951 return LowerSET_ROUNDING(Op, DAG);
12952
12953 // Lower 64-bit shifts.
12954 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
12955 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
12956 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
12957
12958 case ISD::FSHL: return LowerFunnelShift(Op, DAG);
12959 case ISD::FSHR: return LowerFunnelShift(Op, DAG);
12960
12961 // Vector-related lowering.
12962 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12963 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12964 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12965 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12966 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12967 case ISD::MUL: return LowerMUL(Op, DAG);
12968 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12970 case ISD::FP_ROUND:
12971 return LowerFP_ROUND(Op, DAG);
12972 case ISD::ROTL: return LowerROTL(Op, DAG);
12973
12974 // For counter-based loop handling.
12976 return SDValue();
12977
12978 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12979
12980 // Frame & Return address.
12981 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12982 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12983
12985 return LowerINTRINSIC_VOID(Op, DAG);
12986 case ISD::BSWAP:
12987 return LowerBSWAP(Op, DAG);
12989 return LowerATOMIC_CMP_SWAP(Op, DAG);
12990 case ISD::ATOMIC_STORE:
12991 return LowerATOMIC_LOAD_STORE(Op, DAG);
12992 case ISD::IS_FPCLASS:
12993 return LowerIS_FPCLASS(Op, DAG);
12994 case ISD::UADDO:
12995 case ISD::USUBO:
12996 return LowerADDSUBO(Op, DAG);
12997 case ISD::UADDO_CARRY:
12998 case ISD::USUBO_CARRY:
12999 return LowerADDSUBO_CARRY(Op, DAG);
13000 case ISD::UCMP:
13001 return LowerUCMP(Op, DAG);
13002 case ISD::ABDU:
13003 return LowerABDU(Op, DAG);
13004 case ISD::STRICT_LRINT:
13005 case ISD::STRICT_LLRINT:
13006 case ISD::STRICT_LROUND:
13009 if (Op->getFlags().hasNoFPExcept())
13010 return Op;
13011 return SDValue();
13012 case ISD::VP_LOAD:
13013 return LowerVP_LOAD(Op, DAG);
13014 case ISD::VP_STORE:
13015 return LowerVP_STORE(Op, DAG);
13017 return LowerPartialReduce(Op, DAG);
13018 }
13019}
13020
13023 SelectionDAG &DAG) const {
13024 SDLoc dl(N);
13025 switch (N->getOpcode()) {
13026 default:
13027 llvm_unreachable("Do not know how to custom type legalize this operation!");
13028 case ISD::ATOMIC_LOAD: {
13029 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
13030 Results.push_back(Res);
13031 Results.push_back(Res.getValue(1));
13032 break;
13033 }
13034 case ISD::READCYCLECOUNTER: {
13035 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13036 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
13037
13038 Results.push_back(
13039 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
13040 Results.push_back(RTB.getValue(2));
13041 break;
13042 }
13044 if (N->getConstantOperandVal(1) != Intrinsic::loop_decrement)
13045 break;
13046
13047 assert(N->getValueType(0) == MVT::i1 &&
13048 "Unexpected result type for CTR decrement intrinsic");
13049 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13050 N->getValueType(0));
13051 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
13052 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
13053 N->getOperand(1));
13054
13055 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
13056 Results.push_back(NewInt.getValue(1));
13057 break;
13058 }
13060 switch (N->getConstantOperandVal(0)) {
13061 case Intrinsic::ppc_pack_longdouble:
13062 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
13063 N->getOperand(2), N->getOperand(1)));
13064 break;
13065 case Intrinsic::ppc_maxfe:
13066 case Intrinsic::ppc_minfe:
13067 case Intrinsic::ppc_fnmsub:
13068 case Intrinsic::ppc_convert_f128_to_ppcf128:
13069 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
13070 break;
13071 }
13072 break;
13073 }
13074 case ISD::VAARG: {
13075 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
13076 return;
13077
13078 EVT VT = N->getValueType(0);
13079
13080 if (VT == MVT::i64) {
13081 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
13082
13083 Results.push_back(NewNode);
13084 Results.push_back(NewNode.getValue(1));
13085 }
13086 return;
13087 }
13090 case ISD::FP_TO_SINT:
13091 case ISD::FP_TO_UINT: {
13092 // LowerFP_TO_INT() can only handle f32 and f64.
13093 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
13094 MVT::ppcf128)
13095 return;
13096 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
13097 Results.push_back(LoweredValue);
13098 if (N->isStrictFPOpcode())
13099 Results.push_back(LoweredValue.getValue(1));
13100 return;
13101 }
13102 case ISD::TRUNCATE: {
13103 if (!N->getValueType(0).isVector())
13104 return;
13105 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
13106 if (Lowered)
13107 Results.push_back(Lowered);
13108 return;
13109 }
13110 case ISD::SCALAR_TO_VECTOR: {
13111 SDValue Lowered = LowerSCALAR_TO_VECTOR(SDValue(N, 0), DAG);
13112 if (Lowered)
13113 Results.push_back(Lowered);
13114 return;
13115 }
13116 case ISD::FSHL:
13117 case ISD::FSHR:
13118 // Don't handle funnel shifts here.
13119 return;
13120 case ISD::BITCAST:
13121 // Don't handle bitcast here.
13122 return;
13123 case ISD::FP_EXTEND:
13124 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
13125 if (Lowered)
13126 Results.push_back(Lowered);
13127 return;
13128 }
13129}
13130
13131//===----------------------------------------------------------------------===//
13132// Other Lowering Code
13133//===----------------------------------------------------------------------===//
13134
13136 return Builder.CreateIntrinsicWithoutFolding(Id, {});
13137}
13138
13140 Value *Addr,
13141 AtomicOrdering Ord) const {
13142 unsigned SZ = ValueTy->getPrimitiveSizeInBits();
13143
13144 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13145 "Only 8/16/32/64-bit atomic loads supported");
13146 Intrinsic::ID IntID;
13147 switch (SZ) {
13148 default:
13149 llvm_unreachable("Unexpected PrimitiveSize");
13150 case 8:
13151 IntID = Intrinsic::ppc_lbarx;
13152 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13153 break;
13154 case 16:
13155 IntID = Intrinsic::ppc_lharx;
13156 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13157 break;
13158 case 32:
13159 IntID = Intrinsic::ppc_lwarx;
13160 break;
13161 case 64:
13162 IntID = Intrinsic::ppc_ldarx;
13163 break;
13164 }
13165 Value *Call =
13166 Builder.CreateIntrinsic(IntID, Addr, /*FMFSource=*/nullptr, "larx");
13167
13168 return Builder.CreateTruncOrBitCast(Call, ValueTy);
13169}
13170
13171// Perform a store-conditional operation to Addr. Return the status of the
13172// store. This should be 0 if the store succeeded, non-zero otherwise.
13174 Value *Val, Value *Addr,
13175 AtomicOrdering Ord) const {
13176 Type *Ty = Val->getType();
13177 unsigned SZ = Ty->getPrimitiveSizeInBits();
13178
13179 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13180 "Only 8/16/32/64-bit atomic loads supported");
13181 Intrinsic::ID IntID;
13182 switch (SZ) {
13183 default:
13184 llvm_unreachable("Unexpected PrimitiveSize");
13185 case 8:
13186 IntID = Intrinsic::ppc_stbcx;
13187 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13188 break;
13189 case 16:
13190 IntID = Intrinsic::ppc_sthcx;
13191 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13192 break;
13193 case 32:
13194 IntID = Intrinsic::ppc_stwcx;
13195 break;
13196 case 64:
13197 IntID = Intrinsic::ppc_stdcx;
13198 break;
13199 }
13200
13201 if (SZ == 8 || SZ == 16)
13202 Val = Builder.CreateZExt(Val, Builder.getInt32Ty());
13203
13204 Value *Call = Builder.CreateIntrinsic(IntID, {Addr, Val},
13205 /*FMFSource=*/nullptr, "stcx");
13206 return Builder.CreateXor(Call, Builder.getInt32(1));
13207}
13208
13209// The mappings for emitLeading/TrailingFence is taken from
13210// http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13212 Instruction *Inst,
13213 AtomicOrdering Ord) const {
13215 return callIntrinsic(Builder, Intrinsic::ppc_sync);
13216 if (isReleaseOrStronger(Ord))
13217 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13218 return nullptr;
13219}
13220
13222 Instruction *Inst,
13223 AtomicOrdering Ord) const {
13224 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
13225 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
13226 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
13227 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
13228 if (isa<LoadInst>(Inst))
13229 return Builder.CreateIntrinsicWithoutFolding(Intrinsic::ppc_cfence,
13230 {Inst->getType()}, {Inst});
13231 // FIXME: Can use isync for rmw operation.
13232 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13233 }
13234 return nullptr;
13235}
13236
13239 unsigned BinOpcode,
13240 unsigned CmpOpcode,
13241 unsigned CmpPred) const {
13242 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13243 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13244 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13245 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13246 unsigned AtomicSize = MI.getOperand(3).getImm();
13247
13248 auto LoadMnemonic = PPC::LDARX;
13249 auto StoreMnemonic = PPC::STDCX;
13250 switch (AtomicSize) {
13251 default:
13252 llvm_unreachable("Unexpected size of atomic entity");
13253 case 1:
13254 LoadMnemonic = PPC::LBARX;
13255 StoreMnemonic = PPC::STBCX;
13256 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13257 break;
13258 case 2:
13259 LoadMnemonic = PPC::LHARX;
13260 StoreMnemonic = PPC::STHCX;
13261 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13262 break;
13263 case 4:
13264 LoadMnemonic = PPC::LWARX;
13265 StoreMnemonic = PPC::STWCX;
13266 break;
13267 case 8:
13268 LoadMnemonic = PPC::LDARX;
13269 StoreMnemonic = PPC::STDCX;
13270 break;
13271 }
13272
13273 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13274 MachineFunction *F = BB->getParent();
13276
13277 if (CmpOpcode == PPC::CMPW && (AtomicSize == 1 || AtomicSize == 2))
13278 signExtendOperandIfUnknown(MI, BB, 4, /*IsByte=*/AtomicSize == 1, TII);
13279
13280 Register dest = MI.getOperand(0).getReg();
13281 Register ptrA = MI.getOperand(1).getReg();
13282 Register ptrB = MI.getOperand(2).getReg();
13283 Register incr = MI.getOperand(4).getReg();
13284 DebugLoc dl = MI.getDebugLoc();
13285
13286 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13287 MachineBasicBlock *loop2MBB =
13288 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13289 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13290 F->insert(It, loopMBB);
13291 if (CmpOpcode)
13292 F->insert(It, loop2MBB);
13293 F->insert(It, exitMBB);
13294 exitMBB->splice(exitMBB->begin(), BB,
13295 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13297
13298 MachineRegisterInfo &RegInfo = F->getRegInfo();
13299 Register TmpReg = (!BinOpcode) ? incr :
13300 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
13301 : &PPC::GPRCRegClass);
13302
13303 // thisMBB:
13304 // ...
13305 // fallthrough --> loopMBB
13306 BB->addSuccessor(loopMBB);
13307
13308 // loopMBB:
13309 // l[wd]arx dest, ptr
13310 // add r0, dest, incr
13311 // st[wd]cx. r0, ptr
13312 // bne- loopMBB
13313 // fallthrough --> exitMBB
13314
13315 // For max/min...
13316 // loopMBB:
13317 // l[wd]arx dest, ptr
13318 // cmpl?[wd] dest, incr
13319 // bgt exitMBB
13320 // loop2MBB:
13321 // st[wd]cx. dest, ptr
13322 // bne- loopMBB
13323 // fallthrough --> exitMBB
13324
13325 BB = loopMBB;
13326 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
13327 .addReg(ptrA).addReg(ptrB);
13328 if (BinOpcode)
13329 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
13330 if (CmpOpcode) {
13331 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13332 // Signed comparisons of byte or halfword values must be sign-extended.
13333 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
13334 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13335 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
13336 ExtReg).addReg(dest);
13337 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr);
13338 } else
13339 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr);
13340
13341 BuildMI(BB, dl, TII->get(PPC::BCC))
13342 .addImm(CmpPred)
13343 .addReg(CrReg)
13344 .addMBB(exitMBB);
13345 BB->addSuccessor(loop2MBB);
13346 BB->addSuccessor(exitMBB);
13347 BB = loop2MBB;
13348 }
13349 BuildMI(BB, dl, TII->get(StoreMnemonic))
13350 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
13351 BuildMI(BB, dl, TII->get(PPC::BCC))
13353 .addReg(PPC::CR0)
13354 .addMBB(loopMBB);
13355 BB->addSuccessor(loopMBB);
13356 BB->addSuccessor(exitMBB);
13357
13358 // exitMBB:
13359 // ...
13360 BB = exitMBB;
13361 return BB;
13362}
13363
13365 switch(MI.getOpcode()) {
13366 default:
13367 return false;
13368 case PPC::COPY:
13369 return TII->isSignExtended(MI.getOperand(1).getReg(),
13370 &MI.getMF()->getRegInfo());
13371 case PPC::LHA:
13372 case PPC::LHA8:
13373 case PPC::LHAU:
13374 case PPC::LHAU8:
13375 case PPC::LHAUX:
13376 case PPC::LHAUX8:
13377 case PPC::LHAX:
13378 case PPC::LHAX8:
13379 case PPC::LWA:
13380 case PPC::LWAUX:
13381 case PPC::LWAX:
13382 case PPC::LWAX_32:
13383 case PPC::LWA_32:
13384 case PPC::PLHA:
13385 case PPC::PLHA8:
13386 case PPC::PLHA8pc:
13387 case PPC::PLHApc:
13388 case PPC::PLWA:
13389 case PPC::PLWA8:
13390 case PPC::PLWA8pc:
13391 case PPC::PLWApc:
13392 case PPC::EXTSB:
13393 case PPC::EXTSB8:
13394 case PPC::EXTSB8_32_64:
13395 case PPC::EXTSB8_rec:
13396 case PPC::EXTSB_rec:
13397 case PPC::EXTSH:
13398 case PPC::EXTSH8:
13399 case PPC::EXTSH8_32_64:
13400 case PPC::EXTSH8_rec:
13401 case PPC::EXTSH_rec:
13402 case PPC::EXTSW:
13403 case PPC::EXTSWSLI:
13404 case PPC::EXTSWSLI_32_64:
13405 case PPC::EXTSWSLI_32_64_rec:
13406 case PPC::EXTSWSLI_rec:
13407 case PPC::EXTSW_32:
13408 case PPC::EXTSW_32_64:
13409 case PPC::EXTSW_32_64_rec:
13410 case PPC::EXTSW_rec:
13411 case PPC::SRAW:
13412 case PPC::SRAWI:
13413 case PPC::SRAWI_rec:
13414 case PPC::SRAW_rec:
13415 return true;
13416 }
13417 return false;
13418}
13419
13420// Sign extend operand OpIdx if the value is not known to be sign extended.
13421// Assumes the operand is a register. The flag IsByte controls which intruction
13422// is used for the sign extension.
13424 unsigned OpIdx, bool IsByte,
13425 const PPCInstrInfo *TII) {
13426 MachineFunction *F = MI.getMF();
13427 MachineRegisterInfo &RegInfo = F->getRegInfo();
13428 Register Reg = MI.getOperand(OpIdx).getReg();
13429 bool IsSignExtended =
13430 Reg.isVirtual() && isSignExtended(*RegInfo.getVRegDef(Reg), TII);
13431
13432 if (!IsSignExtended) {
13433 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13434 BuildMI(*BB, MI, MI.getDebugLoc(),
13435 TII->get(IsByte ? PPC::EXTSB : PPC::EXTSH), ValueReg)
13436 .addReg(Reg);
13437 MI.getOperand(OpIdx).setReg(ValueReg);
13438 }
13439}
13440
13442 MachineInstr &MI, MachineBasicBlock *BB, unsigned BinOpcode,
13443 unsigned CmpOpcode, unsigned CmpPred) const {
13444 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13445 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13446 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13447 assert(!Subtarget.hasPartwordAtomics() &&
13448 "Assumes that part-word atomics are not available");
13449 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13450
13451 // If this is a signed comparison and the value being compared is not known
13452 // to be sign extended, sign extend it here.
13453 DebugLoc dl = MI.getDebugLoc();
13454 MachineFunction *F = BB->getParent();
13455 MachineRegisterInfo &RegInfo = F->getRegInfo();
13456 const bool is8bit = MI.getOperand(3).getImm() == 1;
13457 if (CmpOpcode == PPC::CMPW)
13458 signExtendOperandIfUnknown(MI, BB, 4, is8bit, TII);
13459 Register incr = MI.getOperand(4).getReg();
13460
13461 // In 64 bit mode we have to use 64 bits for addresses, even though the
13462 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
13463 // registers without caring whether they're 32 or 64, but here we're
13464 // doing actual arithmetic on the addresses.
13465 bool is64bit = Subtarget.isPPC64();
13466 bool isLittleEndian = Subtarget.isLittleEndian();
13467 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
13468
13469 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13471
13472 Register dest = MI.getOperand(0).getReg();
13473 Register ptrA = MI.getOperand(1).getReg();
13474 Register ptrB = MI.getOperand(2).getReg();
13475
13476 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13477 MachineBasicBlock *loop2MBB =
13478 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13479 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13480 F->insert(It, loopMBB);
13481 if (CmpOpcode)
13482 F->insert(It, loop2MBB);
13483 F->insert(It, exitMBB);
13484 exitMBB->splice(exitMBB->begin(), BB,
13485 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13487
13488 const TargetRegisterClass *RC =
13489 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13490 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
13491
13492 Register PtrReg = RegInfo.createVirtualRegister(RC);
13493 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
13494 Register ShiftReg =
13495 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
13496 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
13497 Register MaskReg = RegInfo.createVirtualRegister(GPRC);
13498 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
13499 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
13500 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
13501 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
13502 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
13503 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
13504 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
13505 Register Ptr1Reg;
13506 Register TmpReg =
13507 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
13508
13509 // thisMBB:
13510 // ...
13511 // fallthrough --> loopMBB
13512 BB->addSuccessor(loopMBB);
13513
13514 // The 4-byte load must be aligned, while a char or short may be
13515 // anywhere in the word. Hence all this nasty bookkeeping code.
13516 // add ptr1, ptrA, ptrB [copy if ptrA==0]
13517 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
13518 // xori shift, shift1, 24 [16]
13519 // rlwinm ptr, ptr1, 0, 0, 29
13520 // slw incr2, incr, shift
13521 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
13522 // slw mask, mask2, shift
13523 // loopMBB:
13524 // lwarx tmpDest, ptr
13525 // add tmp, tmpDest, incr2
13526 // andc tmp2, tmpDest, mask
13527 // and tmp3, tmp, mask
13528 // or tmp4, tmp3, tmp2
13529 // stwcx. tmp4, ptr
13530 // bne- loopMBB
13531 // fallthrough --> exitMBB
13532 // srw SrwDest, tmpDest, shift
13533 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
13534 if (ptrA != ZeroReg) {
13535 Ptr1Reg = RegInfo.createVirtualRegister(RC);
13536 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
13537 .addReg(ptrA)
13538 .addReg(ptrB);
13539 } else {
13540 Ptr1Reg = ptrB;
13541 }
13542 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
13543 // mode.
13544 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
13545 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
13546 .addImm(3)
13547 .addImm(27)
13548 .addImm(is8bit ? 28 : 27);
13549 if (!isLittleEndian)
13550 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
13551 .addReg(Shift1Reg)
13552 .addImm(is8bit ? 24 : 16);
13553 if (is64bit)
13554 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
13555 .addReg(Ptr1Reg)
13556 .addImm(0)
13557 .addImm(61);
13558 else
13559 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
13560 .addReg(Ptr1Reg)
13561 .addImm(0)
13562 .addImm(0)
13563 .addImm(29);
13564 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
13565 if (is8bit)
13566 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
13567 else {
13568 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
13569 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
13570 .addReg(Mask3Reg)
13571 .addImm(65535);
13572 }
13573 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
13574 .addReg(Mask2Reg)
13575 .addReg(ShiftReg);
13576
13577 BB = loopMBB;
13578 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
13579 .addReg(ZeroReg)
13580 .addReg(PtrReg);
13581 if (BinOpcode)
13582 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
13583 .addReg(Incr2Reg)
13584 .addReg(TmpDestReg);
13585 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
13586 .addReg(TmpDestReg)
13587 .addReg(MaskReg);
13588 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
13589 if (CmpOpcode) {
13590 // For unsigned comparisons, we can directly compare the shifted values.
13591 // For signed comparisons we shift and sign extend.
13592 Register SReg = RegInfo.createVirtualRegister(GPRC);
13593 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13594 BuildMI(BB, dl, TII->get(PPC::AND), SReg)
13595 .addReg(TmpDestReg)
13596 .addReg(MaskReg);
13597 unsigned ValueReg = SReg;
13598 unsigned CmpReg = Incr2Reg;
13599 if (CmpOpcode == PPC::CMPW) {
13600 ValueReg = RegInfo.createVirtualRegister(GPRC);
13601 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
13602 .addReg(SReg)
13603 .addReg(ShiftReg);
13604 Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
13605 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
13606 .addReg(ValueReg);
13607 ValueReg = ValueSReg;
13608 CmpReg = incr;
13609 }
13610 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg);
13611 BuildMI(BB, dl, TII->get(PPC::BCC))
13612 .addImm(CmpPred)
13613 .addReg(CrReg)
13614 .addMBB(exitMBB);
13615 BB->addSuccessor(loop2MBB);
13616 BB->addSuccessor(exitMBB);
13617 BB = loop2MBB;
13618 }
13619 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
13620 BuildMI(BB, dl, TII->get(PPC::STWCX))
13621 .addReg(Tmp4Reg)
13622 .addReg(ZeroReg)
13623 .addReg(PtrReg);
13624 BuildMI(BB, dl, TII->get(PPC::BCC))
13626 .addReg(PPC::CR0)
13627 .addMBB(loopMBB);
13628 BB->addSuccessor(loopMBB);
13629 BB->addSuccessor(exitMBB);
13630
13631 // exitMBB:
13632 // ...
13633 BB = exitMBB;
13634 // Since the shift amount is not a constant, we need to clear
13635 // the upper bits with a separate RLWINM.
13636 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
13637 .addReg(SrwDestReg)
13638 .addImm(0)
13639 .addImm(is8bit ? 24 : 16)
13640 .addImm(31);
13641 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
13642 .addReg(TmpDestReg)
13643 .addReg(ShiftReg);
13644 return BB;
13645}
13646
13649 MachineBasicBlock *MBB) const {
13650 DebugLoc DL = MI.getDebugLoc();
13651 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13652 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13653
13654 MachineFunction *MF = MBB->getParent();
13655 MachineRegisterInfo &MRI = MF->getRegInfo();
13656
13657 const BasicBlock *BB = MBB->getBasicBlock();
13658 MachineFunction::iterator I = ++MBB->getIterator();
13659
13660 Register DstReg = MI.getOperand(0).getReg();
13661 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13662 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
13663 Register mainDstReg = MRI.createVirtualRegister(RC);
13664 Register restoreDstReg = MRI.createVirtualRegister(RC);
13665
13666 MVT PVT = getPointerTy(MF->getDataLayout());
13667 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13668 "Invalid Pointer Size!");
13669 // For v = setjmp(buf), we generate
13670 //
13671 // thisMBB:
13672 // SjLjSetup mainMBB
13673 // bl mainMBB
13674 // v_restore = 1
13675 // b sinkMBB
13676 //
13677 // mainMBB:
13678 // buf[LabelOffset] = LR
13679 // v_main = 0
13680 //
13681 // sinkMBB:
13682 // v = phi(main, restore)
13683 //
13684
13685 MachineBasicBlock *thisMBB = MBB;
13686 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13687 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13688 MF->insert(I, mainMBB);
13689 MF->insert(I, sinkMBB);
13690
13692
13693 // Transfer the remainder of BB and its successor edges to sinkMBB.
13694 sinkMBB->splice(sinkMBB->begin(), MBB,
13695 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
13697
13698 // Note that the structure of the jmp_buf used here is not compatible
13699 // with that used by libc, and is not designed to be. Specifically, it
13700 // stores only those 'reserved' registers that LLVM does not otherwise
13701 // understand how to spill. Also, by convention, by the time this
13702 // intrinsic is called, Clang has already stored the frame address in the
13703 // first slot of the buffer and stack address in the third. Following the
13704 // X86 target code, we'll store the jump address in the second slot. We also
13705 // need to save the TOC pointer (R2) to handle jumps between shared
13706 // libraries, and that will be stored in the fourth slot. The thread
13707 // identifier (R13) is not affected.
13708
13709 // thisMBB:
13710 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13711 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13712 const int64_t BPOffset = 4 * PVT.getStoreSize();
13713
13714 // Prepare IP either in reg.
13715 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13716 Register LabelReg = MRI.createVirtualRegister(PtrRC);
13717 Register BufReg = MI.getOperand(1).getReg();
13718
13719 if (Subtarget.is64BitELFABI()) {
13720 setUsesTOCBasePtr(*MBB->getParent());
13721 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
13722 .addReg(PPC::X2)
13723 .addImm(TOCOffset)
13724 .addReg(BufReg)
13725 .cloneMemRefs(MI);
13726 }
13727
13728 // Naked functions never have a base pointer, and so we use r1. For all
13729 // other functions, this decision must be delayed until during PEI.
13730 unsigned BaseReg;
13731 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
13732 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
13733 else
13734 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
13735
13736 MIB = BuildMI(*thisMBB, MI, DL,
13737 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
13738 .addReg(BaseReg)
13739 .addImm(BPOffset)
13740 .addReg(BufReg)
13741 .cloneMemRefs(MI);
13742
13743 // Setup
13744 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
13745 MIB.addRegMask(TRI->getNoPreservedMask());
13746
13747 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
13748
13749 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
13750 .addMBB(mainMBB);
13751 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
13752
13753 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
13754 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
13755
13756 // mainMBB:
13757 // mainDstReg = 0
13758 MIB =
13759 BuildMI(mainMBB, DL,
13760 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
13761
13762 // Store IP
13763 if (Subtarget.isPPC64()) {
13764 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
13765 .addReg(LabelReg)
13766 .addImm(LabelOffset)
13767 .addReg(BufReg);
13768 } else {
13769 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
13770 .addReg(LabelReg)
13771 .addImm(LabelOffset)
13772 .addReg(BufReg);
13773 }
13774 MIB.cloneMemRefs(MI);
13775
13776 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
13777 mainMBB->addSuccessor(sinkMBB);
13778
13779 // sinkMBB:
13780 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13781 TII->get(PPC::PHI), DstReg)
13782 .addReg(mainDstReg).addMBB(mainMBB)
13783 .addReg(restoreDstReg).addMBB(thisMBB);
13784
13785 MI.eraseFromParent();
13786 return sinkMBB;
13787}
13788
13791 MachineBasicBlock *MBB) const {
13792 DebugLoc DL = MI.getDebugLoc();
13793 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13794
13795 MachineFunction *MF = MBB->getParent();
13796 MachineRegisterInfo &MRI = MF->getRegInfo();
13797
13798 MVT PVT = getPointerTy(MF->getDataLayout());
13799 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13800 "Invalid Pointer Size!");
13801
13802 const TargetRegisterClass *RC =
13803 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13804 Register Tmp = MRI.createVirtualRegister(RC);
13805 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13806 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
13807 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
13808 unsigned BP =
13809 (PVT == MVT::i64)
13810 ? PPC::X30
13811 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
13812 : PPC::R30);
13813
13815
13816 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13817 const int64_t SPOffset = 2 * PVT.getStoreSize();
13818 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13819 const int64_t BPOffset = 4 * PVT.getStoreSize();
13820
13821 Register BufReg = MI.getOperand(0).getReg();
13822
13823 // Reload FP (the jumped-to function may not have had a
13824 // frame pointer, and if so, then its r31 will be restored
13825 // as necessary).
13826 if (PVT == MVT::i64) {
13827 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
13828 .addImm(0)
13829 .addReg(BufReg);
13830 } else {
13831 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
13832 .addImm(0)
13833 .addReg(BufReg);
13834 }
13835 MIB.cloneMemRefs(MI);
13836
13837 // Reload IP
13838 if (PVT == MVT::i64) {
13839 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
13840 .addImm(LabelOffset)
13841 .addReg(BufReg);
13842 } else {
13843 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
13844 .addImm(LabelOffset)
13845 .addReg(BufReg);
13846 }
13847 MIB.cloneMemRefs(MI);
13848
13849 // Reload SP
13850 if (PVT == MVT::i64) {
13851 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
13852 .addImm(SPOffset)
13853 .addReg(BufReg);
13854 } else {
13855 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
13856 .addImm(SPOffset)
13857 .addReg(BufReg);
13858 }
13859 MIB.cloneMemRefs(MI);
13860
13861 // Reload BP
13862 if (PVT == MVT::i64) {
13863 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
13864 .addImm(BPOffset)
13865 .addReg(BufReg);
13866 } else {
13867 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
13868 .addImm(BPOffset)
13869 .addReg(BufReg);
13870 }
13871 MIB.cloneMemRefs(MI);
13872
13873 // Reload TOC
13874 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
13875 setUsesTOCBasePtr(*MBB->getParent());
13876 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
13877 .addImm(TOCOffset)
13878 .addReg(BufReg)
13879 .cloneMemRefs(MI);
13880 }
13881
13882 // Jump
13883 BuildMI(*MBB, MI, DL,
13884 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
13885 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
13886
13887 MI.eraseFromParent();
13888 return MBB;
13889}
13890
13892 // If the function specifically requests inline stack probes, emit them.
13893 if (MF.getFunction().hasFnAttribute("probe-stack"))
13894 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
13895 "inline-asm";
13896 return false;
13897}
13898
13900 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
13901 unsigned StackAlign = TFI->getStackAlignment();
13902 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
13903 "Unexpected stack alignment");
13904 // The default stack probe size is 4096 if the function has no
13905 // stack-probe-size attribute.
13906 const Function &Fn = MF.getFunction();
13907 unsigned StackProbeSize =
13908 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
13909 // Round down to the stack alignment.
13910 StackProbeSize &= ~(StackAlign - 1);
13911 return StackProbeSize ? StackProbeSize : StackAlign;
13912}
13913
13914// Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
13915// into three phases. In the first phase, it uses pseudo instruction
13916// PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
13917// FinalStackPtr. In the second phase, it generates a loop for probing blocks.
13918// At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
13919// MaxCallFrameSize so that it can calculate correct data area pointer.
13922 MachineBasicBlock *MBB) const {
13923 const bool isPPC64 = Subtarget.isPPC64();
13924 MachineFunction *MF = MBB->getParent();
13925 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13926 DebugLoc DL = MI.getDebugLoc();
13927 const unsigned ProbeSize = getStackProbeSize(*MF);
13928 const BasicBlock *ProbedBB = MBB->getBasicBlock();
13929 MachineRegisterInfo &MRI = MF->getRegInfo();
13930 // The CFG of probing stack looks as
13931 // +-----+
13932 // | MBB |
13933 // +--+--+
13934 // |
13935 // +----v----+
13936 // +--->+ TestMBB +---+
13937 // | +----+----+ |
13938 // | | |
13939 // | +-----v----+ |
13940 // +---+ BlockMBB | |
13941 // +----------+ |
13942 // |
13943 // +---------+ |
13944 // | TailMBB +<--+
13945 // +---------+
13946 // In MBB, calculate previous frame pointer and final stack pointer.
13947 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
13948 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
13949 // TailMBB is spliced via \p MI.
13950 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
13951 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
13952 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
13953
13954 MachineFunction::iterator MBBIter = ++MBB->getIterator();
13955 MF->insert(MBBIter, TestMBB);
13956 MF->insert(MBBIter, BlockMBB);
13957 MF->insert(MBBIter, TailMBB);
13958
13959 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
13960 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
13961
13962 Register DstReg = MI.getOperand(0).getReg();
13963 Register NegSizeReg = MI.getOperand(1).getReg();
13964 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
13965 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13966 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13967 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13968
13969 // Since value of NegSizeReg might be realigned in prologepilog, insert a
13970 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
13971 // NegSize.
13972 unsigned ProbeOpc;
13973 if (!MRI.hasOneNonDBGUse(NegSizeReg))
13974 ProbeOpc =
13975 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
13976 else
13977 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
13978 // and NegSizeReg will be allocated in the same phyreg to avoid
13979 // redundant copy when NegSizeReg has only one use which is current MI and
13980 // will be replaced by PREPARE_PROBED_ALLOCA then.
13981 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
13982 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
13983 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
13984 .addDef(ActualNegSizeReg)
13985 .addReg(NegSizeReg)
13986 .add(MI.getOperand(2))
13987 .add(MI.getOperand(3));
13988
13989 // Calculate final stack pointer, which equals to SP + ActualNegSize.
13990 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
13991 FinalStackPtr)
13992 .addReg(SPReg)
13993 .addReg(ActualNegSizeReg);
13994
13995 // Materialize a scratch register for update.
13996 int64_t NegProbeSize = -(int64_t)ProbeSize;
13997 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
13998 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13999 if (!isInt<16>(NegProbeSize)) {
14000 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14001 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
14002 .addImm(NegProbeSize >> 16);
14003 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
14004 ScratchReg)
14005 .addReg(TempReg)
14006 .addImm(NegProbeSize & 0xFFFF);
14007 } else
14008 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
14009 .addImm(NegProbeSize);
14010
14011 {
14012 // Probing leading residual part.
14013 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14014 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
14015 .addReg(ActualNegSizeReg)
14016 .addReg(ScratchReg);
14017 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14018 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
14019 .addReg(Div)
14020 .addReg(ScratchReg);
14021 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14022 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
14023 .addReg(Mul)
14024 .addReg(ActualNegSizeReg);
14025 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14026 .addReg(FramePointer)
14027 .addReg(SPReg)
14028 .addReg(NegMod);
14029 }
14030
14031 {
14032 // Remaining part should be multiple of ProbeSize.
14033 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
14034 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
14035 .addReg(SPReg)
14036 .addReg(FinalStackPtr);
14037 BuildMI(TestMBB, DL, TII->get(PPC::BCC))
14039 .addReg(CmpResult)
14040 .addMBB(TailMBB);
14041 TestMBB->addSuccessor(BlockMBB);
14042 TestMBB->addSuccessor(TailMBB);
14043 }
14044
14045 {
14046 // Touch the block.
14047 // |P...|P...|P...
14048 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14049 .addReg(FramePointer)
14050 .addReg(SPReg)
14051 .addReg(ScratchReg);
14052 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
14053 BlockMBB->addSuccessor(TestMBB);
14054 }
14055
14056 // Calculation of MaxCallFrameSize is deferred to prologepilog, use
14057 // DYNAREAOFFSET pseudo instruction to get the future result.
14058 Register MaxCallFrameSizeReg =
14059 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14060 BuildMI(TailMBB, DL,
14061 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
14062 MaxCallFrameSizeReg)
14063 .add(MI.getOperand(2))
14064 .add(MI.getOperand(3));
14065 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
14066 .addReg(SPReg)
14067 .addReg(MaxCallFrameSizeReg);
14068
14069 // Splice instructions after MI to TailMBB.
14070 TailMBB->splice(TailMBB->end(), MBB,
14071 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14073 MBB->addSuccessor(TestMBB);
14074
14075 // Delete the pseudo instruction.
14076 MI.eraseFromParent();
14077
14078 ++NumDynamicAllocaProbed;
14079 return TailMBB;
14080}
14081
14082/// Check if the opcode is a SELECT or SELECT_CC variant.
14083/// @param Opcode The opcode to check
14084/// @param CheckOnlyCC If true, only return true for SELECT_CC variants;
14085/// if false, return true for both SELECT and SELECT_CC
14086static bool IsSelect(unsigned Opcode, bool CheckOnlyCC = false) {
14087 switch (Opcode) {
14088 // SELECT_CC variants - always return true
14089 case PPC::SELECT_CC_I4:
14090 case PPC::SELECT_CC_I8:
14091 case PPC::SELECT_CC_F4:
14092 case PPC::SELECT_CC_F8:
14093 case PPC::SELECT_CC_F16:
14094 case PPC::SELECT_CC_VRRC:
14095 case PPC::SELECT_CC_VSFRC:
14096 case PPC::SELECT_CC_VSSRC:
14097 case PPC::SELECT_CC_VSRC:
14098 case PPC::SELECT_CC_SPE4:
14099 case PPC::SELECT_CC_SPE:
14100 return true;
14101 // SELECT variants - only return true if CheckOnlyCC is false
14102 case PPC::SELECT_I4:
14103 case PPC::SELECT_I8:
14104 case PPC::SELECT_F4:
14105 case PPC::SELECT_F8:
14106 case PPC::SELECT_F16:
14107 case PPC::SELECT_SPE:
14108 case PPC::SELECT_SPE4:
14109 case PPC::SELECT_VRRC:
14110 case PPC::SELECT_VSFRC:
14111 case PPC::SELECT_VSSRC:
14112 case PPC::SELECT_VSRC:
14113 return !CheckOnlyCC; // true if checking all SELECTs, false if only CC
14114 default:
14115 return false;
14116 }
14117}
14118static bool IsSelectCC(unsigned Opcode) { return IsSelect(Opcode, true); }
14119
14120/// Emit SELECT instruction, using ISEL if available, otherwise use
14121/// branch-based control flow.
14122///
14123/// For targets with ISEL support (SELECT_CC_I4/I8, SELECT_I4/I8), this
14124/// generates a single ISEL instruction. Otherwise, it creates a
14125/// branch-based control flow pattern with PHI nodes.
14127 const TargetInstrInfo *TII,
14128 const PPCSubtarget &Subtarget) {
14129 assert(IsSelect(MI.getOpcode()) && "Instruction must be a SELECT variant");
14130
14131 // Check if we can use ISEL for this SELECT
14132 if (Subtarget.hasISEL() &&
14133 (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14134 MI.getOpcode() == PPC::SELECT_CC_I8 ||
14135 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
14137 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14138 MI.getOpcode() == PPC::SELECT_CC_I8)
14139 Cond.push_back(MI.getOperand(4));
14140 else
14142 Cond.push_back(MI.getOperand(1));
14143
14144 DebugLoc dl = MI.getDebugLoc();
14145 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
14146 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
14147 MI.eraseFromParent();
14148 return BB;
14149 }
14150
14151 // Fall back to branch-based SELECT implementation
14152 MachineFunction *F = BB->getParent();
14153 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14155 DebugLoc dl = MI.getDebugLoc();
14156
14157 MachineBasicBlock *thisMBB = BB;
14158 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14159 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14160 F->insert(It, copy0MBB);
14161 F->insert(It, sinkMBB);
14162
14163 if (isPhysRegUsedAfter(PPC::CARRY, MI.getIterator())) {
14164 copy0MBB->addLiveIn(PPC::CARRY);
14165 sinkMBB->addLiveIn(PPC::CARRY);
14166 }
14167
14168 // Set the call frame size on entry to the new basic blocks.
14169 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
14170 copy0MBB->setCallFrameSize(CallFrameSize);
14171 sinkMBB->setCallFrameSize(CallFrameSize);
14172
14173 // Transfer the remainder of BB and its successor edges to sinkMBB.
14174 sinkMBB->splice(sinkMBB->begin(), BB,
14175 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14177
14178 // Add successors
14179 BB->addSuccessor(copy0MBB);
14180 BB->addSuccessor(sinkMBB);
14181
14182 // Build branch instruction
14183 if (IsSelectCC(MI.getOpcode()))
14184 BuildMI(BB, dl, TII->get(PPC::BCC))
14185 .addImm(MI.getOperand(4).getImm())
14186 .addReg(MI.getOperand(1).getReg())
14187 .addMBB(sinkMBB);
14188 else
14189 BuildMI(BB, dl, TII->get(PPC::BC))
14190 .addReg(MI.getOperand(1).getReg())
14191 .addMBB(sinkMBB);
14192
14193 // copy0MBB: fallthrough to sinkMBB
14194 BB = copy0MBB;
14195 BB->addSuccessor(sinkMBB);
14196
14197 // sinkMBB: PHI instruction
14198 BB = sinkMBB;
14199 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
14200 .addReg(MI.getOperand(3).getReg())
14201 .addMBB(copy0MBB)
14202 .addReg(MI.getOperand(2).getReg())
14203 .addMBB(thisMBB);
14204 MI.eraseFromParent();
14205 return BB;
14206}
14207
14208/// Helper function to create basic blocks for atomic compare-and-swap.
14209/// Creates three basic blocks (loop1MBB, loop2MBB, exitMBB) and sets up
14210/// the control flow structure common to both hardware and software
14211/// implementations of atomic compare-and-swap operations.
14213 MachineBasicBlock *&loop1MBB,
14214 MachineBasicBlock *&loop2MBB,
14215 MachineBasicBlock *&exitMBB,
14218 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14219 loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
14220 loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
14221 exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
14222 F->insert(It, loop1MBB);
14223 F->insert(It, loop2MBB);
14224 F->insert(It, exitMBB);
14225 exitMBB->splice(exitMBB->begin(), BB,
14226 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14228 BB->addSuccessor(loop1MBB);
14229}
14230
14231/// Emit hardware-supported atomic compare-and-swap for I32/I64 and I8/I16
14232/// with partword atomic support.
14233///
14234/// This uses native PowerPC atomic instructions (LBARX/LHARX/LWARX/LDARX for
14235/// load-and-reserve, STBCX/STHCX/STWCX/STDCX for store-conditional) to
14236/// implement atomic compare-and-swap at byte, halfword, word, or doubleword
14237/// granularity.
14238///
14239/// Control flow:
14240/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14241/// | |
14242/// +------------+
14243///
14244/// loop1MBB:
14245/// - Load-and-reserve from memory
14246/// - Compare loaded value with expected old value
14247/// - Branch to exitMBB if not equal (CAS failed)
14248/// loop2MBB:
14249/// - Store-conditional new value to memory
14250/// - Branch back to loop1MBB if store failed (retry)
14251/// - Fall through to exitMBB on success
14252static MachineBasicBlock *
14254 const TargetInstrInfo *TII,
14255 const PPCSubtarget &Subtarget) {
14256 MachineFunction *F = BB->getParent();
14258
14259 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
14260
14261 unsigned LoadMnemonic = PPC::LDARX;
14262 unsigned StoreMnemonic = PPC::STDCX;
14263 switch (MI.getOpcode()) {
14264 default:
14265 llvm_unreachable("Compare and swap of unknown size");
14266 case PPC::ATOMIC_CMP_SWAP_I8:
14267 LoadMnemonic = PPC::LBARX;
14268 StoreMnemonic = PPC::STBCX;
14269 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14270 break;
14271 case PPC::ATOMIC_CMP_SWAP_I16:
14272 LoadMnemonic = PPC::LHARX;
14273 StoreMnemonic = PPC::STHCX;
14274 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14275 break;
14276 case PPC::ATOMIC_CMP_SWAP_I32:
14277 LoadMnemonic = PPC::LWARX;
14278 StoreMnemonic = PPC::STWCX;
14279 break;
14280 case PPC::ATOMIC_CMP_SWAP_I64:
14281 LoadMnemonic = PPC::LDARX;
14282 StoreMnemonic = PPC::STDCX;
14283 break;
14284 }
14285
14286 MachineRegisterInfo &RegInfo = F->getRegInfo();
14287 Register dest = MI.getOperand(0).getReg();
14288 Register ptrA = MI.getOperand(1).getReg();
14289 Register ptrB = MI.getOperand(2).getReg();
14290 Register oldval = MI.getOperand(3).getReg();
14291 Register newval = MI.getOperand(4).getReg();
14292 DebugLoc dl = MI.getDebugLoc();
14293
14294 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14295 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14296
14297 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14298
14299 // loop1MBB:
14300 // l[bhwd]arx dest, ptr
14301 // cmp[wd] dest, oldval
14302 // bne- exitBB
14303 BB = loop1MBB;
14304 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
14305 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg)
14306 .addReg(dest)
14307 .addReg(oldval);
14308 BuildMI(BB, dl, TII->get(PPC::BCC))
14310 .addReg(CrReg)
14311 .addMBB(exitMBB);
14312 BB->addSuccessor(loop2MBB);
14313 BB->addSuccessor(exitMBB);
14314
14315 // loop2MBB:
14316 // st[bhwd]cx. newval, ptr
14317 // bne- loopMBB
14318 // b exitBB
14319 BB = loop2MBB;
14320 BuildMI(BB, dl, TII->get(StoreMnemonic))
14321 .addReg(newval)
14322 .addReg(ptrA)
14323 .addReg(ptrB);
14324 BuildMI(BB, dl, TII->get(PPC::BCC))
14326 .addReg(PPC::CR0)
14327 .addMBB(loop1MBB);
14328 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14329 BB->addSuccessor(loop1MBB);
14330 BB->addSuccessor(exitMBB);
14331
14332 return exitMBB;
14333}
14334
14335/// Emit software-emulated atomic compare-and-swap for I8/I16 without
14336/// hardware partword atomic support.
14337///
14338/// This emulates byte/halfword atomic operations using word (32-bit) atomic
14339/// instructions. Since PowerPC atomic instructions work at word granularity,
14340/// we must:
14341/// 1. Align the pointer to a word boundary
14342/// 2. Calculate the bit shift for the target byte/halfword within the word
14343/// 3. Create masks to isolate the target byte/halfword
14344/// 4. Shift old/new values into the correct bit position
14345/// 5. Use LWARX/STWCX on the full word
14346/// 6. Mask and merge to preserve other bytes in the word
14347/// 7. Extract and shift the result back
14348///
14349/// Control flow:
14350/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14351/// | |
14352/// +------------+
14353///
14354/// loop1MBB:
14355/// - LWARX: Load-and-reserve full word
14356/// - Mask to extract target byte/halfword
14357/// - Compare with expected old value
14358/// - Branch to exitMBB if not equal (CAS failed)
14359/// loop2MBB:
14360/// - Merge new value with other bytes in the word
14361/// - STWCX: Store-conditional full word
14362/// - Branch back to loop1MBB if store failed (retry)
14363/// - Fall through to exitMBB on success
14364/// exitMBB:
14365/// - Extract and return the loaded value
14366static MachineBasicBlock *
14368 const TargetInstrInfo *TII,
14369 const PPCSubtarget &Subtarget) {
14370 MachineFunction *F = BB->getParent();
14372
14373 bool is64bit = Subtarget.isPPC64();
14374 bool isLittleEndian = Subtarget.isLittleEndian();
14375 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
14376
14377 Register dest = MI.getOperand(0).getReg();
14378 Register ptrA = MI.getOperand(1).getReg();
14379 Register ptrB = MI.getOperand(2).getReg();
14380 Register oldval = MI.getOperand(3).getReg();
14381 Register newval = MI.getOperand(4).getReg();
14382 DebugLoc dl = MI.getDebugLoc();
14383
14384 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14385 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14386
14387 MachineRegisterInfo &RegInfo = F->getRegInfo();
14388 const TargetRegisterClass *RC =
14389 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
14390 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
14391
14392 // Lambda to create virtual registers
14393 auto createVReg = [&](const TargetRegisterClass *RC) {
14394 return RegInfo.createVirtualRegister(RC);
14395 };
14396
14397 Register PtrReg = createVReg(RC);
14398 Register Shift1Reg = createVReg(GPRC);
14399 Register ShiftReg = isLittleEndian ? Shift1Reg : createVReg(GPRC);
14400 Register NewVal2Reg = createVReg(GPRC);
14401 Register NewVal3Reg = createVReg(GPRC);
14402 Register OldVal2Reg = createVReg(GPRC);
14403 Register OldVal3Reg = createVReg(GPRC);
14404 Register MaskReg = createVReg(GPRC);
14405 Register Mask2Reg = createVReg(GPRC);
14406 Register Mask3Reg = createVReg(GPRC);
14407 Register Tmp2Reg = createVReg(GPRC);
14408 Register Tmp4Reg = createVReg(GPRC);
14409 Register TmpDestReg = createVReg(GPRC);
14410 Register TmpReg = createVReg(GPRC);
14411 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
14412 Register CrReg = createVReg(&PPC::CRRCRegClass);
14413
14414 // Compute aligned pointer and shift amount
14415 Register Ptr1Reg;
14416 if (ptrA != ZeroReg) {
14417 Ptr1Reg = createVReg(RC);
14418 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
14419 .addReg(ptrA)
14420 .addReg(ptrB);
14421 } else {
14422 Ptr1Reg = ptrB;
14423 }
14424
14425 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
14426 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
14427 .addImm(3)
14428 .addImm(27)
14429 .addImm(is8bit ? 28 : 27);
14430 if (!isLittleEndian)
14431 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
14432 .addReg(Shift1Reg)
14433 .addImm(is8bit ? 24 : 16);
14434 if (is64bit)
14435 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
14436 .addReg(Ptr1Reg)
14437 .addImm(0)
14438 .addImm(61);
14439 else
14440 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
14441 .addReg(Ptr1Reg)
14442 .addImm(0)
14443 .addImm(0)
14444 .addImm(29);
14445
14446 // Prepare masked values
14447 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
14448 .addReg(newval)
14449 .addReg(ShiftReg);
14450 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
14451 .addReg(oldval)
14452 .addReg(ShiftReg);
14453 if (is8bit)
14454 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
14455 else {
14456 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
14457 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
14458 .addReg(Mask3Reg)
14459 .addImm(65535);
14460 }
14461 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
14462 .addReg(Mask2Reg)
14463 .addReg(ShiftReg);
14464 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
14465 .addReg(NewVal2Reg)
14466 .addReg(MaskReg);
14467 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
14468 .addReg(OldVal2Reg)
14469 .addReg(MaskReg);
14470
14471 // loop1MBB:
14472 // lwarx tmpDest, ptr
14473 // and tmp, tmpDest, mask
14474 // cmpw tmp, oldval3
14475 // bne- exitBB
14476 BB = loop1MBB;
14477 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
14478 .addReg(ZeroReg)
14479 .addReg(PtrReg);
14480 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
14481 .addReg(TmpDestReg)
14482 .addReg(MaskReg);
14483 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg).addReg(TmpReg).addReg(OldVal3Reg);
14484 BuildMI(BB, dl, TII->get(PPC::BCC))
14486 .addReg(CrReg)
14487 .addMBB(exitMBB);
14488 BB->addSuccessor(loop2MBB);
14489 BB->addSuccessor(exitMBB);
14490
14491 // loop2MBB:
14492 // andc tmp2, tmpDest, mask
14493 // or tmp4, tmp2, newval3
14494 // stwcx. tmp4, ptr
14495 // bne- loop1MBB
14496 // b exitBB
14497 BB = loop2MBB;
14498 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
14499 .addReg(TmpDestReg)
14500 .addReg(MaskReg);
14501 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
14502 .addReg(Tmp2Reg)
14503 .addReg(NewVal3Reg);
14504 BuildMI(BB, dl, TII->get(PPC::STWCX))
14505 .addReg(Tmp4Reg)
14506 .addReg(ZeroReg)
14507 .addReg(PtrReg);
14508 BuildMI(BB, dl, TII->get(PPC::BCC))
14510 .addReg(PPC::CR0)
14511 .addMBB(loop1MBB);
14512 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14513 BB->addSuccessor(loop1MBB);
14514 BB->addSuccessor(exitMBB);
14515
14516 // exitMBB:
14517 // srw dest, tmpDest, shift
14518 BB = exitMBB;
14519 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
14520 .addReg(TmpReg)
14521 .addReg(ShiftReg);
14522
14523 return BB;
14524}
14525
14528 MachineBasicBlock *BB) const {
14529 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14530
14531 // To "insert" these instructions we actually have to insert their
14532 // control-flow patterns.
14533 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14535
14536 MachineFunction *F = BB->getParent();
14537 MachineRegisterInfo &MRI = F->getRegInfo();
14538
14539 // Handle SELECT with ISEL support first (before generic SELECT handling)
14540 if (IsSelect(MI.getOpcode()))
14541 return emitSelect(MI, BB, TII, Subtarget);
14542
14543 switch (MI.getOpcode()) {
14544 case TargetOpcode::STACKMAP:
14545 return emitPatchPoint(MI, BB);
14546 case TargetOpcode::PATCHPOINT:
14547 // Call lowering should have added an r2 operand to indicate a dependence
14548 // on the TOC base pointer value. It can't however, because there is no
14549 // way to mark the dependence as implicit there, and so the stackmap code
14550 // will confuse it with a regular operand. Instead, add the dependence
14551 // here.
14552 if (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls())
14553 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
14554 return emitPatchPoint(MI, BB);
14555
14556 case PPC::EH_SjLj_SetJmp32:
14557 case PPC::EH_SjLj_SetJmp64:
14558 return emitEHSjLjSetJmp(MI, BB);
14559
14560 case PPC::EH_SjLj_LongJmp32:
14561 case PPC::EH_SjLj_LongJmp64:
14562 return emitEHSjLjLongJmp(MI, BB);
14563
14564 case PPC::ReadTB: {
14565 // To read the 64-bit time-base register on a 32-bit target, we read the
14566 // two halves. Should the counter have wrapped while it was being read, we
14567 // need to try again.
14568 // ...
14569 // readLoop:
14570 // mfspr Rx,TBU # load from TBU
14571 // mfspr Ry,TB # load from TB
14572 // mfspr Rz,TBU # load from TBU
14573 // cmpw crX,Rx,Rz # check if 'old'='new'
14574 // bne readLoop # branch if they're not equal
14575 // ...
14576
14577 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
14578 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14579 DebugLoc dl = MI.getDebugLoc();
14580 F->insert(It, readMBB);
14581 F->insert(It, sinkMBB);
14582
14583 // Transfer the remainder of BB and its successor edges to sinkMBB.
14584 sinkMBB->splice(sinkMBB->begin(), BB,
14585 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14587
14588 BB->addSuccessor(readMBB);
14589 BB = readMBB;
14590
14591 MachineRegisterInfo &RegInfo = F->getRegInfo();
14592 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
14593 Register LoReg = MI.getOperand(0).getReg();
14594 Register HiReg = MI.getOperand(1).getReg();
14595
14596 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
14597 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
14598 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
14599
14600 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14601
14602 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
14603 .addReg(HiReg)
14604 .addReg(ReadAgainReg);
14605 BuildMI(BB, dl, TII->get(PPC::BCC))
14607 .addReg(CmpReg)
14608 .addMBB(readMBB);
14609
14610 BB->addSuccessor(readMBB);
14611 BB->addSuccessor(sinkMBB);
14612 break;
14613 }
14614 case PPC::ATOMIC_LOAD_ADD_NOWP:
14615 BB = EmitPartwordAtomicBinary(MI, BB, PPC::ADD4);
14616 break;
14617 case PPC::ATOMIC_LOAD_ADD:
14618 BB = EmitAtomicBinary(MI, BB, PPC::ADD4);
14619 break;
14620 case PPC::ATOMIC_LOAD_ADD_I64:
14621 BB = EmitAtomicBinary(MI, BB, PPC::ADD8);
14622 break;
14623 case PPC::ATOMIC_LOAD_AND_NOWP:
14624 BB = EmitPartwordAtomicBinary(MI, BB, PPC::AND);
14625 break;
14626 case PPC::ATOMIC_LOAD_AND:
14627 BB = EmitAtomicBinary(MI, BB, PPC::AND);
14628 break;
14629 case PPC::ATOMIC_LOAD_AND_I64:
14630 BB = EmitAtomicBinary(MI, BB, PPC::AND8);
14631 break;
14632 case PPC::ATOMIC_LOAD_OR_NOWP:
14633 BB = EmitPartwordAtomicBinary(MI, BB, PPC::OR);
14634 break;
14635 case PPC::ATOMIC_LOAD_OR:
14636 BB = EmitAtomicBinary(MI, BB, PPC::OR);
14637 break;
14638 case PPC::ATOMIC_LOAD_OR_I64:
14639 BB = EmitAtomicBinary(MI, BB, PPC::OR8);
14640 break;
14641 case PPC::ATOMIC_LOAD_XOR_NOWP:
14642 BB = EmitPartwordAtomicBinary(MI, BB, PPC::XOR);
14643 break;
14644 case PPC::ATOMIC_LOAD_XOR:
14645 BB = EmitAtomicBinary(MI, BB, PPC::XOR);
14646 break;
14647 case PPC::ATOMIC_LOAD_XOR_I64:
14648 BB = EmitAtomicBinary(MI, BB, PPC::XOR8);
14649 break;
14650 case PPC::ATOMIC_LOAD_NAND_NOWP:
14651 BB = EmitPartwordAtomicBinary(MI, BB, PPC::NAND);
14652 break;
14653 case PPC::ATOMIC_LOAD_NAND:
14654 BB = EmitAtomicBinary(MI, BB, PPC::NAND);
14655 break;
14656 case PPC::ATOMIC_LOAD_NAND_I64:
14657 BB = EmitAtomicBinary(MI, BB, PPC::NAND8);
14658 break;
14659 case PPC::ATOMIC_LOAD_SUB_NOWP:
14660 BB = EmitPartwordAtomicBinary(MI, BB, PPC::SUBF);
14661 break;
14662 case PPC::ATOMIC_LOAD_SUB:
14663 BB = EmitAtomicBinary(MI, BB, PPC::SUBF);
14664 break;
14665 case PPC::ATOMIC_LOAD_SUB_I64:
14666 BB = EmitAtomicBinary(MI, BB, PPC::SUBF8);
14667 break;
14668 case PPC::ATOMIC_LOAD_MIN_NOWP:
14669 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14670 break;
14671 case PPC::ATOMIC_LOAD_MIN:
14672 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14673 break;
14674 case PPC::ATOMIC_LOAD_MIN_I64:
14675 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_LT);
14676 break;
14677 case PPC::ATOMIC_LOAD_MAX_NOWP:
14678 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14679 break;
14680 case PPC::ATOMIC_LOAD_MAX:
14681 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14682 break;
14683 case PPC::ATOMIC_LOAD_MAX_I64:
14684 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_GT);
14685 break;
14686 case PPC::ATOMIC_LOAD_UMIN_NOWP:
14687 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14688 break;
14689 case PPC::ATOMIC_LOAD_UMIN:
14690 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14691 break;
14692 case PPC::ATOMIC_LOAD_UMIN_I64:
14693 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_LT);
14694 break;
14695 case PPC::ATOMIC_LOAD_UMAX_NOWP:
14696 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14697 break;
14698 case PPC::ATOMIC_LOAD_UMAX:
14699 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14700 break;
14701 case PPC::ATOMIC_LOAD_UMAX_I64:
14702 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_GT);
14703 break;
14704 case PPC::ATOMIC_SWAP_NOWP:
14705 BB = EmitPartwordAtomicBinary(MI, BB, 0);
14706 break;
14707 case PPC::ATOMIC_SWAP:
14708 case PPC::ATOMIC_SWAP_I64:
14709 BB = EmitAtomicBinary(MI, BB, 0);
14710 break;
14711 case PPC::ATOMIC_CMP_SWAP_I32:
14712 case PPC::ATOMIC_CMP_SWAP_I64:
14713 case PPC::ATOMIC_CMP_SWAP_I8:
14714 case PPC::ATOMIC_CMP_SWAP_I16: {
14715 // Use hardware-supported atomic operations if available
14716 bool useHardware = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
14717 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
14718 (Subtarget.hasPartwordAtomics() &&
14719 (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
14720 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16));
14721
14722 if (useHardware)
14723 BB = emitAtomicCmpSwapHardware(MI, BB, TII, Subtarget);
14724 else
14725 BB = emitAtomicCmpSwapSoftware(MI, BB, TII, Subtarget);
14726 break;
14727 }
14728 case PPC::FADDrtz: {
14729 // This pseudo performs an FADD with rounding mode temporarily forced
14730 // to round-to-zero. We emit this via custom inserter since the FPSCR
14731 // is not modeled at the SelectionDAG level.
14732 Register Dest = MI.getOperand(0).getReg();
14733 Register Src1 = MI.getOperand(1).getReg();
14734 Register Src2 = MI.getOperand(2).getReg();
14735 DebugLoc dl = MI.getDebugLoc();
14736
14737 MachineRegisterInfo &RegInfo = F->getRegInfo();
14738 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
14739
14740 // Save FPSCR value.
14741 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
14742
14743 // Set rounding mode to round-to-zero.
14744 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
14745 .addImm(31)
14747
14748 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
14749 .addImm(30)
14751
14752 // Perform addition.
14753 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
14754 .addReg(Src1)
14755 .addReg(Src2);
14756 if (MI.getFlag(MachineInstr::NoFPExcept))
14758
14759 // Restore FPSCR value.
14760 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
14761 break;
14762 }
14763 case PPC::ANDI_rec_1_EQ_BIT:
14764 case PPC::ANDI_rec_1_GT_BIT:
14765 case PPC::ANDI_rec_1_EQ_BIT8:
14766 case PPC::ANDI_rec_1_GT_BIT8: {
14767 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
14768 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
14769 ? PPC::ANDI8_rec
14770 : PPC::ANDI_rec;
14771 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
14772 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
14773
14774 MachineRegisterInfo &RegInfo = F->getRegInfo();
14775 Register Dest = RegInfo.createVirtualRegister(
14776 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
14777
14778 DebugLoc Dl = MI.getDebugLoc();
14779 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
14780 .addReg(MI.getOperand(1).getReg())
14781 .addImm(1);
14782 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14783 MI.getOperand(0).getReg())
14784 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
14785 break;
14786 }
14787 case PPC::TCHECK_RET: {
14788 DebugLoc Dl = MI.getDebugLoc();
14789 MachineRegisterInfo &RegInfo = F->getRegInfo();
14790 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14791 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
14792 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14793 MI.getOperand(0).getReg())
14794 .addReg(CRReg);
14795 break;
14796 }
14797 case PPC::TBEGIN_RET: {
14798 DebugLoc Dl = MI.getDebugLoc();
14799 unsigned Imm = MI.getOperand(1).getImm();
14800 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
14801 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14802 MI.getOperand(0).getReg())
14803 .addReg(PPC::CR0EQ);
14804 break;
14805 }
14806 case PPC::SETRNDi: {
14807 DebugLoc dl = MI.getDebugLoc();
14808 Register OldFPSCRReg = MI.getOperand(0).getReg();
14809
14810 // Save FPSCR value.
14811 if (MRI.use_empty(OldFPSCRReg))
14812 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
14813 else
14814 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
14815
14816 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
14817 // the following settings:
14818 // 00 Round to nearest
14819 // 01 Round to 0
14820 // 10 Round to +inf
14821 // 11 Round to -inf
14822
14823 // When the operand is immediate, using the two least significant bits of
14824 // the immediate to set the bits 62:63 of FPSCR.
14825 unsigned Mode = MI.getOperand(1).getImm();
14826 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
14827 .addImm(31)
14829
14830 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
14831 .addImm(30)
14833 break;
14834 }
14835 case PPC::SETRND: {
14836 DebugLoc dl = MI.getDebugLoc();
14837
14838 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
14839 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
14840 // If the target doesn't have DirectMove, we should use stack to do the
14841 // conversion, because the target doesn't have the instructions like mtvsrd
14842 // or mfvsrd to do this conversion directly.
14843 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
14844 if (Subtarget.hasDirectMove()) {
14845 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
14846 .addReg(SrcReg);
14847 } else {
14848 // Use stack to do the register copy.
14849 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
14850 MachineRegisterInfo &RegInfo = F->getRegInfo();
14851 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
14852 if (RC == &PPC::F8RCRegClass) {
14853 // Copy register from F8RCRegClass to G8RCRegclass.
14854 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
14855 "Unsupported RegClass.");
14856
14857 StoreOp = PPC::STFD;
14858 LoadOp = PPC::LD;
14859 } else {
14860 // Copy register from G8RCRegClass to F8RCRegclass.
14861 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
14862 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
14863 "Unsupported RegClass.");
14864 }
14865
14866 MachineFrameInfo &MFI = F->getFrameInfo();
14867 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
14868
14869 MachineMemOperand *MMOStore = F->getMachineMemOperand(
14870 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14872 MFI.getObjectAlign(FrameIdx));
14873
14874 // Store the SrcReg into the stack.
14875 BuildMI(*BB, MI, dl, TII->get(StoreOp))
14876 .addReg(SrcReg)
14877 .addImm(0)
14878 .addFrameIndex(FrameIdx)
14879 .addMemOperand(MMOStore);
14880
14881 MachineMemOperand *MMOLoad = F->getMachineMemOperand(
14882 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14884 MFI.getObjectAlign(FrameIdx));
14885
14886 // Load from the stack where SrcReg is stored, and save to DestReg,
14887 // so we have done the RegClass conversion from RegClass::SrcReg to
14888 // RegClass::DestReg.
14889 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
14890 .addImm(0)
14891 .addFrameIndex(FrameIdx)
14892 .addMemOperand(MMOLoad);
14893 }
14894 };
14895
14896 Register OldFPSCRReg = MI.getOperand(0).getReg();
14897
14898 // Save FPSCR value.
14899 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
14900
14901 // When the operand is gprc register, use two least significant bits of the
14902 // register and mtfsf instruction to set the bits 62:63 of FPSCR.
14903 //
14904 // copy OldFPSCRTmpReg, OldFPSCRReg
14905 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
14906 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
14907 // copy NewFPSCRReg, NewFPSCRTmpReg
14908 // mtfsf 255, NewFPSCRReg
14909 MachineOperand SrcOp = MI.getOperand(1);
14910 MachineRegisterInfo &RegInfo = F->getRegInfo();
14911 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14912
14913 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
14914
14915 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14916 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14917
14918 // The first operand of INSERT_SUBREG should be a register which has
14919 // subregisters, we only care about its RegClass, so we should use an
14920 // IMPLICIT_DEF register.
14921 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
14922 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
14923 .addReg(ImDefReg)
14924 .add(SrcOp)
14925 .addImm(1);
14926
14927 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14928 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
14929 .addReg(OldFPSCRTmpReg)
14930 .addReg(ExtSrcReg)
14931 .addImm(0)
14932 .addImm(62);
14933
14934 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
14935 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
14936
14937 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
14938 // bits of FPSCR.
14939 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
14940 .addImm(255)
14941 .addReg(NewFPSCRReg)
14942 .addImm(0)
14943 .addImm(0);
14944 break;
14945 }
14946 case PPC::SETFLM: {
14947 DebugLoc Dl = MI.getDebugLoc();
14948
14949 // Result of setflm is previous FPSCR content, so we need to save it first.
14950 Register OldFPSCRReg = MI.getOperand(0).getReg();
14951 if (MRI.use_empty(OldFPSCRReg))
14952 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
14953 else
14954 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
14955
14956 // Put bits in 32:63 to FPSCR.
14957 Register NewFPSCRReg = MI.getOperand(1).getReg();
14958 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
14959 .addImm(255)
14960 .addReg(NewFPSCRReg)
14961 .addImm(0)
14962 .addImm(0);
14963 break;
14964 }
14965 case PPC::PROBED_ALLOCA_32:
14966 case PPC::PROBED_ALLOCA_64:
14967 return emitProbedAlloca(MI, BB);
14968
14969 case PPC::SPLIT_QUADWORD: {
14970 DebugLoc DL = MI.getDebugLoc();
14971 Register Src = MI.getOperand(2).getReg();
14972 Register Lo = MI.getOperand(0).getReg();
14973 Register Hi = MI.getOperand(1).getReg();
14974 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
14975 .addDef(Lo)
14976 .addUse(Src, {}, PPC::sub_gp8_x1);
14977 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
14978 .addDef(Hi)
14979 .addUse(Src, {}, PPC::sub_gp8_x0);
14980 break;
14981 }
14982 case PPC::LQX_PSEUDO:
14983 case PPC::STQX_PSEUDO: {
14984 DebugLoc DL = MI.getDebugLoc();
14985 // Ptr is used as the ptr_rc_no_r0 part
14986 // of LQ/STQ's memory operand and adding result of RA and RB,
14987 // so it has to be g8rc_and_g8rc_nox0.
14988 Register Ptr =
14989 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
14990 Register Val = MI.getOperand(0).getReg();
14991 Register RA = MI.getOperand(1).getReg();
14992 Register RB = MI.getOperand(2).getReg();
14993 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
14994 BuildMI(*BB, MI, DL,
14995 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
14996 : TII->get(PPC::STQ))
14997 .addReg(Val, getDefRegState(MI.getOpcode() == PPC::LQX_PSEUDO))
14998 .addImm(0)
14999 .addReg(Ptr);
15000 break;
15001 }
15002 default:
15003 llvm_unreachable("Unexpected instr type to insert");
15004 }
15005
15006 MI.eraseFromParent(); // The pseudo instruction is gone now.
15007 return BB;
15008}
15009
15010//===----------------------------------------------------------------------===//
15011// Target Optimization Hooks
15012//===----------------------------------------------------------------------===//
15013
15014static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
15015 // For the estimates, convergence is quadratic, so we essentially double the
15016 // number of digits correct after every iteration. For both FRE and FRSQRTE,
15017 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
15018 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
15019 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
15020 if (VT.getScalarType() == MVT::f64)
15021 RefinementSteps++;
15022 return RefinementSteps;
15023}
15024
15025SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
15026 const DenormalMode &Mode,
15027 SDNodeFlags Flags) const {
15028 // We only have VSX Vector Test for software Square Root.
15029 EVT VT = Op.getValueType();
15030 if (!isTypeLegal(MVT::i1) ||
15031 (VT != MVT::f64 &&
15032 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
15033 return TargetLowering::getSqrtInputTest(Op, DAG, Mode, Flags);
15034
15035 SDLoc DL(Op);
15036 // The output register of FTSQRT is CR field.
15037 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op, Flags);
15038 // ftsqrt BF,FRB
15039 // Let e_b be the unbiased exponent of the double-precision
15040 // floating-point operand in register FRB.
15041 // fe_flag is set to 1 if either of the following conditions occurs.
15042 // - The double-precision floating-point operand in register FRB is a zero,
15043 // a NaN, or an infinity, or a negative value.
15044 // - e_b is less than or equal to -970.
15045 // Otherwise fe_flag is set to 0.
15046 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
15047 // not eligible for iteration. (zero/negative/infinity/nan or unbiased
15048 // exponent is less than -970)
15049 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
15050 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
15051 FTSQRT, SRIdxVal),
15052 0);
15053}
15054
15055SDValue
15056PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
15057 SelectionDAG &DAG) const {
15058 // We only have VSX Vector Square Root.
15059 EVT VT = Op.getValueType();
15060 if (VT != MVT::f64 &&
15061 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
15063
15064 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
15065}
15066
15067SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
15068 int Enabled, int &RefinementSteps,
15069 bool &UseOneConstNR,
15070 bool Reciprocal) const {
15071 EVT VT = Operand.getValueType();
15072 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
15073 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
15074 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15075 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15076 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15077 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15078
15079 // The Newton-Raphson computation with a single constant does not provide
15080 // enough accuracy on some CPUs.
15081 UseOneConstNR = !Subtarget.needsTwoConstNR();
15082 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
15083 }
15084 return SDValue();
15085}
15086
15087SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
15088 int Enabled,
15089 int &RefinementSteps) const {
15090 EVT VT = Operand.getValueType();
15091 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
15092 (VT == MVT::f64 && Subtarget.hasFRE()) ||
15093 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15094 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15095 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15096 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15097 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
15098 }
15099 return SDValue();
15100}
15101
15103 // Note: This functionality is used only when arcp is enabled, and
15104 // on cores with reciprocal estimates (which are used when arcp is
15105 // enabled for division), this functionality is redundant with the default
15106 // combiner logic (once the division -> reciprocal/multiply transformation
15107 // has taken place). As a result, this matters more for older cores than for
15108 // newer ones.
15109
15110 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15111 // reciprocal if there are two or more FDIVs (for embedded cores with only
15112 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
15113 switch (Subtarget.getCPUDirective()) {
15114 default:
15115 return 3;
15116 case PPC::DIR_440:
15117 case PPC::DIR_A2:
15118 case PPC::DIR_E500:
15119 case PPC::DIR_E500mc:
15120 case PPC::DIR_E5500:
15121 return 2;
15122 }
15123}
15124
15125// isConsecutiveLSLoc needs to work even if all adds have not yet been
15126// collapsed, and so we need to look through chains of them.
15128 int64_t& Offset, SelectionDAG &DAG) {
15129 if (DAG.isBaseWithConstantOffset(Loc)) {
15130 Base = Loc.getOperand(0);
15131 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
15132
15133 // The base might itself be a base plus an offset, and if so, accumulate
15134 // that as well.
15135 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
15136 }
15137}
15138
15140 unsigned Bytes, int Dist,
15141 SelectionDAG &DAG) {
15142 if (VT.getSizeInBits() / 8 != Bytes)
15143 return false;
15144
15145 SDValue BaseLoc = Base->getBasePtr();
15146 if (Loc.getOpcode() == ISD::FrameIndex) {
15147 if (BaseLoc.getOpcode() != ISD::FrameIndex)
15148 return false;
15150 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
15151 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
15152 int FS = MFI.getObjectSize(FI);
15153 int BFS = MFI.getObjectSize(BFI);
15154 if (FS != BFS || FS != (int)Bytes) return false;
15155 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
15156 }
15157
15158 SDValue Base1 = Loc, Base2 = BaseLoc;
15159 int64_t Offset1 = 0, Offset2 = 0;
15160 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
15161 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
15162 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
15163 return true;
15164
15165 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15166 const GlobalValue *GV1 = nullptr;
15167 const GlobalValue *GV2 = nullptr;
15168 Offset1 = 0;
15169 Offset2 = 0;
15170 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
15171 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
15172 if (isGA1 && isGA2 && GV1 == GV2)
15173 return Offset1 == (Offset2 + Dist*Bytes);
15174 return false;
15175}
15176
15177// Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
15178// not enforce equality of the chain operands.
15180 unsigned Bytes, int Dist,
15181 SelectionDAG &DAG) {
15183 EVT VT = LS->getMemoryVT();
15184 SDValue Loc = LS->getBasePtr();
15185 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
15186 }
15187
15188 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
15189 EVT VT;
15190 switch (N->getConstantOperandVal(1)) {
15191 default: return false;
15192 case Intrinsic::ppc_altivec_lvx:
15193 case Intrinsic::ppc_altivec_lvxl:
15194 case Intrinsic::ppc_vsx_lxvw4x:
15195 case Intrinsic::ppc_vsx_lxvw4x_be:
15196 VT = MVT::v4i32;
15197 break;
15198 case Intrinsic::ppc_vsx_lxvd2x:
15199 case Intrinsic::ppc_vsx_lxvd2x_be:
15200 VT = MVT::v2f64;
15201 break;
15202 case Intrinsic::ppc_altivec_lvebx:
15203 VT = MVT::i8;
15204 break;
15205 case Intrinsic::ppc_altivec_lvehx:
15206 VT = MVT::i16;
15207 break;
15208 case Intrinsic::ppc_altivec_lvewx:
15209 VT = MVT::i32;
15210 break;
15211 }
15212
15213 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
15214 }
15215
15216 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
15217 EVT VT;
15218 switch (N->getConstantOperandVal(1)) {
15219 default: return false;
15220 case Intrinsic::ppc_altivec_stvx:
15221 case Intrinsic::ppc_altivec_stvxl:
15222 case Intrinsic::ppc_vsx_stxvw4x:
15223 VT = MVT::v4i32;
15224 break;
15225 case Intrinsic::ppc_vsx_stxvd2x:
15226 VT = MVT::v2f64;
15227 break;
15228 case Intrinsic::ppc_vsx_stxvw4x_be:
15229 VT = MVT::v4i32;
15230 break;
15231 case Intrinsic::ppc_vsx_stxvd2x_be:
15232 VT = MVT::v2f64;
15233 break;
15234 case Intrinsic::ppc_altivec_stvebx:
15235 VT = MVT::i8;
15236 break;
15237 case Intrinsic::ppc_altivec_stvehx:
15238 VT = MVT::i16;
15239 break;
15240 case Intrinsic::ppc_altivec_stvewx:
15241 VT = MVT::i32;
15242 break;
15243 }
15244
15245 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
15246 }
15247
15248 return false;
15249}
15250
15251// Return true is there is a nearyby consecutive load to the one provided
15252// (regardless of alignment). We search up and down the chain, looking though
15253// token factors and other loads (but nothing else). As a result, a true result
15254// indicates that it is safe to create a new consecutive load adjacent to the
15255// load provided.
15257 SDValue Chain = LD->getChain();
15258 EVT VT = LD->getMemoryVT();
15259
15260 SmallPtrSet<SDNode *, 16> LoadRoots;
15261 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
15263
15264 // First, search up the chain, branching to follow all token-factor operands.
15265 // If we find a consecutive load, then we're done, otherwise, record all
15266 // nodes just above the top-level loads and token factors.
15267 while (!Queue.empty()) {
15268 SDNode *ChainNext = Queue.pop_back_val();
15269 if (!Visited.insert(ChainNext).second)
15270 continue;
15271
15272 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
15273 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15274 return true;
15275
15276 if (!Visited.count(ChainLD->getChain().getNode()))
15277 Queue.push_back(ChainLD->getChain().getNode());
15278 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
15279 for (const SDUse &O : ChainNext->ops())
15280 if (!Visited.count(O.getNode()))
15281 Queue.push_back(O.getNode());
15282 } else
15283 LoadRoots.insert(ChainNext);
15284 }
15285
15286 // Second, search down the chain, starting from the top-level nodes recorded
15287 // in the first phase. These top-level nodes are the nodes just above all
15288 // loads and token factors. Starting with their uses, recursively look though
15289 // all loads (just the chain uses) and token factors to find a consecutive
15290 // load.
15291 Visited.clear();
15292 Queue.clear();
15293
15294 for (SDNode *I : LoadRoots) {
15295 Queue.push_back(I);
15296
15297 while (!Queue.empty()) {
15298 SDNode *LoadRoot = Queue.pop_back_val();
15299 if (!Visited.insert(LoadRoot).second)
15300 continue;
15301
15302 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
15303 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15304 return true;
15305
15306 for (SDNode *U : LoadRoot->users())
15307 if (((isa<MemSDNode>(U) &&
15308 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
15309 U->getOpcode() == ISD::TokenFactor) &&
15310 !Visited.count(U))
15311 Queue.push_back(U);
15312 }
15313 }
15314
15315 return false;
15316}
15317
15318/// This function is called when we have proved that a SETCC node can be replaced
15319/// by subtraction (and other supporting instructions) so that the result of
15320/// comparison is kept in a GPR instead of CR. This function is purely for
15321/// codegen purposes and has some flags to guide the codegen process.
15322static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
15323 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
15324 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15325
15326 // Zero extend the operands to the largest legal integer. Originally, they
15327 // must be of a strictly smaller size.
15328 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
15329 DAG.getConstant(Size, DL, MVT::i32));
15330 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
15331 DAG.getConstant(Size, DL, MVT::i32));
15332
15333 // Swap if needed. Depends on the condition code.
15334 if (Swap)
15335 std::swap(Op0, Op1);
15336
15337 // Subtract extended integers.
15338 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
15339
15340 // Move the sign bit to the least significant position and zero out the rest.
15341 // Now the least significant bit carries the result of original comparison.
15342 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
15343 DAG.getConstant(Size - 1, DL, MVT::i32));
15344 auto Final = Shifted;
15345
15346 // Complement the result if needed. Based on the condition code.
15347 if (Complement)
15348 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
15349 DAG.getConstant(1, DL, MVT::i64));
15350
15351 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
15352}
15353
15354SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
15355 DAGCombinerInfo &DCI) const {
15356 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15357
15358 SelectionDAG &DAG = DCI.DAG;
15359 SDLoc DL(N);
15360
15361 // Size of integers being compared has a critical role in the following
15362 // analysis, so we prefer to do this when all types are legal.
15363 if (!DCI.isAfterLegalizeDAG())
15364 return SDValue();
15365
15366 // If all users of SETCC extend its value to a legal integer type
15367 // then we replace SETCC with a subtraction
15368 for (const SDNode *U : N->users())
15369 if (U->getOpcode() != ISD::ZERO_EXTEND)
15370 return SDValue();
15371
15372 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15373 auto OpSize = N->getOperand(0).getValueSizeInBits();
15374
15376
15377 if (OpSize < Size) {
15378 switch (CC) {
15379 default: break;
15380 case ISD::SETULT:
15381 return generateEquivalentSub(N, Size, false, false, DL, DAG);
15382 case ISD::SETULE:
15383 return generateEquivalentSub(N, Size, true, true, DL, DAG);
15384 case ISD::SETUGT:
15385 return generateEquivalentSub(N, Size, false, true, DL, DAG);
15386 case ISD::SETUGE:
15387 return generateEquivalentSub(N, Size, true, false, DL, DAG);
15388 }
15389 }
15390
15391 return SDValue();
15392}
15393
15394SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
15395 DAGCombinerInfo &DCI) const {
15396 SelectionDAG &DAG = DCI.DAG;
15397 SDLoc dl(N);
15398
15399 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
15400 // If we're tracking CR bits, we need to be careful that we don't have:
15401 // trunc(binary-ops(zext(x), zext(y)))
15402 // or
15403 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
15404 // such that we're unnecessarily moving things into GPRs when it would be
15405 // better to keep them in CR bits.
15406
15407 // Note that trunc here can be an actual i1 trunc, or can be the effective
15408 // truncation that comes from a setcc or select_cc.
15409 if (N->getOpcode() == ISD::TRUNCATE &&
15410 N->getValueType(0) != MVT::i1)
15411 return SDValue();
15412
15413 if (N->getOperand(0).getValueType() != MVT::i32 &&
15414 N->getOperand(0).getValueType() != MVT::i64)
15415 return SDValue();
15416
15417 if (N->getOpcode() == ISD::SETCC ||
15418 N->getOpcode() == ISD::SELECT_CC) {
15419 // If we're looking at a comparison, then we need to make sure that the
15420 // high bits (all except for the first) don't matter the result.
15421 ISD::CondCode CC =
15422 cast<CondCodeSDNode>(N->getOperand(
15423 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
15424 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
15425
15426 if (ISD::isSignedIntSetCC(CC)) {
15427 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
15428 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
15429 return SDValue();
15430 } else if (ISD::isUnsignedIntSetCC(CC)) {
15431 if (!DAG.MaskedValueIsZero(N->getOperand(0),
15432 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
15433 !DAG.MaskedValueIsZero(N->getOperand(1),
15434 APInt::getHighBitsSet(OpBits, OpBits-1)))
15435 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
15436 : SDValue());
15437 } else {
15438 // This is neither a signed nor an unsigned comparison, just make sure
15439 // that the high bits are equal.
15440 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
15441 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
15442
15443 // We don't really care about what is known about the first bit (if
15444 // anything), so pretend that it is known zero for both to ensure they can
15445 // be compared as constants.
15446 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
15447 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
15448
15449 if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
15450 Op1Known.getConstant() != Op2Known.getConstant())
15451 return SDValue();
15452 }
15453 }
15454
15455 // We now know that the higher-order bits are irrelevant, we just need to
15456 // make sure that all of the intermediate operations are bit operations, and
15457 // all inputs are extensions.
15458 if (N->getOperand(0).getOpcode() != ISD::AND &&
15459 N->getOperand(0).getOpcode() != ISD::OR &&
15460 N->getOperand(0).getOpcode() != ISD::XOR &&
15461 N->getOperand(0).getOpcode() != ISD::SELECT &&
15462 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
15463 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
15464 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
15465 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
15466 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
15467 return SDValue();
15468
15469 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
15470 N->getOperand(1).getOpcode() != ISD::AND &&
15471 N->getOperand(1).getOpcode() != ISD::OR &&
15472 N->getOperand(1).getOpcode() != ISD::XOR &&
15473 N->getOperand(1).getOpcode() != ISD::SELECT &&
15474 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
15475 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
15476 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
15477 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
15478 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
15479 return SDValue();
15480
15482 SmallVector<SDValue, 8> BinOps, PromOps;
15483 SmallPtrSet<SDNode *, 16> Visited;
15484
15485 for (unsigned i = 0; i < 2; ++i) {
15486 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15487 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15488 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15489 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15490 isa<ConstantSDNode>(N->getOperand(i)))
15491 Inputs.push_back(N->getOperand(i));
15492 else
15493 BinOps.push_back(N->getOperand(i));
15494
15495 if (N->getOpcode() == ISD::TRUNCATE)
15496 break;
15497 }
15498
15499 // Visit all inputs, collect all binary operations (and, or, xor and
15500 // select) that are all fed by extensions.
15501 while (!BinOps.empty()) {
15502 SDValue BinOp = BinOps.pop_back_val();
15503
15504 if (!Visited.insert(BinOp.getNode()).second)
15505 continue;
15506
15507 PromOps.push_back(BinOp);
15508
15509 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15510 // The condition of the select is not promoted.
15511 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15512 continue;
15513 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15514 continue;
15515
15516 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15517 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15518 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15519 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15520 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15521 Inputs.push_back(BinOp.getOperand(i));
15522 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15523 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15524 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15525 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15526 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
15527 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15528 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15529 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15530 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
15531 BinOps.push_back(BinOp.getOperand(i));
15532 } else {
15533 // We have an input that is not an extension or another binary
15534 // operation; we'll abort this transformation.
15535 return SDValue();
15536 }
15537 }
15538 }
15539
15540 // Make sure that this is a self-contained cluster of operations (which
15541 // is not quite the same thing as saying that everything has only one
15542 // use).
15543 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15544 if (isa<ConstantSDNode>(Inputs[i]))
15545 continue;
15546
15547 for (const SDNode *User : Inputs[i].getNode()->users()) {
15548 if (User != N && !Visited.count(User))
15549 return SDValue();
15550
15551 // Make sure that we're not going to promote the non-output-value
15552 // operand(s) or SELECT or SELECT_CC.
15553 // FIXME: Although we could sometimes handle this, and it does occur in
15554 // practice that one of the condition inputs to the select is also one of
15555 // the outputs, we currently can't deal with this.
15556 if (User->getOpcode() == ISD::SELECT) {
15557 if (User->getOperand(0) == Inputs[i])
15558 return SDValue();
15559 } else if (User->getOpcode() == ISD::SELECT_CC) {
15560 if (User->getOperand(0) == Inputs[i] ||
15561 User->getOperand(1) == Inputs[i])
15562 return SDValue();
15563 }
15564 }
15565 }
15566
15567 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15568 for (const SDNode *User : PromOps[i].getNode()->users()) {
15569 if (User != N && !Visited.count(User))
15570 return SDValue();
15571
15572 // Make sure that we're not going to promote the non-output-value
15573 // operand(s) or SELECT or SELECT_CC.
15574 // FIXME: Although we could sometimes handle this, and it does occur in
15575 // practice that one of the condition inputs to the select is also one of
15576 // the outputs, we currently can't deal with this.
15577 if (User->getOpcode() == ISD::SELECT) {
15578 if (User->getOperand(0) == PromOps[i])
15579 return SDValue();
15580 } else if (User->getOpcode() == ISD::SELECT_CC) {
15581 if (User->getOperand(0) == PromOps[i] ||
15582 User->getOperand(1) == PromOps[i])
15583 return SDValue();
15584 }
15585 }
15586 }
15587
15588 // Replace all inputs with the extension operand.
15589 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15590 // Constants may have users outside the cluster of to-be-promoted nodes,
15591 // and so we need to replace those as we do the promotions.
15592 if (isa<ConstantSDNode>(Inputs[i]))
15593 continue;
15594 else
15595 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
15596 }
15597
15598 std::list<HandleSDNode> PromOpHandles;
15599 for (auto &PromOp : PromOps)
15600 PromOpHandles.emplace_back(PromOp);
15601
15602 // Replace all operations (these are all the same, but have a different
15603 // (i1) return type). DAG.getNode will validate that the types of
15604 // a binary operator match, so go through the list in reverse so that
15605 // we've likely promoted both operands first. Any intermediate truncations or
15606 // extensions disappear.
15607 while (!PromOpHandles.empty()) {
15608 SDValue PromOp = PromOpHandles.back().getValue();
15609 PromOpHandles.pop_back();
15610
15611 if (PromOp.getOpcode() == ISD::TRUNCATE ||
15612 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
15613 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
15614 PromOp.getOpcode() == ISD::ANY_EXTEND) {
15615 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
15616 PromOp.getOperand(0).getValueType() != MVT::i1) {
15617 // The operand is not yet ready (see comment below).
15618 PromOpHandles.emplace_front(PromOp);
15619 continue;
15620 }
15621
15622 SDValue RepValue = PromOp.getOperand(0);
15623 if (isa<ConstantSDNode>(RepValue))
15624 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
15625
15626 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
15627 continue;
15628 }
15629
15630 unsigned C;
15631 switch (PromOp.getOpcode()) {
15632 default: C = 0; break;
15633 case ISD::SELECT: C = 1; break;
15634 case ISD::SELECT_CC: C = 2; break;
15635 }
15636
15637 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15638 PromOp.getOperand(C).getValueType() != MVT::i1) ||
15639 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15640 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
15641 // The to-be-promoted operands of this node have not yet been
15642 // promoted (this should be rare because we're going through the
15643 // list backward, but if one of the operands has several users in
15644 // this cluster of to-be-promoted nodes, it is possible).
15645 PromOpHandles.emplace_front(PromOp);
15646 continue;
15647 }
15648
15650
15651 // If there are any constant inputs, make sure they're replaced now.
15652 for (unsigned i = 0; i < 2; ++i)
15653 if (isa<ConstantSDNode>(Ops[C+i]))
15654 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
15655
15656 DAG.ReplaceAllUsesOfValueWith(PromOp,
15657 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
15658 }
15659
15660 // Now we're left with the initial truncation itself.
15661 if (N->getOpcode() == ISD::TRUNCATE)
15662 return N->getOperand(0);
15663
15664 // Otherwise, this is a comparison. The operands to be compared have just
15665 // changed type (to i1), but everything else is the same.
15666 return SDValue(N, 0);
15667}
15668
15669SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
15670 DAGCombinerInfo &DCI) const {
15671 SelectionDAG &DAG = DCI.DAG;
15672 SDLoc dl(N);
15673
15674 // If we're tracking CR bits, we need to be careful that we don't have:
15675 // zext(binary-ops(trunc(x), trunc(y)))
15676 // or
15677 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
15678 // such that we're unnecessarily moving things into CR bits that can more
15679 // efficiently stay in GPRs. Note that if we're not certain that the high
15680 // bits are set as required by the final extension, we still may need to do
15681 // some masking to get the proper behavior.
15682
15683 // This same functionality is important on PPC64 when dealing with
15684 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
15685 // the return values of functions. Because it is so similar, it is handled
15686 // here as well.
15687
15688 if (N->getValueType(0) != MVT::i32 &&
15689 N->getValueType(0) != MVT::i64)
15690 return SDValue();
15691
15692 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
15693 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
15694 return SDValue();
15695
15696 if (N->getOperand(0).getOpcode() != ISD::AND &&
15697 N->getOperand(0).getOpcode() != ISD::OR &&
15698 N->getOperand(0).getOpcode() != ISD::XOR &&
15699 N->getOperand(0).getOpcode() != ISD::SELECT &&
15700 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
15701 return SDValue();
15702
15704 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
15705 SmallPtrSet<SDNode *, 16> Visited;
15706
15707 // Visit all inputs, collect all binary operations (and, or, xor and
15708 // select) that are all fed by truncations.
15709 while (!BinOps.empty()) {
15710 SDValue BinOp = BinOps.pop_back_val();
15711
15712 if (!Visited.insert(BinOp.getNode()).second)
15713 continue;
15714
15715 PromOps.push_back(BinOp);
15716
15717 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15718 // The condition of the select is not promoted.
15719 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15720 continue;
15721 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15722 continue;
15723
15724 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15725 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15726 Inputs.push_back(BinOp.getOperand(i));
15727 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15728 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15729 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15730 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15731 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
15732 BinOps.push_back(BinOp.getOperand(i));
15733 } else {
15734 // We have an input that is not a truncation or another binary
15735 // operation; we'll abort this transformation.
15736 return SDValue();
15737 }
15738 }
15739 }
15740
15741 // The operands of a select that must be truncated when the select is
15742 // promoted because the operand is actually part of the to-be-promoted set.
15743 DenseMap<SDNode *, EVT> SelectTruncOp[2];
15744
15745 // Make sure that this is a self-contained cluster of operations (which
15746 // is not quite the same thing as saying that everything has only one
15747 // use).
15748 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15749 if (isa<ConstantSDNode>(Inputs[i]))
15750 continue;
15751
15752 for (SDNode *User : Inputs[i].getNode()->users()) {
15753 if (User != N && !Visited.count(User))
15754 return SDValue();
15755
15756 // If we're going to promote the non-output-value operand(s) or SELECT or
15757 // SELECT_CC, record them for truncation.
15758 if (User->getOpcode() == ISD::SELECT) {
15759 if (User->getOperand(0) == Inputs[i])
15760 SelectTruncOp[0].insert(std::make_pair(User,
15761 User->getOperand(0).getValueType()));
15762 } else if (User->getOpcode() == ISD::SELECT_CC) {
15763 if (User->getOperand(0) == Inputs[i])
15764 SelectTruncOp[0].insert(std::make_pair(User,
15765 User->getOperand(0).getValueType()));
15766 if (User->getOperand(1) == Inputs[i])
15767 SelectTruncOp[1].insert(std::make_pair(User,
15768 User->getOperand(1).getValueType()));
15769 }
15770 }
15771 }
15772
15773 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15774 for (SDNode *User : PromOps[i].getNode()->users()) {
15775 if (User != N && !Visited.count(User))
15776 return SDValue();
15777
15778 // If we're going to promote the non-output-value operand(s) or SELECT or
15779 // SELECT_CC, record them for truncation.
15780 if (User->getOpcode() == ISD::SELECT) {
15781 if (User->getOperand(0) == PromOps[i])
15782 SelectTruncOp[0].insert(std::make_pair(User,
15783 User->getOperand(0).getValueType()));
15784 } else if (User->getOpcode() == ISD::SELECT_CC) {
15785 if (User->getOperand(0) == PromOps[i])
15786 SelectTruncOp[0].insert(std::make_pair(User,
15787 User->getOperand(0).getValueType()));
15788 if (User->getOperand(1) == PromOps[i])
15789 SelectTruncOp[1].insert(std::make_pair(User,
15790 User->getOperand(1).getValueType()));
15791 }
15792 }
15793 }
15794
15795 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
15796 bool ReallyNeedsExt = false;
15797 if (N->getOpcode() != ISD::ANY_EXTEND) {
15798 // If all of the inputs are not already sign/zero extended, then
15799 // we'll still need to do that at the end.
15800 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15801 if (isa<ConstantSDNode>(Inputs[i]))
15802 continue;
15803
15804 unsigned OpBits =
15805 Inputs[i].getOperand(0).getValueSizeInBits();
15806 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
15807
15808 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
15809 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
15810 APInt::getHighBitsSet(OpBits,
15811 OpBits-PromBits))) ||
15812 (N->getOpcode() == ISD::SIGN_EXTEND &&
15813 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
15814 (OpBits-(PromBits-1)))) {
15815 ReallyNeedsExt = true;
15816 break;
15817 }
15818 }
15819 }
15820
15821 // Convert PromOps to handles before doing any RAUW operations, as these
15822 // may CSE with existing nodes, deleting the originals.
15823 std::list<HandleSDNode> PromOpHandles;
15824 for (auto &PromOp : PromOps)
15825 PromOpHandles.emplace_back(PromOp);
15826
15827 // Replace all inputs, either with the truncation operand, or a
15828 // truncation or extension to the final output type.
15829 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15830 // Constant inputs need to be replaced with the to-be-promoted nodes that
15831 // use them because they might have users outside of the cluster of
15832 // promoted nodes.
15833 if (isa<ConstantSDNode>(Inputs[i]))
15834 continue;
15835
15836 SDValue InSrc = Inputs[i].getOperand(0);
15837 if (Inputs[i].getValueType() == N->getValueType(0))
15838 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
15839 else if (N->getOpcode() == ISD::SIGN_EXTEND)
15840 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15841 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
15842 else if (N->getOpcode() == ISD::ZERO_EXTEND)
15843 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15844 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
15845 else
15846 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15847 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
15848 }
15849
15850 // Replace all operations (these are all the same, but have a different
15851 // (promoted) return type). DAG.getNode will validate that the types of
15852 // a binary operator match, so go through the list in reverse so that
15853 // we've likely promoted both operands first.
15854 while (!PromOpHandles.empty()) {
15855 SDValue PromOp = PromOpHandles.back().getValue();
15856 PromOpHandles.pop_back();
15857
15858 unsigned C;
15859 switch (PromOp.getOpcode()) {
15860 default: C = 0; break;
15861 case ISD::SELECT: C = 1; break;
15862 case ISD::SELECT_CC: C = 2; break;
15863 }
15864
15865 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15866 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
15867 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15868 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
15869 // The to-be-promoted operands of this node have not yet been
15870 // promoted (this should be rare because we're going through the
15871 // list backward, but if one of the operands has several users in
15872 // this cluster of to-be-promoted nodes, it is possible).
15873 PromOpHandles.emplace_front(PromOp);
15874 continue;
15875 }
15876
15877 // For SELECT and SELECT_CC nodes, we do a similar check for any
15878 // to-be-promoted comparison inputs.
15879 if (PromOp.getOpcode() == ISD::SELECT ||
15880 PromOp.getOpcode() == ISD::SELECT_CC) {
15881 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
15882 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
15883 (SelectTruncOp[1].count(PromOp.getNode()) &&
15884 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
15885 PromOpHandles.emplace_front(PromOp);
15886 continue;
15887 }
15888 }
15889
15891
15892 // If this node has constant inputs, then they'll need to be promoted here.
15893 for (unsigned i = 0; i < 2; ++i) {
15894 if (!isa<ConstantSDNode>(Ops[C+i]))
15895 continue;
15896 if (Ops[C+i].getValueType() == N->getValueType(0))
15897 continue;
15898
15899 if (N->getOpcode() == ISD::SIGN_EXTEND)
15900 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15901 else if (N->getOpcode() == ISD::ZERO_EXTEND)
15902 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15903 else
15904 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15905 }
15906
15907 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
15908 // truncate them again to the original value type.
15909 if (PromOp.getOpcode() == ISD::SELECT ||
15910 PromOp.getOpcode() == ISD::SELECT_CC) {
15911 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
15912 if (SI0 != SelectTruncOp[0].end())
15913 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
15914 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
15915 if (SI1 != SelectTruncOp[1].end())
15916 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
15917 }
15918
15919 DAG.ReplaceAllUsesOfValueWith(PromOp,
15920 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
15921 }
15922
15923 // Now we're left with the initial extension itself.
15924 if (!ReallyNeedsExt)
15925 return N->getOperand(0);
15926
15927 // To zero extend, just mask off everything except for the first bit (in the
15928 // i1 case).
15929 if (N->getOpcode() == ISD::ZERO_EXTEND)
15930 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
15932 N->getValueSizeInBits(0), PromBits),
15933 dl, N->getValueType(0)));
15934
15935 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
15936 "Invalid extension type");
15937 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
15938 SDValue ShiftCst =
15939 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
15940 return DAG.getNode(
15941 ISD::SRA, dl, N->getValueType(0),
15942 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
15943 ShiftCst);
15944}
15945
15946// The function check a i128 load can convert to 16i8 load for Vcmpequb.
15947static bool canConvertToVcmpequb(SDValue &LHS, SDValue &RHS, bool IsPPC64) {
15948
15949 auto isValidForConvert = [IsPPC64](SDValue &Operand) {
15950 if (!Operand.hasOneUse())
15951 return false;
15952
15953 if (Operand.getValueType() != MVT::i128)
15954 return false;
15955
15956 if (Operand.getOpcode() == ISD::Constant) {
15957 auto *C = cast<ConstantSDNode>(Operand);
15958 const APInt &Val = C->getAPIntValue();
15959 // On PPC64, comparing an i128 value loaded from memory against a
15960 // constant smaller than 2^16 is usually better left to scalar lowering.
15961 // In that case, the compare can be lowered using xori (since xori has a
15962 // 16-bit immediate field), which is cheaper than materializing a vector
15963 // constant and using vcmpequb.
15964 if (IsPPC64 && Val.ult(1ULL << 16))
15965 return false;
15966 return true;
15967 }
15968
15969 auto *LoadNode = dyn_cast<LoadSDNode>(Operand);
15970 if (!LoadNode)
15971 return false;
15972
15973 // If memory operation is volatile, do not perform any
15974 // optimization or transformation. Volatile operations must be preserved
15975 // as written to ensure correct program behavior, so we return an empty
15976 // SDValue to indicate no action.
15977
15978 if (LoadNode->isVolatile())
15979 return false;
15980
15981 // Only combine loads if both use the unindexed addressing mode.
15982 // PowerPC AltiVec/VMX does not support vector loads or stores with
15983 // pre/post-increment addressing. Indexed modes may imply implicit
15984 // pointer updates, which are not compatible with AltiVec vector
15985 // instructions.
15986 if (LoadNode->getAddressingMode() != ISD::UNINDEXED)
15987 return false;
15988
15989 // Only combine loads if both are non-extending loads
15990 // (ISD::NON_EXTLOAD). Extending loads (such as ISD::ZEXTLOAD or
15991 // ISD::SEXTLOAD) perform zero or sign extension, which may change the
15992 // loaded value's semantics and are not compatible with vector loads.
15993 if (LoadNode->getExtensionType() != ISD::NON_EXTLOAD)
15994 return false;
15995
15996 return true;
15997 };
15998
15999 return (isValidForConvert(LHS) && isValidForConvert(RHS));
16000}
16001
16003 const SDLoc &DL) {
16004
16005 assert(N->getOpcode() == ISD::SETCC && "Should be called with a SETCC node");
16006
16007 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16008 assert((CC == ISD::SETNE || CC == ISD::SETEQ) &&
16009 "CC mus be ISD::SETNE or ISD::SETEQ");
16010
16011 auto getV16i8Load = [&](const SDValue &Operand) {
16012 if (Operand.getOpcode() == ISD::Constant)
16013 return DAG.getBitcast(MVT::v16i8, Operand);
16014
16015 assert(Operand.getOpcode() == ISD::LOAD && "Must be LoadSDNode here.");
16016
16017 auto *LoadNode = cast<LoadSDNode>(Operand);
16018 // Create a new MachineMemOperand without range metadata.
16019 // Range metadata is only valid for integer scalar types, not vectors.
16020 // The original i128 load may have range metadata, but when we convert
16021 // to v16i8, that metadata is no longer semantically valid.
16022 MachineMemOperand *MMO = LoadNode->getMemOperand();
16025 MMO->getPointerInfo(), MMO->getFlags(), MMO->getSize(), MMO->getAlign(),
16026 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
16027 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
16028 SDValue NewLoad = DAG.getLoad(MVT::v16i8, DL, LoadNode->getChain(),
16029 LoadNode->getBasePtr(), NewMMO);
16030 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadNode, 1), NewLoad.getValue(1));
16031 return NewLoad;
16032 };
16033
16034 // Following code transforms the DAG
16035 // t0: ch,glue = EntryToken
16036 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16037 // t3: i128,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16038 // undef:i64
16039 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16040 // t5: i128,ch =
16041 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64 t6: i1 =
16042 // setcc t3, t5, setne:ch
16043 //
16044 // ---->
16045 //
16046 // t0: ch,glue = EntryToken
16047 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16048 // t3: v16i8,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16049 // undef:i64
16050 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16051 // t5: v16i8,ch =
16052 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64
16053 // t6: i32 =
16054 // llvm.ppc.altivec.vcmpequb.p TargetConstant:i32<10505>,
16055 // Constant:i32<2>, t3, t5
16056 // t7: i1 = setcc t6, Constant:i32<0>, seteq:ch
16057
16058 // Or transforms the DAG
16059 // t5: i128,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16060 // t8: i1 =
16061 // setcc Constant:i128<237684487579686500932345921536>, t5, setne:ch
16062 //
16063 // --->
16064 //
16065 // t5: v16i8,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16066 // t6: v16i8 = bitcast Constant:i128<237684487579686500932345921536>
16067 // t7: i32 =
16068 // llvm.ppc.altivec.vcmpequb.p Constant:i32<10962>, Constant:i32<2>, t5, t2
16069
16070 SDValue LHSVec = getV16i8Load(N->getOperand(0));
16071 SDValue RHSVec = getV16i8Load(N->getOperand(1));
16072
16073 SDValue IntrID =
16074 DAG.getConstant(Intrinsic::ppc_altivec_vcmpequb_p, DL, MVT::i32);
16075 SDValue CRSel = DAG.getConstant(2, DL, MVT::i32); // which CR6 predicate field
16076 SDValue PredResult = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
16077 IntrID, CRSel, LHSVec, RHSVec);
16078 // ppc_altivec_vcmpequb_p returns 1 when two vectors are the same,
16079 // so we need to invert the CC opcode.
16080 return DAG.getSetCC(DL, N->getValueType(0), PredResult,
16081 DAG.getConstant(0, DL, MVT::i32),
16082 CC == ISD::SETNE ? ISD::SETEQ : ISD::SETNE);
16083}
16084
16085// Detect whether there is a pattern like (setcc (and X, 1), 0, eq).
16086// If it is , return true; otherwise return false.
16088 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16089
16090 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16091 if (CC != ISD::SETEQ)
16092 return false;
16093
16094 SDValue LHS = N->getOperand(0);
16095 SDValue RHS = N->getOperand(1);
16096
16097 // Check the `SDValue &V` is from `and` with `1`.
16098 auto IsAndWithOne = [](SDValue &V) {
16099 if (V.getOpcode() == ISD::AND) {
16100 for (const SDValue &Op : V->ops())
16101 if (auto *C = dyn_cast<ConstantSDNode>(Op))
16102 if (C->isOne())
16103 return true;
16104 }
16105 return false;
16106 };
16107
16108 // Check whether the SETCC compare with zero.
16109 auto IsCompareWithZero = [](SDValue &V) {
16110 if (auto *C = dyn_cast<ConstantSDNode>(V))
16111 if (C->isZero())
16112 return true;
16113 return false;
16114 };
16115
16116 return (IsAndWithOne(LHS) && IsCompareWithZero(RHS)) ||
16117 (IsAndWithOne(RHS) && IsCompareWithZero(LHS));
16118}
16119
16120// You must check whether the `SDNode* N` can be converted to Xori using
16121// the function `static bool canConvertSETCCToXori(SDNode *N)`
16122// before calling the function; otherwise, it may produce incorrect results.
16124
16125 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16126 SDValue LHS = N->getOperand(0);
16127 SDValue RHS = N->getOperand(1);
16128 SDLoc DL(N);
16129
16130 [[maybe_unused]] ISD::CondCode CC =
16131 cast<CondCodeSDNode>(N->getOperand(2))->get();
16132 assert((CC == ISD::SETEQ) && "CC must be ISD::SETEQ.");
16133 // Rewrite it as XORI (and X, 1), 1.
16134 auto MakeXor1 = [&](SDValue V) {
16135 EVT VT = V.getValueType();
16136 SDValue One = DAG.getConstant(1, DL, VT);
16137 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, V, One);
16138 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Xor);
16139 };
16140
16141 if (LHS.getOpcode() == ISD::AND && RHS.getOpcode() != ISD::AND)
16142 return MakeXor1(LHS);
16143
16144 if (RHS.getOpcode() == ISD::AND && LHS.getOpcode() != ISD::AND)
16145 return MakeXor1(RHS);
16146
16147 llvm_unreachable("Should not reach here.");
16148}
16149
16150// Match `sext(setcc X, 0, eq)` and turn it into an ADDIC/SUBFE sequence.
16151//
16152// This generates code for:
16153// X == 0 ? -1 : 0
16154//
16155// On pre-ISA 3.1 targets, this is better than the longer CNTLZW/SRWI/NEG
16156// sequence. This is useful for cases like:
16157// uint8_t f(uint8_t x) { return (x == 0) ? -1 : 0; }
16158//
16159// ISA 3.1+ is skipped because those targets can use SETBC.
16160
16161SDValue PPCTargetLowering::combineSignExtendSetCC(SDNode *N,
16162 DAGCombinerInfo &DCI) const {
16163 if (Subtarget.isISA3_1())
16164 return SDValue();
16165
16166 EVT VT = N->getValueType(0);
16167 if (VT != MVT::i32 && (VT != MVT::i64 || !Subtarget.isPPC64()))
16168 return SDValue();
16169
16170 SDValue N0 = N->getOperand(0);
16171 if (N0.getOpcode() != ISD::SETCC)
16172 return SDValue();
16173
16175 SDValue LHS = N0.getOperand(0);
16176 SDValue RHS = N0.getOperand(1);
16177
16178 // Not match: sext (setcc x, 0, eq) or sext (setcc 0, x, eq)
16179 if (CC != ISD::SETEQ || (!isNullConstant(LHS) && !isNullConstant(RHS)))
16180 return SDValue();
16181
16182 SDLoc dl(N);
16183 SelectionDAG &DAG = DCI.DAG;
16185 EVT XVT = X.getValueType(); // The type of x in the setcc x, 0, eq.
16186
16187 // The type that ADDC/SUBE operate on. Reject larger types and zero-extend
16188 // smaller ones.
16189 MVT OpVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
16190 if (XVT.bitsGT(OpVT))
16191 return SDValue();
16192
16193 if (XVT.bitsLT(OpVT))
16194 X = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, X);
16195
16196 // Generate: SUBFE(ADDC(X, -1)).
16197 SDValue MinusOne = DAG.getAllOnesConstant(dl, OpVT);
16198 SDValue Addc =
16199 DAG.getNode(PPCISD::ADDC, dl, DAG.getVTList(OpVT, MVT::i32), X, MinusOne);
16200 SDValue Carry = Addc.getValue(1);
16201 SDValue Sube = DAG.getNode(PPCISD::SUBE, dl, DAG.getVTList(OpVT, MVT::i32),
16202 Addc, Addc, Carry);
16203
16204 // Truncate back to i32 if we used i64 operations.
16205 if (OpVT == MVT::i64 && VT == MVT::i32)
16206 return DAG.getNode(ISD::TRUNCATE, dl, VT, Sube);
16207
16208 return Sube;
16209}
16210
16211SDValue PPCTargetLowering::combineSetCC(SDNode *N,
16212 DAGCombinerInfo &DCI) const {
16213 assert(N->getOpcode() == ISD::SETCC &&
16214 "Should be called with a SETCC node");
16215
16216 // Check if the pattern (setcc (and X, 1), 0, eq) is present.
16217 // If it is, rewrite it as XORI (and X, 1), 1.
16219 return ConvertSETCCToXori(N, DCI.DAG);
16220
16221 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16222 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
16223 SDValue LHS = N->getOperand(0);
16224 SDValue RHS = N->getOperand(1);
16225
16226 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
16227 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
16228 LHS.hasOneUse())
16229 std::swap(LHS, RHS);
16230
16231 // x == 0-y --> x+y == 0
16232 // x != 0-y --> x+y != 0
16233 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
16234 RHS.hasOneUse()) {
16235 SDLoc DL(N);
16236 SelectionDAG &DAG = DCI.DAG;
16237 EVT VT = N->getValueType(0);
16238 EVT OpVT = LHS.getValueType();
16239 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
16240 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
16241 }
16242
16243 // Optimization: Fold i128 equality/inequality compares of two loads into a
16244 // vectorized compare using vcmpequb.p when Altivec is available.
16245 //
16246 // Rationale:
16247 // A scalar i128 SETCC (eq/ne) normally lowers to multiple scalar ops.
16248 // On VSX-capable subtargets, we can instead reinterpret the i128 loads
16249 // as v16i8 vectors and use the Altive vcmpequb.p instruction to
16250 // perform a full 128-bit equality check in a single vector compare.
16251 //
16252 // Example Result:
16253 // This transformation replaces memcmp(a, b, 16) with two vector loads
16254 // and one vector compare instruction.
16255
16256 if (Subtarget.hasAltivec() &&
16257 canConvertToVcmpequb(LHS, RHS, Subtarget.isPPC64()))
16258 return convertTwoLoadsAndCmpToVCMPEQUB(DCI.DAG, N, SDLoc(N));
16259 }
16260
16261 return DAGCombineTruncBoolExt(N, DCI);
16262}
16263
16264// Is this an extending load from an f32 to an f64?
16265static bool isFPExtLoad(SDValue Op) {
16266 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
16267 return LD->getExtensionType() == ISD::EXTLOAD &&
16268 Op.getValueType() == MVT::f64;
16269 return false;
16270}
16271
16272/// Reduces the number of fp-to-int conversion when building a vector.
16273///
16274/// If this vector is built out of floating to integer conversions,
16275/// transform it to a vector built out of floating point values followed by a
16276/// single floating to integer conversion of the vector.
16277/// Namely (build_vector (fptosi $A), (fptosi $B), ...)
16278/// becomes (fptosi (build_vector ($A, $B, ...)))
16279SDValue PPCTargetLowering::
16280combineElementTruncationToVectorTruncation(SDNode *N,
16281 DAGCombinerInfo &DCI) const {
16282 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16283 "Should be called with a BUILD_VECTOR node");
16284
16285 SelectionDAG &DAG = DCI.DAG;
16286 SDLoc dl(N);
16287
16288 SDValue FirstInput = N->getOperand(0);
16289 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
16290 "The input operand must be an fp-to-int conversion.");
16291
16292 // This combine happens after legalization so the fp_to_[su]i nodes are
16293 // already converted to PPCSISD nodes.
16294 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
16295 if (FirstConversion == PPCISD::FCTIDZ ||
16296 FirstConversion == PPCISD::FCTIDUZ ||
16297 FirstConversion == PPCISD::FCTIWZ ||
16298 FirstConversion == PPCISD::FCTIWUZ) {
16299 bool IsSplat = true;
16300 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
16301 FirstConversion == PPCISD::FCTIWUZ;
16302 EVT SrcVT = FirstInput.getOperand(0).getValueType();
16304 EVT TargetVT = N->getValueType(0);
16305 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16306 SDValue NextOp = N->getOperand(i);
16307 if (NextOp.getOpcode() != PPCISD::MFVSR)
16308 return SDValue();
16309 unsigned NextConversion = NextOp.getOperand(0).getOpcode();
16310 if (NextConversion != FirstConversion)
16311 return SDValue();
16312 // If we are converting to 32-bit integers, we need to add an FP_ROUND.
16313 // This is not valid if the input was originally double precision. It is
16314 // also not profitable to do unless this is an extending load in which
16315 // case doing this combine will allow us to combine consecutive loads.
16316 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
16317 return SDValue();
16318 if (N->getOperand(i) != FirstInput)
16319 IsSplat = false;
16320 }
16321
16322 // If this is a splat, we leave it as-is since there will be only a single
16323 // fp-to-int conversion followed by a splat of the integer. This is better
16324 // for 32-bit and smaller ints and neutral for 64-bit ints.
16325 if (IsSplat)
16326 return SDValue();
16327
16328 // Now that we know we have the right type of node, get its operands
16329 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16330 SDValue In = N->getOperand(i).getOperand(0);
16331 if (Is32Bit) {
16332 // For 32-bit values, we need to add an FP_ROUND node (if we made it
16333 // here, we know that all inputs are extending loads so this is safe).
16334 if (In.isUndef())
16335 Ops.push_back(DAG.getUNDEF(SrcVT));
16336 else {
16337 SDValue Trunc =
16338 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0),
16339 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
16340 Ops.push_back(Trunc);
16341 }
16342 } else
16343 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
16344 }
16345
16346 unsigned Opcode;
16347 if (FirstConversion == PPCISD::FCTIDZ ||
16348 FirstConversion == PPCISD::FCTIWZ)
16349 Opcode = ISD::FP_TO_SINT;
16350 else
16351 Opcode = ISD::FP_TO_UINT;
16352
16353 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
16354 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
16355 return DAG.getNode(Opcode, dl, TargetVT, BV);
16356 }
16357 return SDValue();
16358}
16359
16360// LXVKQ instruction load VSX vector with a special quadword value
16361// based on an immediate value. This helper method returns the details of the
16362// match as a tuple of {LXVKQ unsigned IMM Value, right_shift_amount}
16363// to help generate the LXVKQ instruction and the subsequent shift instruction
16364// required to match the original build vector pattern.
16365
16366// LXVKQPattern: {LXVKQ unsigned IMM Value, right_shift_amount}
16367using LXVKQPattern = std::tuple<uint32_t, uint8_t>;
16368
16369static std::optional<LXVKQPattern> getPatternInfo(const APInt &FullVal) {
16370
16371 // LXVKQ instruction loads the Quadword value:
16372 // 0x8000_0000_0000_0000_0000_0000_0000_0000 when imm = 0b10000
16373 static const APInt BasePattern = APInt(128, 0x8000000000000000ULL) << 64;
16374 static const uint32_t Uim = 16;
16375
16376 // Check for direct LXVKQ match (no shift needed)
16377 if (FullVal == BasePattern)
16378 return std::make_tuple(Uim, uint8_t{0});
16379
16380 // Check if FullValue is 1 (the result of the base pattern >> 127)
16381 if (FullVal == APInt(128, 1))
16382 return std::make_tuple(Uim, uint8_t{127});
16383
16384 return std::nullopt;
16385}
16386
16387/// Combine vector loads to a single load (using lxvkq) or splat with shift of a
16388/// constant (xxspltib + vsrq) by recognising patterns in the Build Vector.
16389/// LXVKQ instruction load VSX vector with a special quadword value based on an
16390/// immediate value. if UIM=0b10000 then LXVKQ loads VSR[32×TX+T] with value
16391/// 0x8000_0000_0000_0000_0000_0000_0000_0000.
16392/// This can be used to inline the build vector constants that have the
16393/// following patterns:
16394///
16395/// 0x8000_0000_0000_0000_0000_0000_0000_0000 (MSB set pattern)
16396/// 0x0000_0000_0000_0000_0000_0000_0000_0001 (LSB set pattern)
16397/// MSB pattern can directly loaded using LXVKQ while LSB is loaded using a
16398/// combination of splatting and right shift instructions.
16399
16400SDValue PPCTargetLowering::combineBVLoadsSpecialValue(SDValue Op,
16401 SelectionDAG &DAG) const {
16402
16403 assert((Op.getNode() && Op.getOpcode() == ISD::BUILD_VECTOR) &&
16404 "Expected a BuildVectorSDNode in combineBVLoadsSpecialValue");
16405
16406 // This transformation is only supported if we are loading either a byte,
16407 // halfword, word, or doubleword.
16408 EVT VT = Op.getValueType();
16409 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
16410 VT == MVT::v2i64))
16411 return SDValue();
16412
16413 LLVM_DEBUG(llvm::dbgs() << "\ncombineBVLoadsSpecialValue: Build vector ("
16414 << VT.getEVTString() << "): ";
16415 Op->dump());
16416
16417 unsigned NumElems = VT.getVectorNumElements();
16418 unsigned ElemBits = VT.getScalarSizeInBits();
16419
16420 bool IsLittleEndian = DAG.getDataLayout().isLittleEndian();
16421
16422 // Check for Non-constant operand in the build vector.
16423 for (const SDValue &Operand : Op.getNode()->op_values()) {
16424 if (!isa<ConstantSDNode>(Operand))
16425 return SDValue();
16426 }
16427
16428 // Assemble build vector operands as a 128-bit register value
16429 // We need to reconstruct what the 128-bit register pattern would be
16430 // that produces this vector when interpreted with the current endianness
16431 APInt FullVal = APInt::getZero(128);
16432
16433 for (unsigned Index = 0; Index < NumElems; ++Index) {
16434 auto *C = cast<ConstantSDNode>(Op.getOperand(Index));
16435
16436 // Get element value as raw bits (zero-extended)
16437 uint64_t ElemValue = C->getZExtValue();
16438
16439 // Mask to element size to ensure we only get the relevant bits
16440 if (ElemBits < 64)
16441 ElemValue &= ((1ULL << ElemBits) - 1);
16442
16443 // Calculate bit position for this element in the 128-bit register
16444 unsigned BitPos =
16445 (IsLittleEndian) ? (Index * ElemBits) : (128 - (Index + 1) * ElemBits);
16446
16447 // Create APInt for the element value and shift it to correct position
16448 APInt ElemAPInt(128, ElemValue);
16449 ElemAPInt <<= BitPos;
16450
16451 // Place the element value at the correct bit position
16452 FullVal |= ElemAPInt;
16453 }
16454
16455 if (FullVal.isZero() || FullVal.isAllOnes())
16456 return SDValue();
16457
16458 if (auto UIMOpt = getPatternInfo(FullVal)) {
16459 const auto &[Uim, ShiftAmount] = *UIMOpt;
16460 SDLoc Dl(Op);
16461
16462 // Generate LXVKQ instruction if the shift amount is zero.
16463 if (ShiftAmount == 0) {
16464 SDValue UimVal = DAG.getTargetConstant(Uim, Dl, MVT::i32);
16465 SDValue LxvkqInstr =
16466 SDValue(DAG.getMachineNode(PPC::LXVKQ, Dl, VT, UimVal), 0);
16468 << "combineBVLoadsSpecialValue: Instruction Emitted ";
16469 LxvkqInstr.dump());
16470 return LxvkqInstr;
16471 }
16472
16473 assert(ShiftAmount == 127 && "Unexpected lxvkq shift amount value");
16474
16475 // The right shifted pattern can be constructed using a combination of
16476 // XXSPLTIB and VSRQ instruction. VSRQ uses the shift amount from the lower
16477 // 7 bits of byte 15. This can be specified using XXSPLTIB with immediate
16478 // value 255.
16479 SDValue ShiftAmountVec =
16480 SDValue(DAG.getMachineNode(PPC::XXSPLTIB, Dl, MVT::v4i32,
16481 DAG.getTargetConstant(255, Dl, MVT::i32)),
16482 0);
16483 // Generate appropriate right shift instruction
16484 SDValue ShiftVec = SDValue(
16485 DAG.getMachineNode(PPC::VSRQ, Dl, VT, ShiftAmountVec, ShiftAmountVec),
16486 0);
16488 << "\n combineBVLoadsSpecialValue: Instruction Emitted ";
16489 ShiftVec.dump());
16490 return ShiftVec;
16491 }
16492 // No patterns matched for build vectors.
16493 return SDValue();
16494}
16495
16496/// Reduce the number of loads when building a vector.
16497///
16498/// Building a vector out of multiple loads can be converted to a load
16499/// of the vector type if the loads are consecutive. If the loads are
16500/// consecutive but in descending order, a shuffle is added at the end
16501/// to reorder the vector.
16503 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16504 "Should be called with a BUILD_VECTOR node");
16505
16506 SDLoc dl(N);
16507
16508 // Return early for non byte-sized type, as they can't be consecutive.
16509 if (!N->getValueType(0).getVectorElementType().isByteSized())
16510 return SDValue();
16511
16512 bool InputsAreConsecutiveLoads = true;
16513 bool InputsAreReverseConsecutive = true;
16514 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
16515 SDValue FirstInput = N->getOperand(0);
16516 bool IsRoundOfExtLoad = false;
16517 LoadSDNode *FirstLoad = nullptr;
16518
16519 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
16520 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
16521 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0));
16522 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD;
16523 }
16524 // Not a build vector of (possibly fp_rounded) loads.
16525 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
16526 N->getNumOperands() == 1)
16527 return SDValue();
16528
16529 if (!IsRoundOfExtLoad)
16530 FirstLoad = cast<LoadSDNode>(FirstInput);
16531
16533 InputLoads.push_back(FirstLoad);
16534 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
16535 // If any inputs are fp_round(extload), they all must be.
16536 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
16537 return SDValue();
16538
16539 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
16540 N->getOperand(i);
16541 if (NextInput.getOpcode() != ISD::LOAD)
16542 return SDValue();
16543
16544 SDValue PreviousInput =
16545 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
16546 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput);
16547 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput);
16548
16549 // If any inputs are fp_round(extload), they all must be.
16550 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
16551 return SDValue();
16552
16553 // We only care about regular loads. The PPC-specific load intrinsics
16554 // will not lead to a merge opportunity.
16555 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1))
16556 InputsAreConsecutiveLoads = false;
16557 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1))
16558 InputsAreReverseConsecutive = false;
16559
16560 // Exit early if the loads are neither consecutive nor reverse consecutive.
16561 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
16562 return SDValue();
16563 InputLoads.push_back(LD2);
16564 }
16565
16566 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
16567 "The loads cannot be both consecutive and reverse consecutive.");
16568
16569 SDValue WideLoad;
16570 SDValue ReturnSDVal;
16571 if (InputsAreConsecutiveLoads) {
16572 assert(FirstLoad && "Input needs to be a LoadSDNode.");
16573 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(),
16574 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
16575 FirstLoad->getAlign());
16576 ReturnSDVal = WideLoad;
16577 } else if (InputsAreReverseConsecutive) {
16578 LoadSDNode *LastLoad = InputLoads.back();
16579 assert(LastLoad && "Input needs to be a LoadSDNode.");
16580 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(),
16581 LastLoad->getBasePtr(), LastLoad->getPointerInfo(),
16582 LastLoad->getAlign());
16584 for (int i = N->getNumOperands() - 1; i >= 0; i--)
16585 Ops.push_back(i);
16586
16587 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad,
16588 DAG.getUNDEF(N->getValueType(0)), Ops);
16589 } else
16590 return SDValue();
16591
16592 for (auto *LD : InputLoads)
16593 DAG.makeEquivalentMemoryOrdering(LD, WideLoad);
16594 return ReturnSDVal;
16595}
16596
16597// This function adds the required vector_shuffle needed to get
16598// the elements of the vector extract in the correct position
16599// as specified by the CorrectElems encoding.
16601 SDValue Input, uint64_t Elems,
16602 uint64_t CorrectElems) {
16603 SDLoc dl(N);
16604
16605 unsigned NumElems = Input.getValueType().getVectorNumElements();
16606 SmallVector<int, 16> ShuffleMask(NumElems, -1);
16607
16608 // Knowing the element indices being extracted from the original
16609 // vector and the order in which they're being inserted, just put
16610 // them at element indices required for the instruction.
16611 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16612 if (DAG.getDataLayout().isLittleEndian())
16613 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
16614 else
16615 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
16616 CorrectElems = CorrectElems >> 8;
16617 Elems = Elems >> 8;
16618 }
16619
16620 SDValue Shuffle =
16621 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
16622 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
16623
16624 EVT VT = N->getValueType(0);
16625 SDValue Conv = DAG.getBitcast(VT, Shuffle);
16626
16627 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
16628 Input.getValueType().getVectorElementType(),
16630 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
16631 DAG.getValueType(ExtVT));
16632}
16633
16634// Look for build vector patterns where input operands come from sign
16635// extended vector_extract elements of specific indices. If the correct indices
16636// aren't used, add a vector shuffle to fix up the indices and create
16637// SIGN_EXTEND_INREG node which selects the vector sign extend instructions
16638// during instruction selection.
16640 // This array encodes the indices that the vector sign extend instructions
16641 // extract from when extending from one type to another for both BE and LE.
16642 // The right nibble of each byte corresponds to the LE incides.
16643 // and the left nibble of each byte corresponds to the BE incides.
16644 // For example: 0x3074B8FC byte->word
16645 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
16646 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
16647 // For example: 0x000070F8 byte->double word
16648 // For LE: the allowed indices are: 0x0,0x8
16649 // For BE: the allowed indices are: 0x7,0xF
16650 uint64_t TargetElems[] = {
16651 0x3074B8FC, // b->w
16652 0x000070F8, // b->d
16653 0x10325476, // h->w
16654 0x00003074, // h->d
16655 0x00001032, // w->d
16656 };
16657
16658 uint64_t Elems = 0;
16659 int Index;
16660 SDValue Input;
16661
16662 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
16663 if (!Op)
16664 return false;
16665 if (Op.getOpcode() != ISD::SIGN_EXTEND &&
16666 Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
16667 return false;
16668
16669 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
16670 // of the right width.
16671 SDValue Extract = Op.getOperand(0);
16672 if (Extract.getOpcode() == ISD::ANY_EXTEND)
16673 Extract = Extract.getOperand(0);
16674 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16675 return false;
16676
16678 if (!ExtOp)
16679 return false;
16680
16681 Index = ExtOp->getZExtValue();
16682 if (Input && Input != Extract.getOperand(0))
16683 return false;
16684
16685 if (!Input)
16686 Input = Extract.getOperand(0);
16687
16688 Elems = Elems << 8;
16689 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
16690 Elems |= Index;
16691
16692 return true;
16693 };
16694
16695 // If the build vector operands aren't sign extended vector extracts,
16696 // of the same input vector, then return.
16697 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16698 if (!isSExtOfVecExtract(N->getOperand(i))) {
16699 return SDValue();
16700 }
16701 }
16702
16703 // If the vector extract indices are not correct, add the appropriate
16704 // vector_shuffle.
16705 int TgtElemArrayIdx;
16706 int InputSize = Input.getValueType().getScalarSizeInBits();
16707 int OutputSize = N->getValueType(0).getScalarSizeInBits();
16708 if (InputSize + OutputSize == 40)
16709 TgtElemArrayIdx = 0;
16710 else if (InputSize + OutputSize == 72)
16711 TgtElemArrayIdx = 1;
16712 else if (InputSize + OutputSize == 48)
16713 TgtElemArrayIdx = 2;
16714 else if (InputSize + OutputSize == 80)
16715 TgtElemArrayIdx = 3;
16716 else if (InputSize + OutputSize == 96)
16717 TgtElemArrayIdx = 4;
16718 else
16719 return SDValue();
16720
16721 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
16722 CorrectElems = DAG.getDataLayout().isLittleEndian()
16723 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
16724 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
16725 if (Elems != CorrectElems) {
16726 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
16727 }
16728
16729 // Regular lowering will catch cases where a shuffle is not needed.
16730 return SDValue();
16731}
16732
16733// Look for the pattern of a load from a narrow width to i128, feeding
16734// into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
16735// (LXVRZX). This node represents a zero extending load that will be matched
16736// to the Load VSX Vector Rightmost instructions.
16738 SDLoc DL(N);
16739
16740 // This combine is only eligible for a BUILD_VECTOR of v1i128.
16741 if (N->getValueType(0) != MVT::v1i128)
16742 return SDValue();
16743
16744 SDValue Operand = N->getOperand(0);
16745 // Proceed with the transformation if the operand to the BUILD_VECTOR
16746 // is a load instruction.
16747 if (Operand.getOpcode() != ISD::LOAD)
16748 return SDValue();
16749
16750 auto *LD = cast<LoadSDNode>(Operand);
16751 EVT MemoryType = LD->getMemoryVT();
16752
16753 // This transformation is only valid if the we are loading either a byte,
16754 // halfword, word, or doubleword.
16755 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
16756 MemoryType == MVT::i32 || MemoryType == MVT::i64;
16757
16758 // Ensure that the load from the narrow width is being zero extended to i128.
16759 if (!ValidLDType ||
16760 (LD->getExtensionType() != ISD::ZEXTLOAD &&
16761 LD->getExtensionType() != ISD::EXTLOAD))
16762 return SDValue();
16763
16764 SDValue LoadOps[] = {
16765 LD->getChain(), LD->getBasePtr(),
16766 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
16767
16768 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
16769 DAG.getVTList(MVT::v1i128, MVT::Other),
16770 LoadOps, MemoryType, LD->getMemOperand());
16771}
16772
16773SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
16774 DAGCombinerInfo &DCI) const {
16775 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16776 "Should be called with a BUILD_VECTOR node");
16777
16778 SelectionDAG &DAG = DCI.DAG;
16779 SDLoc dl(N);
16780
16781 if (!Subtarget.hasVSX())
16782 return SDValue();
16783
16784 // The target independent DAG combiner will leave a build_vector of
16785 // float-to-int conversions intact. We can generate MUCH better code for
16786 // a float-to-int conversion of a vector of floats.
16787 SDValue FirstInput = N->getOperand(0);
16788 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
16789 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
16790 if (Reduced)
16791 return Reduced;
16792 }
16793
16794 // If we're building a vector out of consecutive loads, just load that
16795 // vector type.
16796 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
16797 if (Reduced)
16798 return Reduced;
16799
16800 // If we're building a vector out of extended elements from another vector
16801 // we have P9 vector integer extend instructions. The code assumes legal
16802 // input types (i.e. it can't handle things like v4i16) so do not run before
16803 // legalization.
16804 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
16805 Reduced = combineBVOfVecSExt(N, DAG);
16806 if (Reduced)
16807 return Reduced;
16808 }
16809
16810 // On Power10, the Load VSX Vector Rightmost instructions can be utilized
16811 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
16812 // is a load from <valid narrow width> to i128.
16813 if (Subtarget.isISA3_1()) {
16814 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
16815 if (BVOfZLoad)
16816 return BVOfZLoad;
16817 }
16818
16819 if (N->getValueType(0) != MVT::v2f64)
16820 return SDValue();
16821
16822 // Looking for:
16823 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
16824 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
16825 FirstInput.getOpcode() != ISD::UINT_TO_FP)
16826 return SDValue();
16827 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
16828 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
16829 return SDValue();
16830 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
16831 return SDValue();
16832
16833 SDValue Ext1 = FirstInput.getOperand(0);
16834 SDValue Ext2 = N->getOperand(1).getOperand(0);
16835 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
16837 return SDValue();
16838
16839 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
16840 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
16841 if (!Ext1Op || !Ext2Op)
16842 return SDValue();
16843 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
16844 Ext1.getOperand(0) != Ext2.getOperand(0))
16845 return SDValue();
16846
16847 int FirstElem = Ext1Op->getZExtValue();
16848 int SecondElem = Ext2Op->getZExtValue();
16849 int SubvecIdx;
16850 if (FirstElem == 0 && SecondElem == 1)
16851 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
16852 else if (FirstElem == 2 && SecondElem == 3)
16853 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
16854 else
16855 return SDValue();
16856
16857 SDValue SrcVec = Ext1.getOperand(0);
16858 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
16859 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
16860 return DAG.getNode(NodeType, dl, MVT::v2f64,
16861 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
16862}
16863
16864SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
16865 DAGCombinerInfo &DCI) const {
16866 assert((N->getOpcode() == ISD::SINT_TO_FP ||
16867 N->getOpcode() == ISD::UINT_TO_FP) &&
16868 "Need an int -> FP conversion node here");
16869
16870 if (useSoftFloat() || !Subtarget.has64BitSupport())
16871 return SDValue();
16872
16873 SelectionDAG &DAG = DCI.DAG;
16874 SDLoc dl(N);
16875 SDValue Op(N, 0);
16876
16877 // Don't handle ppc_fp128 here or conversions that are out-of-range capable
16878 // from the hardware.
16879 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
16880 return SDValue();
16881 if (!Op.getOperand(0).getValueType().isSimple())
16882 return SDValue();
16883 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
16884 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
16885 return SDValue();
16886
16887 SDValue FirstOperand(Op.getOperand(0));
16888 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
16889 (FirstOperand.getValueType() == MVT::i8 ||
16890 FirstOperand.getValueType() == MVT::i16);
16891 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
16892 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
16893 bool DstDouble = Op.getValueType() == MVT::f64;
16894 unsigned ConvOp = Signed ?
16895 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
16896 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
16897 SDValue WidthConst =
16898 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
16899 dl, false);
16900 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
16901 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
16902 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
16903 DAG.getVTList(MVT::f64, MVT::Other),
16904 Ops, MVT::i8, LDN->getMemOperand());
16905 DAG.makeEquivalentMemoryOrdering(LDN, Ld);
16906
16907 // For signed conversion, we need to sign-extend the value in the VSR
16908 if (Signed) {
16909 SDValue ExtOps[] = { Ld, WidthConst };
16910 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
16911 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
16912 } else
16913 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
16914 }
16915
16916
16917 // For i32 intermediate values, unfortunately, the conversion functions
16918 // leave the upper 32 bits of the value are undefined. Within the set of
16919 // scalar instructions, we have no method for zero- or sign-extending the
16920 // value. Thus, we cannot handle i32 intermediate values here.
16921 if (Op.getOperand(0).getValueType() == MVT::i32)
16922 return SDValue();
16923
16924 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
16925 "UINT_TO_FP is supported only with FPCVT");
16926
16927 // If we have FCFIDS, then use it when converting to single-precision.
16928 // Otherwise, convert to double-precision and then round.
16929 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
16930 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
16931 : PPCISD::FCFIDS)
16932 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
16933 : PPCISD::FCFID);
16934 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
16935 ? MVT::f32
16936 : MVT::f64;
16937
16938 // If we're converting from a float, to an int, and back to a float again,
16939 // then we don't need the store/load pair at all.
16940 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
16941 Subtarget.hasFPCVT()) ||
16942 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
16943 SDValue Src = Op.getOperand(0).getOperand(0);
16944 if (Src.getValueType() == MVT::f32) {
16945 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
16946 DCI.AddToWorklist(Src.getNode());
16947 } else if (Src.getValueType() != MVT::f64) {
16948 // Make sure that we don't pick up a ppc_fp128 source value.
16949 return SDValue();
16950 }
16951
16952 unsigned FCTOp =
16953 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
16954 PPCISD::FCTIDUZ;
16955
16956 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
16957 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
16958
16959 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
16960 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
16961 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
16962 DCI.AddToWorklist(FP.getNode());
16963 }
16964
16965 return FP;
16966 }
16967
16968 return SDValue();
16969}
16970
16971// expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
16972// builtins) into loads with swaps.
16974 DAGCombinerInfo &DCI) const {
16975 // Delay VSX load for LE combine until after LegalizeOps to prioritize other
16976 // load combines.
16977 if (DCI.isBeforeLegalizeOps())
16978 return SDValue();
16979
16980 SelectionDAG &DAG = DCI.DAG;
16981 SDLoc dl(N);
16982 SDValue Chain;
16983 SDValue Base;
16984 MachineMemOperand *MMO;
16985
16986 switch (N->getOpcode()) {
16987 default:
16988 llvm_unreachable("Unexpected opcode for little endian VSX load");
16989 case ISD::LOAD: {
16991 Chain = LD->getChain();
16992 Base = LD->getBasePtr();
16993 MMO = LD->getMemOperand();
16994 // If the MMO suggests this isn't a load of a full vector, leave
16995 // things alone. For a built-in, we have to make the change for
16996 // correctness, so if there is a size problem that will be a bug.
16997 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
16998 return SDValue();
16999 break;
17000 }
17003 Chain = Intrin->getChain();
17004 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
17005 // us what we want. Get operand 2 instead.
17006 Base = Intrin->getOperand(2);
17007 MMO = Intrin->getMemOperand();
17008 break;
17009 }
17010 }
17011
17012 MVT VecTy = N->getValueType(0).getSimpleVT();
17013
17014 SDValue LoadOps[] = { Chain, Base };
17015 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
17016 DAG.getVTList(MVT::v2f64, MVT::Other),
17017 LoadOps, MVT::v2f64, MMO);
17018
17019 DCI.AddToWorklist(Load.getNode());
17020 Chain = Load.getValue(1);
17021 SDValue Swap = DAG.getNode(
17022 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
17023 DCI.AddToWorklist(Swap.getNode());
17024
17025 // Add a bitcast if the resulting load type doesn't match v2f64.
17026 if (VecTy != MVT::v2f64) {
17027 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
17028 DCI.AddToWorklist(N.getNode());
17029 // Package {bitcast value, swap's chain} to match Load's shape.
17030 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
17031 N, Swap.getValue(1));
17032 }
17033
17034 return Swap;
17035}
17036
17037// expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
17038// builtins) into stores with swaps.
17040 DAGCombinerInfo &DCI) const {
17041 // Delay VSX store for LE combine until after LegalizeOps to prioritize other
17042 // store combines.
17043 if (DCI.isBeforeLegalizeOps())
17044 return SDValue();
17045
17046 SelectionDAG &DAG = DCI.DAG;
17047 SDLoc dl(N);
17048 SDValue Chain;
17049 SDValue Base;
17050 unsigned SrcOpnd;
17051 MachineMemOperand *MMO;
17052
17053 switch (N->getOpcode()) {
17054 default:
17055 llvm_unreachable("Unexpected opcode for little endian VSX store");
17056 case ISD::STORE: {
17058 Chain = ST->getChain();
17059 Base = ST->getBasePtr();
17060 MMO = ST->getMemOperand();
17061 SrcOpnd = 1;
17062 // If the MMO suggests this isn't a store of a full vector, leave
17063 // things alone. For a built-in, we have to make the change for
17064 // correctness, so if there is a size problem that will be a bug.
17065 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
17066 return SDValue();
17067 break;
17068 }
17069 case ISD::INTRINSIC_VOID: {
17071 Chain = Intrin->getChain();
17072 // Intrin->getBasePtr() oddly does not get what we want.
17073 Base = Intrin->getOperand(3);
17074 MMO = Intrin->getMemOperand();
17075 SrcOpnd = 2;
17076 break;
17077 }
17078 }
17079
17080 SDValue Src = N->getOperand(SrcOpnd);
17081 MVT VecTy = Src.getValueType().getSimpleVT();
17082
17083 // All stores are done as v2f64 and possible bit cast.
17084 if (VecTy != MVT::v2f64) {
17085 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
17086 DCI.AddToWorklist(Src.getNode());
17087 }
17088
17089 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
17090 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
17091 DCI.AddToWorklist(Swap.getNode());
17092 Chain = Swap.getValue(1);
17093 SDValue StoreOps[] = { Chain, Swap, Base };
17094 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
17095 DAG.getVTList(MVT::Other),
17096 StoreOps, VecTy, MMO);
17097 DCI.AddToWorklist(Store.getNode());
17098 return Store;
17099}
17100
17101// Handle DAG combine for STORE (FP_TO_INT F).
17102SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
17103 DAGCombinerInfo &DCI) const {
17104 SelectionDAG &DAG = DCI.DAG;
17105 SDLoc dl(N);
17106 unsigned Opcode = N->getOperand(1).getOpcode();
17107 (void)Opcode;
17108 bool Strict = N->getOperand(1)->isStrictFPOpcode();
17109
17110 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
17111 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT)
17112 && "Not a FP_TO_INT Instruction!");
17113
17114 SDValue Val = N->getOperand(1).getOperand(Strict ? 1 : 0);
17115 EVT Op1VT = N->getOperand(1).getValueType();
17116 EVT ResVT = Val.getValueType();
17117
17118 if (!Subtarget.hasVSX() || !Subtarget.hasFPCVT() || !isTypeLegal(ResVT))
17119 return SDValue();
17120
17121 // Only perform combine for conversion to i64/i32 or power9 i16/i8.
17122 bool ValidTypeForStoreFltAsInt =
17123 (Op1VT == MVT::i32 || (Op1VT == MVT::i64 && Subtarget.isPPC64()) ||
17124 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
17125
17126 // TODO: Lower conversion from f128 on all VSX targets
17127 if (ResVT == MVT::ppcf128 || (ResVT == MVT::f128 && !Subtarget.hasP9Vector()))
17128 return SDValue();
17129
17130 if ((Op1VT != MVT::i64 && !Subtarget.hasP8Vector()) ||
17131 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
17132 return SDValue();
17133
17134 Val = convertFPToInt(N->getOperand(1), DAG, Subtarget);
17135
17136 // Set number of bytes being converted.
17137 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
17138 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2),
17139 DAG.getIntPtrConstant(ByteSize, dl, false),
17140 DAG.getValueType(Op1VT)};
17141
17142 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
17143 DAG.getVTList(MVT::Other), Ops,
17144 cast<StoreSDNode>(N)->getMemoryVT(),
17145 cast<StoreSDNode>(N)->getMemOperand());
17146
17147 return Val;
17148}
17149
17150static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
17151 // Check that the source of the element keeps flipping
17152 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
17153 bool PrevElemFromFirstVec = Mask[0] < NumElts;
17154 for (int i = 1, e = Mask.size(); i < e; i++) {
17155 if (PrevElemFromFirstVec && Mask[i] < NumElts)
17156 return false;
17157 if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
17158 return false;
17159 PrevElemFromFirstVec = !PrevElemFromFirstVec;
17160 }
17161 return true;
17162}
17163
17164static bool isSplatBV(SDValue Op) {
17165 if (Op.getOpcode() != ISD::BUILD_VECTOR)
17166 return false;
17167 SDValue FirstOp;
17168
17169 // Find first non-undef input.
17170 for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
17171 FirstOp = Op.getOperand(i);
17172 if (!FirstOp.isUndef())
17173 break;
17174 }
17175
17176 // All inputs are undef or the same as the first non-undef input.
17177 for (int i = 1, e = Op.getNumOperands(); i < e; i++)
17178 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
17179 return false;
17180 return true;
17181}
17182
17184 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17185 return Op;
17186 if (Op.getOpcode() != ISD::BITCAST)
17187 return SDValue();
17188 Op = Op.getOperand(0);
17189 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17190 return Op;
17191 return SDValue();
17192}
17193
17194// Fix up the shuffle mask to account for the fact that the result of
17195// scalar_to_vector is not in lane zero. This just takes all values in
17196// the ranges specified by the min/max indices and adds the number of
17197// elements required to ensure each element comes from the respective
17198// position in the valid lane.
17199// On little endian, that's just the corresponding element in the other
17200// half of the vector. On big endian, it is in the same half but right
17201// justified rather than left justified in that half.
17203 SmallVectorImpl<int> &ShuffV, int LHSFirstElt, int LHSLastElt,
17204 int RHSFirstElt, int RHSLastElt, int HalfVec, unsigned LHSNumValidElts,
17205 unsigned RHSNumValidElts, const PPCSubtarget &Subtarget) {
17206 int LHSEltFixup =
17207 Subtarget.isLittleEndian() ? HalfVec : HalfVec - LHSNumValidElts;
17208 int RHSEltFixup =
17209 Subtarget.isLittleEndian() ? HalfVec : HalfVec - RHSNumValidElts;
17210 for (int I = 0, E = ShuffV.size(); I < E; ++I) {
17211 int Idx = ShuffV[I];
17212 if (Idx >= LHSFirstElt && Idx <= LHSLastElt)
17213 ShuffV[I] += LHSEltFixup;
17214 else if (Idx >= RHSFirstElt && Idx <= RHSLastElt)
17215 ShuffV[I] += RHSEltFixup;
17216 }
17217}
17218
17219// Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
17220// the original is:
17221// (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
17222// In such a case, just change the shuffle mask to extract the element
17223// from the permuted index.
17225 const PPCSubtarget &Subtarget) {
17226 SDLoc dl(OrigSToV);
17227 EVT VT = OrigSToV.getValueType();
17228 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
17229 "Expecting a SCALAR_TO_VECTOR here");
17230 SDValue Input = OrigSToV.getOperand(0);
17231
17232 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17233 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
17234 SDValue OrigVector = Input.getOperand(0);
17235
17236 // Can't handle non-const element indices or different vector types
17237 // for the input to the extract and the output of the scalar_to_vector.
17238 if (Idx && VT == OrigVector.getValueType()) {
17239 unsigned NumElts = VT.getVectorNumElements();
17240 assert(
17241 NumElts > 1 &&
17242 "Cannot produce a permuted scalar_to_vector for one element vector");
17243 SmallVector<int, 16> NewMask(NumElts, -1);
17244 unsigned ResultInElt = NumElts / 2;
17245 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
17246 NewMask[ResultInElt] = Idx->getZExtValue();
17247 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
17248 }
17249 }
17250 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
17251 OrigSToV.getOperand(0));
17252}
17253
17255 int HalfVec, int LHSLastElementDefined,
17256 int RHSLastElementDefined) {
17257 for (int Index : ShuffV) {
17258 if (Index < 0) // Skip explicitly undefined mask indices.
17259 continue;
17260 // Handle first input vector of the vector_shuffle.
17261 if ((LHSLastElementDefined >= 0) && (Index < HalfVec) &&
17262 (Index > LHSLastElementDefined))
17263 return false;
17264 // Handle second input vector of the vector_shuffle.
17265 if ((RHSLastElementDefined >= 0) &&
17266 (Index > HalfVec + RHSLastElementDefined))
17267 return false;
17268 }
17269 return true;
17270}
17271
17273 int ScalarSize, uint64_t ShuffleEltWidth, unsigned &NumValidElts,
17274 int FirstElt, int &LastElt, SDValue VecShuffOperand, SDValue SToVNode,
17275 SelectionDAG &DAG, const PPCSubtarget &Subtarget) {
17276 EVT VecShuffOperandType = VecShuffOperand.getValueType();
17277 // Set up the values for the shuffle vector fixup.
17278 NumValidElts = ScalarSize / VecShuffOperandType.getScalarSizeInBits();
17279 // The last element depends on if the input comes from the LHS or RHS.
17280 //
17281 // For example:
17282 // (shuff (s_to_v i32), (bitcast (s_to_v i64), v4i32), ...)
17283 //
17284 // For the LHS: The last element that comes from the LHS is actually 0, not 3
17285 // because elements 1 and higher of a scalar_to_vector are undefined.
17286 // For the RHS: The last element that comes from the RHS is actually 5, not 7
17287 // because elements 1 and higher of a scalar_to_vector are undefined.
17288 // It is also not 4 because the original scalar_to_vector is wider and
17289 // actually contains two i32 elements.
17290 LastElt = (uint64_t)ScalarSize > ShuffleEltWidth
17291 ? ScalarSize / ShuffleEltWidth - 1 + FirstElt
17292 : FirstElt;
17293 SDValue SToVPermuted = getSToVPermuted(SToVNode, DAG, Subtarget);
17294 if (SToVPermuted.getValueType() != VecShuffOperandType)
17295 SToVPermuted = DAG.getBitcast(VecShuffOperandType, SToVPermuted);
17296 return SToVPermuted;
17297}
17298
17299// On little endian subtargets, combine shuffles such as:
17300// vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
17301// into:
17302// vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
17303// because the latter can be matched to a single instruction merge.
17304// Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
17305// to put the value into element zero. Adjust the shuffle mask so that the
17306// vector can remain in permuted form (to prevent a swap prior to a shuffle).
17307// On big endian targets, this is still useful for SCALAR_TO_VECTOR
17308// nodes with elements smaller than doubleword because all the ways
17309// of getting scalar data into a vector register put the value in the
17310// rightmost element of the left half of the vector.
17311SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
17312 SelectionDAG &DAG) const {
17313 SDValue LHS = SVN->getOperand(0);
17314 SDValue RHS = SVN->getOperand(1);
17315 auto Mask = SVN->getMask();
17316 int NumElts = LHS.getValueType().getVectorNumElements();
17317 SDValue Res(SVN, 0);
17318 SDLoc dl(SVN);
17319 bool IsLittleEndian = Subtarget.isLittleEndian();
17320
17321 // On big endian targets this is only useful for subtargets with direct moves.
17322 // On little endian targets it would be useful for all subtargets with VSX.
17323 // However adding special handling for LE subtargets without direct moves
17324 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
17325 // which includes direct moves.
17326 if (!Subtarget.hasDirectMove())
17327 return Res;
17328
17329 // If this is not a shuffle of a shuffle and the first element comes from
17330 // the second vector, canonicalize to the commuted form. This will make it
17331 // more likely to match one of the single instruction patterns.
17332 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17333 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
17334 std::swap(LHS, RHS);
17335 Res = DAG.getCommutedVectorShuffle(*SVN);
17336
17337 if (!isa<ShuffleVectorSDNode>(Res))
17338 return Res;
17339
17340 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17341 }
17342
17343 // Adjust the shuffle mask if either input vector comes from a
17344 // SCALAR_TO_VECTOR and keep the respective input vector in permuted
17345 // form (to prevent the need for a swap).
17346 SmallVector<int, 16> ShuffV(Mask);
17347 SDValue SToVLHS = isScalarToVec(LHS);
17348 SDValue SToVRHS = isScalarToVec(RHS);
17349 if (SToVLHS || SToVRHS) {
17350 EVT VT = SVN->getValueType(0);
17351 uint64_t ShuffleEltWidth = VT.getVectorElementType().getSizeInBits();
17352 int ShuffleNumElts = ShuffV.size();
17353 int HalfVec = ShuffleNumElts / 2;
17354 // The width of the "valid lane" (i.e. the lane that contains the value that
17355 // is vectorized) needs to be expressed in terms of the number of elements
17356 // of the shuffle. It is thereby the ratio of the values before and after
17357 // any bitcast, which will be set later on if the LHS or RHS are
17358 // SCALAR_TO_VECTOR nodes.
17359 unsigned LHSNumValidElts = HalfVec;
17360 unsigned RHSNumValidElts = HalfVec;
17361
17362 // Initially assume that neither input is permuted. These will be adjusted
17363 // accordingly if either input is. Note, that -1 means that all elements
17364 // are undefined.
17365 int LHSFirstElt = 0;
17366 int RHSFirstElt = ShuffleNumElts;
17367 int LHSLastElt = -1;
17368 int RHSLastElt = -1;
17369
17370 // Get the permuted scalar to vector nodes for the source(s) that come from
17371 // ISD::SCALAR_TO_VECTOR.
17372 // On big endian systems, this only makes sense for element sizes smaller
17373 // than 64 bits since for 64-bit elements, all instructions already put
17374 // the value into element zero. Since scalar size of LHS and RHS may differ
17375 // after isScalarToVec, this should be checked using their own sizes.
17376 int LHSScalarSize = 0;
17377 int RHSScalarSize = 0;
17378 if (SToVLHS) {
17379 LHSScalarSize = SToVLHS.getValueType().getScalarSizeInBits();
17380 if (!IsLittleEndian && LHSScalarSize >= 64)
17381 return Res;
17382 }
17383 if (SToVRHS) {
17384 RHSScalarSize = SToVRHS.getValueType().getScalarSizeInBits();
17385 if (!IsLittleEndian && RHSScalarSize >= 64)
17386 return Res;
17387 }
17388 if (LHSScalarSize != 0)
17390 LHSScalarSize, ShuffleEltWidth, LHSNumValidElts, LHSFirstElt,
17391 LHSLastElt, LHS, SToVLHS, DAG, Subtarget);
17392 if (RHSScalarSize != 0)
17394 RHSScalarSize, ShuffleEltWidth, RHSNumValidElts, RHSFirstElt,
17395 RHSLastElt, RHS, SToVRHS, DAG, Subtarget);
17396
17397 if (!isShuffleMaskInRange(ShuffV, HalfVec, LHSLastElt, RHSLastElt))
17398 return Res;
17399
17400 // Fix up the shuffle mask to reflect where the desired element actually is.
17401 // The minimum and maximum indices that correspond to element zero for both
17402 // the LHS and RHS are computed and will control which shuffle mask entries
17403 // are to be changed. For example, if the RHS is permuted, any shuffle mask
17404 // entries in the range [RHSFirstElt,RHSLastElt] will be adjusted.
17406 ShuffV, LHSFirstElt, LHSLastElt, RHSFirstElt, RHSLastElt, HalfVec,
17407 LHSNumValidElts, RHSNumValidElts, Subtarget);
17408 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17409
17410 // We may have simplified away the shuffle. We won't be able to do anything
17411 // further with it here.
17412 if (!isa<ShuffleVectorSDNode>(Res))
17413 return Res;
17414 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17415 }
17416
17417 SDValue TheSplat = IsLittleEndian ? RHS : LHS;
17418 // The common case after we commuted the shuffle is that the RHS is a splat
17419 // and we have elements coming in from the splat at indices that are not
17420 // conducive to using a merge.
17421 // Example:
17422 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
17423 if (!isSplatBV(TheSplat))
17424 return Res;
17425
17426 // We are looking for a mask such that all even elements are from
17427 // one vector and all odd elements from the other.
17428 if (!isAlternatingShuffMask(Mask, NumElts))
17429 return Res;
17430
17431 // Adjust the mask so we are pulling in the same index from the splat
17432 // as the index from the interesting vector in consecutive elements.
17433 if (IsLittleEndian) {
17434 // Example (even elements from first vector):
17435 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
17436 if (Mask[0] < NumElts)
17437 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17438 if (ShuffV[i] < 0)
17439 continue;
17440 // If element from non-splat is undef, pick first element from splat.
17441 ShuffV[i] = (ShuffV[i - 1] >= 0 ? ShuffV[i - 1] : 0) + NumElts;
17442 }
17443 // Example (odd elements from first vector):
17444 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
17445 else
17446 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17447 if (ShuffV[i] < 0)
17448 continue;
17449 // If element from non-splat is undef, pick first element from splat.
17450 ShuffV[i] = (ShuffV[i + 1] >= 0 ? ShuffV[i + 1] : 0) + NumElts;
17451 }
17452 } else {
17453 // Example (even elements from first vector):
17454 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
17455 if (Mask[0] < NumElts)
17456 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17457 if (ShuffV[i] < 0)
17458 continue;
17459 // If element from non-splat is undef, pick first element from splat.
17460 ShuffV[i] = ShuffV[i + 1] >= 0 ? ShuffV[i + 1] - NumElts : 0;
17461 }
17462 // Example (odd elements from first vector):
17463 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
17464 else
17465 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17466 if (ShuffV[i] < 0)
17467 continue;
17468 // If element from non-splat is undef, pick first element from splat.
17469 ShuffV[i] = ShuffV[i - 1] >= 0 ? ShuffV[i - 1] - NumElts : 0;
17470 }
17471 }
17472
17473 // If the RHS has undefs, we need to remove them since we may have created
17474 // a shuffle that adds those instead of the splat value.
17475 SDValue SplatVal =
17476 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
17477 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
17478
17479 if (IsLittleEndian)
17480 RHS = TheSplat;
17481 else
17482 LHS = TheSplat;
17483 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17484}
17485
17486SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
17487 LSBaseSDNode *LSBase,
17488 DAGCombinerInfo &DCI) const {
17489 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
17490 "Not a reverse memop pattern!");
17491
17492 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
17493 auto Mask = SVN->getMask();
17494 int i = 0;
17495 auto I = Mask.rbegin();
17496 auto E = Mask.rend();
17497
17498 for (; I != E; ++I) {
17499 if (*I != i)
17500 return false;
17501 i++;
17502 }
17503 return true;
17504 };
17505
17506 SelectionDAG &DAG = DCI.DAG;
17507 EVT VT = SVN->getValueType(0);
17508
17509 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
17510 return SDValue();
17511
17512 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
17513 // See comment in PPCVSXSwapRemoval.cpp.
17514 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
17515 if (!Subtarget.hasP9Vector())
17516 return SDValue();
17517
17518 if(!IsElementReverse(SVN))
17519 return SDValue();
17520
17521 if (LSBase->getOpcode() == ISD::LOAD) {
17522 // If the load return value 0 has more than one user except the
17523 // shufflevector instruction, it is not profitable to replace the
17524 // shufflevector with a reverse load.
17525 for (SDUse &Use : LSBase->uses())
17526 if (Use.getResNo() == 0 &&
17527 Use.getUser()->getOpcode() != ISD::VECTOR_SHUFFLE)
17528 return SDValue();
17529
17530 SDLoc dl(LSBase);
17531 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
17532 return DAG.getMemIntrinsicNode(
17533 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
17534 LSBase->getMemoryVT(), LSBase->getMemOperand());
17535 }
17536
17537 if (LSBase->getOpcode() == ISD::STORE) {
17538 // If there are other uses of the shuffle, the swap cannot be avoided.
17539 // Forcing the use of an X-Form (since swapped stores only have
17540 // X-Forms) without removing the swap is unprofitable.
17541 if (!SVN->hasOneUse())
17542 return SDValue();
17543
17544 SDLoc dl(LSBase);
17545 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
17546 LSBase->getBasePtr()};
17547 return DAG.getMemIntrinsicNode(
17548 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
17549 LSBase->getMemoryVT(), LSBase->getMemOperand());
17550 }
17551
17552 llvm_unreachable("Expected a load or store node here");
17553}
17554
17555static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) {
17556 unsigned IntrinsicID = Intrin.getConstantOperandVal(1);
17557 if (IntrinsicID == Intrinsic::ppc_stdcx)
17558 StoreWidth = 8;
17559 else if (IntrinsicID == Intrinsic::ppc_stwcx)
17560 StoreWidth = 4;
17561 else if (IntrinsicID == Intrinsic::ppc_sthcx)
17562 StoreWidth = 2;
17563 else if (IntrinsicID == Intrinsic::ppc_stbcx)
17564 StoreWidth = 1;
17565 else
17566 return false;
17567 return true;
17568}
17569
17572 if (N->getOpcode() == PPCISD::ADDC && N->hasAnyUseOfValue(1)) {
17573 // (ADDC (ADDE 0, 0, C), -1) -> C
17574 SDValue LHS = N->getOperand(0);
17575 SDValue RHS = N->getOperand(1);
17576 if (LHS->getOpcode() == PPCISD::ADDE &&
17577 isNullConstant(LHS->getOperand(0)) &&
17578 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
17579 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
17580 }
17581 }
17582 return SDValue();
17583}
17584
17587 if (N->getOpcode() == PPCISD::SUBE) {
17588 SDValue LHS = N->getOperand(0);
17589 SDValue RHS = N->getOperand(1);
17590 SDValue Carry = N->getOperand(2);
17591
17592 // SUBE(ADDC(ADDE(0, 0, C), -1), same, C) -> ADDC(ADDE(0, 0, C), -1)
17593 if (LHS == RHS && LHS.getOpcode() == PPCISD::ADDC) {
17594 SDValue AddcLHS = LHS.getOperand(0);
17595 SDValue AddcRHS = LHS.getOperand(1);
17596 if (AddcLHS.getOpcode() == PPCISD::ADDE &&
17597 isNullConstant(AddcLHS.getOperand(0)) &&
17598 isNullConstant(AddcLHS.getOperand(1)) && isAllOnesConstant(AddcRHS) &&
17599 Carry == AddcLHS.getOperand(2)) {
17600 return LHS;
17601 }
17602 }
17603 }
17604 return SDValue();
17605}
17606
17607/// Optimize the bitfloor(X) pattern for PowerPC.
17608/// Transforms: select_cc X, 0, 0, (srl MinSignedValue, (ctlz X)), seteq
17609/// Into: srl MinSignedValue, (ctlz X)
17610///
17611/// This is safe on PowerPC because the srw instruction returns 0 when the
17612/// shift amount is == bitwidth, which matches the behavior we need for X=0.
17614 if (N->getOpcode() != ISD::SELECT_CC)
17615 return SDValue();
17616
17617 // SELECT_CC operands: LHS, RHS, TrueVal, FalseVal, CC
17618 SDValue CmpLHS = N->getOperand(0);
17619 SDValue CmpRHS = N->getOperand(1);
17620 SDValue TrueVal = N->getOperand(2);
17621 SDValue FalseVal = N->getOperand(3);
17622 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
17623
17624 // Check if condition is (X == 0)
17625 if (CC != ISD::SETEQ || !isNullConstant(CmpRHS))
17626 return SDValue();
17627
17628 // Check if TrueVal is constant 0
17629 if (!isNullConstant(TrueVal))
17630 return SDValue();
17631
17632 // This combine is replacing a select_cc with a PPC srl, not an srl with a
17633 // PPC srl. If the original srl had multiple uses it would just remain in the
17634 // code. This is at most a performance consideration.
17635 if (FalseVal.getOpcode() != ISD::SRL || !FalseVal.hasOneUse())
17636 return SDValue();
17637
17638 SDValue ShiftVal = FalseVal.getOperand(0);
17639 SDValue ShiftAmt = FalseVal.getOperand(1);
17640
17641 // Check if ShiftVal is MinSignedValue
17642 auto *ShiftConst = dyn_cast<ConstantSDNode>(ShiftVal);
17643 if (!ShiftConst || !ShiftConst->getAPIntValue().isMinSignedValue())
17644 return SDValue();
17645
17646 SDValue CtlzArg;
17647 // Check if ShiftAmt is (ctlz CmpLHS) or (truncate (ctlz ...))
17648 if (ShiftAmt.getOpcode() != ISD::CTLZ) {
17649 // Look through truncate if present (for i64 ctlz truncated to i32 shift
17650 // amount)
17651 if (ShiftAmt.getOpcode() != ISD::TRUNCATE)
17652 return SDValue();
17653
17654 // Verify the truncate target type is appropriate for shift amount (i32, not
17655 // i1 or other)
17656 if (ShiftAmt.getValueType() != MVT::i32)
17657 return SDValue();
17658
17659 SDValue CtlzNode = ShiftAmt.getOperand(0);
17660
17661 if (CtlzNode.getOpcode() != ISD::CTLZ)
17662 return SDValue();
17663
17664 CtlzArg = CtlzNode.getOperand(0);
17665 } else {
17666 CtlzArg = ShiftAmt.getOperand(0);
17667 }
17668
17669 // Check if ctlz operates on the same value as the comparison
17670 if (CtlzArg != CmpLHS)
17671 return SDValue();
17672
17673 // Using PPCISD::SRL to ensure well-defined behavior.
17674 // On PowerPC, PPCISD::SRL guarantees that shift by bitwidth returns 0,
17675 // which is exactly what we need for the bitfloor(0) case.
17676 SDLoc DL(N);
17677 SDValue PPCSrl =
17678 DAG.getNode(PPCISD::SRL, DL, FalseVal.getValueType(), ShiftVal, ShiftAmt);
17679 return PPCSrl;
17680}
17681
17682// Optimize zero-extension of setcc when the compared value is known to be 0
17683// or 1.
17684//
17685// Pattern: zext(setcc(Value, 0, seteq/setne)) where Value is 0 or 1
17686// -> zext(xor(Value, 1)) for seteq
17687// -> zext(Value) for setne
17688//
17689// This optimization avoids the i32 -> i1 -> i32/i64 conversion sequence
17690// by keeping the value in its original i32 type throughout.
17691//
17692// Example:
17693// Before: zext(setcc(test_data_class(...), 0, seteq))
17694// // test_data_class returns 0 or 1 in i32
17695// // setcc converts i32 -> i1
17696// // zext converts i1 -> i64
17697// After: zext(xor(test_data_class(...), 1))
17698// // Stays in i32, then extends to i64
17699//
17700// This is beneficial because:
17701// 1. Eliminates the setcc instruction
17702// 2. Avoids i32 -> i1 truncation
17703// 3. Keeps computation in native integer width
17704
17706 // Check if this is a zero_extend
17707 if (N->getOpcode() != ISD::ZERO_EXTEND)
17708 return SDValue();
17709
17710 SDValue Src = N->getOperand(0);
17711
17712 // Check if the source is a setcc
17713 if (Src.getOpcode() != ISD::SETCC)
17714 return SDValue();
17715
17716 SDValue LHS = Src.getOperand(0);
17717 SDValue RHS = Src.getOperand(1);
17718 ISD::CondCode CC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
17719
17721 return SDValue();
17722
17723 SDValue NonNullConstant = isNullConstant(RHS) ? LHS : RHS;
17724
17725 auto isZeroOrOne = [=](SDValue &V) {
17726 if (V.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
17727 V.getConstantOperandVal(0) == Intrinsic::ppc_test_data_class)
17728 return true;
17729 return false;
17730 };
17731
17732 if (!isZeroOrOne(NonNullConstant))
17733 return SDValue();
17734
17735 // Check for pattern: zext(setcc (Value), 0, seteq)) or
17736 // zext(setcc (Value), 0, setne))
17737 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
17738 // Replace with: zext(xor(Value, 1)) for seteq
17739 // or: zext(Value) for setne
17740 // This keeps the value in i32 instead of converting to i1
17741 SDLoc DL(N);
17742 EVT VType = N->getValueType(0);
17743 SDValue NewNonNullConstant = DAG.getZExtOrTrunc(NonNullConstant, DL, VType);
17744
17745 if (CC == ISD::SETNE)
17746 return NewNonNullConstant;
17747
17748 SDValue One = DAG.getConstant(1, DL, VType);
17749 return DAG.getNode(ISD::XOR, DL, VType, NewNonNullConstant, One);
17750 }
17751
17752 return SDValue();
17753}
17754
17755// Combine XOR patterns with SELECT_CC_I4/I8, for Example:
17756// 1. XOR(SELECT_CC_I4(cond, 1, 0, cc), 1) -> SELECT_CC_I4(cond, 0, 1, cc)
17757// 2. XOR(ZEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond, 0,
17758// 1, cc))
17759// 3. XOR(ANYEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond,
17760// 0, 1, cc))
17761// 4. etc
17763 assert(N->getOpcode() == ISD::XOR && "Expected XOR node");
17764
17765 EVT XorVT = N->getValueType(0);
17766 if ((XorVT != MVT::i32 && XorVT != MVT::i64))
17767 return SDValue();
17768
17769 SDValue LHS = N->getOperand(0);
17770 SDValue RHS = N->getOperand(1);
17771
17772 // Check for XOR with constant 1
17774 if (!XorConst || !XorConst->isOne()) {
17775 XorConst = dyn_cast<ConstantSDNode>(LHS);
17776 if (!XorConst || !XorConst->isOne())
17777 return SDValue();
17778 // Swap so LHS is the SELECT_CC_I4 (or extension) and RHS is the constant
17779 std::swap(LHS, RHS);
17780 }
17781
17782 // Check if LHS has only one use
17783 if (!LHS.hasOneUse())
17784 return SDValue();
17785
17786 // Handle extensions: ZEXT, ANYEXT
17787 SDValue SelectNode = LHS;
17788
17789 if (LHS.getOpcode() == ISD::ZERO_EXTEND ||
17790 LHS.getOpcode() == ISD::ANY_EXTEND) {
17791 SelectNode = LHS.getOperand(0);
17792
17793 // Check if the extension input has only one use
17794 if (!SelectNode.hasOneUse())
17795 return SDValue();
17796 }
17797
17798 // Check if SelectNode is a MachineSDNode with SELECT_CC_I4/I8 opcode
17799 if (!SelectNode.isMachineOpcode())
17800 return SDValue();
17801
17802 unsigned MachineOpc = SelectNode.getMachineOpcode();
17803
17804 // Handle both SELECT_CC_I4 and SELECT_CC_I8
17805 if (MachineOpc != PPC::SELECT_CC_I4 && MachineOpc != PPC::SELECT_CC_I8)
17806 return SDValue();
17807
17808 // SELECT_CC_I4 operands: (cond, true_val, false_val, bropc)
17809 if (SelectNode.getNumOperands() != 4)
17810 return SDValue();
17811
17812 ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(1));
17813 ConstantSDNode *ConstOp2 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(2));
17814
17815 if (!ConstOp1 || !ConstOp2)
17816 return SDValue();
17817
17818 // Only optimize if operands are {0, 1} or {1, 0}
17819 if (!((ConstOp1->isOne() && ConstOp2->isZero()) ||
17820 (ConstOp1->isZero() && ConstOp2->isOne())))
17821 return SDValue();
17822
17823 // Pattern matched! Create new SELECT_CC with swapped 0/1 operands to
17824 // eliminate XOR. If original was SELECT_CC(cond, 1, 0, pred), create
17825 // SELECT_CC(cond, 0, 1, pred). If original was SELECT_CC(cond, 0, 1, pred),
17826 // create SELECT_CC(cond, 1, 0, pred).
17827 SDLoc DL(N);
17828 MachineOpc = (XorVT == MVT::i32) ? PPC::SELECT_CC_I4 : PPC::SELECT_CC_I8;
17829
17830 bool ConstOp1IsOne = ConstOp1->isOne();
17831 return SDValue(
17832 DAG.getMachineNode(MachineOpc, DL, XorVT,
17833 {SelectNode.getOperand(0),
17834 DAG.getConstant(ConstOp1IsOne ? 0 : 1, DL, XorVT),
17835 DAG.getConstant(ConstOp1IsOne ? 1 : 0, DL, XorVT),
17836 SelectNode.getOperand(3)}),
17837 0);
17838}
17839
17841 DAGCombinerInfo &DCI) const {
17842 SelectionDAG &DAG = DCI.DAG;
17843 SDLoc dl(N);
17844 switch (N->getOpcode()) {
17845 default: break;
17846 case ISD::ADD:
17847 return combineADD(N, DCI);
17848 case ISD::AND: {
17849 // We don't want (and (zext (shift...)), C) if C fits in the width of the
17850 // original input as that will prevent us from selecting optimal rotates.
17851 // This only matters if the input to the extend is i32 widened to i64.
17852 SDValue Op1 = N->getOperand(0);
17853 SDValue Op2 = N->getOperand(1);
17854 if ((Op1.getOpcode() != ISD::ZERO_EXTEND &&
17855 Op1.getOpcode() != ISD::ANY_EXTEND) ||
17856 !isa<ConstantSDNode>(Op2) || N->getValueType(0) != MVT::i64 ||
17857 Op1.getOperand(0).getValueType() != MVT::i32)
17858 break;
17859 SDValue NarrowOp = Op1.getOperand(0);
17860 if (NarrowOp.getOpcode() != ISD::SHL && NarrowOp.getOpcode() != ISD::SRL &&
17861 NarrowOp.getOpcode() != ISD::ROTL && NarrowOp.getOpcode() != ISD::ROTR)
17862 break;
17863
17864 uint64_t Imm = Op2->getAsZExtVal();
17865 // Make sure that the constant is narrow enough to fit in the narrow type.
17866 if (!isUInt<32>(Imm))
17867 break;
17868 SDValue ConstOp = DAG.getConstant(Imm, dl, MVT::i32);
17869 SDValue NarrowAnd = DAG.getNode(ISD::AND, dl, MVT::i32, NarrowOp, ConstOp);
17870 return DAG.getZExtOrTrunc(NarrowAnd, dl, N->getValueType(0));
17871 }
17872 case ISD::XOR: {
17873 // Optimize XOR(ISEL(1,0,CR), 1) -> ISEL(0,1,CR)
17874 if (SDValue V = combineXorSelectCC(N, DAG))
17875 return V;
17876 break;
17877 }
17878 case ISD::SHL:
17879 return combineSHL(N, DCI);
17880 case ISD::SRA:
17881 return combineSRA(N, DCI);
17882 case ISD::SRL:
17883 return combineSRL(N, DCI);
17884 case ISD::MUL:
17885 return combineMUL(N, DCI);
17886 case ISD::FMA:
17887 case PPCISD::FNMSUB:
17888 return combineFMALike(N, DCI);
17889 case PPCISD::SHL:
17890 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
17891 return N->getOperand(0);
17892 break;
17893 case PPCISD::SRL:
17894 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
17895 return N->getOperand(0);
17896 break;
17897 case PPCISD::SRA:
17898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
17899 if (C->isZero() || // 0 >>s V -> 0.
17900 C->isAllOnes()) // -1 >>s V -> -1.
17901 return N->getOperand(0);
17902 }
17903 break;
17904 case ISD::SIGN_EXTEND:
17905 if (SDValue SECC = combineSignExtendSetCC(N, DCI))
17906 return SECC;
17907 [[fallthrough]];
17908 case ISD::ZERO_EXTEND:
17909 if (SDValue RetV = combineZextSetccWithZero(N, DCI.DAG))
17910 return RetV;
17911 [[fallthrough]];
17912 case ISD::ANY_EXTEND:
17913 return DAGCombineExtBoolTrunc(N, DCI);
17914 case ISD::TRUNCATE:
17915 return combineTRUNCATE(N, DCI);
17916 case ISD::SETCC:
17917 if (SDValue CSCC = combineSetCC(N, DCI))
17918 return CSCC;
17919 [[fallthrough]];
17920 case ISD::SELECT_CC:
17921 if (SDValue V = combineSELECT_CCBitFloor(N, DAG))
17922 return V;
17923 return DAGCombineTruncBoolExt(N, DCI);
17924 case ISD::SINT_TO_FP:
17925 case ISD::UINT_TO_FP:
17926 return combineFPToIntToFP(N, DCI);
17928 if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
17929 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
17930 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
17931 }
17932 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
17933 case ISD::STORE: {
17934
17935 EVT Op1VT = N->getOperand(1).getValueType();
17936 unsigned Opcode = N->getOperand(1).getOpcode();
17937
17938 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
17939 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT) {
17940 SDValue Val = combineStoreFPToInt(N, DCI);
17941 if (Val)
17942 return Val;
17943 }
17944
17945 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
17946 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
17947 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
17948 if (Val)
17949 return Val;
17950 }
17951
17952 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
17953 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
17954 N->getOperand(1).getNode()->hasOneUse() &&
17955 (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
17956 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
17957
17958 // STBRX can only handle simple types and it makes no sense to store less
17959 // two bytes in byte-reversed order.
17960 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
17961 if (mVT.isExtended() || mVT.getSizeInBits() < 16)
17962 break;
17963
17964 SDValue BSwapOp = N->getOperand(1).getOperand(0);
17965 // Do an any-extend to 32-bits if this is a half-word input.
17966 if (BSwapOp.getValueType() == MVT::i16)
17967 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
17968
17969 // If the type of BSWAP operand is wider than stored memory width
17970 // it need to be shifted to the right side before STBRX.
17971 if (Op1VT.bitsGT(mVT)) {
17972 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
17973 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
17974 DAG.getConstant(Shift, dl, MVT::i32));
17975 // Need to truncate if this is a bswap of i64 stored as i32/i16.
17976 if (Op1VT == MVT::i64)
17977 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
17978 }
17979
17980 SDValue Ops[] = {
17981 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
17982 };
17983 return
17984 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
17985 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
17986 cast<StoreSDNode>(N)->getMemOperand());
17987 }
17988
17989 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
17990 // So it can increase the chance of CSE constant construction.
17991 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
17992 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
17993 // Need to sign-extended to 64-bits to handle negative values.
17994 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
17995 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
17996 MemVT.getSizeInBits());
17997 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
17998
17999 auto *ST = cast<StoreSDNode>(N);
18000 SDValue NewST = DAG.getStore(ST->getChain(), dl, Const64,
18001 ST->getBasePtr(), ST->getOffset(), MemVT,
18002 ST->getMemOperand(), ST->getAddressingMode(),
18003 /*IsTruncating=*/true);
18004 // Note we use CombineTo here to prevent DAGCombiner from visiting the
18005 // new store which will change the constant by removing non-demanded bits.
18006 return ST->isUnindexed()
18007 ? DCI.CombineTo(N, NewST, /*AddTo=*/false)
18008 : DCI.CombineTo(N, NewST, NewST.getValue(1), /*AddTo=*/false);
18009 }
18010
18011 // For little endian, VSX stores require generating xxswapd/lxvd2x.
18012 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18013 if (Op1VT.isSimple()) {
18014 MVT StoreVT = Op1VT.getSimpleVT();
18015 if (Subtarget.needsSwapsForVSXMemOps() &&
18016 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
18017 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
18018 return expandVSXStoreForLE(N, DCI);
18019 }
18020 break;
18021 }
18022 case ISD::LOAD: {
18024 EVT VT = LD->getValueType(0);
18025
18026 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18027 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18028 if (VT.isSimple()) {
18029 MVT LoadVT = VT.getSimpleVT();
18030 if (Subtarget.needsSwapsForVSXMemOps() &&
18031 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
18032 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
18033 return expandVSXLoadForLE(N, DCI);
18034 }
18035
18036 // We sometimes end up with a 64-bit integer load, from which we extract
18037 // two single-precision floating-point numbers. This happens with
18038 // std::complex<float>, and other similar structures, because of the way we
18039 // canonicalize structure copies. However, if we lack direct moves,
18040 // then the final bitcasts from the extracted integer values to the
18041 // floating-point numbers turn into store/load pairs. Even with direct moves,
18042 // just loading the two floating-point numbers is likely better.
18043 auto ReplaceTwoFloatLoad = [&]() {
18044 if (VT != MVT::i64)
18045 return false;
18046
18047 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
18048 LD->isVolatile())
18049 return false;
18050
18051 // We're looking for a sequence like this:
18052 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
18053 // t16: i64 = srl t13, Constant:i32<32>
18054 // t17: i32 = truncate t16
18055 // t18: f32 = bitcast t17
18056 // t19: i32 = truncate t13
18057 // t20: f32 = bitcast t19
18058
18059 if (!LD->hasNUsesOfValue(2, 0))
18060 return false;
18061
18062 auto UI = LD->user_begin();
18063 while (UI.getUse().getResNo() != 0) ++UI;
18064 SDNode *Trunc = *UI++;
18065 while (UI.getUse().getResNo() != 0) ++UI;
18066 SDNode *RightShift = *UI;
18067 if (Trunc->getOpcode() != ISD::TRUNCATE)
18068 std::swap(Trunc, RightShift);
18069
18070 if (Trunc->getOpcode() != ISD::TRUNCATE ||
18071 Trunc->getValueType(0) != MVT::i32 ||
18072 !Trunc->hasOneUse())
18073 return false;
18074 if (RightShift->getOpcode() != ISD::SRL ||
18075 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
18076 RightShift->getConstantOperandVal(1) != 32 ||
18077 !RightShift->hasOneUse())
18078 return false;
18079
18080 SDNode *Trunc2 = *RightShift->user_begin();
18081 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
18082 Trunc2->getValueType(0) != MVT::i32 ||
18083 !Trunc2->hasOneUse())
18084 return false;
18085
18086 SDNode *Bitcast = *Trunc->user_begin();
18087 SDNode *Bitcast2 = *Trunc2->user_begin();
18088
18089 if (Bitcast->getOpcode() != ISD::BITCAST ||
18090 Bitcast->getValueType(0) != MVT::f32)
18091 return false;
18092 if (Bitcast2->getOpcode() != ISD::BITCAST ||
18093 Bitcast2->getValueType(0) != MVT::f32)
18094 return false;
18095
18096 if (Subtarget.isLittleEndian())
18097 std::swap(Bitcast, Bitcast2);
18098
18099 // Bitcast has the second float (in memory-layout order) and Bitcast2
18100 // has the first one.
18101
18102 SDValue BasePtr = LD->getBasePtr();
18103 if (LD->isIndexed()) {
18104 assert(LD->getAddressingMode() == ISD::PRE_INC &&
18105 "Non-pre-inc AM on PPC?");
18106 BasePtr =
18107 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18108 LD->getOffset());
18109 }
18110
18111 auto MMOFlags =
18112 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
18113 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
18114 LD->getPointerInfo(), LD->getAlign(),
18115 MMOFlags, LD->getAAInfo());
18116 SDValue AddPtr =
18117 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
18118 BasePtr, DAG.getIntPtrConstant(4, dl));
18119 SDValue FloatLoad2 = DAG.getLoad(
18120 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
18121 LD->getPointerInfo().getWithOffset(4),
18122 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo());
18123
18124 if (LD->isIndexed()) {
18125 // Note that DAGCombine should re-form any pre-increment load(s) from
18126 // what is produced here if that makes sense.
18127 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
18128 }
18129
18130 DCI.CombineTo(Bitcast2, FloatLoad);
18131 DCI.CombineTo(Bitcast, FloatLoad2);
18132
18133 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
18134 SDValue(FloatLoad2.getNode(), 1));
18135 return true;
18136 };
18137
18138 if (ReplaceTwoFloatLoad())
18139 return SDValue(N, 0);
18140
18141 EVT MemVT = LD->getMemoryVT();
18142 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
18143 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
18144 if (LD->isUnindexed() && VT.isVector() &&
18145 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
18146 // P8 and later hardware should just use LOAD.
18147 !Subtarget.hasP8Vector() &&
18148 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
18149 VT == MVT::v4f32))) &&
18150 LD->getAlign() < ABIAlignment) {
18151 // This is a type-legal unaligned Altivec load.
18152 SDValue Chain = LD->getChain();
18153 SDValue Ptr = LD->getBasePtr();
18154 bool isLittleEndian = Subtarget.isLittleEndian();
18155
18156 // This implements the loading of unaligned vectors as described in
18157 // the venerable Apple Velocity Engine overview. Specifically:
18158 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
18159 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
18160 //
18161 // The general idea is to expand a sequence of one or more unaligned
18162 // loads into an alignment-based permutation-control instruction (lvsl
18163 // or lvsr), a series of regular vector loads (which always truncate
18164 // their input address to an aligned address), and a series of
18165 // permutations. The results of these permutations are the requested
18166 // loaded values. The trick is that the last "extra" load is not taken
18167 // from the address you might suspect (sizeof(vector) bytes after the
18168 // last requested load), but rather sizeof(vector) - 1 bytes after the
18169 // last requested vector. The point of this is to avoid a page fault if
18170 // the base address happened to be aligned. This works because if the
18171 // base address is aligned, then adding less than a full vector length
18172 // will cause the last vector in the sequence to be (re)loaded.
18173 // Otherwise, the next vector will be fetched as you might suspect was
18174 // necessary.
18175
18176 // We might be able to reuse the permutation generation from
18177 // a different base address offset from this one by an aligned amount.
18178 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
18179 // optimization later.
18180 Intrinsic::ID Intr, IntrLD, IntrPerm;
18181 MVT PermCntlTy, PermTy, LDTy;
18182 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18183 : Intrinsic::ppc_altivec_lvsl;
18184 IntrLD = Intrinsic::ppc_altivec_lvx;
18185 IntrPerm = Intrinsic::ppc_altivec_vperm;
18186 PermCntlTy = MVT::v16i8;
18187 PermTy = MVT::v4i32;
18188 LDTy = MVT::v4i32;
18189
18190 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
18191
18192 // Create the new MMO for the new base load. It is like the original MMO,
18193 // but represents an area in memory almost twice the vector size centered
18194 // on the original address. If the address is unaligned, we might start
18195 // reading up to (sizeof(vector)-1) bytes below the address of the
18196 // original unaligned load.
18198 MachineMemOperand *BaseMMO =
18199 MF.getMachineMemOperand(LD->getMemOperand(),
18200 -(int64_t)MemVT.getStoreSize()+1,
18201 2*MemVT.getStoreSize()-1);
18202
18203 // Create the new base load.
18204 SDValue LDXIntID =
18205 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
18206 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
18207 SDValue BaseLoad =
18209 DAG.getVTList(PermTy, MVT::Other),
18210 BaseLoadOps, LDTy, BaseMMO);
18211
18212 // Note that the value of IncOffset (which is provided to the next
18213 // load's pointer info offset value, and thus used to calculate the
18214 // alignment), and the value of IncValue (which is actually used to
18215 // increment the pointer value) are different! This is because we
18216 // require the next load to appear to be aligned, even though it
18217 // is actually offset from the base pointer by a lesser amount.
18218 int IncOffset = VT.getSizeInBits() / 8;
18219 int IncValue = IncOffset;
18220
18221 // Walk (both up and down) the chain looking for another load at the real
18222 // (aligned) offset (the alignment of the other load does not matter in
18223 // this case). If found, then do not use the offset reduction trick, as
18224 // that will prevent the loads from being later combined (as they would
18225 // otherwise be duplicates).
18226 if (!findConsecutiveLoad(LD, DAG))
18227 --IncValue;
18228
18230 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
18231 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18232
18233 MachineMemOperand *ExtraMMO =
18234 MF.getMachineMemOperand(LD->getMemOperand(),
18235 1, 2*MemVT.getStoreSize()-1);
18236 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
18237 SDValue ExtraLoad =
18239 DAG.getVTList(PermTy, MVT::Other),
18240 ExtraLoadOps, LDTy, ExtraMMO);
18241
18242 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18243 BaseLoad.getValue(1), ExtraLoad.getValue(1));
18244
18245 // Because vperm has a big-endian bias, we must reverse the order
18246 // of the input vectors and complement the permute control vector
18247 // when generating little endian code. We have already handled the
18248 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
18249 // and ExtraLoad here.
18250 SDValue Perm;
18251 if (isLittleEndian)
18252 Perm = BuildIntrinsicOp(IntrPerm,
18253 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
18254 else
18255 Perm = BuildIntrinsicOp(IntrPerm,
18256 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
18257
18258 if (VT != PermTy)
18259 Perm = Subtarget.hasAltivec()
18260 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
18261 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
18262 DAG.getTargetConstant(1, dl, MVT::i64));
18263 // second argument is 1 because this rounding
18264 // is always exact.
18265
18266 // The output of the permutation is our loaded result, the TokenFactor is
18267 // our new chain.
18268 DCI.CombineTo(N, Perm, TF);
18269 return SDValue(N, 0);
18270 }
18271 }
18272 break;
18274 bool isLittleEndian = Subtarget.isLittleEndian();
18275 unsigned IID = N->getConstantOperandVal(0);
18276 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18277 : Intrinsic::ppc_altivec_lvsl);
18278 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
18279 SDValue Add = N->getOperand(1);
18280
18281 int Bits = 4 /* 16 byte alignment */;
18282
18283 if (DAG.MaskedValueIsZero(Add->getOperand(1),
18284 APInt::getAllOnes(Bits /* alignment */)
18285 .zext(Add.getScalarValueSizeInBits()))) {
18286 SDNode *BasePtr = Add->getOperand(0).getNode();
18287 for (SDNode *U : BasePtr->users()) {
18288 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18289 U->getConstantOperandVal(0) == IID) {
18290 // We've found another LVSL/LVSR, and this address is an aligned
18291 // multiple of that one. The results will be the same, so use the
18292 // one we've just found instead.
18293
18294 return SDValue(U, 0);
18295 }
18296 }
18297 }
18298
18299 if (isa<ConstantSDNode>(Add->getOperand(1))) {
18300 SDNode *BasePtr = Add->getOperand(0).getNode();
18301 for (SDNode *U : BasePtr->users()) {
18302 if (U->getOpcode() == ISD::ADD &&
18303 isa<ConstantSDNode>(U->getOperand(1)) &&
18304 (Add->getConstantOperandVal(1) - U->getConstantOperandVal(1)) %
18305 (1ULL << Bits) ==
18306 0) {
18307 SDNode *OtherAdd = U;
18308 for (SDNode *V : OtherAdd->users()) {
18309 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18310 V->getConstantOperandVal(0) == IID) {
18311 return SDValue(V, 0);
18312 }
18313 }
18314 }
18315 }
18316 }
18317 }
18318
18319 // Combine vmaxsw/h/b(a, a's negation) to abs(a)
18320 // Expose the vabsduw/h/b opportunity for down stream
18321 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
18322 (IID == Intrinsic::ppc_altivec_vmaxsw ||
18323 IID == Intrinsic::ppc_altivec_vmaxsh ||
18324 IID == Intrinsic::ppc_altivec_vmaxsb)) {
18325 SDValue V1 = N->getOperand(1);
18326 SDValue V2 = N->getOperand(2);
18327 if ((V1.getSimpleValueType() == MVT::v4i32 ||
18328 V1.getSimpleValueType() == MVT::v8i16 ||
18329 V1.getSimpleValueType() == MVT::v16i8) &&
18330 V1.getSimpleValueType() == V2.getSimpleValueType()) {
18331 // (0-a, a)
18332 if (V1.getOpcode() == ISD::SUB &&
18333 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
18334 V1.getOperand(1) == V2) {
18335 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
18336 }
18337 // (a, 0-a)
18338 if (V2.getOpcode() == ISD::SUB &&
18340 V2.getOperand(1) == V1) {
18341 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18342 }
18343 // (x-y, y-x)
18344 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
18345 V1.getOperand(0) == V2.getOperand(1) &&
18346 V1.getOperand(1) == V2.getOperand(0)) {
18347 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18348 }
18349 }
18350 }
18351 }
18352
18353 break;
18355 switch (N->getConstantOperandVal(1)) {
18356 default:
18357 break;
18358 case Intrinsic::ppc_altivec_vsum4sbs:
18359 case Intrinsic::ppc_altivec_vsum4shs:
18360 case Intrinsic::ppc_altivec_vsum4ubs: {
18361 // These sum-across intrinsics only have a chain due to the side effect
18362 // that they may set the SAT bit. If we know the SAT bit will not be set
18363 // for some inputs, we can replace any uses of their chain with the
18364 // input chain.
18365 if (BuildVectorSDNode *BVN =
18366 dyn_cast<BuildVectorSDNode>(N->getOperand(3))) {
18367 APInt APSplatBits, APSplatUndef;
18368 unsigned SplatBitSize;
18369 bool HasAnyUndefs;
18370 bool BVNIsConstantSplat = BVN->isConstantSplat(
18371 APSplatBits, APSplatUndef, SplatBitSize, HasAnyUndefs, 0,
18372 !Subtarget.isLittleEndian());
18373 // If the constant splat vector is 0, the SAT bit will not be set.
18374 if (BVNIsConstantSplat && APSplatBits == 0)
18375 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), N->getOperand(0));
18376 }
18377 return SDValue();
18378 }
18379 case Intrinsic::ppc_vsx_lxvw4x:
18380 case Intrinsic::ppc_vsx_lxvd2x:
18381 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18382 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18383 if (Subtarget.needsSwapsForVSXMemOps())
18384 return expandVSXLoadForLE(N, DCI);
18385 break;
18386 }
18387 break;
18389 // For little endian, VSX stores require generating xxswapd/stxvd2x.
18390 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18391 if (Subtarget.needsSwapsForVSXMemOps()) {
18392 switch (N->getConstantOperandVal(1)) {
18393 default:
18394 break;
18395 case Intrinsic::ppc_vsx_stxvw4x:
18396 case Intrinsic::ppc_vsx_stxvd2x:
18397 return expandVSXStoreForLE(N, DCI);
18398 }
18399 }
18400 break;
18401 case ISD::BSWAP: {
18402 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
18403 // For subtargets without LDBRX, we can still do better than the default
18404 // expansion even for 64-bit BSWAP (LOAD).
18405 bool Is64BitBswapOn64BitTgt =
18406 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
18407 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
18408 N->getOperand(0).hasOneUse();
18409 if (IsSingleUseNormalLd &&
18410 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
18411 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
18412 SDValue Load = N->getOperand(0);
18414 // Create the byte-swapping load.
18415 SDValue Ops[] = {
18416 LD->getChain(), // Chain
18417 LD->getBasePtr(), // Ptr
18418 DAG.getValueType(N->getValueType(0)) // VT
18419 };
18420 SDValue BSLoad =
18421 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
18422 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
18423 MVT::i64 : MVT::i32, MVT::Other),
18424 Ops, LD->getMemoryVT(), LD->getMemOperand());
18425
18426 // If this is an i16 load, insert the truncate.
18427 SDValue ResVal = BSLoad;
18428 if (N->getValueType(0) == MVT::i16)
18429 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
18430
18431 // First, combine the bswap away. This makes the value produced by the
18432 // load dead.
18433 DCI.CombineTo(N, ResVal);
18434
18435 // Next, combine the load away, we give it a bogus result value but a real
18436 // chain result. The result value is dead because the bswap is dead.
18437 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
18438
18439 // Return N so it doesn't get rechecked!
18440 return SDValue(N, 0);
18441 }
18442 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
18443 // before legalization so that the BUILD_PAIR is handled correctly.
18444 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
18445 !IsSingleUseNormalLd)
18446 return SDValue();
18447 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
18448
18449 // Can't split volatile or atomic loads.
18450 if (!LD->isSimple())
18451 return SDValue();
18452 SDValue BasePtr = LD->getBasePtr();
18453 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
18454 LD->getPointerInfo(), LD->getAlign());
18455 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
18456 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18457 DAG.getIntPtrConstant(4, dl));
18459 LD->getMemOperand(), 4, 4);
18460 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
18461 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
18462 SDValue Res;
18463 if (Subtarget.isLittleEndian())
18464 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
18465 else
18466 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
18467 SDValue TF =
18468 DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18469 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
18470 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
18471 return Res;
18472 }
18473 case PPCISD::VCMP:
18474 // If a VCMP_rec node already exists with exactly the same operands as this
18475 // node, use its result instead of this node (VCMP_rec computes both a CR6
18476 // and a normal output).
18477 //
18478 if (!N->getOperand(0).hasOneUse() &&
18479 !N->getOperand(1).hasOneUse() &&
18480 !N->getOperand(2).hasOneUse()) {
18481
18482 // Scan all of the users of the LHS, looking for VCMP_rec's that match.
18483 SDNode *VCMPrecNode = nullptr;
18484
18485 SDNode *LHSN = N->getOperand(0).getNode();
18486 for (SDNode *User : LHSN->users())
18487 if (User->getOpcode() == PPCISD::VCMP_rec &&
18488 User->getOperand(1) == N->getOperand(1) &&
18489 User->getOperand(2) == N->getOperand(2) &&
18490 User->getOperand(0) == N->getOperand(0)) {
18491 VCMPrecNode = User;
18492 break;
18493 }
18494
18495 // If there is no VCMP_rec node, or if the flag value has a single use,
18496 // don't transform this.
18497 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
18498 break;
18499
18500 // Look at the (necessarily single) use of the flag value. If it has a
18501 // chain, this transformation is more complex. Note that multiple things
18502 // could use the value result, which we should ignore.
18503 SDNode *FlagUser = nullptr;
18504 for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
18505 FlagUser == nullptr; ++UI) {
18506 assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
18507 SDNode *User = UI->getUser();
18508 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
18509 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
18510 FlagUser = User;
18511 break;
18512 }
18513 }
18514 }
18515
18516 // If the user is a MFOCRF instruction, we know this is safe.
18517 // Otherwise we give up for right now.
18518 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
18519 return SDValue(VCMPrecNode, 0);
18520 }
18521 break;
18522 case ISD::BR_CC: {
18523 // If this is a branch on an altivec predicate comparison, lower this so
18524 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
18525 // lowering is done pre-legalize, because the legalizer lowers the predicate
18526 // compare down to code that is difficult to reassemble.
18527 // This code also handles branches that depend on the result of a store
18528 // conditional.
18529 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18530 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
18531
18532 int CompareOpc;
18533 bool isDot;
18534
18535 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE))
18536 break;
18537
18538 // Since we are doing this pre-legalize, the RHS can be a constant of
18539 // arbitrary bitwidth which may cause issues when trying to get the value
18540 // from the underlying APInt.
18541 auto RHSAPInt = RHS->getAsAPIntVal();
18542 if (!RHSAPInt.isIntN(64))
18543 break;
18544
18545 unsigned Val = RHSAPInt.getZExtValue();
18546 auto isImpossibleCompare = [&]() {
18547 // If this is a comparison against something other than 0/1, then we know
18548 // that the condition is never/always true.
18549 if (Val != 0 && Val != 1) {
18550 if (CC == ISD::SETEQ) // Cond never true, remove branch.
18551 return N->getOperand(0);
18552 // Always !=, turn it into an unconditional branch.
18553 return DAG.getNode(ISD::BR, dl, MVT::Other,
18554 N->getOperand(0), N->getOperand(4));
18555 }
18556 return SDValue();
18557 };
18558 // Combine branches fed by store conditional instructions (st[bhwd]cx).
18559 unsigned StoreWidth = 0;
18560 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
18561 isStoreConditional(LHS, StoreWidth)) {
18562 if (SDValue Impossible = isImpossibleCompare())
18563 return Impossible;
18564 PPC::Predicate CompOpc;
18565 // eq 0 => ne
18566 // ne 0 => eq
18567 // eq 1 => eq
18568 // ne 1 => ne
18569 if (Val == 0)
18570 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ;
18571 else
18572 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE;
18573
18574 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3),
18575 DAG.getConstant(StoreWidth, dl, MVT::i32)};
18576 auto *MemNode = cast<MemSDNode>(LHS);
18577 SDValue ConstSt = DAG.getMemIntrinsicNode(
18578 PPCISD::STORE_COND, dl,
18579 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops,
18580 MemNode->getMemoryVT(), MemNode->getMemOperand());
18581
18582 SDValue InChain;
18583 // Unchain the branch from the original store conditional.
18584 if (N->getOperand(0) == LHS.getValue(1))
18585 InChain = LHS.getOperand(0);
18586 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) {
18587 SmallVector<SDValue, 4> InChains;
18588 SDValue InTF = N->getOperand(0);
18589 for (int i = 0, e = InTF.getNumOperands(); i < e; i++)
18590 if (InTF.getOperand(i) != LHS.getValue(1))
18591 InChains.push_back(InTF.getOperand(i));
18592 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains);
18593 }
18594
18595 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain,
18596 DAG.getConstant(CompOpc, dl, MVT::i32),
18597 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4),
18598 ConstSt.getValue(2));
18599 }
18600
18601 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18602 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
18603 assert(isDot && "Can't compare against a vector result!");
18604
18605 if (SDValue Impossible = isImpossibleCompare())
18606 return Impossible;
18607
18608 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
18609 // Create the PPCISD altivec 'dot' comparison node.
18610 SDValue Ops[] = {
18611 LHS.getOperand(2), // LHS of compare
18612 LHS.getOperand(3), // RHS of compare
18613 DAG.getConstant(CompareOpc, dl, MVT::i32)
18614 };
18615 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
18616 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
18617
18618 // Unpack the result based on how the target uses it.
18619 PPC::Predicate CompOpc;
18620 switch (LHS.getConstantOperandVal(1)) {
18621 default: // Can't happen, don't crash on invalid number though.
18622 case 0: // Branch on the value of the EQ bit of CR6.
18623 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
18624 break;
18625 case 1: // Branch on the inverted value of the EQ bit of CR6.
18626 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
18627 break;
18628 case 2: // Branch on the value of the LT bit of CR6.
18629 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
18630 break;
18631 case 3: // Branch on the inverted value of the LT bit of CR6.
18632 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
18633 break;
18634 }
18635
18636 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
18637 DAG.getConstant(CompOpc, dl, MVT::i32),
18638 DAG.getRegister(PPC::CR6, MVT::i32),
18639 N->getOperand(4), CompNode.getValue(1));
18640 }
18641 break;
18642 }
18643 case ISD::BUILD_VECTOR:
18644 return DAGCombineBuildVector(N, DCI);
18645 case PPCISD::ADDC:
18646 return DAGCombineAddc(N, DCI);
18647 case PPCISD::SUBE:
18648 return DAGCombineSube(N, DCI);
18649
18650 case ISD::BITCAST:
18651 return DAGCombineBitcast(N, DCI);
18652 }
18653
18654 return SDValue();
18655}
18656
18657SDValue
18659 SelectionDAG &DAG,
18660 SmallVectorImpl<SDNode *> &Created) const {
18661 // fold (sdiv X, pow2)
18662 EVT VT = N->getValueType(0);
18663 if (VT == MVT::i64 && !Subtarget.isPPC64())
18664 return SDValue();
18665 if ((VT != MVT::i32 && VT != MVT::i64) ||
18666 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
18667 return SDValue();
18668
18669 SDLoc DL(N);
18670 SDValue N0 = N->getOperand(0);
18671
18672 bool IsNegPow2 = Divisor.isNegatedPowerOf2();
18673 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countr_zero();
18674 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
18675
18676 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
18677 Created.push_back(Op.getNode());
18678
18679 if (IsNegPow2) {
18680 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
18681 Created.push_back(Op.getNode());
18682 }
18683
18684 return Op;
18685}
18686
18687//===----------------------------------------------------------------------===//
18688// Inline Assembly Support
18689//===----------------------------------------------------------------------===//
18690
18693 const APInt &DemandedElts,
18694 const SelectionDAG &DAG,
18695 unsigned Depth) const {
18696 Known.resetAll();
18697 switch (Op.getOpcode()) {
18698 default: break;
18699 case PPCISD::LBRX: {
18700 // lhbrx is known to have the top bits cleared out.
18701 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
18702 Known.Zero = 0xFFFF0000;
18703 break;
18704 }
18705 case PPCISD::ADDE: {
18706 if (Op.getResNo() == 0) {
18707 // (0|1), _ = ADDE 0, 0, CARRY
18708 SDValue LHS = Op.getOperand(0);
18709 SDValue RHS = Op.getOperand(1);
18710 if (isNullConstant(LHS) && isNullConstant(RHS))
18711 Known.Zero = ~1ULL;
18712 }
18713 break;
18714 }
18716 switch (Op.getConstantOperandVal(0)) {
18717 default: break;
18718 case Intrinsic::ppc_altivec_vcmpbfp_p:
18719 case Intrinsic::ppc_altivec_vcmpeqfp_p:
18720 case Intrinsic::ppc_altivec_vcmpequb_p:
18721 case Intrinsic::ppc_altivec_vcmpequh_p:
18722 case Intrinsic::ppc_altivec_vcmpequw_p:
18723 case Intrinsic::ppc_altivec_vcmpequd_p:
18724 case Intrinsic::ppc_altivec_vcmpequq_p:
18725 case Intrinsic::ppc_altivec_vcmpgefp_p:
18726 case Intrinsic::ppc_altivec_vcmpgtfp_p:
18727 case Intrinsic::ppc_altivec_vcmpgtsb_p:
18728 case Intrinsic::ppc_altivec_vcmpgtsh_p:
18729 case Intrinsic::ppc_altivec_vcmpgtsw_p:
18730 case Intrinsic::ppc_altivec_vcmpgtsd_p:
18731 case Intrinsic::ppc_altivec_vcmpgtsq_p:
18732 case Intrinsic::ppc_altivec_vcmpgtub_p:
18733 case Intrinsic::ppc_altivec_vcmpgtuh_p:
18734 case Intrinsic::ppc_altivec_vcmpgtuw_p:
18735 case Intrinsic::ppc_altivec_vcmpgtud_p:
18736 case Intrinsic::ppc_altivec_vcmpgtuq_p:
18737 Known.Zero = ~1U; // All bits but the low one are known to be zero.
18738 break;
18739 }
18740 break;
18741 }
18743 switch (Op.getConstantOperandVal(1)) {
18744 default:
18745 break;
18746 case Intrinsic::ppc_load2r:
18747 // Top bits are cleared for load2r (which is the same as lhbrx).
18748 Known.Zero = 0xFFFF0000;
18749 break;
18750 }
18751 break;
18752 }
18753 }
18754}
18755
18757 switch (Subtarget.getCPUDirective()) {
18758 default: break;
18759 case PPC::DIR_970:
18760 case PPC::DIR_PWR4:
18761 case PPC::DIR_PWR5:
18762 case PPC::DIR_PWR5X:
18763 case PPC::DIR_PWR6:
18764 case PPC::DIR_PWR6X:
18765 case PPC::DIR_PWR7:
18766 case PPC::DIR_PWR8:
18767 case PPC::DIR_PWR9:
18768 case PPC::DIR_PWR10:
18769 case PPC::DIR_PWR11:
18770 case PPC::DIR_PWR_FUTURE: {
18771 if (!ML)
18772 break;
18773
18775 // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
18776 // so that we can decrease cache misses and branch-prediction misses.
18777 // Actual alignment of the loop will depend on the hotness check and other
18778 // logic in alignBlocks.
18779 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
18780 return Align(32);
18781 }
18782
18783 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
18784
18785 // For small loops (between 5 and 8 instructions), align to a 32-byte
18786 // boundary so that the entire loop fits in one instruction-cache line.
18787 uint64_t LoopSize = 0;
18788 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
18789 for (const MachineInstr &J : **I) {
18790 LoopSize += TII->getInstSizeInBytes(J);
18791 if (LoopSize > 32)
18792 break;
18793 }
18794
18795 if (LoopSize > 16 && LoopSize <= 32)
18796 return Align(32);
18797
18798 break;
18799 }
18800 }
18801
18803}
18804
18805/// getConstraintType - Given a constraint, return the type of
18806/// constraint it is for this target.
18809 if (Constraint.size() == 1) {
18810 switch (Constraint[0]) {
18811 default: break;
18812 case 'b':
18813 case 'r':
18814 case 'f':
18815 case 'd':
18816 case 'v':
18817 case 'y':
18818 return C_RegisterClass;
18819 case 'Z':
18820 // FIXME: While Z does indicate a memory constraint, it specifically
18821 // indicates an r+r address (used in conjunction with the 'y' modifier
18822 // in the replacement string). Currently, we're forcing the base
18823 // register to be r0 in the asm printer (which is interpreted as zero)
18824 // and forming the complete address in the second register. This is
18825 // suboptimal.
18826 return C_Memory;
18827 }
18828 } else if (Constraint == "wc") { // individual CR bits.
18829 return C_RegisterClass;
18830 } else if (Constraint == "wa" || Constraint == "wd" ||
18831 Constraint == "wf" || Constraint == "ws" ||
18832 Constraint == "wi" || Constraint == "ww") {
18833 return C_RegisterClass; // VSX registers.
18834 }
18835 return TargetLowering::getConstraintType(Constraint);
18836}
18837
18838/// Examine constraint type and operand type and determine a weight value.
18839/// This object must already have been set up with the operand type
18840/// and the current alternative constraint selected.
18843 AsmOperandInfo &info, const char *constraint) const {
18845 Value *CallOperandVal = info.CallOperandVal;
18846 // If we don't have a value, we can't do a match,
18847 // but allow it at the lowest weight.
18848 if (!CallOperandVal)
18849 return CW_Default;
18850 Type *type = CallOperandVal->getType();
18851
18852 // Look at the constraint type.
18853 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
18854 return CW_Register; // an individual CR bit.
18855 else if ((StringRef(constraint) == "wa" ||
18856 StringRef(constraint) == "wd" ||
18857 StringRef(constraint) == "wf") &&
18858 type->isVectorTy())
18859 return CW_Register;
18860 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
18861 return CW_Register; // just hold 64-bit integers data.
18862 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
18863 return CW_Register;
18864 else if (StringRef(constraint) == "ww" && type->isFloatTy())
18865 return CW_Register;
18866
18867 switch (*constraint) {
18868 default:
18870 break;
18871 case 'b':
18872 if (type->isIntegerTy())
18873 weight = CW_Register;
18874 break;
18875 case 'f':
18876 if (type->isFloatTy())
18877 weight = CW_Register;
18878 break;
18879 case 'd':
18880 if (type->isDoubleTy())
18881 weight = CW_Register;
18882 break;
18883 case 'v':
18884 if (type->isVectorTy())
18885 weight = CW_Register;
18886 break;
18887 case 'y':
18888 weight = CW_Register;
18889 break;
18890 case 'Z':
18891 weight = CW_Memory;
18892 break;
18893 }
18894 return weight;
18895}
18896
18897std::pair<unsigned, const TargetRegisterClass *>
18899 StringRef Constraint,
18900 MVT VT) const {
18901 if (Constraint.size() == 1) {
18902 // GCC RS6000 Constraint Letters
18903 switch (Constraint[0]) {
18904 case 'b': // R1-R31
18905 if (VT == MVT::i64 && Subtarget.isPPC64())
18906 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
18907 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
18908 case 'r': // R0-R31
18909 if (VT == MVT::i64 && Subtarget.isPPC64())
18910 return std::make_pair(0U, &PPC::G8RCRegClass);
18911 return std::make_pair(0U, &PPC::GPRCRegClass);
18912 // 'd' and 'f' constraints are both defined to be "the floating point
18913 // registers", where one is for 32-bit and the other for 64-bit. We don't
18914 // really care overly much here so just give them all the same reg classes.
18915 case 'd':
18916 case 'f':
18917 if (Subtarget.hasSPE()) {
18918 if (VT == MVT::f32 || VT == MVT::i32)
18919 return std::make_pair(0U, &PPC::GPRCRegClass);
18920 if (VT == MVT::f64 || VT == MVT::i64)
18921 return std::make_pair(0U, &PPC::SPERCRegClass);
18922 } else {
18923 if (VT == MVT::f32 || VT == MVT::i32)
18924 return std::make_pair(0U, &PPC::F4RCRegClass);
18925 if (VT == MVT::f64 || VT == MVT::i64)
18926 return std::make_pair(0U, &PPC::F8RCRegClass);
18927 }
18928 break;
18929 case 'v':
18930 if (Subtarget.hasAltivec() && VT.isVector())
18931 return std::make_pair(0U, &PPC::VRRCRegClass);
18932 else if (Subtarget.hasVSX())
18933 // Scalars in Altivec registers only make sense with VSX.
18934 return std::make_pair(0U, &PPC::VFRCRegClass);
18935 break;
18936 case 'y': // crrc
18937 return std::make_pair(0U, &PPC::CRRCRegClass);
18938 }
18939 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
18940 // An individual CR bit.
18941 return std::make_pair(0U, &PPC::CRBITRCRegClass);
18942 } else if ((Constraint == "wa" || Constraint == "wd" ||
18943 Constraint == "wf" || Constraint == "wi") &&
18944 Subtarget.hasVSX()) {
18945 // A VSX register for either a scalar (FP) or vector. There is no
18946 // support for single precision scalars on subtargets prior to Power8.
18947 if (VT.isVector())
18948 return std::make_pair(0U, &PPC::VSRCRegClass);
18949 if (VT == MVT::f32 && Subtarget.hasP8Vector())
18950 return std::make_pair(0U, &PPC::VSSRCRegClass);
18951 return std::make_pair(0U, &PPC::VSFRCRegClass);
18952 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
18953 if (VT == MVT::f32 && Subtarget.hasP8Vector())
18954 return std::make_pair(0U, &PPC::VSSRCRegClass);
18955 else
18956 return std::make_pair(0U, &PPC::VSFRCRegClass);
18957 } else if (Constraint == "lr") {
18958 if (VT == MVT::i64)
18959 return std::make_pair(0U, &PPC::LR8RCRegClass);
18960 else
18961 return std::make_pair(0U, &PPC::LRRCRegClass);
18962 }
18963
18964 // Handle special cases of physical registers that are not properly handled
18965 // by the base class.
18966 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
18967 // If we name a VSX register, we can't defer to the base class because it
18968 // will not recognize the correct register (their names will be VSL{0-31}
18969 // and V{0-31} so they won't match). So we match them here.
18970 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
18971 int VSNum = atoi(Constraint.data() + 3);
18972 assert(VSNum >= 0 && VSNum <= 63 &&
18973 "Attempted to access a vsr out of range");
18974 if (VSNum < 32)
18975 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
18976 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
18977 }
18978
18979 // For float registers, we can't defer to the base class as it will match
18980 // the SPILLTOVSRRC class.
18981 if (Constraint.size() > 3 && Constraint[1] == 'f') {
18982 int RegNum = atoi(Constraint.data() + 2);
18983 if (RegNum > 31 || RegNum < 0)
18984 report_fatal_error("Invalid floating point register number");
18985 if (VT == MVT::f32 || VT == MVT::i32)
18986 return Subtarget.hasSPE()
18987 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
18988 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
18989 if (VT == MVT::f64 || VT == MVT::i64)
18990 return Subtarget.hasSPE()
18991 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
18992 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
18993 }
18994 }
18995
18996 std::pair<unsigned, const TargetRegisterClass *> R =
18998
18999 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
19000 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
19001 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
19002 // register.
19003 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
19004 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
19005 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
19006 PPC::GPRCRegClass.contains(R.first))
19007 return std::make_pair(TRI->getMatchingSuperReg(R.first,
19008 PPC::sub_32, &PPC::G8RCRegClass),
19009 &PPC::G8RCRegClass);
19010
19011 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
19012 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
19013 R.first = PPC::CR0;
19014 R.second = &PPC::CRRCRegClass;
19015 }
19016 // FIXME: This warning should ideally be emitted in the front end.
19017 const auto &TM = getTargetMachine();
19018 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
19019 if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
19020 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
19021 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
19022 errs() << "warning: vector registers 20 to 32 are reserved in the "
19023 "default AIX AltiVec ABI and cannot be used\n";
19024 }
19025
19026 return R;
19027}
19028
19029/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19030/// vector. If it is invalid, don't add anything to Ops.
19032 StringRef Constraint,
19033 std::vector<SDValue> &Ops,
19034 SelectionDAG &DAG) const {
19035 SDValue Result;
19036
19037 // Only support length 1 constraints.
19038 if (Constraint.size() > 1)
19039 return;
19040
19041 char Letter = Constraint[0];
19042 switch (Letter) {
19043 default: break;
19044 case 'I':
19045 case 'J':
19046 case 'K':
19047 case 'L':
19048 case 'M':
19049 case 'N':
19050 case 'O':
19051 case 'P': {
19053 if (!CST) return; // Must be an immediate to match.
19054 SDLoc dl(Op);
19055 int64_t Value = CST->getSExtValue();
19056 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
19057 // numbers are printed as such.
19058 switch (Letter) {
19059 default: llvm_unreachable("Unknown constraint letter!");
19060 case 'I': // "I" is a signed 16-bit constant.
19061 if (isInt<16>(Value))
19062 Result = DAG.getTargetConstant(Value, dl, TCVT);
19063 break;
19064 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
19066 Result = DAG.getTargetConstant(Value, dl, TCVT);
19067 break;
19068 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
19070 Result = DAG.getTargetConstant(Value, dl, TCVT);
19071 break;
19072 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
19073 if (isUInt<16>(Value))
19074 Result = DAG.getTargetConstant(Value, dl, TCVT);
19075 break;
19076 case 'M': // "M" is a constant that is greater than 31.
19077 if (Value > 31)
19078 Result = DAG.getTargetConstant(Value, dl, TCVT);
19079 break;
19080 case 'N': // "N" is a positive constant that is an exact power of two.
19081 if (Value > 0 && isPowerOf2_64(Value))
19082 Result = DAG.getTargetConstant(Value, dl, TCVT);
19083 break;
19084 case 'O': // "O" is the constant zero.
19085 if (Value == 0)
19086 Result = DAG.getTargetConstant(Value, dl, TCVT);
19087 break;
19088 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
19089 if (isInt<16>(-Value))
19090 Result = DAG.getTargetConstant(Value, dl, TCVT);
19091 break;
19092 }
19093 break;
19094 }
19095 }
19096
19097 if (Result.getNode()) {
19098 Ops.push_back(Result);
19099 return;
19100 }
19101
19102 // Handle standard constraint letters.
19104}
19105
19108 SelectionDAG &DAG) const {
19109 if (I.getNumOperands() <= 1)
19110 return;
19111 if (!isa<ConstantSDNode>(Ops[1].getNode()))
19112 return;
19113 auto IntrinsicID = Ops[1].getNode()->getAsZExtVal();
19114 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
19115 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap)
19116 return;
19117
19118 if (MDNode *MDN = I.getMetadata(LLVMContext::MD_annotation))
19119 Ops.push_back(DAG.getMDNode(MDN));
19120}
19121
19122// isLegalAddressingMode - Return true if the addressing mode represented
19123// by AM is legal for this target, for a load/store of the specified type.
19125 const AddrMode &AM, Type *Ty,
19126 unsigned AS,
19127 Instruction *I) const {
19128 // Vector type r+i form is supported since power9 as DQ form. We don't check
19129 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
19130 // imm form is preferred and the offset can be adjusted to use imm form later
19131 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
19132 // max offset to check legal addressing mode, we should be a little aggressive
19133 // to contain other offsets for that LSRUse.
19134 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
19135 return false;
19136
19137 // PPC allows a sign-extended 16-bit immediate field.
19138 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
19139 return false;
19140
19141 // No global is ever allowed as a base.
19142 if (AM.BaseGV)
19143 return false;
19144
19145 // PPC only support r+r,
19146 switch (AM.Scale) {
19147 case 0: // "r+i" or just "i", depending on HasBaseReg.
19148 break;
19149 case 1:
19150 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
19151 return false;
19152 // Otherwise we have r+r or r+i.
19153 break;
19154 case 2:
19155 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
19156 return false;
19157 // Allow 2*r as r+r.
19158 break;
19159 default:
19160 // No other scales are supported.
19161 return false;
19162 }
19163
19164 return true;
19165}
19166
19167SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
19168 SelectionDAG &DAG) const {
19170 MachineFrameInfo &MFI = MF.getFrameInfo();
19171 MFI.setReturnAddressIsTaken(true);
19172
19173 SDLoc dl(Op);
19174 unsigned Depth = Op.getConstantOperandVal(0);
19175
19176 // Make sure the function does not optimize away the store of the RA to
19177 // the stack.
19178 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
19179 FuncInfo->setLRStoreRequired();
19180 auto PtrVT = getPointerTy(MF.getDataLayout());
19181
19182 if (Depth > 0) {
19183 // The link register (return address) is saved in the caller's frame
19184 // not the callee's stack frame. So we must get the caller's frame
19185 // address and load the return address at the LR offset from there.
19186 SDValue FrameAddr =
19187 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19189 SDValue Offset =
19190 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
19191 Subtarget.getScalarIntVT());
19192 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
19193 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
19195 }
19196
19197 // Just load the return address off the stack.
19198 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
19199 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
19201}
19202
19203SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
19204 SelectionDAG &DAG) const {
19205 SDLoc dl(Op);
19206 unsigned Depth = Op.getConstantOperandVal(0);
19207
19208 MachineFunction &MF = DAG.getMachineFunction();
19209 MachineFrameInfo &MFI = MF.getFrameInfo();
19210 MFI.setFrameAddressIsTaken(true);
19211
19212 EVT PtrVT = getPointerTy(MF.getDataLayout());
19213 bool isPPC64 = PtrVT == MVT::i64;
19214
19215 // Naked functions never have a frame pointer, and so we use r1. For all
19216 // other functions, this decision must be delayed until during PEI.
19217 unsigned FrameReg;
19218 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
19219 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
19220 else
19221 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
19222
19223 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
19224 PtrVT);
19225 while (Depth--)
19226 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19227 FrameAddr, MachinePointerInfo());
19228 return FrameAddr;
19229}
19230
19231#define GET_REGISTER_MATCHER
19232#include "PPCGenAsmMatcher.inc"
19233
19235 const MachineFunction &MF) const {
19236 bool IsPPC64 = Subtarget.isPPC64();
19237
19238 bool Is64Bit = IsPPC64 && VT == LLT::scalar(64);
19239 if (!Is64Bit && VT != LLT::scalar(32))
19240 report_fatal_error("Invalid register global variable type");
19241
19243 if (!Reg)
19244 return Reg;
19245
19246 // FIXME: Unable to generate code for `-O2` but okay for `-O0`.
19247 // Need followup investigation as to why.
19248 if ((IsPPC64 && Reg == PPC::R2) || Reg == PPC::R0)
19249 report_fatal_error(Twine("Trying to reserve an invalid register \"" +
19250 StringRef(RegName) + "\"."));
19251
19252 // Convert GPR to GP8R register for 64bit.
19253 if (Is64Bit && StringRef(RegName).starts_with_insensitive("r"))
19254 Reg = Reg.id() - PPC::R0 + PPC::X0;
19255
19256 return Reg;
19257}
19258
19260 // 32-bit SVR4 ABI access everything as got-indirect.
19261 if (Subtarget.is32BitELFABI())
19262 return true;
19263
19264 // AIX accesses everything indirectly through the TOC, which is similar to
19265 // the GOT.
19266 if (Subtarget.isAIXABI())
19267 return true;
19268
19270 // If it is small or large code model, module locals are accessed
19271 // indirectly by loading their address from .toc/.got.
19272 if (CModel == CodeModel::Small || CModel == CodeModel::Large)
19273 return true;
19274
19275 // JumpTable and BlockAddress are accessed as got-indirect.
19277 return true;
19278
19280 return Subtarget.isGVIndirectSymbol(G->getGlobal());
19281
19282 return false;
19283}
19284
19285bool
19287 // The PowerPC target isn't yet aware of offsets.
19288 return false;
19289}
19290
19293 MachineFunction &MF, unsigned Intrinsic) const {
19294 IntrinsicInfo Info;
19295 switch (Intrinsic) {
19296 case Intrinsic::ppc_atomicrmw_xchg_i128:
19297 case Intrinsic::ppc_atomicrmw_add_i128:
19298 case Intrinsic::ppc_atomicrmw_sub_i128:
19299 case Intrinsic::ppc_atomicrmw_nand_i128:
19300 case Intrinsic::ppc_atomicrmw_and_i128:
19301 case Intrinsic::ppc_atomicrmw_or_i128:
19302 case Intrinsic::ppc_atomicrmw_xor_i128:
19303 case Intrinsic::ppc_cmpxchg_i128:
19304 Info.opc = ISD::INTRINSIC_W_CHAIN;
19305 Info.memVT = MVT::i128;
19306 Info.ptrVal = I.getArgOperand(0);
19307 Info.offset = 0;
19308 Info.align = Align(16);
19311 Infos.push_back(Info);
19312 return;
19313 case Intrinsic::ppc_atomic_load_i128:
19314 Info.opc = ISD::INTRINSIC_W_CHAIN;
19315 Info.memVT = MVT::i128;
19316 Info.ptrVal = I.getArgOperand(0);
19317 Info.offset = 0;
19318 Info.align = Align(16);
19320 Infos.push_back(Info);
19321 return;
19322 case Intrinsic::ppc_atomic_store_i128:
19323 Info.opc = ISD::INTRINSIC_VOID;
19324 Info.memVT = MVT::i128;
19325 Info.ptrVal = I.getArgOperand(2);
19326 Info.offset = 0;
19327 Info.align = Align(16);
19329 Infos.push_back(Info);
19330 return;
19331 case Intrinsic::ppc_altivec_lvx:
19332 case Intrinsic::ppc_altivec_lvxl:
19333 case Intrinsic::ppc_altivec_lvebx:
19334 case Intrinsic::ppc_altivec_lvehx:
19335 case Intrinsic::ppc_altivec_lvewx:
19336 case Intrinsic::ppc_vsx_lxvd2x:
19337 case Intrinsic::ppc_vsx_lxvw4x:
19338 case Intrinsic::ppc_vsx_lxvd2x_be:
19339 case Intrinsic::ppc_vsx_lxvw4x_be:
19340 case Intrinsic::ppc_vsx_lxvl:
19341 case Intrinsic::ppc_vsx_lxvll: {
19342 EVT VT;
19343 switch (Intrinsic) {
19344 case Intrinsic::ppc_altivec_lvebx:
19345 VT = MVT::i8;
19346 break;
19347 case Intrinsic::ppc_altivec_lvehx:
19348 VT = MVT::i16;
19349 break;
19350 case Intrinsic::ppc_altivec_lvewx:
19351 VT = MVT::i32;
19352 break;
19353 case Intrinsic::ppc_vsx_lxvd2x:
19354 case Intrinsic::ppc_vsx_lxvd2x_be:
19355 VT = MVT::v2f64;
19356 break;
19357 default:
19358 VT = MVT::v4i32;
19359 break;
19360 }
19361
19362 Info.opc = ISD::INTRINSIC_W_CHAIN;
19363 Info.memVT = VT;
19364 Info.ptrVal = I.getArgOperand(0);
19365 Info.offset = -VT.getStoreSize()+1;
19366 Info.size = 2*VT.getStoreSize()-1;
19367 Info.align = Align(1);
19368 Info.flags = MachineMemOperand::MOLoad;
19369 Infos.push_back(Info);
19370 return;
19371 }
19372 case Intrinsic::ppc_altivec_stvx:
19373 case Intrinsic::ppc_altivec_stvxl:
19374 case Intrinsic::ppc_altivec_stvebx:
19375 case Intrinsic::ppc_altivec_stvehx:
19376 case Intrinsic::ppc_altivec_stvewx:
19377 case Intrinsic::ppc_vsx_stxvd2x:
19378 case Intrinsic::ppc_vsx_stxvw4x:
19379 case Intrinsic::ppc_vsx_stxvd2x_be:
19380 case Intrinsic::ppc_vsx_stxvw4x_be:
19381 case Intrinsic::ppc_vsx_stxvl:
19382 case Intrinsic::ppc_vsx_stxvll: {
19383 EVT VT;
19384 switch (Intrinsic) {
19385 case Intrinsic::ppc_altivec_stvebx:
19386 VT = MVT::i8;
19387 break;
19388 case Intrinsic::ppc_altivec_stvehx:
19389 VT = MVT::i16;
19390 break;
19391 case Intrinsic::ppc_altivec_stvewx:
19392 VT = MVT::i32;
19393 break;
19394 case Intrinsic::ppc_vsx_stxvd2x:
19395 case Intrinsic::ppc_vsx_stxvd2x_be:
19396 VT = MVT::v2f64;
19397 break;
19398 default:
19399 VT = MVT::v4i32;
19400 break;
19401 }
19402
19403 Info.opc = ISD::INTRINSIC_VOID;
19404 Info.memVT = VT;
19405 Info.ptrVal = I.getArgOperand(1);
19406 Info.offset = -VT.getStoreSize()+1;
19407 Info.size = 2*VT.getStoreSize()-1;
19408 Info.align = Align(1);
19409 Info.flags = MachineMemOperand::MOStore;
19410 Infos.push_back(Info);
19411 return;
19412 }
19413 case Intrinsic::ppc_stdcx:
19414 case Intrinsic::ppc_stwcx:
19415 case Intrinsic::ppc_sthcx:
19416 case Intrinsic::ppc_stbcx: {
19417 EVT VT;
19418 auto Alignment = Align(8);
19419 switch (Intrinsic) {
19420 case Intrinsic::ppc_stdcx:
19421 VT = MVT::i64;
19422 break;
19423 case Intrinsic::ppc_stwcx:
19424 VT = MVT::i32;
19425 Alignment = Align(4);
19426 break;
19427 case Intrinsic::ppc_sthcx:
19428 VT = MVT::i16;
19429 Alignment = Align(2);
19430 break;
19431 case Intrinsic::ppc_stbcx:
19432 VT = MVT::i8;
19433 Alignment = Align(1);
19434 break;
19435 }
19436 Info.opc = ISD::INTRINSIC_W_CHAIN;
19437 Info.memVT = VT;
19438 Info.ptrVal = I.getArgOperand(0);
19439 Info.offset = 0;
19440 Info.align = Alignment;
19442 Infos.push_back(Info);
19443 return;
19444 }
19445 default:
19446 break;
19447 }
19448}
19449
19450/// It returns EVT::Other if the type should be determined using generic
19451/// target-independent logic.
19453 LLVMContext &Context, const MemOp &Op,
19454 const AttributeList &FuncAttributes) const {
19455 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None) {
19456 // We should use Altivec/VSX loads and stores when available. For unaligned
19457 // addresses, unaligned VSX loads are only fast starting with the P8.
19458 if (Subtarget.hasAltivec() && Op.size() >= 16) {
19459 if (Op.isMemset() && Subtarget.hasVSX()) {
19460 uint64_t TailSize = Op.size() % 16;
19461 // For memset lowering, EXTRACT_VECTOR_ELT tries to return constant
19462 // element if vector element type matches tail store. For tail size
19463 // 3/4, the tail store is i32, v4i32 cannot be used, need a legal one.
19464 if (TailSize > 2 && TailSize <= 4) {
19465 return MVT::v8i16;
19466 }
19467 return MVT::v4i32;
19468 }
19469 if (Op.isAligned(Align(16)) || Subtarget.hasP8Vector())
19470 return MVT::v4i32;
19471 }
19472 }
19473
19474 if (Subtarget.isPPC64()) {
19475 return MVT::i64;
19476 }
19477
19478 return MVT::i32;
19479}
19480
19481/// Returns true if it is beneficial to convert a load of a constant
19482/// to just the constant itself.
19484 Type *Ty) const {
19485 assert(Ty->isIntegerTy());
19486
19487 unsigned BitSize = Ty->getPrimitiveSizeInBits();
19488 return !(BitSize == 0 || BitSize > 64);
19489}
19490
19492 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19493 return false;
19494 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19495 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19496 return NumBits1 == 64 && NumBits2 == 32;
19497}
19498
19500 if (!VT1.isInteger() || !VT2.isInteger())
19501 return false;
19502 unsigned NumBits1 = VT1.getSizeInBits();
19503 unsigned NumBits2 = VT2.getSizeInBits();
19504 return NumBits1 == 64 && NumBits2 == 32;
19505}
19506
19508 // Generally speaking, zexts are not free, but they are free when they can be
19509 // folded with other operations.
19510 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
19511 EVT MemVT = LD->getMemoryVT();
19512 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
19513 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
19514 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
19515 LD->getExtensionType() == ISD::ZEXTLOAD))
19516 return true;
19517 }
19518
19519 // FIXME: Add other cases...
19520 // - 32-bit shifts with a zext to i64
19521 // - zext after ctlz, bswap, etc.
19522 // - zext after and by a constant mask
19523
19524 return TargetLowering::isZExtFree(Val, VT2);
19525}
19526
19527bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
19528 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
19529 "invalid fpext types");
19530 // Extending to float128 is not free.
19531 if (DestVT == MVT::f128)
19532 return false;
19533 return true;
19534}
19535
19537 return isInt<16>(Imm) || isUInt<16>(Imm);
19538}
19539
19541 return isInt<16>(Imm) || isUInt<16>(Imm);
19542}
19543
19546 unsigned *Fast) const {
19548 return false;
19549
19550 // PowerPC supports unaligned memory access for simple non-vector types.
19551 // Although accessing unaligned addresses is not as efficient as accessing
19552 // aligned addresses, it is generally more efficient than manual expansion,
19553 // and generally only traps for software emulation when crossing page
19554 // boundaries.
19555
19556 if (!VT.isSimple())
19557 return false;
19558
19559 if (VT.isFloatingPoint() && !VT.isVector() &&
19560 !Subtarget.allowsUnalignedFPAccess())
19561 return false;
19562
19563 if (VT.getSimpleVT().isVector()) {
19564 if (Subtarget.hasVSX()) {
19565 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
19566 VT != MVT::v4f32 && VT != MVT::v4i32)
19567 return false;
19568 } else {
19569 return false;
19570 }
19571 }
19572
19573 if (VT == MVT::ppcf128)
19574 return false;
19575
19576 if (Fast)
19577 *Fast = 1;
19578
19579 return true;
19580}
19581
19583 SDValue C) const {
19584 // Check integral scalar types.
19585 if (!VT.isScalarInteger())
19586 return false;
19587 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
19588 if (!ConstNode->getAPIntValue().isSignedIntN(64))
19589 return false;
19590 // This transformation will generate >= 2 operations. But the following
19591 // cases will generate <= 2 instructions during ISEL. So exclude them.
19592 // 1. If the constant multiplier fits 16 bits, it can be handled by one
19593 // HW instruction, ie. MULLI
19594 // 2. If the multiplier after shifted fits 16 bits, an extra shift
19595 // instruction is needed than case 1, ie. MULLI and RLDICR
19596 int64_t Imm = ConstNode->getSExtValue();
19597 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
19598 Imm >>= Shift;
19599 if (isInt<16>(Imm))
19600 return false;
19601 uint64_t UImm = static_cast<uint64_t>(Imm);
19602 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
19603 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
19604 return true;
19605 }
19606 return false;
19607}
19608
19614
19616 Type *Ty) const {
19617 if (Subtarget.hasSPE() || Subtarget.useSoftFloat())
19618 return false;
19619 switch (Ty->getScalarType()->getTypeID()) {
19620 case Type::FloatTyID:
19621 case Type::DoubleTyID:
19622 return true;
19623 case Type::FP128TyID:
19624 return Subtarget.hasP9Vector();
19625 default:
19626 return false;
19627 }
19628}
19629
19630// FIXME: add more patterns which are not profitable to hoist.
19632 if (!I->hasOneUse())
19633 return true;
19634
19635 Instruction *User = I->user_back();
19636 assert(User && "A single use instruction with no uses.");
19637
19638 switch (I->getOpcode()) {
19639 case Instruction::FMul: {
19640 // Don't break FMA, PowerPC prefers FMA.
19641 if (User->getOpcode() != Instruction::FSub &&
19642 User->getOpcode() != Instruction::FAdd)
19643 return true;
19644
19646 const Function *F = I->getFunction();
19647 const DataLayout &DL = F->getDataLayout();
19648 Type *Ty = User->getOperand(0)->getType();
19649 bool AllowContract = I->getFastMathFlags().allowContract() &&
19650 User->getFastMathFlags().allowContract();
19651
19652 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
19654 (AllowContract || Options.AllowFPOpFusion == FPOpFusion::Fast));
19655 }
19656 case Instruction::Load: {
19657 // Don't break "store (load float*)" pattern, this pattern will be combined
19658 // to "store (load int32)" in later InstCombine pass. See function
19659 // combineLoadToOperationType. On PowerPC, loading a float point takes more
19660 // cycles than loading a 32 bit integer.
19661 LoadInst *LI = cast<LoadInst>(I);
19662 // For the loads that combineLoadToOperationType does nothing, like
19663 // ordered load, it should be profitable to hoist them.
19664 // For swifterror load, it can only be used for pointer to pointer type, so
19665 // later type check should get rid of this case.
19666 if (!LI->isUnordered())
19667 return true;
19668
19669 if (User->getOpcode() != Instruction::Store)
19670 return true;
19671
19672 if (I->getType()->getTypeID() != Type::FloatTyID)
19673 return true;
19674
19675 return false;
19676 }
19677 default:
19678 return true;
19679 }
19680 return true;
19681}
19682
19683const MCPhysReg *
19685 // LR is a callee-save register, but we must treat it as clobbered by any call
19686 // site. Hence we include LR in the scratch registers, which are in turn added
19687 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
19688 // to CTR, which is used by any indirect call.
19689 static const MCPhysReg ScratchRegs[] = {
19690 PPC::X12, PPC::LR8, PPC::CTR8, 0
19691 };
19692
19693 return ScratchRegs;
19694}
19695
19697 const Constant *PersonalityFn) const {
19698 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
19699}
19700
19702 const Constant *PersonalityFn) const {
19703 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
19704}
19705
19706bool
19708 EVT VT , unsigned DefinedValues) const {
19709 if (VT == MVT::v2i64)
19710 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
19711
19712 if (Subtarget.hasVSX())
19713 return true;
19714
19716}
19717
19719 if (DisableILPPref || Subtarget.enableMachineScheduler())
19721
19722 return Sched::ILP;
19723}
19724
19725// Create a fast isel object.
19727 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo,
19728 const LibcallLoweringInfo *LibcallLowering) const {
19729 return PPC::createFastISel(FuncInfo, LibInfo, LibcallLowering);
19730}
19731
19732// 'Inverted' means the FMA opcode after negating one multiplicand.
19733// For example, (fma -a b c) = (fnmsub a b c)
19734static unsigned invertFMAOpcode(unsigned Opc) {
19735 switch (Opc) {
19736 default:
19737 llvm_unreachable("Invalid FMA opcode for PowerPC!");
19738 case ISD::FMA:
19739 return PPCISD::FNMSUB;
19740 case PPCISD::FNMSUB:
19741 return ISD::FMA;
19742 }
19743}
19744
19746 bool LegalOps, bool OptForSize,
19748 unsigned Depth) const {
19750 return SDValue();
19751
19752 unsigned Opc = Op.getOpcode();
19753 EVT VT = Op.getValueType();
19754 SDNodeFlags Flags = Op.getNode()->getFlags();
19755
19756 switch (Opc) {
19757 case PPCISD::FNMSUB:
19758 if (!Op.hasOneUse() || !isTypeLegal(VT))
19759 break;
19760
19761 SDValue N0 = Op.getOperand(0);
19762 SDValue N1 = Op.getOperand(1);
19763 SDValue N2 = Op.getOperand(2);
19764 SDLoc Loc(Op);
19765
19767 SDValue NegN2 =
19768 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
19769
19770 if (!NegN2)
19771 return SDValue();
19772
19773 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
19774 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
19775 // These transformations may change sign of zeroes. For example,
19776 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
19777 if (Flags.hasNoSignedZeros()) {
19778 // Try and choose the cheaper one to negate.
19780 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
19781 N0Cost, Depth + 1);
19782
19784 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
19785 N1Cost, Depth + 1);
19786
19787 if (NegN0 && N0Cost <= N1Cost) {
19788 Cost = std::min(N0Cost, N2Cost);
19789 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
19790 } else if (NegN1) {
19791 Cost = std::min(N1Cost, N2Cost);
19792 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
19793 }
19794 }
19795
19796 // (fneg (fnmsub a b c)) => (fma a b (fneg c))
19797 if (isOperationLegal(ISD::FMA, VT)) {
19798 Cost = N2Cost;
19799 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
19800 }
19801
19802 break;
19803 }
19804
19805 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
19806 Cost, Depth);
19807}
19808
19809// Override to enable LOAD_STACK_GUARD lowering on Linux.
19811 if (M.getStackProtectorGuard() == "tls" || Subtarget.isTargetLinux())
19812 return true;
19814}
19815
19817 bool ForCodeSize) const {
19818 if (!VT.isSimple() || !Subtarget.hasVSX())
19819 return false;
19820
19821 switch(VT.getSimpleVT().SimpleTy) {
19822 default:
19823 // For FP types that are currently not supported by PPC backend, return
19824 // false. Examples: f16, f80.
19825 return false;
19826 case MVT::f32:
19827 case MVT::f64: {
19828 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
19829 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
19830 return true;
19831 }
19832 bool IsExact;
19833 APSInt IntResult(16, false);
19834 // The rounding mode doesn't really matter because we only care about floats
19835 // that can be converted to integers exactly.
19836 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
19837 // For exact values in the range [-16, 15] we can materialize the float.
19838 if (IsExact && IntResult <= 15 && IntResult >= -16)
19839 return true;
19840 return Imm.isZero();
19841 }
19842 case MVT::ppcf128:
19843 return Imm.isPosZero();
19844 }
19845}
19846
19847// For vector shift operation op, fold
19848// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
19850 SelectionDAG &DAG) {
19851 SDValue N0 = N->getOperand(0);
19852 SDValue N1 = N->getOperand(1);
19853 EVT VT = N0.getValueType();
19854 unsigned OpSizeInBits = VT.getScalarSizeInBits();
19855 unsigned Opcode = N->getOpcode();
19856 unsigned TargetOpcode;
19857
19858 switch (Opcode) {
19859 default:
19860 llvm_unreachable("Unexpected shift operation");
19861 case ISD::SHL:
19862 TargetOpcode = PPCISD::SHL;
19863 break;
19864 case ISD::SRL:
19865 TargetOpcode = PPCISD::SRL;
19866 break;
19867 case ISD::SRA:
19868 TargetOpcode = PPCISD::SRA;
19869 break;
19870 }
19871
19872 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
19873 N1->getOpcode() == ISD::AND)
19874 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
19875 if (Mask->getZExtValue() == OpSizeInBits - 1)
19876 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
19877
19878 return SDValue();
19879}
19880
19881SDValue PPCTargetLowering::combineVectorShift(SDNode *N,
19882 DAGCombinerInfo &DCI) const {
19883 EVT VT = N->getValueType(0);
19884 assert(VT.isVector() && "Vector type expected.");
19885
19886 unsigned Opc = N->getOpcode();
19887 assert((Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
19888 "Unexpected opcode.");
19889
19890 if (!isOperationLegal(Opc, VT))
19891 return SDValue();
19892
19893 EVT EltTy = VT.getScalarType();
19894 unsigned EltBits = EltTy.getSizeInBits();
19895 if (EltTy != MVT::i64 && EltTy != MVT::i32)
19896 return SDValue();
19897
19898 SDValue N1 = N->getOperand(1);
19899 uint64_t SplatBits = 0;
19900 bool AddSplatCase = false;
19901 unsigned OpcN1 = N1.getOpcode();
19902 if (OpcN1 == PPCISD::VADD_SPLAT &&
19904 AddSplatCase = true;
19905 SplatBits = N1.getConstantOperandVal(0);
19906 }
19907
19908 if (!AddSplatCase) {
19909 if (OpcN1 != ISD::BUILD_VECTOR)
19910 return SDValue();
19911
19912 unsigned SplatBitSize;
19913 bool HasAnyUndefs;
19914 APInt APSplatBits, APSplatUndef;
19915 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(N1);
19916 bool BVNIsConstantSplat =
19917 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
19918 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
19919 if (!BVNIsConstantSplat || SplatBitSize != EltBits)
19920 return SDValue();
19921 SplatBits = APSplatBits.getZExtValue();
19922 }
19923
19924 SDLoc DL(N);
19925 SDValue N0 = N->getOperand(0);
19926 // PPC vector shifts by word/double look at only the low 5/6 bits of the
19927 // shift vector, which means the max value is 31/63. A shift vector of all
19928 // 1s will be truncated to 31/63, which is useful as vspltiw is limited to
19929 // -16 to 15 range.
19930 if (SplatBits == (EltBits - 1)) {
19931 unsigned NewOpc;
19932 switch (Opc) {
19933 case ISD::SHL:
19934 NewOpc = PPCISD::SHL;
19935 break;
19936 case ISD::SRL:
19937 NewOpc = PPCISD::SRL;
19938 break;
19939 case ISD::SRA:
19940 NewOpc = PPCISD::SRA;
19941 break;
19942 }
19943 SDValue SplatOnes = getCanonicalConstSplat(255, 1, VT, DCI.DAG, DL);
19944 return DCI.DAG.getNode(NewOpc, DL, VT, N0, SplatOnes);
19945 }
19946
19947 if (Opc != ISD::SHL || !isOperationLegal(ISD::ADD, VT))
19948 return SDValue();
19949
19950 // For 64-bit there is no splat immediate so we want to catch shift by 1 here
19951 // before the BUILD_VECTOR is replaced by a load.
19952 if (EltTy != MVT::i64 || SplatBits != 1)
19953 return SDValue();
19954
19955 return DCI.DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19956}
19957
19958SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
19959 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
19960 return Value;
19961
19962 if (N->getValueType(0).isVector())
19963 return combineVectorShift(N, DCI);
19964
19965 SDValue N0 = N->getOperand(0);
19966 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
19967 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
19968 N0.getOpcode() != ISD::SIGN_EXTEND ||
19969 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
19970 N->getValueType(0) != MVT::i64)
19971 return SDValue();
19972
19973 // We can't save an operation here if the value is already extended, and
19974 // the existing shift is easier to combine.
19975 SDValue ExtsSrc = N0.getOperand(0);
19976 if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
19977 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
19978 return SDValue();
19979
19980 SDLoc DL(N0);
19981 SDValue ShiftBy = SDValue(CN1, 0);
19982 // We want the shift amount to be i32 on the extswli, but the shift could
19983 // have an i64.
19984 if (ShiftBy.getValueType() == MVT::i64)
19985 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
19986
19987 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
19988 ShiftBy);
19989}
19990
19991SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
19992 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
19993 return Value;
19994
19995 if (N->getValueType(0).isVector())
19996 return combineVectorShift(N, DCI);
19997
19998 return SDValue();
19999}
20000
20001SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
20002 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
20003 return Value;
20004
20005 if (N->getValueType(0).isVector())
20006 return combineVectorShift(N, DCI);
20007
20008 return SDValue();
20009}
20010
20011// Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
20012// Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
20013// When C is zero, the equation (addi Z, -C) can be simplified to Z
20014// Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
20016 const PPCSubtarget &Subtarget) {
20017 if (!Subtarget.isPPC64())
20018 return SDValue();
20019
20020 SDValue LHS = N->getOperand(0);
20021 SDValue RHS = N->getOperand(1);
20022
20023 auto isZextOfCompareWithConstant = [](SDValue Op) {
20024 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
20025 Op.getValueType() != MVT::i64)
20026 return false;
20027
20028 SDValue Cmp = Op.getOperand(0);
20029 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
20030 Cmp.getOperand(0).getValueType() != MVT::i64)
20031 return false;
20032
20033 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
20034 int64_t NegConstant = 0 - Constant->getSExtValue();
20035 // Due to the limitations of the addi instruction,
20036 // -C is required to be [-32768, 32767].
20037 return isInt<16>(NegConstant);
20038 }
20039
20040 return false;
20041 };
20042
20043 bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
20044 bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
20045
20046 // If there is a pattern, canonicalize a zext operand to the RHS.
20047 if (LHSHasPattern && !RHSHasPattern)
20048 std::swap(LHS, RHS);
20049 else if (!LHSHasPattern && !RHSHasPattern)
20050 return SDValue();
20051
20052 SDLoc DL(N);
20053 EVT CarryType = Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
20054 SDVTList VTs = DAG.getVTList(MVT::i64, CarryType);
20055 SDValue Cmp = RHS.getOperand(0);
20056 SDValue Z = Cmp.getOperand(0);
20057 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
20058 int64_t NegConstant = 0 - Constant->getSExtValue();
20059
20060 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
20061 default: break;
20062 case ISD::SETNE: {
20063 // when C == 0
20064 // --> addze X, (addic Z, -1).carry
20065 // /
20066 // add X, (zext(setne Z, C))--
20067 // \ when -32768 <= -C <= 32767 && C != 0
20068 // --> addze X, (addic (addi Z, -C), -1).carry
20069 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20070 DAG.getConstant(NegConstant, DL, MVT::i64));
20071 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20072 SDValue Addc =
20073 DAG.getNode(ISD::UADDO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20074 AddOrZ, DAG.getAllOnesConstant(DL, MVT::i64),
20075 DAG.getConstant(0, DL, CarryType));
20076 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20077 DAG.getConstant(0, DL, MVT::i64),
20078 SDValue(Addc.getNode(), 1));
20079 }
20080 case ISD::SETEQ: {
20081 // when C == 0
20082 // --> addze X, (subfic Z, 0).carry
20083 // /
20084 // add X, (zext(sete Z, C))--
20085 // \ when -32768 <= -C <= 32767 && C != 0
20086 // --> addze X, (subfic (addi Z, -C), 0).carry
20087 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20088 DAG.getConstant(NegConstant, DL, MVT::i64));
20089 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20090 SDValue Subc =
20091 DAG.getNode(ISD::USUBO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20092 DAG.getConstant(0, DL, MVT::i64), AddOrZ,
20093 DAG.getConstant(0, DL, CarryType));
20094 SDValue Invert = DAG.getNode(ISD::XOR, DL, CarryType, Subc.getValue(1),
20095 DAG.getConstant(1UL, DL, CarryType));
20096 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20097 DAG.getConstant(0, DL, MVT::i64), Invert);
20098 }
20099 }
20100
20101 return SDValue();
20102}
20103
20104// Transform
20105// (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
20106// (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
20107// In this case both C1 and C2 must be known constants.
20108// C1+C2 must fit into a 34 bit signed integer.
20110 const PPCSubtarget &Subtarget) {
20111 if (!Subtarget.isUsingPCRelativeCalls())
20112 return SDValue();
20113
20114 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
20115 // If we find that node try to cast the Global Address and the Constant.
20116 SDValue LHS = N->getOperand(0);
20117 SDValue RHS = N->getOperand(1);
20118
20119 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20120 std::swap(LHS, RHS);
20121
20122 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20123 return SDValue();
20124
20125 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
20128
20129 // Check that both casts succeeded.
20130 if (!GSDN || !ConstNode)
20131 return SDValue();
20132
20133 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
20134 SDLoc DL(GSDN);
20135
20136 // The signed int offset needs to fit in 34 bits.
20137 if (!isInt<34>(NewOffset))
20138 return SDValue();
20139
20140 // The new global address is a copy of the old global address except
20141 // that it has the updated Offset.
20142 SDValue GA =
20143 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
20144 NewOffset, GSDN->getTargetFlags());
20145 SDValue MatPCRel =
20146 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
20147 return MatPCRel;
20148}
20149
20150// Transform (add X, (build_vector (T 1), (T 1), ...)) -> (sub X, (XXLEQVOnes))
20151// XXLEQVOnes creates an all-1s vector (0xFFFFFFFF...) efficiently via xxleqv
20152// Mathematical identity: X + 1 = X - (-1)
20153// Applies to v4i32, v2i64, v8i16, v16i8 where all elements are constant 1
20154// Requirement: VSX feature for efficient xxleqv generation
20156 const PPCSubtarget &Subtarget) {
20157
20158 EVT VT = N->getValueType(0);
20159 if (!Subtarget.hasVSX())
20160 return SDValue();
20161
20162 // Handle v2i64, v4i32, v8i16 and v16i8 types
20163 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
20164 VT == MVT::v2i64))
20165 return SDValue();
20166
20167 SDValue LHS = N->getOperand(0);
20168 SDValue RHS = N->getOperand(1);
20169
20170 // Check if RHS is BUILD_VECTOR
20171 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
20172 return SDValue();
20173
20174 // Check if all the elements are 1
20175 unsigned NumOfEles = RHS.getNumOperands();
20176 for (unsigned i = 0; i < NumOfEles; ++i) {
20177 auto *CN = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
20178 if (!CN || CN->getSExtValue() != 1)
20179 return SDValue();
20180 }
20181 SDLoc DL(N);
20182
20183 SDValue MinusOne = DAG.getConstant(APInt::getAllOnes(32), DL, MVT::i32);
20184 SmallVector<SDValue, 4> Ops(4, MinusOne);
20185 SDValue AllOnesVec = DAG.getBuildVector(MVT::v4i32, DL, Ops);
20186
20187 // Bitcast to the target vector type
20188 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT, AllOnesVec);
20189
20190 return DAG.getNode(ISD::SUB, DL, VT, LHS, Bitcast);
20191}
20192
20193SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
20194 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
20195 return Value;
20196
20197 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
20198 return Value;
20199
20200 if (auto Value = combineADDToSUB(N, DCI.DAG, Subtarget))
20201 return Value;
20202 return SDValue();
20203}
20204
20205// Detect TRUNCATE operations on bitcasts of float128 values.
20206// What we are looking for here is the situtation where we extract a subset
20207// of bits from a 128 bit float.
20208// This can be of two forms:
20209// 1) BITCAST of f128 feeding TRUNCATE
20210// 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
20211// The reason this is required is because we do not have a legal i128 type
20212// and so we want to prevent having to store the f128 and then reload part
20213// of it.
20214SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
20215 DAGCombinerInfo &DCI) const {
20216 // If we are using CRBits then try that first.
20217 if (Subtarget.useCRBits()) {
20218 // Check if CRBits did anything and return that if it did.
20219 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
20220 return CRTruncValue;
20221 }
20222
20223 SDLoc dl(N);
20224 SDValue Op0 = N->getOperand(0);
20225
20226 // Looking for a truncate of i128 to i64.
20227 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
20228 return SDValue();
20229
20230 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
20231
20232 // SRL feeding TRUNCATE.
20233 if (Op0.getOpcode() == ISD::SRL) {
20234 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
20235 // The right shift has to be by 64 bits.
20236 if (!ConstNode || ConstNode->getZExtValue() != 64)
20237 return SDValue();
20238
20239 // Switch the element number to extract.
20240 EltToExtract = EltToExtract ? 0 : 1;
20241 // Update Op0 past the SRL.
20242 Op0 = Op0.getOperand(0);
20243 }
20244
20245 // BITCAST feeding a TRUNCATE possibly via SRL.
20246 if (Op0.getOpcode() == ISD::BITCAST &&
20247 Op0.getValueType() == MVT::i128 &&
20248 Op0.getOperand(0).getValueType() == MVT::f128) {
20249 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
20250 return DCI.DAG.getNode(
20251 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
20252 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
20253 }
20254 return SDValue();
20255}
20256
20257SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
20258 SelectionDAG &DAG = DCI.DAG;
20259
20260 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
20261 if (!ConstOpOrElement)
20262 return SDValue();
20263
20264 // An imul is usually smaller than the alternative sequence for legal type.
20266 isOperationLegal(ISD::MUL, N->getValueType(0)))
20267 return SDValue();
20268
20269 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
20270 switch (this->Subtarget.getCPUDirective()) {
20271 default:
20272 // TODO: enhance the condition for subtarget before pwr8
20273 return false;
20274 case PPC::DIR_PWR8:
20275 // type mul add shl
20276 // scalar 4 1 1
20277 // vector 7 2 2
20278 return true;
20279 case PPC::DIR_PWR9:
20280 case PPC::DIR_PWR10:
20281 case PPC::DIR_PWR11:
20283 // type mul add shl
20284 // scalar 5 2 2
20285 // vector 7 2 2
20286
20287 // The cycle RATIO of related operations are showed as a table above.
20288 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
20289 // scalar and vector type. For 2 instrs patterns, add/sub + shl
20290 // are 4, it is always profitable; but for 3 instrs patterns
20291 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
20292 // So we should only do it for vector type.
20293 return IsAddOne && IsNeg ? VT.isVector() : true;
20294 }
20295 };
20296
20297 EVT VT = N->getValueType(0);
20298 SDLoc DL(N);
20299
20300 const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
20301 bool IsNeg = MulAmt.isNegative();
20302 APInt MulAmtAbs = MulAmt.abs();
20303
20304 if ((MulAmtAbs - 1).isPowerOf2()) {
20305 // (mul x, 2^N + 1) => (add (shl x, N), x)
20306 // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
20307
20308 if (!IsProfitable(IsNeg, true, VT))
20309 return SDValue();
20310
20311 SDValue Op0 = N->getOperand(0);
20312 SDValue Op1 =
20313 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20314 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
20315 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
20316
20317 if (!IsNeg)
20318 return Res;
20319
20320 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
20321 } else if ((MulAmtAbs + 1).isPowerOf2()) {
20322 // (mul x, 2^N - 1) => (sub (shl x, N), x)
20323 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
20324
20325 if (!IsProfitable(IsNeg, false, VT))
20326 return SDValue();
20327
20328 SDValue Op0 = N->getOperand(0);
20329 SDValue Op1 =
20330 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20331 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
20332
20333 if (!IsNeg)
20334 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
20335 else
20336 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
20337
20338 } else {
20339 return SDValue();
20340 }
20341}
20342
20343// Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
20344// in combiner since we need to check SD flags and other subtarget features.
20345SDValue PPCTargetLowering::combineFMALike(SDNode *N,
20346 DAGCombinerInfo &DCI) const {
20347 SDValue N0 = N->getOperand(0);
20348 SDValue N1 = N->getOperand(1);
20349 SDValue N2 = N->getOperand(2);
20350 SDNodeFlags Flags = N->getFlags();
20351 EVT VT = N->getValueType(0);
20352 SelectionDAG &DAG = DCI.DAG;
20353 unsigned Opc = N->getOpcode();
20355 bool LegalOps = !DCI.isBeforeLegalizeOps();
20356 SDLoc Loc(N);
20357
20358 if (!isOperationLegal(ISD::FMA, VT))
20359 return SDValue();
20360
20361 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
20362 // since (fnmsub a b c)=-0 while c-ab=+0.
20363 if (!Flags.hasNoSignedZeros())
20364 return SDValue();
20365
20366 // (fma (fneg a) b c) => (fnmsub a b c)
20367 // (fnmsub (fneg a) b c) => (fma a b c)
20368 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
20369 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
20370
20371 // (fma a (fneg b) c) => (fnmsub a b c)
20372 // (fnmsub a (fneg b) c) => (fma a b c)
20373 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
20374 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
20375
20376 return SDValue();
20377}
20378
20379bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
20380 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
20381 if (!Subtarget.is64BitELFABI())
20382 return false;
20383
20384 // If not a tail call then no need to proceed.
20385 if (!CI->isTailCall())
20386 return false;
20387
20388 // If sibling calls have been disabled and tail-calls aren't guaranteed
20389 // there is no reason to duplicate.
20390 auto &TM = getTargetMachine();
20391 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
20392 return false;
20393
20394 // Can't tail call a function called indirectly, or if it has variadic args.
20395 const Function *Callee = CI->getCalledFunction();
20396 if (!Callee || Callee->isVarArg())
20397 return false;
20398
20399 // Make sure the callee and caller calling conventions are eligible for tco.
20400 const Function *Caller = CI->getParent()->getParent();
20401 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
20402 CI->getCallingConv()))
20403 return false;
20404
20405 // If the function is local then we have a good chance at tail-calling it
20406 return getTargetMachine().shouldAssumeDSOLocal(Callee);
20407}
20408
20409bool PPCTargetLowering::
20410isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
20411 const Value *Mask = AndI.getOperand(1);
20412 // If the mask is suitable for andi. or andis. we should sink the and.
20413 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
20414 // Can't handle constants wider than 64-bits.
20415 if (CI->getBitWidth() > 64)
20416 return false;
20417 int64_t ConstVal = CI->getZExtValue();
20418 return isUInt<16>(ConstVal) ||
20419 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
20420 }
20421
20422 // For non-constant masks, we can always use the record-form and.
20423 return true;
20424}
20425
20426/// getAddrModeForFlags - Based on the set of address flags, select the most
20427/// optimal instruction format to match by.
20428PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
20429 // This is not a node we should be handling here.
20430 if (Flags == PPC::MOF_None)
20431 return PPC::AM_None;
20432 // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
20433 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
20434 if ((Flags & FlagSet) == FlagSet)
20435 return PPC::AM_DForm;
20436 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
20437 if ((Flags & FlagSet) == FlagSet)
20438 return PPC::AM_DSForm;
20439 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
20440 if ((Flags & FlagSet) == FlagSet)
20441 return PPC::AM_DQForm;
20442 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
20443 if ((Flags & FlagSet) == FlagSet)
20444 return PPC::AM_PrefixDForm;
20445 // If no other forms are selected, return an X-Form as it is the most
20446 // general addressing mode.
20447 return PPC::AM_XForm;
20448}
20449
20450/// Set alignment flags based on whether or not the Frame Index is aligned.
20451/// Utilized when computing flags for address computation when selecting
20452/// load and store instructions.
20453static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
20454 SelectionDAG &DAG) {
20455 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
20456 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
20457 if (!FI)
20458 return;
20460 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
20461 // If this is (add $FI, $S16Imm), the alignment flags are already set
20462 // based on the immediate. We just need to clear the alignment flags
20463 // if the FI alignment is weaker.
20464 if ((FrameIndexAlign % 4) != 0)
20465 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
20466 if ((FrameIndexAlign % 16) != 0)
20467 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
20468 // If the address is a plain FrameIndex, set alignment flags based on
20469 // FI alignment.
20470 if (!IsAdd) {
20471 if ((FrameIndexAlign % 4) == 0)
20472 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20473 if ((FrameIndexAlign % 16) == 0)
20474 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20475 }
20476}
20477
20478/// Given a node, compute flags that are used for address computation when
20479/// selecting load and store instructions. The flags computed are stored in
20480/// FlagSet. This function takes into account whether the node is a constant,
20481/// an ADD, OR, or a constant, and computes the address flags accordingly.
20482static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
20483 SelectionDAG &DAG) {
20484 // Set the alignment flags for the node depending on if the node is
20485 // 4-byte or 16-byte aligned.
20486 auto SetAlignFlagsForImm = [&](uint64_t Imm) {
20487 if ((Imm & 0x3) == 0)
20488 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20489 if ((Imm & 0xf) == 0)
20490 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20491 };
20492
20494 // All 32-bit constants can be computed as LIS + Disp.
20495 const APInt &ConstImm = CN->getAPIntValue();
20496 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
20497 FlagSet |= PPC::MOF_AddrIsSImm32;
20498 SetAlignFlagsForImm(ConstImm.getZExtValue());
20499 setAlignFlagsForFI(N, FlagSet, DAG);
20500 }
20501 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
20502 FlagSet |= PPC::MOF_RPlusSImm34;
20503 else // Let constant materialization handle large constants.
20504 FlagSet |= PPC::MOF_NotAddNorCst;
20505 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
20506 // This address can be represented as an addition of:
20507 // - Register + Imm16 (possibly a multiple of 4/16)
20508 // - Register + Imm34
20509 // - Register + PPCISD::Lo
20510 // - Register + Register
20511 // In any case, we won't have to match this as Base + Zero.
20512 SDValue RHS = N.getOperand(1);
20514 const APInt &ConstImm = CN->getAPIntValue();
20515 if (ConstImm.isSignedIntN(16)) {
20516 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
20517 SetAlignFlagsForImm(ConstImm.getZExtValue());
20518 setAlignFlagsForFI(N, FlagSet, DAG);
20519 }
20520 if (ConstImm.isSignedIntN(34))
20521 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
20522 else
20523 FlagSet |= PPC::MOF_RPlusR; // Register.
20524 } else if (RHS.getOpcode() == PPCISD::Lo && !RHS.getConstantOperandVal(1))
20525 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
20526 else
20527 FlagSet |= PPC::MOF_RPlusR;
20528 } else { // The address computation is not a constant or an addition.
20529 setAlignFlagsForFI(N, FlagSet, DAG);
20530 FlagSet |= PPC::MOF_NotAddNorCst;
20531 }
20532}
20533
20534static bool isPCRelNode(SDValue N) {
20535 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
20540}
20541
20542/// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
20543/// the address flags of the load/store instruction that is to be matched.
20544unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
20545 SelectionDAG &DAG) const {
20546 unsigned FlagSet = PPC::MOF_None;
20547
20548 // Compute subtarget flags.
20549 if (!Subtarget.hasP9Vector())
20550 FlagSet |= PPC::MOF_SubtargetBeforeP9;
20551 else
20552 FlagSet |= PPC::MOF_SubtargetP9;
20553
20554 if (Subtarget.hasPrefixInstrs())
20555 FlagSet |= PPC::MOF_SubtargetP10;
20556
20557 if (Subtarget.hasSPE())
20558 FlagSet |= PPC::MOF_SubtargetSPE;
20559
20560 // Check if we have a PCRel node and return early.
20561 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
20562 return FlagSet;
20563
20564 // If the node is the paired load/store intrinsics, compute flags for
20565 // address computation and return early.
20566 unsigned ParentOp = Parent->getOpcode();
20567 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
20568 (ParentOp == ISD::INTRINSIC_VOID))) {
20569 unsigned ID = Parent->getConstantOperandVal(1);
20570 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
20571 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
20572 ? Parent->getOperand(2)
20573 : Parent->getOperand(3);
20574 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
20575 FlagSet |= PPC::MOF_Vector;
20576 return FlagSet;
20577 }
20578 }
20579
20580 // Mark this as something we don't want to handle here if it is atomic
20581 // or pre-increment instruction.
20582 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
20583 if (LSB->isIndexed())
20584 return PPC::MOF_None;
20585
20586 // Compute in-memory type flags. This is based on if there are scalars,
20587 // floats or vectors.
20588 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
20589 assert(MN && "Parent should be a MemSDNode!");
20590 EVT MemVT = MN->getMemoryVT();
20591 unsigned Size = MemVT.getSizeInBits();
20592 if (MemVT.isScalarInteger()) {
20593 assert(Size <= 128 &&
20594 "Not expecting scalar integers larger than 16 bytes!");
20595 if (Size < 32)
20596 FlagSet |= PPC::MOF_SubWordInt;
20597 else if (Size == 32)
20598 FlagSet |= PPC::MOF_WordInt;
20599 else
20600 FlagSet |= PPC::MOF_DoubleWordInt;
20601 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
20602 if (Size == 128)
20603 FlagSet |= PPC::MOF_Vector;
20604 else if (Size == 256) {
20605 assert(Subtarget.pairedVectorMemops() &&
20606 "256-bit vectors are only available when paired vector memops is "
20607 "enabled!");
20608 FlagSet |= PPC::MOF_Vector;
20609 } else
20610 llvm_unreachable("Not expecting illegal vectors!");
20611 } else { // Floating point type: can be scalar, f128 or vector types.
20612 if (Size == 32 || Size == 64)
20613 FlagSet |= PPC::MOF_ScalarFloat;
20614 else if (MemVT == MVT::f128 || MemVT.isVector())
20615 FlagSet |= PPC::MOF_Vector;
20616 else
20617 llvm_unreachable("Not expecting illegal scalar floats!");
20618 }
20619
20620 // Compute flags for address computation.
20621 computeFlagsForAddressComputation(N, FlagSet, DAG);
20622
20623 // Compute type extension flags.
20624 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
20625 switch (LN->getExtensionType()) {
20626 case ISD::SEXTLOAD:
20627 FlagSet |= PPC::MOF_SExt;
20628 break;
20629 case ISD::EXTLOAD:
20630 case ISD::ZEXTLOAD:
20631 FlagSet |= PPC::MOF_ZExt;
20632 break;
20633 case ISD::NON_EXTLOAD:
20634 FlagSet |= PPC::MOF_NoExt;
20635 break;
20636 }
20637 } else
20638 FlagSet |= PPC::MOF_NoExt;
20639
20640 // For integers, no extension is the same as zero extension.
20641 // We set the extension mode to zero extension so we don't have
20642 // to add separate entries in AddrModesMap for loads and stores.
20643 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
20644 FlagSet |= PPC::MOF_ZExt;
20645 FlagSet &= ~PPC::MOF_NoExt;
20646 }
20647
20648 // If we don't have prefixed instructions, 34-bit constants should be
20649 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
20650 bool IsNonP1034BitConst =
20652 FlagSet) == PPC::MOF_RPlusSImm34;
20653 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
20654 IsNonP1034BitConst)
20655 FlagSet |= PPC::MOF_NotAddNorCst;
20656
20657 return FlagSet;
20658}
20659
20660/// SelectForceXFormMode - Given the specified address, force it to be
20661/// represented as an indexed [r+r] operation (an XForm instruction).
20663 SDValue &Base,
20664 SelectionDAG &DAG) const {
20665
20667 int16_t ForceXFormImm = 0;
20668 if (provablyDisjointOr(DAG, N) &&
20669 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
20670 Disp = N.getOperand(0);
20671 Base = N.getOperand(1);
20672 return Mode;
20673 }
20674
20675 // If the address is the result of an add, we will utilize the fact that the
20676 // address calculation includes an implicit add. However, we can reduce
20677 // register pressure if we do not materialize a constant just for use as the
20678 // index register. We only get rid of the add if it is not an add of a
20679 // value and a 16-bit signed constant and both have a single use.
20680 if (N.getOpcode() == ISD::ADD &&
20681 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
20682 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
20683 Disp = N.getOperand(0);
20684 Base = N.getOperand(1);
20685 return Mode;
20686 }
20687
20688 // Otherwise, use R0 as the base register.
20689 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20690 N.getValueType());
20691 Base = N;
20692
20693 return Mode;
20694}
20695
20697 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
20698 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
20699 EVT ValVT = Val.getValueType();
20700 // If we are splitting a scalar integer into f64 parts (i.e. so they
20701 // can be placed into VFRC registers), we need to zero extend and
20702 // bitcast the values. This will ensure the value is placed into a
20703 // VSR using direct moves or stack operations as needed.
20704 if (PartVT == MVT::f64 &&
20705 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
20706 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
20707 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
20708 Parts[0] = Val;
20709 return true;
20710 }
20711 return false;
20712}
20713
20714SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
20715 SelectionDAG &DAG) const {
20716 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20718 EVT RetVT = Op.getValueType();
20719 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
20720 SDValue Callee =
20721 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
20722 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetTy, false);
20724 for (const SDValue &N : Op->op_values()) {
20725 EVT ArgVT = N.getValueType();
20726 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
20727 TargetLowering::ArgListEntry Entry(N, ArgTy);
20728 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, SignExtend);
20729 Entry.IsZExt = !Entry.IsSExt;
20730 Args.push_back(Entry);
20731 }
20732
20733 SDValue InChain = DAG.getEntryNode();
20734 SDValue TCChain = InChain;
20735 const Function &F = DAG.getMachineFunction().getFunction();
20736 bool isTailCall =
20737 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
20738 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
20739 if (isTailCall)
20740 InChain = TCChain;
20741 CLI.setDebugLoc(SDLoc(Op))
20742 .setChain(InChain)
20743 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
20744 .setTailCall(isTailCall)
20745 .setSExtResult(SignExtend)
20746 .setZExtResult(!SignExtend)
20748 return TLI.LowerCallTo(CLI).first;
20749}
20750
20751SDValue PPCTargetLowering::lowerLibCallBasedOnType(
20752 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
20753 SelectionDAG &DAG) const {
20754 if (Op.getValueType() == MVT::f32)
20755 return lowerToLibCall(LibCallFloatName, Op, DAG);
20756
20757 if (Op.getValueType() == MVT::f64)
20758 return lowerToLibCall(LibCallDoubleName, Op, DAG);
20759
20760 return SDValue();
20761}
20762
20763bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
20764 SDNodeFlags Flags = Op.getNode()->getFlags();
20765 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
20766 Flags.hasNoNaNs() && Flags.hasNoInfs();
20767}
20768
20769bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
20770 return Op.getNode()->getFlags().hasApproximateFuncs();
20771}
20772
20773bool PPCTargetLowering::isScalarMASSConversionEnabled() const {
20775}
20776
20777SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
20778 const char *LibCallFloatName,
20779 const char *LibCallDoubleNameFinite,
20780 const char *LibCallFloatNameFinite,
20781 SDValue Op,
20782 SelectionDAG &DAG) const {
20783 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op))
20784 return SDValue();
20785
20786 if (!isLowringToMASSFiniteSafe(Op))
20787 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
20788 DAG);
20789
20790 return lowerLibCallBasedOnType(LibCallFloatNameFinite,
20791 LibCallDoubleNameFinite, Op, DAG);
20792}
20793
20794SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
20795 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
20796 "__xl_powf_finite", Op, DAG);
20797}
20798
20799SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
20800 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
20801 "__xl_sinf_finite", Op, DAG);
20802}
20803
20804SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
20805 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
20806 "__xl_cosf_finite", Op, DAG);
20807}
20808
20809SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
20810 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
20811 "__xl_logf_finite", Op, DAG);
20812}
20813
20814SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
20815 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
20816 "__xl_log10f_finite", Op, DAG);
20817}
20818
20819SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
20820 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
20821 "__xl_expf_finite", Op, DAG);
20822}
20823
20824// If we happen to match to an aligned D-Form, check if the Frame Index is
20825// adequately aligned. If it is not, reset the mode to match to X-Form.
20826static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
20829 return;
20830 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
20833}
20834
20835/// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
20836/// compute the address flags of the node, get the optimal address mode based
20837/// on the flags, and set the Base and Disp based on the address mode.
20839 SDValue N, SDValue &Disp,
20840 SDValue &Base,
20841 SelectionDAG &DAG,
20842 MaybeAlign Align) const {
20843 SDLoc DL(Parent);
20844
20845 // Compute the address flags.
20846 unsigned Flags = computeMOFlags(Parent, N, DAG);
20847
20848 // Get the optimal address mode based on the Flags.
20849 PPC::AddrMode Mode = getAddrModeForFlags(Flags);
20850
20851 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
20852 // Select an X-Form load if it is not.
20853 setXFormForUnalignedFI(N, Flags, Mode);
20854
20855 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
20856 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
20857 assert(Subtarget.isUsingPCRelativeCalls() &&
20858 "Must be using PC-Relative calls when a valid PC-Relative node is "
20859 "present!");
20860 Mode = PPC::AM_PCRel;
20861 }
20862
20863 // Set Base and Disp accordingly depending on the address mode.
20864 switch (Mode) {
20865 case PPC::AM_DForm:
20866 case PPC::AM_DSForm:
20867 case PPC::AM_DQForm: {
20868 // This is a register plus a 16-bit immediate. The base will be the
20869 // register and the displacement will be the immediate unless it
20870 // isn't sufficiently aligned.
20871 if (Flags & PPC::MOF_RPlusSImm16) {
20872 SDValue Op0 = N.getOperand(0);
20873 SDValue Op1 = N.getOperand(1);
20874 int16_t Imm = Op1->getAsZExtVal();
20875 if (!Align || isAligned(*Align, Imm)) {
20876 Disp = DAG.getSignedTargetConstant(Imm, DL, N.getValueType());
20877 Base = Op0;
20879 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20880 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
20881 }
20882 break;
20883 }
20884 }
20885 // This is a register plus the @lo relocation. The base is the register
20886 // and the displacement is the global address.
20887 else if (Flags & PPC::MOF_RPlusLo) {
20888 Disp = N.getOperand(1).getOperand(0); // The global address.
20893 Base = N.getOperand(0);
20894 break;
20895 }
20896 // This is a constant address at most 32 bits. The base will be
20897 // zero or load-immediate-shifted and the displacement will be
20898 // the low 16 bits of the address.
20899 else if (Flags & PPC::MOF_AddrIsSImm32) {
20900 auto *CN = cast<ConstantSDNode>(N);
20901 EVT CNType = CN->getValueType(0);
20902 uint64_t CNImm = CN->getZExtValue();
20903 // If this address fits entirely in a 16-bit sext immediate field, codegen
20904 // this as "d, 0".
20905 int16_t Imm;
20906 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
20907 Disp = DAG.getSignedTargetConstant(Imm, DL, CNType);
20908 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20909 CNType);
20910 break;
20911 }
20912 // Handle 32-bit sext immediate with LIS + Addr mode.
20913 if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
20914 (!Align || isAligned(*Align, CNImm))) {
20915 int32_t Addr = (int32_t)CNImm;
20916 // Otherwise, break this down into LIS + Disp.
20917 Disp = DAG.getSignedTargetConstant((int16_t)Addr, DL, MVT::i32);
20918 Base = DAG.getSignedTargetConstant((Addr - (int16_t)Addr) >> 16, DL,
20919 MVT::i32);
20920 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
20921 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
20922 break;
20923 }
20924 }
20925 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
20926 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
20928 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20929 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
20930 } else
20931 Base = N;
20932 break;
20933 }
20934 case PPC::AM_PrefixDForm: {
20935 int64_t Imm34 = 0;
20936 unsigned Opcode = N.getOpcode();
20937 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
20938 (isIntS34Immediate(N.getOperand(1), Imm34))) {
20939 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
20940 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
20941 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
20942 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20943 else
20944 Base = N.getOperand(0);
20945 } else if (isIntS34Immediate(N, Imm34)) {
20946 // The address is a 34-bit signed immediate.
20947 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
20948 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
20949 }
20950 break;
20951 }
20952 case PPC::AM_PCRel: {
20953 // When selecting PC-Relative instructions, "Base" is not utilized as
20954 // we select the address as [PC+imm].
20955 Disp = N;
20956 break;
20957 }
20958 case PPC::AM_None:
20959 break;
20960 default: { // By default, X-Form is always available to be selected.
20961 // When a frame index is not aligned, we also match by XForm.
20963 Base = FI ? N : N.getOperand(1);
20964 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20965 N.getValueType())
20966 : N.getOperand(0);
20967 break;
20968 }
20969 }
20970 return Mode;
20971}
20972
20974 bool Return,
20975 bool IsVarArg) const {
20976 switch (CC) {
20977 case CallingConv::Cold:
20978 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF);
20979 default:
20980 return CC_PPC64_ELF;
20981 }
20982}
20983
20985 return Subtarget.isPPC64() && Subtarget.hasQuadwordAtomics();
20986}
20987
20990 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
20991 if (shouldInlineQuadwordAtomics() && Size == 128)
20993
20994 switch (AI->getOperation()) {
21000 default:
21002 }
21003
21004 llvm_unreachable("unreachable atomicrmw operation");
21005}
21006
21015
21016static Intrinsic::ID
21018 switch (BinOp) {
21019 default:
21020 llvm_unreachable("Unexpected AtomicRMW BinOp");
21022 return Intrinsic::ppc_atomicrmw_xchg_i128;
21023 case AtomicRMWInst::Add:
21024 return Intrinsic::ppc_atomicrmw_add_i128;
21025 case AtomicRMWInst::Sub:
21026 return Intrinsic::ppc_atomicrmw_sub_i128;
21027 case AtomicRMWInst::And:
21028 return Intrinsic::ppc_atomicrmw_and_i128;
21029 case AtomicRMWInst::Or:
21030 return Intrinsic::ppc_atomicrmw_or_i128;
21031 case AtomicRMWInst::Xor:
21032 return Intrinsic::ppc_atomicrmw_xor_i128;
21034 return Intrinsic::ppc_atomicrmw_nand_i128;
21035 }
21036}
21037
21039 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
21040 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
21041 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21042 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21043 Type *ValTy = Incr->getType();
21044 assert(ValTy->getPrimitiveSizeInBits() == 128);
21045 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21046 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
21047 Value *IncrHi =
21048 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
21049 Value *LoHi = Builder.CreateIntrinsic(
21051 {AlignedAddr, IncrLo, IncrHi});
21052 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21053 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21054 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21055 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21056 return Builder.CreateOr(
21057 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21058}
21059
21061 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
21062 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
21063 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21064 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21065 Type *ValTy = CmpVal->getType();
21066 assert(ValTy->getPrimitiveSizeInBits() == 128);
21067 Function *IntCmpXchg =
21068 Intrinsic::getOrInsertDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
21069 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21070 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
21071 Value *CmpHi =
21072 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
21073 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
21074 Value *NewHi =
21075 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
21076 emitLeadingFence(Builder, CI, Ord);
21077 Value *LoHi =
21078 Builder.CreateCall(IntCmpXchg, {AlignedAddr, CmpLo, CmpHi, NewLo, NewHi});
21079 emitTrailingFence(Builder, CI, Ord);
21080 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21081 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21082 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21083 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21084 return Builder.CreateOr(
21085 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21086}
21087
21089 return Subtarget.useCRBits();
21090}
21091
21092/// Shuffle masks for vectors of bits are not legal as such vectors are
21093/// reserved for MMA/DM.
21094bool PPCTargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
21095 if (VT.getScalarType() == MVT::i1)
21096 return false;
21097 return TargetLowering::isShuffleMaskLegal(Mask, VT);
21098}
21099
21100// Optimize the following patterns using vbpermq/vbpermd:
21101// i16 = bitcast(v16i1 truncate(v16i8))
21102// i8 = bitcast(v8i1 truncate(v8i16))
21103// i8 = bitcast(v8i1 truncate(v8i8))
21104SDValue PPCTargetLowering::DAGCombineBitcast(SDNode *N,
21105 DAGCombinerInfo &DCI) const {
21106 SDValue Op0 = N->getOperand(0);
21107 if (Op0.getOpcode() != ISD::TRUNCATE)
21108 return SDValue();
21109 SDValue Src = Op0.getOperand(0);
21110 EVT ResVT = N->getValueType(0);
21111 EVT TruncResVT = Op0.getValueType();
21112 EVT SrcVT = Src.getValueType();
21113 SDLoc dl(N);
21114 SelectionDAG &DAG = DCI.DAG;
21115 bool IsLittleEndian = Subtarget.isLittleEndian();
21116
21117 if (ResVT != MVT::i16 && ResVT != MVT::i8)
21118 return SDValue();
21119 SDValue VBPerm =
21120 GenerateVBPERM(DAG, dl, Src, SrcVT, TruncResVT, IsLittleEndian);
21121 if (!VBPerm)
21122 return SDValue();
21123 SDValue ForExtract = DAG.getBitcast(MVT::v4i32, VBPerm);
21124 SDValue Extracted =
21125 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, ForExtract,
21126 DAG.getIntPtrConstant(IsLittleEndian ? 2 : 1, dl));
21127 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, Extracted);
21128}
21129
21130SDValue PPCTargetLowering::GenerateVBPERM(SelectionDAG &DAG, SDLoc dl,
21131 SDValue Src, EVT SrcVT, EVT ResVT,
21132 bool IsLE) const {
21133 bool IsV16i8 = (ResVT == MVT::v16i1 && SrcVT == MVT::v16i8);
21134 bool IsV8i16 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i16);
21135 bool IsV8i8 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i8);
21136
21137 if (!IsV16i8 && !IsV8i16 && !IsV8i8)
21138 return SDValue();
21139
21140 if (IsV8i8) {
21141 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i8,
21142 DAG.getUNDEF(MVT::v16i8), Src,
21143 DAG.getIntPtrConstant(0, dl));
21144 }
21145 SmallVector<int, 16> BitIndices(16, 128);
21146 unsigned NumElts = SrcVT.getVectorNumElements();
21147 unsigned EltSize = SrcVT.getScalarType().getSizeInBits();
21148 for (int Idx = 0, End = SrcVT.getVectorNumElements(); Idx < End; Idx++) {
21149 BitIndices[Idx] = EltSize * (NumElts - Idx) - 1;
21150 if (IsV8i8 && IsLE)
21151 BitIndices[Idx] += 64;
21152 }
21153 if (!IsLE)
21154 std::reverse(BitIndices.begin(), BitIndices.end());
21156 for (auto Idx : BitIndices)
21157 BVOps.push_back(DAG.getConstant(Idx, dl, MVT::i8));
21158 SDValue VRB = DAG.getBuildVector(MVT::v16i8, dl, BVOps);
21159 return DAG.getNode(
21160 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v16i8,
21161 DAG.getConstant(Intrinsic::ppc_altivec_vbpermq, dl, MVT::i32),
21162 DAG.getBitcast(MVT::v16i8, Src), VRB);
21163}
21164
21165// For Power8/9, optimize vec splats of small FP values that can be
21166// represented as integers. Use vspltisw + xvcvsxwdp/xvcvsxwsp instead of
21167// loading from constant pool.
21168SDValue PPCTargetLowering::LowerVecSplatSmallFP(SDValue Op, SelectionDAG &DAG,
21169 bool BVNIsConstantSplat,
21170 unsigned SplatBitSize) const {
21171
21172 if (!BVNIsConstantSplat || !Subtarget.hasVSX() || !Subtarget.hasP8Vector() ||
21173 Subtarget.hasP10Vector())
21174 return SDValue();
21175
21176 EVT VT = Op->getValueType(0);
21177 if (!((SplatBitSize == 64 && VT == MVT::v2f64) ||
21178 (SplatBitSize == 32 && VT == MVT::v4f32)))
21179 return SDValue();
21180
21181 auto *CN = dyn_cast<ConstantFPSDNode>(Op.getOperand(0));
21182 if (!CN)
21183 return SDValue();
21184
21185 APFloat APFloatVal = CN->getValueAPF();
21186 bool IsExact;
21187 APSInt IntResult(16, false);
21188 APFloatVal.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
21189
21190 if (!(IsExact && IntResult <= 15 && IntResult >= -16 && !APFloatVal.isZero()))
21191 return SDValue();
21192
21193 int64_t IntVal = IntResult.getSExtValue();
21194
21195 SDLoc dl(Op);
21196 SDValue IntSplat = getCanonicalConstSplat(IntVal, 4, MVT::v4i32, DAG, dl);
21197
21198 if (SplatBitSize == 64)
21199 return DAG.getNode(
21200 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v2f64,
21201 DAG.getConstant(Intrinsic::ppc_vsx_xvcvsxwdp, dl, MVT::i32), IntSplat);
21202
21203 return DAG.getNode(PPCISD::XVCVSXWSP, dl, MVT::v4f32, IntSplat);
21204}
static MCRegister MatchRegisterName(StringRef Name)
static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect, bool IsTailCall, std::optional< CallLowering::PtrAuthInfo > &PAI, MachineRegisterInfo &MRI)
return SDValue()
static SDValue GeneratePerfectShuffle(unsigned ID, SDValue V1, SDValue V2, unsigned PFEntry, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const SDLoc &DL)
GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit the specified operations t...
static bool isSignExtended(SDValue N, SelectionDAG &DAG)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static std::pair< Register, unsigned > getBaseWithConstantOffset(MachineRegisterInfo &MRI, Register Reg)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isLoad(int Opcode)
static bool isFloatingPointZero(SDValue Op)
isFloatingPointZero - Return true if this is +0.0.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
Atomic ordering constants.
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, const SDLoc &dl)
CreateCopyOfByValArgument - Make a copy of an aggregate at address specified by "Src" to address "Dst...
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
lazy value info
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static int getEstimateRefinementSteps(EVT VT, const LoongArchSubtarget &Subtarget)
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static bool isConstantOrUndef(const SDValue Op)
MachineInstr unsigned OpIdx
#define P(N)
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
cl::opt< bool > ANDIGlueBug("expose-ppc-andi-glue-bug", cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden)
static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, SelectionDAG &DAG, const SDLoc &dl)
getCanonicalConstSplat - Build a canonical splat immediate of Val with an element size of SplatSize.
static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static const TargetRegisterClass * getRegClassForSVT(MVT::SimpleValueType SVT, bool IsPPC64, bool HasP8Vector, bool HasVSX)
static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign)
static SDValue DAGCombineAddc(SDNode *N, llvm::PPCTargetLowering::DAGCombinerInfo &DCI)
static bool needStackSlotPassParameters(const PPCSubtarget &Subtarget, const SmallVectorImpl< ISD::OutputArg > &Outs)
std::tuple< uint32_t, uint8_t > LXVKQPattern
static bool isAlternatingShuffMask(const ArrayRef< int > &Mask, int NumElts)
static bool isShuffleMaskInRange(const SmallVectorImpl< int > &ShuffV, int HalfVec, int LHSLastElementDefined, int RHSLastElementDefined)
static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, SDValue Input, uint64_t Elems, uint64_t CorrectElems)
static cl::opt< bool > DisablePPCUnaligned("disable-ppc-unaligned", cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden)
static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG)
static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, bool Swap, SDLoc &DL, SelectionDAG &DAG)
This function is called when we have proved that a SETCC node can be replaced by subtraction (and oth...
static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL)
static void CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg, int SPDiff, unsigned ArgOffset, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments)
CalculateTailCallArgDest - Remember Argument for later processing.
static MachineBasicBlock * emitAtomicCmpSwapSoftware(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit software-emulated atomic compare-and-swap for I8/I16 without hardware partword atomic support.
static SDValue DAGCombineSube(SDNode *N, llvm::PPCTargetLowering::DAGCombinerInfo &DCI)
static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, SelectionDAG &DAG)
Set alignment flags based on whether or not the Frame Index is aligned.
static bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget)
static void updateForAIXShLibTLSModelOpt(TLSModel::Model &Model, SelectionDAG &DAG, const TargetMachine &TM)
updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings, and then apply the update...
static bool IsSelect(unsigned Opcode, bool CheckOnlyCC=false)
Check if the opcode is a SELECT or SELECT_CC variant.
static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N)
Used when computing address flags for selecting loads and stores.
static bool callsShareTOCBase(const Function *Caller, const GlobalValue *CalleeGV, const TargetMachine &TM)
static void prepareOutOfLineGlueCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, SDValue CallSeqStart, const CallBase *CB, const SDLoc &dl, bool hasNest, const PPCSubtarget &Subtarget)
static SDValue generateSToVPermutedForVecShuffle(int ScalarSize, uint64_t ShuffleEltWidth, unsigned &NumValidElts, int FirstElt, int &LastElt, SDValue VecShuffOperand, SDValue SToVNode, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
constexpr uint64_t AIXSmallTlsPolicySizeLimit
static bool isPCRelNode(SDValue N)
static void LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, bool isTailCall, bool isVector, SmallVectorImpl< SDValue > &MemOpChains, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments, const SDLoc &dl)
LowerMemOpCallTo - Store the argument to the stack or remember it in case of tail calls.
static cl::opt< unsigned > PPCGatherAllAliasesMaxDepth("ppc-gather-alias-max-depth", cl::init(18), cl::Hidden, cl::desc("max depth when checking alias info in GatherAllAliases()"))
static bool IsSelectCC(unsigned Opcode)
static bool areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, CallingConv::ID CalleeCC)
static const MCPhysReg FPR[]
FPR - The set of FP registers that should be allocated for arguments on Darwin and AIX.
static SDNode * isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG)
isCallCompatibleAddress - Return the immediate to use if the specified 32-bit value is representable ...
static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize)
CalculateStackSlotAlignment - Calculates the alignment of this argument on the stack.
static SDValue ConvertCarryFlagToCarryValue(EVT SumType, SDValue Flag, EVT CarryType, SelectionDAG &DAG, const PPCSubtarget &STI)
static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, bool HasDirectMove, bool HasP8Vector)
Do we have an efficient pattern in a .td file for this node?
static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void setUsesTOCBasePtr(MachineFunction &MF)
static SDValue combineXorSelectCC(SDNode *N, SelectionDAG &DAG)
static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, const SDLoc &dl, const PPCSubtarget &Subtarget)
static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, unsigned NumBytes)
EnsureStackAlignment - Round stack frame size up from NumBytes to ensure minimum alignment required f...
static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth)
static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB)
static bool isFPExtLoad(SDValue Op)
static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, const SDLoc &dl, EVT DestVT=MVT::Other)
BuildIntrinsicOp - Return a unary operator intrinsic node with the specified intrinsic ID.
static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG)
static bool canConvertToVcmpequb(SDValue &LHS, SDValue &RHS, bool IsPPC64)
static void StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, SDValue Chain, const SmallVectorImpl< TailCallArgumentInfo > &TailCallArgs, SmallVectorImpl< SDValue > &MemOpChains, const SDLoc &dl)
StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
static cl::opt< bool > UseAbsoluteJumpTables("ppc-use-absolute-jumptables", cl::desc("use absolute jump tables on ppc"), cl::Hidden)
static void setXFormForUnalignedFI(SDValue N, unsigned Flags, PPC::AddrMode &Mode)
static cl::opt< unsigned > PPCMinimumBitTestCmps("ppc-min-bit-test-cmps", cl::init(3), cl::Hidden, cl::desc("Set minimum of largest number of comparisons to use bit test for " "switch on PPC."))
static CallInst * callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id)
static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign)
getMaxByValAlign - Helper for getByValTypeAlignment to determine the desired ByVal argument alignment...
static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG)
static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned LHSStart, unsigned RHSStart)
isVMerge - Common function, used to match vmrg* shuffles.
static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, unsigned &HiOpFlags, unsigned &LoOpFlags, const GlobalValue *GV=nullptr)
Return true if we should reference labels using a PICBase, set the HiOpFlags and LoOpFlags to the tar...
cl::opt< bool > DisableAutoPairedVecSt("disable-auto-paired-vec-st", cl::desc("disable automatically generated 32byte paired vector stores"), cl::init(true), cl::Hidden)
static void buildCallOperands(SmallVectorImpl< SDValue > &Ops, PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, SmallVector< std::pair< unsigned, SDValue >, 8 > &RegsToPass, SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, const PPCSubtarget &Subtarget)
static cl::opt< bool > DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden)
static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget &ST)
Returns true if we should use a direct load into vector instruction (such as lxsd or lfd),...
static SDValue getDataClassTest(SDValue Op, FPClassTest Mask, const SDLoc &Dl, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl< int > &ShuffV, int LHSFirstElt, int LHSLastElt, int RHSFirstElt, int RHSLastElt, int HalfVec, unsigned LHSNumValidElts, unsigned RHSNumValidElts, const PPCSubtarget &Subtarget)
static SDValue AdjustLength(SDValue Val, unsigned Bits, bool Left, SelectionDAG &DAG)
static cl::opt< bool > DisableSCO("disable-ppc-sco", cl::desc("disable sibling call optimization on ppc"), cl::Hidden)
static std::optional< LXVKQPattern > getPatternInfo(const APInt &FullVal)
static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT)
static cl::opt< bool > DisablePPCPreinc("disable-ppc-preinc", cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden)
static SDValue ConvertSETCCToXori(SDNode *N, SelectionDAG &DAG)
static Intrinsic::ID getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp)
static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize)
CalculateStackSlotSize - Calculates the size reserved for this argument on the stack.
static int CalculateTailCallSPDiff(SelectionDAG &DAG, bool isTailCall, unsigned ParamSize)
CalculateTailCallSPDiff - Get the amount the stack pointer has to be adjusted to accommodate the argu...
static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, const SDLoc &dl)
static SDValue combineSELECT_CCBitFloor(SDNode *N, SelectionDAG &DAG)
Optimize the bitfloor(X) pattern for PowerPC.
static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, SelectionDAG &DAG)
static SDValue isScalarToVec(SDValue Op)
static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl)
static cl::opt< bool > DisablePerfectShuffle("ppc-disable-perfect-shuffle", cl::desc("disable vector permute decomposition"), cl::init(true), cl::Hidden)
bool isValidMtVsrBmi(APInt &BitMask, BuildVectorSDNode &BVN, bool IsLittleEndian)
static MachineBasicBlock * emitSelect(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit SELECT instruction, using ISEL if available, otherwise use branch-based control flow.
static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, bool &isDot, const PPCSubtarget &Subtarget)
getVectorCompareInfo - Given an intrinsic, return false if it is not a vector comparison.
static unsigned invertFMAOpcode(unsigned Opc)
static SDValue combineADDToSUB(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static const SDValue * getNormalLoadInput(const SDValue &Op, bool &IsPermuted)
static bool canConvertSETCCToXori(SDNode *N)
static cl::opt< unsigned > PPCMinimumJumpTableEntries("ppc-min-jump-table-entries", cl::init(64), cl::Hidden, cl::desc("Set minimum number of entries to use a jump table on PPC"))
static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, unsigned &Opcode)
static SDValue ConvertCarryValueToCarryFlag(EVT SumType, SDValue Value, SelectionDAG &DAG, const PPCSubtarget &STI)
static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, const PPCSubtarget &Subtarget, SDValue Chain=SDValue())
static void PrepareTailCall(SelectionDAG &DAG, SDValue &InGlue, SDValue &Chain, const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, SDValue FPOp, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments)
static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, SDValue OldRetAddr, SDValue OldFP, int SPDiff, const SDLoc &dl)
EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to the appropriate stack sl...
static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, SelectionDAG &DAG, const SDLoc &dl)
BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified amount.
static void createAtomicLoopBlocks(MachineFunction *F, MachineBasicBlock *BB, MachineBasicBlock *&loop1MBB, MachineBasicBlock *&loop2MBB, MachineBasicBlock *&exitMBB, MachineInstr &MI, MachineFunction::iterator It)
Helper function to create basic blocks for atomic compare-and-swap.
static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG)
static SDValue combineZextSetccWithZero(SDNode *N, SelectionDAG &DAG)
static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, SelectionDAG &DAG, SDValue ArgValue, MVT LocVT, const SDLoc &dl)
static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, SelectionDAG &DAG)
Given a node, compute flags that are used for address computation when selecting load and store instr...
static MachineBasicBlock * emitAtomicCmpSwapHardware(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit hardware-supported atomic compare-and-swap for I32/I64 and I8/I16 with partword atomic support.
SDValue convertTwoLoadsAndCmpToVCMPEQUB(SelectionDAG &DAG, SDNode *N, const SDLoc &DL)
static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart)
static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize, unsigned LinkageSize, unsigned ParamAreaSize, unsigned &ArgOffset, unsigned &AvailableFPRs, unsigned &AvailableVRs)
CalculateStackSlotUsed - Return whether this argument will use its stack slot (instead of being passe...
static void signExtendOperandIfUnknown(MachineInstr &MI, MachineBasicBlock *BB, unsigned OpIdx, bool IsByte, const PPCInstrInfo *TII)
static cl::opt< unsigned > PPCAIXTLSModelOptUseIEForLDLimit("ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden, cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a " "function to use initial-exec"))
static unsigned getPPCStrictOpcode(unsigned Opc)
static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, SDValue CallSeqStart, const CallBase *CB, const SDLoc &dl, bool hasNest, const PPCSubtarget &Subtarget)
static cl::opt< bool > DisableP10StoreForward("disable-p10-store-forward", cl::desc("disable P10 store forward-friendly conversion"), cl::Hidden, cl::init(false))
static bool isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width)
static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV)
static bool isSplatBV(SDValue Op)
static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG)
static cl::opt< bool > DisableILPPref("disable-ppc-ilp-pref", cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden)
static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int)
Check that the mask is shuffling N byte elements.
static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG)
Reduce the number of loads when building a vector.
static bool isValidPCRelNode(SDValue N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
if(PassOpts->AAPipeline)
pre isel intrinsic Pre ISel Intrinsic Lowering
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI optimize exec mask operations pre RA
static const MCExpr * MaskShift(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG, const SparcSubtarget *Subtarget)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
static constexpr int TPOffset
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:297
static constexpr roundingMode rmTowardZero
Definition APFloat.h:349
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:345
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:300
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5920
bool isDenormal() const
Definition APFloat.h:1566
bool isZero() const
Definition APFloat.h:1561
APInt bitcastToAPInt() const
Definition APFloat.h:1457
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1418
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1421
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:436
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:398
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:472
double bitsToDouble() const
Converts APInt bits to a double.
Definition APInt.h:1747
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ UIncWrap
Increment one up to a maximum value.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
BinOp getOperation() const
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const BlockAddress * getBlockAddress() const
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
CCState - This class holds information needed while lowering arguments and return values.
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
unsigned getValNo() const
static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getCalledOperand() const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const Constant * getConstVal() const
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
int64_t getSExtValue() const
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:691
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:357
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:758
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:770
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:688
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:328
arg_iterator arg_begin()
Definition Function.h:845
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
size_t arg_size() const
Definition Function.h:878
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
const Argument * const_arg_iterator
Definition Function.h:74
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
const GlobalValue * getGlobal() const
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
void setThreadLocalMode(ThreadLocalMode Val)
bool hasHiddenVisibility() const
LLVM_ABI StringRef getSection() const
Definition Globals.cpp:264
Module * getParent()
Get the module that this global value is contained inside of...
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
bool hasComdat() const
Type * getValueType() const
bool hasProtectedVisibility() const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
LLVM_ABI bool hasAtomicLoad() const LLVM_READONLY
Return true if this atomic instruction loads from memory.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget.
An instruction for reading from memory.
bool isUnordered() const
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
bool hasValue() const
TypeSize getValue() const
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MCSymbolXCOFF * getQualNameSymbol() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
Metadata node.
Definition Metadata.h:1069
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool hasVAStart() const
Returns true if the function calls the llvm.va_start intrinsic.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
AtomicOrdering getFailureOrdering() const
For cmpxchg atomic operations, return the atomic ordering requirements when store does not occur.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID for this memory operation.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
AtomicOrdering getSuccessOrdering() const
Return the atomic ordering requirements for this memory operation.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateImm(int64_t Val)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI Register getLiveInVirtReg(MCRegister PReg) const
getLiveInVirtReg - If PReg is a live-in physical register, return the corresponding live-in virtual r...
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
Align getAlign() const
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getBasePtr() const
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
uint64_t getReturnSaveOffset() const
getReturnSaveOffset - Return the previous frame offset to save the return address.
unsigned getLinkageSize() const
getLinkageSize - Return the size of the PowerPC ABI linkage area.
uint64_t getTOCSaveOffset() const
getTOCSaveOffset - Return the previous frame offset to save the TOC register – 64-bit SVR4 ABI only.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
void setVarArgsNumFPR(unsigned Num)
void setVarArgsNumGPR(unsigned Num)
void appendParameterType(ParamType Type)
void setMinReservedArea(unsigned size)
unsigned getMinReservedArea() const
void setVarArgsStackOffset(int Offset)
void addLiveInAttr(Register VReg, ISD::ArgFlagsTy Flags)
This function associates attributes for each live-in virtual register.
static bool hasPCRelFlag(unsigned TF)
bool is32BitELFABI() const
unsigned descriptorTOCAnchorOffset() const
MVT getScalarIntVT() const
bool isAIXABI() const
MCRegister getGlueCodeDescriptorRegister() const
const PPCFrameLowering * getFrameLowering() const override
bool isUsingPCRelativeCalls() const
bool usesFunctionDescriptors() const
True if the ABI is descriptor based.
MCRegister getEnvironmentPointerRegister() const
bool isSVR4ABI() const
bool isLittleEndian() const
MCRegister getTOCPointerRegister() const
MCRegister getStackPointerRegister() const
bool is64BitELFABI() const
bool isELFv2ABI() const
const PPCTargetMachine & getTargetMachine() const
const PPCRegisterInfo * getRegisterInfo() const override
unsigned descriptorEnvironmentPointerOffset() const
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
CCAssignFn * ccAssignFnForCall(CallingConv::ID CC, bool Return, bool IsVarArg) const
bool isTruncateFree(Type *Ty1, Type *Ty2) const override
isTruncateFree - Return true if it's free to truncate a value of type Ty1 to type Ty2.
Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const override
Perform a masked atomicrmw using a target-specific intrinsic.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
bool isFPExtFree(EVT DestVT, EVT SrcVT) const override
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
PPC::AddrMode SelectForceXFormMode(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG) const
SelectForceXFormMode - Given the specified address, force it to be represented as an indexed [r+r] op...
Instruction * emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
TargetLowering::AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
bool hasInlineStackProbe(const MachineFunction &MF) const override
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool supportsTailCallFor(const CallBase *CB) const
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
MachineBasicBlock * emitProbedAlloca(MachineInstr &MI, MachineBasicBlock *MBB) const
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const override
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
bool SelectAddressRegImm(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, MaybeAlign EncodingAlignment) const
SelectAddressRegImm - Returns true if the address N can be represented by a base register plus a sign...
SDValue expandVSXLoadForLE(SDNode *N, DAGCombinerInfo &DCI) const
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
LowerAsmOperandForConstraint - Lower the specified operand into the Ops vector.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
ReplaceNodeResults - Replace the results of node with an illegal result type with new values built ou...
bool hasMultipleConditionRegisters(EVT VT) const override
Does the target have multiple (allocatable) condition registers that can be used to store the results...
Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const override
getByValTypeAlignment - Return the desired alignment for ByVal aggregate function arguments in the ca...
bool SelectAddressRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, MaybeAlign EncodingAlignment=std::nullopt) const
SelectAddressRegReg - Given the specified addressed, check to see if it can be more efficiently repre...
SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const override
Targets may override this function to provide custom SDIV lowering for power-of-2 denominators.
Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const override
Perform a store-conditional operation to Addr.
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool SelectAddressRegRegOnly(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const
SelectAddressRegRegOnly - Given the specified addressed, force it to be represented as an indexed [r+...
bool useSoftFloat() const override
SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const override
Returns relocation base for the given PIC jumptable.
TargetLowering::AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const override
Perform a masked cmpxchg using a target-specific intrinsic.
ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool enableAggressiveFMAFusion(EVT VT) const override
Return true if target always benefits from combining into FMA for a given value type.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const override
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
isLegalAddressingMode - Return true if the addressing mode represented by AM is legal for this target...
bool preferIncOfAddToSubOfNot(EVT VT) const override
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Returns true if it is beneficial to convert a load of a constant to just the constant itself.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
getPreIndexedAddressParts - returns true by value, base pointer and offset pointer and addressing mod...
FastISel * createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo, const LibcallLoweringInfo *LibcallLowering) const override
createFastISel - This method returns a target-specific FastISel object, or null if the target does no...
bool isProfitableToHoist(Instruction *I) const override
isProfitableToHoist - Check if it is profitable to hoist instruction I to its dominator block.
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns true if the target can instruction select the specified FP immediate natively.
Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const override
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
ConstraintType getConstraintType(StringRef Constraint) const override
getConstraintType - Given a constraint, return the type of constraint it is for this target.
const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const override
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const override
Return true if the target shall perform extract vector element and store given that the vector is kno...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
It returns EVT::Other if the type should be determined using generic target-independent logic.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue expandVSXStoreForLE(SDNode *N, DAGCombinerInfo &DCI) const
void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const override
unsigned getStackProbeSize(const MachineFunction &MF) const
PPCTargetLowering(const PPCTargetMachine &TM, const PPCSubtarget &STI)
bool useLoadStackGuardNode(const Module &M) const override
Override to support customized stack guard loading.
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster than a pair of fmul and fadd i...
MachineBasicBlock * EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode, unsigned CmpOpcode=0, unsigned CmpPred=0) const
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const override
Is unaligned memory access allowed for the given type, and is it fast relative to software emulation.
bool shouldExpandBuildVectorWithShuffles(EVT VT, unsigned DefinedValues) const override
bool SelectAddressRegImm34(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG) const
Similar to the 16-bit case but for instructions that take a 34-bit displacement field (prefixed loads...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
Register getExceptionSelectorRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
bool isJumpTableRelative() const override
Register getExceptionPointerRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
LowerOperation - Provide custom lowering hooks for some operations.
PPC::AddrMode SelectOptimalAddrMode(const SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, MaybeAlign Align) const
SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), compute the address flags of...
bool SelectAddressPCRel(SDValue N, SDValue &Base) const
SelectAddressPCRel - Represent the specified address as pc relative to be represented as [pc+imm].
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
getSetCCResultType - Return the ISD::SETCC ValueType
bool SelectAddressEVXRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const
SelectAddressEVXRegReg - Given the specified addressed, check to see if it can be more efficiently re...
bool isLegalICmpImmediate(int64_t Imm) const override
isLegalICmpImmediate - Return true if the specified immediate is legal icmp immediate,...
MachineBasicBlock * EmitPartwordAtomicBinary(MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode, unsigned CmpOpcode=0, unsigned CmpPred=0) const
bool isAccessedAsGotIndirect(SDValue N) const
Align getPrefLoopAlignment(MachineLoop *ML) const override
Return the preferred loop alignment.
Instruction * emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
Inserts in the IR a target-specific intrinsic specifying a fence.
bool isLegalAddImmediate(int64_t Imm) const override
isLegalAddImmediate - Return true if the specified immediate is legal add immediate,...
Common code between 32-bit and 64-bit PowerPC targets.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
LLVM_ABI void dump() const
Dump this node, for debugging.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
iterator_range< value_op_iterator > op_values() const
iterator_range< use_iterator > uses()
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
user_iterator user_begin() const
Provide iteration support to walk over all users of an SDNode.
static use_iterator use_end()
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
unsigned getNumOperands() const
static SectionKind getMetadata()
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the sub of 2 nodes can never overflow.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
size_type size() const
Definition SmallPtrSet.h:99
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getValue() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
void setMinimumBitTestCmps(unsigned Val)
Set the minimum of largest of number of comparisons to generate BitTest.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
const TargetMachine & getTargetMachine() const
unsigned MaxLoadsPerMemcmp
Specify maximum number of load instructions per memcmp call.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop alignment.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
virtual bool isJumpTableRelative() const
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT, LegalizeAction Action)
Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treate...
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
unsigned MaxLoadsPerMemcmpOptSize
Likewise for functions with the OptSize attribute.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
unsigned GatherAllAliasesMaxDepth
Depth that GatherAllAliases should continue looking for chain dependencies when trying to find a more...
NegatibleCost
Enum that specifies when a float negation is beneficial.
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
void setJumpIsExpensive(bool isExpensive=true)
Tells the code generator not to expand logic operations on comparison predicates into separate sequen...
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const
void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS, SDValue &NewRHS, ISD::CondCode &CCCode, const SDLoc &DL, const SDValue OldLHS, const SDValue OldRHS) const
Soften the operands of a comparison.
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
virtual SDValue getSqrtResultForDenormInput(SDValue Operand, SelectionDAG &DAG) const
Return a target-dependent result if the input operand is not suitable for use with a square root esti...
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG, const DenormalMode &Mode, SDNodeFlags Flags={}) const
Return a target-dependent comparison result if the input operand is suitable for use with a square ro...
virtual bool isGAPlusOffset(SDNode *N, const GlobalValue *&GA, int64_t &Offset) const
Returns true (and the GlobalValue and the offset) if the node is a GlobalAddress + offset.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
unsigned PPCGenScalarMASSEntries
Enables scalar MASS conversions.
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:180
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:273
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ TargetConstantPool
Definition ISDOpcodes.h:189
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:513
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:168
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ GlobalAddress
Definition ISDOpcodes.h:88
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:438
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ SET_ROUNDING
Set rounding mode.
Definition ISDOpcodes.h:985
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:487
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ TargetExternalSymbol
Definition ISDOpcodes.h:190
@ BR
Control flow instructions. These all have token chains.
@ TargetJumpTable
Definition ISDOpcodes.h:188
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:185
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:980
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:486
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:150
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:480
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:427
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:458
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:162
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:186
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isUNINDEXEDLoad(const SDNode *N)
Returns true if the specified node is an unindexed load.
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ Bitcast
Perform the operation on a different, but equivalently sized type.
@ VecShuffle
Definition NVPTX.h:157
@ MO_TLSLDM_FLAG
MO_TLSLDM_FLAG - on AIX the ML relocation type is only valid for a reference to a TOC symbol from the...
Definition PPC.h:148
@ MO_PIC_LO_FLAG
MO_PIC_LO_FLAG = MO_PIC_FLAG | MO_LO.
Definition PPC.h:196
@ MO_TPREL_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TPREL_FLAG.
Definition PPC.h:199
@ MO_GOT_TPREL_PCREL_FLAG
MO_GOT_TPREL_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:174
@ MO_GOT_PCREL_FLAG
MO_GOT_PCREL_FLAG = MO_PCREL_FLAG | MO_GOT_FLAG.
Definition PPC.h:205
@ MO_TLSGDM_FLAG
MO_TLSGDM_FLAG - If this bit is set the symbol reference is relative to the region handle of TLS Gene...
Definition PPC.h:156
@ MO_PCREL_FLAG
MO_PCREL_FLAG - If this bit is set, the symbol reference is relative to the current instruction addre...
Definition PPC.h:123
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition PPC.h:152
@ MO_TLS_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TLS.
Definition PPC.h:202
@ MO_TPREL_HA
Definition PPC.h:181
@ MO_PLT
On PPC, the 12 bits are not enough for all target operand flags.
Definition PPC.h:115
@ MO_TLS
Symbol for VK_TLS fixup attached to an ADD instruction.
Definition PPC.h:190
@ MO_TPREL_FLAG
MO_TPREL_FLAG - If this bit is set, the symbol reference is relative to the thread pointer and the sy...
Definition PPC.h:142
@ MO_TPREL_LO
Definition PPC.h:180
@ MO_LO
MO_LO, MO_HA - lo16(symbol) and ha16(symbol)
Definition PPC.h:177
@ MO_GOT_TLSLD_PCREL_FLAG
MO_GOT_TLSLD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:168
@ MO_PIC_HA_FLAG
MO_PIC_HA_FLAG = MO_PIC_FLAG | MO_HA.
Definition PPC.h:193
@ MO_TLSGD_FLAG
MO_TLSGD_FLAG - If this bit is set the symbol reference is relative to TLS General Dynamic model for ...
Definition PPC.h:137
@ MO_GOT_TLSGD_PCREL_FLAG
MO_GOT_TLSGD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:162
@ MO_HA
Definition PPC.h:178
@ MO_PIC_FLAG
MO_PIC_FLAG - If this bit is set, the symbol reference is relative to the function's picbase,...
Definition PPC.h:119
@ MFOCRF
R32 = MFOCRF(CRREG, INFLAG) - Represents the MFOCRF instruction.
@ VADD_SPLAT
VRRC = VADD_SPLAT Elt, EltSize - Temporary node to be expanded during instruction selection to optimi...
@ PPC32_PICGOT
GPRC = address of GLOBAL_OFFSET_TABLE.
@ GlobalBaseReg
The result of the mflr at function entry, used for PIC code.
@ SRA_ADDZE
The combination of sra[wd]i and addze used to implemented signed integer division by a power of 2.
Define some predicates that are used for node matching.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
SDValue get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG)
get_VSPLTI_elt - If this is a build_vector of constants which can be formed by using a vspltis[bhw] i...
bool isXXBRDShuffleMask(ShuffleVectorSDNode *N)
isXXBRDShuffleMask - Return true if this is a shuffle mask suitable for a XXBRD instruction.
bool isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for a VRGH* instruction with the ...
bool isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a VPKUDUM instruction.
bool isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGEOShuffleMask - Return true if this is a shuffle mask suitable for a VMRGEW or VMRGOW instructi...
bool isXXBRQShuffleMask(ShuffleVectorSDNode *N)
isXXBRQShuffleMask - Return true if this is a shuffle mask suitable for a XXBRQ instruction.
bool isXXBRWShuffleMask(ShuffleVectorSDNode *N)
isXXBRWShuffleMask - Return true if this is a shuffle mask suitable for a XXBRW instruction.
bool isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, bool &Swap, bool IsLE)
isXXPERMDIShuffleMask - Return true if this is a shuffle mask suitable for a XXPERMDI instruction.
bool isXXBRHShuffleMask(ShuffleVectorSDNode *N)
isXXBRHShuffleMask - Return true if this is a shuffle mask suitable for a XXBRH instruction.
unsigned getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, SelectionDAG &DAG)
getSplatIdxForPPCMnemonics - Return the splat index as a value that is appropriate for PPC mnemonics ...
bool isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, bool &Swap, bool IsLE)
isXXSLDWIShuffleMask - Return true if this is a shuffle mask suitable for a XXSLDWI instruction.
FastISel * createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo, const LibcallLoweringInfo *LibcallLowering)
int isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift amount, otherwise return -1.
bool isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for a VRGL* instruction with the ...
bool isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, unsigned &InsertAtByte, bool &Swap, bool IsLE)
isXXINSERTWMask - Return true if this VECTOR_SHUFFLE can be handled by the XXINSERTW instruction intr...
bool isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize)
isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand specifies a splat of a singl...
bool isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a VPKUWUM instruction.
bool isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a VPKUHUM instruction.
Invariant opcodes: All instruction sets have these as their low opcodes.
@ XMC_PR
Program Code.
Definition XCOFF.h:106
@ XTY_ER
External reference.
Definition XCOFF.h:242
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:387
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:383
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:395
iterator end() const
Definition BasicBlock.h:89
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
static bool isIndirectCall(const MachineInstr &MI)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
bool checkConvertToNonDenormSingle(APFloat &ArgAPFloat)
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
bool isIntS16Immediate(SDNode *N, int16_t &Imm)
isIntS16Immediate - This method tests to see if the node is either a 32-bit or 64-bit immediate,...
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
static bool isRunOfOnes64(uint64_t Val, unsigned &MB, unsigned &ME)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool RetCC_PPC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
bool CC_PPC64_ELF(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
unsigned M1(unsigned Val)
Definition VE.h:377
bool isReleaseOrStronger(AtomicOrdering AO)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool convertToNonDenormSingle(APInt &ArgAPInt)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool CC_PPC32_SVR4_ByVal(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool CC_PPC32_SVR4(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
bool RetCC_PPC_Cold(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
@ Success
The lock was released successfully.
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
const unsigned PerfectShuffleTable[6561+1]
AtomicOrdering
Atomic ordering for LLVM's memory model.
bool isIntS34Immediate(SDNode *N, int64_t &Imm)
isIntS34Immediate - This method tests if value of node given can be accurately represented as a sign ...
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI bool isPhysRegUsedAfter(Register Reg, MachineBasicBlock::iterator MBI)
Check if physical register Reg is used after MBI.
unsigned M0(unsigned Val)
Definition VE.h:376
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
bool isAcquireOrStronger(AtomicOrdering AO)
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition MathExtras.h:555
constexpr unsigned BitWidth
bool CC_PPC32_SVR4_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:573
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME)
Returns true iff Val consists of one contiguous run of 1s with any number of 0s on either side.
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Represent subnormal handling kind for floating point instruction inputs and outputs.
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
LLVM_ABI std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
unsigned getByValSize() const
void setByValSize(unsigned S)
Align getNonZeroByValAlign() const
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Structure that collects some common arguments that get passed around between the functions for call l...
These are IR-level optimization flags that may be propagated to SDNodes.
void setNoFPExcept(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setSExtResult(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
This structure is used to pass arguments to makeLibCall function.