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.
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.
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 {
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 {
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
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 case MVT::v4f32:
4285 case MVT::v2f64:
4286 case MVT::v2i64:
4287 case MVT::f128:
4288 RC = &PPC::VRRCRegClass;
4289 break;
4290 }
4291
4292 SDValue ArgValue;
4293 // Transform the arguments stored in physical registers into
4294 // virtual ones.
4295 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4296 assert(i + 1 < e && "No second half of double precision argument");
4297 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4298 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4299 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4300 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4301 if (!Subtarget.isLittleEndian())
4302 std::swap (ArgValueLo, ArgValueHi);
4303 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4304 ArgValueHi);
4305 } else {
4306 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4307 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4308 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4309 if (ValVT == MVT::i1)
4310 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4311 }
4312
4313 InVals.push_back(ArgValue);
4314 } else {
4315 // Argument stored in memory.
4316 assert(VA.isMemLoc());
4317
4318 // Get the extended size of the argument type in stack
4319 unsigned ArgSize = VA.getLocVT().getStoreSize();
4320 // Get the actual size of the argument type
4321 unsigned ObjSize = VA.getValVT().getStoreSize();
4322 unsigned ArgOffset = VA.getLocMemOffset();
4323 // Stack objects in PPC32 are right justified.
4324 ArgOffset += ArgSize - ObjSize;
4325 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4326
4327 // Create load nodes to retrieve arguments from the stack.
4328 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4329 InVals.push_back(
4330 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4331 }
4332 }
4333
4334 // Assign locations to all of the incoming aggregate by value arguments.
4335 // Aggregates passed by value are stored in the local variable space of the
4336 // caller's stack frame, right above the parameter list area.
4337 SmallVector<CCValAssign, 16> ByValArgLocs;
4338 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4339 ByValArgLocs, *DAG.getContext());
4340
4341 // Reserve stack space for the allocations in CCInfo.
4342 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
4343
4344 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4345
4346 // Area that is at least reserved in the caller of this function.
4347 unsigned MinReservedArea = CCByValInfo.getStackSize();
4348 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4349
4350 // Set the size that is at least reserved in caller of this function. Tail
4351 // call optimized function's reserved stack space needs to be aligned so that
4352 // taking the difference between two stack areas will result in an aligned
4353 // stack.
4354 MinReservedArea =
4355 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4356 FuncInfo->setMinReservedArea(MinReservedArea);
4357
4359
4360 // If the function takes variable number of arguments, make a frame index for
4361 // the start of the first vararg value... for expansion of llvm.va_start.
4362 if (isVarArg) {
4363 static const MCPhysReg GPArgRegs[] = {
4364 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4365 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4366 };
4367 const unsigned NumGPArgRegs = std::size(GPArgRegs);
4368
4369 static const MCPhysReg FPArgRegs[] = {
4370 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4371 PPC::F8
4372 };
4373 unsigned NumFPArgRegs = std::size(FPArgRegs);
4374
4375 if (useSoftFloat() || hasSPE())
4376 NumFPArgRegs = 0;
4377
4378 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4379 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4380
4381 // Make room for NumGPArgRegs and NumFPArgRegs.
4382 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4383 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4384
4386 PtrVT.getSizeInBits() / 8, CCInfo.getStackSize(), true));
4387
4388 FuncInfo->setVarArgsFrameIndex(
4389 MFI.CreateStackObject(Depth, Align(8), false));
4390 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4391
4392 // The fixed integer arguments of a variadic function are stored to the
4393 // VarArgsFrameIndex on the stack so that they may be loaded by
4394 // dereferencing the result of va_next.
4395 for (MCPhysReg GPArgReg : GPArgRegs) {
4396 // Get an existing live-in vreg, or add a new one.
4397 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgReg);
4398 if (!VReg)
4399 VReg = MF.addLiveIn(GPArgReg, &PPC::GPRCRegClass);
4400
4401 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4402 SDValue Store =
4403 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4404 MemOps.push_back(Store);
4405 // Increment the address by four for the next argument to store
4406 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4407 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4408 }
4409
4410 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4411 // is set.
4412 // The double arguments are stored to the VarArgsFrameIndex
4413 // on the stack.
4414 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4415 // Get an existing live-in vreg, or add a new one.
4416 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4417 if (!VReg)
4418 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4419
4420 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4421 SDValue Store =
4422 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4423 MemOps.push_back(Store);
4424 // Increment the address by eight for the next argument to store
4425 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4426 PtrVT);
4427 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4428 }
4429 }
4430
4431 if (!MemOps.empty())
4432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4433
4434 return Chain;
4435}
4436
4437// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4438// value to MVT::i64 and then truncate to the correct register size.
4439SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4440 EVT ObjectVT, SelectionDAG &DAG,
4441 SDValue ArgVal,
4442 const SDLoc &dl) const {
4443 if (Flags.isSExt())
4444 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4445 DAG.getValueType(ObjectVT));
4446 else if (Flags.isZExt())
4447 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4448 DAG.getValueType(ObjectVT));
4449
4450 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4451}
4452
4453SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4454 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4455 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4456 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4457 // TODO: add description of PPC stack frame format, or at least some docs.
4458 //
4459 bool isELFv2ABI = Subtarget.isELFv2ABI();
4460 bool isLittleEndian = Subtarget.isLittleEndian();
4462 MachineFrameInfo &MFI = MF.getFrameInfo();
4463 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4464
4465 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4466 "fastcc not supported on varargs functions");
4467
4468 EVT PtrVT = getPointerTy(MF.getDataLayout());
4469 // Potential tail calls could cause overwriting of argument stack slots.
4470 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4471 (CallConv == CallingConv::Fast));
4472 unsigned PtrByteSize = 8;
4473 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4474
4475 static const MCPhysReg GPR[] = {
4476 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4477 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4478 };
4479 static const MCPhysReg VR[] = {
4480 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4481 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4482 };
4483
4484 const unsigned Num_GPR_Regs = std::size(GPR);
4485 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4486 const unsigned Num_VR_Regs = std::size(VR);
4487
4488 // Do a first pass over the arguments to determine whether the ABI
4489 // guarantees that our caller has allocated the parameter save area
4490 // on its stack frame. In the ELFv1 ABI, this is always the case;
4491 // in the ELFv2 ABI, it is true if this is a vararg function or if
4492 // any parameter is located in a stack slot.
4493
4494 bool HasParameterArea = !isELFv2ABI || isVarArg;
4495 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4496 unsigned NumBytes = LinkageSize;
4497 unsigned AvailableFPRs = Num_FPR_Regs;
4498 unsigned AvailableVRs = Num_VR_Regs;
4499 for (const ISD::InputArg &In : Ins) {
4500 if (In.Flags.isNest())
4501 continue;
4502
4503 if (CalculateStackSlotUsed(In.VT, In.ArgVT, In.Flags, PtrByteSize,
4504 LinkageSize, ParamAreaSize, NumBytes,
4505 AvailableFPRs, AvailableVRs))
4506 HasParameterArea = true;
4507 }
4508
4509 // Add DAG nodes to load the arguments or copy them out of registers. On
4510 // entry to a function on PPC, the arguments start after the linkage area,
4511 // although the first ones are often in registers.
4512
4513 unsigned ArgOffset = LinkageSize;
4514 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4517 unsigned CurArgIdx = 0;
4518 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4519 SDValue ArgVal;
4520 bool needsLoad = false;
4521 EVT ObjectVT = Ins[ArgNo].VT;
4522 EVT OrigVT = Ins[ArgNo].ArgVT;
4523 unsigned ObjSize = ObjectVT.getStoreSize();
4524 unsigned ArgSize = ObjSize;
4525 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4526 if (Ins[ArgNo].isOrigArg()) {
4527 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4528 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4529 }
4530 // We re-align the argument offset for each argument, except when using the
4531 // fast calling convention, when we need to make sure we do that only when
4532 // we'll actually use a stack slot.
4533 unsigned CurArgOffset;
4535 auto ComputeArgOffset = [&]() {
4536 /* Respect alignment of argument on the stack. */
4537 Alignment =
4538 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4539 ArgOffset = alignTo(ArgOffset, Alignment);
4540 CurArgOffset = ArgOffset;
4541 };
4542
4543 if (CallConv != CallingConv::Fast) {
4544 ComputeArgOffset();
4545
4546 /* Compute GPR index associated with argument offset. */
4547 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4548 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4549 }
4550
4551 // FIXME the codegen can be much improved in some cases.
4552 // We do not have to keep everything in memory.
4553 if (Flags.isByVal()) {
4554 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4555
4556 if (CallConv == CallingConv::Fast)
4557 ComputeArgOffset();
4558
4559 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4560 ObjSize = Flags.getByValSize();
4561 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4562 // Empty aggregate parameters do not take up registers. Examples:
4563 // struct { } a;
4564 // union { } b;
4565 // int c[0];
4566 // etc. However, we have to provide a place-holder in InVals, so
4567 // pretend we have an 8-byte item at the current address for that
4568 // purpose.
4569 if (!ObjSize) {
4570 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4571 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4572 InVals.push_back(FIN);
4573 continue;
4574 }
4575
4576 // Create a stack object covering all stack doublewords occupied
4577 // by the argument. If the argument is (fully or partially) on
4578 // the stack, or if the argument is fully in registers but the
4579 // caller has allocated the parameter save anyway, we can refer
4580 // directly to the caller's stack frame. Otherwise, create a
4581 // local copy in our own frame.
4582 int FI;
4583 if (HasParameterArea ||
4584 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4585 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4586 else
4587 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4588 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4589
4590 // Handle aggregates smaller than 8 bytes.
4591 if (ObjSize < PtrByteSize) {
4592 // The value of the object is its address, which differs from the
4593 // address of the enclosing doubleword on big-endian systems.
4594 SDValue Arg = FIN;
4595 if (!isLittleEndian) {
4596 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4597 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4598 }
4599 InVals.push_back(Arg);
4600
4601 if (GPR_idx != Num_GPR_Regs) {
4602 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4603 FuncInfo->addLiveInAttr(VReg, Flags);
4604 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4605 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4606 SDValue Store =
4607 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4608 MachinePointerInfo(&*FuncArg), ObjType);
4609 MemOps.push_back(Store);
4610 }
4611 // Whether we copied from a register or not, advance the offset
4612 // into the parameter save area by a full doubleword.
4613 ArgOffset += PtrByteSize;
4614 continue;
4615 }
4616
4617 // The value of the object is its address, which is the address of
4618 // its first stack doubleword.
4619 InVals.push_back(FIN);
4620
4621 // Store whatever pieces of the object are in registers to memory.
4622 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4623 if (GPR_idx == Num_GPR_Regs)
4624 break;
4625
4626 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4627 FuncInfo->addLiveInAttr(VReg, Flags);
4628 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4629 SDValue Addr = FIN;
4630 if (j) {
4631 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4632 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4633 }
4634 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4635 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4636 SDValue Store =
4637 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4638 MachinePointerInfo(&*FuncArg, j), ObjType);
4639 MemOps.push_back(Store);
4640 ++GPR_idx;
4641 }
4642 ArgOffset += ArgSize;
4643 continue;
4644 }
4645
4646 switch (ObjectVT.getSimpleVT().SimpleTy) {
4647 default: llvm_unreachable("Unhandled argument type!");
4648 case MVT::i1:
4649 case MVT::i32:
4650 case MVT::i64:
4651 if (Flags.isNest()) {
4652 // The 'nest' parameter, if any, is passed in R11.
4653 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4654 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4655
4656 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4657 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4658
4659 break;
4660 }
4661
4662 // These can be scalar arguments or elements of an integer array type
4663 // passed directly. Clang may use those instead of "byval" aggregate
4664 // types to avoid forcing arguments to memory unnecessarily.
4665 if (GPR_idx != Num_GPR_Regs) {
4666 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4667 FuncInfo->addLiveInAttr(VReg, Flags);
4668 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4669
4670 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4671 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4672 // value to MVT::i64 and then truncate to the correct register size.
4673 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4674 } else {
4675 if (CallConv == CallingConv::Fast)
4676 ComputeArgOffset();
4677
4678 needsLoad = true;
4679 ArgSize = PtrByteSize;
4680 }
4681 if (CallConv != CallingConv::Fast || needsLoad)
4682 ArgOffset += 8;
4683 break;
4684
4685 case MVT::f32:
4686 case MVT::f64:
4687 // These can be scalar arguments or elements of a float array type
4688 // passed directly. The latter are used to implement ELFv2 homogenous
4689 // float aggregates.
4690 if (FPR_idx != Num_FPR_Regs) {
4691 unsigned VReg;
4692
4693 if (ObjectVT == MVT::f32)
4694 VReg = MF.addLiveIn(FPR[FPR_idx],
4695 Subtarget.hasP8Vector()
4696 ? &PPC::VSSRCRegClass
4697 : &PPC::F4RCRegClass);
4698 else
4699 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4700 ? &PPC::VSFRCRegClass
4701 : &PPC::F8RCRegClass);
4702
4703 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4704 ++FPR_idx;
4705 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4706 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4707 // once we support fp <-> gpr moves.
4708
4709 // This can only ever happen in the presence of f32 array types,
4710 // since otherwise we never run out of FPRs before running out
4711 // of GPRs.
4712 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4713 FuncInfo->addLiveInAttr(VReg, Flags);
4714 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4715
4716 if (ObjectVT == MVT::f32) {
4717 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4718 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4719 DAG.getConstant(32, dl, MVT::i32));
4720 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4721 }
4722
4723 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4724 } else {
4725 if (CallConv == CallingConv::Fast)
4726 ComputeArgOffset();
4727
4728 needsLoad = true;
4729 }
4730
4731 // When passing an array of floats, the array occupies consecutive
4732 // space in the argument area; only round up to the next doubleword
4733 // at the end of the array. Otherwise, each float takes 8 bytes.
4734 if (CallConv != CallingConv::Fast || needsLoad) {
4735 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4736 ArgOffset += ArgSize;
4737 if (Flags.isInConsecutiveRegsLast())
4738 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4739 }
4740 break;
4741 case MVT::v4f32:
4742 case MVT::v4i32:
4743 case MVT::v8i16:
4744 case MVT::v16i8:
4745 case MVT::v2f64:
4746 case MVT::v2i64:
4747 case MVT::v1i128:
4748 case MVT::f128:
4749 // These can be scalar arguments or elements of a vector array type
4750 // passed directly. The latter are used to implement ELFv2 homogenous
4751 // vector aggregates.
4752 if (VR_idx != Num_VR_Regs) {
4753 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4754 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4755 ++VR_idx;
4756 } else {
4757 if (CallConv == CallingConv::Fast)
4758 ComputeArgOffset();
4759 needsLoad = true;
4760 }
4761 if (CallConv != CallingConv::Fast || needsLoad)
4762 ArgOffset += 16;
4763 break;
4764 }
4765
4766 // We need to load the argument to a virtual register if we determined
4767 // above that we ran out of physical registers of the appropriate type.
4768 if (needsLoad) {
4769 if (ObjSize < ArgSize && !isLittleEndian)
4770 CurArgOffset += ArgSize - ObjSize;
4771 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4772 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4773 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4774 }
4775
4776 InVals.push_back(ArgVal);
4777 }
4778
4779 // Area that is at least reserved in the caller of this function.
4780 unsigned MinReservedArea;
4781 if (HasParameterArea)
4782 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4783 else
4784 MinReservedArea = LinkageSize;
4785
4786 // Set the size that is at least reserved in caller of this function. Tail
4787 // call optimized functions' reserved stack space needs to be aligned so that
4788 // taking the difference between two stack areas will result in an aligned
4789 // stack.
4790 MinReservedArea =
4791 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4792 FuncInfo->setMinReservedArea(MinReservedArea);
4793
4794 // If the function takes variable number of arguments, make a frame index for
4795 // the start of the first vararg value... for expansion of llvm.va_start.
4796 // On ELFv2ABI spec, it writes:
4797 // C programs that are intended to be *portable* across different compilers
4798 // and architectures must use the header file <stdarg.h> to deal with variable
4799 // argument lists.
4800 if (isVarArg && MFI.hasVAStart()) {
4801 int Depth = ArgOffset;
4802
4803 FuncInfo->setVarArgsFrameIndex(
4804 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4805 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4806
4807 // If this function is vararg, store any remaining integer argument regs
4808 // to their spots on the stack so that they may be loaded by dereferencing
4809 // the result of va_next.
4810 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4811 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4812 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4813 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4814 SDValue Store =
4815 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4816 MemOps.push_back(Store);
4817 // Increment the address by four for the next argument to store
4818 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4819 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4820 }
4821 }
4822
4823 if (!MemOps.empty())
4824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4825
4826 return Chain;
4827}
4828
4829/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4830/// adjusted to accommodate the arguments for the tailcall.
4831static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4832 unsigned ParamSize) {
4833
4834 if (!isTailCall) return 0;
4835
4837 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4838 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4839 // Remember only if the new adjustment is bigger.
4840 if (SPDiff < FI->getTailCallSPDelta())
4841 FI->setTailCallSPDelta(SPDiff);
4842
4843 return SPDiff;
4844}
4845
4846static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV);
4847
4848static bool callsShareTOCBase(const Function *Caller,
4849 const GlobalValue *CalleeGV,
4850 const TargetMachine &TM) {
4851 // It does not make sense to call callsShareTOCBase() with a caller that
4852 // is PC Relative since PC Relative callers do not have a TOC.
4853#ifndef NDEBUG
4854 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4855 assert(!STICaller->isUsingPCRelativeCalls() &&
4856 "PC Relative callers do not have a TOC and cannot share a TOC Base");
4857#endif
4858
4859 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4860 // don't have enough information to determine if the caller and callee share
4861 // the same TOC base, so we have to pessimistically assume they don't for
4862 // correctness.
4863 if (!CalleeGV)
4864 return false;
4865
4866 // If the callee is preemptable, then the static linker will use a plt-stub
4867 // which saves the toc to the stack, and needs a nop after the call
4868 // instruction to convert to a toc-restore.
4869 if (!TM.shouldAssumeDSOLocal(CalleeGV))
4870 return false;
4871
4872 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4873 // We may need a TOC restore in the situation where the caller requires a
4874 // valid TOC but the callee is PC Relative and does not.
4875 const Function *F = dyn_cast<Function>(CalleeGV);
4876 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(CalleeGV);
4877
4878 // If we have an Alias we can try to get the function from there.
4879 if (Alias) {
4880 const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4881 F = dyn_cast<Function>(GlobalObj);
4882 }
4883
4884 // If we still have no valid function pointer we do not have enough
4885 // information to determine if the callee uses PC Relative calls so we must
4886 // assume that it does.
4887 if (!F)
4888 return false;
4889
4890 // If the callee uses PC Relative we cannot guarantee that the callee won't
4891 // clobber the TOC of the caller and so we must assume that the two
4892 // functions do not share a TOC base.
4893 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4894 if (STICallee->isUsingPCRelativeCalls())
4895 return false;
4896
4897 // If the GV is not a strong definition then we need to assume it can be
4898 // replaced by another function at link time. The function that replaces
4899 // it may not share the same TOC as the caller since the callee may be
4900 // replaced by a PC Relative version of the same function.
4901 if (!CalleeGV->isStrongDefinitionForLinker())
4902 return false;
4903
4904 // The medium and large code models are expected to provide a sufficiently
4905 // large TOC to provide all data addressing needs of a module with a
4906 // single TOC.
4907 if (CodeModel::Medium == TM.getCodeModel() ||
4909 return true;
4910
4911 // Any explicitly-specified sections and section prefixes must also match.
4912 // Also, if we're using -ffunction-sections, then each function is always in
4913 // a different section (the same is true for COMDAT functions).
4914 if (TM.getFunctionSections() || CalleeGV->hasComdat() ||
4915 Caller->hasComdat() || CalleeGV->getSection() != Caller->getSection())
4916 return false;
4917 if (const auto *F = dyn_cast<Function>(CalleeGV)) {
4918 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4919 return false;
4920 }
4921
4922 return true;
4923}
4924
4925static bool
4927 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4928 assert(Subtarget.is64BitELFABI());
4929
4930 const unsigned PtrByteSize = 8;
4931 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4932
4933 static const MCPhysReg GPR[] = {
4934 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4935 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4936 };
4937 static const MCPhysReg VR[] = {
4938 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4939 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4940 };
4941
4942 const unsigned NumGPRs = std::size(GPR);
4943 const unsigned NumFPRs = 13;
4944 const unsigned NumVRs = std::size(VR);
4945 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4946
4947 unsigned NumBytes = LinkageSize;
4948 unsigned AvailableFPRs = NumFPRs;
4949 unsigned AvailableVRs = NumVRs;
4950
4951 for (const ISD::OutputArg& Param : Outs) {
4952 if (Param.Flags.isNest()) continue;
4953
4954 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4955 LinkageSize, ParamAreaSize, NumBytes,
4956 AvailableFPRs, AvailableVRs))
4957 return true;
4958 }
4959 return false;
4960}
4961
4962static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4963 if (CB.arg_size() != CallerFn->arg_size())
4964 return false;
4965
4966 auto CalleeArgIter = CB.arg_begin();
4967 auto CalleeArgEnd = CB.arg_end();
4968 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4969
4970 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4971 const Value* CalleeArg = *CalleeArgIter;
4972 const Value* CallerArg = &(*CallerArgIter);
4973 if (CalleeArg == CallerArg)
4974 continue;
4975
4976 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4977 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4978 // }
4979 // 1st argument of callee is undef and has the same type as caller.
4980 if (CalleeArg->getType() == CallerArg->getType() &&
4981 isa<UndefValue>(CalleeArg))
4982 continue;
4983
4984 return false;
4985 }
4986
4987 return true;
4988}
4989
4990// Returns true if TCO is possible between the callers and callees
4991// calling conventions.
4992static bool
4994 CallingConv::ID CalleeCC) {
4995 // Tail calls are possible with fastcc and ccc.
4996 auto isTailCallableCC = [] (CallingConv::ID CC){
4997 return CC == CallingConv::C || CC == CallingConv::Fast;
4998 };
4999 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
5000 return false;
5001
5002 // We can safely tail call both fastcc and ccc callees from a c calling
5003 // convention caller. If the caller is fastcc, we may have less stack space
5004 // than a non-fastcc caller with the same signature so disable tail-calls in
5005 // that case.
5006 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
5007}
5008
5009bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
5010 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5011 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5013 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5014 bool isCalleeExternalSymbol) const {
5015 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
5016
5017 if (DisableSCO && !TailCallOpt) return false;
5018
5019 // Variadic argument functions are not supported.
5020 if (isVarArg) return false;
5021
5022 // Check that the calling conventions are compatible for tco.
5023 if (!areCallingConvEligibleForTCO_64SVR4(CallerCC, CalleeCC))
5024 return false;
5025
5026 // Caller contains any byval parameter is not supported.
5027 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5028 return false;
5029
5030 // Callee contains any byval parameter is not supported, too.
5031 // Note: This is a quick work around, because in some cases, e.g.
5032 // caller's stack size > callee's stack size, we are still able to apply
5033 // sibling call optimization. For example, gcc is able to do SCO for caller1
5034 // in the following example, but not for caller2.
5035 // struct test {
5036 // long int a;
5037 // char ary[56];
5038 // } gTest;
5039 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
5040 // b->a = v.a;
5041 // return 0;
5042 // }
5043 // void caller1(struct test a, struct test c, struct test *b) {
5044 // callee(gTest, b); }
5045 // void caller2(struct test *b) { callee(gTest, b); }
5046 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
5047 return false;
5048
5049 // If callee and caller use different calling conventions, we cannot pass
5050 // parameters on stack since offsets for the parameter area may be different.
5051 if (CallerCC != CalleeCC && needStackSlotPassParameters(Subtarget, Outs))
5052 return false;
5053
5054 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
5055 // the caller and callee share the same TOC for TCO/SCO. If the caller and
5056 // callee potentially have different TOC bases then we cannot tail call since
5057 // we need to restore the TOC pointer after the call.
5058 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
5059 // We cannot guarantee this for indirect calls or calls to external functions.
5060 // When PC-Relative addressing is used, the concept of the TOC is no longer
5061 // applicable so this check is not required.
5062 // Check first for indirect calls.
5063 if (!Subtarget.isUsingPCRelativeCalls() &&
5064 !isFunctionGlobalAddress(CalleeGV) && !isCalleeExternalSymbol)
5065 return false;
5066
5067 // Check if we share the TOC base.
5068 if (!Subtarget.isUsingPCRelativeCalls() &&
5069 !callsShareTOCBase(CallerFunc, CalleeGV, getTargetMachine()))
5070 return false;
5071
5072 // TCO allows altering callee ABI, so we don't have to check further.
5073 if (CalleeCC == CallingConv::Fast && TailCallOpt)
5074 return true;
5075
5076 if (DisableSCO) return false;
5077
5078 // If callee use the same argument list that caller is using, then we can
5079 // apply SCO on this case. If it is not, then we need to check if callee needs
5080 // stack for passing arguments.
5081 // PC Relative tail calls may not have a CallBase.
5082 // If there is no CallBase we cannot verify if we have the same argument
5083 // list so assume that we don't have the same argument list.
5084 if (CB && !hasSameArgumentList(CallerFunc, *CB) &&
5085 needStackSlotPassParameters(Subtarget, Outs))
5086 return false;
5087 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5088 return false;
5089
5090 return true;
5091}
5092
5093/// IsEligibleForTailCallOptimization - Check whether the call is eligible
5094/// for tail call optimization. Targets which want to do tail call
5095/// optimization should implement this function.
5096bool PPCTargetLowering::IsEligibleForTailCallOptimization(
5097 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5098 CallingConv::ID CallerCC, bool isVarArg,
5099 const SmallVectorImpl<ISD::InputArg> &Ins) const {
5100 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5101 return false;
5102
5103 // Variable argument functions are not supported.
5104 if (isVarArg)
5105 return false;
5106
5107 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5108 // Functions containing by val parameters are not supported.
5109 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5110 return false;
5111
5112 // Non-PIC/GOT tail calls are supported.
5113 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5114 return true;
5115
5116 // At the moment we can only do local tail calls (in same module, hidden
5117 // or protected) if we are generating PIC.
5118 if (CalleeGV)
5119 return CalleeGV->hasHiddenVisibility() ||
5120 CalleeGV->hasProtectedVisibility();
5121 }
5122
5123 return false;
5124}
5125
5126/// isCallCompatibleAddress - Return the immediate to use if the specified
5127/// 32-bit value is representable in the immediate field of a BxA instruction.
5130 if (!C) return nullptr;
5131
5132 int Addr = C->getZExtValue();
5133 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
5134 SignExtend32<26>(Addr) != Addr)
5135 return nullptr; // Top 6 bits have to be sext of immediate.
5136
5137 return DAG
5139 (int)C->getZExtValue() >> 2, SDLoc(Op),
5141 .getNode();
5142}
5143
5144namespace {
5145
5146struct TailCallArgumentInfo {
5147 SDValue Arg;
5148 SDValue FrameIdxOp;
5149 int FrameIdx = 0;
5150
5151 TailCallArgumentInfo() = default;
5152};
5153
5154} // end anonymous namespace
5155
5156/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5158 SelectionDAG &DAG, SDValue Chain,
5159 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5160 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5161 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5162 SDValue Arg = TailCallArgs[i].Arg;
5163 SDValue FIN = TailCallArgs[i].FrameIdxOp;
5164 int FI = TailCallArgs[i].FrameIdx;
5165 // Store relative to framepointer.
5166 MemOpChains.push_back(DAG.getStore(
5167 Chain, dl, Arg, FIN,
5169 }
5170}
5171
5172/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5173/// the appropriate stack slot for the tail call optimized function call.
5175 SDValue OldRetAddr, SDValue OldFP,
5176 int SPDiff, const SDLoc &dl) {
5177 if (SPDiff) {
5178 // Calculate the new stack slot for the return address.
5180 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5181 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5182 int SlotSize = Subtarget.isPPC64() ? 8 : 4;
5183 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5184 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5185 NewRetAddrLoc, true);
5186 SDValue NewRetAddrFrIdx =
5187 DAG.getFrameIndex(NewRetAddr, Subtarget.getScalarIntVT());
5188 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5189 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5190 }
5191 return Chain;
5192}
5193
5194/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5195/// the position of the argument.
5197 SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg,
5198 int SPDiff, unsigned ArgOffset,
5199 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5200 int Offset = ArgOffset + SPDiff;
5201 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5202 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5203 EVT VT = IsPPC64 ? MVT::i64 : MVT::i32;
5204 SDValue FIN = DAG.getFrameIndex(FI, VT);
5205 TailCallArgumentInfo Info;
5206 Info.Arg = Arg;
5207 Info.FrameIdxOp = FIN;
5208 Info.FrameIdx = FI;
5209 TailCallArguments.push_back(Info);
5210}
5211
5212/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5213/// stack slot. Returns the chain as result and the loaded frame pointers in
5214/// LROpOut/FPOpout. Used when tail calling.
5215SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5216 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5217 SDValue &FPOpOut, const SDLoc &dl) const {
5218 if (SPDiff) {
5219 // Load the LR and FP stack slot for later adjusting.
5220 LROpOut = getReturnAddrFrameIndex(DAG);
5221 LROpOut = DAG.getLoad(Subtarget.getScalarIntVT(), dl, Chain, LROpOut,
5222 MachinePointerInfo());
5223 Chain = SDValue(LROpOut.getNode(), 1);
5224 }
5225 return Chain;
5226}
5227
5228/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5229/// by "Src" to address "Dst" of size "Size". Alignment information is
5230/// specified by the specific parameter attribute. The copy will be passed as
5231/// a byval function parameter.
5232/// Sometimes what we are copying is the end of a larger object, the part that
5233/// does not fit in registers.
5235 SDValue Chain, ISD::ArgFlagsTy Flags,
5236 SelectionDAG &DAG, const SDLoc &dl) {
5237 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5238 Align Alignment = Flags.getNonZeroByValAlign();
5239 return DAG.getMemcpy(
5240 Chain, dl, Dst, Src, SizeNode, Alignment, Alignment, false, false,
5241 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
5242}
5243
5244/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5245/// tail calls.
5247 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5248 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5249 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5250 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5252 if (!isTailCall) {
5253 if (isVector) {
5254 SDValue StackPtr;
5255 if (isPPC64)
5256 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5257 else
5258 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5259 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5260 DAG.getConstant(ArgOffset, dl, PtrVT));
5261 }
5262 MemOpChains.push_back(
5263 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5264 // Calculate and remember argument location.
5265 } else
5266 CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5267 TailCallArguments);
5268}
5269
5270static void
5272 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5273 SDValue FPOp,
5274 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5275 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5276 // might overwrite each other in case of tail call optimization.
5277 SmallVector<SDValue, 8> MemOpChains2;
5278 // Do not flag preceding copytoreg stuff together with the following stuff.
5279 InGlue = SDValue();
5280 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5281 MemOpChains2, dl);
5282 if (!MemOpChains2.empty())
5283 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5284
5285 // Store the return address to the appropriate stack slot.
5286 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5287
5288 // Emit callseq_end just before tailcall node.
5289 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
5290 InGlue = Chain.getValue(1);
5291}
5292
5293// Is this global address that of a function that can be called by name? (as
5294// opposed to something that must hold a descriptor for an indirect call).
5295static bool isFunctionGlobalAddress(const GlobalValue *GV) {
5296 if (GV) {
5297 if (GV->isThreadLocal())
5298 return false;
5299
5300 return GV->getValueType()->isFunctionTy();
5301 }
5302
5303 return false;
5304}
5305
5306SDValue PPCTargetLowering::LowerCallResult(
5307 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
5308 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5309 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5311 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5312 *DAG.getContext());
5313
5314 CCRetInfo.AnalyzeCallResult(
5315 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5317 : RetCC_PPC);
5318
5319 // Copy all of the result registers out of their specified physreg.
5320 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5321 CCValAssign &VA = RVLocs[i];
5322 assert(VA.isRegLoc() && "Can only return in registers!");
5323
5324 SDValue Val;
5325
5326 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5327 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5328 InGlue);
5329 Chain = Lo.getValue(1);
5330 InGlue = Lo.getValue(2);
5331 VA = RVLocs[++i]; // skip ahead to next loc
5332 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5333 InGlue);
5334 Chain = Hi.getValue(1);
5335 InGlue = Hi.getValue(2);
5336 if (!Subtarget.isLittleEndian())
5337 std::swap (Lo, Hi);
5338 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5339 } else {
5340 Val = DAG.getCopyFromReg(Chain, dl,
5341 VA.getLocReg(), VA.getLocVT(), InGlue);
5342 Chain = Val.getValue(1);
5343 InGlue = Val.getValue(2);
5344 }
5345
5346 switch (VA.getLocInfo()) {
5347 default: llvm_unreachable("Unknown loc info!");
5348 case CCValAssign::Full: break;
5349 case CCValAssign::AExt:
5350 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5351 break;
5352 case CCValAssign::ZExt:
5353 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5354 DAG.getValueType(VA.getValVT()));
5355 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5356 break;
5357 case CCValAssign::SExt:
5358 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5359 DAG.getValueType(VA.getValVT()));
5360 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5361 break;
5362 }
5363
5364 InVals.push_back(Val);
5365 }
5366
5367 return Chain;
5368}
5369
5370static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5371 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5372 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5373 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5374
5375 // PatchPoint calls are not indirect.
5376 if (isPatchPoint)
5377 return false;
5378
5380 return false;
5381
5382 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5383 // becuase the immediate function pointer points to a descriptor instead of
5384 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5385 // pointer immediate points to the global entry point, while the BLA would
5386 // need to jump to the local entry point (see rL211174).
5387 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5388 isBLACompatibleAddress(Callee, DAG))
5389 return false;
5390
5391 return true;
5392}
5393
5394// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5395static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5396 return Subtarget.isAIXABI() ||
5397 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5398}
5399
5401 const Function &Caller, const SDValue &Callee,
5402 const PPCSubtarget &Subtarget,
5403 const TargetMachine &TM,
5404 bool IsStrictFPCall = false) {
5405 if (CFlags.IsTailCall)
5406 return PPCISD::TC_RETURN;
5407
5408 unsigned RetOpc = 0;
5409 // This is a call through a function pointer.
5410 if (CFlags.IsIndirect) {
5411 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5412 // indirect calls. The save of the caller's TOC pointer to the stack will be
5413 // inserted into the DAG as part of call lowering. The restore of the TOC
5414 // pointer is modeled by using a pseudo instruction for the call opcode that
5415 // represents the 2 instruction sequence of an indirect branch and link,
5416 // immediately followed by a load of the TOC pointer from the stack save
5417 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5418 // as it is not saved or used.
5419 if (Subtarget.usePointerGlueHelper())
5420 RetOpc = PPCISD::BL_LOAD_TOC;
5421 else
5422 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5423 : PPCISD::BCTRL;
5424 } else if (Subtarget.isUsingPCRelativeCalls()) {
5425 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5426 RetOpc = PPCISD::CALL_NOTOC;
5427 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) {
5428 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5429 // immediately following the call instruction if the caller and callee may
5430 // have different TOC bases. At link time if the linker determines the calls
5431 // may not share a TOC base, the call is redirected to a trampoline inserted
5432 // by the linker. The trampoline will (among other things) save the callers
5433 // TOC pointer at an ABI designated offset in the linkage area and the
5434 // linker will rewrite the nop to be a load of the TOC pointer from the
5435 // linkage area into gpr2.
5436 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5437 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5438 RetOpc =
5439 callsShareTOCBase(&Caller, GV, TM) ? PPCISD::CALL : PPCISD::CALL_NOP;
5440 } else
5441 RetOpc = PPCISD::CALL;
5442 if (IsStrictFPCall) {
5443 switch (RetOpc) {
5444 default:
5445 llvm_unreachable("Unknown call opcode");
5446 case PPCISD::BCTRL_LOAD_TOC:
5447 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5448 break;
5449 case PPCISD::BCTRL:
5450 RetOpc = PPCISD::BCTRL_RM;
5451 break;
5452 case PPCISD::BL_LOAD_TOC:
5453 RetOpc = PPCISD::BL_LOAD_TOC_RM;
5454 break;
5455 case PPCISD::CALL_NOTOC:
5456 RetOpc = PPCISD::CALL_NOTOC_RM;
5457 break;
5458 case PPCISD::CALL:
5459 RetOpc = PPCISD::CALL_RM;
5460 break;
5461 case PPCISD::CALL_NOP:
5462 RetOpc = PPCISD::CALL_NOP_RM;
5463 break;
5464 }
5465 }
5466 return RetOpc;
5467}
5468
5469static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5470 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5471 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5472 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5473 return SDValue(Dest, 0);
5474
5475 // Returns true if the callee is local, and false otherwise.
5476 auto isLocalCallee = [&]() {
5478 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5479
5480 return DAG.getTarget().shouldAssumeDSOLocal(GV) &&
5482 };
5483
5484 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5485 // a static relocation model causes some versions of GNU LD (2.17.50, at
5486 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5487 // built with secure-PLT.
5488 bool UsePlt =
5489 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5491
5492 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5493 const TargetMachine &TM = Subtarget.getTargetMachine();
5495 auto *S =
5496 static_cast<MCSymbolXCOFF *>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5497
5499 return DAG.getMCSymbol(S, PtrVT);
5500 };
5501
5502 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5503 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5504 if (isFunctionGlobalAddress(GV)) {
5505 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5506
5507 if (Subtarget.isAIXABI()) {
5508 return getAIXFuncEntryPointSymbolSDNode(GV);
5509 }
5510 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5511 UsePlt ? PPCII::MO_PLT : 0);
5512 }
5513
5515 const char *SymName = S->getSymbol();
5516 if (Subtarget.isAIXABI()) {
5517 // If there exists a user-declared function whose name is the same as the
5518 // ExternalSymbol's, then we pick up the user-declared version.
5520 if (const Function *F =
5521 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5522 return getAIXFuncEntryPointSymbolSDNode(F);
5523
5524 // On AIX, direct function calls reference the symbol for the function's
5525 // entry point, which is named by prepending a "." before the function's
5526 // C-linkage name. A Qualname is returned here because an external
5527 // function entry point is a csect with XTY_ER property.
5528 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5529 auto &Context = DAG.getMachineFunction().getContext();
5530 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5531 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5533 return Sec->getQualNameSymbol();
5534 };
5535
5536 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5537 }
5538 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5539 UsePlt ? PPCII::MO_PLT : 0);
5540 }
5541
5542 // No transformation needed.
5543 assert(Callee.getNode() && "What no callee?");
5544 return Callee;
5545}
5546
5548 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5549 "Expected a CALLSEQ_STARTSDNode.");
5550
5551 // The last operand is the chain, except when the node has glue. If the node
5552 // has glue, then the last operand is the glue, and the chain is the second
5553 // last operand.
5554 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5555 if (LastValue.getValueType() != MVT::Glue)
5556 return LastValue;
5557
5558 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5559}
5560
5561// Creates the node that moves a functions address into the count register
5562// to prepare for an indirect call instruction.
5563static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5564 SDValue &Glue, SDValue &Chain,
5565 const SDLoc &dl) {
5566 SDValue MTCTROps[] = {Chain, Callee, Glue};
5567 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5568 Chain = DAG.getNode(PPCISD::MTCTR, dl, ReturnTypes,
5569 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5570 // The glue is the second value produced.
5571 Glue = Chain.getValue(1);
5572}
5573
5575 SDValue &Glue, SDValue &Chain,
5576 SDValue CallSeqStart,
5577 const CallBase *CB, const SDLoc &dl,
5578 bool hasNest,
5579 const PPCSubtarget &Subtarget) {
5580 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5581 // entry point, but to the function descriptor (the function entry point
5582 // address is part of the function descriptor though).
5583 // The function descriptor is a three doubleword structure with the
5584 // following fields: function entry point, TOC base address and
5585 // environment pointer.
5586 // Thus for a call through a function pointer, the following actions need
5587 // to be performed:
5588 // 1. Save the TOC of the caller in the TOC save area of its stack
5589 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5590 // 2. Load the address of the function entry point from the function
5591 // descriptor.
5592 // 3. Load the TOC of the callee from the function descriptor into r2.
5593 // 4. Load the environment pointer from the function descriptor into
5594 // r11.
5595 // 5. Branch to the function entry point address.
5596 // 6. On return of the callee, the TOC of the caller needs to be
5597 // restored (this is done in FinishCall()).
5598 //
5599 // The loads are scheduled at the beginning of the call sequence, and the
5600 // register copies are flagged together to ensure that no other
5601 // operations can be scheduled in between. E.g. without flagging the
5602 // copies together, a TOC access in the caller could be scheduled between
5603 // the assignment of the callee TOC and the branch to the callee, which leads
5604 // to incorrect code.
5605
5606 // Start by loading the function address from the descriptor.
5607 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5608 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5612
5613 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5614
5615 // Registers used in building the DAG.
5616 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5617 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5618
5619 // Offsets of descriptor members.
5620 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5621 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5622
5623 const MVT RegVT = Subtarget.getScalarIntVT();
5624 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
5625
5626 // One load for the functions entry point address.
5627 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5628 Alignment, MMOFlags);
5629
5630 // One for loading the TOC anchor for the module that contains the called
5631 // function.
5632 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5633 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5634 SDValue TOCPtr =
5635 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5636 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5637
5638 // One for loading the environment pointer.
5639 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5640 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5641 SDValue LoadEnvPtr =
5642 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5643 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5644
5645
5646 // Then copy the newly loaded TOC anchor to the TOC pointer.
5647 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5648 Chain = TOCVal.getValue(0);
5649 Glue = TOCVal.getValue(1);
5650
5651 // If the function call has an explicit 'nest' parameter, it takes the
5652 // place of the environment pointer.
5653 assert((!hasNest || !Subtarget.isAIXABI()) &&
5654 "Nest parameter is not supported on AIX.");
5655 if (!hasNest) {
5656 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5657 Chain = EnvVal.getValue(0);
5658 Glue = EnvVal.getValue(1);
5659 }
5660
5661 // The rest of the indirect call sequence is the same as the non-descriptor
5662 // DAG.
5663 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5664}
5665
5667 SDValue &Glue, SDValue &Chain,
5668 SDValue CallSeqStart, const CallBase *CB,
5669 const SDLoc &dl, bool hasNest,
5670 const PPCSubtarget &Subtarget) {
5671 // On AIX there is a feature ("out of line glue code") which uses a special
5672 // trampoline function ._ptrgl to do the indirect call. If this option is
5673 // enabled we instead simply load the address of the descriptor into gpr11,
5674 // with the arguments in the 'normal' registers and branch to the ._ptrgl
5675 // stub.
5676 const MCRegister PtrGlueReg = Subtarget.getGlueCodeDescriptorRegister();
5677 SDValue MoveToPhysicalReg =
5678 DAG.getCopyToReg(Chain, dl, PtrGlueReg, Callee, Glue);
5679 Chain = MoveToPhysicalReg.getValue(0);
5680 Glue = MoveToPhysicalReg.getValue(1);
5681}
5682
5683static void
5685 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5686 SelectionDAG &DAG,
5687 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5688 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5689 const PPCSubtarget &Subtarget) {
5690 const bool IsPPC64 = Subtarget.isPPC64();
5691 // MVT for a general purpose register.
5692 const MVT RegVT = Subtarget.getScalarIntVT();
5693
5694 // First operand is always the chain.
5695 Ops.push_back(Chain);
5696
5697 // If it's a direct call pass the callee as the second operand.
5698 if (!CFlags.IsIndirect)
5699 Ops.push_back(Callee);
5700 else if (Subtarget.usePointerGlueHelper()) {
5701 Ops.push_back(Callee);
5702 // Add the register used to pass the descriptor address.
5703 Ops.push_back(
5704 DAG.getRegister(Subtarget.getGlueCodeDescriptorRegister(), RegVT));
5705 } else {
5706 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5707
5708 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5709 // on the stack (this would have been done in `LowerCall_64SVR4` or
5710 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5711 // represents both the indirect branch and a load that restores the TOC
5712 // pointer from the linkage area. The operand for the TOC restore is an add
5713 // of the TOC save offset to the stack pointer. This must be the second
5714 // operand: after the chain input but before any other variadic arguments.
5715 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5716 // saved or used.
5717 if (isTOCSaveRestoreRequired(Subtarget)) {
5718 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5719
5720 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5721 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5722 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5723 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5724 Ops.push_back(AddTOC);
5725 }
5726
5727 // Add the register used for the environment pointer.
5728 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5729 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5730 RegVT));
5731
5732
5733 // Add CTR register as callee so a bctr can be emitted later.
5734 if (CFlags.IsTailCall)
5735 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5736 }
5737
5738 // If this is a tail call add stack pointer delta.
5739 if (CFlags.IsTailCall)
5740 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5741
5742 // Add argument registers to the end of the list so that they are known live
5743 // into the call.
5744 for (const auto &[Reg, N] : RegsToPass)
5745 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
5746
5747 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5748 // no way to mark dependencies as implicit here.
5749 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5750 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5751 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5752 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5753
5754 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5755 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5756 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5757
5758 // Add a register mask operand representing the call-preserved registers.
5759 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5760 const uint32_t *Mask =
5761 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5762 assert(Mask && "Missing call preserved mask for calling convention");
5763 Ops.push_back(DAG.getRegisterMask(Mask));
5764
5765 // If the glue is valid, it is the last operand.
5766 if (Glue.getNode())
5767 Ops.push_back(Glue);
5768}
5769
5770SDValue PPCTargetLowering::FinishCall(
5771 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5772 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5773 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5774 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5775 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5776
5777 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5778 Subtarget.isAIXABI())
5779 setUsesTOCBasePtr(DAG);
5780
5781 unsigned CallOpc =
5782 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5783 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5784
5785 if (!CFlags.IsIndirect)
5786 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5787 else if (Subtarget.usesFunctionDescriptors()) {
5788 if (Subtarget.usePointerGlueHelper()) {
5789 prepareOutOfLineGlueCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, dl,
5790 CFlags.HasNest, Subtarget);
5791 SDValue PtrGlueCallee =
5792 DAG.getExternalSymbol("_ptrgl", getPointerTy(DAG.getDataLayout()));
5793 Callee = transformCallee(PtrGlueCallee, DAG, dl, Subtarget);
5794 } else {
5795 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5796 dl, CFlags.HasNest, Subtarget);
5797 }
5798 } else {
5799 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5800 }
5801
5802 // Build the operand list for the call instruction.
5804 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5805 SPDiff, Subtarget);
5806
5807 // Emit tail call.
5808 if (CFlags.IsTailCall) {
5809 // Indirect tail call when using PC Relative calls do not have the same
5810 // constraints.
5811 assert(((Callee.getOpcode() == ISD::Register &&
5812 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5813 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5814 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5815 isa<ConstantSDNode>(Callee) ||
5816 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5817 "Expecting a global address, external symbol, absolute value, "
5818 "register or an indirect tail call when PC Relative calls are "
5819 "used.");
5820 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5821 assert(CallOpc == PPCISD::TC_RETURN &&
5822 "Unexpected call opcode for a tail call.");
5824 SDValue Ret = DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5825 DAG.addNoMergeSiteInfo(Ret.getNode(), CFlags.NoMerge);
5826 return Ret;
5827 }
5828
5829 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5830 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5831 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5832 Glue = Chain.getValue(1);
5833
5834 // When performing tail call optimization the callee pops its arguments off
5835 // the stack. Account for this here so these bytes can be pushed back on in
5836 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5837 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5839 ? NumBytes
5840 : 0;
5841
5842 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
5843 Glue = Chain.getValue(1);
5844
5845 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5846 DAG, InVals);
5847}
5848
5850 CallingConv::ID CalleeCC = CB->getCallingConv();
5851 const Function *CallerFunc = CB->getCaller();
5852 CallingConv::ID CallerCC = CallerFunc->getCallingConv();
5853 const Function *CalleeFunc = CB->getCalledFunction();
5854 if (!CalleeFunc)
5855 return false;
5856 const GlobalValue *CalleeGV = dyn_cast<GlobalValue>(CalleeFunc);
5857
5860
5861 GetReturnInfo(CalleeCC, CalleeFunc->getReturnType(),
5862 CalleeFunc->getAttributes(), Outs, *this,
5863 CalleeFunc->getDataLayout());
5864
5865 return isEligibleForTCO(CalleeGV, CalleeCC, CallerCC, CB,
5866 CalleeFunc->isVarArg(), Outs, Ins, CallerFunc,
5867 false /*isCalleeExternalSymbol*/);
5868}
5869
5870bool PPCTargetLowering::isEligibleForTCO(
5871 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5872 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5874 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5875 bool isCalleeExternalSymbol) const {
5876 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5877 return false;
5878
5879 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5880 return IsEligibleForTailCallOptimization_64SVR4(
5881 CalleeGV, CalleeCC, CallerCC, CB, isVarArg, Outs, Ins, CallerFunc,
5882 isCalleeExternalSymbol);
5883 else
5884 return IsEligibleForTailCallOptimization(CalleeGV, CalleeCC, CallerCC,
5885 isVarArg, Ins);
5886}
5887
5888SDValue
5889PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5890 SmallVectorImpl<SDValue> &InVals) const {
5891 SelectionDAG &DAG = CLI.DAG;
5892 SDLoc &dl = CLI.DL;
5894 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5896 SDValue Chain = CLI.Chain;
5897 SDValue Callee = CLI.Callee;
5898 bool &isTailCall = CLI.IsTailCall;
5899 CallingConv::ID CallConv = CLI.CallConv;
5900 bool isVarArg = CLI.IsVarArg;
5901 bool isPatchPoint = CLI.IsPatchPoint;
5902 const CallBase *CB = CLI.CB;
5903
5904 if (isTailCall) {
5906 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5907 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5908 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5909 bool IsCalleeExternalSymbol = isa<ExternalSymbolSDNode>(Callee);
5910
5911 isTailCall =
5912 isEligibleForTCO(GV, CallConv, CallerCC, CB, isVarArg, Outs, Ins,
5913 &(MF.getFunction()), IsCalleeExternalSymbol);
5914 if (isTailCall) {
5915 ++NumTailCalls;
5916 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5917 ++NumSiblingCalls;
5918
5919 // PC Relative calls no longer guarantee that the callee is a Global
5920 // Address Node. The callee could be an indirect tail call in which
5921 // case the SDValue for the callee could be a load (to load the address
5922 // of a function pointer) or it may be a register copy (to move the
5923 // address of the callee from a function parameter into a virtual
5924 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5925 assert((Subtarget.isUsingPCRelativeCalls() ||
5926 isa<GlobalAddressSDNode>(Callee)) &&
5927 "Callee should be an llvm::Function object.");
5928
5929 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5930 << "\nTCO callee: ");
5931 LLVM_DEBUG(Callee.dump());
5932 }
5933 }
5934
5935 if (!isTailCall && CB && CB->isMustTailCall())
5936 report_fatal_error("failed to perform tail call elimination on a call "
5937 "site marked musttail");
5938
5939 // When long calls (i.e. indirect calls) are always used, calls are always
5940 // made via function pointer. If we have a function name, first translate it
5941 // into a pointer.
5942 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5943 !isTailCall)
5944 Callee = LowerGlobalAddress(Callee, DAG);
5945
5946 CallFlags CFlags(
5947 CallConv, isTailCall, isVarArg, isPatchPoint,
5948 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5949 // hasNest
5950 Subtarget.is64BitELFABI() &&
5951 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5952 CLI.NoMerge);
5953
5954 if (Subtarget.isAIXABI())
5955 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5956 InVals, CB);
5957
5958 assert(Subtarget.isSVR4ABI());
5959 if (Subtarget.isPPC64())
5960 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5961 InVals, CB);
5962 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5963 InVals, CB);
5964}
5965
5966SDValue PPCTargetLowering::LowerCall_32SVR4(
5967 SDValue Chain, SDValue Callee, CallFlags CFlags,
5969 const SmallVectorImpl<SDValue> &OutVals,
5970 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5972 const CallBase *CB) const {
5973 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5974 // of the 32-bit SVR4 ABI stack frame layout.
5975
5976 const CallingConv::ID CallConv = CFlags.CallConv;
5977 const bool IsVarArg = CFlags.IsVarArg;
5978 const bool IsTailCall = CFlags.IsTailCall;
5979
5980 assert((CallConv == CallingConv::C ||
5981 CallConv == CallingConv::Cold ||
5982 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5983
5984 const Align PtrAlign(4);
5985
5987
5988 // Mark this function as potentially containing a function that contains a
5989 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5990 // and restoring the callers stack pointer in this functions epilog. This is
5991 // done because by tail calling the called function might overwrite the value
5992 // in this function's (MF) stack pointer stack slot 0(SP).
5993 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5994 CallConv == CallingConv::Fast)
5995 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5996
5997 // Count how many bytes are to be pushed on the stack, including the linkage
5998 // area, parameter list area and the part of the local variable space which
5999 // contains copies of aggregates which are passed by value.
6000
6001 // Assign locations to all of the outgoing arguments.
6003 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6004
6005 // Reserve space for the linkage area on the stack.
6006 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
6007 PtrAlign);
6008
6009 if (IsVarArg) {
6010 // Handle fixed and variable vector arguments differently.
6011 // Fixed vector arguments go into registers as long as registers are
6012 // available. Variable vector arguments always go into memory.
6013 unsigned NumArgs = Outs.size();
6014
6015 for (unsigned i = 0; i != NumArgs; ++i) {
6016 MVT ArgVT = Outs[i].VT;
6017 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6018 bool Result;
6019
6020 if (!ArgFlags.isVarArg()) {
6021 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
6022 Outs[i].OrigTy, CCInfo);
6023 } else {
6025 ArgFlags, Outs[i].OrigTy, CCInfo);
6026 }
6027
6028 if (Result) {
6029#ifndef NDEBUG
6030 errs() << "Call operand #" << i << " has unhandled type "
6031 << ArgVT << "\n";
6032#endif
6033 llvm_unreachable(nullptr);
6034 }
6035 }
6036 } else {
6037 // All arguments are treated the same.
6038 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
6039 }
6040
6041 // Assign locations to all of the outgoing aggregate by value arguments.
6042 SmallVector<CCValAssign, 16> ByValArgLocs;
6043 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
6044
6045 // Reserve stack space for the allocations in CCInfo.
6046 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
6047
6048 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
6049
6050 // Size of the linkage area, parameter list area and the part of the local
6051 // space variable where copies of aggregates which are passed by value are
6052 // stored.
6053 unsigned NumBytes = CCByValInfo.getStackSize();
6054
6055 // Calculate by how many bytes the stack has to be adjusted in case of tail
6056 // call optimization.
6057 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
6058
6059 // Adjust the stack pointer for the new arguments...
6060 // These operations are automatically eliminated by the prolog/epilog pass
6061 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6062 SDValue CallSeqStart = Chain;
6063
6064 // Load the return address and frame pointer so it can be moved somewhere else
6065 // later.
6066 SDValue LROp, FPOp;
6067 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6068
6069 // Set up a copy of the stack pointer for use loading and storing any
6070 // arguments that may not fit in the registers available for argument
6071 // passing.
6072 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6073
6075 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6076 SmallVector<SDValue, 8> MemOpChains;
6077
6078 bool seenFloatArg = false;
6079 // Walk the register/memloc assignments, inserting copies/loads.
6080 // i - Tracks the index into the list of registers allocated for the call
6081 // RealArgIdx - Tracks the index into the list of actual function arguments
6082 // j - Tracks the index into the list of byval arguments
6083 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
6084 i != e;
6085 ++i, ++RealArgIdx) {
6086 CCValAssign &VA = ArgLocs[i];
6087 SDValue Arg = OutVals[RealArgIdx];
6088 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
6089
6090 if (Flags.isByVal()) {
6091 // Argument is an aggregate which is passed by value, thus we need to
6092 // create a copy of it in the local variable space of the current stack
6093 // frame (which is the stack frame of the caller) and pass the address of
6094 // this copy to the callee.
6095 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
6096 CCValAssign &ByValVA = ByValArgLocs[j++];
6097 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
6098
6099 // Memory reserved in the local variable space of the callers stack frame.
6100 unsigned LocMemOffset = ByValVA.getLocMemOffset();
6101
6102 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6103 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6104 StackPtr, PtrOff);
6105
6106 // Create a copy of the argument in the local area of the current
6107 // stack frame.
6108 SDValue MemcpyCall =
6109 CreateCopyOfByValArgument(Arg, PtrOff,
6110 CallSeqStart.getNode()->getOperand(0),
6111 Flags, DAG, dl);
6112
6113 // This must go outside the CALLSEQ_START..END.
6114 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
6115 SDLoc(MemcpyCall));
6116 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6117 NewCallSeqStart.getNode());
6118 Chain = CallSeqStart = NewCallSeqStart;
6119
6120 // Pass the address of the aggregate copy on the stack either in a
6121 // physical register or in the parameter list area of the current stack
6122 // frame to the callee.
6123 Arg = PtrOff;
6124 }
6125
6126 // When useCRBits() is true, there can be i1 arguments.
6127 // It is because getRegisterType(MVT::i1) => MVT::i1,
6128 // and for other integer types getRegisterType() => MVT::i32.
6129 // Extend i1 and ensure callee will get i32.
6130 if (Arg.getValueType() == MVT::i1)
6131 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6132 dl, MVT::i32, Arg);
6133
6134 if (VA.isRegLoc()) {
6135 seenFloatArg |= VA.getLocVT().isFloatingPoint();
6136 // Put argument in a physical register.
6137 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
6138 bool IsLE = Subtarget.isLittleEndian();
6139 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6140 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
6141 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
6142 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6143 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
6144 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
6145 SVal.getValue(0)));
6146 } else
6147 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
6148 } else {
6149 // Put argument in the parameter list area of the current stack frame.
6150 assert(VA.isMemLoc());
6151 unsigned LocMemOffset = VA.getLocMemOffset();
6152
6153 if (!IsTailCall) {
6154 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6155 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6156 StackPtr, PtrOff);
6157
6158 MemOpChains.push_back(
6159 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6160 } else {
6161 // Calculate and remember argument location.
6162 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
6163 TailCallArguments);
6164 }
6165 }
6166 }
6167
6168 if (!MemOpChains.empty())
6169 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6170
6171 // Build a sequence of copy-to-reg nodes chained together with token chain
6172 // and flag operands which copy the outgoing args into the appropriate regs.
6173 SDValue InGlue;
6174 for (const auto &[Reg, N] : RegsToPass) {
6175 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6176 InGlue = Chain.getValue(1);
6177 }
6178
6179 // Set CR bit 6 to true if this is a vararg call with floating args passed in
6180 // registers.
6181 if (IsVarArg) {
6182 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6183 SDValue Ops[] = { Chain, InGlue };
6184
6185 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
6186 VTs, ArrayRef(Ops, InGlue.getNode() ? 2 : 1));
6187
6188 InGlue = Chain.getValue(1);
6189 }
6190
6191 if (IsTailCall)
6192 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6193 TailCallArguments);
6194
6195 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6196 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6197}
6198
6199// Copy an argument into memory, being careful to do this outside the
6200// call sequence for the call to which the argument belongs.
6201SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6202 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6203 SelectionDAG &DAG, const SDLoc &dl) const {
6204 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6205 CallSeqStart.getNode()->getOperand(0),
6206 Flags, DAG, dl);
6207 // The MEMCPY must go outside the CALLSEQ_START..END.
6208 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6209 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6210 SDLoc(MemcpyCall));
6211 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6212 NewCallSeqStart.getNode());
6213 return NewCallSeqStart;
6214}
6215
6216SDValue PPCTargetLowering::LowerCall_64SVR4(
6217 SDValue Chain, SDValue Callee, CallFlags CFlags,
6219 const SmallVectorImpl<SDValue> &OutVals,
6220 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6222 const CallBase *CB) const {
6223 bool isELFv2ABI = Subtarget.isELFv2ABI();
6224 bool isLittleEndian = Subtarget.isLittleEndian();
6225 unsigned NumOps = Outs.size();
6226 bool IsSibCall = false;
6227 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6228
6229 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6230 unsigned PtrByteSize = 8;
6231
6233
6234 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6235 IsSibCall = true;
6236
6237 // Mark this function as potentially containing a function that contains a
6238 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6239 // and restoring the callers stack pointer in this functions epilog. This is
6240 // done because by tail calling the called function might overwrite the value
6241 // in this function's (MF) stack pointer stack slot 0(SP).
6242 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6243 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6244
6245 assert(!(IsFastCall && CFlags.IsVarArg) &&
6246 "fastcc not supported on varargs functions");
6247
6248 // Count how many bytes are to be pushed on the stack, including the linkage
6249 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
6250 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6251 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6252 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6253 unsigned NumBytes = LinkageSize;
6254 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6255
6256 static const MCPhysReg GPR[] = {
6257 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6258 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6259 };
6260 static const MCPhysReg VR[] = {
6261 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6262 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6263 };
6264
6265 const unsigned NumGPRs = std::size(GPR);
6266 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6267 const unsigned NumVRs = std::size(VR);
6268
6269 // On ELFv2, we can avoid allocating the parameter area if all the arguments
6270 // can be passed to the callee in registers.
6271 // For the fast calling convention, there is another check below.
6272 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6273 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6274 if (!HasParameterArea) {
6275 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6276 unsigned AvailableFPRs = NumFPRs;
6277 unsigned AvailableVRs = NumVRs;
6278 unsigned NumBytesTmp = NumBytes;
6279 for (unsigned i = 0; i != NumOps; ++i) {
6280 if (Outs[i].Flags.isNest()) continue;
6281 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6282 PtrByteSize, LinkageSize, ParamAreaSize,
6283 NumBytesTmp, AvailableFPRs, AvailableVRs))
6284 HasParameterArea = true;
6285 }
6286 }
6287
6288 // When using the fast calling convention, we don't provide backing for
6289 // arguments that will be in registers.
6290 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6291
6292 // Avoid allocating parameter area for fastcc functions if all the arguments
6293 // can be passed in the registers.
6294 if (IsFastCall)
6295 HasParameterArea = false;
6296
6297 // Add up all the space actually used.
6298 for (unsigned i = 0; i != NumOps; ++i) {
6299 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6300 EVT ArgVT = Outs[i].VT;
6301 EVT OrigVT = Outs[i].ArgVT;
6302
6303 if (Flags.isNest())
6304 continue;
6305
6306 if (IsFastCall) {
6307 if (Flags.isByVal()) {
6308 NumGPRsUsed += (Flags.getByValSize()+7)/8;
6309 if (NumGPRsUsed > NumGPRs)
6310 HasParameterArea = true;
6311 } else {
6312 switch (ArgVT.getSimpleVT().SimpleTy) {
6313 default: llvm_unreachable("Unexpected ValueType for argument!");
6314 case MVT::i1:
6315 case MVT::i32:
6316 case MVT::i64:
6317 if (++NumGPRsUsed <= NumGPRs)
6318 continue;
6319 break;
6320 case MVT::v4i32:
6321 case MVT::v8i16:
6322 case MVT::v16i8:
6323 case MVT::v2f64:
6324 case MVT::v2i64:
6325 case MVT::v1i128:
6326 case MVT::f128:
6327 if (++NumVRsUsed <= NumVRs)
6328 continue;
6329 break;
6330 case MVT::v4f32:
6331 if (++NumVRsUsed <= NumVRs)
6332 continue;
6333 break;
6334 case MVT::f32:
6335 case MVT::f64:
6336 if (++NumFPRsUsed <= NumFPRs)
6337 continue;
6338 break;
6339 }
6340 HasParameterArea = true;
6341 }
6342 }
6343
6344 /* Respect alignment of argument on the stack. */
6345 auto Alignement =
6346 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6347 NumBytes = alignTo(NumBytes, Alignement);
6348
6349 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6350 if (Flags.isInConsecutiveRegsLast())
6351 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6352 }
6353
6354 unsigned NumBytesActuallyUsed = NumBytes;
6355
6356 // In the old ELFv1 ABI,
6357 // the prolog code of the callee may store up to 8 GPR argument registers to
6358 // the stack, allowing va_start to index over them in memory if its varargs.
6359 // Because we cannot tell if this is needed on the caller side, we have to
6360 // conservatively assume that it is needed. As such, make sure we have at
6361 // least enough stack space for the caller to store the 8 GPRs.
6362 // In the ELFv2 ABI, we allocate the parameter area iff a callee
6363 // really requires memory operands, e.g. a vararg function.
6364 if (HasParameterArea)
6365 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6366 else
6367 NumBytes = LinkageSize;
6368
6369 // Tail call needs the stack to be aligned.
6370 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6371 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6372
6373 int SPDiff = 0;
6374
6375 // Calculate by how many bytes the stack has to be adjusted in case of tail
6376 // call optimization.
6377 if (!IsSibCall)
6378 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6379
6380 // To protect arguments on the stack from being clobbered in a tail call,
6381 // force all the loads to happen before doing any other lowering.
6382 if (CFlags.IsTailCall)
6383 Chain = DAG.getStackArgumentTokenFactor(Chain);
6384
6385 // Adjust the stack pointer for the new arguments...
6386 // These operations are automatically eliminated by the prolog/epilog pass
6387 if (!IsSibCall)
6388 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6389 SDValue CallSeqStart = Chain;
6390
6391 // Load the return address and frame pointer so it can be move somewhere else
6392 // later.
6393 SDValue LROp, FPOp;
6394 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6395
6396 // Set up a copy of the stack pointer for use loading and storing any
6397 // arguments that may not fit in the registers available for argument
6398 // passing.
6399 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6400
6401 // Figure out which arguments are going to go in registers, and which in
6402 // memory. Also, if this is a vararg function, floating point operations
6403 // must be stored to our stack, and loaded into integer regs as well, if
6404 // any integer regs are available for argument passing.
6405 unsigned ArgOffset = LinkageSize;
6406
6408 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6409
6410 SmallVector<SDValue, 8> MemOpChains;
6411 for (unsigned i = 0; i != NumOps; ++i) {
6412 SDValue Arg = OutVals[i];
6413 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6414 EVT ArgVT = Outs[i].VT;
6415 EVT OrigVT = Outs[i].ArgVT;
6416
6417 // PtrOff will be used to store the current argument to the stack if a
6418 // register cannot be found for it.
6419 SDValue PtrOff;
6420
6421 // We re-align the argument offset for each argument, except when using the
6422 // fast calling convention, when we need to make sure we do that only when
6423 // we'll actually use a stack slot.
6424 auto ComputePtrOff = [&]() {
6425 /* Respect alignment of argument on the stack. */
6426 auto Alignment =
6427 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6428 ArgOffset = alignTo(ArgOffset, Alignment);
6429
6430 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6431
6432 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6433 };
6434
6435 if (!IsFastCall) {
6436 ComputePtrOff();
6437
6438 /* Compute GPR index associated with argument offset. */
6439 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6440 GPR_idx = std::min(GPR_idx, NumGPRs);
6441 }
6442
6443 // Promote integers to 64-bit values.
6444 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6445 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6446 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6447 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6448 }
6449
6450 // FIXME memcpy is used way more than necessary. Correctness first.
6451 // Note: "by value" is code for passing a structure by value, not
6452 // basic types.
6453 if (Flags.isByVal()) {
6454 // Note: Size includes alignment padding, so
6455 // struct x { short a; char b; }
6456 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
6457 // These are the proper values we need for right-justifying the
6458 // aggregate in a parameter register.
6459 unsigned Size = Flags.getByValSize();
6460
6461 // An empty aggregate parameter takes up no storage and no
6462 // registers.
6463 if (Size == 0)
6464 continue;
6465
6466 if (IsFastCall)
6467 ComputePtrOff();
6468
6469 // All aggregates smaller than 8 bytes must be passed right-justified.
6470 if (Size==1 || Size==2 || Size==4) {
6471 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6472 if (GPR_idx != NumGPRs) {
6473 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6474 MachinePointerInfo(), VT);
6475 MemOpChains.push_back(Load.getValue(1));
6476 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6477
6478 ArgOffset += PtrByteSize;
6479 continue;
6480 }
6481 }
6482
6483 if (GPR_idx == NumGPRs && Size < 8) {
6484 SDValue AddPtr = PtrOff;
6485 if (!isLittleEndian) {
6486 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6487 PtrOff.getValueType());
6488 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6489 }
6490 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6491 CallSeqStart,
6492 Flags, DAG, dl);
6493 ArgOffset += PtrByteSize;
6494 continue;
6495 }
6496 // Copy the object to parameter save area if it can not be entirely passed
6497 // by registers.
6498 // FIXME: we only need to copy the parts which need to be passed in
6499 // parameter save area. For the parts passed by registers, we don't need
6500 // to copy them to the stack although we need to allocate space for them
6501 // in parameter save area.
6502 if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6503 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6504 CallSeqStart,
6505 Flags, DAG, dl);
6506
6507 // When a register is available, pass a small aggregate right-justified.
6508 if (Size < 8 && GPR_idx != NumGPRs) {
6509 // The easiest way to get this right-justified in a register
6510 // is to copy the structure into the rightmost portion of a
6511 // local variable slot, then load the whole slot into the
6512 // register.
6513 // FIXME: The memcpy seems to produce pretty awful code for
6514 // small aggregates, particularly for packed ones.
6515 // FIXME: It would be preferable to use the slot in the
6516 // parameter save area instead of a new local variable.
6517 SDValue AddPtr = PtrOff;
6518 if (!isLittleEndian) {
6519 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6520 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6521 }
6522 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6523 CallSeqStart,
6524 Flags, DAG, dl);
6525
6526 // Load the slot into the register.
6527 SDValue Load =
6528 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6529 MemOpChains.push_back(Load.getValue(1));
6530 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6531
6532 // Done with this argument.
6533 ArgOffset += PtrByteSize;
6534 continue;
6535 }
6536
6537 // For aggregates larger than PtrByteSize, copy the pieces of the
6538 // object that fit into registers from the parameter save area.
6539 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6540 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6541 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6542 if (GPR_idx != NumGPRs) {
6543 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6544 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6545 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6546 MachinePointerInfo(), ObjType);
6547
6548 MemOpChains.push_back(Load.getValue(1));
6549 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6550 ArgOffset += PtrByteSize;
6551 } else {
6552 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6553 break;
6554 }
6555 }
6556 continue;
6557 }
6558
6559 switch (Arg.getSimpleValueType().SimpleTy) {
6560 default: llvm_unreachable("Unexpected ValueType for argument!");
6561 case MVT::i1:
6562 case MVT::i32:
6563 case MVT::i64:
6564 if (Flags.isNest()) {
6565 // The 'nest' parameter, if any, is passed in R11.
6566 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6567 break;
6568 }
6569
6570 // These can be scalar arguments or elements of an integer array type
6571 // passed directly. Clang may use those instead of "byval" aggregate
6572 // types to avoid forcing arguments to memory unnecessarily.
6573 if (GPR_idx != NumGPRs) {
6574 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6575 } else {
6576 if (IsFastCall)
6577 ComputePtrOff();
6578
6579 assert(HasParameterArea &&
6580 "Parameter area must exist to pass an argument in memory.");
6581 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6582 true, CFlags.IsTailCall, false, MemOpChains,
6583 TailCallArguments, dl);
6584 if (IsFastCall)
6585 ArgOffset += PtrByteSize;
6586 }
6587 if (!IsFastCall)
6588 ArgOffset += PtrByteSize;
6589 break;
6590 case MVT::f32:
6591 case MVT::f64: {
6592 // These can be scalar arguments or elements of a float array type
6593 // passed directly. The latter are used to implement ELFv2 homogenous
6594 // float aggregates.
6595
6596 // Named arguments go into FPRs first, and once they overflow, the
6597 // remaining arguments go into GPRs and then the parameter save area.
6598 // Unnamed arguments for vararg functions always go to GPRs and
6599 // then the parameter save area. For now, put all arguments to vararg
6600 // routines always in both locations (FPR *and* GPR or stack slot).
6601 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6602 bool NeededLoad = false;
6603
6604 // First load the argument into the next available FPR.
6605 if (FPR_idx != NumFPRs)
6606 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6607
6608 // Next, load the argument into GPR or stack slot if needed.
6609 if (!NeedGPROrStack)
6610 ;
6611 else if (GPR_idx != NumGPRs && !IsFastCall) {
6612 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6613 // once we support fp <-> gpr moves.
6614
6615 // In the non-vararg case, this can only ever happen in the
6616 // presence of f32 array types, since otherwise we never run
6617 // out of FPRs before running out of GPRs.
6618 SDValue ArgVal;
6619
6620 // Double values are always passed in a single GPR.
6621 if (Arg.getValueType() != MVT::f32) {
6622 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6623
6624 // Non-array float values are extended and passed in a GPR.
6625 } else if (!Flags.isInConsecutiveRegs()) {
6626 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6627 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6628
6629 // If we have an array of floats, we collect every odd element
6630 // together with its predecessor into one GPR.
6631 } else if (ArgOffset % PtrByteSize != 0) {
6632 SDValue Lo, Hi;
6633 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6634 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6635 if (!isLittleEndian)
6636 std::swap(Lo, Hi);
6637 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6638
6639 // The final element, if even, goes into the first half of a GPR.
6640 } else if (Flags.isInConsecutiveRegsLast()) {
6641 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6642 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6643 if (!isLittleEndian)
6644 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6645 DAG.getConstant(32, dl, MVT::i32));
6646
6647 // Non-final even elements are skipped; they will be handled
6648 // together the with subsequent argument on the next go-around.
6649 } else
6650 ArgVal = SDValue();
6651
6652 if (ArgVal.getNode())
6653 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6654 } else {
6655 if (IsFastCall)
6656 ComputePtrOff();
6657
6658 // Single-precision floating-point values are mapped to the
6659 // second (rightmost) word of the stack doubleword.
6660 if (Arg.getValueType() == MVT::f32 &&
6661 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6662 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6663 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6664 }
6665
6666 assert(HasParameterArea &&
6667 "Parameter area must exist to pass an argument in memory.");
6668 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6669 true, CFlags.IsTailCall, false, MemOpChains,
6670 TailCallArguments, dl);
6671
6672 NeededLoad = true;
6673 }
6674 // When passing an array of floats, the array occupies consecutive
6675 // space in the argument area; only round up to the next doubleword
6676 // at the end of the array. Otherwise, each float takes 8 bytes.
6677 if (!IsFastCall || NeededLoad) {
6678 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6679 Flags.isInConsecutiveRegs()) ? 4 : 8;
6680 if (Flags.isInConsecutiveRegsLast())
6681 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6682 }
6683 break;
6684 }
6685 case MVT::v4f32:
6686 case MVT::v4i32:
6687 case MVT::v8i16:
6688 case MVT::v16i8:
6689 case MVT::v2f64:
6690 case MVT::v2i64:
6691 case MVT::v1i128:
6692 case MVT::f128:
6693 // These can be scalar arguments or elements of a vector array type
6694 // passed directly. The latter are used to implement ELFv2 homogenous
6695 // vector aggregates.
6696
6697 // For a varargs call, named arguments go into VRs or on the stack as
6698 // usual; unnamed arguments always go to the stack or the corresponding
6699 // GPRs when within range. For now, we always put the value in both
6700 // locations (or even all three).
6701 if (CFlags.IsVarArg) {
6702 assert(HasParameterArea &&
6703 "Parameter area must exist if we have a varargs call.");
6704 // We could elide this store in the case where the object fits
6705 // entirely in R registers. Maybe later.
6706 SDValue Store =
6707 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6708 MemOpChains.push_back(Store);
6709 if (VR_idx != NumVRs) {
6710 SDValue Load =
6711 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6712 MemOpChains.push_back(Load.getValue(1));
6713 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6714 }
6715 ArgOffset += 16;
6716 for (unsigned i=0; i<16; i+=PtrByteSize) {
6717 if (GPR_idx == NumGPRs)
6718 break;
6719 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6720 DAG.getConstant(i, dl, PtrVT));
6721 SDValue Load =
6722 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6723 MemOpChains.push_back(Load.getValue(1));
6724 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6725 }
6726 break;
6727 }
6728
6729 // Non-varargs Altivec params go into VRs or on the stack.
6730 if (VR_idx != NumVRs) {
6731 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6732 } else {
6733 if (IsFastCall)
6734 ComputePtrOff();
6735
6736 assert(HasParameterArea &&
6737 "Parameter area must exist to pass an argument in memory.");
6738 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6739 true, CFlags.IsTailCall, true, MemOpChains,
6740 TailCallArguments, dl);
6741 if (IsFastCall)
6742 ArgOffset += 16;
6743 }
6744
6745 if (!IsFastCall)
6746 ArgOffset += 16;
6747 break;
6748 }
6749 }
6750
6751 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6752 "mismatch in size of parameter area");
6753 (void)NumBytesActuallyUsed;
6754
6755 if (!MemOpChains.empty())
6756 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6757
6758 // Check if this is an indirect call (MTCTR/BCTRL).
6759 // See prepareDescriptorIndirectCall and buildCallOperands for more
6760 // information about calls through function pointers in the 64-bit SVR4 ABI.
6761 if (CFlags.IsIndirect) {
6762 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6763 // caller in the TOC save area.
6764 if (isTOCSaveRestoreRequired(Subtarget)) {
6765 assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6766 // Load r2 into a virtual register and store it to the TOC save area.
6767 setUsesTOCBasePtr(DAG);
6768 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6769 // TOC save area offset.
6770 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6771 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6772 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6773 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6775 DAG.getMachineFunction(), TOCSaveOffset));
6776 }
6777 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6778 // This does not mean the MTCTR instruction must use R12; it's easier
6779 // to model this as an extra parameter, so do that.
6780 if (isELFv2ABI && !CFlags.IsPatchPoint)
6781 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6782 }
6783
6784 // Build a sequence of copy-to-reg nodes chained together with token chain
6785 // and flag operands which copy the outgoing args into the appropriate regs.
6786 SDValue InGlue;
6787 for (const auto &[Reg, N] : RegsToPass) {
6788 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6789 InGlue = Chain.getValue(1);
6790 }
6791
6792 if (CFlags.IsTailCall && !IsSibCall)
6793 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6794 TailCallArguments);
6795
6796 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6797 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6798}
6799
6800// Returns true when the shadow of a general purpose argument register
6801// in the parameter save area is aligned to at least 'RequiredAlign'.
6802static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6803 assert(RequiredAlign.value() <= 16 &&
6804 "Required alignment greater than stack alignment.");
6805 switch (Reg) {
6806 default:
6807 report_fatal_error("called on invalid register.");
6808 case PPC::R5:
6809 case PPC::R9:
6810 case PPC::X3:
6811 case PPC::X5:
6812 case PPC::X7:
6813 case PPC::X9:
6814 // These registers are 16 byte aligned which is the most strict aligment
6815 // we can support.
6816 return true;
6817 case PPC::R3:
6818 case PPC::R7:
6819 case PPC::X4:
6820 case PPC::X6:
6821 case PPC::X8:
6822 case PPC::X10:
6823 // The shadow of these registers in the PSA is 8 byte aligned.
6824 return RequiredAlign <= 8;
6825 case PPC::R4:
6826 case PPC::R6:
6827 case PPC::R8:
6828 case PPC::R10:
6829 return RequiredAlign <= 4;
6830 }
6831}
6832
6833static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6834 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6835 Type *OrigTy, CCState &State) {
6836 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6837 State.getMachineFunction().getSubtarget());
6838 const bool IsPPC64 = Subtarget.isPPC64();
6839 const unsigned PtrSize = IsPPC64 ? 8 : 4;
6840 const Align PtrAlign(PtrSize);
6841 const Align StackAlign(16);
6842 const MVT RegVT = Subtarget.getScalarIntVT();
6843
6844 if (ValVT == MVT::f128)
6845 report_fatal_error("f128 is unimplemented on AIX.");
6846
6847 static const MCPhysReg GPR_32[] = {// 32-bit registers.
6848 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6849 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6850 static const MCPhysReg GPR_64[] = {// 64-bit registers.
6851 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6852 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6853
6854 static const MCPhysReg VR[] = {// Vector registers.
6855 PPC::V2, PPC::V3, PPC::V4, PPC::V5,
6856 PPC::V6, PPC::V7, PPC::V8, PPC::V9,
6857 PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6858
6859 const ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6860
6861 if (ArgFlags.isNest()) {
6862 MCRegister EnvReg = State.AllocateReg(IsPPC64 ? PPC::X11 : PPC::R11);
6863 if (!EnvReg)
6864 report_fatal_error("More then one nest argument.");
6865 State.addLoc(CCValAssign::getReg(ValNo, ValVT, EnvReg, RegVT, LocInfo));
6866 return false;
6867 }
6868
6869 if (ArgFlags.isByVal()) {
6870 const Align ByValAlign(ArgFlags.getNonZeroByValAlign());
6871 if (ByValAlign > StackAlign)
6872 report_fatal_error("Pass-by-value arguments with alignment greater than "
6873 "16 are not supported.");
6874
6875 const unsigned ByValSize = ArgFlags.getByValSize();
6876 const Align ObjAlign = ByValAlign > PtrAlign ? ByValAlign : PtrAlign;
6877
6878 // An empty aggregate parameter takes up no storage and no registers,
6879 // but needs a MemLoc for a stack slot for the formal arguments side.
6880 if (ByValSize == 0) {
6882 State.getStackSize(), RegVT, LocInfo));
6883 return false;
6884 }
6885
6886 // Shadow allocate any registers that are not properly aligned.
6887 unsigned NextReg = State.getFirstUnallocated(GPRs);
6888 while (NextReg != GPRs.size() &&
6889 !isGPRShadowAligned(GPRs[NextReg], ObjAlign)) {
6890 // Shadow allocate next registers since its aligment is not strict enough.
6891 MCRegister Reg = State.AllocateReg(GPRs);
6892 // Allocate the stack space shadowed by said register.
6893 State.AllocateStack(PtrSize, PtrAlign);
6894 assert(Reg && "Alocating register unexpectedly failed.");
6895 (void)Reg;
6896 NextReg = State.getFirstUnallocated(GPRs);
6897 }
6898
6899 const unsigned StackSize = alignTo(ByValSize, ObjAlign);
6900 unsigned Offset = State.AllocateStack(StackSize, ObjAlign);
6901 for (const unsigned E = Offset + StackSize; Offset < E; Offset += PtrSize) {
6902 if (MCRegister Reg = State.AllocateReg(GPRs))
6903 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6904 else {
6907 LocInfo));
6908 break;
6909 }
6910 }
6911 return false;
6912 }
6913
6914 // Arguments always reserve parameter save area.
6915 switch (ValVT.SimpleTy) {
6916 default:
6917 report_fatal_error("Unhandled value type for argument.");
6918 case MVT::i64:
6919 // i64 arguments should have been split to i32 for PPC32.
6920 assert(IsPPC64 && "PPC32 should have split i64 values.");
6921 [[fallthrough]];
6922 case MVT::i1:
6923 case MVT::i32: {
6924 const unsigned Offset = State.AllocateStack(PtrSize, PtrAlign);
6925 // AIX integer arguments are always passed in register width.
6926 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6927 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6929 if (MCRegister Reg = State.AllocateReg(GPRs))
6930 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6931 else
6932 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6933
6934 return false;
6935 }
6936 case MVT::f32:
6937 case MVT::f64: {
6938 // Parameter save area (PSA) is reserved even if the float passes in fpr.
6939 const unsigned StoreSize = LocVT.getStoreSize();
6940 // Floats are always 4-byte aligned in the PSA on AIX.
6941 // This includes f64 in 64-bit mode for ABI compatibility.
6942 const unsigned Offset =
6943 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6944 MCRegister FReg = State.AllocateReg(FPR);
6945 if (FReg)
6946 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6947
6948 // Reserve and initialize GPRs or initialize the PSA as required.
6949 for (unsigned I = 0; I < StoreSize; I += PtrSize) {
6950 if (MCRegister Reg = State.AllocateReg(GPRs)) {
6951 assert(FReg && "An FPR should be available when a GPR is reserved.");
6952 if (State.isVarArg()) {
6953 // Successfully reserved GPRs are only initialized for vararg calls.
6954 // Custom handling is required for:
6955 // f64 in PPC32 needs to be split into 2 GPRs.
6956 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6957 State.addLoc(
6958 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6959 }
6960 } else {
6961 // If there are insufficient GPRs, the PSA needs to be initialized.
6962 // Initialization occurs even if an FPR was initialized for
6963 // compatibility with the AIX XL compiler. The full memory for the
6964 // argument will be initialized even if a prior word is saved in GPR.
6965 // A custom memLoc is used when the argument also passes in FPR so
6966 // that the callee handling can skip over it easily.
6967 State.addLoc(
6968 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6969 LocInfo)
6970 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6971 break;
6972 }
6973 }
6974
6975 return false;
6976 }
6977 case MVT::v4f32:
6978 case MVT::v4i32:
6979 case MVT::v8i16:
6980 case MVT::v16i8:
6981 case MVT::v2i64:
6982 case MVT::v2f64:
6983 case MVT::v1i128: {
6984 const unsigned VecSize = 16;
6985 const Align VecAlign(VecSize);
6986
6987 if (!State.isVarArg()) {
6988 // If there are vector registers remaining we don't consume any stack
6989 // space.
6990 if (MCRegister VReg = State.AllocateReg(VR)) {
6991 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6992 return false;
6993 }
6994 // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6995 // might be allocated in the portion of the PSA that is shadowed by the
6996 // GPRs.
6997 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6998 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6999 return false;
7000 }
7001
7002 unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
7003 // Burn any underaligned registers and their shadowed stack space until
7004 // we reach the required alignment.
7005 while (NextRegIndex != GPRs.size() &&
7006 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
7007 // Shadow allocate register and its stack shadow.
7008 MCRegister Reg = State.AllocateReg(GPRs);
7009 State.AllocateStack(PtrSize, PtrAlign);
7010 assert(Reg && "Allocating register unexpectedly failed.");
7011 (void)Reg;
7012 NextRegIndex = State.getFirstUnallocated(GPRs);
7013 }
7014
7015 // Vectors that are passed as fixed arguments are handled differently.
7016 // They are passed in VRs if any are available (unlike arguments passed
7017 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
7018 // functions)
7019 if (!ArgFlags.isVarArg()) {
7020 if (MCRegister VReg = State.AllocateReg(VR)) {
7021 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7022 // Shadow allocate GPRs and stack space even though we pass in a VR.
7023 for (unsigned I = 0; I != VecSize; I += PtrSize)
7024 State.AllocateReg(GPRs);
7025 State.AllocateStack(VecSize, VecAlign);
7026 return false;
7027 }
7028 // No vector registers remain so pass on the stack.
7029 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7030 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7031 return false;
7032 }
7033
7034 // If all GPRS are consumed then we pass the argument fully on the stack.
7035 if (NextRegIndex == GPRs.size()) {
7036 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7037 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7038 return false;
7039 }
7040
7041 // Corner case for 32-bit codegen. We have 2 registers to pass the first
7042 // half of the argument, and then need to pass the remaining half on the
7043 // stack.
7044 if (GPRs[NextRegIndex] == PPC::R9) {
7045 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7046 State.addLoc(
7047 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7048
7049 const MCRegister FirstReg = State.AllocateReg(PPC::R9);
7050 const MCRegister SecondReg = State.AllocateReg(PPC::R10);
7051 assert(FirstReg && SecondReg &&
7052 "Allocating R9 or R10 unexpectedly failed.");
7053 State.addLoc(
7054 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
7055 State.addLoc(
7056 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
7057 return false;
7058 }
7059
7060 // We have enough GPRs to fully pass the vector argument, and we have
7061 // already consumed any underaligned registers. Start with the custom
7062 // MemLoc and then the custom RegLocs.
7063 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7064 State.addLoc(
7065 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7066 for (unsigned I = 0; I != VecSize; I += PtrSize) {
7067 const MCRegister Reg = State.AllocateReg(GPRs);
7068 assert(Reg && "Failed to allocated register for vararg vector argument");
7069 State.addLoc(
7070 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7071 }
7072 return false;
7073 }
7074 }
7075 return true;
7076}
7077
7078// So far, this function is only used by LowerFormalArguments_AIX()
7080 bool IsPPC64,
7081 bool HasP8Vector,
7082 bool HasVSX) {
7083 assert((IsPPC64 || SVT != MVT::i64) &&
7084 "i64 should have been split for 32-bit codegen.");
7085
7086 switch (SVT) {
7087 default:
7088 report_fatal_error("Unexpected value type for formal argument");
7089 case MVT::i1:
7090 case MVT::i32:
7091 case MVT::i64:
7092 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7093 case MVT::f32:
7094 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
7095 case MVT::f64:
7096 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
7097 case MVT::v4f32:
7098 case MVT::v4i32:
7099 case MVT::v8i16:
7100 case MVT::v16i8:
7101 case MVT::v2i64:
7102 case MVT::v2f64:
7103 case MVT::v1i128:
7104 return &PPC::VRRCRegClass;
7105 }
7106}
7107
7109 SelectionDAG &DAG, SDValue ArgValue,
7110 MVT LocVT, const SDLoc &dl) {
7111 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7112 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7113
7114 if (Flags.isSExt())
7115 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7116 DAG.getValueType(ValVT));
7117 else if (Flags.isZExt())
7118 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7119 DAG.getValueType(ValVT));
7120
7121 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7122}
7123
7124static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7125 const unsigned LASize = FL->getLinkageSize();
7126
7127 if (PPC::GPRCRegClass.contains(Reg)) {
7128 assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7129 "Reg must be a valid argument register!");
7130 return LASize + 4 * (Reg - PPC::R3);
7131 }
7132
7133 if (PPC::G8RCRegClass.contains(Reg)) {
7134 assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7135 "Reg must be a valid argument register!");
7136 return LASize + 8 * (Reg - PPC::X3);
7137 }
7138
7139 llvm_unreachable("Only general purpose registers expected.");
7140}
7141
7142// AIX ABI Stack Frame Layout:
7143//
7144// Low Memory +--------------------------------------------+
7145// SP +---> | Back chain | ---+
7146// | +--------------------------------------------+ |
7147// | | Saved Condition Register | |
7148// | +--------------------------------------------+ |
7149// | | Saved Linkage Register | |
7150// | +--------------------------------------------+ | Linkage Area
7151// | | Reserved for compilers | |
7152// | +--------------------------------------------+ |
7153// | | Reserved for binders | |
7154// | +--------------------------------------------+ |
7155// | | Saved TOC pointer | ---+
7156// | +--------------------------------------------+
7157// | | Parameter save area |
7158// | +--------------------------------------------+
7159// | | Alloca space |
7160// | +--------------------------------------------+
7161// | | Local variable space |
7162// | +--------------------------------------------+
7163// | | Float/int conversion temporary |
7164// | +--------------------------------------------+
7165// | | Save area for AltiVec registers |
7166// | +--------------------------------------------+
7167// | | AltiVec alignment padding |
7168// | +--------------------------------------------+
7169// | | Save area for VRSAVE register |
7170// | +--------------------------------------------+
7171// | | Save area for General Purpose registers |
7172// | +--------------------------------------------+
7173// | | Save area for Floating Point registers |
7174// | +--------------------------------------------+
7175// +---- | Back chain |
7176// High Memory +--------------------------------------------+
7177//
7178// Specifications:
7179// AIX 7.2 Assembler Language Reference
7180// Subroutine linkage convention
7181
7182SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7183 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7184 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7185 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7186
7187 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7188 CallConv == CallingConv::Fast) &&
7189 "Unexpected calling convention!");
7190
7191 if (getTargetMachine().Options.GuaranteedTailCallOpt)
7192 report_fatal_error("Tail call support is unimplemented on AIX.");
7193
7194 if (useSoftFloat())
7195 report_fatal_error("Soft float support is unimplemented on AIX.");
7196
7197 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7198
7199 const bool IsPPC64 = Subtarget.isPPC64();
7200 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7201
7202 // Assign locations to all of the incoming arguments.
7205 MachineFrameInfo &MFI = MF.getFrameInfo();
7206 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7207 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7208
7209 const EVT PtrVT = getPointerTy(MF.getDataLayout());
7210 // Reserve space for the linkage area on the stack.
7211 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7212 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7213 uint64_t SaveStackPos = CCInfo.getStackSize();
7214 bool SaveParams = MF.getFunction().hasFnAttribute("save-reg-params");
7215 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7216
7218
7219 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7220 CCValAssign &VA = ArgLocs[I++];
7221 MVT LocVT = VA.getLocVT();
7222 MVT ValVT = VA.getValVT();
7223 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7224
7225 EVT ArgVT = Ins[VA.getValNo()].ArgVT;
7226 bool ArgSignExt = Ins[VA.getValNo()].Flags.isSExt();
7227 // For compatibility with the AIX XL compiler, the float args in the
7228 // parameter save area are initialized even if the argument is available
7229 // in register. The caller is required to initialize both the register
7230 // and memory, however, the callee can choose to expect it in either.
7231 // The memloc is dismissed here because the argument is retrieved from
7232 // the register.
7233 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
7234 continue;
7235
7236 if (SaveParams && VA.isRegLoc() && !Flags.isByVal() && !VA.needsCustom()) {
7237 const TargetRegisterClass *RegClass = getRegClassForSVT(
7238 LocVT.SimpleTy, IsPPC64, Subtarget.hasP8Vector(), Subtarget.hasVSX());
7239 // On PPC64, debugger assumes extended 8-byte values are stored from GPR.
7240 MVT SaveVT = RegClass == &PPC::G8RCRegClass ? MVT::i64 : LocVT;
7241 const Register VReg = MF.addLiveIn(VA.getLocReg(), RegClass);
7242 SDValue Parm = DAG.getCopyFromReg(Chain, dl, VReg, SaveVT);
7243 int FI = MFI.CreateFixedObject(SaveVT.getStoreSize(), SaveStackPos, true);
7244 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7245 SDValue StoreReg = DAG.getStore(Chain, dl, Parm, FIN,
7246 MachinePointerInfo(), Align(PtrByteSize));
7247 SaveStackPos = alignTo(SaveStackPos + SaveVT.getStoreSize(), PtrByteSize);
7248 MemOps.push_back(StoreReg);
7249 }
7250
7251 if (SaveParams && (VA.isMemLoc() || Flags.isByVal()) && !VA.needsCustom()) {
7252 unsigned StoreSize =
7253 Flags.isByVal() ? Flags.getByValSize() : LocVT.getStoreSize();
7254 SaveStackPos = alignTo(SaveStackPos + StoreSize, PtrByteSize);
7255 }
7256
7257 auto HandleMemLoc = [&]() {
7258 const unsigned LocSize = LocVT.getStoreSize();
7259 const unsigned ValSize = ValVT.getStoreSize();
7260 assert((ValSize <= LocSize) &&
7261 "Object size is larger than size of MemLoc");
7262 int CurArgOffset = VA.getLocMemOffset();
7263 // Objects are right-justified because AIX is big-endian.
7264 if (LocSize > ValSize)
7265 CurArgOffset += LocSize - ValSize;
7266 // Potential tail calls could cause overwriting of argument stack slots.
7267 const bool IsImmutable =
7269 (CallConv == CallingConv::Fast));
7270 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7271 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7272 SDValue ArgValue =
7273 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7274
7275 // While the ABI specifies the argument type is (sign or zero) extended
7276 // out to register width, not all code is compliant. We truncate and
7277 // re-extend to be more forgiving of these callers when the argument type
7278 // is smaller than register width.
7279 if (!ArgVT.isVector() && !ValVT.isVector() && ArgVT.isInteger() &&
7280 ValVT.isInteger() &&
7281 ArgVT.getScalarSizeInBits() < ValVT.getScalarSizeInBits()) {
7282 // It is possible to have either real integer values
7283 // or integers that were not originally integers.
7284 // In the latter case, these could have came from structs,
7285 // and these integers would not have an extend on the parameter.
7286 // Since these types of integers do not have an extend specified
7287 // in the first place, the type of extend that we do should not matter.
7288 EVT TruncatedArgVT = ArgVT.isSimple() && ArgVT.getSimpleVT() == MVT::i1
7289 ? MVT::i8
7290 : ArgVT;
7291 SDValue ArgValueTrunc =
7292 DAG.getNode(ISD::TRUNCATE, dl, TruncatedArgVT, ArgValue);
7293 SDValue ArgValueExt =
7294 ArgSignExt ? DAG.getSExtOrTrunc(ArgValueTrunc, dl, ValVT)
7295 : DAG.getZExtOrTrunc(ArgValueTrunc, dl, ValVT);
7296 InVals.push_back(ArgValueExt);
7297 } else {
7298 InVals.push_back(ArgValue);
7299 }
7300 };
7301
7302 // Vector arguments to VaArg functions are passed both on the stack, and
7303 // in any available GPRs. Load the value from the stack and add the GPRs
7304 // as live ins.
7305 if (VA.isMemLoc() && VA.needsCustom()) {
7306 assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
7307 assert(isVarArg && "Only use custom memloc for vararg.");
7308 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
7309 // matching custom RegLocs.
7310 const unsigned OriginalValNo = VA.getValNo();
7311 (void)OriginalValNo;
7312
7313 auto HandleCustomVecRegLoc = [&]() {
7314 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7315 "Missing custom RegLoc.");
7316 VA = ArgLocs[I++];
7317 assert(VA.getValVT().isVector() &&
7318 "Unexpected Val type for custom RegLoc.");
7319 assert(VA.getValNo() == OriginalValNo &&
7320 "ValNo mismatch between custom MemLoc and RegLoc.");
7322 MF.addLiveIn(VA.getLocReg(),
7323 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7324 Subtarget.hasVSX()));
7325 };
7326
7327 HandleMemLoc();
7328 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7329 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7330 // R10.
7331 HandleCustomVecRegLoc();
7332 HandleCustomVecRegLoc();
7333
7334 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7335 // we passed the vector in R5, R6, R7 and R8.
7336 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7337 assert(!IsPPC64 &&
7338 "Only 2 custom RegLocs expected for 64-bit codegen.");
7339 HandleCustomVecRegLoc();
7340 HandleCustomVecRegLoc();
7341 }
7342
7343 continue;
7344 }
7345
7346 if (VA.isRegLoc()) {
7347 if (VA.getValVT().isScalarInteger())
7349 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7350 switch (VA.getValVT().SimpleTy) {
7351 default:
7352 report_fatal_error("Unhandled value type for argument.");
7353 case MVT::f32:
7355 break;
7356 case MVT::f64:
7358 break;
7359 }
7360 } else if (VA.getValVT().isVector()) {
7361 switch (VA.getValVT().SimpleTy) {
7362 default:
7363 report_fatal_error("Unhandled value type for argument.");
7364 case MVT::v16i8:
7366 break;
7367 case MVT::v8i16:
7369 break;
7370 case MVT::v4i32:
7371 case MVT::v2i64:
7372 case MVT::v1i128:
7374 break;
7375 case MVT::v4f32:
7376 case MVT::v2f64:
7378 break;
7379 }
7380 }
7381 }
7382
7383 if (Flags.isByVal() && VA.isMemLoc()) {
7384 const unsigned Size =
7385 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7386 PtrByteSize);
7387 const int FI = MF.getFrameInfo().CreateFixedObject(
7388 Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7389 /* IsAliased */ true);
7390 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7391 InVals.push_back(FIN);
7392
7393 continue;
7394 }
7395
7396 if (Flags.isByVal()) {
7397 assert(VA.isRegLoc() && "MemLocs should already be handled.");
7398
7399 const MCPhysReg ArgReg = VA.getLocReg();
7400 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7401
7402 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7403 const int FI = MF.getFrameInfo().CreateFixedObject(
7404 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7405 /* IsAliased */ true);
7406 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7407 InVals.push_back(FIN);
7408
7409 // Add live ins for all the RegLocs for the same ByVal.
7410 const TargetRegisterClass *RegClass =
7411 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7412
7413 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7414 unsigned Offset) {
7415 const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7416 // Since the callers side has left justified the aggregate in the
7417 // register, we can simply store the entire register into the stack
7418 // slot.
7419 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7420 // The store to the fixedstack object is needed becuase accessing a
7421 // field of the ByVal will use a gep and load. Ideally we will optimize
7422 // to extracting the value from the register directly, and elide the
7423 // stores when the arguments address is not taken, but that will need to
7424 // be future work.
7425 SDValue Store = DAG.getStore(
7426 CopyFrom.getValue(1), dl, CopyFrom,
7429
7430 MemOps.push_back(Store);
7431 };
7432
7433 unsigned Offset = 0;
7434 HandleRegLoc(VA.getLocReg(), Offset);
7435 Offset += PtrByteSize;
7436 for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7437 Offset += PtrByteSize) {
7438 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7439 "RegLocs should be for ByVal argument.");
7440
7441 const CCValAssign RL = ArgLocs[I++];
7442 HandleRegLoc(RL.getLocReg(), Offset);
7444 }
7445
7446 if (Offset != StackSize) {
7447 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7448 "Expected MemLoc for remaining bytes.");
7449 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7450 // Consume the MemLoc.The InVal has already been emitted, so nothing
7451 // more needs to be done.
7452 ++I;
7453 }
7454
7455 continue;
7456 }
7457
7458 if (VA.isRegLoc() && !VA.needsCustom()) {
7459 MVT::SimpleValueType SVT = ValVT.SimpleTy;
7460 Register VReg =
7461 MF.addLiveIn(VA.getLocReg(),
7462 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7463 Subtarget.hasVSX()));
7464 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7465 if (ValVT.isScalarInteger() &&
7466 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7467 ArgValue =
7468 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7469 }
7470 InVals.push_back(ArgValue);
7471 continue;
7472 }
7473 if (VA.isMemLoc()) {
7474 HandleMemLoc();
7475 continue;
7476 }
7477 }
7478
7479 // On AIX a minimum of 8 words is saved to the parameter save area.
7480 const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7481 // Area that is at least reserved in the caller of this function.
7482 unsigned CallerReservedArea = std::max<unsigned>(
7483 CCInfo.getStackSize(), LinkageSize + MinParameterSaveArea);
7484
7485 // Set the size that is at least reserved in caller of this function. Tail
7486 // call optimized function's reserved stack space needs to be aligned so
7487 // that taking the difference between two stack areas will result in an
7488 // aligned stack.
7489 CallerReservedArea =
7490 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7491 FuncInfo->setMinReservedArea(CallerReservedArea);
7492
7493 if (isVarArg) {
7494 int VAListIndex = 0;
7495 // If any of the optional arguments are passed in register then the fixed
7496 // stack object we spill into is not immutable. Create a fixed stack object
7497 // that overlaps the remainder of the parameter save area.
7498 if (CCInfo.getStackSize() < (LinkageSize + MinParameterSaveArea)) {
7499 unsigned FixedStackSize =
7500 LinkageSize + MinParameterSaveArea - CCInfo.getStackSize();
7501 VAListIndex =
7502 MFI.CreateFixedObject(FixedStackSize, CCInfo.getStackSize(),
7503 /* IsImmutable */ false, /* IsAliased */ true);
7504 } else {
7505 // All the arguments passed through ellipses are on the stack. Create a
7506 // dummy fixed stack object the same size as a pointer since we don't
7507 // know the actual size.
7508 VAListIndex =
7509 MFI.CreateFixedObject(PtrByteSize, CCInfo.getStackSize(),
7510 /* IsImmutable */ true, /* IsAliased */ true);
7511 }
7512
7513 FuncInfo->setVarArgsFrameIndex(VAListIndex);
7514 SDValue FIN = DAG.getFrameIndex(VAListIndex, PtrVT);
7515
7516 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7517 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7518
7519 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7520 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7521 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
7522
7523 // The fixed integer arguments of a variadic function are stored to the
7524 // VarArgsFrameIndex on the stack so that they may be loaded by
7525 // dereferencing the result of va_next.
7526 for (unsigned
7527 GPRIndex = (CCInfo.getStackSize() - LinkageSize) / PtrByteSize,
7528 Offset = 0;
7529 GPRIndex < NumGPArgRegs; ++GPRIndex, Offset += PtrByteSize) {
7530
7531 const Register VReg =
7532 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7533 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7534
7535 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7536 MachinePointerInfo MPI =
7537 MachinePointerInfo::getFixedStack(MF, VAListIndex, Offset);
7538 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MPI);
7539 MemOps.push_back(Store);
7540 // Increment the address for the next argument to store.
7541 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7542 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7543 }
7544 }
7545
7546 if (!MemOps.empty())
7547 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7548
7549 return Chain;
7550}
7551
7552SDValue PPCTargetLowering::LowerCall_AIX(
7553 SDValue Chain, SDValue Callee, CallFlags CFlags,
7555 const SmallVectorImpl<SDValue> &OutVals,
7556 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7558 const CallBase *CB) const {
7559 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7560 // AIX ABI stack frame layout.
7561
7562 assert((CFlags.CallConv == CallingConv::C ||
7563 CFlags.CallConv == CallingConv::Cold ||
7564 CFlags.CallConv == CallingConv::Fast) &&
7565 "Unexpected calling convention!");
7566
7567 if (CFlags.IsPatchPoint)
7568 report_fatal_error("This call type is unimplemented on AIX.");
7569
7570 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7571
7574 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7575 *DAG.getContext());
7576
7577 // Reserve space for the linkage save area (LSA) on the stack.
7578 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7579 // [SP][CR][LR][2 x reserved][TOC].
7580 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7581 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7582 const bool IsPPC64 = Subtarget.isPPC64();
7583 const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7584 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7585 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7586 CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7587
7588 // The prolog code of the callee may store up to 8 GPR argument registers to
7589 // the stack, allowing va_start to index over them in memory if the callee
7590 // is variadic.
7591 // Because we cannot tell if this is needed on the caller side, we have to
7592 // conservatively assume that it is needed. As such, make sure we have at
7593 // least enough stack space for the caller to store the 8 GPRs.
7594 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7595 const unsigned NumBytes = std::max<unsigned>(
7596 LinkageSize + MinParameterSaveAreaSize, CCInfo.getStackSize());
7597
7598 // Adjust the stack pointer for the new arguments...
7599 // These operations are automatically eliminated by the prolog/epilog pass.
7600 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7601 SDValue CallSeqStart = Chain;
7602
7604 SmallVector<SDValue, 8> MemOpChains;
7605
7606 // Set up a copy of the stack pointer for loading and storing any
7607 // arguments that may not fit in the registers available for argument
7608 // passing.
7609 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7610 : DAG.getRegister(PPC::R1, MVT::i32);
7611
7612 for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7613 const unsigned ValNo = ArgLocs[I].getValNo();
7614 SDValue Arg = OutVals[ValNo];
7615 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7616
7617 if (Flags.isByVal()) {
7618 const unsigned ByValSize = Flags.getByValSize();
7619
7620 // Nothing to do for zero-sized ByVals on the caller side.
7621 if (!ByValSize) {
7622 ++I;
7623 continue;
7624 }
7625
7626 auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7627 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7628 (LoadOffset != 0)
7629 ? DAG.getObjectPtrOffset(
7630 dl, Arg, TypeSize::getFixed(LoadOffset))
7631 : Arg,
7632 MachinePointerInfo(), VT);
7633 };
7634
7635 unsigned LoadOffset = 0;
7636
7637 // Initialize registers, which are fully occupied by the by-val argument.
7638 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7639 SDValue Load = GetLoad(PtrVT, LoadOffset);
7640 MemOpChains.push_back(Load.getValue(1));
7641 LoadOffset += PtrByteSize;
7642 const CCValAssign &ByValVA = ArgLocs[I++];
7643 assert(ByValVA.getValNo() == ValNo &&
7644 "Unexpected location for pass-by-value argument.");
7645 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7646 }
7647
7648 if (LoadOffset == ByValSize)
7649 continue;
7650
7651 // There must be one more loc to handle the remainder.
7652 assert(ArgLocs[I].getValNo() == ValNo &&
7653 "Expected additional location for by-value argument.");
7654
7655 if (ArgLocs[I].isMemLoc()) {
7656 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7657 const CCValAssign &ByValVA = ArgLocs[I++];
7658 ISD::ArgFlagsTy MemcpyFlags = Flags;
7659 // Only memcpy the bytes that don't pass in register.
7660 MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7661 Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7662 (LoadOffset != 0) ? DAG.getObjectPtrOffset(
7663 dl, Arg, TypeSize::getFixed(LoadOffset))
7664 : Arg,
7666 dl, StackPtr, TypeSize::getFixed(ByValVA.getLocMemOffset())),
7667 CallSeqStart, MemcpyFlags, DAG, dl);
7668 continue;
7669 }
7670
7671 // Initialize the final register residue.
7672 // Any residue that occupies the final by-val arg register must be
7673 // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7674 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7675 // 2 and 1 byte loads.
7676 const unsigned ResidueBytes = ByValSize % PtrByteSize;
7677 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7678 "Unexpected register residue for by-value argument.");
7679 SDValue ResidueVal;
7680 for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7681 const unsigned N = llvm::bit_floor(ResidueBytes - Bytes);
7682 const MVT VT =
7683 N == 1 ? MVT::i8
7684 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7685 SDValue Load = GetLoad(VT, LoadOffset);
7686 MemOpChains.push_back(Load.getValue(1));
7687 LoadOffset += N;
7688 Bytes += N;
7689
7690 // By-val arguments are passed left-justfied in register.
7691 // Every load here needs to be shifted, otherwise a full register load
7692 // should have been used.
7693 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7694 "Unexpected load emitted during handling of pass-by-value "
7695 "argument.");
7696 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7697 EVT ShiftAmountTy =
7698 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7699 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7700 SDValue ShiftedLoad =
7701 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7702 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7703 ShiftedLoad)
7704 : ShiftedLoad;
7705 }
7706
7707 const CCValAssign &ByValVA = ArgLocs[I++];
7708 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7709 continue;
7710 }
7711
7712 CCValAssign &VA = ArgLocs[I++];
7713 const MVT LocVT = VA.getLocVT();
7714 const MVT ValVT = VA.getValVT();
7715
7716 switch (VA.getLocInfo()) {
7717 default:
7718 report_fatal_error("Unexpected argument extension type.");
7719 case CCValAssign::Full:
7720 break;
7721 case CCValAssign::ZExt:
7722 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7723 break;
7724 case CCValAssign::SExt:
7725 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7726 break;
7727 }
7728
7729 if (VA.isRegLoc() && !VA.needsCustom()) {
7730 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7731 continue;
7732 }
7733
7734 // Vector arguments passed to VarArg functions need custom handling when
7735 // they are passed (at least partially) in GPRs.
7736 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7737 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7738 // Store value to its stack slot.
7739 SDValue PtrOff =
7740 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7741 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7742 SDValue Store =
7743 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7744 MemOpChains.push_back(Store);
7745 const unsigned OriginalValNo = VA.getValNo();
7746 // Then load the GPRs from the stack
7747 unsigned LoadOffset = 0;
7748 auto HandleCustomVecRegLoc = [&]() {
7749 assert(I != E && "Unexpected end of CCvalAssigns.");
7750 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7751 "Expected custom RegLoc.");
7752 CCValAssign RegVA = ArgLocs[I++];
7753 assert(RegVA.getValNo() == OriginalValNo &&
7754 "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7755 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7756 DAG.getConstant(LoadOffset, dl, PtrVT));
7757 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7758 MemOpChains.push_back(Load.getValue(1));
7759 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7760 LoadOffset += PtrByteSize;
7761 };
7762
7763 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7764 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7765 // R10.
7766 HandleCustomVecRegLoc();
7767 HandleCustomVecRegLoc();
7768
7769 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7770 ArgLocs[I].getValNo() == OriginalValNo) {
7771 assert(!IsPPC64 &&
7772 "Only 2 custom RegLocs expected for 64-bit codegen.");
7773 HandleCustomVecRegLoc();
7774 HandleCustomVecRegLoc();
7775 }
7776
7777 continue;
7778 }
7779
7780 if (VA.isMemLoc()) {
7781 SDValue PtrOff =
7782 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7783 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7784 MemOpChains.push_back(
7785 DAG.getStore(Chain, dl, Arg, PtrOff,
7787 Subtarget.getFrameLowering()->getStackAlign()));
7788
7789 continue;
7790 }
7791
7792 if (!ValVT.isFloatingPoint())
7794 "Unexpected register handling for calling convention.");
7795
7796 // Custom handling is used for GPR initializations for vararg float
7797 // arguments.
7798 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7799 LocVT.isInteger() &&
7800 "Custom register handling only expected for VarArg.");
7801
7802 SDValue ArgAsInt =
7803 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7804
7805 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7806 // f32 in 32-bit GPR
7807 // f64 in 64-bit GPR
7808 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7809 else if (Arg.getValueType().getFixedSizeInBits() <
7810 LocVT.getFixedSizeInBits())
7811 // f32 in 64-bit GPR.
7812 RegsToPass.push_back(std::make_pair(
7813 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7814 else {
7815 // f64 in two 32-bit GPRs
7816 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7817 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7818 "Unexpected custom register for argument!");
7819 CCValAssign &GPR1 = VA;
7820 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7821 DAG.getConstant(32, dl, MVT::i8));
7822 RegsToPass.push_back(std::make_pair(
7823 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7824
7825 if (I != E) {
7826 // If only 1 GPR was available, there will only be one custom GPR and
7827 // the argument will also pass in memory.
7828 CCValAssign &PeekArg = ArgLocs[I];
7829 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7830 assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7831 CCValAssign &GPR2 = ArgLocs[I++];
7832 RegsToPass.push_back(std::make_pair(
7833 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7834 }
7835 }
7836 }
7837 }
7838
7839 if (!MemOpChains.empty())
7840 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7841
7842 // For indirect calls, we need to save the TOC base to the stack for
7843 // restoration after the call.
7844 if (CFlags.IsIndirect && !Subtarget.usePointerGlueHelper()) {
7845 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7846 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7847 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7848 const MVT PtrVT = Subtarget.getScalarIntVT();
7849 const unsigned TOCSaveOffset =
7850 Subtarget.getFrameLowering()->getTOCSaveOffset();
7851
7852 setUsesTOCBasePtr(DAG);
7853 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7854 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7855 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7856 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7857 Chain = DAG.getStore(
7858 Val.getValue(1), dl, Val, AddPtr,
7859 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7860 }
7861
7862 // Build a sequence of copy-to-reg nodes chained together with token chain
7863 // and flag operands which copy the outgoing args into the appropriate regs.
7864 SDValue InGlue;
7865 for (auto Reg : RegsToPass) {
7866 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InGlue);
7867 InGlue = Chain.getValue(1);
7868 }
7869
7870 const int SPDiff = 0;
7871 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
7872 Callee, SPDiff, NumBytes, Ins, InVals, CB);
7873}
7874
7875bool
7876PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7877 MachineFunction &MF, bool isVarArg,
7880 const Type *RetTy) const {
7882 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7883 return CCInfo.CheckReturn(
7884 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7886 : RetCC_PPC);
7887}
7888
7889SDValue
7890PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7891 bool isVarArg,
7893 const SmallVectorImpl<SDValue> &OutVals,
7894 const SDLoc &dl, SelectionDAG &DAG) const {
7896 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7897 *DAG.getContext());
7898 CCInfo.AnalyzeReturn(Outs,
7899 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7901 : RetCC_PPC);
7902
7903 SDValue Glue;
7904 SmallVector<SDValue, 4> RetOps(1, Chain);
7905
7906 // Copy the result values into the output registers.
7907 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7908 CCValAssign &VA = RVLocs[i];
7909 assert(VA.isRegLoc() && "Can only return in registers!");
7910
7911 SDValue Arg = OutVals[RealResIdx];
7912
7913 switch (VA.getLocInfo()) {
7914 default: llvm_unreachable("Unknown loc info!");
7915 case CCValAssign::Full: break;
7916 case CCValAssign::AExt:
7917 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7918 break;
7919 case CCValAssign::ZExt:
7920 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7921 break;
7922 case CCValAssign::SExt:
7923 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7924 break;
7925 }
7926 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7927 bool isLittleEndian = Subtarget.isLittleEndian();
7928 // Legalize ret f64 -> ret 2 x i32.
7929 SDValue SVal =
7930 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7931 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7933 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7934 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7935 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7936 Glue = Chain.getValue(1);
7937 VA = RVLocs[++i]; // skip ahead to next loc
7938 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7939 } else
7940 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
7941 Glue = Chain.getValue(1);
7942 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7943 }
7944
7945 RetOps[0] = Chain; // Update chain.
7946
7947 // Add the glue if we have it.
7948 if (Glue.getNode())
7949 RetOps.push_back(Glue);
7950
7951 return DAG.getNode(PPCISD::RET_GLUE, dl, MVT::Other, RetOps);
7952}
7953
7954SDValue
7955PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7956 SelectionDAG &DAG) const {
7957 SDLoc dl(Op);
7958
7959 // Get the correct type for integers.
7960 EVT IntVT = Op.getValueType();
7961
7962 // Get the inputs.
7963 SDValue Chain = Op.getOperand(0);
7964 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7965 // Build a DYNAREAOFFSET node.
7966 SDValue Ops[2] = {Chain, FPSIdx};
7967 SDVTList VTs = DAG.getVTList(IntVT);
7968 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7969}
7970
7971SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7972 SelectionDAG &DAG) const {
7973 // When we pop the dynamic allocation we need to restore the SP link.
7974 SDLoc dl(Op);
7975
7976 // Get the correct type for pointers.
7977 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7978
7979 // Construct the stack pointer operand.
7980 bool isPPC64 = Subtarget.isPPC64();
7981 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7982 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7983
7984 // Get the operands for the STACKRESTORE.
7985 SDValue Chain = Op.getOperand(0);
7986 SDValue SaveSP = Op.getOperand(1);
7987
7988 // Load the old link SP.
7989 SDValue LoadLinkSP =
7990 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7991
7992 // Restore the stack pointer.
7993 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7994
7995 // Store the old link SP.
7996 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7997}
7998
7999SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
8001 bool isPPC64 = Subtarget.isPPC64();
8002 EVT PtrVT = getPointerTy(MF.getDataLayout());
8003
8004 // Get current frame pointer save index. The users of this index will be
8005 // primarily DYNALLOC instructions.
8006 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8007 int RASI = FI->getReturnAddrSaveIndex();
8008
8009 // If the frame pointer save index hasn't been defined yet.
8010 if (!RASI) {
8011 // Find out what the fix offset of the frame pointer save area.
8012 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
8013 // Allocate the frame index for frame pointer save area.
8014 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
8015 // Save the result.
8016 FI->setReturnAddrSaveIndex(RASI);
8017 }
8018 return DAG.getFrameIndex(RASI, PtrVT);
8019}
8020
8021SDValue
8022PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
8024 bool isPPC64 = Subtarget.isPPC64();
8025 EVT PtrVT = getPointerTy(MF.getDataLayout());
8026
8027 // Get current frame pointer save index. The users of this index will be
8028 // primarily DYNALLOC instructions.
8029 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8030 int FPSI = FI->getFramePointerSaveIndex();
8031
8032 // If the frame pointer save index hasn't been defined yet.
8033 if (!FPSI) {
8034 // Find out what the fix offset of the frame pointer save area.
8035 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
8036 // Allocate the frame index for frame pointer save area.
8037 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
8038 // Save the result.
8039 FI->setFramePointerSaveIndex(FPSI);
8040 }
8041 return DAG.getFrameIndex(FPSI, PtrVT);
8042}
8043
8044SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8045 SelectionDAG &DAG) const {
8047 // Get the inputs.
8048 SDValue Chain = Op.getOperand(0);
8049 SDValue Size = Op.getOperand(1);
8050 SDLoc dl(Op);
8051
8052 // Get the correct type for pointers.
8053 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8054 // Negate the size.
8055 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
8056 DAG.getConstant(0, dl, PtrVT), Size);
8057 // Construct a node for the frame pointer save index.
8058 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
8059 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
8060 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
8061 if (hasInlineStackProbe(MF))
8062 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
8063 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
8064}
8065
8066SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
8067 SelectionDAG &DAG) const {
8069
8070 bool isPPC64 = Subtarget.isPPC64();
8071 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8072
8073 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
8074 return DAG.getFrameIndex(FI, PtrVT);
8075}
8076
8077SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
8078 SelectionDAG &DAG) const {
8079 SDLoc DL(Op);
8080 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
8081 DAG.getVTList(MVT::i32, MVT::Other),
8082 Op.getOperand(0), Op.getOperand(1));
8083}
8084
8085SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
8086 SelectionDAG &DAG) const {
8087 SDLoc DL(Op);
8088 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
8089 Op.getOperand(0), Op.getOperand(1));
8090}
8091
8092SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8093 if (Op.getValueType().isVector())
8094 return LowerVectorLoad(Op, DAG);
8095
8096 assert(Op.getValueType() == MVT::i1 &&
8097 "Custom lowering only for i1 loads");
8098
8099 // First, load 8 bits into 32 bits, then truncate to 1 bit.
8100
8101 SDLoc dl(Op);
8102 LoadSDNode *LD = cast<LoadSDNode>(Op);
8103
8104 SDValue Chain = LD->getChain();
8105 SDValue BasePtr = LD->getBasePtr();
8106 MachineMemOperand *MMO = LD->getMemOperand();
8107
8108 SDValue NewLD =
8109 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8110 BasePtr, MVT::i8, MMO);
8111 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8112
8113 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8114 return DAG.getMergeValues(Ops, dl);
8115}
8116
8117SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8118 if (Op.getOperand(1).getValueType().isVector())
8119 return LowerVectorStore(Op, DAG);
8120
8121 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8122 "Custom lowering only for i1 stores");
8123
8124 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8125
8126 SDLoc dl(Op);
8127 StoreSDNode *ST = cast<StoreSDNode>(Op);
8128
8129 SDValue Chain = ST->getChain();
8130 SDValue BasePtr = ST->getBasePtr();
8131 SDValue Value = ST->getValue();
8132 MachineMemOperand *MMO = ST->getMemOperand();
8133
8135 Value);
8136 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8137}
8138
8139// FIXME: Remove this once the ANDI glue bug is fixed:
8140SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8141 assert(Op.getValueType() == MVT::i1 &&
8142 "Custom lowering only for i1 results");
8143
8144 SDLoc DL(Op);
8145 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8146}
8147
8148SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8149 SelectionDAG &DAG) const {
8150
8151 // Implements a vector truncate that fits in a vector register as a shuffle.
8152 // We want to legalize vector truncates down to where the source fits in
8153 // a vector register (and target is therefore smaller than vector register
8154 // size). At that point legalization will try to custom lower the sub-legal
8155 // result and get here - where we can contain the truncate as a single target
8156 // operation.
8157
8158 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8159 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8160 //
8161 // We will implement it for big-endian ordering as this (where x denotes
8162 // undefined):
8163 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8164 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8165 //
8166 // The same operation in little-endian ordering will be:
8167 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8168 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8169
8170 EVT TrgVT = Op.getValueType();
8171 assert(TrgVT.isVector() && "Vector type expected.");
8172 unsigned TrgNumElts = TrgVT.getVectorNumElements();
8173 EVT EltVT = TrgVT.getVectorElementType();
8174 if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8175 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8177 return SDValue();
8178
8179 SDValue N1 = Op.getOperand(0);
8180 EVT SrcVT = N1.getValueType();
8181 unsigned SrcSize = SrcVT.getSizeInBits();
8182 if (SrcSize > 256 || !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8185 return SDValue();
8186 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8187 return SDValue();
8188
8189 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8190 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8191
8192 SDLoc DL(Op);
8193 SDValue Op1, Op2;
8194 if (SrcSize == 256) {
8195 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8196 EVT SplitVT =
8198 unsigned SplitNumElts = SplitVT.getVectorNumElements();
8199 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8200 DAG.getConstant(0, DL, VecIdxTy));
8201 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8202 DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8203 }
8204 else {
8205 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8206 Op2 = DAG.getUNDEF(WideVT);
8207 }
8208
8209 // First list the elements we want to keep.
8210 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8211 SmallVector<int, 16> ShuffV;
8212 if (Subtarget.isLittleEndian())
8213 for (unsigned i = 0; i < TrgNumElts; ++i)
8214 ShuffV.push_back(i * SizeMult);
8215 else
8216 for (unsigned i = 1; i <= TrgNumElts; ++i)
8217 ShuffV.push_back(i * SizeMult - 1);
8218
8219 // Populate the remaining elements with undefs.
8220 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8221 // ShuffV.push_back(i + WideNumElts);
8222 ShuffV.push_back(WideNumElts + 1);
8223
8224 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8225 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8226 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8227}
8228
8229/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8230/// possible.
8231SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8232 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8233 EVT ResVT = Op.getValueType();
8234 EVT CmpVT = Op.getOperand(0).getValueType();
8235 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8236 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
8237 SDLoc dl(Op);
8238
8239 // Without power9-vector, we don't have native instruction for f128 comparison.
8240 // Following transformation to libcall is needed for setcc:
8241 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
8242 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
8243 SDValue Z = DAG.getSetCC(
8244 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
8245 LHS, RHS, CC);
8246 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
8247 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
8248 }
8249
8250 // Not FP, or using SPE? Not a fsel.
8251 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
8252 Subtarget.hasSPE())
8253 return Op;
8254
8255 SDNodeFlags Flags = Op.getNode()->getFlags();
8256
8257 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
8258 // presence of infinities.
8259 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8260 switch (CC) {
8261 default:
8262 break;
8263 case ISD::SETOGT:
8264 case ISD::SETGT:
8265 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
8266 case ISD::SETOLT:
8267 case ISD::SETLT:
8268 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
8269 }
8270 }
8271
8272 // We might be able to do better than this under some circumstances, but in
8273 // general, fsel-based lowering of select is a finite-math-only optimization.
8274 // For more information, see section F.3 of the 2.06 ISA specification.
8275 // With ISA 3.0
8276 if (!Flags.hasNoInfs() || !Flags.hasNoNaNs() || ResVT == MVT::f128)
8277 return Op;
8278
8279 // If the RHS of the comparison is a 0.0, we don't need to do the
8280 // subtraction at all.
8281 SDValue Sel1;
8283 switch (CC) {
8284 default: break; // SETUO etc aren't handled by fsel.
8285 case ISD::SETNE:
8286 std::swap(TV, FV);
8287 [[fallthrough]];
8288 case ISD::SETEQ:
8289 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8290 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8291 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8292 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8293 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8294 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8295 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8296 case ISD::SETULT:
8297 case ISD::SETLT:
8298 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8299 [[fallthrough]];
8300 case ISD::SETOGE:
8301 case ISD::SETGE:
8302 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8303 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8304 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8305 case ISD::SETUGT:
8306 case ISD::SETGT:
8307 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8308 [[fallthrough]];
8309 case ISD::SETOLE:
8310 case ISD::SETLE:
8311 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8312 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8313 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8314 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8315 }
8316
8317 SDValue Cmp;
8318 switch (CC) {
8319 default: break; // SETUO etc aren't handled by fsel.
8320 case ISD::SETNE:
8321 std::swap(TV, FV);
8322 [[fallthrough]];
8323 case ISD::SETEQ:
8324 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8325 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8326 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8327 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8328 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8329 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8330 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8331 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8332 case ISD::SETULT:
8333 case ISD::SETLT:
8334 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8335 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8336 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8337 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8338 case ISD::SETOGE:
8339 case ISD::SETGE:
8340 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8341 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8342 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8343 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8344 case ISD::SETUGT:
8345 case ISD::SETGT:
8346 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8347 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8348 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8349 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8350 case ISD::SETOLE:
8351 case ISD::SETLE:
8352 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8353 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8354 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8355 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8356 }
8357 return Op;
8358}
8359
8360static unsigned getPPCStrictOpcode(unsigned Opc) {
8361 switch (Opc) {
8362 default:
8363 llvm_unreachable("No strict version of this opcode!");
8364 case PPCISD::FCTIDZ:
8365 return PPCISD::STRICT_FCTIDZ;
8366 case PPCISD::FCTIWZ:
8367 return PPCISD::STRICT_FCTIWZ;
8368 case PPCISD::FCTIDUZ:
8369 return PPCISD::STRICT_FCTIDUZ;
8370 case PPCISD::FCTIWUZ:
8371 return PPCISD::STRICT_FCTIWUZ;
8372 case PPCISD::FCFID:
8373 return PPCISD::STRICT_FCFID;
8374 case PPCISD::FCFIDU:
8375 return PPCISD::STRICT_FCFIDU;
8376 case PPCISD::FCFIDS:
8377 return PPCISD::STRICT_FCFIDS;
8378 case PPCISD::FCFIDUS:
8379 return PPCISD::STRICT_FCFIDUS;
8380 }
8381}
8382
8384 const PPCSubtarget &Subtarget) {
8385 SDLoc dl(Op);
8386 bool IsStrict = Op->isStrictFPOpcode();
8387 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8388 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8389
8390 // TODO: Any other flags to propagate?
8391 SDNodeFlags Flags;
8392 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8393
8394 // For strict nodes, source is the second operand.
8395 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8396 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8397 MVT DestTy = Op.getSimpleValueType();
8398 assert(Src.getValueType().isFloatingPoint() &&
8399 (DestTy == MVT::i8 || DestTy == MVT::i16 || DestTy == MVT::i32 ||
8400 DestTy == MVT::i64) &&
8401 "Invalid FP_TO_INT types");
8402 if (Src.getValueType() == MVT::f32) {
8403 if (IsStrict) {
8404 Src =
8406 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8407 Chain = Src.getValue(1);
8408 } else
8409 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8410 }
8411 if ((DestTy == MVT::i8 || DestTy == MVT::i16) && Subtarget.hasP9Vector())
8412 DestTy = Subtarget.getScalarIntVT();
8413 unsigned Opc = ISD::DELETED_NODE;
8414 switch (DestTy.SimpleTy) {
8415 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8416 case MVT::i32:
8417 Opc = IsSigned ? PPCISD::FCTIWZ
8418 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8419 break;
8420 case MVT::i64:
8421 assert((IsSigned || Subtarget.hasFPCVT()) &&
8422 "i64 FP_TO_UINT is supported only with FPCVT");
8423 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8424 }
8425 EVT ConvTy = Src.getValueType() == MVT::f128 ? MVT::f128 : MVT::f64;
8426 SDValue Conv;
8427 if (IsStrict) {
8429 Conv = DAG.getNode(Opc, dl, DAG.getVTList(ConvTy, MVT::Other), {Chain, Src},
8430 Flags);
8431 } else {
8432 Conv = DAG.getNode(Opc, dl, ConvTy, Src);
8433 }
8434 return Conv;
8435}
8436
8437void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8438 SelectionDAG &DAG,
8439 const SDLoc &dl) const {
8440 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8441 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8442 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8443 bool IsStrict = Op->isStrictFPOpcode();
8444
8445 // Convert the FP value to an int value through memory.
8446 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8447 (IsSigned || Subtarget.hasFPCVT());
8448 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8449 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8450 MachinePointerInfo MPI =
8452
8453 // Emit a store to the stack slot.
8454 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8456 if (i32Stack) {
8458 Alignment = Align(4);
8459 MachineMemOperand *MMO =
8460 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8461 SDValue Ops[] = { Chain, Tmp, FIPtr };
8462 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8463 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8464 } else
8465 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8466
8467 // Result is a load from the stack slot. If loading 4 bytes, make sure to
8468 // add in a bias on big endian.
8469 if (Op.getValueType() == MVT::i32 && !i32Stack &&
8470 !Subtarget.isLittleEndian()) {
8471 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8472 DAG.getConstant(4, dl, FIPtr.getValueType()));
8473 MPI = MPI.getWithOffset(4);
8474 }
8475
8476 RLI.Chain = Chain;
8477 RLI.Ptr = FIPtr;
8478 RLI.MPI = MPI;
8479 RLI.Alignment = Alignment;
8480}
8481
8482/// Custom lowers floating point to integer conversions to use
8483/// the direct move instructions available in ISA 2.07 to avoid the
8484/// need for load/store combinations.
8485SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8486 SelectionDAG &DAG,
8487 const SDLoc &dl) const {
8488 SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8489 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8490 if (Op->isStrictFPOpcode())
8491 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8492 else
8493 return Mov;
8494}
8495
8496SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8497 const SDLoc &dl) const {
8498 bool IsStrict = Op->isStrictFPOpcode();
8499 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8500 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8501 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8502 EVT SrcVT = Src.getValueType();
8503 EVT DstVT = Op.getValueType();
8504
8505 // FP to INT conversions are legal for f128.
8506 if (SrcVT == MVT::f128)
8507 return Subtarget.hasP9Vector() ? Op : SDValue();
8508
8509 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8510 // PPC (the libcall is not available).
8511 if (SrcVT == MVT::ppcf128) {
8512 if (DstVT == MVT::i32) {
8513 // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8514 // set other fast-math flags to FP operations in both strict and
8515 // non-strict cases. (FP_TO_SINT, FSUB)
8516 SDNodeFlags Flags;
8517 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8518
8519 if (IsSigned) {
8520 SDValue Lo, Hi;
8521 std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::f64, MVT::f64);
8522
8523 // Add the two halves of the long double in round-to-zero mode, and use
8524 // a smaller FP_TO_SINT.
8525 if (IsStrict) {
8526 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8527 DAG.getVTList(MVT::f64, MVT::Other),
8528 {Op.getOperand(0), Lo, Hi}, Flags);
8529 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8530 DAG.getVTList(MVT::i32, MVT::Other),
8531 {Res.getValue(1), Res}, Flags);
8532 } else {
8533 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8534 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8535 }
8536 } else {
8537 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8538 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8539 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8540 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8541 if (IsStrict) {
8542 // Sel = Src < 0x80000000
8543 // FltOfs = select Sel, 0.0, 0x80000000
8544 // IntOfs = select Sel, 0, 0x80000000
8545 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8546 SDValue Chain = Op.getOperand(0);
8547 EVT SetCCVT =
8548 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8549 EVT DstSetCCVT =
8550 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8551 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8552 Chain, true);
8553 Chain = Sel.getValue(1);
8554
8555 SDValue FltOfs = DAG.getSelect(
8556 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8557 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8558
8559 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8560 DAG.getVTList(SrcVT, MVT::Other),
8561 {Chain, Src, FltOfs}, Flags);
8562 Chain = Val.getValue(1);
8563 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8564 DAG.getVTList(DstVT, MVT::Other),
8565 {Chain, Val}, Flags);
8566 Chain = SInt.getValue(1);
8567 SDValue IntOfs = DAG.getSelect(
8568 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8569 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8570 return DAG.getMergeValues({Result, Chain}, dl);
8571 } else {
8572 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8573 // FIXME: generated code sucks.
8574 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8575 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8576 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8577 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8578 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8579 }
8580 }
8581 }
8582
8583 return SDValue();
8584 }
8585
8586 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8587 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8588
8589 ReuseLoadInfo RLI;
8590 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8591
8592 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8593 RLI.Alignment, RLI.MMOFlags(),
8594 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8595}
8596
8597// We're trying to insert a regular store, S, and then a load, L. If the
8598// incoming value, O, is a load, we might just be able to have our load use the
8599// address used by O. However, we don't know if anything else will store to
8600// that address before we can load from it. To prevent this situation, we need
8601// to insert our load, L, into the chain as a peer of O. To do this, we give L
8602// the same chain operand as O, we create a token factor from the chain results
8603// of O and L, and we replace all uses of O's chain result with that token
8604// factor (this last part is handled by makeEquivalentMemoryOrdering).
8605bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8606 ReuseLoadInfo &RLI,
8607 SelectionDAG &DAG,
8608 ISD::LoadExtType ET) const {
8609 // Conservatively skip reusing for constrained FP nodes.
8610 if (Op->isStrictFPOpcode())
8611 return false;
8612
8613 SDLoc dl(Op);
8614 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8615 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8616 if (ET == ISD::NON_EXTLOAD &&
8617 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8618 isOperationLegalOrCustom(Op.getOpcode(),
8619 Op.getOperand(0).getValueType())) {
8620
8621 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8622 return true;
8623 }
8624
8625 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8626 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8627 LD->isNonTemporal())
8628 return false;
8629 if (LD->getMemoryVT() != MemVT)
8630 return false;
8631
8632 // If the result of the load is an illegal type, then we can't build a
8633 // valid chain for reuse since the legalised loads and token factor node that
8634 // ties the legalised loads together uses a different output chain then the
8635 // illegal load.
8636 if (!isTypeLegal(LD->getValueType(0)))
8637 return false;
8638
8639 RLI.Ptr = LD->getBasePtr();
8640 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8641 assert(LD->getAddressingMode() == ISD::PRE_INC &&
8642 "Non-pre-inc AM on PPC?");
8643 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8644 LD->getOffset());
8645 }
8646
8647 RLI.Chain = LD->getChain();
8648 RLI.MPI = LD->getPointerInfo();
8649 RLI.IsDereferenceable = LD->isDereferenceable();
8650 RLI.IsInvariant = LD->isInvariant();
8651 RLI.Alignment = LD->getAlign();
8652 RLI.AAInfo = LD->getAAInfo();
8653 RLI.Ranges = LD->getRanges();
8654
8655 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8656 return true;
8657}
8658
8659/// Analyze profitability of direct move
8660/// prefer float load to int load plus direct move
8661/// when there is no integer use of int load
8662bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8663 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode();
8664 if (Origin->getOpcode() != ISD::LOAD)
8665 return true;
8666
8667 // If there is no LXSIBZX/LXSIHZX, like Power8,
8668 // prefer direct move if the memory size is 1 or 2 bytes.
8669 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8670 if (!Subtarget.hasP9Vector() &&
8671 (!MMO->getSize().hasValue() || MMO->getSize().getValue() <= 2))
8672 return true;
8673
8674 for (SDUse &Use : Origin->uses()) {
8675
8676 // Only look at the users of the loaded value.
8677 if (Use.getResNo() != 0)
8678 continue;
8679
8680 SDNode *User = Use.getUser();
8681 if (User->getOpcode() != ISD::SINT_TO_FP &&
8682 User->getOpcode() != ISD::UINT_TO_FP &&
8683 User->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8684 User->getOpcode() != ISD::STRICT_UINT_TO_FP)
8685 return true;
8686 }
8687
8688 return false;
8689}
8690
8692 const PPCSubtarget &Subtarget,
8693 SDValue Chain = SDValue()) {
8694 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8695 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8696 SDLoc dl(Op);
8697
8698 // TODO: Any other flags to propagate?
8699 SDNodeFlags Flags;
8700 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8701
8702 // If we have FCFIDS, then use it when converting to single-precision.
8703 // Otherwise, convert to double-precision and then round.
8704 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8705 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8706 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8707 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8708 if (Op->isStrictFPOpcode()) {
8709 if (!Chain)
8710 Chain = Op.getOperand(0);
8711 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8712 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8713 } else
8714 return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8715}
8716
8717/// Custom lowers integer to floating point conversions to use
8718/// the direct move instructions available in ISA 2.07 to avoid the
8719/// need for load/store combinations.
8720SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8721 SelectionDAG &DAG,
8722 const SDLoc &dl) const {
8723 assert((Op.getValueType() == MVT::f32 ||
8724 Op.getValueType() == MVT::f64) &&
8725 "Invalid floating point type as target of conversion");
8726 assert(Subtarget.hasFPCVT() &&
8727 "Int to FP conversions with direct moves require FPCVT");
8728 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8729 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8730 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8731 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8732 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8733 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8734 return convertIntToFP(Op, Mov, DAG, Subtarget);
8735}
8736
8737static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8738
8739 EVT VecVT = Vec.getValueType();
8740 assert(VecVT.isVector() && "Expected a vector type.");
8741 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8742
8743 EVT EltVT = VecVT.getVectorElementType();
8744 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8745 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8746
8747 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8748 SmallVector<SDValue, 16> Ops(NumConcat);
8749 Ops[0] = Vec;
8750 SDValue UndefVec = DAG.getUNDEF(VecVT);
8751 for (unsigned i = 1; i < NumConcat; ++i)
8752 Ops[i] = UndefVec;
8753
8754 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8755}
8756
8757SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8758 const SDLoc &dl) const {
8759 bool IsStrict = Op->isStrictFPOpcode();
8760 unsigned Opc = Op.getOpcode();
8761 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8764 "Unexpected conversion type");
8765 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8766 "Supports conversions to v2f64/v4f32 only.");
8767
8768 // TODO: Any other flags to propagate?
8769 SDNodeFlags Flags;
8770 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8771
8772 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8773 bool FourEltRes = Op.getValueType() == MVT::v4f32;
8774
8775 SDValue Wide = widenVec(DAG, Src, dl);
8776 EVT WideVT = Wide.getValueType();
8777 unsigned WideNumElts = WideVT.getVectorNumElements();
8778 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8779
8780 SmallVector<int, 16> ShuffV;
8781 for (unsigned i = 0; i < WideNumElts; ++i)
8782 ShuffV.push_back(i + WideNumElts);
8783
8784 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8785 int SaveElts = FourEltRes ? 4 : 2;
8786 if (Subtarget.isLittleEndian())
8787 for (int i = 0; i < SaveElts; i++)
8788 ShuffV[i * Stride] = i;
8789 else
8790 for (int i = 1; i <= SaveElts; i++)
8791 ShuffV[i * Stride - 1] = i - 1;
8792
8793 SDValue ShuffleSrc2 =
8794 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8795 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8796
8797 SDValue Extend;
8798 if (SignedConv) {
8799 Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8800 EVT ExtVT = Src.getValueType();
8801 if (Subtarget.hasP9Altivec())
8802 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8803 IntermediateVT.getVectorNumElements());
8804
8805 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8806 DAG.getValueType(ExtVT));
8807 } else
8808 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8809
8810 if (IsStrict)
8811 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8812 {Op.getOperand(0), Extend}, Flags);
8813
8814 return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8815}
8816
8817SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8818 SelectionDAG &DAG) const {
8819 SDLoc dl(Op);
8820 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8821 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8822 bool IsStrict = Op->isStrictFPOpcode();
8823 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8824 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8825
8826 // TODO: Any other flags to propagate?
8827 SDNodeFlags Flags;
8828 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8829
8830 EVT InVT = Src.getValueType();
8831 EVT OutVT = Op.getValueType();
8832 if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8833 isOperationCustom(Op.getOpcode(), InVT))
8834 return LowerINT_TO_FPVector(Op, DAG, dl);
8835
8836 // Conversions to f128 are legal.
8837 if (Op.getValueType() == MVT::f128)
8838 return Subtarget.hasP9Vector() ? Op : SDValue();
8839
8840 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8841 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8842 return SDValue();
8843
8844 if (Src.getValueType() == MVT::i1) {
8845 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8846 DAG.getConstantFP(1.0, dl, Op.getValueType()),
8847 DAG.getConstantFP(0.0, dl, Op.getValueType()));
8848 if (IsStrict)
8849 return DAG.getMergeValues({Sel, Chain}, dl);
8850 else
8851 return Sel;
8852 }
8853
8854 // If we have direct moves, we can do all the conversion, skip the store/load
8855 // however, without FPCVT we can't do most conversions.
8856 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8857 Subtarget.isPPC64() && Subtarget.hasFPCVT())
8858 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8859
8860 assert((IsSigned || Subtarget.hasFPCVT()) &&
8861 "UINT_TO_FP is supported only with FPCVT");
8862
8863 if (Src.getValueType() == MVT::i64) {
8864 SDValue SINT = Src;
8865 // When converting to single-precision, we actually need to convert
8866 // to double-precision first and then round to single-precision.
8867 // To avoid double-rounding effects during that operation, we have
8868 // to prepare the input operand. Bits that might be truncated when
8869 // converting to double-precision are replaced by a bit that won't
8870 // be lost at this stage, but is below the single-precision rounding
8871 // position.
8872 //
8873 // However, if afn is in effect, accept double
8874 // rounding to avoid the extra overhead.
8875 // FIXME: Currently INT_TO_FP can't support fast math flags because
8876 // of nneg flag, thus Op->getFlags().hasApproximateFuncs() is always
8877 // false.
8878 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT() &&
8879 !Op->getFlags().hasApproximateFuncs()) {
8880
8881 // Twiddle input to make sure the low 11 bits are zero. (If this
8882 // is the case, we are guaranteed the value will fit into the 53 bit
8883 // mantissa of an IEEE double-precision value without rounding.)
8884 // If any of those low 11 bits were not zero originally, make sure
8885 // bit 12 (value 2048) is set instead, so that the final rounding
8886 // to single-precision gets the correct result.
8887 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8888 SINT, DAG.getConstant(2047, dl, MVT::i64));
8889 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8890 Round, DAG.getConstant(2047, dl, MVT::i64));
8891 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8892 Round = DAG.getNode(ISD::AND, dl, MVT::i64, Round,
8893 DAG.getSignedConstant(-2048, dl, MVT::i64));
8894
8895 // However, we cannot use that value unconditionally: if the magnitude
8896 // of the input value is small, the bit-twiddling we did above might
8897 // end up visibly changing the output. Fortunately, in that case, we
8898 // don't need to twiddle bits since the original input will convert
8899 // exactly to double-precision floating-point already. Therefore,
8900 // construct a conditional to use the original value if the top 11
8901 // bits are all sign-bit copies, and use the rounded value computed
8902 // above otherwise.
8903 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8904 SINT, DAG.getConstant(53, dl, MVT::i32));
8905 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8906 Cond, DAG.getConstant(1, dl, MVT::i64));
8907 Cond = DAG.getSetCC(
8908 dl,
8909 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8910 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8911
8912 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8913 }
8914
8915 ReuseLoadInfo RLI;
8916 SDValue Bits;
8917
8919 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8920 // Drop range metadata, as this metadata becomes invalid for f64 bit
8921 // reinterpretation of i64 values.
8922 Bits =
8923 DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, RLI.Alignment,
8924 RLI.MMOFlags(), MMOMetadata(RLI.AAInfo));
8925 if (RLI.ResChain)
8926 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8927 } else if (Subtarget.hasLFIWAX() &&
8928 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8929 MachineMemOperand *MMO = MF.getMachineMemOperand(
8930 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8931 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8932 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8933 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8934 DAG.getVTList(MVT::f64, MVT::Other),
8935 Ops, MVT::i32, MMO);
8936 if (RLI.ResChain)
8937 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8938 } else if (Subtarget.hasFPCVT() &&
8939 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8940 MachineMemOperand *MMO = MF.getMachineMemOperand(
8941 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8942 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8943 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8944 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8945 DAG.getVTList(MVT::f64, MVT::Other),
8946 Ops, MVT::i32, MMO);
8947 if (RLI.ResChain)
8948 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8949 } else if (((Subtarget.hasLFIWAX() &&
8950 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8951 (Subtarget.hasFPCVT() &&
8952 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8953 SINT.getOperand(0).getValueType() == MVT::i32) {
8954 MachineFrameInfo &MFI = MF.getFrameInfo();
8955 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8956
8957 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8958 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8959
8960 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8962 DAG.getMachineFunction(), FrameIdx));
8963 Chain = Store;
8964
8965 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8966 "Expected an i32 store");
8967
8968 RLI.Ptr = FIdx;
8969 RLI.Chain = Chain;
8970 RLI.MPI =
8972 RLI.Alignment = Align(4);
8973
8974 MachineMemOperand *MMO = MF.getMachineMemOperand(
8975 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8976 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8977 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8979 PPCISD::LFIWZX : PPCISD::LFIWAX,
8980 dl, DAG.getVTList(MVT::f64, MVT::Other),
8981 Ops, MVT::i32, MMO);
8982 Chain = Bits.getValue(1);
8983 } else
8984 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8985
8986 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8987 if (IsStrict)
8988 Chain = FP.getValue(1);
8989
8990 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8991 if (IsStrict)
8992 FP = DAG.getNode(
8993 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
8994 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)},
8995 Flags);
8996 else
8997 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8998 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
8999 }
9000 return FP;
9001 }
9002
9003 assert(Src.getValueType() == MVT::i32 &&
9004 "Unhandled INT_TO_FP type in custom expander!");
9005 // Since we only generate this in 64-bit mode, we can take advantage of
9006 // 64-bit registers. In particular, sign extend the input value into the
9007 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
9008 // then lfd it and fcfid it.
9010 MachineFrameInfo &MFI = MF.getFrameInfo();
9011 EVT PtrVT = getPointerTy(MF.getDataLayout());
9012
9013 SDValue Ld;
9014 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
9015 ReuseLoadInfo RLI;
9016 bool ReusingLoad;
9017 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
9018 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
9019 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9020
9021 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
9023 DAG.getMachineFunction(), FrameIdx));
9024 Chain = Store;
9025
9026 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
9027 "Expected an i32 store");
9028
9029 RLI.Ptr = FIdx;
9030 RLI.Chain = Chain;
9031 RLI.MPI =
9033 RLI.Alignment = Align(4);
9034 }
9035
9036 MachineMemOperand *MMO = MF.getMachineMemOperand(
9037 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
9038 MMOMetadata(RLI.AAInfo, RLI.Ranges));
9039 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
9040 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
9041 DAG.getVTList(MVT::f64, MVT::Other), Ops,
9042 MVT::i32, MMO);
9043 Chain = Ld.getValue(1);
9044 if (ReusingLoad && RLI.ResChain) {
9045 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Ld.getValue(1));
9046 }
9047 } else {
9048 assert(Subtarget.isPPC64() &&
9049 "i32->FP without LFIWAX supported only on PPC64");
9050
9051 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
9052 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9053
9054 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
9055
9056 // STD the extended value into the stack slot.
9057 SDValue Store = DAG.getStore(
9058 Chain, dl, Ext64, FIdx,
9060 Chain = Store;
9061
9062 // Load the value as a double.
9063 Ld = DAG.getLoad(
9064 MVT::f64, dl, Chain, FIdx,
9066 Chain = Ld.getValue(1);
9067 }
9068
9069 // FCFID it and return it.
9070 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
9071 if (IsStrict)
9072 Chain = FP.getValue(1);
9073 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9074 if (IsStrict)
9075 FP = DAG.getNode(
9076 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
9077 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)}, Flags);
9078 else
9079 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
9080 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
9081 }
9082 return FP;
9083}
9084
9085SDValue PPCTargetLowering::LowerSET_ROUNDING(SDValue Op,
9086 SelectionDAG &DAG) const {
9087 SDLoc Dl(Op);
9089 EVT PtrVT = getPointerTy(MF.getDataLayout());
9090 SDValue Chain = Op.getOperand(0);
9091
9092 // If requested mode is constant, just use simpler mtfsb/mffscrni
9093 if (auto *CVal = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9094 uint64_t Mode = CVal->getZExtValue();
9095 assert(Mode < 4 && "Unsupported rounding mode!");
9096 unsigned InternalRnd = Mode ^ (~(Mode >> 1) & 1);
9097 if (Subtarget.isISA3_0())
9098 return SDValue(
9099 DAG.getMachineNode(
9100 PPC::MFFSCRNI, Dl, {MVT::f64, MVT::Other},
9101 {DAG.getConstant(InternalRnd, Dl, MVT::i32, true), Chain}),
9102 1);
9103 SDNode *SetHi = DAG.getMachineNode(
9104 (InternalRnd & 2) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9105 {DAG.getConstant(30, Dl, MVT::i32, true), Chain});
9106 SDNode *SetLo = DAG.getMachineNode(
9107 (InternalRnd & 1) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9108 {DAG.getConstant(31, Dl, MVT::i32, true), SDValue(SetHi, 0)});
9109 return SDValue(SetLo, 0);
9110 }
9111
9112 // Use x ^ (~(x >> 1) & 1) to transform LLVM rounding mode to Power format.
9113 SDValue One = DAG.getConstant(1, Dl, MVT::i32);
9114 SDValue SrcFlag = DAG.getNode(ISD::AND, Dl, MVT::i32, Op.getOperand(1),
9115 DAG.getConstant(3, Dl, MVT::i32));
9116 SDValue DstFlag = DAG.getNode(
9117 ISD::XOR, Dl, MVT::i32, SrcFlag,
9118 DAG.getNode(ISD::AND, Dl, MVT::i32,
9119 DAG.getNOT(Dl,
9120 DAG.getNode(ISD::SRL, Dl, MVT::i32, SrcFlag, One),
9121 MVT::i32),
9122 One));
9123 // For Power9, there's faster mffscrn, and we don't need to read FPSCR
9124 SDValue MFFS;
9125 if (!Subtarget.isISA3_0()) {
9126 MFFS = DAG.getNode(PPCISD::MFFS, Dl, {MVT::f64, MVT::Other}, Chain);
9127 Chain = MFFS.getValue(1);
9128 }
9129 SDValue NewFPSCR;
9130 if (Subtarget.isPPC64()) {
9131 if (Subtarget.isISA3_0()) {
9132 NewFPSCR = DAG.getAnyExtOrTrunc(DstFlag, Dl, MVT::i64);
9133 } else {
9134 // Set the last two bits (rounding mode) of bitcasted FPSCR.
9135 SDNode *InsertRN = DAG.getMachineNode(
9136 PPC::RLDIMI, Dl, MVT::i64,
9137 {DAG.getNode(ISD::BITCAST, Dl, MVT::i64, MFFS),
9138 DAG.getNode(ISD::ZERO_EXTEND, Dl, MVT::i64, DstFlag),
9139 DAG.getTargetConstant(0, Dl, MVT::i32),
9140 DAG.getTargetConstant(62, Dl, MVT::i32)});
9141 NewFPSCR = SDValue(InsertRN, 0);
9142 }
9143 NewFPSCR = DAG.getNode(ISD::BITCAST, Dl, MVT::f64, NewFPSCR);
9144 } else {
9145 // In 32-bit mode, store f64, load and update the lower half.
9146 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9147 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9148 SDValue Addr = Subtarget.isLittleEndian()
9149 ? StackSlot
9150 : DAG.getNode(ISD::ADD, Dl, PtrVT, StackSlot,
9151 DAG.getConstant(4, Dl, PtrVT));
9152 if (Subtarget.isISA3_0()) {
9153 Chain = DAG.getStore(Chain, Dl, DstFlag, Addr, MachinePointerInfo());
9154 } else {
9155 Chain = DAG.getStore(Chain, Dl, MFFS, StackSlot, MachinePointerInfo());
9156 SDValue Tmp =
9157 DAG.getLoad(MVT::i32, Dl, Chain, Addr, MachinePointerInfo());
9158 Chain = Tmp.getValue(1);
9159 Tmp = SDValue(DAG.getMachineNode(
9160 PPC::RLWIMI, Dl, MVT::i32,
9161 {Tmp, DstFlag, DAG.getTargetConstant(0, Dl, MVT::i32),
9162 DAG.getTargetConstant(30, Dl, MVT::i32),
9163 DAG.getTargetConstant(31, Dl, MVT::i32)}),
9164 0);
9165 Chain = DAG.getStore(Chain, Dl, Tmp, Addr, MachinePointerInfo());
9166 }
9167 NewFPSCR =
9168 DAG.getLoad(MVT::f64, Dl, Chain, StackSlot, MachinePointerInfo());
9169 Chain = NewFPSCR.getValue(1);
9170 }
9171 if (Subtarget.isISA3_0())
9172 return SDValue(DAG.getMachineNode(PPC::MFFSCRN, Dl, {MVT::f64, MVT::Other},
9173 {NewFPSCR, Chain}),
9174 1);
9175 SDValue Zero = DAG.getConstant(0, Dl, MVT::i32, true);
9176 SDNode *MTFSF = DAG.getMachineNode(
9177 PPC::MTFSF, Dl, MVT::Other,
9178 {DAG.getConstant(255, Dl, MVT::i32, true), NewFPSCR, Zero, Zero, Chain});
9179 return SDValue(MTFSF, 0);
9180}
9181
9182SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op,
9183 SelectionDAG &DAG) const {
9184 SDLoc dl(Op);
9185 /*
9186 The rounding mode is in bits 30:31 of FPSR, and has the following
9187 settings:
9188 00 Round to nearest
9189 01 Round to 0
9190 10 Round to +inf
9191 11 Round to -inf
9192
9193 GET_ROUNDING, on the other hand, expects the following:
9194 -1 Undefined
9195 0 Round to 0
9196 1 Round to nearest
9197 2 Round to +inf
9198 3 Round to -inf
9199
9200 To perform the conversion, we do:
9201 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
9202 */
9203
9205 EVT VT = Op.getValueType();
9206 EVT PtrVT = getPointerTy(MF.getDataLayout());
9207
9208 // Save FP Control Word to register
9209 SDValue Chain = Op.getOperand(0);
9210 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
9211 Chain = MFFS.getValue(1);
9212
9213 SDValue CWD;
9214 if (isTypeLegal(MVT::i64)) {
9215 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
9216 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
9217 } else {
9218 // Save FP register to stack slot
9219 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9220 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9221 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
9222
9223 // Load FP Control Word from low 32 bits of stack slot.
9225 "Stack slot adjustment is valid only on big endian subtargets!");
9226 SDValue Four = DAG.getConstant(4, dl, PtrVT);
9227 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
9228 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
9229 Chain = CWD.getValue(1);
9230 }
9231
9232 // Transform as necessary
9233 SDValue CWD1 =
9234 DAG.getNode(ISD::AND, dl, MVT::i32,
9235 CWD, DAG.getConstant(3, dl, MVT::i32));
9236 SDValue CWD2 =
9237 DAG.getNode(ISD::SRL, dl, MVT::i32,
9238 DAG.getNode(ISD::AND, dl, MVT::i32,
9239 DAG.getNode(ISD::XOR, dl, MVT::i32,
9240 CWD, DAG.getConstant(3, dl, MVT::i32)),
9241 DAG.getConstant(3, dl, MVT::i32)),
9242 DAG.getConstant(1, dl, MVT::i32));
9243
9244 SDValue RetVal =
9245 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
9246
9247 RetVal =
9249 dl, VT, RetVal);
9250
9251 return DAG.getMergeValues({RetVal, Chain}, dl);
9252}
9253
9254SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9255 EVT VT = Op.getValueType();
9257 SDLoc dl(Op);
9258 assert(Op.getNumOperands() == 3 &&
9259 VT == Op.getOperand(1).getValueType() &&
9260 "Unexpected SHL!");
9261
9262 // Expand into a bunch of logical ops. Note that these ops
9263 // depend on the PPC behavior for oversized shift amounts.
9264 SDValue Lo = Op.getOperand(0);
9265 SDValue Hi = Op.getOperand(1);
9266 SDValue Amt = Op.getOperand(2);
9267 EVT AmtVT = Amt.getValueType();
9268
9269 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9270 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9271 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
9272 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
9273 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
9274 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9275 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9276 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
9277 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9278 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
9279 SDValue OutOps[] = { OutLo, OutHi };
9280 return DAG.getMergeValues(OutOps, dl);
9281}
9282
9283SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9284 EVT VT = Op.getValueType();
9285 SDLoc dl(Op);
9287 assert(Op.getNumOperands() == 3 &&
9288 VT == Op.getOperand(1).getValueType() &&
9289 "Unexpected SRL!");
9290
9291 // Expand into a bunch of logical ops. Note that these ops
9292 // depend on the PPC behavior for oversized shift amounts.
9293 SDValue Lo = Op.getOperand(0);
9294 SDValue Hi = Op.getOperand(1);
9295 SDValue Amt = Op.getOperand(2);
9296 EVT AmtVT = Amt.getValueType();
9297
9298 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9299 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9300 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9301 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9302 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9303 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9304 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9305 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9306 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9307 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9308 SDValue OutOps[] = { OutLo, OutHi };
9309 return DAG.getMergeValues(OutOps, dl);
9310}
9311
9312SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9313 SDLoc dl(Op);
9314 EVT VT = Op.getValueType();
9316 assert(Op.getNumOperands() == 3 &&
9317 VT == Op.getOperand(1).getValueType() &&
9318 "Unexpected SRA!");
9319
9320 // Expand into a bunch of logical ops, followed by a select_cc.
9321 SDValue Lo = Op.getOperand(0);
9322 SDValue Hi = Op.getOperand(1);
9323 SDValue Amt = Op.getOperand(2);
9324 EVT AmtVT = Amt.getValueType();
9325
9326 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9327 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9328 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9329 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9330 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9331 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9332 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9333 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9334 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9335 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9336 Tmp4, Tmp6, ISD::SETLE);
9337 SDValue OutOps[] = { OutLo, OutHi };
9338 return DAG.getMergeValues(OutOps, dl);
9339}
9340
9341SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9342 SelectionDAG &DAG) const {
9343 SDLoc dl(Op);
9344 EVT VT = Op.getValueType();
9345 unsigned BitWidth = VT.getSizeInBits();
9346
9347 bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9348 SDValue X = Op.getOperand(0);
9349 SDValue Y = Op.getOperand(1);
9350 SDValue Z = Op.getOperand(2);
9351 EVT AmtVT = Z.getValueType();
9352
9353 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9354 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9355 // This is simpler than TargetLowering::expandFunnelShift because we can rely
9356 // on PowerPC shift by BW being well defined.
9357 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9358 DAG.getConstant(BitWidth - 1, dl, AmtVT));
9359 SDValue SubZ =
9360 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9361 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9362 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9363 return DAG.getNode(ISD::OR, dl, VT, X, Y);
9364}
9365
9366//===----------------------------------------------------------------------===//
9367// Vector related lowering.
9368//
9369
9370/// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9371/// element size of SplatSize. Cast the result to VT.
9372static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9373 SelectionDAG &DAG, const SDLoc &dl) {
9374 static const MVT VTys[] = { // canonical VT to use for each size.
9375 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9376 };
9377
9378 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9379
9380 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9381 if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
9382 SplatSize = 1;
9383 Val = 0xFF;
9384 }
9385
9386 EVT CanonicalVT = VTys[SplatSize-1];
9387
9388 // Build a canonical splat for this value.
9389 // Explicitly truncate APInt here, as this API is used with a mix of
9390 // signed and unsigned values.
9391 return DAG.getBitcast(
9392 ReqVT,
9393 DAG.getConstant(APInt(64, Val).trunc(SplatSize * 8), dl, CanonicalVT));
9394}
9395
9396/// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9397/// specified intrinsic ID.
9399 const SDLoc &dl, EVT DestVT = MVT::Other) {
9400 if (DestVT == MVT::Other) DestVT = Op.getValueType();
9401 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9402 DAG.getConstant(IID, dl, MVT::i32), Op);
9403}
9404
9405/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9406/// specified intrinsic ID.
9408 SelectionDAG &DAG, const SDLoc &dl,
9409 EVT DestVT = MVT::Other) {
9410 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9411 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9412 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9413}
9414
9415/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9416/// specified intrinsic ID.
9417static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9418 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9419 EVT DestVT = MVT::Other) {
9420 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9421 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9422 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9423}
9424
9425/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9426/// amount. The result has the specified value type.
9427static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9428 SelectionDAG &DAG, const SDLoc &dl) {
9429 // Force LHS/RHS to be the right type.
9430 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9431 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9432
9433 int Ops[16];
9434 for (unsigned i = 0; i != 16; ++i)
9435 Ops[i] = i + Amt;
9436 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9437 return DAG.getNode(ISD::BITCAST, dl, VT, T);
9438}
9439
9440/// Do we have an efficient pattern in a .td file for this node?
9441///
9442/// \param V - pointer to the BuildVectorSDNode being matched
9443/// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9444///
9445/// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9446/// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9447/// the opposite is true (expansion is beneficial) are:
9448/// - The node builds a vector out of integers that are not 32 or 64-bits
9449/// - The node builds a vector out of constants
9450/// - The node is a "load-and-splat"
9451/// In all other cases, we will choose to keep the BUILD_VECTOR.
9453 bool HasDirectMove,
9454 bool HasP8Vector) {
9455 EVT VecVT = V->getValueType(0);
9456 bool RightType = VecVT == MVT::v2f64 ||
9457 (HasP8Vector && VecVT == MVT::v4f32) ||
9458 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9459 if (!RightType)
9460 return false;
9461
9462 bool IsSplat = true;
9463 bool IsLoad = false;
9464 SDValue Op0 = V->getOperand(0);
9465
9466 // This function is called in a block that confirms the node is not a constant
9467 // splat. So a constant BUILD_VECTOR here means the vector is built out of
9468 // different constants.
9469 if (V->isConstant())
9470 return false;
9471 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9472 if (V->getOperand(i).isUndef())
9473 return false;
9474 // We want to expand nodes that represent load-and-splat even if the
9475 // loaded value is a floating point truncation or conversion to int.
9476 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9477 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9478 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9479 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9480 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9481 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9482 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9483 IsLoad = true;
9484 // If the operands are different or the input is not a load and has more
9485 // uses than just this BV node, then it isn't a splat.
9486 if (V->getOperand(i) != Op0 ||
9487 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9488 IsSplat = false;
9489 }
9490 return !(IsSplat && IsLoad);
9491}
9492
9493// Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9494SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9495
9496 SDLoc dl(Op);
9497 SDValue Op0 = Op->getOperand(0);
9498
9499 if (!Subtarget.isPPC64() || (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9500 (Op.getValueType() != MVT::f128))
9501 return SDValue();
9502
9503 SDValue Lo = Op0.getOperand(0);
9504 SDValue Hi = Op0.getOperand(1);
9505 if ((Lo.getValueType() != MVT::i64) || (Hi.getValueType() != MVT::i64))
9506 return SDValue();
9507
9508 if (!Subtarget.isLittleEndian())
9509 std::swap(Lo, Hi);
9510
9511 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Lo, Hi);
9512}
9513
9514static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9515 const SDValue *InputLoad = &Op;
9516 while (InputLoad->getOpcode() == ISD::BITCAST)
9517 InputLoad = &InputLoad->getOperand(0);
9518 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9519 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9520 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9521 InputLoad = &InputLoad->getOperand(0);
9522 }
9523 if (InputLoad->getOpcode() != ISD::LOAD)
9524 return nullptr;
9525 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9526 return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9527}
9528
9529// Convert the argument APFloat to a single precision APFloat if there is no
9530// loss in information during the conversion to single precision APFloat and the
9531// resulting number is not a denormal number. Return true if successful.
9533 APFloat APFloatToConvert = ArgAPFloat;
9534 bool LosesInfo = true;
9536 &LosesInfo);
9537 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9538 if (Success)
9539 ArgAPFloat = APFloatToConvert;
9540 return Success;
9541}
9542
9543// Bitcast the argument APInt to a double and convert it to a single precision
9544// APFloat, bitcast the APFloat to an APInt and assign it to the original
9545// argument if there is no loss in information during the conversion from
9546// double to single precision APFloat and the resulting number is not a denormal
9547// number. Return true if successful.
9549 double DpValue = ArgAPInt.bitsToDouble();
9550 APFloat APFloatDp(DpValue);
9551 bool Success = convertToNonDenormSingle(APFloatDp);
9552 if (Success)
9553 ArgAPInt = APFloatDp.bitcastToAPInt();
9554 return Success;
9555}
9556
9557// Nondestructive check for convertTonNonDenormSingle.
9559 // Only convert if it loses info, since XXSPLTIDP should
9560 // handle the other case.
9561 APFloat APFloatToConvert = ArgAPFloat;
9562 bool LosesInfo = true;
9564 &LosesInfo);
9565
9566 return (!LosesInfo && !APFloatToConvert.isDenormal());
9567}
9568
9569static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9570 unsigned &Opcode) {
9571 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9572 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9573 return false;
9574
9575 EVT Ty = Op->getValueType(0);
9576 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9577 // as we cannot handle extending loads for these types.
9578 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9579 ISD::isNON_EXTLoad(InputNode))
9580 return true;
9581
9582 EVT MemVT = InputNode->getMemoryVT();
9583 // For v8i16 and v16i8 types, extending loads can be handled as long as the
9584 // memory VT is the same vector element VT type.
9585 // The loads feeding into the v8i16 and v16i8 types will be extending because
9586 // scalar i8/i16 are not legal types.
9587 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9588 (MemVT == Ty.getVectorElementType()))
9589 return true;
9590
9591 if (Ty == MVT::v2i64) {
9592 // Check the extend type, when the input type is i32, and the output vector
9593 // type is v2i64.
9594 if (MemVT == MVT::i32) {
9595 if (ISD::isZEXTLoad(InputNode))
9596 Opcode = PPCISD::ZEXT_LD_SPLAT;
9597 if (ISD::isSEXTLoad(InputNode))
9598 Opcode = PPCISD::SEXT_LD_SPLAT;
9599 }
9600 return true;
9601 }
9602 return false;
9603}
9604
9606 bool IsLittleEndian) {
9607 assert(BVN.getNumOperands() > 0 && "Unexpected 0-size build vector");
9608
9609 BitMask.clearAllBits();
9610 EVT VT = BVN.getValueType(0);
9611 unsigned VTSize = VT.getSizeInBits();
9612 APInt ConstValue(VTSize, 0);
9613
9614 unsigned EltWidth = VT.getScalarSizeInBits();
9615
9616 unsigned BitPos = 0;
9617 for (auto OpVal : BVN.op_values()) {
9618 auto *CN = dyn_cast<ConstantSDNode>(OpVal);
9619
9620 if (!CN)
9621 return false;
9622 // The elements in a vector register are ordered in reverse byte order
9623 // between little-endian and big-endian modes.
9624 ConstValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth),
9625 IsLittleEndian ? BitPos : VTSize - EltWidth - BitPos);
9626 BitPos += EltWidth;
9627 }
9628
9629 for (unsigned J = 0; J < 16; ++J) {
9630 APInt ExtractValue = ConstValue.extractBits(8, J * 8);
9631 if (ExtractValue != 0x00 && ExtractValue != 0xFF)
9632 return false;
9633 if (ExtractValue == 0xFF)
9634 BitMask.setBit(J);
9635 }
9636 return true;
9637}
9638
9639// If this is a case we can't handle, return null and let the default
9640// expansion code take care of it. If we CAN select this case, and if it
9641// selects to a single instruction, return Op. Otherwise, if we can codegen
9642// this case more efficiently than a constant pool load, lower it to the
9643// sequence of ops that should be used.
9644SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9645 SelectionDAG &DAG) const {
9646 SDLoc dl(Op);
9647 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9648 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9649
9650 if (Subtarget.hasP10Vector()) {
9651 APInt BitMask(32, 0);
9652 // If the value of the vector is all zeros or all ones,
9653 // we do not convert it to MTVSRBMI.
9654 // The xxleqv instruction sets a vector with all ones.
9655 // The xxlxor instruction sets a vector with all zeros.
9656 if (isValidMtVsrBmi(BitMask, *BVN, Subtarget.isLittleEndian()) &&
9657 BitMask != 0 && BitMask != 0xffff) {
9658 SDValue SDConstant = DAG.getTargetConstant(BitMask, dl, MVT::i32);
9659 MachineSDNode *MSDNode =
9660 DAG.getMachineNode(PPC::MTVSRBMI, dl, MVT::v16i8, SDConstant);
9661 SDValue SDV = SDValue(MSDNode, 0);
9662 EVT DVT = BVN->getValueType(0);
9663 EVT SVT = SDV.getValueType();
9664 if (SVT != DVT) {
9665 SDV = DAG.getNode(ISD::BITCAST, dl, DVT, SDV);
9666 }
9667 return SDV;
9668 }
9669 // Recognize build vector patterns to emit VSX vector instructions
9670 // instead of loading value from memory.
9671 if (SDValue VecPat = combineBVLoadsSpecialValue(Op, DAG))
9672 return VecPat;
9673 }
9674 // Check if this is a splat of a constant value.
9675 APInt APSplatBits, APSplatUndef;
9676 unsigned SplatBitSize = 0;
9677 bool HasAnyUndefs;
9678 bool BVNIsConstantSplat =
9679 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9680 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9681
9682 // If it is a splat of a double, check if we can shrink it to a 32 bit
9683 // non-denormal float which when converted back to double gives us the same
9684 // double. This is to exploit the XXSPLTIDP instruction.
9685 // If we lose precision, we use XXSPLTI32DX.
9686 if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9687 Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
9688 // Check the type first to short-circuit so we don't modify APSplatBits if
9689 // this block isn't executed.
9690 if ((Op->getValueType(0) == MVT::v2f64) &&
9691 convertToNonDenormSingle(APSplatBits)) {
9692 SDValue SplatNode = DAG.getNode(
9693 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9694 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9695 return DAG.getBitcast(Op.getValueType(), SplatNode);
9696 } else {
9697 // We may lose precision, so we have to use XXSPLTI32DX.
9698
9699 uint32_t Hi = Hi_32(APSplatBits.getZExtValue());
9700 uint32_t Lo = Lo_32(APSplatBits.getZExtValue());
9701 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9702
9703 if (!Hi || !Lo)
9704 // If either load is 0, then we should generate XXLXOR to set to 0.
9705 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9706
9707 if (Hi)
9708 SplatNode = DAG.getNode(
9709 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9710 DAG.getTargetConstant(0, dl, MVT::i32),
9711 DAG.getTargetConstant(Hi, dl, MVT::i32));
9712
9713 if (Lo)
9714 SplatNode =
9715 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9716 DAG.getTargetConstant(1, dl, MVT::i32),
9717 DAG.getTargetConstant(Lo, dl, MVT::i32));
9718
9719 return DAG.getBitcast(Op.getValueType(), SplatNode);
9720 }
9721 }
9722
9723 if (SDValue V =
9724 LowerVecSplatSmallFP(Op, DAG, BVNIsConstantSplat, SplatBitSize))
9725 return V;
9726
9727 bool IsSplat64 = false;
9728 uint64_t SplatBits = 0;
9729 int32_t SextVal = 0;
9730 if (BVNIsConstantSplat && SplatBitSize <= 64) {
9731 SplatBits = APSplatBits.getZExtValue();
9732 if (SplatBitSize <= 32) {
9733 SextVal = SignExtend32(SplatBits, SplatBitSize);
9734 } else if (SplatBitSize == 64 && Subtarget.hasP8Altivec()) {
9735 int64_t Splat64Val = static_cast<int64_t>(SplatBits);
9736 bool P9Vector = Subtarget.hasP9Vector();
9737 int32_t Hi = P9Vector ? 127 : 15;
9738 int32_t Lo = P9Vector ? -128 : -16;
9739 IsSplat64 = Splat64Val >= Lo && Splat64Val <= Hi;
9740 SextVal = static_cast<int32_t>(SplatBits);
9741 }
9742 }
9743
9744 if (!BVNIsConstantSplat || (SplatBitSize > 32 && !IsSplat64)) {
9745 unsigned NewOpcode = PPCISD::LD_SPLAT;
9746
9747 // Handle load-and-splat patterns as we have instructions that will do this
9748 // in one go.
9749 if (DAG.isSplatValue(Op, true) &&
9750 isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9751 const SDValue *InputLoad = &Op.getOperand(0);
9752 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9753
9754 // If the input load is an extending load, it will be an i32 -> i64
9755 // extending load and isValidSplatLoad() will update NewOpcode.
9756 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9757 unsigned ElementSize =
9758 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9759
9760 assert(((ElementSize == 2 * MemorySize)
9761 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9762 NewOpcode == PPCISD::SEXT_LD_SPLAT)
9763 : (NewOpcode == PPCISD::LD_SPLAT)) &&
9764 "Unmatched element size and opcode!\n");
9765
9766 // Checking for a single use of this load, we have to check for vector
9767 // width (128 bits) / ElementSize uses (since each operand of the
9768 // BUILD_VECTOR is a separate use of the value.
9769 unsigned NumUsesOfInputLD = 128 / ElementSize;
9770 for (SDValue BVInOp : Op->ops())
9771 if (BVInOp.isUndef())
9772 NumUsesOfInputLD--;
9773
9774 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9775 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9776 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9777 // 15", but function IsValidSplatLoad() now will only return true when
9778 // the data at index 0 is not nullptr. So we will not get into trouble for
9779 // these cases.
9780 //
9781 // case 1 - lfiwzx/lfiwax
9782 // 1.1: load result is i32 and is sign/zero extend to i64;
9783 // 1.2: build a v2i64 vector type with above loaded value;
9784 // 1.3: the vector has only one value at index 0, others are all undef;
9785 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9786 if (NumUsesOfInputLD == 1 &&
9787 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9788 !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9789 Subtarget.hasLFIWAX()))
9790 return SDValue();
9791
9792 // case 2 - lxvr[hb]x
9793 // 2.1: load result is at most i16;
9794 // 2.2: build a vector with above loaded value;
9795 // 2.3: the vector has only one value at index 0, others are all undef;
9796 // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9797 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9798 Subtarget.isISA3_1() && ElementSize <= 16)
9799 return SDValue();
9800
9801 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9802 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9803 Subtarget.hasVSX()) {
9804 SDValue Ops[] = {
9805 LD->getChain(), // Chain
9806 LD->getBasePtr(), // Ptr
9807 DAG.getValueType(Op.getValueType()) // VT
9808 };
9809 SDValue LdSplt = DAG.getMemIntrinsicNode(
9810 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9811 LD->getMemoryVT(), LD->getMemOperand());
9812 // Replace all uses of the output chain of the original load with the
9813 // output chain of the new load.
9814 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9815 LdSplt.getValue(1));
9816 return LdSplt;
9817 }
9818 }
9819
9820 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9821 // 32-bits can be lowered to VSX instructions under certain conditions.
9822 // Without VSX, there is no pattern more efficient than expanding the node.
9823 if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9824 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9825 Subtarget.hasP8Vector()))
9826 return Op;
9827 return SDValue();
9828 }
9829
9830 uint64_t SplatUndef = APSplatUndef.getZExtValue();
9831 unsigned SplatSize = SplatBitSize / 8;
9832
9833 // First, handle single instruction cases.
9834
9835 // All zeros?
9836 if (SplatBits == 0) {
9837 // Canonicalize all zero vectors to be v4i32.
9838 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9839 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9840 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9841 }
9842 return Op;
9843 }
9844
9845 // We have XXSPLTIW for constant splats four bytes wide.
9846 // Given vector length is a multiple of 4, 2-byte splats can be replaced
9847 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9848 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9849 // turned into a 4-byte splat of 0xABABABAB.
9850 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 2)
9851 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9852 Op.getValueType(), DAG, dl);
9853
9854 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 4)
9855 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9856 dl);
9857
9858 // We have XXSPLTIB for constant splats one byte wide.
9859 if (Subtarget.hasP9Vector() && SplatSize == 1)
9860 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9861 dl);
9862
9863 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9864 // Use VSPLTIW/VUPKLSW for v2i64 in range [-16,15].
9865 if (SextVal >= -16 && SextVal <= 15) {
9866 // SplatSize may be 1, 2, 4, or 8. Use size 4 instead of 8 for the splat to
9867 // generate a splat word with extend for size 8.
9868 unsigned UseSize = SplatSize == 8 ? 4 : SplatSize;
9869 SDValue Res =
9870 getCanonicalConstSplat(SextVal, UseSize, Op.getValueType(), DAG, dl);
9871 if (SplatSize != 8)
9872 return Res;
9873 SDValue IntrinsicOp =
9874 BuildIntrinsicOp(Intrinsic::ppc_altivec_vupklsw,
9875 DAG.getBitcast(MVT::v4i32, Res), DAG, dl, MVT::v2i64);
9876 return DAG.getBitcast(Op.getValueType(), IntrinsicOp);
9877 }
9878
9879 // Two instruction sequences.
9880
9881 if (Subtarget.hasP9Vector() && SextVal >= -128 && SextVal <= 127) {
9882 SDValue C = DAG.getConstant((unsigned char)SextVal, dl, MVT::i32);
9884 SDValue BV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
9885 unsigned IID;
9886 EVT VT;
9887 switch (SplatSize) {
9888 default:
9889 llvm_unreachable("Unexpected type for vector constant.");
9890 case 2:
9891 IID = Intrinsic::ppc_altivec_vupklsb;
9892 VT = MVT::v8i16;
9893 break;
9894 case 4:
9895 IID = Intrinsic::ppc_altivec_vextsb2w;
9896 VT = MVT::v4i32;
9897 break;
9898 case 8:
9899 IID = Intrinsic::ppc_altivec_vextsb2d;
9900 VT = MVT::v2i64;
9901 break;
9902 }
9903 SDValue Extend = BuildIntrinsicOp(IID, BV, DAG, dl, VT);
9904 return DAG.getBitcast(Op->getValueType(0), Extend);
9905 }
9906 assert(!IsSplat64 && "Unhandled 64-bit splat pattern");
9907
9908 // If this value is in the range [-32,30] and is even, use:
9909 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9910 // If this value is in the range [17,31] and is odd, use:
9911 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9912 // If this value is in the range [-31,-17] and is odd, use:
9913 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9914 // Note the last two are three-instruction sequences.
9915 if (SextVal >= -32 && SextVal <= 31) {
9916 // To avoid having these optimizations undone by constant folding,
9917 // we convert to a pseudo that will be expanded later into one of
9918 // the above forms.
9919 SDValue Elt = DAG.getSignedConstant(SextVal, dl, MVT::i32);
9920 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9921 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9922 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9923 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9924 if (VT == Op.getValueType())
9925 return RetVal;
9926 else
9927 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9928 }
9929
9930 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
9931 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
9932 // for fneg/fabs.
9933 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9934 // Make -1 and vspltisw -1:
9935 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9936
9937 // Make the VSLW intrinsic, computing 0x8000_0000.
9938 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9939 OnesV, DAG, dl);
9940
9941 // xor by OnesV to invert it.
9942 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9943 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9944 }
9945
9946 // Check to see if this is a wide variety of vsplti*, binop self cases.
9947 static const signed char SplatCsts[] = {
9948 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9949 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9950 };
9951
9952 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) {
9953 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9954 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
9955 int i = SplatCsts[idx];
9956
9957 // Figure out what shift amount will be used by altivec if shifted by i in
9958 // this splat size.
9959 unsigned TypeShiftAmt = i & (SplatBitSize-1);
9960
9961 // vsplti + shl self.
9962 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9963 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9964 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9965 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9966 Intrinsic::ppc_altivec_vslw
9967 };
9968 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9969 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9970 }
9971
9972 // vsplti + srl self.
9973 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9974 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9975 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9976 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9977 Intrinsic::ppc_altivec_vsrw
9978 };
9979 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9980 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9981 }
9982
9983 // vsplti + rol self.
9984 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9985 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9986 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9987 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9988 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9989 Intrinsic::ppc_altivec_vrlw
9990 };
9991 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9992 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9993 }
9994
9995 // t = vsplti c, result = vsldoi t, t, 1
9996 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9997 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9998 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9999 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10000 }
10001 // t = vsplti c, result = vsldoi t, t, 2
10002 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
10003 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10004 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
10005 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10006 }
10007 // t = vsplti c, result = vsldoi t, t, 3
10008 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
10009 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10010 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
10011 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10012 }
10013 }
10014
10015 return SDValue();
10016}
10017
10018/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
10019/// the specified operations to build the shuffle.
10021 SDValue RHS, SelectionDAG &DAG,
10022 const SDLoc &dl) {
10023 unsigned OpNum = (PFEntry >> 26) & 0x0F;
10024 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
10025 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
10026
10027 enum {
10028 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
10029 OP_VMRGHW,
10030 OP_VMRGLW,
10031 OP_VSPLTISW0,
10032 OP_VSPLTISW1,
10033 OP_VSPLTISW2,
10034 OP_VSPLTISW3,
10035 OP_VSLDOI4,
10036 OP_VSLDOI8,
10037 OP_VSLDOI12
10038 };
10039
10040 if (OpNum == OP_COPY) {
10041 if (LHSID == (1*9+2)*9+3) return LHS;
10042 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
10043 return RHS;
10044 }
10045
10046 SDValue OpLHS, OpRHS;
10047 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
10048 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
10049
10050 int ShufIdxs[16];
10051 switch (OpNum) {
10052 default: llvm_unreachable("Unknown i32 permute!");
10053 case OP_VMRGHW:
10054 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
10055 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
10056 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
10057 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
10058 break;
10059 case OP_VMRGLW:
10060 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
10061 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
10062 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
10063 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
10064 break;
10065 case OP_VSPLTISW0:
10066 for (unsigned i = 0; i != 16; ++i)
10067 ShufIdxs[i] = (i&3)+0;
10068 break;
10069 case OP_VSPLTISW1:
10070 for (unsigned i = 0; i != 16; ++i)
10071 ShufIdxs[i] = (i&3)+4;
10072 break;
10073 case OP_VSPLTISW2:
10074 for (unsigned i = 0; i != 16; ++i)
10075 ShufIdxs[i] = (i&3)+8;
10076 break;
10077 case OP_VSPLTISW3:
10078 for (unsigned i = 0; i != 16; ++i)
10079 ShufIdxs[i] = (i&3)+12;
10080 break;
10081 case OP_VSLDOI4:
10082 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
10083 case OP_VSLDOI8:
10084 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
10085 case OP_VSLDOI12:
10086 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
10087 }
10088 EVT VT = OpLHS.getValueType();
10089 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
10090 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
10091 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
10092 return DAG.getNode(ISD::BITCAST, dl, VT, T);
10093}
10094
10095/// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
10096/// by the VINSERTB instruction introduced in ISA 3.0, else just return default
10097/// SDValue.
10098SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
10099 SelectionDAG &DAG) const {
10100 const unsigned BytesInVector = 16;
10101 bool IsLE = Subtarget.isLittleEndian();
10102 SDLoc dl(N);
10103 SDValue V1 = N->getOperand(0);
10104 SDValue V2 = N->getOperand(1);
10105 unsigned ShiftElts = 0, InsertAtByte = 0;
10106 bool Swap = false;
10107
10108 // Shifts required to get the byte we want at element 7.
10109 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
10110 0, 15, 14, 13, 12, 11, 10, 9};
10111 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
10112 1, 2, 3, 4, 5, 6, 7, 8};
10113
10114 ArrayRef<int> Mask = N->getMask();
10115 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
10116
10117 // For each mask element, find out if we're just inserting something
10118 // from V2 into V1 or vice versa.
10119 // Possible permutations inserting an element from V2 into V1:
10120 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10121 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10122 // ...
10123 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
10124 // Inserting from V1 into V2 will be similar, except mask range will be
10125 // [16,31].
10126
10127 bool FoundCandidate = false;
10128 // If both vector operands for the shuffle are the same vector, the mask
10129 // will contain only elements from the first one and the second one will be
10130 // undef.
10131 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
10132 // Go through the mask of half-words to find an element that's being moved
10133 // from one vector to the other.
10134 for (unsigned i = 0; i < BytesInVector; ++i) {
10135 unsigned CurrentElement = Mask[i];
10136 // If 2nd operand is undefined, we should only look for element 7 in the
10137 // Mask.
10138 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
10139 continue;
10140
10141 bool OtherElementsInOrder = true;
10142 // Examine the other elements in the Mask to see if they're in original
10143 // order.
10144 for (unsigned j = 0; j < BytesInVector; ++j) {
10145 if (j == i)
10146 continue;
10147 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
10148 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
10149 // in which we always assume we're always picking from the 1st operand.
10150 int MaskOffset =
10151 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
10152 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
10153 OtherElementsInOrder = false;
10154 break;
10155 }
10156 }
10157 // If other elements are in original order, we record the number of shifts
10158 // we need to get the element we want into element 7. Also record which byte
10159 // in the vector we should insert into.
10160 if (OtherElementsInOrder) {
10161 // If 2nd operand is undefined, we assume no shifts and no swapping.
10162 if (V2.isUndef()) {
10163 ShiftElts = 0;
10164 Swap = false;
10165 } else {
10166 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
10167 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
10168 : BigEndianShifts[CurrentElement & 0xF];
10169 Swap = CurrentElement < BytesInVector;
10170 }
10171 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
10172 FoundCandidate = true;
10173 break;
10174 }
10175 }
10176
10177 if (!FoundCandidate)
10178 return SDValue();
10179
10180 // Candidate found, construct the proper SDAG sequence with VINSERTB,
10181 // optionally with VECSHL if shift is required.
10182 if (Swap)
10183 std::swap(V1, V2);
10184 if (V2.isUndef())
10185 V2 = V1;
10186 if (ShiftElts) {
10187 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10188 DAG.getConstant(ShiftElts, dl, MVT::i32));
10189 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
10190 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10191 }
10192 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
10193 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10194}
10195
10196/// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
10197/// by the VINSERTH instruction introduced in ISA 3.0, else just return default
10198/// SDValue.
10199SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
10200 SelectionDAG &DAG) const {
10201 const unsigned NumHalfWords = 8;
10202 const unsigned BytesInVector = NumHalfWords * 2;
10203 // Check that the shuffle is on half-words.
10204 if (!isNByteElemShuffleMask(N, 2, 1))
10205 return SDValue();
10206
10207 bool IsLE = Subtarget.isLittleEndian();
10208 SDLoc dl(N);
10209 SDValue V1 = N->getOperand(0);
10210 SDValue V2 = N->getOperand(1);
10211 unsigned ShiftElts = 0, InsertAtByte = 0;
10212 bool Swap = false;
10213
10214 // Shifts required to get the half-word we want at element 3.
10215 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
10216 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
10217
10218 uint32_t Mask = 0;
10219 uint32_t OriginalOrderLow = 0x1234567;
10220 uint32_t OriginalOrderHigh = 0x89ABCDEF;
10221 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
10222 // 32-bit space, only need 4-bit nibbles per element.
10223 for (unsigned i = 0; i < NumHalfWords; ++i) {
10224 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10225 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
10226 }
10227
10228 // For each mask element, find out if we're just inserting something
10229 // from V2 into V1 or vice versa. Possible permutations inserting an element
10230 // from V2 into V1:
10231 // X, 1, 2, 3, 4, 5, 6, 7
10232 // 0, X, 2, 3, 4, 5, 6, 7
10233 // 0, 1, X, 3, 4, 5, 6, 7
10234 // 0, 1, 2, X, 4, 5, 6, 7
10235 // 0, 1, 2, 3, X, 5, 6, 7
10236 // 0, 1, 2, 3, 4, X, 6, 7
10237 // 0, 1, 2, 3, 4, 5, X, 7
10238 // 0, 1, 2, 3, 4, 5, 6, X
10239 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
10240
10241 bool FoundCandidate = false;
10242 // Go through the mask of half-words to find an element that's being moved
10243 // from one vector to the other.
10244 for (unsigned i = 0; i < NumHalfWords; ++i) {
10245 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10246 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
10247 uint32_t MaskOtherElts = ~(0xF << MaskShift);
10248 uint32_t TargetOrder = 0x0;
10249
10250 // If both vector operands for the shuffle are the same vector, the mask
10251 // will contain only elements from the first one and the second one will be
10252 // undef.
10253 if (V2.isUndef()) {
10254 ShiftElts = 0;
10255 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
10256 TargetOrder = OriginalOrderLow;
10257 Swap = false;
10258 // Skip if not the correct element or mask of other elements don't equal
10259 // to our expected order.
10260 if (MaskOneElt == VINSERTHSrcElem &&
10261 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10262 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10263 FoundCandidate = true;
10264 break;
10265 }
10266 } else { // If both operands are defined.
10267 // Target order is [8,15] if the current mask is between [0,7].
10268 TargetOrder =
10269 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
10270 // Skip if mask of other elements don't equal our expected order.
10271 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10272 // We only need the last 3 bits for the number of shifts.
10273 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
10274 : BigEndianShifts[MaskOneElt & 0x7];
10275 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10276 Swap = MaskOneElt < NumHalfWords;
10277 FoundCandidate = true;
10278 break;
10279 }
10280 }
10281 }
10282
10283 if (!FoundCandidate)
10284 return SDValue();
10285
10286 // Candidate found, construct the proper SDAG sequence with VINSERTH,
10287 // optionally with VECSHL if shift is required.
10288 if (Swap)
10289 std::swap(V1, V2);
10290 if (V2.isUndef())
10291 V2 = V1;
10292 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10293 if (ShiftElts) {
10294 // Double ShiftElts because we're left shifting on v16i8 type.
10295 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10296 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
10297 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
10298 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10299 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10300 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10301 }
10302 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
10303 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10304 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10305 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10306}
10307
10308/// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
10309/// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
10310/// return the default SDValue.
10311SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
10312 SelectionDAG &DAG) const {
10313 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
10314 // to v16i8. Peek through the bitcasts to get the actual operands.
10317
10318 auto ShuffleMask = SVN->getMask();
10319 SDValue VecShuffle(SVN, 0);
10320 SDLoc DL(SVN);
10321
10322 // Check that we have a four byte shuffle.
10323 if (!isNByteElemShuffleMask(SVN, 4, 1))
10324 return SDValue();
10325
10326 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
10327 if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
10328 std::swap(LHS, RHS);
10330 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle);
10331 if (!CommutedSV)
10332 return SDValue();
10333 ShuffleMask = CommutedSV->getMask();
10334 }
10335
10336 // Ensure that the RHS is a vector of constants.
10337 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
10338 if (!BVN)
10339 return SDValue();
10340
10341 // Check if RHS is a splat of 4-bytes (or smaller).
10342 APInt APSplatValue, APSplatUndef;
10343 unsigned SplatBitSize;
10344 bool HasAnyUndefs;
10345 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
10346 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
10347 SplatBitSize > 32)
10348 return SDValue();
10349
10350 // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
10351 // The instruction splats a constant C into two words of the source vector
10352 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
10353 // Thus we check that the shuffle mask is the equivalent of
10354 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
10355 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
10356 // within each word are consecutive, so we only need to check the first byte.
10357 SDValue Index;
10358 bool IsLE = Subtarget.isLittleEndian();
10359 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
10360 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
10361 ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
10362 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
10363 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
10364 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
10365 ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
10366 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
10367 else
10368 return SDValue();
10369
10370 // If the splat is narrower than 32-bits, we need to get the 32-bit value
10371 // for XXSPLTI32DX.
10372 unsigned SplatVal = APSplatValue.getZExtValue();
10373 for (; SplatBitSize < 32; SplatBitSize <<= 1)
10374 SplatVal |= (SplatVal << SplatBitSize);
10375
10376 SDValue SplatNode = DAG.getNode(
10377 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
10378 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
10379 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
10380}
10381
10382/// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
10383/// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
10384/// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
10385/// i.e (or (shl x, C1), (srl x, 128-C1)).
10386SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
10387 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
10388 assert(Op.getValueType() == MVT::v1i128 &&
10389 "Only set v1i128 as custom, other type shouldn't reach here!");
10390 SDLoc dl(Op);
10391 SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
10392 SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
10393 unsigned SHLAmt = N1.getConstantOperandVal(0);
10394 if (SHLAmt % 8 == 0) {
10395 std::array<int, 16> Mask;
10396 std::iota(Mask.begin(), Mask.end(), 0);
10397 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
10398 if (SDValue Shuffle =
10399 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
10400 DAG.getUNDEF(MVT::v16i8), Mask))
10401 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
10402 }
10403 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
10404 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
10405 DAG.getConstant(SHLAmt, dl, MVT::i32));
10406 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
10407 DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
10408 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
10409 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
10410}
10411
10412/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
10413/// is a shuffle we can handle in a single instruction, return it. Otherwise,
10414/// return the code it can be lowered into. Worst case, it can always be
10415/// lowered into a vperm.
10416SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
10417 SelectionDAG &DAG) const {
10418 SDLoc dl(Op);
10419 SDValue V1 = Op.getOperand(0);
10420 SDValue V2 = Op.getOperand(1);
10421 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10422
10423 // Any nodes that were combined in the target-independent combiner prior
10424 // to vector legalization will not be sent to the target combine. Try to
10425 // combine it here.
10426 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
10427 if (!isa<ShuffleVectorSDNode>(NewShuffle))
10428 return NewShuffle;
10429 Op = NewShuffle;
10431 V1 = Op.getOperand(0);
10432 V2 = Op.getOperand(1);
10433 }
10434 EVT VT = Op.getValueType();
10435 bool isLittleEndian = Subtarget.isLittleEndian();
10436
10437 unsigned ShiftElts, InsertAtByte;
10438 bool Swap = false;
10439
10440 // If this is a load-and-splat, we can do that with a single instruction
10441 // in some cases. However if the load has multiple uses, we don't want to
10442 // combine it because that will just produce multiple loads.
10443 bool IsPermutedLoad = false;
10444 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
10445 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
10446 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
10447 InputLoad->hasOneUse()) {
10448 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
10449 int SplatIdx =
10450 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
10451
10452 // The splat index for permuted loads will be in the left half of the vector
10453 // which is strictly wider than the loaded value by 8 bytes. So we need to
10454 // adjust the splat index to point to the correct address in memory.
10455 if (IsPermutedLoad) {
10456 assert((isLittleEndian || IsFourByte) &&
10457 "Unexpected size for permuted load on big endian target");
10458 SplatIdx += IsFourByte ? 2 : 1;
10459 assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
10460 "Splat of a value outside of the loaded memory");
10461 }
10462
10463 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
10464 // For 4-byte load-and-splat, we need Power9.
10465 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
10466 uint64_t Offset = 0;
10467 if (IsFourByte)
10468 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
10469 else
10470 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
10471
10472 // If the width of the load is the same as the width of the splat,
10473 // loading with an offset would load the wrong memory.
10474 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
10475 Offset = 0;
10476
10477 SDValue BasePtr = LD->getBasePtr();
10478 if (Offset != 0)
10480 BasePtr, DAG.getIntPtrConstant(Offset, dl));
10481 SDValue Ops[] = {
10482 LD->getChain(), // Chain
10483 BasePtr, // BasePtr
10484 DAG.getValueType(Op.getValueType()) // VT
10485 };
10486 SDVTList VTL =
10487 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
10488 SDValue LdSplt =
10489 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
10490 Ops, LD->getMemoryVT(), LD->getMemOperand());
10491 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
10492 if (LdSplt.getValueType() != SVOp->getValueType(0))
10493 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10494 return LdSplt;
10495 }
10496 }
10497
10498 // All v2i64 and v2f64 shuffles are legal
10499 if (VT == MVT::v2i64 || VT == MVT::v2f64)
10500 return Op;
10501
10502 if (Subtarget.hasP9Vector() &&
10503 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10504 isLittleEndian)) {
10505 if (V2.isUndef())
10506 V2 = V1;
10507 else if (Swap)
10508 std::swap(V1, V2);
10509 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10510 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10511 if (ShiftElts) {
10512 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10513 DAG.getConstant(ShiftElts, dl, MVT::i32));
10514 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10515 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10516 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10517 }
10518 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10519 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10520 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10521 }
10522
10523 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
10524 SDValue SplatInsertNode;
10525 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10526 return SplatInsertNode;
10527 }
10528
10529 if (Subtarget.hasP9Altivec()) {
10530 SDValue NewISDNode;
10531 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10532 return NewISDNode;
10533
10534 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10535 return NewISDNode;
10536 }
10537
10538 if (Subtarget.hasVSX() &&
10539 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10540 if (Swap)
10541 std::swap(V1, V2);
10542 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10543 SDValue Conv2 =
10544 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10545
10546 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10547 DAG.getConstant(ShiftElts, dl, MVT::i32));
10548 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10549 }
10550
10551 if (Subtarget.hasVSX() &&
10552 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10553 if (Swap)
10554 std::swap(V1, V2);
10555 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10556 SDValue Conv2 =
10557 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10558
10559 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10560 DAG.getConstant(ShiftElts, dl, MVT::i32));
10561 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10562 }
10563
10564 if (Subtarget.hasP9Vector()) {
10565 if (PPC::isXXBRHShuffleMask(SVOp)) {
10566 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10567 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10568 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10569 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10570 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10571 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10572 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10573 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10574 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10575 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10576 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10577 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10578 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10579 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10580 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10581 }
10582 }
10583
10584 if (Subtarget.hasVSX()) {
10585 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10586 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10587
10588 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10589 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10590 DAG.getConstant(SplatIdx, dl, MVT::i32));
10591 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10592 }
10593
10594 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10595 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10596 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10597 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10598 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10599 }
10600 }
10601
10602 // Cases that are handled by instructions that take permute immediates
10603 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10604 // selected by the instruction selector.
10605 if (V2.isUndef()) {
10606 if (PPC::isSplatShuffleMask(SVOp, 1) ||
10607 PPC::isSplatShuffleMask(SVOp, 2) ||
10608 PPC::isSplatShuffleMask(SVOp, 4) ||
10609 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10610 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10611 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10612 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10613 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10614 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10615 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10616 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10617 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10618 (Subtarget.hasP8Altivec() && (
10619 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10620 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10621 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10622 return Op;
10623 }
10624 }
10625
10626 // Altivec has a variety of "shuffle immediates" that take two vector inputs
10627 // and produce a fixed permutation. If any of these match, do not lower to
10628 // VPERM.
10629 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10630 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10631 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10632 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10633 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10634 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10635 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10636 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10637 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10638 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10639 (Subtarget.hasP8Altivec() && (
10640 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10641 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10642 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10643 return Op;
10644
10645 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
10646 // perfect shuffle table to emit an optimal matching sequence.
10647 ArrayRef<int> PermMask = SVOp->getMask();
10648
10649 if (!DisablePerfectShuffle && !isLittleEndian) {
10650 unsigned PFIndexes[4];
10651 bool isFourElementShuffle = true;
10652 for (unsigned i = 0; i != 4 && isFourElementShuffle;
10653 ++i) { // Element number
10654 unsigned EltNo = 8; // Start out undef.
10655 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10656 if (PermMask[i * 4 + j] < 0)
10657 continue; // Undef, ignore it.
10658
10659 unsigned ByteSource = PermMask[i * 4 + j];
10660 if ((ByteSource & 3) != j) {
10661 isFourElementShuffle = false;
10662 break;
10663 }
10664
10665 if (EltNo == 8) {
10666 EltNo = ByteSource / 4;
10667 } else if (EltNo != ByteSource / 4) {
10668 isFourElementShuffle = false;
10669 break;
10670 }
10671 }
10672 PFIndexes[i] = EltNo;
10673 }
10674
10675 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10676 // perfect shuffle vector to determine if it is cost effective to do this as
10677 // discrete instructions, or whether we should use a vperm.
10678 // For now, we skip this for little endian until such time as we have a
10679 // little-endian perfect shuffle table.
10680 if (isFourElementShuffle) {
10681 // Compute the index in the perfect shuffle table.
10682 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10683 PFIndexes[2] * 9 + PFIndexes[3];
10684
10685 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10686 unsigned Cost = (PFEntry >> 30);
10687
10688 // Determining when to avoid vperm is tricky. Many things affect the cost
10689 // of vperm, particularly how many times the perm mask needs to be
10690 // computed. For example, if the perm mask can be hoisted out of a loop or
10691 // is already used (perhaps because there are multiple permutes with the
10692 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the
10693 // permute mask out of the loop requires an extra register.
10694 //
10695 // As a compromise, we only emit discrete instructions if the shuffle can
10696 // be generated in 3 or fewer operations. When we have loop information
10697 // available, if this block is within a loop, we should avoid using vperm
10698 // for 3-operation perms and use a constant pool load instead.
10699 if (Cost < 3)
10700 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10701 }
10702 }
10703
10704 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10705 // vector that will get spilled to the constant pool.
10706 if (V2.isUndef()) V2 = V1;
10707
10708 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2);
10709}
10710
10711SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG,
10712 ArrayRef<int> PermMask, EVT VT,
10713 SDValue V1, SDValue V2) const {
10714 unsigned Opcode = PPCISD::VPERM;
10715 EVT ValType = V1.getValueType();
10716 SDLoc dl(Op);
10717 bool NeedSwap = false;
10718 bool isLittleEndian = Subtarget.isLittleEndian();
10719 bool isPPC64 = Subtarget.isPPC64();
10720
10721 if (Subtarget.hasVSX() && Subtarget.hasP9Vector() &&
10722 (V1->hasOneUse() || V2->hasOneUse())) {
10723 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using "
10724 "XXPERM instead\n");
10725 Opcode = PPCISD::XXPERM;
10726
10727 // The second input to XXPERM is also an output so if the second input has
10728 // multiple uses then copying is necessary, as a result we want the
10729 // single-use operand to be used as the second input to prevent copying.
10730 if ((!isLittleEndian && !V2->hasOneUse() && V1->hasOneUse()) ||
10731 (isLittleEndian && !V1->hasOneUse() && V2->hasOneUse())) {
10732 std::swap(V1, V2);
10733 NeedSwap = !NeedSwap;
10734 }
10735 }
10736
10737 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10738 // that it is in input element units, not in bytes. Convert now.
10739
10740 // For little endian, the order of the input vectors is reversed, and
10741 // the permutation mask is complemented with respect to 31. This is
10742 // necessary to produce proper semantics with the big-endian-based vperm
10743 // instruction.
10744 EVT EltVT = V1.getValueType().getVectorElementType();
10745 unsigned BytesPerElement = EltVT.getSizeInBits() / 8;
10746
10747 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10748 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10749
10750 /*
10751 Vectors will be appended like so: [ V1 | v2 ]
10752 XXSWAPD on V1:
10753 [ A | B | C | D ] -> [ C | D | A | B ]
10754 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15
10755 i.e. index of A, B += 8, and index of C, D -= 8.
10756 XXSWAPD on V2:
10757 [ E | F | G | H ] -> [ G | H | E | F ]
10758 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31
10759 i.e. index of E, F += 8, index of G, H -= 8
10760 Swap V1 and V2:
10761 [ V1 | V2 ] -> [ V2 | V1 ]
10762 0-15 16-31 0-15 16-31
10763 i.e. index of V1 += 16, index of V2 -= 16
10764 */
10765
10766 SmallVector<SDValue, 16> ResultMask;
10767 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10768 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10769
10770 if (V1HasXXSWAPD) {
10771 if (SrcElt < 8)
10772 SrcElt += 8;
10773 else if (SrcElt < 16)
10774 SrcElt -= 8;
10775 }
10776 if (V2HasXXSWAPD) {
10777 if (SrcElt > 23)
10778 SrcElt -= 8;
10779 else if (SrcElt > 15)
10780 SrcElt += 8;
10781 }
10782 if (NeedSwap) {
10783 if (SrcElt < 16)
10784 SrcElt += 16;
10785 else
10786 SrcElt -= 16;
10787 }
10788 for (unsigned j = 0; j != BytesPerElement; ++j)
10789 if (isLittleEndian)
10790 ResultMask.push_back(
10791 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32));
10792 else
10793 ResultMask.push_back(
10794 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32));
10795 }
10796
10797 if (V1HasXXSWAPD) {
10798 dl = SDLoc(V1->getOperand(0));
10799 V1 = V1->getOperand(0)->getOperand(1);
10800 }
10801 if (V2HasXXSWAPD) {
10802 dl = SDLoc(V2->getOperand(0));
10803 V2 = V2->getOperand(0)->getOperand(1);
10804 }
10805
10806 if (isPPC64 && (V1HasXXSWAPD || V2HasXXSWAPD)) {
10807 if (ValType != MVT::v2f64)
10808 V1 = DAG.getBitcast(MVT::v2f64, V1);
10809 if (V2.getValueType() != MVT::v2f64)
10810 V2 = DAG.getBitcast(MVT::v2f64, V2);
10811 }
10812
10813 ShufflesHandledWithVPERM++;
10814 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10815 LLVM_DEBUG({
10816 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10817 if (Opcode == PPCISD::XXPERM) {
10818 dbgs() << "Emitting a XXPERM for the following shuffle:\n";
10819 } else {
10820 dbgs() << "Emitting a VPERM for the following shuffle:\n";
10821 }
10822 SVOp->dump();
10823 dbgs() << "With the following permute control vector:\n";
10824 VPermMask.dump();
10825 });
10826
10827 if (Opcode == PPCISD::XXPERM)
10828 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask);
10829
10830 // Only need to place items backwards in LE,
10831 // the mask was properly calculated.
10832 if (isLittleEndian)
10833 std::swap(V1, V2);
10834
10835 SDValue VPERMNode =
10836 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask);
10837
10838 VPERMNode = DAG.getBitcast(ValType, VPERMNode);
10839 return VPERMNode;
10840}
10841
10842/// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10843/// vector comparison. If it is, return true and fill in Opc/isDot with
10844/// information about the intrinsic.
10845static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10846 bool &isDot, const PPCSubtarget &Subtarget) {
10847 unsigned IntrinsicID = Intrin.getConstantOperandVal(0);
10848 CompareOpc = -1;
10849 isDot = false;
10850 switch (IntrinsicID) {
10851 default:
10852 return false;
10853 // Comparison predicates.
10854 case Intrinsic::ppc_altivec_vcmpbfp_p:
10855 CompareOpc = 966;
10856 isDot = true;
10857 break;
10858 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10859 CompareOpc = 198;
10860 isDot = true;
10861 break;
10862 case Intrinsic::ppc_altivec_vcmpequb_p:
10863 CompareOpc = 6;
10864 isDot = true;
10865 break;
10866 case Intrinsic::ppc_altivec_vcmpequh_p:
10867 CompareOpc = 70;
10868 isDot = true;
10869 break;
10870 case Intrinsic::ppc_altivec_vcmpequw_p:
10871 CompareOpc = 134;
10872 isDot = true;
10873 break;
10874 case Intrinsic::ppc_altivec_vcmpequd_p:
10875 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10876 CompareOpc = 199;
10877 isDot = true;
10878 } else
10879 return false;
10880 break;
10881 case Intrinsic::ppc_altivec_vcmpneb_p:
10882 case Intrinsic::ppc_altivec_vcmpneh_p:
10883 case Intrinsic::ppc_altivec_vcmpnew_p:
10884 case Intrinsic::ppc_altivec_vcmpnezb_p:
10885 case Intrinsic::ppc_altivec_vcmpnezh_p:
10886 case Intrinsic::ppc_altivec_vcmpnezw_p:
10887 if (Subtarget.hasP9Altivec()) {
10888 switch (IntrinsicID) {
10889 default:
10890 llvm_unreachable("Unknown comparison intrinsic.");
10891 case Intrinsic::ppc_altivec_vcmpneb_p:
10892 CompareOpc = 7;
10893 break;
10894 case Intrinsic::ppc_altivec_vcmpneh_p:
10895 CompareOpc = 71;
10896 break;
10897 case Intrinsic::ppc_altivec_vcmpnew_p:
10898 CompareOpc = 135;
10899 break;
10900 case Intrinsic::ppc_altivec_vcmpnezb_p:
10901 CompareOpc = 263;
10902 break;
10903 case Intrinsic::ppc_altivec_vcmpnezh_p:
10904 CompareOpc = 327;
10905 break;
10906 case Intrinsic::ppc_altivec_vcmpnezw_p:
10907 CompareOpc = 391;
10908 break;
10909 }
10910 isDot = true;
10911 } else
10912 return false;
10913 break;
10914 case Intrinsic::ppc_altivec_vcmpgefp_p:
10915 CompareOpc = 454;
10916 isDot = true;
10917 break;
10918 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10919 CompareOpc = 710;
10920 isDot = true;
10921 break;
10922 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10923 CompareOpc = 774;
10924 isDot = true;
10925 break;
10926 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10927 CompareOpc = 838;
10928 isDot = true;
10929 break;
10930 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10931 CompareOpc = 902;
10932 isDot = true;
10933 break;
10934 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10935 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10936 CompareOpc = 967;
10937 isDot = true;
10938 } else
10939 return false;
10940 break;
10941 case Intrinsic::ppc_altivec_vcmpgtub_p:
10942 CompareOpc = 518;
10943 isDot = true;
10944 break;
10945 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10946 CompareOpc = 582;
10947 isDot = true;
10948 break;
10949 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10950 CompareOpc = 646;
10951 isDot = true;
10952 break;
10953 case Intrinsic::ppc_altivec_vcmpgtud_p:
10954 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10955 CompareOpc = 711;
10956 isDot = true;
10957 } else
10958 return false;
10959 break;
10960
10961 case Intrinsic::ppc_altivec_vcmpequq:
10962 case Intrinsic::ppc_altivec_vcmpgtsq:
10963 case Intrinsic::ppc_altivec_vcmpgtuq:
10964 if (!Subtarget.isISA3_1())
10965 return false;
10966 switch (IntrinsicID) {
10967 default:
10968 llvm_unreachable("Unknown comparison intrinsic.");
10969 case Intrinsic::ppc_altivec_vcmpequq:
10970 CompareOpc = 455;
10971 break;
10972 case Intrinsic::ppc_altivec_vcmpgtsq:
10973 CompareOpc = 903;
10974 break;
10975 case Intrinsic::ppc_altivec_vcmpgtuq:
10976 CompareOpc = 647;
10977 break;
10978 }
10979 break;
10980
10981 // VSX predicate comparisons use the same infrastructure
10982 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10983 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10984 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10985 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10986 case Intrinsic::ppc_vsx_xvcmpgesp_p:
10987 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10988 if (Subtarget.hasVSX()) {
10989 switch (IntrinsicID) {
10990 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10991 CompareOpc = 99;
10992 break;
10993 case Intrinsic::ppc_vsx_xvcmpgedp_p:
10994 CompareOpc = 115;
10995 break;
10996 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10997 CompareOpc = 107;
10998 break;
10999 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
11000 CompareOpc = 67;
11001 break;
11002 case Intrinsic::ppc_vsx_xvcmpgesp_p:
11003 CompareOpc = 83;
11004 break;
11005 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
11006 CompareOpc = 75;
11007 break;
11008 }
11009 isDot = true;
11010 } else
11011 return false;
11012 break;
11013
11014 // Normal Comparisons.
11015 case Intrinsic::ppc_altivec_vcmpbfp:
11016 CompareOpc = 966;
11017 break;
11018 case Intrinsic::ppc_altivec_vcmpeqfp:
11019 CompareOpc = 198;
11020 break;
11021 case Intrinsic::ppc_altivec_vcmpequb:
11022 CompareOpc = 6;
11023 break;
11024 case Intrinsic::ppc_altivec_vcmpequh:
11025 CompareOpc = 70;
11026 break;
11027 case Intrinsic::ppc_altivec_vcmpequw:
11028 CompareOpc = 134;
11029 break;
11030 case Intrinsic::ppc_altivec_vcmpequd:
11031 if (Subtarget.hasP8Altivec())
11032 CompareOpc = 199;
11033 else
11034 return false;
11035 break;
11036 case Intrinsic::ppc_altivec_vcmpneb:
11037 case Intrinsic::ppc_altivec_vcmpneh:
11038 case Intrinsic::ppc_altivec_vcmpnew:
11039 case Intrinsic::ppc_altivec_vcmpnezb:
11040 case Intrinsic::ppc_altivec_vcmpnezh:
11041 case Intrinsic::ppc_altivec_vcmpnezw:
11042 if (Subtarget.hasP9Altivec())
11043 switch (IntrinsicID) {
11044 default:
11045 llvm_unreachable("Unknown comparison intrinsic.");
11046 case Intrinsic::ppc_altivec_vcmpneb:
11047 CompareOpc = 7;
11048 break;
11049 case Intrinsic::ppc_altivec_vcmpneh:
11050 CompareOpc = 71;
11051 break;
11052 case Intrinsic::ppc_altivec_vcmpnew:
11053 CompareOpc = 135;
11054 break;
11055 case Intrinsic::ppc_altivec_vcmpnezb:
11056 CompareOpc = 263;
11057 break;
11058 case Intrinsic::ppc_altivec_vcmpnezh:
11059 CompareOpc = 327;
11060 break;
11061 case Intrinsic::ppc_altivec_vcmpnezw:
11062 CompareOpc = 391;
11063 break;
11064 }
11065 else
11066 return false;
11067 break;
11068 case Intrinsic::ppc_altivec_vcmpgefp:
11069 CompareOpc = 454;
11070 break;
11071 case Intrinsic::ppc_altivec_vcmpgtfp:
11072 CompareOpc = 710;
11073 break;
11074 case Intrinsic::ppc_altivec_vcmpgtsb:
11075 CompareOpc = 774;
11076 break;
11077 case Intrinsic::ppc_altivec_vcmpgtsh:
11078 CompareOpc = 838;
11079 break;
11080 case Intrinsic::ppc_altivec_vcmpgtsw:
11081 CompareOpc = 902;
11082 break;
11083 case Intrinsic::ppc_altivec_vcmpgtsd:
11084 if (Subtarget.hasP8Altivec())
11085 CompareOpc = 967;
11086 else
11087 return false;
11088 break;
11089 case Intrinsic::ppc_altivec_vcmpgtub:
11090 CompareOpc = 518;
11091 break;
11092 case Intrinsic::ppc_altivec_vcmpgtuh:
11093 CompareOpc = 582;
11094 break;
11095 case Intrinsic::ppc_altivec_vcmpgtuw:
11096 CompareOpc = 646;
11097 break;
11098 case Intrinsic::ppc_altivec_vcmpgtud:
11099 if (Subtarget.hasP8Altivec())
11100 CompareOpc = 711;
11101 else
11102 return false;
11103 break;
11104 case Intrinsic::ppc_altivec_vcmpequq_p:
11105 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11106 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11107 if (!Subtarget.isISA3_1())
11108 return false;
11109 switch (IntrinsicID) {
11110 default:
11111 llvm_unreachable("Unknown comparison intrinsic.");
11112 case Intrinsic::ppc_altivec_vcmpequq_p:
11113 CompareOpc = 455;
11114 break;
11115 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11116 CompareOpc = 903;
11117 break;
11118 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11119 CompareOpc = 647;
11120 break;
11121 }
11122 isDot = true;
11123 break;
11124 }
11125 return true;
11126}
11127
11128/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
11129/// lower, do it, otherwise return null.
11130SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11131 SelectionDAG &DAG) const {
11132 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11133
11134 SDLoc dl(Op);
11135 // Note: BCD instructions expect the immediate operand in vector form (v4i32),
11136 // but the builtin provides it as a scalar. To satisfy the instruction
11137 // encoding, we splat the scalar across all lanes using SPLAT_VECTOR.
11138 auto MapNodeWithSplatVector =
11139 [&](unsigned Opcode,
11140 std::initializer_list<SDValue> ExtraOps = {}) -> SDValue {
11141 SDValue SplatVal =
11142 DAG.getNode(ISD::SPLAT_VECTOR, dl, MVT::v4i32, Op.getOperand(2));
11143
11144 SmallVector<SDValue, 4> Ops{SplatVal, Op.getOperand(1)};
11145 Ops.append(ExtraOps.begin(), ExtraOps.end());
11146 return DAG.getNode(Opcode, dl, MVT::v16i8, Ops);
11147 };
11148
11149 switch (IntrinsicID) {
11150 case Intrinsic::thread_pointer:
11151 // Reads the thread pointer register, used for __builtin_thread_pointer.
11152 if (Subtarget.isPPC64())
11153 return DAG.getRegister(PPC::X13, MVT::i64);
11154 return DAG.getRegister(PPC::R2, MVT::i32);
11155
11156 case Intrinsic::ppc_rldimi: {
11157 assert(Subtarget.isPPC64() && "rldimi is only available in 64-bit!");
11158 SDValue Src = Op.getOperand(1);
11159 APInt Mask = Op.getConstantOperandAPInt(4);
11160 if (Mask.isZero())
11161 return Op.getOperand(2);
11162 if (Mask.isAllOnes())
11163 return DAG.getNode(ISD::ROTL, dl, MVT::i64, Src, Op.getOperand(3));
11164 uint64_t SH = Op.getConstantOperandVal(3);
11165 unsigned MB = 0, ME = 0;
11166 if (!isRunOfOnes64(Mask.getZExtValue(), MB, ME))
11167 report_fatal_error("invalid rldimi mask!");
11168 // rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
11169 if (ME < 63 - SH) {
11170 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11171 DAG.getConstant(ME + SH + 1, dl, MVT::i32));
11172 } else if (ME > 63 - SH) {
11173 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11174 DAG.getConstant(ME + SH - 63, dl, MVT::i32));
11175 }
11176 return SDValue(
11177 DAG.getMachineNode(PPC::RLDIMI, dl, MVT::i64,
11178 {Op.getOperand(2), Src,
11179 DAG.getTargetConstant(63 - ME, dl, MVT::i32),
11180 DAG.getTargetConstant(MB, dl, MVT::i32)}),
11181 0);
11182 }
11183
11184 case Intrinsic::ppc_rlwimi: {
11185 APInt Mask = Op.getConstantOperandAPInt(4);
11186 if (Mask.isZero())
11187 return Op.getOperand(2);
11188 if (Mask.isAllOnes())
11189 return DAG.getNode(ISD::ROTL, dl, MVT::i32, Op.getOperand(1),
11190 Op.getOperand(3));
11191 unsigned MB = 0, ME = 0;
11192 if (!isRunOfOnes(Mask.getZExtValue(), MB, ME))
11193 report_fatal_error("invalid rlwimi mask!");
11194 return SDValue(DAG.getMachineNode(
11195 PPC::RLWIMI, dl, MVT::i32,
11196 {Op.getOperand(2), Op.getOperand(1), Op.getOperand(3),
11197 DAG.getTargetConstant(MB, dl, MVT::i32),
11198 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11199 0);
11200 }
11201
11202 case Intrinsic::ppc_bcdshift:
11203 return MapNodeWithSplatVector(PPCISD::BCDSHIFT, {Op.getOperand(3)});
11204 case Intrinsic::ppc_bcdshiftround:
11205 return MapNodeWithSplatVector(PPCISD::BCDSHIFTROUND, {Op.getOperand(3)});
11206 case Intrinsic::ppc_bcdtruncate:
11207 return MapNodeWithSplatVector(PPCISD::BCDTRUNC, {Op.getOperand(3)});
11208 case Intrinsic::ppc_bcdunsignedtruncate:
11209 return MapNodeWithSplatVector(PPCISD::BCDUTRUNC);
11210 case Intrinsic::ppc_bcdunsignedshift:
11211 return MapNodeWithSplatVector(PPCISD::BCDUSHIFT);
11212
11213 case Intrinsic::ppc_rlwnm: {
11214 if (Op.getConstantOperandVal(3) == 0)
11215 return DAG.getConstant(0, dl, MVT::i32);
11216 unsigned MB = 0, ME = 0;
11217 if (!isRunOfOnes(Op.getConstantOperandVal(3), MB, ME))
11218 report_fatal_error("invalid rlwnm mask!");
11219 return SDValue(
11220 DAG.getMachineNode(PPC::RLWNM, dl, MVT::i32,
11221 {Op.getOperand(1), Op.getOperand(2),
11222 DAG.getTargetConstant(MB, dl, MVT::i32),
11223 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11224 0);
11225 }
11226
11227 case Intrinsic::ppc_mma_disassemble_acc: {
11228 if (Subtarget.isISAFuture()) {
11229 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11230 SDValue WideVec =
11231 SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes,
11232 Op.getOperand(1)),
11233 0);
11235 SDValue Value = SDValue(WideVec.getNode(), 0);
11236 SDValue Value2 = SDValue(WideVec.getNode(), 1);
11237
11238 SDValue Extract;
11239 Extract = DAG.getNode(
11240 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11241 Subtarget.isLittleEndian() ? Value2 : Value,
11242 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11243 dl, getPointerTy(DAG.getDataLayout())));
11244 RetOps.push_back(Extract);
11245 Extract = DAG.getNode(
11246 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11247 Subtarget.isLittleEndian() ? Value2 : Value,
11248 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11249 dl, getPointerTy(DAG.getDataLayout())));
11250 RetOps.push_back(Extract);
11251 Extract = DAG.getNode(
11252 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11253 Subtarget.isLittleEndian() ? Value : Value2,
11254 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11255 dl, getPointerTy(DAG.getDataLayout())));
11256 RetOps.push_back(Extract);
11257 Extract = DAG.getNode(
11258 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11259 Subtarget.isLittleEndian() ? Value : Value2,
11260 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11261 dl, getPointerTy(DAG.getDataLayout())));
11262 RetOps.push_back(Extract);
11263 return DAG.getMergeValues(RetOps, dl);
11264 }
11265 [[fallthrough]];
11266 }
11267 case Intrinsic::ppc_vsx_disassemble_pair: {
11268 int NumVecs = 2;
11269 SDValue WideVec = Op.getOperand(1);
11270 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
11271 NumVecs = 4;
11272 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
11273 }
11275 for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
11276 SDValue Extract = DAG.getNode(
11277 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
11278 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
11279 : VecNo,
11280 dl, getPointerTy(DAG.getDataLayout())));
11281 RetOps.push_back(Extract);
11282 }
11283 return DAG.getMergeValues(RetOps, dl);
11284 }
11285
11286 case Intrinsic::ppc_build_dmr: {
11289 for (int i = 1; i < 9; i += 2) {
11290 SDValue Hi = Op.getOperand(i);
11291 SDValue Lo = Op.getOperand(i + 1);
11292 if (Hi->getOpcode() == ISD::LOAD)
11293 Chains.push_back(Hi.getValue(1));
11294 if (Lo->getOpcode() == ISD::LOAD)
11295 Chains.push_back(Lo.getValue(1));
11296 Pairs.push_back(
11297 DAG.getNode(PPCISD::PAIR_BUILD, dl, MVT::v256i1, {Hi, Lo}));
11298 }
11299 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11300 SDValue Value = DMFInsert1024(Pairs, SDLoc(Op), DAG);
11301 return DAG.getMergeValues({Value, TF}, dl);
11302 }
11303
11304 case Intrinsic::ppc_mma_dmxxextfdmr512: {
11305 assert(Subtarget.isISAFuture() && "dmxxextfdmr512 requires ISA Future");
11306 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11307 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11308 "Specify P of 0 or 1 for lower or upper 512 bytes");
11309 unsigned HiLo = Idx->getSExtValue();
11310 unsigned Opcode;
11311 unsigned Subx;
11312 if (HiLo == 0) {
11313 Opcode = PPC::DMXXEXTFDMR512;
11314 Subx = PPC::sub_wacc_lo;
11315 } else {
11316 Opcode = PPC::DMXXEXTFDMR512_HI;
11317 Subx = PPC::sub_wacc_hi;
11318 }
11319 SDValue Subreg(
11320 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
11321 Op.getOperand(1),
11322 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11323 0);
11324 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11325 return SDValue(DAG.getMachineNode(Opcode, dl, ReturnTypes, Subreg), 0);
11326 }
11327
11328 case Intrinsic::ppc_mma_dmxxextfdmr256: {
11329 assert(Subtarget.isISAFuture() && "dmxxextfdmr256 requires ISA Future");
11330 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11331 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11332 "Specify a dmr row pair 0-3");
11333 unsigned IdxVal = Idx->getSExtValue();
11334 unsigned Subx;
11335 switch (IdxVal) {
11336 case 0:
11337 Subx = PPC::sub_dmrrowp0;
11338 break;
11339 case 1:
11340 Subx = PPC::sub_dmrrowp1;
11341 break;
11342 case 2:
11343 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11344 break;
11345 case 3:
11346 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11347 break;
11348 }
11349 SDValue Subreg(
11350 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v256i1,
11351 Op.getOperand(1),
11352 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11353 0);
11354 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11355 return SDValue(
11356 DAG.getMachineNode(PPC::DMXXEXTFDMR256, dl, MVT::v256i1, {Subreg, P}),
11357 0);
11358 }
11359
11360 case Intrinsic::ppc_mma_dmxxinstdmr512: {
11361 assert(Subtarget.isISAFuture() && "dmxxinstdmr512 requires ISA Future");
11362 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4));
11363 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11364 "Specify P of 0 or 1 for lower or upper 512 bytes");
11365 unsigned HiLo = Idx->getSExtValue();
11366 unsigned Opcode;
11367 unsigned Subx;
11368 if (HiLo == 0) {
11369 Opcode = PPCISD::INST512;
11370 Subx = PPC::sub_wacc_lo;
11371 } else {
11372 Opcode = PPCISD::INST512HI;
11373 Subx = PPC::sub_wacc_hi;
11374 }
11375 SDValue Wacc = DAG.getNode(Opcode, dl, MVT::v512i1, Op.getOperand(2),
11376 Op.getOperand(3));
11377 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11378 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11379 Op.getOperand(1), Wacc, SubReg),
11380 0);
11381 }
11382
11383 case Intrinsic::ppc_mma_dmxxinstdmr256: {
11384 assert(Subtarget.isISAFuture() && "dmxxinstdmr256 requires ISA Future");
11385 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3));
11386 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11387 "Specify a dmr row pair 0-3");
11388 unsigned IdxVal = Idx->getSExtValue();
11389 unsigned Subx;
11390 switch (IdxVal) {
11391 case 0:
11392 Subx = PPC::sub_dmrrowp0;
11393 break;
11394 case 1:
11395 Subx = PPC::sub_dmrrowp1;
11396 break;
11397 case 2:
11398 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11399 break;
11400 case 3:
11401 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11402 break;
11403 }
11404 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11405 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11406 SDValue DMRRowp =
11407 DAG.getNode(PPCISD::INST256, dl, MVT::v256i1, Op.getOperand(2), P);
11408 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11409 Op.getOperand(1), DMRRowp, SubReg),
11410 0);
11411 }
11412
11413 case Intrinsic::ppc_mma_xxmfacc:
11414 case Intrinsic::ppc_mma_xxmtacc: {
11415 // Allow pre-isa-future subtargets to lower as normal.
11416 if (!Subtarget.isISAFuture())
11417 return SDValue();
11418 // The intrinsics for xxmtacc and xxmfacc take one argument of
11419 // type v512i1, for future cpu the corresponding wacc instruction
11420 // dmxx[inst|extf]dmr512 is always generated for type v512i1, negating
11421 // the need to produce the xxm[t|f]acc.
11422 SDValue WideVec = Op.getOperand(1);
11423 DAG.ReplaceAllUsesWith(Op, WideVec);
11424 return SDValue();
11425 }
11426
11427 case Intrinsic::ppc_unpack_longdouble: {
11428 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11429 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11430 "Argument of long double unpack must be 0 or 1!");
11431 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
11432 DAG.getConstant(!!(Idx->getSExtValue()), dl,
11433 Idx->getValueType(0)));
11434 }
11435
11436 case Intrinsic::ppc_compare_exp_lt:
11437 case Intrinsic::ppc_compare_exp_gt:
11438 case Intrinsic::ppc_compare_exp_eq:
11439 case Intrinsic::ppc_compare_exp_uo: {
11440 unsigned Pred;
11441 switch (IntrinsicID) {
11442 case Intrinsic::ppc_compare_exp_lt:
11443 Pred = PPC::PRED_LT;
11444 break;
11445 case Intrinsic::ppc_compare_exp_gt:
11446 Pred = PPC::PRED_GT;
11447 break;
11448 case Intrinsic::ppc_compare_exp_eq:
11449 Pred = PPC::PRED_EQ;
11450 break;
11451 case Intrinsic::ppc_compare_exp_uo:
11452 Pred = PPC::PRED_UN;
11453 break;
11454 }
11455 return SDValue(
11456 DAG.getMachineNode(
11457 PPC::SELECT_CC_I4, dl, MVT::i32,
11458 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
11459 Op.getOperand(1), Op.getOperand(2)),
11460 0),
11461 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
11462 DAG.getTargetConstant(Pred, dl, MVT::i32)}),
11463 0);
11464 }
11465 case Intrinsic::ppc_test_data_class: {
11466 EVT OpVT = Op.getOperand(1).getValueType();
11467 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP
11468 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP
11469 : PPC::XSTSTDCSP);
11470 // Lower __builtin_ppc_test_data_class(value, mask) to XSTSTDC* instruction.
11471 // The XSTSTDC* instructions test if a floating-point value matches any of
11472 // the data classes specified in the mask, setting CR field bits
11473 // accordingly. We need to extract the EQ bit (bit 2) from the CR field and
11474 // convert it to an integer result (1 if match, 0 if no match).
11475 //
11476 // Note: Operands are swapped because XSTSTDC* expects (mask, value) but the
11477 // intrinsic provides (value, mask) as Op.getOperand(1) and
11478 // Op.getOperand(2).
11479 SDValue TestDataClass =
11480 SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32,
11481 {Op.getOperand(2), Op.getOperand(1)}),
11482 0);
11483 if (Subtarget.isISA3_1()) {
11484 // ISA 3.1+: Use SETBC instruction to directly convert CR bit to integer.
11485 // This is more efficient than the SELECT_CC approach used in earlier
11486 // ISAs.
11487 SDValue SubRegIdx = DAG.getTargetConstant(PPC::sub_eq, dl, MVT::i32);
11488 SDValue CRBit =
11489 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11490 TestDataClass, SubRegIdx),
11491 0);
11492
11493 return DAG.getNode(PPCISD::SETBC, dl, MVT::i32, CRBit);
11494 }
11495
11496 // Pre-ISA 3.1: Use SELECT_CC to convert CR field to integer (1 or 0).
11497 return SDValue(
11498 DAG.getMachineNode(PPC::SELECT_CC_I4, dl, MVT::i32,
11499 {TestDataClass, DAG.getConstant(1, dl, MVT::i32),
11500 DAG.getConstant(0, dl, MVT::i32),
11501 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
11502 0);
11503 }
11504 case Intrinsic::ppc_fnmsub: {
11505 EVT VT = Op.getOperand(1).getValueType();
11506 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
11507 return DAG.getNode(
11508 ISD::FNEG, dl, VT,
11509 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
11510 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
11511 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
11512 Op.getOperand(2), Op.getOperand(3));
11513 }
11514 case Intrinsic::ppc_convert_f128_to_ppcf128:
11515 case Intrinsic::ppc_convert_ppcf128_to_f128: {
11516 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
11517 ? RTLIB::CONVERT_PPCF128_F128
11518 : RTLIB::CONVERT_F128_PPCF128;
11519 MakeLibCallOptions CallOptions;
11520 std::pair<SDValue, SDValue> Result =
11521 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
11522 dl, SDValue());
11523 return Result.first;
11524 }
11525 case Intrinsic::ppc_maxfe:
11526 case Intrinsic::ppc_maxfl:
11527 case Intrinsic::ppc_maxfs:
11528 case Intrinsic::ppc_minfe:
11529 case Intrinsic::ppc_minfl:
11530 case Intrinsic::ppc_minfs: {
11531 EVT VT = Op.getValueType();
11532 assert(
11533 all_of(Op->ops().drop_front(4),
11534 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
11535 "ppc_[max|min]f[e|l|s] must have uniform type arguments");
11536 (void)VT;
11538 if (IntrinsicID == Intrinsic::ppc_minfe ||
11539 IntrinsicID == Intrinsic::ppc_minfl ||
11540 IntrinsicID == Intrinsic::ppc_minfs)
11541 CC = ISD::SETLT;
11542 unsigned I = Op.getNumOperands() - 2, Cnt = I;
11543 SDValue Res = Op.getOperand(I);
11544 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
11545 Res =
11546 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
11547 }
11548 return Res;
11549 }
11550 }
11551
11552 // If this is a lowered altivec predicate compare, CompareOpc is set to the
11553 // opcode number of the comparison.
11554 int CompareOpc;
11555 bool isDot;
11556 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
11557 return SDValue(); // Don't custom lower most intrinsics.
11558
11559 // If this is a non-dot comparison, make the VCMP node and we are done.
11560 if (!isDot) {
11561 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
11562 Op.getOperand(1), Op.getOperand(2),
11563 DAG.getConstant(CompareOpc, dl, MVT::i32));
11564 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
11565 }
11566
11567 // Create the PPCISD altivec 'dot' comparison node.
11568 SDValue Ops[] = {
11569 Op.getOperand(2), // LHS
11570 Op.getOperand(3), // RHS
11571 DAG.getConstant(CompareOpc, dl, MVT::i32)
11572 };
11573 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
11574 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
11575
11576 // Unpack the result based on how the target uses it.
11577 unsigned BitNo; // Bit # of CR6.
11578 bool InvertBit; // Invert result?
11579 unsigned Bitx;
11580 unsigned SetOp;
11581 switch (Op.getConstantOperandVal(1)) {
11582 default: // Can't happen, don't crash on invalid number though.
11583 case 0: // Return the value of the EQ bit of CR6.
11584 BitNo = 0;
11585 InvertBit = false;
11586 Bitx = PPC::sub_eq;
11587 SetOp = PPCISD::SETBC;
11588 break;
11589 case 1: // Return the inverted value of the EQ bit of CR6.
11590 BitNo = 0;
11591 InvertBit = true;
11592 Bitx = PPC::sub_eq;
11593 SetOp = PPCISD::SETBCR;
11594 break;
11595 case 2: // Return the value of the LT bit of CR6.
11596 BitNo = 2;
11597 InvertBit = false;
11598 Bitx = PPC::sub_lt;
11599 SetOp = PPCISD::SETBC;
11600 break;
11601 case 3: // Return the inverted value of the LT bit of CR6.
11602 BitNo = 2;
11603 InvertBit = true;
11604 Bitx = PPC::sub_lt;
11605 SetOp = PPCISD::SETBCR;
11606 break;
11607 }
11608
11609 SDValue GlueOp = CompNode.getValue(1);
11610 if (Subtarget.isISA3_1()) {
11611 SDValue SubRegIdx = DAG.getTargetConstant(Bitx, dl, MVT::i32);
11612 SDValue CR6Reg = DAG.getRegister(PPC::CR6, MVT::i32);
11613 SDValue CRBit =
11614 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11615 CR6Reg, SubRegIdx, GlueOp),
11616 0);
11617 return DAG.getNode(SetOp, dl, MVT::i32, CRBit);
11618 }
11619
11620 // Now that we have the comparison, emit a copy from the CR to a GPR.
11621 // This is flagged to the above dot comparison.
11622 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
11623 DAG.getRegister(PPC::CR6, MVT::i32), GlueOp);
11624
11625 // Shift the bit into the low position.
11626 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
11627 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
11628 // Isolate the bit.
11629 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
11630 DAG.getConstant(1, dl, MVT::i32));
11631
11632 // If we are supposed to, toggle the bit.
11633 if (InvertBit)
11634 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
11635 DAG.getConstant(1, dl, MVT::i32));
11636 return Flags;
11637}
11638
11639SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
11640 SelectionDAG &DAG) const {
11641 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
11642 // the beginning of the argument list.
11643 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
11644 SDLoc DL(Op);
11645 switch (Op.getConstantOperandVal(ArgStart)) {
11646 case Intrinsic::ppc_cfence: {
11647 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
11648 SDValue Val = Op.getOperand(ArgStart + 1);
11649 EVT Ty = Val.getValueType();
11650 if (Ty == MVT::i128) {
11651 // FIXME: Testing one of two paired registers is sufficient to guarantee
11652 // ordering?
11653 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
11654 }
11655 unsigned Opcode = Subtarget.isPPC64() ? PPC::CFENCE8 : PPC::CFENCE;
11656 return SDValue(
11657 DAG.getMachineNode(
11658 Opcode, DL, MVT::Other,
11659 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getScalarIntVT(), Val),
11660 Op.getOperand(0)),
11661 0);
11662 }
11663 case Intrinsic::ppc_disassemble_dmr: {
11664 assert(ArgStart == 1 &&
11665 "llvm.ppc.disassemble.dmr must carry a chain argument.");
11666 return DAG.getStore(Op.getOperand(0), DL, Op.getOperand(ArgStart + 2),
11667 Op.getOperand(ArgStart + 1), MachinePointerInfo());
11668 }
11669 default:
11670 break;
11671 }
11672 return SDValue();
11673}
11674
11675// Lower scalar BSWAP64 to xxbrd.
11676SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
11677 SDLoc dl(Op);
11678 if (!Subtarget.isPPC64())
11679 return Op;
11680
11681 if (Subtarget.hasP9Vector()) {
11682 // MTVSRDD
11683 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
11684 Op.getOperand(0));
11685 // XXBRD
11686 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
11687 // MFVSRD
11688 int VectorIndex = 0;
11689 if (Subtarget.isLittleEndian())
11690 VectorIndex = 1;
11691 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
11692 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
11693 return Op;
11694 }
11695
11696 // For Power8, use parallel rotate instructions for faster bswap64.
11697 SDValue Input = Op.getOperand(0);
11698 // Helper to create rotate-and-insert operations (RLWIMI/RLDIMI).
11699 auto CreateRotateInsert =
11700 [&](unsigned Opcode, MVT VT, SDValue Dest, SDValue Src, unsigned RotAmt,
11701 unsigned MaskBegin,
11702 std::optional<unsigned> MaskEnd = std::nullopt) -> SDValue {
11704 Dest, Src, DAG.getTargetConstant(RotAmt, dl, MVT::i32),
11705 DAG.getTargetConstant(MaskBegin, dl, MVT::i32)};
11706 if (MaskEnd.has_value())
11707 Ops.push_back(DAG.getTargetConstant(*MaskEnd, dl, MVT::i32));
11708
11709 return SDValue(DAG.getMachineNode(Opcode, dl, VT, Ops), 0);
11710 };
11711
11712 // Helper to perform 32-bit byte swap using rotl(8) + 2x rlwimi.
11713 auto Swap32 = [&](SDValue Val32) -> SDValue {
11714 SDValue Rot = DAG.getNode(ISD::ROTL, dl, MVT::i32, Val32,
11715 DAG.getConstant(8, dl, MVT::i32));
11716 // Insert bits [24:31] from Val32 into Rot at position [0:7].
11717 SDValue Swap =
11718 CreateRotateInsert(PPC::RLWIMI, MVT::i32, Rot, Val32, 24, 0, 7);
11719 // Insert bits [16:23] from Val32 into Swap at position [16:23].
11720 return CreateRotateInsert(PPC::RLWIMI, MVT::i32, Swap, Val32, 24, 16, 23);
11721 };
11722 // Extract and swap high and low 32-bit halves independently for parallelism.
11723 SDValue Hi32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
11724 DAG.getNode(ISD::SRL, dl, MVT::i64, Input,
11725 DAG.getConstant(32, dl, MVT::i64)));
11726 SDValue Lo32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Input);
11727
11728 // Combine swapped halves: rotate LoSwap left by 32 bits and insert into
11729 // HiSwap to swap their positions, completing the 64-bit byte reversal.
11730 SDValue HiSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Hi32));
11731 SDValue LoSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Lo32));
11732
11733 return CreateRotateInsert(PPC::RLDIMI, MVT::i64, HiSwap, LoSwap, 32, 0);
11734}
11735
11736// ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
11737// compared to a value that is atomically loaded (atomic loads zero-extend).
11738SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
11739 SelectionDAG &DAG) const {
11740 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
11741 "Expecting an atomic compare-and-swap here.");
11742 SDLoc dl(Op);
11743 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
11744 EVT MemVT = AtomicNode->getMemoryVT();
11745 if (MemVT.getSizeInBits() >= 32)
11746 return Op;
11747
11748 SDValue CmpOp = Op.getOperand(2);
11749 // If this is already correctly zero-extended, leave it alone.
11750 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
11751 if (DAG.MaskedValueIsZero(CmpOp, HighBits))
11752 return Op;
11753
11754 // Clear the high bits of the compare operand.
11755 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
11756 SDValue NewCmpOp =
11757 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
11758 DAG.getConstant(MaskVal, dl, MVT::i32));
11759
11760 // Replace the existing compare operand with the properly zero-extended one.
11762 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
11763 Ops.push_back(AtomicNode->getOperand(i));
11764 Ops[2] = NewCmpOp;
11765 MachineMemOperand *MMO = AtomicNode->getMemOperand();
11766 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
11767 auto NodeTy =
11768 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
11769 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
11770}
11771
11772SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
11773 SelectionDAG &DAG) const {
11774 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
11775 EVT MemVT = N->getMemoryVT();
11776 assert(MemVT.getSimpleVT() == MVT::i128 &&
11777 "Expect quadword atomic operations");
11778 SDLoc dl(N);
11779 unsigned Opc = N->getOpcode();
11780 switch (Opc) {
11781 case ISD::ATOMIC_LOAD: {
11782 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
11783 // lowered to ppc instructions by pattern matching instruction selector.
11784 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
11786 N->getOperand(0),
11787 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
11788 for (int I = 1, E = N->getNumOperands(); I < E; ++I)
11789 Ops.push_back(N->getOperand(I));
11790 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
11791 Ops, MemVT, N->getMemOperand());
11792 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
11793 SDValue ValHi =
11794 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
11795 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
11796 DAG.getConstant(64, dl, MVT::i32));
11797 SDValue Val =
11798 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
11799 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
11800 {Val, LoadedVal.getValue(2)});
11801 }
11802 case ISD::ATOMIC_STORE: {
11803 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
11804 // lowered to ppc instructions by pattern matching instruction selector.
11805 SDVTList Tys = DAG.getVTList(MVT::Other);
11807 N->getOperand(0),
11808 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
11809 SDValue Val = N->getOperand(1);
11810 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
11811 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
11812 DAG.getConstant(64, dl, MVT::i32));
11813 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
11814 Ops.push_back(ValLo);
11815 Ops.push_back(ValHi);
11816 Ops.push_back(N->getOperand(2));
11817 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
11818 N->getMemOperand());
11819 }
11820 default:
11821 llvm_unreachable("Unexpected atomic opcode");
11822 }
11823}
11824
11826 SelectionDAG &DAG,
11827 const PPCSubtarget &Subtarget) {
11828 assert(Mask <= fcAllFlags && "Invalid fp_class flags!");
11829
11830 enum DataClassMask {
11831 DC_NAN = 1 << 6,
11832 DC_NEG_INF = 1 << 4,
11833 DC_POS_INF = 1 << 5,
11834 DC_NEG_ZERO = 1 << 2,
11835 DC_POS_ZERO = 1 << 3,
11836 DC_NEG_SUBNORM = 1,
11837 DC_POS_SUBNORM = 1 << 1,
11838 };
11839
11840 EVT VT = Op.getValueType();
11841
11842 unsigned TestOp = VT == MVT::f128 ? PPC::XSTSTDCQP
11843 : VT == MVT::f64 ? PPC::XSTSTDCDP
11844 : PPC::XSTSTDCSP;
11845
11846 if (Mask == fcAllFlags)
11847 return DAG.getBoolConstant(true, Dl, MVT::i1, VT);
11848 if (Mask == 0)
11849 return DAG.getBoolConstant(false, Dl, MVT::i1, VT);
11850
11851 // When it's cheaper or necessary to test reverse flags.
11852 if ((Mask & fcNormal) == fcNormal || Mask == ~fcQNan || Mask == ~fcSNan) {
11853 SDValue Rev = getDataClassTest(Op, ~Mask, Dl, DAG, Subtarget);
11854 return DAG.getNOT(Dl, Rev, MVT::i1);
11855 }
11856
11857 // Power doesn't support testing whether a value is 'normal'. Test the rest
11858 // first, and test if it's 'not not-normal' with expected sign.
11859 if (Mask & fcNormal) {
11860 SDValue Rev(DAG.getMachineNode(
11861 TestOp, Dl, MVT::i32,
11862 DAG.getTargetConstant(DC_NAN | DC_NEG_INF | DC_POS_INF |
11863 DC_NEG_ZERO | DC_POS_ZERO |
11864 DC_NEG_SUBNORM | DC_POS_SUBNORM,
11865 Dl, MVT::i32),
11866 Op),
11867 0);
11868 // Sign are stored in CR bit 0, result are in CR bit 2.
11869 SDValue Sign(
11870 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11871 DAG.getTargetConstant(PPC::sub_lt, Dl, MVT::i32)),
11872 0);
11873 SDValue Normal(DAG.getNOT(
11874 Dl,
11876 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11877 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11878 0),
11879 MVT::i1));
11880 if (Mask & fcPosNormal)
11881 Sign = DAG.getNOT(Dl, Sign, MVT::i1);
11882 SDValue Result = DAG.getNode(ISD::AND, Dl, MVT::i1, Sign, Normal);
11883 if (Mask == fcPosNormal || Mask == fcNegNormal)
11884 return Result;
11885
11886 return DAG.getNode(
11887 ISD::OR, Dl, MVT::i1,
11888 getDataClassTest(Op, Mask & ~fcNormal, Dl, DAG, Subtarget), Result);
11889 }
11890
11891 // The instruction doesn't differentiate between signaling or quiet NaN. Test
11892 // the rest first, and test if it 'is NaN and is signaling/quiet'.
11893 if ((Mask & fcNan) == fcQNan || (Mask & fcNan) == fcSNan) {
11894 bool IsQuiet = Mask & fcQNan;
11895 SDValue NanCheck = getDataClassTest(Op, fcNan, Dl, DAG, Subtarget);
11896
11897 // Quietness is determined by the first bit in fraction field.
11898 uint64_t QuietMask = 0;
11899 SDValue HighWord;
11900 if (VT == MVT::f128) {
11901 HighWord = DAG.getNode(
11902 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, DAG.getBitcast(MVT::v4i32, Op),
11903 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 3 : 0, Dl));
11904 QuietMask = 0x8000;
11905 } else if (VT == MVT::f64) {
11906 if (Subtarget.isPPC64()) {
11907 HighWord = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32,
11908 DAG.getBitcast(MVT::i64, Op),
11909 DAG.getConstant(1, Dl, MVT::i32));
11910 } else {
11911 SDValue Vec = DAG.getBitcast(
11912 MVT::v4i32, DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v2f64, Op));
11913 HighWord = DAG.getNode(
11914 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, Vec,
11915 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 1 : 0, Dl));
11916 }
11917 QuietMask = 0x80000;
11918 } else if (VT == MVT::f32) {
11919 HighWord = DAG.getBitcast(MVT::i32, Op);
11920 QuietMask = 0x400000;
11921 }
11922 SDValue NanRes = DAG.getSetCC(
11923 Dl, MVT::i1,
11924 DAG.getNode(ISD::AND, Dl, MVT::i32, HighWord,
11925 DAG.getConstant(QuietMask, Dl, MVT::i32)),
11926 DAG.getConstant(0, Dl, MVT::i32), IsQuiet ? ISD::SETNE : ISD::SETEQ);
11927 NanRes = DAG.getNode(ISD::AND, Dl, MVT::i1, NanCheck, NanRes);
11928 if (Mask == fcQNan || Mask == fcSNan)
11929 return NanRes;
11930
11931 return DAG.getNode(ISD::OR, Dl, MVT::i1,
11932 getDataClassTest(Op, Mask & ~fcNan, Dl, DAG, Subtarget),
11933 NanRes);
11934 }
11935
11936 unsigned NativeMask = 0;
11937 if ((Mask & fcNan) == fcNan)
11938 NativeMask |= DC_NAN;
11939 if (Mask & fcNegInf)
11940 NativeMask |= DC_NEG_INF;
11941 if (Mask & fcPosInf)
11942 NativeMask |= DC_POS_INF;
11943 if (Mask & fcNegZero)
11944 NativeMask |= DC_NEG_ZERO;
11945 if (Mask & fcPosZero)
11946 NativeMask |= DC_POS_ZERO;
11947 if (Mask & fcNegSubnormal)
11948 NativeMask |= DC_NEG_SUBNORM;
11949 if (Mask & fcPosSubnormal)
11950 NativeMask |= DC_POS_SUBNORM;
11951 return SDValue(
11952 DAG.getMachineNode(
11953 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1,
11955 TestOp, Dl, MVT::i32,
11956 DAG.getTargetConstant(NativeMask, Dl, MVT::i32), Op),
11957 0),
11958 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11959 0);
11960}
11961
11962SDValue PPCTargetLowering::LowerIS_FPCLASS(SDValue Op,
11963 SelectionDAG &DAG) const {
11964 assert(Subtarget.hasP9Vector() && "Test data class requires Power9");
11965 SDValue LHS = Op.getOperand(0);
11966 uint64_t RHSC = Op.getConstantOperandVal(1);
11967 SDLoc Dl(Op);
11968 FPClassTest Category = static_cast<FPClassTest>(RHSC);
11969 if (LHS.getValueType() == MVT::ppcf128) {
11970 // The higher part determines the value class.
11971 LHS = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::f64, LHS,
11972 DAG.getConstant(1, Dl, MVT::i32));
11973 }
11974
11975 return getDataClassTest(LHS, Category, Dl, DAG, Subtarget);
11976}
11977
11978// Adjust the length value for a load/store with length to account for the
11979// instructions requiring a left justified length, and for non-byte element
11980// types requiring scaling by element size.
11981static SDValue AdjustLength(SDValue Val, unsigned Bits, bool Left,
11982 SelectionDAG &DAG) {
11983 SDLoc dl(Val);
11984 EVT VT = Val->getValueType(0);
11985 unsigned LeftAdj = Left ? VT.getSizeInBits() - 8 : 0;
11986 unsigned TypeAdj = llvm::countr_zero<uint32_t>(Bits / 8);
11987 SDValue SHLAmt = DAG.getConstant(LeftAdj + TypeAdj, dl, VT);
11988 return DAG.getNode(ISD::SHL, dl, VT, Val, SHLAmt);
11989}
11990
11991SDValue PPCTargetLowering::LowerVP_LOAD(SDValue Op, SelectionDAG &DAG) const {
11992 auto VPLD = cast<VPLoadSDNode>(Op);
11993 bool Future = Subtarget.isISAFuture();
11994 SDLoc dl(Op);
11995 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(3).getNode(), true) &&
11996 "Mask predication not supported");
11997 EVT PtrVT = getPointerTy(DAG.getDataLayout());
11998 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPLD->getOperand(4));
11999 unsigned IID = Future ? Intrinsic::ppc_vsx_lxvrl : Intrinsic::ppc_vsx_lxvl;
12000 unsigned EltBits = Op->getValueType(0).getScalarType().getSizeInBits();
12001 Len = AdjustLength(Len, EltBits, !Future, DAG);
12002 SDValue Ops[] = {VPLD->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12003 VPLD->getOperand(1), Len};
12004 SDVTList Tys = DAG.getVTList(Op->getValueType(0), MVT::Other);
12005 SDValue VPL =
12007 VPLD->getMemoryVT(), VPLD->getMemOperand());
12008 return VPL;
12009}
12010
12011SDValue PPCTargetLowering::LowerVP_STORE(SDValue Op, SelectionDAG &DAG) const {
12012 auto VPST = cast<VPStoreSDNode>(Op);
12013 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(4).getNode(), true) &&
12014 "Mask predication not supported");
12015 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12016 SDLoc dl(Op);
12017 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPST->getOperand(5));
12018 unsigned EltBits =
12019 Op->getOperand(1).getValueType().getScalarType().getSizeInBits();
12020 bool Future = Subtarget.isISAFuture();
12021 unsigned IID = Future ? Intrinsic::ppc_vsx_stxvrl : Intrinsic::ppc_vsx_stxvl;
12022 Len = AdjustLength(Len, EltBits, !Future, DAG);
12023 SDValue Ops[] = {
12024 VPST->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12025 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, VPST->getOperand(1)),
12026 VPST->getOperand(2), Len};
12027 SDVTList Tys = DAG.getVTList(MVT::Other);
12028 SDValue VPS =
12030 VPST->getMemoryVT(), VPST->getMemOperand());
12031 return VPS;
12032}
12033
12034SDValue PPCTargetLowering::LowerPartialReduce(SDValue Op,
12035 SelectionDAG &DAG) const {
12036 SDValue Acc = Op.getOperand(0);
12037 SDValue Op1 = Op.getOperand(1);
12038 SDValue Op2 = Op.getOperand(2);
12039
12040 assert(Op.getOpcode() == ISD::PARTIAL_REDUCE_UMLA &&
12041 "Unexpected partial reduction");
12042
12043 if (Acc.getValueType() != MVT::v4i32)
12044 return SDValue();
12045 if (Op1.getValueType() != MVT::v16i32 || Op1.getOpcode() != ISD::SIGN_EXTEND)
12046 return SDValue();
12047 SDValue Op1Input = Op1.getOperand(0);
12048 if (Op1Input.getValueType() != MVT::v16i8 || !llvm::isOneOrOneSplat(Op2))
12049 return SDValue();
12050
12051 SDLoc dl(Op);
12052 SDValue Ones = DAG.getConstant(1, dl, MVT::v16i8);
12053 return DAG.getNode(ISD::PARTIAL_REDUCE_SUMLA, dl, MVT::v4i32, Acc, Op1Input,
12054 Ones);
12055}
12056
12057SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
12058 SelectionDAG &DAG) const {
12059 SDLoc dl(Op);
12060
12062 SDValue Op0 = Op.getOperand(0);
12063 EVT ValVT = Op0.getValueType();
12064 unsigned EltSize = Op.getValueType().getScalarSizeInBits();
12065 if (isa<ConstantSDNode>(Op0) && EltSize <= 32) {
12066 int64_t IntVal = Op.getConstantOperandVal(0);
12067 if (IntVal >= -16 && IntVal <= 15)
12068 return getCanonicalConstSplat(IntVal, EltSize / 8, Op.getValueType(), DAG,
12069 dl);
12070 }
12071
12072 ReuseLoadInfo RLI;
12073 if (Subtarget.hasLFIWAX() && Subtarget.hasVSX() &&
12074 Op.getValueType() == MVT::v4i32 && Op0.getOpcode() == ISD::LOAD &&
12075 Op0.getValueType() == MVT::i32 && Op0.hasOneUse() &&
12076 canReuseLoadAddress(Op0, MVT::i32, RLI, DAG, ISD::NON_EXTLOAD)) {
12077
12078 MachineMemOperand *MMO = MF.getMachineMemOperand(
12079 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
12080 MMOMetadata(RLI.AAInfo, RLI.Ranges));
12081 SDValue Ops[] = {RLI.Chain, RLI.Ptr, DAG.getValueType(Op.getValueType())};
12083 PPCISD::LD_SPLAT, dl, DAG.getVTList(MVT::v4i32, MVT::Other), Ops,
12084 MVT::i32, MMO);
12085 if (RLI.ResChain)
12086 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
12087 return Bits.getValue(0);
12088 }
12089
12090 // Create a stack slot that is 16-byte aligned.
12091 MachineFrameInfo &MFI = MF.getFrameInfo();
12092 int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
12093 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12094 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
12095
12096 SDValue Val = Op0;
12097 // P10 hardware store forwarding requires that a single store contains all
12098 // the data for the load. P10 is able to merge a pair of adjacent stores. Try
12099 // to avoid load hit store on P10 when running binaries compiled for older
12100 // processors by generating two mergeable scalar stores to forward with the
12101 // vector load.
12102 if (!DisableP10StoreForward && Subtarget.isPPC64() &&
12103 !Subtarget.isLittleEndian() && ValVT.isInteger() &&
12104 ValVT.getSizeInBits() <= 64) {
12105 Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, Val);
12106 EVT ShiftAmountTy = getShiftAmountTy(MVT::i64, DAG.getDataLayout());
12107 SDValue ShiftBy = DAG.getConstant(
12108 64 - Op.getValueType().getScalarSizeInBits(), dl, ShiftAmountTy);
12109 Val = DAG.getNode(ISD::SHL, dl, MVT::i64, Val, ShiftBy);
12110 SDValue Plus8 =
12111 DAG.getNode(ISD::ADD, dl, PtrVT, FIdx, DAG.getConstant(8, dl, PtrVT));
12112 SDValue Store2 =
12113 DAG.getStore(DAG.getEntryNode(), dl, Val, Plus8, MachinePointerInfo());
12114 SDValue Store = DAG.getStore(Store2, dl, Val, FIdx, MachinePointerInfo());
12115 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx,
12116 MachinePointerInfo());
12117 }
12118
12119 // Store the input value into Value#0 of the stack slot.
12120 SDValue Store =
12121 DAG.getStore(DAG.getEntryNode(), dl, Val, FIdx, MachinePointerInfo());
12122 // Load it out.
12123 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
12124}
12125
12126SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12127 SelectionDAG &DAG) const {
12128 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12129 "Should only be called for ISD::INSERT_VECTOR_ELT");
12130
12131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
12132
12133 EVT VT = Op.getValueType();
12134 SDLoc dl(Op);
12135 SDValue V1 = Op.getOperand(0);
12136 SDValue V2 = Op.getOperand(1);
12137
12138 if (VT == MVT::v2f64 && C)
12139 return Op;
12140
12141 if (Subtarget.hasP9Vector()) {
12142 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
12143 // because on P10, it allows this specific insert_vector_elt load pattern to
12144 // utilize the refactored load and store infrastructure in order to exploit
12145 // prefixed loads.
12146 // On targets with inexpensive direct moves (Power9 and up), a
12147 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
12148 // load since a single precision load will involve conversion to double
12149 // precision on the load followed by another conversion to single precision.
12150 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
12151 (isa<LoadSDNode>(V2))) {
12152 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
12153 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
12154 SDValue InsVecElt =
12155 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
12156 BitcastLoad, Op.getOperand(2));
12157 return DAG.getBitcast(MVT::v4f32, InsVecElt);
12158 }
12159 }
12160
12161 if (Subtarget.isISA3_1()) {
12162 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
12163 return SDValue();
12164 // On P10, we have legal lowering for constant and variable indices for
12165 // all vectors.
12166 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
12167 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
12168 return Op;
12169 }
12170
12171 // Before P10, we have legal lowering for constant indices but not for
12172 // variable ones.
12173 if (!C)
12174 return SDValue();
12175
12176 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
12177 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
12178 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
12179 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
12180 unsigned InsertAtElement = C->getZExtValue();
12181 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
12182 if (Subtarget.isLittleEndian()) {
12183 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
12184 }
12185 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
12186 DAG.getConstant(InsertAtByte, dl, MVT::i32));
12187 }
12188 return Op;
12189}
12190
12191SDValue PPCTargetLowering::LowerDMFVectorLoad(SDValue Op,
12192 SelectionDAG &DAG) const {
12193 SDLoc dl(Op);
12194 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12195 SDValue LoadChain = LN->getChain();
12196 SDValue BasePtr = LN->getBasePtr();
12197 EVT VT = Op.getValueType();
12198 bool IsV1024i1 = VT == MVT::v1024i1;
12199 bool IsV2048i1 = VT == MVT::v2048i1;
12200
12201 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12202 // Dense Math dmr pair registers, respectively.
12203 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12204 (void)IsV2048i1;
12205 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12206 "Dense Math support required.");
12207 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12208
12210 SmallVector<SDValue, 8> LoadChains;
12211
12212 SDValue IntrinID = DAG.getConstant(Intrinsic::ppc_vsx_lxvp, dl, MVT::i32);
12213 SDValue LoadOps[] = {LoadChain, IntrinID, BasePtr};
12214 MachineMemOperand *MMO = LN->getMemOperand();
12215 unsigned NumVecs = VT.getSizeInBits() / 256;
12216 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12217 MachineMemOperand *NewMMO =
12218 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12219 if (Idx > 0) {
12220 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12221 DAG.getConstant(32, dl, BasePtr.getValueType()));
12222 LoadOps[2] = BasePtr;
12223 }
12225 DAG.getVTList(MVT::v256i1, MVT::Other),
12226 LoadOps, MVT::v256i1, NewMMO);
12227 LoadChains.push_back(Ld.getValue(1));
12228 Loads.push_back(Ld);
12229 }
12230
12231 if (Subtarget.isLittleEndian()) {
12232 std::reverse(Loads.begin(), Loads.end());
12233 std::reverse(LoadChains.begin(), LoadChains.end());
12234 }
12235
12236 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12237 SDValue Value = DMFInsert1024(Loads, dl, DAG);
12238
12239 if (IsV1024i1) {
12240 return DAG.getMergeValues({Value, TF}, dl);
12241 }
12242
12243 // Handle Loads for V2048i1 which represents a dmr pair.
12244 SmallVector<SDValue, 4> MoreLoads{Loads[4], Loads[5], Loads[6], Loads[7]};
12245 SDValue Dmr1Value = DMFInsert1024(MoreLoads, dl, DAG);
12246
12247 SDValue Dmr0Sub = DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32);
12248 SDValue Dmr1Sub = DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32);
12249
12250 SDValue DmrPRC = DAG.getTargetConstant(PPC::DMRpRCRegClassID, dl, MVT::i32);
12251 const SDValue DmrPOps[] = {DmrPRC, Value, Dmr0Sub, Dmr1Value, Dmr1Sub};
12252
12253 SDValue DmrPValue = SDValue(
12254 DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v2048i1, DmrPOps), 0);
12255
12256 return DAG.getMergeValues({DmrPValue, TF}, dl);
12257}
12258
12259SDValue PPCTargetLowering::DMFInsert1024(const SmallVectorImpl<SDValue> &Pairs,
12260 const SDLoc &dl,
12261 SelectionDAG &DAG) const {
12262 SDValue Lo =
12263 DAG.getNode(PPCISD::INST512, dl, MVT::v512i1, Pairs[0], Pairs[1]);
12264 SDValue LoSub = DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32);
12265 SDValue Hi =
12266 DAG.getNode(PPCISD::INST512HI, dl, MVT::v512i1, Pairs[2], Pairs[3]);
12267 SDValue HiSub = DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32);
12268 SDValue RC = DAG.getTargetConstant(PPC::DMRRCRegClassID, dl, MVT::i32);
12269
12270 return SDValue(DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v1024i1,
12271 {RC, Lo, LoSub, Hi, HiSub}),
12272 0);
12273}
12274
12275SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
12276 SelectionDAG &DAG) const {
12277 SDLoc dl(Op);
12278 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12279 SDValue LoadChain = LN->getChain();
12280 SDValue BasePtr = LN->getBasePtr();
12281 EVT VT = Op.getValueType();
12282
12283 if (VT == MVT::v1024i1 || VT == MVT::v2048i1)
12284 return LowerDMFVectorLoad(Op, DAG);
12285
12286 if (VT != MVT::v256i1 && VT != MVT::v512i1)
12287 return Op;
12288
12289 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12290 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
12291 "Type unsupported without MMA");
12292 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12293 "Type unsupported without paired vector support");
12294
12295 // For v256i1 on ISA Future, let the load go through to instruction selection
12296 // where it will be matched to lxvp/plxvp by the instruction patterns.
12297 if (VT == MVT::v256i1 && Subtarget.isISAFuture())
12298 return Op;
12299
12300 // For other cases, create 2 or 4 v16i8 loads to load the pair or accumulator
12301 // value in 2 or 4 vsx registers.
12302 Align Alignment = LN->getAlign();
12304 SmallVector<SDValue, 4> LoadChains;
12305 unsigned NumVecs = VT.getSizeInBits() / 128;
12306 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12307 SDValue Load =
12308 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
12309 LN->getPointerInfo().getWithOffset(Idx * 16),
12310 commonAlignment(Alignment, Idx * 16),
12311 LN->getMemOperand()->getFlags(), LN->getAAInfo());
12312 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12313 DAG.getConstant(16, dl, BasePtr.getValueType()));
12314 Loads.push_back(Load);
12315 LoadChains.push_back(Load.getValue(1));
12316 }
12317 if (Subtarget.isLittleEndian()) {
12318 std::reverse(Loads.begin(), Loads.end());
12319 std::reverse(LoadChains.begin(), LoadChains.end());
12320 }
12321 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12322 SDValue Value =
12323 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
12324 dl, VT, Loads);
12325 SDValue RetOps[] = {Value, TF};
12326 return DAG.getMergeValues(RetOps, dl);
12327}
12328
12329SDValue PPCTargetLowering::LowerDMFVectorStore(SDValue Op,
12330 SelectionDAG &DAG) const {
12331
12332 SDLoc dl(Op);
12333 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12334 SDValue StoreChain = SN->getChain();
12335 SDValue BasePtr = SN->getBasePtr();
12338 EVT VT = SN->getValue().getValueType();
12339 bool IsV1024i1 = VT == MVT::v1024i1;
12340 bool IsV2048i1 = VT == MVT::v2048i1;
12341
12342 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12343 // Dense Math dmr pair registers, respectively.
12344 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12345 (void)IsV2048i1;
12346 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12347 "Dense Math support required.");
12348 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12349
12350 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12351 if (IsV1024i1) {
12353 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12354 Op.getOperand(1),
12355 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12356 0);
12358 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12359 Op.getOperand(1),
12360 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12361 0);
12362 MachineSDNode *ExtNode =
12363 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Lo);
12364 Values.push_back(SDValue(ExtNode, 0));
12365 Values.push_back(SDValue(ExtNode, 1));
12366 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Hi);
12367 Values.push_back(SDValue(ExtNode, 0));
12368 Values.push_back(SDValue(ExtNode, 1));
12369 } else {
12370 // This corresponds to v2048i1 which represents a dmr pair.
12371 SDValue Dmr0(
12372 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12373 Op.getOperand(1),
12374 DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32)),
12375 0);
12376
12377 SDValue Dmr1(
12378 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12379 Op.getOperand(1),
12380 DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32)),
12381 0);
12382
12383 SDValue Dmr0Lo(DAG.getMachineNode(
12384 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12385 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12386 0);
12387
12388 SDValue Dmr0Hi(DAG.getMachineNode(
12389 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12390 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12391 0);
12392
12393 SDValue Dmr1Lo(DAG.getMachineNode(
12394 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12395 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12396 0);
12397
12398 SDValue Dmr1Hi(DAG.getMachineNode(
12399 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12400 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12401 0);
12402
12403 MachineSDNode *ExtNode =
12404 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr0Lo);
12405 Values.push_back(SDValue(ExtNode, 0));
12406 Values.push_back(SDValue(ExtNode, 1));
12407 ExtNode =
12408 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr0Hi);
12409 Values.push_back(SDValue(ExtNode, 0));
12410 Values.push_back(SDValue(ExtNode, 1));
12411 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr1Lo);
12412 Values.push_back(SDValue(ExtNode, 0));
12413 Values.push_back(SDValue(ExtNode, 1));
12414 ExtNode =
12415 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr1Hi);
12416 Values.push_back(SDValue(ExtNode, 0));
12417 Values.push_back(SDValue(ExtNode, 1));
12418 }
12419
12420 if (Subtarget.isLittleEndian())
12421 std::reverse(Values.begin(), Values.end());
12422
12423 SDVTList Tys = DAG.getVTList(MVT::Other);
12425 StoreChain, DAG.getConstant(Intrinsic::ppc_vsx_stxvp, dl, MVT::i32),
12426 Values[0], BasePtr};
12427 MachineMemOperand *MMO = SN->getMemOperand();
12428 unsigned NumVecs = VT.getSizeInBits() / 256;
12429 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12430 MachineMemOperand *NewMMO =
12431 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12432 if (Idx > 0) {
12433 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12434 DAG.getConstant(32, dl, BasePtr.getValueType()));
12435 Ops[3] = BasePtr;
12436 }
12437 Ops[2] = Values[Idx];
12439 MVT::v256i1, NewMMO);
12440 Stores.push_back(St);
12441 }
12442
12443 SDValue TF = DAG.getTokenFactor(dl, Stores);
12444 return TF;
12445}
12446
12447SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
12448 SelectionDAG &DAG) const {
12449 SDLoc dl(Op);
12450 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12451 SDValue StoreChain = SN->getChain();
12452 SDValue BasePtr = SN->getBasePtr();
12453 SDValue Value = SN->getValue();
12454 SDValue Value2 = SN->getValue();
12455 EVT StoreVT = Value.getValueType();
12456
12457 if (StoreVT == MVT::v1024i1 || StoreVT == MVT::v2048i1)
12458 return LowerDMFVectorStore(Op, DAG);
12459
12460 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
12461 return Op;
12462
12463 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12464 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
12465 "Type unsupported without MMA");
12466 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12467 "Type unsupported without paired vector support");
12468
12469 // For v256i1 on ISA Future, let the store go through to instruction selection
12470 // where it will be matched to stxvp/pstxvp by the instruction patterns.
12471 if (StoreVT == MVT::v256i1 && Subtarget.isISAFuture() &&
12473 return Op;
12474
12475 // For other cases, create 2 or 4 v16i8 stores to store the pair or
12476 // accumulator underlying registers individually.
12477 Align Alignment = SN->getAlign();
12479 unsigned NumVecs = 2;
12480 if (StoreVT == MVT::v512i1) {
12481 if (Subtarget.isISAFuture()) {
12482 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12483 MachineSDNode *ExtNode = DAG.getMachineNode(
12484 PPC::DMXXEXTFDMR512, dl, ReturnTypes, Op.getOperand(1));
12485
12486 Value = SDValue(ExtNode, 0);
12487 Value2 = SDValue(ExtNode, 1);
12488 } else
12489 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
12490 NumVecs = 4;
12491 }
12492 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12493 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
12494 SDValue Elt;
12495 if (Subtarget.isISAFuture()) {
12496 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2);
12497 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
12498 Idx > 1 ? Value2 : Value,
12499 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12500 } else
12501 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
12502 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12503
12504 SDValue Store =
12505 DAG.getStore(StoreChain, dl, Elt, BasePtr,
12506 SN->getPointerInfo().getWithOffset(Idx * 16),
12507 commonAlignment(Alignment, Idx * 16),
12508 SN->getMemOperand()->getFlags(), SN->getAAInfo());
12509 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12510 DAG.getConstant(16, dl, BasePtr.getValueType()));
12511 Stores.push_back(Store);
12512 }
12513 SDValue TF = DAG.getTokenFactor(dl, Stores);
12514 return TF;
12515}
12516
12517SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
12518 SDLoc dl(Op);
12519 if (Op.getValueType() == MVT::v4i32) {
12520 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12521
12522 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
12523 // +16 as shift amt.
12524 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
12525 SDValue RHSSwap = // = vrlw RHS, 16
12526 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
12527
12528 // Shrinkify inputs to v8i16.
12529 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
12530 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
12531 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
12532
12533 // Low parts multiplied together, generating 32-bit results (we ignore the
12534 // top parts).
12535 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
12536 LHS, RHS, DAG, dl, MVT::v4i32);
12537
12538 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
12539 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
12540 // Shift the high parts up 16 bits.
12541 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
12542 Neg16, DAG, dl);
12543 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
12544 } else if (Op.getValueType() == MVT::v16i8) {
12545 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12546 bool isLittleEndian = Subtarget.isLittleEndian();
12547
12548 // Multiply the even 8-bit parts, producing 16-bit sums.
12549 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
12550 LHS, RHS, DAG, dl, MVT::v8i16);
12551 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
12552
12553 // Multiply the odd 8-bit parts, producing 16-bit sums.
12554 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
12555 LHS, RHS, DAG, dl, MVT::v8i16);
12556 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
12557
12558 // Merge the results together. Because vmuleub and vmuloub are
12559 // instructions with a big-endian bias, we must reverse the
12560 // element numbering and reverse the meaning of "odd" and "even"
12561 // when generating little endian code.
12562 int Ops[16];
12563 for (unsigned i = 0; i != 8; ++i) {
12564 if (isLittleEndian) {
12565 Ops[i*2 ] = 2*i;
12566 Ops[i*2+1] = 2*i+16;
12567 } else {
12568 Ops[i*2 ] = 2*i+1;
12569 Ops[i*2+1] = 2*i+1+16;
12570 }
12571 }
12572 if (isLittleEndian)
12573 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
12574 else
12575 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
12576 } else {
12577 llvm_unreachable("Unknown mul to lower!");
12578 }
12579}
12580
12581SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12582 bool IsStrict = Op->isStrictFPOpcode();
12583 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
12584 !Subtarget.hasP9Vector())
12585 return SDValue();
12586
12587 return Op;
12588}
12589
12590// Custom lowering for fpext vf32 to v2f64
12591SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12592
12593 assert(Op.getOpcode() == ISD::FP_EXTEND &&
12594 "Should only be called for ISD::FP_EXTEND");
12595
12596 // FIXME: handle extends from half precision float vectors on P9.
12597 // We only want to custom lower an extend from v2f32 to v2f64.
12598 if (Op.getValueType() != MVT::v2f64 ||
12599 Op.getOperand(0).getValueType() != MVT::v2f32)
12600 return SDValue();
12601
12602 SDLoc dl(Op);
12603 SDValue Op0 = Op.getOperand(0);
12604
12605 switch (Op0.getOpcode()) {
12606 default:
12607 return SDValue();
12609 assert(Op0.getNumOperands() == 2 &&
12611 "Node should have 2 operands with second one being a constant!");
12612
12613 if (Op0.getOperand(0).getValueType() != MVT::v4f32)
12614 return SDValue();
12615
12616 // Custom lower is only done for high or low doubleword.
12617 int Idx = Op0.getConstantOperandVal(1);
12618 if (Idx % 2 != 0)
12619 return SDValue();
12620
12621 // Since input is v4f32, at this point Idx is either 0 or 2.
12622 // Shift to get the doubleword position we want.
12623 int DWord = Idx >> 1;
12624
12625 // High and low word positions are different on little endian.
12626 if (Subtarget.isLittleEndian())
12627 DWord ^= 0x1;
12628
12629 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
12630 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
12631 }
12632 case ISD::FADD:
12633 case ISD::FMUL:
12634 case ISD::FSUB: {
12635 SDValue NewLoad[2];
12636 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
12637 // Ensure both input are loads.
12638 SDValue LdOp = Op0.getOperand(i);
12639 if (LdOp.getOpcode() != ISD::LOAD)
12640 return SDValue();
12641 // Generate new load node.
12642 LoadSDNode *LD = cast<LoadSDNode>(LdOp);
12643 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12644 NewLoad[i] = DAG.getMemIntrinsicNode(
12645 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12646 LD->getMemoryVT(), LD->getMemOperand());
12647 }
12648 SDValue NewOp =
12649 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
12650 NewLoad[1], Op0.getNode()->getFlags());
12651 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
12652 DAG.getConstant(0, dl, MVT::i32));
12653 }
12654 case ISD::LOAD: {
12655 LoadSDNode *LD = cast<LoadSDNode>(Op0);
12656 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12657 SDValue NewLd = DAG.getMemIntrinsicNode(
12658 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12659 LD->getMemoryVT(), LD->getMemOperand());
12660 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
12661 DAG.getConstant(0, dl, MVT::i32));
12662 }
12663 }
12664 llvm_unreachable("ERROR:Should return for all cases within swtich.");
12665}
12666
12668 SelectionDAG &DAG,
12669 const PPCSubtarget &STI) {
12670 SDLoc DL(Value);
12671 if (STI.useCRBits())
12672 Value = DAG.getNode(ISD::SELECT, DL, SumType, Value,
12673 DAG.getConstant(1, DL, SumType),
12674 DAG.getConstant(0, DL, SumType));
12675 else
12676 Value = DAG.getZExtOrTrunc(Value, DL, SumType);
12677 SDValue Sum = DAG.getNode(PPCISD::ADDC, DL, DAG.getVTList(SumType, MVT::i32),
12678 Value, DAG.getAllOnesConstant(DL, SumType));
12679 return Sum.getValue(1);
12680}
12681
12683 EVT CarryType, SelectionDAG &DAG,
12684 const PPCSubtarget &STI) {
12685 SDLoc DL(Flag);
12686 SDValue Zero = DAG.getConstant(0, DL, SumType);
12687 SDValue Carry = DAG.getNode(
12688 PPCISD::ADDE, DL, DAG.getVTList(SumType, MVT::i32), Zero, Zero, Flag);
12689 if (STI.useCRBits())
12690 return DAG.getSetCC(DL, CarryType, Carry, Zero, ISD::SETNE);
12691 return DAG.getZExtOrTrunc(Carry, DL, CarryType);
12692}
12693
12694SDValue PPCTargetLowering::LowerADDSUBO(SDValue Op, SelectionDAG &DAG) const {
12695
12696 SDLoc DL(Op);
12697 SDNode *N = Op.getNode();
12698 EVT VT = N->getValueType(0);
12699 EVT CarryType = N->getValueType(1);
12700 unsigned Opc = N->getOpcode();
12701 bool IsAdd = Opc == ISD::UADDO;
12702 Opc = IsAdd ? PPCISD::ADDC : PPCISD::SUBC;
12703 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12704 N->getOperand(0), N->getOperand(1));
12705 SDValue Carry = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType,
12706 DAG, Subtarget);
12707 if (!IsAdd)
12708 Carry = DAG.getNode(ISD::XOR, DL, CarryType, Carry,
12709 DAG.getConstant(1UL, DL, CarryType));
12710 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, Carry);
12711}
12712
12713SDValue PPCTargetLowering::LowerADDSUBO_CARRY(SDValue Op,
12714 SelectionDAG &DAG) const {
12715 SDLoc DL(Op);
12716 SDNode *N = Op.getNode();
12717 unsigned Opc = N->getOpcode();
12718 EVT VT = N->getValueType(0);
12719 EVT CarryType = N->getValueType(1);
12720 SDValue CarryOp = N->getOperand(2);
12721 bool IsAdd = Opc == ISD::UADDO_CARRY;
12722 Opc = IsAdd ? PPCISD::ADDE : PPCISD::SUBE;
12723 if (!IsAdd)
12724 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12725 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12726 CarryOp = ConvertCarryValueToCarryFlag(VT, CarryOp, DAG, Subtarget);
12727 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12728 Op.getOperand(0), Op.getOperand(1), CarryOp);
12729 CarryOp = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType, DAG,
12730 Subtarget);
12731 if (!IsAdd)
12732 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12733 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12734 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, CarryOp);
12735}
12736
12737SDValue PPCTargetLowering::LowerSSUBO(SDValue Op, SelectionDAG &DAG) const {
12738
12739 SDLoc dl(Op);
12740 SDValue LHS = Op.getOperand(0);
12741 SDValue RHS = Op.getOperand(1);
12742 EVT VT = Op.getNode()->getValueType(0);
12743
12744 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12745
12746 SDValue Xor1 = DAG.getNode(ISD::XOR, dl, VT, RHS, LHS);
12747 SDValue Xor2 = DAG.getNode(ISD::XOR, dl, VT, Sub, LHS);
12748
12749 SDValue And = DAG.getNode(ISD::AND, dl, VT, Xor1, Xor2);
12750
12751 SDValue Overflow =
12752 DAG.getNode(ISD::SRL, dl, VT, And,
12753 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12754
12755 SDValue OverflowTrunc =
12756 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12757
12758 return DAG.getMergeValues({Sub, OverflowTrunc}, dl);
12759}
12760
12761/// Implements signed add with overflow detection using the rule:
12762/// (x eqv y) & (sum xor x), where the overflow bit is extracted from the sign
12763SDValue PPCTargetLowering::LowerSADDO(SDValue Op, SelectionDAG &DAG) const {
12764
12765 SDLoc dl(Op);
12766 SDValue LHS = Op.getOperand(0);
12767 SDValue RHS = Op.getOperand(1);
12768 EVT VT = Op.getNode()->getValueType(0);
12769
12770 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
12771
12772 // Compute ~(x xor y)
12773 SDValue XorXY = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12774 SDValue EqvXY = DAG.getNOT(dl, XorXY, VT);
12775 // Compute (s xor x)
12776 SDValue SumXorX = DAG.getNode(ISD::XOR, dl, VT, Sum, LHS);
12777
12778 // overflow = (x eqv y) & (s xor x)
12779 SDValue OverflowInSign = DAG.getNode(ISD::AND, dl, VT, EqvXY, SumXorX);
12780
12781 // Shift sign bit down to LSB
12782 SDValue Overflow =
12783 DAG.getNode(ISD::SRL, dl, VT, OverflowInSign,
12784 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12785 // Truncate to the overflow type (i1)
12786 SDValue OverflowTrunc =
12787 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12788
12789 return DAG.getMergeValues({Sum, OverflowTrunc}, dl);
12790}
12791
12792/// Lower ABDU with negation pattern using branchless carry arithmetic.
12793/// Recognizes: abdu(a, sub(0, x)) and transforms to:
12794/// a - (0 - x) = a + x (mod 2^n)
12795/// Uses SUBC to compute result without branches.
12796SDValue PPCTargetLowering::LowerABDU(SDValue Op, SelectionDAG &DAG) const {
12797 SDLoc DL(Op);
12798 SDValue LHS = Op.getOperand(0);
12799 SDValue RHS = Op.getOperand(1);
12800 EVT OpVT = LHS.getValueType();
12801 EVT VT = Op.getValueType();
12802 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
12803
12804 // If the subtract doesn't overflow then just use abs(sub()).
12805 if (DAG.willNotOverflowSub(IsNonNegative, LHS, RHS))
12806 return DAG.getNode(ISD::ABS, DL, VT,
12807 DAG.getNode(ISD::SUB, DL, VT, LHS, RHS));
12808
12809 if (DAG.willNotOverflowSub(IsNonNegative, RHS, LHS))
12810 return DAG.getNode(ISD::ABS, DL, VT,
12811 DAG.getNode(ISD::SUB, DL, VT, RHS, LHS));
12812
12813 // General path: use SUBC (or ADDC when RHS is 0-X) to get
12814 // subtract-with-flags, then CMOV to select a-b or b-a. ADDC/SUBC produce the
12815 // flags we need.
12816 unsigned Opcode = PPCISD::SUBC;
12817
12818 // Check if RHS is a negation (0 - X). If so, we can use ADDC instead of SUBC:
12819 // a - (0 - x) = a + x (mod 2^n)
12820 // Same semantics as in LowerCMP; apply same safety checks.
12821 if (RHS.getOpcode() == ISD::SUB) {
12822 SDValue SubLHS = RHS.getOperand(0);
12823 SDValue SubRHS = RHS.getOperand(1);
12824
12825 if (isNullConstant(SubLHS) && DAG.isKnownNeverZero(SubRHS)) {
12826 Opcode = PPCISD::ADDC;
12827 RHS = SubRHS;
12828 }
12829 }
12830
12831 // On PPC64, carry ops use the full 64-bit register. Operands are type-legal
12832 // i32 here; widen only for the carry path (fast abs(sub) stays at VT).
12833 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12834 LHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, LHS);
12835 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RHS);
12836 OpVT = MVT::i64;
12837 }
12838
12839 // Calculate LHS - RHS and capture the carry (CA)
12840 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12841 SDValue Res = DAG.getNode(Opcode, DL, VTs, LHS, RHS);
12842 SDValue CA0 = Res.getValue(1);
12843
12844 // t2 = A - B + CA0 using SUBE.
12845 SDValue ZeroOrNeg1 = DAG.getNode(PPCISD::SUBE, DL, VTs, Res, Res, CA0);
12846
12847 SDValue Xor = DAG.getNode(ISD::XOR, DL, OpVT, Res, ZeroOrNeg1);
12848
12849 Res = DAG.getNode(ISD::SUB, DL, OpVT, Xor, ZeroOrNeg1);
12850
12851 Res = DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
12852 return Res;
12853}
12854
12855// Lower unsigned 3-way compare producing -1/0/1.
12856SDValue PPCTargetLowering::LowerUCMP(SDValue Op, SelectionDAG &DAG) const {
12857 SDLoc DL(Op);
12858 SDValue A = DAG.getFreeze(Op.getOperand(0));
12859 SDValue B = DAG.getFreeze(Op.getOperand(1));
12860 EVT OpVT = A.getValueType();
12861 EVT ResVT = Op.getValueType();
12862
12863 // On PPC64, i32 carries are affected by the upper 32 bits of the registers.
12864 // We must zero-extend to i64 to ensure the carry reflects the 32-bit unsigned
12865 // comparison.
12866 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12867 A = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, A);
12868 B = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, B);
12869 OpVT = MVT::i64;
12870 }
12871
12872 // First compute diff = A - B.
12873 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, A, B);
12874
12875 // Generate B - A using SUBC to capture carry.
12876 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12877 SDValue SubC = DAG.getNode(PPCISD::SUBC, DL, VTs, B, A);
12878 SDValue CA0 = SubC.getValue(1);
12879
12880 // t2 = A - B + CA0 using SUBE.
12881 SDValue SubE1 = DAG.getNode(PPCISD::SUBE, DL, VTs, A, B, CA0);
12882 SDValue CA1 = SubE1.getValue(1);
12883
12884 // res = diff - t2 + CA1 using SUBE (produces desired -1/0/1).
12885 SDValue ResPair = DAG.getNode(PPCISD::SUBE, DL, VTs, Diff, SubE1, CA1);
12886
12887 // Extract the first result and truncate to result type if needed.
12888 return DAG.getSExtOrTrunc(ResPair.getValue(0), DL, ResVT);
12889}
12890
12891/// LowerOperation - Provide custom lowering hooks for some operations.
12892///
12894 switch (Op.getOpcode()) {
12895 default:
12896 llvm_unreachable("Wasn't expecting to be able to lower this!");
12897 case ISD::FPOW: return lowerPow(Op, DAG);
12898 case ISD::FSIN: return lowerSin(Op, DAG);
12899 case ISD::FCOS: return lowerCos(Op, DAG);
12900 case ISD::FLOG: return lowerLog(Op, DAG);
12901 case ISD::FLOG10: return lowerLog10(Op, DAG);
12902 case ISD::FEXP: return lowerExp(Op, DAG);
12903 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12904 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12905 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12906 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12907 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12908 case ISD::STRICT_FSETCC:
12910 case ISD::SETCC: return LowerSETCC(Op, DAG);
12911 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
12912 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12913 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12914 case ISD::SSUBO:
12915 return LowerSSUBO(Op, DAG);
12916 case ISD::SADDO:
12917 return LowerSADDO(Op, DAG);
12918
12919 case ISD::INLINEASM:
12920 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
12921 // Variable argument lowering.
12922 case ISD::VASTART: return LowerVASTART(Op, DAG);
12923 case ISD::VAARG: return LowerVAARG(Op, DAG);
12924 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
12925
12926 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
12927 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12929 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
12930
12931 // Exception handling lowering.
12932 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
12933 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12934 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12935
12936 case ISD::LOAD: return LowerLOAD(Op, DAG);
12937 case ISD::STORE: return LowerSTORE(Op, DAG);
12938 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12939 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
12942 case ISD::FP_TO_UINT:
12943 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
12946 case ISD::UINT_TO_FP:
12947 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
12948 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
12949 case ISD::SET_ROUNDING:
12950 return LowerSET_ROUNDING(Op, DAG);
12951
12952 // Lower 64-bit shifts.
12953 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
12954 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
12955 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
12956
12957 case ISD::FSHL: return LowerFunnelShift(Op, DAG);
12958 case ISD::FSHR: return LowerFunnelShift(Op, DAG);
12959
12960 // Vector-related lowering.
12961 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12962 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12963 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12964 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12965 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12966 case ISD::MUL: return LowerMUL(Op, DAG);
12967 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12969 case ISD::FP_ROUND:
12970 return LowerFP_ROUND(Op, DAG);
12971 case ISD::ROTL: return LowerROTL(Op, DAG);
12972
12973 // For counter-based loop handling.
12975 return SDValue();
12976
12977 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12978
12979 // Frame & Return address.
12980 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12981 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12982
12984 return LowerINTRINSIC_VOID(Op, DAG);
12985 case ISD::BSWAP:
12986 return LowerBSWAP(Op, DAG);
12988 return LowerATOMIC_CMP_SWAP(Op, DAG);
12989 case ISD::ATOMIC_STORE:
12990 return LowerATOMIC_LOAD_STORE(Op, DAG);
12991 case ISD::IS_FPCLASS:
12992 return LowerIS_FPCLASS(Op, DAG);
12993 case ISD::UADDO:
12994 case ISD::USUBO:
12995 return LowerADDSUBO(Op, DAG);
12996 case ISD::UADDO_CARRY:
12997 case ISD::USUBO_CARRY:
12998 return LowerADDSUBO_CARRY(Op, DAG);
12999 case ISD::UCMP:
13000 return LowerUCMP(Op, DAG);
13001 case ISD::ABDU:
13002 return LowerABDU(Op, DAG);
13003 case ISD::STRICT_LRINT:
13004 case ISD::STRICT_LLRINT:
13005 case ISD::STRICT_LROUND:
13008 if (Op->getFlags().hasNoFPExcept())
13009 return Op;
13010 return SDValue();
13011 case ISD::VP_LOAD:
13012 return LowerVP_LOAD(Op, DAG);
13013 case ISD::VP_STORE:
13014 return LowerVP_STORE(Op, DAG);
13016 return LowerPartialReduce(Op, DAG);
13017 }
13018}
13019
13022 SelectionDAG &DAG) const {
13023 SDLoc dl(N);
13024 switch (N->getOpcode()) {
13025 default:
13026 llvm_unreachable("Do not know how to custom type legalize this operation!");
13027 case ISD::ATOMIC_LOAD: {
13028 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
13029 Results.push_back(Res);
13030 Results.push_back(Res.getValue(1));
13031 break;
13032 }
13033 case ISD::READCYCLECOUNTER: {
13034 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13035 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
13036
13037 Results.push_back(
13038 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
13039 Results.push_back(RTB.getValue(2));
13040 break;
13041 }
13043 if (N->getConstantOperandVal(1) != Intrinsic::loop_decrement)
13044 break;
13045
13046 assert(N->getValueType(0) == MVT::i1 &&
13047 "Unexpected result type for CTR decrement intrinsic");
13048 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13049 N->getValueType(0));
13050 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
13051 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
13052 N->getOperand(1));
13053
13054 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
13055 Results.push_back(NewInt.getValue(1));
13056 break;
13057 }
13059 switch (N->getConstantOperandVal(0)) {
13060 case Intrinsic::ppc_pack_longdouble:
13061 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
13062 N->getOperand(2), N->getOperand(1)));
13063 break;
13064 case Intrinsic::ppc_maxfe:
13065 case Intrinsic::ppc_minfe:
13066 case Intrinsic::ppc_fnmsub:
13067 case Intrinsic::ppc_convert_f128_to_ppcf128:
13068 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
13069 break;
13070 }
13071 break;
13072 }
13073 case ISD::VAARG: {
13074 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
13075 return;
13076
13077 EVT VT = N->getValueType(0);
13078
13079 if (VT == MVT::i64) {
13080 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
13081
13082 Results.push_back(NewNode);
13083 Results.push_back(NewNode.getValue(1));
13084 }
13085 return;
13086 }
13089 case ISD::FP_TO_SINT:
13090 case ISD::FP_TO_UINT: {
13091 // LowerFP_TO_INT() can only handle f32 and f64.
13092 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
13093 MVT::ppcf128)
13094 return;
13095 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
13096 Results.push_back(LoweredValue);
13097 if (N->isStrictFPOpcode())
13098 Results.push_back(LoweredValue.getValue(1));
13099 return;
13100 }
13101 case ISD::TRUNCATE: {
13102 if (!N->getValueType(0).isVector())
13103 return;
13104 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
13105 if (Lowered)
13106 Results.push_back(Lowered);
13107 return;
13108 }
13109 case ISD::SCALAR_TO_VECTOR: {
13110 SDValue Lowered = LowerSCALAR_TO_VECTOR(SDValue(N, 0), DAG);
13111 if (Lowered)
13112 Results.push_back(Lowered);
13113 return;
13114 }
13115 case ISD::FSHL:
13116 case ISD::FSHR:
13117 // Don't handle funnel shifts here.
13118 return;
13119 case ISD::BITCAST:
13120 // Don't handle bitcast here.
13121 return;
13122 case ISD::FP_EXTEND:
13123 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
13124 if (Lowered)
13125 Results.push_back(Lowered);
13126 return;
13127 }
13128}
13129
13130//===----------------------------------------------------------------------===//
13131// Other Lowering Code
13132//===----------------------------------------------------------------------===//
13133
13135 return Builder.CreateIntrinsicWithoutFolding(Id, {});
13136}
13137
13139 Value *Addr,
13140 AtomicOrdering Ord) const {
13141 unsigned SZ = ValueTy->getPrimitiveSizeInBits();
13142
13143 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13144 "Only 8/16/32/64-bit atomic loads supported");
13145 Intrinsic::ID IntID;
13146 switch (SZ) {
13147 default:
13148 llvm_unreachable("Unexpected PrimitiveSize");
13149 case 8:
13150 IntID = Intrinsic::ppc_lbarx;
13151 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13152 break;
13153 case 16:
13154 IntID = Intrinsic::ppc_lharx;
13155 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13156 break;
13157 case 32:
13158 IntID = Intrinsic::ppc_lwarx;
13159 break;
13160 case 64:
13161 IntID = Intrinsic::ppc_ldarx;
13162 break;
13163 }
13164 Value *Call =
13165 Builder.CreateIntrinsic(IntID, Addr, /*FMFSource=*/nullptr, "larx");
13166
13167 return Builder.CreateTruncOrBitCast(Call, ValueTy);
13168}
13169
13170// Perform a store-conditional operation to Addr. Return the status of the
13171// store. This should be 0 if the store succeeded, non-zero otherwise.
13173 Value *Val, Value *Addr,
13174 AtomicOrdering Ord) const {
13175 Type *Ty = Val->getType();
13176 unsigned SZ = Ty->getPrimitiveSizeInBits();
13177
13178 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13179 "Only 8/16/32/64-bit atomic loads supported");
13180 Intrinsic::ID IntID;
13181 switch (SZ) {
13182 default:
13183 llvm_unreachable("Unexpected PrimitiveSize");
13184 case 8:
13185 IntID = Intrinsic::ppc_stbcx;
13186 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13187 break;
13188 case 16:
13189 IntID = Intrinsic::ppc_sthcx;
13190 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13191 break;
13192 case 32:
13193 IntID = Intrinsic::ppc_stwcx;
13194 break;
13195 case 64:
13196 IntID = Intrinsic::ppc_stdcx;
13197 break;
13198 }
13199
13200 if (SZ == 8 || SZ == 16)
13201 Val = Builder.CreateZExt(Val, Builder.getInt32Ty());
13202
13203 Value *Call = Builder.CreateIntrinsic(IntID, {Addr, Val},
13204 /*FMFSource=*/nullptr, "stcx");
13205 return Builder.CreateXor(Call, Builder.getInt32(1));
13206}
13207
13208// The mappings for emitLeading/TrailingFence is taken from
13209// http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13211 Instruction *Inst,
13212 AtomicOrdering Ord) const {
13214 return callIntrinsic(Builder, Intrinsic::ppc_sync);
13215 if (isReleaseOrStronger(Ord))
13216 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13217 return nullptr;
13218}
13219
13221 Instruction *Inst,
13222 AtomicOrdering Ord) const {
13223 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
13224 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
13225 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
13226 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
13227 if (isa<LoadInst>(Inst))
13228 return Builder.CreateIntrinsicWithoutFolding(Intrinsic::ppc_cfence,
13229 {Inst->getType()}, {Inst});
13230 // FIXME: Can use isync for rmw operation.
13231 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13232 }
13233 return nullptr;
13234}
13235
13238 unsigned BinOpcode,
13239 unsigned CmpOpcode,
13240 unsigned CmpPred) const {
13241 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13242 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13243 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13244 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13245 unsigned AtomicSize = MI.getOperand(3).getImm();
13246
13247 auto LoadMnemonic = PPC::LDARX;
13248 auto StoreMnemonic = PPC::STDCX;
13249 switch (AtomicSize) {
13250 default:
13251 llvm_unreachable("Unexpected size of atomic entity");
13252 case 1:
13253 LoadMnemonic = PPC::LBARX;
13254 StoreMnemonic = PPC::STBCX;
13255 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13256 break;
13257 case 2:
13258 LoadMnemonic = PPC::LHARX;
13259 StoreMnemonic = PPC::STHCX;
13260 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13261 break;
13262 case 4:
13263 LoadMnemonic = PPC::LWARX;
13264 StoreMnemonic = PPC::STWCX;
13265 break;
13266 case 8:
13267 LoadMnemonic = PPC::LDARX;
13268 StoreMnemonic = PPC::STDCX;
13269 break;
13270 }
13271
13272 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13273 MachineFunction *F = BB->getParent();
13275
13276 if (CmpOpcode == PPC::CMPW && (AtomicSize == 1 || AtomicSize == 2))
13277 signExtendOperandIfUnknown(MI, BB, 4, /*IsByte=*/AtomicSize == 1, TII);
13278
13279 Register dest = MI.getOperand(0).getReg();
13280 Register ptrA = MI.getOperand(1).getReg();
13281 Register ptrB = MI.getOperand(2).getReg();
13282 Register incr = MI.getOperand(4).getReg();
13283 DebugLoc dl = MI.getDebugLoc();
13284
13285 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13286 MachineBasicBlock *loop2MBB =
13287 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13288 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13289 F->insert(It, loopMBB);
13290 if (CmpOpcode)
13291 F->insert(It, loop2MBB);
13292 F->insert(It, exitMBB);
13293 exitMBB->splice(exitMBB->begin(), BB,
13294 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13296
13297 MachineRegisterInfo &RegInfo = F->getRegInfo();
13298 Register TmpReg = (!BinOpcode) ? incr :
13299 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
13300 : &PPC::GPRCRegClass);
13301
13302 // thisMBB:
13303 // ...
13304 // fallthrough --> loopMBB
13305 BB->addSuccessor(loopMBB);
13306
13307 // loopMBB:
13308 // l[wd]arx dest, ptr
13309 // add r0, dest, incr
13310 // st[wd]cx. r0, ptr
13311 // bne- loopMBB
13312 // fallthrough --> exitMBB
13313
13314 // For max/min...
13315 // loopMBB:
13316 // l[wd]arx dest, ptr
13317 // cmpl?[wd] dest, incr
13318 // bgt exitMBB
13319 // loop2MBB:
13320 // st[wd]cx. dest, ptr
13321 // bne- loopMBB
13322 // fallthrough --> exitMBB
13323
13324 BB = loopMBB;
13325 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
13326 .addReg(ptrA).addReg(ptrB);
13327 if (BinOpcode)
13328 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
13329 if (CmpOpcode) {
13330 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13331 // Signed comparisons of byte or halfword values must be sign-extended.
13332 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
13333 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13334 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
13335 ExtReg).addReg(dest);
13336 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr);
13337 } else
13338 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr);
13339
13340 BuildMI(BB, dl, TII->get(PPC::BCC))
13341 .addImm(CmpPred)
13342 .addReg(CrReg)
13343 .addMBB(exitMBB);
13344 BB->addSuccessor(loop2MBB);
13345 BB->addSuccessor(exitMBB);
13346 BB = loop2MBB;
13347 }
13348 BuildMI(BB, dl, TII->get(StoreMnemonic))
13349 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
13350 BuildMI(BB, dl, TII->get(PPC::BCC))
13352 .addReg(PPC::CR0)
13353 .addMBB(loopMBB);
13354 BB->addSuccessor(loopMBB);
13355 BB->addSuccessor(exitMBB);
13356
13357 // exitMBB:
13358 // ...
13359 BB = exitMBB;
13360 return BB;
13361}
13362
13364 switch(MI.getOpcode()) {
13365 default:
13366 return false;
13367 case PPC::COPY:
13368 return TII->isSignExtended(MI.getOperand(1).getReg(),
13369 &MI.getMF()->getRegInfo());
13370 case PPC::LHA:
13371 case PPC::LHA8:
13372 case PPC::LHAU:
13373 case PPC::LHAU8:
13374 case PPC::LHAUX:
13375 case PPC::LHAUX8:
13376 case PPC::LHAX:
13377 case PPC::LHAX8:
13378 case PPC::LWA:
13379 case PPC::LWAUX:
13380 case PPC::LWAX:
13381 case PPC::LWAX_32:
13382 case PPC::LWA_32:
13383 case PPC::PLHA:
13384 case PPC::PLHA8:
13385 case PPC::PLHA8pc:
13386 case PPC::PLHApc:
13387 case PPC::PLWA:
13388 case PPC::PLWA8:
13389 case PPC::PLWA8pc:
13390 case PPC::PLWApc:
13391 case PPC::EXTSB:
13392 case PPC::EXTSB8:
13393 case PPC::EXTSB8_32_64:
13394 case PPC::EXTSB8_rec:
13395 case PPC::EXTSB_rec:
13396 case PPC::EXTSH:
13397 case PPC::EXTSH8:
13398 case PPC::EXTSH8_32_64:
13399 case PPC::EXTSH8_rec:
13400 case PPC::EXTSH_rec:
13401 case PPC::EXTSW:
13402 case PPC::EXTSWSLI:
13403 case PPC::EXTSWSLI_32_64:
13404 case PPC::EXTSWSLI_32_64_rec:
13405 case PPC::EXTSWSLI_rec:
13406 case PPC::EXTSW_32:
13407 case PPC::EXTSW_32_64:
13408 case PPC::EXTSW_32_64_rec:
13409 case PPC::EXTSW_rec:
13410 case PPC::SRAW:
13411 case PPC::SRAWI:
13412 case PPC::SRAWI_rec:
13413 case PPC::SRAW_rec:
13414 return true;
13415 }
13416 return false;
13417}
13418
13419// Sign extend operand OpIdx if the value is not known to be sign extended.
13420// Assumes the operand is a register. The flag IsByte controls which intruction
13421// is used for the sign extension.
13423 unsigned OpIdx, bool IsByte,
13424 const PPCInstrInfo *TII) {
13425 MachineFunction *F = MI.getMF();
13426 MachineRegisterInfo &RegInfo = F->getRegInfo();
13427 Register Reg = MI.getOperand(OpIdx).getReg();
13428 bool IsSignExtended =
13429 Reg.isVirtual() && isSignExtended(*RegInfo.getVRegDef(Reg), TII);
13430
13431 if (!IsSignExtended) {
13432 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13433 BuildMI(*BB, MI, MI.getDebugLoc(),
13434 TII->get(IsByte ? PPC::EXTSB : PPC::EXTSH), ValueReg)
13435 .addReg(Reg);
13436 MI.getOperand(OpIdx).setReg(ValueReg);
13437 }
13438}
13439
13441 MachineInstr &MI, MachineBasicBlock *BB, unsigned BinOpcode,
13442 unsigned CmpOpcode, unsigned CmpPred) const {
13443 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13444 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13445 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13446 assert(!Subtarget.hasPartwordAtomics() &&
13447 "Assumes that part-word atomics are not available");
13448 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13449
13450 // If this is a signed comparison and the value being compared is not known
13451 // to be sign extended, sign extend it here.
13452 DebugLoc dl = MI.getDebugLoc();
13453 MachineFunction *F = BB->getParent();
13454 MachineRegisterInfo &RegInfo = F->getRegInfo();
13455 const bool is8bit = MI.getOperand(3).getImm() == 1;
13456 if (CmpOpcode == PPC::CMPW)
13457 signExtendOperandIfUnknown(MI, BB, 4, is8bit, TII);
13458 Register incr = MI.getOperand(4).getReg();
13459
13460 // In 64 bit mode we have to use 64 bits for addresses, even though the
13461 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
13462 // registers without caring whether they're 32 or 64, but here we're
13463 // doing actual arithmetic on the addresses.
13464 bool is64bit = Subtarget.isPPC64();
13465 bool isLittleEndian = Subtarget.isLittleEndian();
13466 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
13467
13468 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13470
13471 Register dest = MI.getOperand(0).getReg();
13472 Register ptrA = MI.getOperand(1).getReg();
13473 Register ptrB = MI.getOperand(2).getReg();
13474
13475 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13476 MachineBasicBlock *loop2MBB =
13477 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13478 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13479 F->insert(It, loopMBB);
13480 if (CmpOpcode)
13481 F->insert(It, loop2MBB);
13482 F->insert(It, exitMBB);
13483 exitMBB->splice(exitMBB->begin(), BB,
13484 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13486
13487 const TargetRegisterClass *RC =
13488 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13489 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
13490
13491 Register PtrReg = RegInfo.createVirtualRegister(RC);
13492 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
13493 Register ShiftReg =
13494 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
13495 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
13496 Register MaskReg = RegInfo.createVirtualRegister(GPRC);
13497 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
13498 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
13499 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
13500 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
13501 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
13502 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
13503 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
13504 Register Ptr1Reg;
13505 Register TmpReg =
13506 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
13507
13508 // thisMBB:
13509 // ...
13510 // fallthrough --> loopMBB
13511 BB->addSuccessor(loopMBB);
13512
13513 // The 4-byte load must be aligned, while a char or short may be
13514 // anywhere in the word. Hence all this nasty bookkeeping code.
13515 // add ptr1, ptrA, ptrB [copy if ptrA==0]
13516 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
13517 // xori shift, shift1, 24 [16]
13518 // rlwinm ptr, ptr1, 0, 0, 29
13519 // slw incr2, incr, shift
13520 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
13521 // slw mask, mask2, shift
13522 // loopMBB:
13523 // lwarx tmpDest, ptr
13524 // add tmp, tmpDest, incr2
13525 // andc tmp2, tmpDest, mask
13526 // and tmp3, tmp, mask
13527 // or tmp4, tmp3, tmp2
13528 // stwcx. tmp4, ptr
13529 // bne- loopMBB
13530 // fallthrough --> exitMBB
13531 // srw SrwDest, tmpDest, shift
13532 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
13533 if (ptrA != ZeroReg) {
13534 Ptr1Reg = RegInfo.createVirtualRegister(RC);
13535 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
13536 .addReg(ptrA)
13537 .addReg(ptrB);
13538 } else {
13539 Ptr1Reg = ptrB;
13540 }
13541 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
13542 // mode.
13543 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
13544 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
13545 .addImm(3)
13546 .addImm(27)
13547 .addImm(is8bit ? 28 : 27);
13548 if (!isLittleEndian)
13549 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
13550 .addReg(Shift1Reg)
13551 .addImm(is8bit ? 24 : 16);
13552 if (is64bit)
13553 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
13554 .addReg(Ptr1Reg)
13555 .addImm(0)
13556 .addImm(61);
13557 else
13558 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
13559 .addReg(Ptr1Reg)
13560 .addImm(0)
13561 .addImm(0)
13562 .addImm(29);
13563 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
13564 if (is8bit)
13565 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
13566 else {
13567 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
13568 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
13569 .addReg(Mask3Reg)
13570 .addImm(65535);
13571 }
13572 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
13573 .addReg(Mask2Reg)
13574 .addReg(ShiftReg);
13575
13576 BB = loopMBB;
13577 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
13578 .addReg(ZeroReg)
13579 .addReg(PtrReg);
13580 if (BinOpcode)
13581 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
13582 .addReg(Incr2Reg)
13583 .addReg(TmpDestReg);
13584 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
13585 .addReg(TmpDestReg)
13586 .addReg(MaskReg);
13587 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
13588 if (CmpOpcode) {
13589 // For unsigned comparisons, we can directly compare the shifted values.
13590 // For signed comparisons we shift and sign extend.
13591 Register SReg = RegInfo.createVirtualRegister(GPRC);
13592 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13593 BuildMI(BB, dl, TII->get(PPC::AND), SReg)
13594 .addReg(TmpDestReg)
13595 .addReg(MaskReg);
13596 unsigned ValueReg = SReg;
13597 unsigned CmpReg = Incr2Reg;
13598 if (CmpOpcode == PPC::CMPW) {
13599 ValueReg = RegInfo.createVirtualRegister(GPRC);
13600 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
13601 .addReg(SReg)
13602 .addReg(ShiftReg);
13603 Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
13604 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
13605 .addReg(ValueReg);
13606 ValueReg = ValueSReg;
13607 CmpReg = incr;
13608 }
13609 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg);
13610 BuildMI(BB, dl, TII->get(PPC::BCC))
13611 .addImm(CmpPred)
13612 .addReg(CrReg)
13613 .addMBB(exitMBB);
13614 BB->addSuccessor(loop2MBB);
13615 BB->addSuccessor(exitMBB);
13616 BB = loop2MBB;
13617 }
13618 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
13619 BuildMI(BB, dl, TII->get(PPC::STWCX))
13620 .addReg(Tmp4Reg)
13621 .addReg(ZeroReg)
13622 .addReg(PtrReg);
13623 BuildMI(BB, dl, TII->get(PPC::BCC))
13625 .addReg(PPC::CR0)
13626 .addMBB(loopMBB);
13627 BB->addSuccessor(loopMBB);
13628 BB->addSuccessor(exitMBB);
13629
13630 // exitMBB:
13631 // ...
13632 BB = exitMBB;
13633 // Since the shift amount is not a constant, we need to clear
13634 // the upper bits with a separate RLWINM.
13635 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
13636 .addReg(SrwDestReg)
13637 .addImm(0)
13638 .addImm(is8bit ? 24 : 16)
13639 .addImm(31);
13640 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
13641 .addReg(TmpDestReg)
13642 .addReg(ShiftReg);
13643 return BB;
13644}
13645
13648 MachineBasicBlock *MBB) const {
13649 DebugLoc DL = MI.getDebugLoc();
13650 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13651 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13652
13653 MachineFunction *MF = MBB->getParent();
13654 MachineRegisterInfo &MRI = MF->getRegInfo();
13655
13656 const BasicBlock *BB = MBB->getBasicBlock();
13657 MachineFunction::iterator I = ++MBB->getIterator();
13658
13659 Register DstReg = MI.getOperand(0).getReg();
13660 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13661 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
13662 Register mainDstReg = MRI.createVirtualRegister(RC);
13663 Register restoreDstReg = MRI.createVirtualRegister(RC);
13664
13665 MVT PVT = getPointerTy(MF->getDataLayout());
13666 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13667 "Invalid Pointer Size!");
13668 // For v = setjmp(buf), we generate
13669 //
13670 // thisMBB:
13671 // SjLjSetup mainMBB
13672 // bl mainMBB
13673 // v_restore = 1
13674 // b sinkMBB
13675 //
13676 // mainMBB:
13677 // buf[LabelOffset] = LR
13678 // v_main = 0
13679 //
13680 // sinkMBB:
13681 // v = phi(main, restore)
13682 //
13683
13684 MachineBasicBlock *thisMBB = MBB;
13685 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13686 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13687 MF->insert(I, mainMBB);
13688 MF->insert(I, sinkMBB);
13689
13691
13692 // Transfer the remainder of BB and its successor edges to sinkMBB.
13693 sinkMBB->splice(sinkMBB->begin(), MBB,
13694 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
13696
13697 // Note that the structure of the jmp_buf used here is not compatible
13698 // with that used by libc, and is not designed to be. Specifically, it
13699 // stores only those 'reserved' registers that LLVM does not otherwise
13700 // understand how to spill. Also, by convention, by the time this
13701 // intrinsic is called, Clang has already stored the frame address in the
13702 // first slot of the buffer and stack address in the third. Following the
13703 // X86 target code, we'll store the jump address in the second slot. We also
13704 // need to save the TOC pointer (R2) to handle jumps between shared
13705 // libraries, and that will be stored in the fourth slot. The thread
13706 // identifier (R13) is not affected.
13707
13708 // thisMBB:
13709 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13710 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13711 const int64_t BPOffset = 4 * PVT.getStoreSize();
13712
13713 // Prepare IP either in reg.
13714 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13715 Register LabelReg = MRI.createVirtualRegister(PtrRC);
13716 Register BufReg = MI.getOperand(1).getReg();
13717
13718 if (Subtarget.is64BitELFABI()) {
13719 setUsesTOCBasePtr(*MBB->getParent());
13720 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
13721 .addReg(PPC::X2)
13722 .addImm(TOCOffset)
13723 .addReg(BufReg)
13724 .cloneMemRefs(MI);
13725 }
13726
13727 // Naked functions never have a base pointer, and so we use r1. For all
13728 // other functions, this decision must be delayed until during PEI.
13729 unsigned BaseReg;
13730 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
13731 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
13732 else
13733 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
13734
13735 MIB = BuildMI(*thisMBB, MI, DL,
13736 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
13737 .addReg(BaseReg)
13738 .addImm(BPOffset)
13739 .addReg(BufReg)
13740 .cloneMemRefs(MI);
13741
13742 // Setup
13743 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
13744 MIB.addRegMask(TRI->getNoPreservedMask());
13745
13746 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
13747
13748 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
13749 .addMBB(mainMBB);
13750 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
13751
13752 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
13753 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
13754
13755 // mainMBB:
13756 // mainDstReg = 0
13757 MIB =
13758 BuildMI(mainMBB, DL,
13759 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
13760
13761 // Store IP
13762 if (Subtarget.isPPC64()) {
13763 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
13764 .addReg(LabelReg)
13765 .addImm(LabelOffset)
13766 .addReg(BufReg);
13767 } else {
13768 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
13769 .addReg(LabelReg)
13770 .addImm(LabelOffset)
13771 .addReg(BufReg);
13772 }
13773 MIB.cloneMemRefs(MI);
13774
13775 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
13776 mainMBB->addSuccessor(sinkMBB);
13777
13778 // sinkMBB:
13779 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13780 TII->get(PPC::PHI), DstReg)
13781 .addReg(mainDstReg).addMBB(mainMBB)
13782 .addReg(restoreDstReg).addMBB(thisMBB);
13783
13784 MI.eraseFromParent();
13785 return sinkMBB;
13786}
13787
13790 MachineBasicBlock *MBB) const {
13791 DebugLoc DL = MI.getDebugLoc();
13792 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13793
13794 MachineFunction *MF = MBB->getParent();
13795 MachineRegisterInfo &MRI = MF->getRegInfo();
13796
13797 MVT PVT = getPointerTy(MF->getDataLayout());
13798 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13799 "Invalid Pointer Size!");
13800
13801 const TargetRegisterClass *RC =
13802 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13803 Register Tmp = MRI.createVirtualRegister(RC);
13804 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13805 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
13806 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
13807 unsigned BP =
13808 (PVT == MVT::i64)
13809 ? PPC::X30
13810 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
13811 : PPC::R30);
13812
13814
13815 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13816 const int64_t SPOffset = 2 * PVT.getStoreSize();
13817 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13818 const int64_t BPOffset = 4 * PVT.getStoreSize();
13819
13820 Register BufReg = MI.getOperand(0).getReg();
13821
13822 // Reload FP (the jumped-to function may not have had a
13823 // frame pointer, and if so, then its r31 will be restored
13824 // as necessary).
13825 if (PVT == MVT::i64) {
13826 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
13827 .addImm(0)
13828 .addReg(BufReg);
13829 } else {
13830 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
13831 .addImm(0)
13832 .addReg(BufReg);
13833 }
13834 MIB.cloneMemRefs(MI);
13835
13836 // Reload IP
13837 if (PVT == MVT::i64) {
13838 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
13839 .addImm(LabelOffset)
13840 .addReg(BufReg);
13841 } else {
13842 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
13843 .addImm(LabelOffset)
13844 .addReg(BufReg);
13845 }
13846 MIB.cloneMemRefs(MI);
13847
13848 // Reload SP
13849 if (PVT == MVT::i64) {
13850 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
13851 .addImm(SPOffset)
13852 .addReg(BufReg);
13853 } else {
13854 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
13855 .addImm(SPOffset)
13856 .addReg(BufReg);
13857 }
13858 MIB.cloneMemRefs(MI);
13859
13860 // Reload BP
13861 if (PVT == MVT::i64) {
13862 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
13863 .addImm(BPOffset)
13864 .addReg(BufReg);
13865 } else {
13866 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
13867 .addImm(BPOffset)
13868 .addReg(BufReg);
13869 }
13870 MIB.cloneMemRefs(MI);
13871
13872 // Reload TOC
13873 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
13874 setUsesTOCBasePtr(*MBB->getParent());
13875 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
13876 .addImm(TOCOffset)
13877 .addReg(BufReg)
13878 .cloneMemRefs(MI);
13879 }
13880
13881 // Jump
13882 BuildMI(*MBB, MI, DL,
13883 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
13884 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
13885
13886 MI.eraseFromParent();
13887 return MBB;
13888}
13889
13891 // If the function specifically requests inline stack probes, emit them.
13892 if (MF.getFunction().hasFnAttribute("probe-stack"))
13893 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
13894 "inline-asm";
13895 return false;
13896}
13897
13899 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
13900 unsigned StackAlign = TFI->getStackAlignment();
13901 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
13902 "Unexpected stack alignment");
13903 // The default stack probe size is 4096 if the function has no
13904 // stack-probe-size attribute.
13905 const Function &Fn = MF.getFunction();
13906 unsigned StackProbeSize =
13907 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
13908 // Round down to the stack alignment.
13909 StackProbeSize &= ~(StackAlign - 1);
13910 return StackProbeSize ? StackProbeSize : StackAlign;
13911}
13912
13913// Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
13914// into three phases. In the first phase, it uses pseudo instruction
13915// PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
13916// FinalStackPtr. In the second phase, it generates a loop for probing blocks.
13917// At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
13918// MaxCallFrameSize so that it can calculate correct data area pointer.
13921 MachineBasicBlock *MBB) const {
13922 const bool isPPC64 = Subtarget.isPPC64();
13923 MachineFunction *MF = MBB->getParent();
13924 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13925 DebugLoc DL = MI.getDebugLoc();
13926 const unsigned ProbeSize = getStackProbeSize(*MF);
13927 const BasicBlock *ProbedBB = MBB->getBasicBlock();
13928 MachineRegisterInfo &MRI = MF->getRegInfo();
13929 // The CFG of probing stack looks as
13930 // +-----+
13931 // | MBB |
13932 // +--+--+
13933 // |
13934 // +----v----+
13935 // +--->+ TestMBB +---+
13936 // | +----+----+ |
13937 // | | |
13938 // | +-----v----+ |
13939 // +---+ BlockMBB | |
13940 // +----------+ |
13941 // |
13942 // +---------+ |
13943 // | TailMBB +<--+
13944 // +---------+
13945 // In MBB, calculate previous frame pointer and final stack pointer.
13946 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
13947 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
13948 // TailMBB is spliced via \p MI.
13949 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
13950 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
13951 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
13952
13953 MachineFunction::iterator MBBIter = ++MBB->getIterator();
13954 MF->insert(MBBIter, TestMBB);
13955 MF->insert(MBBIter, BlockMBB);
13956 MF->insert(MBBIter, TailMBB);
13957
13958 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
13959 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
13960
13961 Register DstReg = MI.getOperand(0).getReg();
13962 Register NegSizeReg = MI.getOperand(1).getReg();
13963 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
13964 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13965 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13966 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13967
13968 // Since value of NegSizeReg might be realigned in prologepilog, insert a
13969 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
13970 // NegSize.
13971 unsigned ProbeOpc;
13972 if (!MRI.hasOneNonDBGUse(NegSizeReg))
13973 ProbeOpc =
13974 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
13975 else
13976 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
13977 // and NegSizeReg will be allocated in the same phyreg to avoid
13978 // redundant copy when NegSizeReg has only one use which is current MI and
13979 // will be replaced by PREPARE_PROBED_ALLOCA then.
13980 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
13981 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
13982 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
13983 .addDef(ActualNegSizeReg)
13984 .addReg(NegSizeReg)
13985 .add(MI.getOperand(2))
13986 .add(MI.getOperand(3));
13987
13988 // Calculate final stack pointer, which equals to SP + ActualNegSize.
13989 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
13990 FinalStackPtr)
13991 .addReg(SPReg)
13992 .addReg(ActualNegSizeReg);
13993
13994 // Materialize a scratch register for update.
13995 int64_t NegProbeSize = -(int64_t)ProbeSize;
13996 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
13997 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
13998 if (!isInt<16>(NegProbeSize)) {
13999 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14000 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
14001 .addImm(NegProbeSize >> 16);
14002 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
14003 ScratchReg)
14004 .addReg(TempReg)
14005 .addImm(NegProbeSize & 0xFFFF);
14006 } else
14007 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
14008 .addImm(NegProbeSize);
14009
14010 {
14011 // Probing leading residual part.
14012 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14013 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
14014 .addReg(ActualNegSizeReg)
14015 .addReg(ScratchReg);
14016 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14017 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
14018 .addReg(Div)
14019 .addReg(ScratchReg);
14020 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14021 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
14022 .addReg(Mul)
14023 .addReg(ActualNegSizeReg);
14024 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14025 .addReg(FramePointer)
14026 .addReg(SPReg)
14027 .addReg(NegMod);
14028 }
14029
14030 {
14031 // Remaining part should be multiple of ProbeSize.
14032 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
14033 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
14034 .addReg(SPReg)
14035 .addReg(FinalStackPtr);
14036 BuildMI(TestMBB, DL, TII->get(PPC::BCC))
14038 .addReg(CmpResult)
14039 .addMBB(TailMBB);
14040 TestMBB->addSuccessor(BlockMBB);
14041 TestMBB->addSuccessor(TailMBB);
14042 }
14043
14044 {
14045 // Touch the block.
14046 // |P...|P...|P...
14047 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14048 .addReg(FramePointer)
14049 .addReg(SPReg)
14050 .addReg(ScratchReg);
14051 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
14052 BlockMBB->addSuccessor(TestMBB);
14053 }
14054
14055 // Calculation of MaxCallFrameSize is deferred to prologepilog, use
14056 // DYNAREAOFFSET pseudo instruction to get the future result.
14057 Register MaxCallFrameSizeReg =
14058 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14059 BuildMI(TailMBB, DL,
14060 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
14061 MaxCallFrameSizeReg)
14062 .add(MI.getOperand(2))
14063 .add(MI.getOperand(3));
14064 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
14065 .addReg(SPReg)
14066 .addReg(MaxCallFrameSizeReg);
14067
14068 // Splice instructions after MI to TailMBB.
14069 TailMBB->splice(TailMBB->end(), MBB,
14070 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14072 MBB->addSuccessor(TestMBB);
14073
14074 // Delete the pseudo instruction.
14075 MI.eraseFromParent();
14076
14077 ++NumDynamicAllocaProbed;
14078 return TailMBB;
14079}
14080
14081/// Check if the opcode is a SELECT or SELECT_CC variant.
14082/// @param Opcode The opcode to check
14083/// @param CheckOnlyCC If true, only return true for SELECT_CC variants;
14084/// if false, return true for both SELECT and SELECT_CC
14085static bool IsSelect(unsigned Opcode, bool CheckOnlyCC = false) {
14086 switch (Opcode) {
14087 // SELECT_CC variants - always return true
14088 case PPC::SELECT_CC_I4:
14089 case PPC::SELECT_CC_I8:
14090 case PPC::SELECT_CC_F4:
14091 case PPC::SELECT_CC_F8:
14092 case PPC::SELECT_CC_F16:
14093 case PPC::SELECT_CC_VRRC:
14094 case PPC::SELECT_CC_VSFRC:
14095 case PPC::SELECT_CC_VSSRC:
14096 case PPC::SELECT_CC_VSRC:
14097 case PPC::SELECT_CC_SPE4:
14098 case PPC::SELECT_CC_SPE:
14099 return true;
14100 // SELECT variants - only return true if CheckOnlyCC is false
14101 case PPC::SELECT_I4:
14102 case PPC::SELECT_I8:
14103 case PPC::SELECT_F4:
14104 case PPC::SELECT_F8:
14105 case PPC::SELECT_F16:
14106 case PPC::SELECT_SPE:
14107 case PPC::SELECT_SPE4:
14108 case PPC::SELECT_VRRC:
14109 case PPC::SELECT_VSFRC:
14110 case PPC::SELECT_VSSRC:
14111 case PPC::SELECT_VSRC:
14112 return !CheckOnlyCC; // true if checking all SELECTs, false if only CC
14113 default:
14114 return false;
14115 }
14116}
14117static bool IsSelectCC(unsigned Opcode) { return IsSelect(Opcode, true); }
14118
14119/// Emit SELECT instruction, using ISEL if available, otherwise use
14120/// branch-based control flow.
14121///
14122/// For targets with ISEL support (SELECT_CC_I4/I8, SELECT_I4/I8), this
14123/// generates a single ISEL instruction. Otherwise, it creates a
14124/// branch-based control flow pattern with PHI nodes.
14126 const TargetInstrInfo *TII,
14127 const PPCSubtarget &Subtarget) {
14128 assert(IsSelect(MI.getOpcode()) && "Instruction must be a SELECT variant");
14129
14130 // Check if we can use ISEL for this SELECT
14131 if (Subtarget.hasISEL() &&
14132 (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14133 MI.getOpcode() == PPC::SELECT_CC_I8 ||
14134 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
14136 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14137 MI.getOpcode() == PPC::SELECT_CC_I8)
14138 Cond.push_back(MI.getOperand(4));
14139 else
14141 Cond.push_back(MI.getOperand(1));
14142
14143 DebugLoc dl = MI.getDebugLoc();
14144 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
14145 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
14146 MI.eraseFromParent();
14147 return BB;
14148 }
14149
14150 // Fall back to branch-based SELECT implementation
14151 MachineFunction *F = BB->getParent();
14152 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14154 DebugLoc dl = MI.getDebugLoc();
14155
14156 MachineBasicBlock *thisMBB = BB;
14157 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14158 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14159 F->insert(It, copy0MBB);
14160 F->insert(It, sinkMBB);
14161
14162 if (isPhysRegUsedAfter(PPC::CARRY, MI.getIterator())) {
14163 copy0MBB->addLiveIn(PPC::CARRY);
14164 sinkMBB->addLiveIn(PPC::CARRY);
14165 }
14166
14167 // Set the call frame size on entry to the new basic blocks.
14168 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
14169 copy0MBB->setCallFrameSize(CallFrameSize);
14170 sinkMBB->setCallFrameSize(CallFrameSize);
14171
14172 // Transfer the remainder of BB and its successor edges to sinkMBB.
14173 sinkMBB->splice(sinkMBB->begin(), BB,
14174 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14176
14177 // Add successors
14178 BB->addSuccessor(copy0MBB);
14179 BB->addSuccessor(sinkMBB);
14180
14181 // Build branch instruction
14182 if (IsSelectCC(MI.getOpcode()))
14183 BuildMI(BB, dl, TII->get(PPC::BCC))
14184 .addImm(MI.getOperand(4).getImm())
14185 .addReg(MI.getOperand(1).getReg())
14186 .addMBB(sinkMBB);
14187 else
14188 BuildMI(BB, dl, TII->get(PPC::BC))
14189 .addReg(MI.getOperand(1).getReg())
14190 .addMBB(sinkMBB);
14191
14192 // copy0MBB: fallthrough to sinkMBB
14193 BB = copy0MBB;
14194 BB->addSuccessor(sinkMBB);
14195
14196 // sinkMBB: PHI instruction
14197 BB = sinkMBB;
14198 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
14199 .addReg(MI.getOperand(3).getReg())
14200 .addMBB(copy0MBB)
14201 .addReg(MI.getOperand(2).getReg())
14202 .addMBB(thisMBB);
14203 MI.eraseFromParent();
14204 return BB;
14205}
14206
14207/// Helper function to create basic blocks for atomic compare-and-swap.
14208/// Creates three basic blocks (loop1MBB, loop2MBB, exitMBB) and sets up
14209/// the control flow structure common to both hardware and software
14210/// implementations of atomic compare-and-swap operations.
14212 MachineBasicBlock *&loop1MBB,
14213 MachineBasicBlock *&loop2MBB,
14214 MachineBasicBlock *&exitMBB,
14217 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14218 loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
14219 loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
14220 exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
14221 F->insert(It, loop1MBB);
14222 F->insert(It, loop2MBB);
14223 F->insert(It, exitMBB);
14224 exitMBB->splice(exitMBB->begin(), BB,
14225 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14227 BB->addSuccessor(loop1MBB);
14228}
14229
14230/// Emit hardware-supported atomic compare-and-swap for I32/I64 and I8/I16
14231/// with partword atomic support.
14232///
14233/// This uses native PowerPC atomic instructions (LBARX/LHARX/LWARX/LDARX for
14234/// load-and-reserve, STBCX/STHCX/STWCX/STDCX for store-conditional) to
14235/// implement atomic compare-and-swap at byte, halfword, word, or doubleword
14236/// granularity.
14237///
14238/// Control flow:
14239/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14240/// | |
14241/// +------------+
14242///
14243/// loop1MBB:
14244/// - Load-and-reserve from memory
14245/// - Compare loaded value with expected old value
14246/// - Branch to exitMBB if not equal (CAS failed)
14247/// loop2MBB:
14248/// - Store-conditional new value to memory
14249/// - Branch back to loop1MBB if store failed (retry)
14250/// - Fall through to exitMBB on success
14251static MachineBasicBlock *
14253 const TargetInstrInfo *TII,
14254 const PPCSubtarget &Subtarget) {
14255 MachineFunction *F = BB->getParent();
14257
14258 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
14259
14260 unsigned LoadMnemonic = PPC::LDARX;
14261 unsigned StoreMnemonic = PPC::STDCX;
14262 switch (MI.getOpcode()) {
14263 default:
14264 llvm_unreachable("Compare and swap of unknown size");
14265 case PPC::ATOMIC_CMP_SWAP_I8:
14266 LoadMnemonic = PPC::LBARX;
14267 StoreMnemonic = PPC::STBCX;
14268 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14269 break;
14270 case PPC::ATOMIC_CMP_SWAP_I16:
14271 LoadMnemonic = PPC::LHARX;
14272 StoreMnemonic = PPC::STHCX;
14273 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14274 break;
14275 case PPC::ATOMIC_CMP_SWAP_I32:
14276 LoadMnemonic = PPC::LWARX;
14277 StoreMnemonic = PPC::STWCX;
14278 break;
14279 case PPC::ATOMIC_CMP_SWAP_I64:
14280 LoadMnemonic = PPC::LDARX;
14281 StoreMnemonic = PPC::STDCX;
14282 break;
14283 }
14284
14285 MachineRegisterInfo &RegInfo = F->getRegInfo();
14286 Register dest = MI.getOperand(0).getReg();
14287 Register ptrA = MI.getOperand(1).getReg();
14288 Register ptrB = MI.getOperand(2).getReg();
14289 Register oldval = MI.getOperand(3).getReg();
14290 Register newval = MI.getOperand(4).getReg();
14291 DebugLoc dl = MI.getDebugLoc();
14292
14293 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14294 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14295
14296 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14297
14298 // loop1MBB:
14299 // l[bhwd]arx dest, ptr
14300 // cmp[wd] dest, oldval
14301 // bne- exitBB
14302 BB = loop1MBB;
14303 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
14304 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg)
14305 .addReg(dest)
14306 .addReg(oldval);
14307 BuildMI(BB, dl, TII->get(PPC::BCC))
14309 .addReg(CrReg)
14310 .addMBB(exitMBB);
14311 BB->addSuccessor(loop2MBB);
14312 BB->addSuccessor(exitMBB);
14313
14314 // loop2MBB:
14315 // st[bhwd]cx. newval, ptr
14316 // bne- loopMBB
14317 // b exitBB
14318 BB = loop2MBB;
14319 BuildMI(BB, dl, TII->get(StoreMnemonic))
14320 .addReg(newval)
14321 .addReg(ptrA)
14322 .addReg(ptrB);
14323 BuildMI(BB, dl, TII->get(PPC::BCC))
14325 .addReg(PPC::CR0)
14326 .addMBB(loop1MBB);
14327 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14328 BB->addSuccessor(loop1MBB);
14329 BB->addSuccessor(exitMBB);
14330
14331 return exitMBB;
14332}
14333
14334/// Emit software-emulated atomic compare-and-swap for I8/I16 without
14335/// hardware partword atomic support.
14336///
14337/// This emulates byte/halfword atomic operations using word (32-bit) atomic
14338/// instructions. Since PowerPC atomic instructions work at word granularity,
14339/// we must:
14340/// 1. Align the pointer to a word boundary
14341/// 2. Calculate the bit shift for the target byte/halfword within the word
14342/// 3. Create masks to isolate the target byte/halfword
14343/// 4. Shift old/new values into the correct bit position
14344/// 5. Use LWARX/STWCX on the full word
14345/// 6. Mask and merge to preserve other bytes in the word
14346/// 7. Extract and shift the result back
14347///
14348/// Control flow:
14349/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14350/// | |
14351/// +------------+
14352///
14353/// loop1MBB:
14354/// - LWARX: Load-and-reserve full word
14355/// - Mask to extract target byte/halfword
14356/// - Compare with expected old value
14357/// - Branch to exitMBB if not equal (CAS failed)
14358/// loop2MBB:
14359/// - Merge new value with other bytes in the word
14360/// - STWCX: Store-conditional full word
14361/// - Branch back to loop1MBB if store failed (retry)
14362/// - Fall through to exitMBB on success
14363/// exitMBB:
14364/// - Extract and return the loaded value
14365static MachineBasicBlock *
14367 const TargetInstrInfo *TII,
14368 const PPCSubtarget &Subtarget) {
14369 MachineFunction *F = BB->getParent();
14371
14372 bool is64bit = Subtarget.isPPC64();
14373 bool isLittleEndian = Subtarget.isLittleEndian();
14374 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
14375
14376 Register dest = MI.getOperand(0).getReg();
14377 Register ptrA = MI.getOperand(1).getReg();
14378 Register ptrB = MI.getOperand(2).getReg();
14379 Register oldval = MI.getOperand(3).getReg();
14380 Register newval = MI.getOperand(4).getReg();
14381 DebugLoc dl = MI.getDebugLoc();
14382
14383 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14384 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14385
14386 MachineRegisterInfo &RegInfo = F->getRegInfo();
14387 const TargetRegisterClass *RC =
14388 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
14389 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
14390
14391 // Lambda to create virtual registers
14392 auto createVReg = [&](const TargetRegisterClass *RC) {
14393 return RegInfo.createVirtualRegister(RC);
14394 };
14395
14396 Register PtrReg = createVReg(RC);
14397 Register Shift1Reg = createVReg(GPRC);
14398 Register ShiftReg = isLittleEndian ? Shift1Reg : createVReg(GPRC);
14399 Register NewVal2Reg = createVReg(GPRC);
14400 Register NewVal3Reg = createVReg(GPRC);
14401 Register OldVal2Reg = createVReg(GPRC);
14402 Register OldVal3Reg = createVReg(GPRC);
14403 Register MaskReg = createVReg(GPRC);
14404 Register Mask2Reg = createVReg(GPRC);
14405 Register Mask3Reg = createVReg(GPRC);
14406 Register Tmp2Reg = createVReg(GPRC);
14407 Register Tmp4Reg = createVReg(GPRC);
14408 Register TmpDestReg = createVReg(GPRC);
14409 Register TmpReg = createVReg(GPRC);
14410 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
14411 Register CrReg = createVReg(&PPC::CRRCRegClass);
14412
14413 // Compute aligned pointer and shift amount
14414 Register Ptr1Reg;
14415 if (ptrA != ZeroReg) {
14416 Ptr1Reg = createVReg(RC);
14417 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
14418 .addReg(ptrA)
14419 .addReg(ptrB);
14420 } else {
14421 Ptr1Reg = ptrB;
14422 }
14423
14424 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
14425 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
14426 .addImm(3)
14427 .addImm(27)
14428 .addImm(is8bit ? 28 : 27);
14429 if (!isLittleEndian)
14430 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
14431 .addReg(Shift1Reg)
14432 .addImm(is8bit ? 24 : 16);
14433 if (is64bit)
14434 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
14435 .addReg(Ptr1Reg)
14436 .addImm(0)
14437 .addImm(61);
14438 else
14439 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
14440 .addReg(Ptr1Reg)
14441 .addImm(0)
14442 .addImm(0)
14443 .addImm(29);
14444
14445 // Prepare masked values
14446 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
14447 .addReg(newval)
14448 .addReg(ShiftReg);
14449 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
14450 .addReg(oldval)
14451 .addReg(ShiftReg);
14452 if (is8bit)
14453 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
14454 else {
14455 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
14456 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
14457 .addReg(Mask3Reg)
14458 .addImm(65535);
14459 }
14460 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
14461 .addReg(Mask2Reg)
14462 .addReg(ShiftReg);
14463 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
14464 .addReg(NewVal2Reg)
14465 .addReg(MaskReg);
14466 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
14467 .addReg(OldVal2Reg)
14468 .addReg(MaskReg);
14469
14470 // loop1MBB:
14471 // lwarx tmpDest, ptr
14472 // and tmp, tmpDest, mask
14473 // cmpw tmp, oldval3
14474 // bne- exitBB
14475 BB = loop1MBB;
14476 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
14477 .addReg(ZeroReg)
14478 .addReg(PtrReg);
14479 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
14480 .addReg(TmpDestReg)
14481 .addReg(MaskReg);
14482 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg).addReg(TmpReg).addReg(OldVal3Reg);
14483 BuildMI(BB, dl, TII->get(PPC::BCC))
14485 .addReg(CrReg)
14486 .addMBB(exitMBB);
14487 BB->addSuccessor(loop2MBB);
14488 BB->addSuccessor(exitMBB);
14489
14490 // loop2MBB:
14491 // andc tmp2, tmpDest, mask
14492 // or tmp4, tmp2, newval3
14493 // stwcx. tmp4, ptr
14494 // bne- loop1MBB
14495 // b exitBB
14496 BB = loop2MBB;
14497 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
14498 .addReg(TmpDestReg)
14499 .addReg(MaskReg);
14500 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
14501 .addReg(Tmp2Reg)
14502 .addReg(NewVal3Reg);
14503 BuildMI(BB, dl, TII->get(PPC::STWCX))
14504 .addReg(Tmp4Reg)
14505 .addReg(ZeroReg)
14506 .addReg(PtrReg);
14507 BuildMI(BB, dl, TII->get(PPC::BCC))
14509 .addReg(PPC::CR0)
14510 .addMBB(loop1MBB);
14511 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14512 BB->addSuccessor(loop1MBB);
14513 BB->addSuccessor(exitMBB);
14514
14515 // exitMBB:
14516 // srw dest, tmpDest, shift
14517 BB = exitMBB;
14518 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
14519 .addReg(TmpReg)
14520 .addReg(ShiftReg);
14521
14522 return BB;
14523}
14524
14527 MachineBasicBlock *BB) const {
14528 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14529
14530 // To "insert" these instructions we actually have to insert their
14531 // control-flow patterns.
14532 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14534
14535 MachineFunction *F = BB->getParent();
14536 MachineRegisterInfo &MRI = F->getRegInfo();
14537
14538 // Handle SELECT with ISEL support first (before generic SELECT handling)
14539 if (IsSelect(MI.getOpcode()))
14540 return emitSelect(MI, BB, TII, Subtarget);
14541
14542 switch (MI.getOpcode()) {
14543 case TargetOpcode::STACKMAP:
14544 return emitPatchPoint(MI, BB);
14545 case TargetOpcode::PATCHPOINT:
14546 // Call lowering should have added an r2 operand to indicate a dependence
14547 // on the TOC base pointer value. It can't however, because there is no
14548 // way to mark the dependence as implicit there, and so the stackmap code
14549 // will confuse it with a regular operand. Instead, add the dependence
14550 // here.
14551 if (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls())
14552 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
14553 return emitPatchPoint(MI, BB);
14554
14555 case PPC::EH_SjLj_SetJmp32:
14556 case PPC::EH_SjLj_SetJmp64:
14557 return emitEHSjLjSetJmp(MI, BB);
14558
14559 case PPC::EH_SjLj_LongJmp32:
14560 case PPC::EH_SjLj_LongJmp64:
14561 return emitEHSjLjLongJmp(MI, BB);
14562
14563 case PPC::ReadTB: {
14564 // To read the 64-bit time-base register on a 32-bit target, we read the
14565 // two halves. Should the counter have wrapped while it was being read, we
14566 // need to try again.
14567 // ...
14568 // readLoop:
14569 // mfspr Rx,TBU # load from TBU
14570 // mfspr Ry,TB # load from TB
14571 // mfspr Rz,TBU # load from TBU
14572 // cmpw crX,Rx,Rz # check if 'old'='new'
14573 // bne readLoop # branch if they're not equal
14574 // ...
14575
14576 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
14577 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14578 DebugLoc dl = MI.getDebugLoc();
14579 F->insert(It, readMBB);
14580 F->insert(It, sinkMBB);
14581
14582 // Transfer the remainder of BB and its successor edges to sinkMBB.
14583 sinkMBB->splice(sinkMBB->begin(), BB,
14584 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14586
14587 BB->addSuccessor(readMBB);
14588 BB = readMBB;
14589
14590 MachineRegisterInfo &RegInfo = F->getRegInfo();
14591 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
14592 Register LoReg = MI.getOperand(0).getReg();
14593 Register HiReg = MI.getOperand(1).getReg();
14594
14595 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
14596 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
14597 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
14598
14599 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14600
14601 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
14602 .addReg(HiReg)
14603 .addReg(ReadAgainReg);
14604 BuildMI(BB, dl, TII->get(PPC::BCC))
14606 .addReg(CmpReg)
14607 .addMBB(readMBB);
14608
14609 BB->addSuccessor(readMBB);
14610 BB->addSuccessor(sinkMBB);
14611 break;
14612 }
14613 case PPC::ATOMIC_LOAD_ADD_NOWP:
14614 BB = EmitPartwordAtomicBinary(MI, BB, PPC::ADD4);
14615 break;
14616 case PPC::ATOMIC_LOAD_ADD:
14617 BB = EmitAtomicBinary(MI, BB, PPC::ADD4);
14618 break;
14619 case PPC::ATOMIC_LOAD_ADD_I64:
14620 BB = EmitAtomicBinary(MI, BB, PPC::ADD8);
14621 break;
14622 case PPC::ATOMIC_LOAD_AND_NOWP:
14623 BB = EmitPartwordAtomicBinary(MI, BB, PPC::AND);
14624 break;
14625 case PPC::ATOMIC_LOAD_AND:
14626 BB = EmitAtomicBinary(MI, BB, PPC::AND);
14627 break;
14628 case PPC::ATOMIC_LOAD_AND_I64:
14629 BB = EmitAtomicBinary(MI, BB, PPC::AND8);
14630 break;
14631 case PPC::ATOMIC_LOAD_OR_NOWP:
14632 BB = EmitPartwordAtomicBinary(MI, BB, PPC::OR);
14633 break;
14634 case PPC::ATOMIC_LOAD_OR:
14635 BB = EmitAtomicBinary(MI, BB, PPC::OR);
14636 break;
14637 case PPC::ATOMIC_LOAD_OR_I64:
14638 BB = EmitAtomicBinary(MI, BB, PPC::OR8);
14639 break;
14640 case PPC::ATOMIC_LOAD_XOR_NOWP:
14641 BB = EmitPartwordAtomicBinary(MI, BB, PPC::XOR);
14642 break;
14643 case PPC::ATOMIC_LOAD_XOR:
14644 BB = EmitAtomicBinary(MI, BB, PPC::XOR);
14645 break;
14646 case PPC::ATOMIC_LOAD_XOR_I64:
14647 BB = EmitAtomicBinary(MI, BB, PPC::XOR8);
14648 break;
14649 case PPC::ATOMIC_LOAD_NAND_NOWP:
14650 BB = EmitPartwordAtomicBinary(MI, BB, PPC::NAND);
14651 break;
14652 case PPC::ATOMIC_LOAD_NAND:
14653 BB = EmitAtomicBinary(MI, BB, PPC::NAND);
14654 break;
14655 case PPC::ATOMIC_LOAD_NAND_I64:
14656 BB = EmitAtomicBinary(MI, BB, PPC::NAND8);
14657 break;
14658 case PPC::ATOMIC_LOAD_SUB_NOWP:
14659 BB = EmitPartwordAtomicBinary(MI, BB, PPC::SUBF);
14660 break;
14661 case PPC::ATOMIC_LOAD_SUB:
14662 BB = EmitAtomicBinary(MI, BB, PPC::SUBF);
14663 break;
14664 case PPC::ATOMIC_LOAD_SUB_I64:
14665 BB = EmitAtomicBinary(MI, BB, PPC::SUBF8);
14666 break;
14667 case PPC::ATOMIC_LOAD_MIN_NOWP:
14668 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14669 break;
14670 case PPC::ATOMIC_LOAD_MIN:
14671 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14672 break;
14673 case PPC::ATOMIC_LOAD_MIN_I64:
14674 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_LT);
14675 break;
14676 case PPC::ATOMIC_LOAD_MAX_NOWP:
14677 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14678 break;
14679 case PPC::ATOMIC_LOAD_MAX:
14680 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14681 break;
14682 case PPC::ATOMIC_LOAD_MAX_I64:
14683 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_GT);
14684 break;
14685 case PPC::ATOMIC_LOAD_UMIN_NOWP:
14686 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14687 break;
14688 case PPC::ATOMIC_LOAD_UMIN:
14689 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14690 break;
14691 case PPC::ATOMIC_LOAD_UMIN_I64:
14692 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_LT);
14693 break;
14694 case PPC::ATOMIC_LOAD_UMAX_NOWP:
14695 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14696 break;
14697 case PPC::ATOMIC_LOAD_UMAX:
14698 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14699 break;
14700 case PPC::ATOMIC_LOAD_UMAX_I64:
14701 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_GT);
14702 break;
14703 case PPC::ATOMIC_SWAP_NOWP:
14704 BB = EmitPartwordAtomicBinary(MI, BB, 0);
14705 break;
14706 case PPC::ATOMIC_SWAP:
14707 case PPC::ATOMIC_SWAP_I64:
14708 BB = EmitAtomicBinary(MI, BB, 0);
14709 break;
14710 case PPC::ATOMIC_CMP_SWAP_I32:
14711 case PPC::ATOMIC_CMP_SWAP_I64:
14712 case PPC::ATOMIC_CMP_SWAP_I8:
14713 case PPC::ATOMIC_CMP_SWAP_I16: {
14714 // Use hardware-supported atomic operations if available
14715 bool useHardware = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
14716 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
14717 (Subtarget.hasPartwordAtomics() &&
14718 (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
14719 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16));
14720
14721 if (useHardware)
14722 BB = emitAtomicCmpSwapHardware(MI, BB, TII, Subtarget);
14723 else
14724 BB = emitAtomicCmpSwapSoftware(MI, BB, TII, Subtarget);
14725 break;
14726 }
14727 case PPC::FADDrtz: {
14728 // This pseudo performs an FADD with rounding mode temporarily forced
14729 // to round-to-zero. We emit this via custom inserter since the FPSCR
14730 // is not modeled at the SelectionDAG level.
14731 Register Dest = MI.getOperand(0).getReg();
14732 Register Src1 = MI.getOperand(1).getReg();
14733 Register Src2 = MI.getOperand(2).getReg();
14734 DebugLoc dl = MI.getDebugLoc();
14735
14736 MachineRegisterInfo &RegInfo = F->getRegInfo();
14737 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
14738
14739 // Save FPSCR value.
14740 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
14741
14742 // Set rounding mode to round-to-zero.
14743 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
14744 .addImm(31)
14746
14747 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
14748 .addImm(30)
14750
14751 // Perform addition.
14752 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
14753 .addReg(Src1)
14754 .addReg(Src2);
14755 if (MI.getFlag(MachineInstr::NoFPExcept))
14757
14758 // Restore FPSCR value.
14759 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
14760 break;
14761 }
14762 case PPC::ANDI_rec_1_EQ_BIT:
14763 case PPC::ANDI_rec_1_GT_BIT:
14764 case PPC::ANDI_rec_1_EQ_BIT8:
14765 case PPC::ANDI_rec_1_GT_BIT8: {
14766 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
14767 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
14768 ? PPC::ANDI8_rec
14769 : PPC::ANDI_rec;
14770 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
14771 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
14772
14773 MachineRegisterInfo &RegInfo = F->getRegInfo();
14774 Register Dest = RegInfo.createVirtualRegister(
14775 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
14776
14777 DebugLoc Dl = MI.getDebugLoc();
14778 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
14779 .addReg(MI.getOperand(1).getReg())
14780 .addImm(1);
14781 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14782 MI.getOperand(0).getReg())
14783 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
14784 break;
14785 }
14786 case PPC::TCHECK_RET: {
14787 DebugLoc Dl = MI.getDebugLoc();
14788 MachineRegisterInfo &RegInfo = F->getRegInfo();
14789 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14790 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
14791 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14792 MI.getOperand(0).getReg())
14793 .addReg(CRReg);
14794 break;
14795 }
14796 case PPC::TBEGIN_RET: {
14797 DebugLoc Dl = MI.getDebugLoc();
14798 unsigned Imm = MI.getOperand(1).getImm();
14799 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
14800 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14801 MI.getOperand(0).getReg())
14802 .addReg(PPC::CR0EQ);
14803 break;
14804 }
14805 case PPC::SETRNDi: {
14806 DebugLoc dl = MI.getDebugLoc();
14807 Register OldFPSCRReg = MI.getOperand(0).getReg();
14808
14809 // Save FPSCR value.
14810 if (MRI.use_empty(OldFPSCRReg))
14811 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
14812 else
14813 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
14814
14815 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
14816 // the following settings:
14817 // 00 Round to nearest
14818 // 01 Round to 0
14819 // 10 Round to +inf
14820 // 11 Round to -inf
14821
14822 // When the operand is immediate, using the two least significant bits of
14823 // the immediate to set the bits 62:63 of FPSCR.
14824 unsigned Mode = MI.getOperand(1).getImm();
14825 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
14826 .addImm(31)
14828
14829 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
14830 .addImm(30)
14832 break;
14833 }
14834 case PPC::SETRND: {
14835 DebugLoc dl = MI.getDebugLoc();
14836
14837 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
14838 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
14839 // If the target doesn't have DirectMove, we should use stack to do the
14840 // conversion, because the target doesn't have the instructions like mtvsrd
14841 // or mfvsrd to do this conversion directly.
14842 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
14843 if (Subtarget.hasDirectMove()) {
14844 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
14845 .addReg(SrcReg);
14846 } else {
14847 // Use stack to do the register copy.
14848 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
14849 MachineRegisterInfo &RegInfo = F->getRegInfo();
14850 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
14851 if (RC == &PPC::F8RCRegClass) {
14852 // Copy register from F8RCRegClass to G8RCRegclass.
14853 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
14854 "Unsupported RegClass.");
14855
14856 StoreOp = PPC::STFD;
14857 LoadOp = PPC::LD;
14858 } else {
14859 // Copy register from G8RCRegClass to F8RCRegclass.
14860 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
14861 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
14862 "Unsupported RegClass.");
14863 }
14864
14865 MachineFrameInfo &MFI = F->getFrameInfo();
14866 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
14867
14868 MachineMemOperand *MMOStore = F->getMachineMemOperand(
14869 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14871 MFI.getObjectAlign(FrameIdx));
14872
14873 // Store the SrcReg into the stack.
14874 BuildMI(*BB, MI, dl, TII->get(StoreOp))
14875 .addReg(SrcReg)
14876 .addImm(0)
14877 .addFrameIndex(FrameIdx)
14878 .addMemOperand(MMOStore);
14879
14880 MachineMemOperand *MMOLoad = F->getMachineMemOperand(
14881 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14883 MFI.getObjectAlign(FrameIdx));
14884
14885 // Load from the stack where SrcReg is stored, and save to DestReg,
14886 // so we have done the RegClass conversion from RegClass::SrcReg to
14887 // RegClass::DestReg.
14888 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
14889 .addImm(0)
14890 .addFrameIndex(FrameIdx)
14891 .addMemOperand(MMOLoad);
14892 }
14893 };
14894
14895 Register OldFPSCRReg = MI.getOperand(0).getReg();
14896
14897 // Save FPSCR value.
14898 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
14899
14900 // When the operand is gprc register, use two least significant bits of the
14901 // register and mtfsf instruction to set the bits 62:63 of FPSCR.
14902 //
14903 // copy OldFPSCRTmpReg, OldFPSCRReg
14904 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
14905 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
14906 // copy NewFPSCRReg, NewFPSCRTmpReg
14907 // mtfsf 255, NewFPSCRReg
14908 MachineOperand SrcOp = MI.getOperand(1);
14909 MachineRegisterInfo &RegInfo = F->getRegInfo();
14910 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14911
14912 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
14913
14914 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14915 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14916
14917 // The first operand of INSERT_SUBREG should be a register which has
14918 // subregisters, we only care about its RegClass, so we should use an
14919 // IMPLICIT_DEF register.
14920 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
14921 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
14922 .addReg(ImDefReg)
14923 .add(SrcOp)
14924 .addImm(PPC::sub_32);
14925
14926 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
14927 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
14928 .addReg(OldFPSCRTmpReg)
14929 .addReg(ExtSrcReg)
14930 .addImm(0)
14931 .addImm(62);
14932
14933 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
14934 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
14935
14936 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
14937 // bits of FPSCR.
14938 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
14939 .addImm(255)
14940 .addReg(NewFPSCRReg)
14941 .addImm(0)
14942 .addImm(0);
14943 break;
14944 }
14945 case PPC::SETFLM: {
14946 DebugLoc Dl = MI.getDebugLoc();
14947
14948 // Result of setflm is previous FPSCR content, so we need to save it first.
14949 Register OldFPSCRReg = MI.getOperand(0).getReg();
14950 if (MRI.use_empty(OldFPSCRReg))
14951 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
14952 else
14953 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
14954
14955 // Put bits in 32:63 to FPSCR.
14956 Register NewFPSCRReg = MI.getOperand(1).getReg();
14957 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
14958 .addImm(255)
14959 .addReg(NewFPSCRReg)
14960 .addImm(0)
14961 .addImm(0);
14962 break;
14963 }
14964 case PPC::PROBED_ALLOCA_32:
14965 case PPC::PROBED_ALLOCA_64:
14966 return emitProbedAlloca(MI, BB);
14967
14968 case PPC::SPLIT_QUADWORD: {
14969 DebugLoc DL = MI.getDebugLoc();
14970 Register Src = MI.getOperand(2).getReg();
14971 Register Lo = MI.getOperand(0).getReg();
14972 Register Hi = MI.getOperand(1).getReg();
14973 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
14974 .addDef(Lo)
14975 .addUse(Src, {}, PPC::sub_gp8_x1);
14976 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
14977 .addDef(Hi)
14978 .addUse(Src, {}, PPC::sub_gp8_x0);
14979 break;
14980 }
14981 case PPC::LQX_PSEUDO:
14982 case PPC::STQX_PSEUDO: {
14983 DebugLoc DL = MI.getDebugLoc();
14984 // Ptr is used as the ptr_rc_no_r0 part
14985 // of LQ/STQ's memory operand and adding result of RA and RB,
14986 // so it has to be g8rc_and_g8rc_nox0.
14987 Register Ptr =
14988 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
14989 Register Val = MI.getOperand(0).getReg();
14990 Register RA = MI.getOperand(1).getReg();
14991 Register RB = MI.getOperand(2).getReg();
14992 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
14993 BuildMI(*BB, MI, DL,
14994 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
14995 : TII->get(PPC::STQ))
14996 .addReg(Val, getDefRegState(MI.getOpcode() == PPC::LQX_PSEUDO))
14997 .addImm(0)
14998 .addReg(Ptr);
14999 break;
15000 }
15001 default:
15002 llvm_unreachable("Unexpected instr type to insert");
15003 }
15004
15005 MI.eraseFromParent(); // The pseudo instruction is gone now.
15006 return BB;
15007}
15008
15009//===----------------------------------------------------------------------===//
15010// Target Optimization Hooks
15011//===----------------------------------------------------------------------===//
15012
15013static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
15014 // For the estimates, convergence is quadratic, so we essentially double the
15015 // number of digits correct after every iteration. For both FRE and FRSQRTE,
15016 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
15017 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
15018 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
15019 if (VT.getScalarType() == MVT::f64)
15020 RefinementSteps++;
15021 return RefinementSteps;
15022}
15023
15024SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
15025 const DenormalMode &Mode,
15026 SDNodeFlags Flags) const {
15027 // We only have VSX Vector Test for software Square Root.
15028 EVT VT = Op.getValueType();
15029 if (!isTypeLegal(MVT::i1) ||
15030 (VT != MVT::f64 &&
15031 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
15032 return TargetLowering::getSqrtInputTest(Op, DAG, Mode, Flags);
15033
15034 SDLoc DL(Op);
15035 // The output register of FTSQRT is CR field.
15036 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op, Flags);
15037 // ftsqrt BF,FRB
15038 // Let e_b be the unbiased exponent of the double-precision
15039 // floating-point operand in register FRB.
15040 // fe_flag is set to 1 if either of the following conditions occurs.
15041 // - The double-precision floating-point operand in register FRB is a zero,
15042 // a NaN, or an infinity, or a negative value.
15043 // - e_b is less than or equal to -970.
15044 // Otherwise fe_flag is set to 0.
15045 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
15046 // not eligible for iteration. (zero/negative/infinity/nan or unbiased
15047 // exponent is less than -970)
15048 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
15049 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
15050 FTSQRT, SRIdxVal),
15051 0);
15052}
15053
15054SDValue
15055PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
15056 SelectionDAG &DAG) const {
15057 // We only have VSX Vector Square Root.
15058 EVT VT = Op.getValueType();
15059 if (VT != MVT::f64 &&
15060 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
15062
15063 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
15064}
15065
15066SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
15067 int Enabled, int &RefinementSteps,
15068 bool &UseOneConstNR,
15069 bool Reciprocal) const {
15070 EVT VT = Operand.getValueType();
15071 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
15072 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
15073 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15074 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15075 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15076 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15077
15078 // The Newton-Raphson computation with a single constant does not provide
15079 // enough accuracy on some CPUs.
15080 UseOneConstNR = !Subtarget.needsTwoConstNR();
15081 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
15082 }
15083 return SDValue();
15084}
15085
15086SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
15087 int Enabled,
15088 int &RefinementSteps) const {
15089 EVT VT = Operand.getValueType();
15090 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
15091 (VT == MVT::f64 && Subtarget.hasFRE()) ||
15092 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15093 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15094 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15095 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15096 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
15097 }
15098 return SDValue();
15099}
15100
15102 // Note: This functionality is used only when arcp is enabled, and
15103 // on cores with reciprocal estimates (which are used when arcp is
15104 // enabled for division), this functionality is redundant with the default
15105 // combiner logic (once the division -> reciprocal/multiply transformation
15106 // has taken place). As a result, this matters more for older cores than for
15107 // newer ones.
15108
15109 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15110 // reciprocal if there are two or more FDIVs (for embedded cores with only
15111 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
15112 switch (Subtarget.getCPUDirective()) {
15113 default:
15114 return 3;
15115 case PPC::DIR_440:
15116 case PPC::DIR_A2:
15117 case PPC::DIR_E500:
15118 case PPC::DIR_E500mc:
15119 case PPC::DIR_E5500:
15120 return 2;
15121 }
15122}
15123
15124// isConsecutiveLSLoc needs to work even if all adds have not yet been
15125// collapsed, and so we need to look through chains of them.
15127 int64_t& Offset, SelectionDAG &DAG) {
15128 if (DAG.isBaseWithConstantOffset(Loc)) {
15129 Base = Loc.getOperand(0);
15130 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
15131
15132 // The base might itself be a base plus an offset, and if so, accumulate
15133 // that as well.
15134 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
15135 }
15136}
15137
15139 unsigned Bytes, int Dist,
15140 SelectionDAG &DAG) {
15141 if (VT.getSizeInBits() / 8 != Bytes)
15142 return false;
15143
15144 SDValue BaseLoc = Base->getBasePtr();
15145 if (Loc.getOpcode() == ISD::FrameIndex) {
15146 if (BaseLoc.getOpcode() != ISD::FrameIndex)
15147 return false;
15149 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
15150 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
15151 int FS = MFI.getObjectSize(FI);
15152 int BFS = MFI.getObjectSize(BFI);
15153 if (FS != BFS || FS != (int)Bytes) return false;
15154 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
15155 }
15156
15157 SDValue Base1 = Loc, Base2 = BaseLoc;
15158 int64_t Offset1 = 0, Offset2 = 0;
15159 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
15160 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
15161 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
15162 return true;
15163
15164 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15165 const GlobalValue *GV1 = nullptr;
15166 const GlobalValue *GV2 = nullptr;
15167 Offset1 = 0;
15168 Offset2 = 0;
15169 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
15170 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
15171 if (isGA1 && isGA2 && GV1 == GV2)
15172 return Offset1 == (Offset2 + Dist*Bytes);
15173 return false;
15174}
15175
15176// Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
15177// not enforce equality of the chain operands.
15179 unsigned Bytes, int Dist,
15180 SelectionDAG &DAG) {
15182 EVT VT = LS->getMemoryVT();
15183 SDValue Loc = LS->getBasePtr();
15184 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
15185 }
15186
15187 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
15188 EVT VT;
15189 switch (N->getConstantOperandVal(1)) {
15190 default: return false;
15191 case Intrinsic::ppc_altivec_lvx:
15192 case Intrinsic::ppc_altivec_lvxl:
15193 case Intrinsic::ppc_vsx_lxvw4x:
15194 case Intrinsic::ppc_vsx_lxvw4x_be:
15195 VT = MVT::v4i32;
15196 break;
15197 case Intrinsic::ppc_vsx_lxvd2x:
15198 case Intrinsic::ppc_vsx_lxvd2x_be:
15199 VT = MVT::v2f64;
15200 break;
15201 case Intrinsic::ppc_altivec_lvebx:
15202 VT = MVT::i8;
15203 break;
15204 case Intrinsic::ppc_altivec_lvehx:
15205 VT = MVT::i16;
15206 break;
15207 case Intrinsic::ppc_altivec_lvewx:
15208 VT = MVT::i32;
15209 break;
15210 }
15211
15212 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
15213 }
15214
15215 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
15216 EVT VT;
15217 switch (N->getConstantOperandVal(1)) {
15218 default: return false;
15219 case Intrinsic::ppc_altivec_stvx:
15220 case Intrinsic::ppc_altivec_stvxl:
15221 case Intrinsic::ppc_vsx_stxvw4x:
15222 VT = MVT::v4i32;
15223 break;
15224 case Intrinsic::ppc_vsx_stxvd2x:
15225 VT = MVT::v2f64;
15226 break;
15227 case Intrinsic::ppc_vsx_stxvw4x_be:
15228 VT = MVT::v4i32;
15229 break;
15230 case Intrinsic::ppc_vsx_stxvd2x_be:
15231 VT = MVT::v2f64;
15232 break;
15233 case Intrinsic::ppc_altivec_stvebx:
15234 VT = MVT::i8;
15235 break;
15236 case Intrinsic::ppc_altivec_stvehx:
15237 VT = MVT::i16;
15238 break;
15239 case Intrinsic::ppc_altivec_stvewx:
15240 VT = MVT::i32;
15241 break;
15242 }
15243
15244 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
15245 }
15246
15247 return false;
15248}
15249
15250// Return true is there is a nearyby consecutive load to the one provided
15251// (regardless of alignment). We search up and down the chain, looking though
15252// token factors and other loads (but nothing else). As a result, a true result
15253// indicates that it is safe to create a new consecutive load adjacent to the
15254// load provided.
15256 SDValue Chain = LD->getChain();
15257 EVT VT = LD->getMemoryVT();
15258
15259 SmallPtrSet<SDNode *, 16> LoadRoots;
15260 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
15262
15263 // First, search up the chain, branching to follow all token-factor operands.
15264 // If we find a consecutive load, then we're done, otherwise, record all
15265 // nodes just above the top-level loads and token factors.
15266 while (!Queue.empty()) {
15267 SDNode *ChainNext = Queue.pop_back_val();
15268 if (!Visited.insert(ChainNext).second)
15269 continue;
15270
15271 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
15272 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15273 return true;
15274
15275 if (!Visited.count(ChainLD->getChain().getNode()))
15276 Queue.push_back(ChainLD->getChain().getNode());
15277 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
15278 for (const SDUse &O : ChainNext->ops())
15279 if (!Visited.count(O.getNode()))
15280 Queue.push_back(O.getNode());
15281 } else
15282 LoadRoots.insert(ChainNext);
15283 }
15284
15285 // Second, search down the chain, starting from the top-level nodes recorded
15286 // in the first phase. These top-level nodes are the nodes just above all
15287 // loads and token factors. Starting with their uses, recursively look though
15288 // all loads (just the chain uses) and token factors to find a consecutive
15289 // load.
15290 Visited.clear();
15291 Queue.clear();
15292
15293 for (SDNode *I : LoadRoots) {
15294 Queue.push_back(I);
15295
15296 while (!Queue.empty()) {
15297 SDNode *LoadRoot = Queue.pop_back_val();
15298 if (!Visited.insert(LoadRoot).second)
15299 continue;
15300
15301 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
15302 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15303 return true;
15304
15305 for (SDNode *U : LoadRoot->users())
15306 if (((isa<MemSDNode>(U) &&
15307 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
15308 U->getOpcode() == ISD::TokenFactor) &&
15309 !Visited.count(U))
15310 Queue.push_back(U);
15311 }
15312 }
15313
15314 return false;
15315}
15316
15317/// This function is called when we have proved that a SETCC node can be replaced
15318/// by subtraction (and other supporting instructions) so that the result of
15319/// comparison is kept in a GPR instead of CR. This function is purely for
15320/// codegen purposes and has some flags to guide the codegen process.
15321static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
15322 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
15323 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15324
15325 // Zero extend the operands to the largest legal integer. Originally, they
15326 // must be of a strictly smaller size.
15327 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
15328 DAG.getConstant(Size, DL, MVT::i32));
15329 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
15330 DAG.getConstant(Size, DL, MVT::i32));
15331
15332 // Swap if needed. Depends on the condition code.
15333 if (Swap)
15334 std::swap(Op0, Op1);
15335
15336 // Subtract extended integers.
15337 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
15338
15339 // Move the sign bit to the least significant position and zero out the rest.
15340 // Now the least significant bit carries the result of original comparison.
15341 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
15342 DAG.getConstant(Size - 1, DL, MVT::i32));
15343 auto Final = Shifted;
15344
15345 // Complement the result if needed. Based on the condition code.
15346 if (Complement)
15347 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
15348 DAG.getConstant(1, DL, MVT::i64));
15349
15350 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
15351}
15352
15353SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
15354 DAGCombinerInfo &DCI) const {
15355 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15356
15357 SelectionDAG &DAG = DCI.DAG;
15358 SDLoc DL(N);
15359
15360 // Size of integers being compared has a critical role in the following
15361 // analysis, so we prefer to do this when all types are legal.
15362 if (!DCI.isAfterLegalizeDAG())
15363 return SDValue();
15364
15365 // If all users of SETCC extend its value to a legal integer type
15366 // then we replace SETCC with a subtraction
15367 for (const SDNode *U : N->users())
15368 if (U->getOpcode() != ISD::ZERO_EXTEND)
15369 return SDValue();
15370
15371 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15372 auto OpSize = N->getOperand(0).getValueSizeInBits();
15373
15375
15376 if (OpSize < Size) {
15377 switch (CC) {
15378 default: break;
15379 case ISD::SETULT:
15380 return generateEquivalentSub(N, Size, false, false, DL, DAG);
15381 case ISD::SETULE:
15382 return generateEquivalentSub(N, Size, true, true, DL, DAG);
15383 case ISD::SETUGT:
15384 return generateEquivalentSub(N, Size, false, true, DL, DAG);
15385 case ISD::SETUGE:
15386 return generateEquivalentSub(N, Size, true, false, DL, DAG);
15387 }
15388 }
15389
15390 return SDValue();
15391}
15392
15393SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
15394 DAGCombinerInfo &DCI) const {
15395 SelectionDAG &DAG = DCI.DAG;
15396 SDLoc dl(N);
15397
15398 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
15399 // If we're tracking CR bits, we need to be careful that we don't have:
15400 // trunc(binary-ops(zext(x), zext(y)))
15401 // or
15402 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
15403 // such that we're unnecessarily moving things into GPRs when it would be
15404 // better to keep them in CR bits.
15405
15406 // Note that trunc here can be an actual i1 trunc, or can be the effective
15407 // truncation that comes from a setcc or select_cc.
15408 if (N->getOpcode() == ISD::TRUNCATE &&
15409 N->getValueType(0) != MVT::i1)
15410 return SDValue();
15411
15412 if (N->getOperand(0).getValueType() != MVT::i32 &&
15413 N->getOperand(0).getValueType() != MVT::i64)
15414 return SDValue();
15415
15416 if (N->getOpcode() == ISD::SETCC ||
15417 N->getOpcode() == ISD::SELECT_CC) {
15418 // If we're looking at a comparison, then we need to make sure that the
15419 // high bits (all except for the first) don't matter the result.
15420 ISD::CondCode CC =
15421 cast<CondCodeSDNode>(N->getOperand(
15422 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
15423 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
15424
15425 if (ISD::isSignedIntSetCC(CC)) {
15426 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
15427 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
15428 return SDValue();
15429 } else if (ISD::isUnsignedIntSetCC(CC)) {
15430 if (!DAG.MaskedValueIsZero(N->getOperand(0),
15431 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
15432 !DAG.MaskedValueIsZero(N->getOperand(1),
15433 APInt::getHighBitsSet(OpBits, OpBits-1)))
15434 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
15435 : SDValue());
15436 } else {
15437 // This is neither a signed nor an unsigned comparison, just make sure
15438 // that the high bits are equal.
15439 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
15440 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
15441
15442 // We don't really care about what is known about the first bit (if
15443 // anything), so pretend that it is known zero for both to ensure they can
15444 // be compared as constants.
15445 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
15446 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
15447
15448 if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
15449 Op1Known.getConstant() != Op2Known.getConstant())
15450 return SDValue();
15451 }
15452 }
15453
15454 // We now know that the higher-order bits are irrelevant, we just need to
15455 // make sure that all of the intermediate operations are bit operations, and
15456 // all inputs are extensions.
15457 if (N->getOperand(0).getOpcode() != ISD::AND &&
15458 N->getOperand(0).getOpcode() != ISD::OR &&
15459 N->getOperand(0).getOpcode() != ISD::XOR &&
15460 N->getOperand(0).getOpcode() != ISD::SELECT &&
15461 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
15462 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
15463 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
15464 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
15465 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
15466 return SDValue();
15467
15468 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
15469 N->getOperand(1).getOpcode() != ISD::AND &&
15470 N->getOperand(1).getOpcode() != ISD::OR &&
15471 N->getOperand(1).getOpcode() != ISD::XOR &&
15472 N->getOperand(1).getOpcode() != ISD::SELECT &&
15473 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
15474 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
15475 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
15476 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
15477 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
15478 return SDValue();
15479
15481 SmallVector<SDValue, 8> BinOps, PromOps;
15482 SmallPtrSet<SDNode *, 16> Visited;
15483
15484 for (unsigned i = 0; i < 2; ++i) {
15485 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15486 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15487 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15488 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15489 isa<ConstantSDNode>(N->getOperand(i)))
15490 Inputs.push_back(N->getOperand(i));
15491 else
15492 BinOps.push_back(N->getOperand(i));
15493
15494 if (N->getOpcode() == ISD::TRUNCATE)
15495 break;
15496 }
15497
15498 // Visit all inputs, collect all binary operations (and, or, xor and
15499 // select) that are all fed by extensions.
15500 while (!BinOps.empty()) {
15501 SDValue BinOp = BinOps.pop_back_val();
15502
15503 if (!Visited.insert(BinOp.getNode()).second)
15504 continue;
15505
15506 PromOps.push_back(BinOp);
15507
15508 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15509 // The condition of the select is not promoted.
15510 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15511 continue;
15512 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15513 continue;
15514
15515 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15516 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15517 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15518 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15519 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15520 Inputs.push_back(BinOp.getOperand(i));
15521 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15522 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15523 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15524 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15525 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
15526 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15527 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15528 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15529 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
15530 BinOps.push_back(BinOp.getOperand(i));
15531 } else {
15532 // We have an input that is not an extension or another binary
15533 // operation; we'll abort this transformation.
15534 return SDValue();
15535 }
15536 }
15537 }
15538
15539 // Make sure that this is a self-contained cluster of operations (which
15540 // is not quite the same thing as saying that everything has only one
15541 // use).
15542 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15543 if (isa<ConstantSDNode>(Inputs[i]))
15544 continue;
15545
15546 for (const SDNode *User : Inputs[i].getNode()->users()) {
15547 if (User != N && !Visited.count(User))
15548 return SDValue();
15549
15550 // Make sure that we're not going to promote the non-output-value
15551 // operand(s) or SELECT or SELECT_CC.
15552 // FIXME: Although we could sometimes handle this, and it does occur in
15553 // practice that one of the condition inputs to the select is also one of
15554 // the outputs, we currently can't deal with this.
15555 if (User->getOpcode() == ISD::SELECT) {
15556 if (User->getOperand(0) == Inputs[i])
15557 return SDValue();
15558 } else if (User->getOpcode() == ISD::SELECT_CC) {
15559 if (User->getOperand(0) == Inputs[i] ||
15560 User->getOperand(1) == Inputs[i])
15561 return SDValue();
15562 }
15563 }
15564 }
15565
15566 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15567 for (const SDNode *User : PromOps[i].getNode()->users()) {
15568 if (User != N && !Visited.count(User))
15569 return SDValue();
15570
15571 // Make sure that we're not going to promote the non-output-value
15572 // operand(s) or SELECT or SELECT_CC.
15573 // FIXME: Although we could sometimes handle this, and it does occur in
15574 // practice that one of the condition inputs to the select is also one of
15575 // the outputs, we currently can't deal with this.
15576 if (User->getOpcode() == ISD::SELECT) {
15577 if (User->getOperand(0) == PromOps[i])
15578 return SDValue();
15579 } else if (User->getOpcode() == ISD::SELECT_CC) {
15580 if (User->getOperand(0) == PromOps[i] ||
15581 User->getOperand(1) == PromOps[i])
15582 return SDValue();
15583 }
15584 }
15585 }
15586
15587 // Replace all inputs with the extension operand.
15588 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15589 // Constants may have users outside the cluster of to-be-promoted nodes,
15590 // and so we need to replace those as we do the promotions.
15591 if (isa<ConstantSDNode>(Inputs[i]))
15592 continue;
15593 else
15594 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
15595 }
15596
15597 std::list<HandleSDNode> PromOpHandles;
15598 for (auto &PromOp : PromOps)
15599 PromOpHandles.emplace_back(PromOp);
15600
15601 // Replace all operations (these are all the same, but have a different
15602 // (i1) return type). DAG.getNode will validate that the types of
15603 // a binary operator match, so go through the list in reverse so that
15604 // we've likely promoted both operands first. Any intermediate truncations or
15605 // extensions disappear.
15606 while (!PromOpHandles.empty()) {
15607 SDValue PromOp = PromOpHandles.back().getValue();
15608 PromOpHandles.pop_back();
15609
15610 if (PromOp.getOpcode() == ISD::TRUNCATE ||
15611 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
15612 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
15613 PromOp.getOpcode() == ISD::ANY_EXTEND) {
15614 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
15615 PromOp.getOperand(0).getValueType() != MVT::i1) {
15616 // The operand is not yet ready (see comment below).
15617 PromOpHandles.emplace_front(PromOp);
15618 continue;
15619 }
15620
15621 SDValue RepValue = PromOp.getOperand(0);
15622 if (isa<ConstantSDNode>(RepValue))
15623 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
15624
15625 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
15626 continue;
15627 }
15628
15629 unsigned C;
15630 switch (PromOp.getOpcode()) {
15631 default: C = 0; break;
15632 case ISD::SELECT: C = 1; break;
15633 case ISD::SELECT_CC: C = 2; break;
15634 }
15635
15636 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15637 PromOp.getOperand(C).getValueType() != MVT::i1) ||
15638 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15639 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
15640 // The to-be-promoted operands of this node have not yet been
15641 // promoted (this should be rare because we're going through the
15642 // list backward, but if one of the operands has several users in
15643 // this cluster of to-be-promoted nodes, it is possible).
15644 PromOpHandles.emplace_front(PromOp);
15645 continue;
15646 }
15647
15649
15650 // If there are any constant inputs, make sure they're replaced now.
15651 for (unsigned i = 0; i < 2; ++i)
15652 if (isa<ConstantSDNode>(Ops[C+i]))
15653 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
15654
15655 DAG.ReplaceAllUsesOfValueWith(PromOp,
15656 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
15657 }
15658
15659 // Now we're left with the initial truncation itself.
15660 if (N->getOpcode() == ISD::TRUNCATE)
15661 return N->getOperand(0);
15662
15663 // Otherwise, this is a comparison. The operands to be compared have just
15664 // changed type (to i1), but everything else is the same.
15665 return SDValue(N, 0);
15666}
15667
15668SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
15669 DAGCombinerInfo &DCI) const {
15670 SelectionDAG &DAG = DCI.DAG;
15671 SDLoc dl(N);
15672
15673 // If we're tracking CR bits, we need to be careful that we don't have:
15674 // zext(binary-ops(trunc(x), trunc(y)))
15675 // or
15676 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
15677 // such that we're unnecessarily moving things into CR bits that can more
15678 // efficiently stay in GPRs. Note that if we're not certain that the high
15679 // bits are set as required by the final extension, we still may need to do
15680 // some masking to get the proper behavior.
15681
15682 // This same functionality is important on PPC64 when dealing with
15683 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
15684 // the return values of functions. Because it is so similar, it is handled
15685 // here as well.
15686
15687 if (N->getValueType(0) != MVT::i32 &&
15688 N->getValueType(0) != MVT::i64)
15689 return SDValue();
15690
15691 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
15692 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
15693 return SDValue();
15694
15695 if (N->getOperand(0).getOpcode() != ISD::AND &&
15696 N->getOperand(0).getOpcode() != ISD::OR &&
15697 N->getOperand(0).getOpcode() != ISD::XOR &&
15698 N->getOperand(0).getOpcode() != ISD::SELECT &&
15699 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
15700 return SDValue();
15701
15703 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
15704 SmallPtrSet<SDNode *, 16> Visited;
15705
15706 // Visit all inputs, collect all binary operations (and, or, xor and
15707 // select) that are all fed by truncations.
15708 while (!BinOps.empty()) {
15709 SDValue BinOp = BinOps.pop_back_val();
15710
15711 if (!Visited.insert(BinOp.getNode()).second)
15712 continue;
15713
15714 PromOps.push_back(BinOp);
15715
15716 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15717 // The condition of the select is not promoted.
15718 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15719 continue;
15720 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15721 continue;
15722
15723 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15724 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15725 Inputs.push_back(BinOp.getOperand(i));
15726 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15727 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15728 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15729 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15730 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
15731 BinOps.push_back(BinOp.getOperand(i));
15732 } else {
15733 // We have an input that is not a truncation or another binary
15734 // operation; we'll abort this transformation.
15735 return SDValue();
15736 }
15737 }
15738 }
15739
15740 // The operands of a select that must be truncated when the select is
15741 // promoted because the operand is actually part of the to-be-promoted set.
15742 DenseMap<SDNode *, EVT> SelectTruncOp[2];
15743
15744 // Make sure that this is a self-contained cluster of operations (which
15745 // is not quite the same thing as saying that everything has only one
15746 // use).
15747 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15748 if (isa<ConstantSDNode>(Inputs[i]))
15749 continue;
15750
15751 for (SDNode *User : Inputs[i].getNode()->users()) {
15752 if (User != N && !Visited.count(User))
15753 return SDValue();
15754
15755 // If we're going to promote the non-output-value operand(s) or SELECT or
15756 // SELECT_CC, record them for truncation.
15757 if (User->getOpcode() == ISD::SELECT) {
15758 if (User->getOperand(0) == Inputs[i])
15759 SelectTruncOp[0].insert(std::make_pair(User,
15760 User->getOperand(0).getValueType()));
15761 } else if (User->getOpcode() == ISD::SELECT_CC) {
15762 if (User->getOperand(0) == Inputs[i])
15763 SelectTruncOp[0].insert(std::make_pair(User,
15764 User->getOperand(0).getValueType()));
15765 if (User->getOperand(1) == Inputs[i])
15766 SelectTruncOp[1].insert(std::make_pair(User,
15767 User->getOperand(1).getValueType()));
15768 }
15769 }
15770 }
15771
15772 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15773 for (SDNode *User : PromOps[i].getNode()->users()) {
15774 if (User != N && !Visited.count(User))
15775 return SDValue();
15776
15777 // If we're going to promote the non-output-value operand(s) or SELECT or
15778 // SELECT_CC, record them for truncation.
15779 if (User->getOpcode() == ISD::SELECT) {
15780 if (User->getOperand(0) == PromOps[i])
15781 SelectTruncOp[0].insert(std::make_pair(User,
15782 User->getOperand(0).getValueType()));
15783 } else if (User->getOpcode() == ISD::SELECT_CC) {
15784 if (User->getOperand(0) == PromOps[i])
15785 SelectTruncOp[0].insert(std::make_pair(User,
15786 User->getOperand(0).getValueType()));
15787 if (User->getOperand(1) == PromOps[i])
15788 SelectTruncOp[1].insert(std::make_pair(User,
15789 User->getOperand(1).getValueType()));
15790 }
15791 }
15792 }
15793
15794 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
15795 bool ReallyNeedsExt = false;
15796 if (N->getOpcode() != ISD::ANY_EXTEND) {
15797 // If all of the inputs are not already sign/zero extended, then
15798 // we'll still need to do that at the end.
15799 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15800 if (isa<ConstantSDNode>(Inputs[i]))
15801 continue;
15802
15803 unsigned OpBits =
15804 Inputs[i].getOperand(0).getValueSizeInBits();
15805 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
15806
15807 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
15808 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
15809 APInt::getHighBitsSet(OpBits,
15810 OpBits-PromBits))) ||
15811 (N->getOpcode() == ISD::SIGN_EXTEND &&
15812 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
15813 (OpBits-(PromBits-1)))) {
15814 ReallyNeedsExt = true;
15815 break;
15816 }
15817 }
15818 }
15819
15820 // Convert PromOps to handles before doing any RAUW operations, as these
15821 // may CSE with existing nodes, deleting the originals.
15822 std::list<HandleSDNode> PromOpHandles;
15823 for (auto &PromOp : PromOps)
15824 PromOpHandles.emplace_back(PromOp);
15825
15826 // Replace all inputs, either with the truncation operand, or a
15827 // truncation or extension to the final output type.
15828 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15829 // Constant inputs need to be replaced with the to-be-promoted nodes that
15830 // use them because they might have users outside of the cluster of
15831 // promoted nodes.
15832 if (isa<ConstantSDNode>(Inputs[i]))
15833 continue;
15834
15835 SDValue InSrc = Inputs[i].getOperand(0);
15836 if (Inputs[i].getValueType() == N->getValueType(0))
15837 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
15838 else if (N->getOpcode() == ISD::SIGN_EXTEND)
15839 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15840 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
15841 else if (N->getOpcode() == ISD::ZERO_EXTEND)
15842 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15843 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
15844 else
15845 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15846 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
15847 }
15848
15849 // Replace all operations (these are all the same, but have a different
15850 // (promoted) return type). DAG.getNode will validate that the types of
15851 // a binary operator match, so go through the list in reverse so that
15852 // we've likely promoted both operands first.
15853 while (!PromOpHandles.empty()) {
15854 SDValue PromOp = PromOpHandles.back().getValue();
15855 PromOpHandles.pop_back();
15856
15857 unsigned C;
15858 switch (PromOp.getOpcode()) {
15859 default: C = 0; break;
15860 case ISD::SELECT: C = 1; break;
15861 case ISD::SELECT_CC: C = 2; break;
15862 }
15863
15864 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15865 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
15866 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15867 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
15868 // The to-be-promoted operands of this node have not yet been
15869 // promoted (this should be rare because we're going through the
15870 // list backward, but if one of the operands has several users in
15871 // this cluster of to-be-promoted nodes, it is possible).
15872 PromOpHandles.emplace_front(PromOp);
15873 continue;
15874 }
15875
15876 // For SELECT and SELECT_CC nodes, we do a similar check for any
15877 // to-be-promoted comparison inputs.
15878 if (PromOp.getOpcode() == ISD::SELECT ||
15879 PromOp.getOpcode() == ISD::SELECT_CC) {
15880 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
15881 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
15882 (SelectTruncOp[1].count(PromOp.getNode()) &&
15883 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
15884 PromOpHandles.emplace_front(PromOp);
15885 continue;
15886 }
15887 }
15888
15890
15891 // If this node has constant inputs, then they'll need to be promoted here.
15892 for (unsigned i = 0; i < 2; ++i) {
15893 if (!isa<ConstantSDNode>(Ops[C+i]))
15894 continue;
15895 if (Ops[C+i].getValueType() == N->getValueType(0))
15896 continue;
15897
15898 if (N->getOpcode() == ISD::SIGN_EXTEND)
15899 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15900 else if (N->getOpcode() == ISD::ZERO_EXTEND)
15901 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15902 else
15903 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
15904 }
15905
15906 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
15907 // truncate them again to the original value type.
15908 if (PromOp.getOpcode() == ISD::SELECT ||
15909 PromOp.getOpcode() == ISD::SELECT_CC) {
15910 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
15911 if (SI0 != SelectTruncOp[0].end())
15912 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
15913 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
15914 if (SI1 != SelectTruncOp[1].end())
15915 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
15916 }
15917
15918 DAG.ReplaceAllUsesOfValueWith(PromOp,
15919 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
15920 }
15921
15922 // Now we're left with the initial extension itself.
15923 if (!ReallyNeedsExt)
15924 return N->getOperand(0);
15925
15926 // To zero extend, just mask off everything except for the first bit (in the
15927 // i1 case).
15928 if (N->getOpcode() == ISD::ZERO_EXTEND)
15929 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
15931 N->getValueSizeInBits(0), PromBits),
15932 dl, N->getValueType(0)));
15933
15934 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
15935 "Invalid extension type");
15936 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
15937 SDValue ShiftCst =
15938 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
15939 return DAG.getNode(
15940 ISD::SRA, dl, N->getValueType(0),
15941 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
15942 ShiftCst);
15943}
15944
15945// The function check a i128 load can convert to 16i8 load for Vcmpequb.
15946static bool canConvertToVcmpequb(SDValue &LHS, SDValue &RHS, bool IsPPC64) {
15947
15948 auto isValidForConvert = [IsPPC64](SDValue &Operand) {
15949 if (!Operand.hasOneUse())
15950 return false;
15951
15952 if (Operand.getValueType() != MVT::i128)
15953 return false;
15954
15955 if (Operand.getOpcode() == ISD::Constant) {
15956 auto *C = cast<ConstantSDNode>(Operand);
15957 const APInt &Val = C->getAPIntValue();
15958 // On PPC64, comparing an i128 value loaded from memory against a
15959 // constant smaller than 2^16 is usually better left to scalar lowering.
15960 // In that case, the compare can be lowered using xori (since xori has a
15961 // 16-bit immediate field), which is cheaper than materializing a vector
15962 // constant and using vcmpequb.
15963 if (IsPPC64 && Val.ult(1ULL << 16))
15964 return false;
15965 return true;
15966 }
15967
15968 auto *LoadNode = dyn_cast<LoadSDNode>(Operand);
15969 if (!LoadNode)
15970 return false;
15971
15972 // If memory operation is volatile, do not perform any
15973 // optimization or transformation. Volatile operations must be preserved
15974 // as written to ensure correct program behavior, so we return an empty
15975 // SDValue to indicate no action.
15976
15977 if (LoadNode->isVolatile())
15978 return false;
15979
15980 // Only combine loads if both use the unindexed addressing mode.
15981 // PowerPC AltiVec/VMX does not support vector loads or stores with
15982 // pre/post-increment addressing. Indexed modes may imply implicit
15983 // pointer updates, which are not compatible with AltiVec vector
15984 // instructions.
15985 if (LoadNode->getAddressingMode() != ISD::UNINDEXED)
15986 return false;
15987
15988 // Only combine loads if both are non-extending loads
15989 // (ISD::NON_EXTLOAD). Extending loads (such as ISD::ZEXTLOAD or
15990 // ISD::SEXTLOAD) perform zero or sign extension, which may change the
15991 // loaded value's semantics and are not compatible with vector loads.
15992 if (LoadNode->getExtensionType() != ISD::NON_EXTLOAD)
15993 return false;
15994
15995 return true;
15996 };
15997
15998 return (isValidForConvert(LHS) && isValidForConvert(RHS));
15999}
16000
16002 const SDLoc &DL) {
16003
16004 assert(N->getOpcode() == ISD::SETCC && "Should be called with a SETCC node");
16005
16006 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16007 assert((CC == ISD::SETNE || CC == ISD::SETEQ) &&
16008 "CC mus be ISD::SETNE or ISD::SETEQ");
16009
16010 auto getV16i8Load = [&](const SDValue &Operand) {
16011 if (Operand.getOpcode() == ISD::Constant)
16012 return DAG.getBitcast(MVT::v16i8, Operand);
16013
16014 assert(Operand.getOpcode() == ISD::LOAD && "Must be LoadSDNode here.");
16015
16016 auto *LoadNode = cast<LoadSDNode>(Operand);
16017 // Create a new MachineMemOperand without range metadata.
16018 // Range metadata is only valid for integer scalar types, not vectors.
16019 // The original i128 load may have range metadata, but when we convert
16020 // to v16i8, that metadata is no longer semantically valid.
16021 MachineMemOperand *MMO = LoadNode->getMemOperand();
16024 MMO->getPointerInfo(), MMO->getFlags(), MMO->getSize(), MMO->getAlign(),
16025 MMO->getAAInfo(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
16026 MMO->getFailureOrdering());
16027 SDValue NewLoad = DAG.getLoad(MVT::v16i8, DL, LoadNode->getChain(),
16028 LoadNode->getBasePtr(), NewMMO);
16029 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadNode, 1), NewLoad.getValue(1));
16030 return NewLoad;
16031 };
16032
16033 // Following code transforms the DAG
16034 // t0: ch,glue = EntryToken
16035 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16036 // t3: i128,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16037 // undef:i64
16038 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16039 // t5: i128,ch =
16040 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64 t6: i1 =
16041 // setcc t3, t5, setne:ch
16042 //
16043 // ---->
16044 //
16045 // t0: ch,glue = EntryToken
16046 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16047 // t3: v16i8,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16048 // undef:i64
16049 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16050 // t5: v16i8,ch =
16051 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64
16052 // t6: i32 =
16053 // llvm.ppc.altivec.vcmpequb.p TargetConstant:i32<10505>,
16054 // Constant:i32<2>, t3, t5
16055 // t7: i1 = setcc t6, Constant:i32<0>, seteq:ch
16056
16057 // Or transforms the DAG
16058 // t5: i128,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16059 // t8: i1 =
16060 // setcc Constant:i128<237684487579686500932345921536>, t5, setne:ch
16061 //
16062 // --->
16063 //
16064 // t5: v16i8,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16065 // t6: v16i8 = bitcast Constant:i128<237684487579686500932345921536>
16066 // t7: i32 =
16067 // llvm.ppc.altivec.vcmpequb.p Constant:i32<10962>, Constant:i32<2>, t5, t2
16068
16069 SDValue LHSVec = getV16i8Load(N->getOperand(0));
16070 SDValue RHSVec = getV16i8Load(N->getOperand(1));
16071
16072 SDValue IntrID =
16073 DAG.getConstant(Intrinsic::ppc_altivec_vcmpequb_p, DL, MVT::i32);
16074 SDValue CRSel = DAG.getConstant(2, DL, MVT::i32); // which CR6 predicate field
16075 SDValue PredResult = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
16076 IntrID, CRSel, LHSVec, RHSVec);
16077 // ppc_altivec_vcmpequb_p returns 1 when two vectors are the same,
16078 // so we need to invert the CC opcode.
16079 return DAG.getSetCC(DL, N->getValueType(0), PredResult,
16080 DAG.getConstant(0, DL, MVT::i32),
16081 CC == ISD::SETNE ? ISD::SETEQ : ISD::SETNE);
16082}
16083
16084// Detect whether there is a pattern like (setcc (and X, 1), 0, eq).
16085// If it is , return true; otherwise return false.
16087 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16088
16089 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16090 if (CC != ISD::SETEQ)
16091 return false;
16092
16093 SDValue LHS = N->getOperand(0);
16094 SDValue RHS = N->getOperand(1);
16095
16096 // Check the `SDValue &V` is from `and` with `1`.
16097 auto IsAndWithOne = [](SDValue &V) {
16098 if (V.getOpcode() == ISD::AND) {
16099 for (const SDValue &Op : V->ops())
16100 if (auto *C = dyn_cast<ConstantSDNode>(Op))
16101 if (C->isOne())
16102 return true;
16103 }
16104 return false;
16105 };
16106
16107 // Check whether the SETCC compare with zero.
16108 auto IsCompareWithZero = [](SDValue &V) {
16109 if (auto *C = dyn_cast<ConstantSDNode>(V))
16110 if (C->isZero())
16111 return true;
16112 return false;
16113 };
16114
16115 return (IsAndWithOne(LHS) && IsCompareWithZero(RHS)) ||
16116 (IsAndWithOne(RHS) && IsCompareWithZero(LHS));
16117}
16118
16119// You must check whether the `SDNode* N` can be converted to Xori using
16120// the function `static bool canConvertSETCCToXori(SDNode *N)`
16121// before calling the function; otherwise, it may produce incorrect results.
16123
16124 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16125 SDValue LHS = N->getOperand(0);
16126 SDValue RHS = N->getOperand(1);
16127 SDLoc DL(N);
16128
16129 [[maybe_unused]] ISD::CondCode CC =
16130 cast<CondCodeSDNode>(N->getOperand(2))->get();
16131 assert((CC == ISD::SETEQ) && "CC must be ISD::SETEQ.");
16132 // Rewrite it as XORI (and X, 1), 1.
16133 auto MakeXor1 = [&](SDValue V) {
16134 EVT VT = V.getValueType();
16135 SDValue One = DAG.getConstant(1, DL, VT);
16136 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, V, One);
16137 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Xor);
16138 };
16139
16140 if (LHS.getOpcode() == ISD::AND && RHS.getOpcode() != ISD::AND)
16141 return MakeXor1(LHS);
16142
16143 if (RHS.getOpcode() == ISD::AND && LHS.getOpcode() != ISD::AND)
16144 return MakeXor1(RHS);
16145
16146 llvm_unreachable("Should not reach here.");
16147}
16148
16149// Match `sext(setcc X, 0, eq)` and turn it into an ADDIC/SUBFE sequence.
16150//
16151// This generates code for:
16152// X == 0 ? -1 : 0
16153//
16154// On pre-ISA 3.1 targets, this is better than the longer CNTLZW/SRWI/NEG
16155// sequence. This is useful for cases like:
16156// uint8_t f(uint8_t x) { return (x == 0) ? -1 : 0; }
16157//
16158// ISA 3.1+ is skipped because those targets can use SETBC.
16159
16160SDValue PPCTargetLowering::combineSignExtendSetCC(SDNode *N,
16161 DAGCombinerInfo &DCI) const {
16162 if (Subtarget.isISA3_1())
16163 return SDValue();
16164
16165 EVT VT = N->getValueType(0);
16166 if (VT != MVT::i32 && (VT != MVT::i64 || !Subtarget.isPPC64()))
16167 return SDValue();
16168
16169 SDValue N0 = N->getOperand(0);
16170 if (N0.getOpcode() != ISD::SETCC)
16171 return SDValue();
16172
16174 SDValue LHS = N0.getOperand(0);
16175 SDValue RHS = N0.getOperand(1);
16176
16177 // Not match: sext (setcc x, 0, eq) or sext (setcc 0, x, eq)
16178 if (CC != ISD::SETEQ || (!isNullConstant(LHS) && !isNullConstant(RHS)))
16179 return SDValue();
16180
16181 SDLoc dl(N);
16182 SelectionDAG &DAG = DCI.DAG;
16184 EVT XVT = X.getValueType(); // The type of x in the setcc x, 0, eq.
16185
16186 // The type that ADDC/SUBE operate on. Reject larger types and zero-extend
16187 // smaller ones.
16188 MVT OpVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
16189 if (XVT.bitsGT(OpVT))
16190 return SDValue();
16191
16192 if (XVT.bitsLT(OpVT))
16193 X = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, X);
16194
16195 // Generate: SUBFE(ADDC(X, -1)).
16196 SDValue MinusOne = DAG.getAllOnesConstant(dl, OpVT);
16197 SDValue Addc =
16198 DAG.getNode(PPCISD::ADDC, dl, DAG.getVTList(OpVT, MVT::i32), X, MinusOne);
16199 SDValue Carry = Addc.getValue(1);
16200 SDValue Sube = DAG.getNode(PPCISD::SUBE, dl, DAG.getVTList(OpVT, MVT::i32),
16201 Addc, Addc, Carry);
16202
16203 // Truncate back to i32 if we used i64 operations.
16204 if (OpVT == MVT::i64 && VT == MVT::i32)
16205 return DAG.getNode(ISD::TRUNCATE, dl, VT, Sube);
16206
16207 return Sube;
16208}
16209
16210SDValue PPCTargetLowering::combineSetCC(SDNode *N,
16211 DAGCombinerInfo &DCI) const {
16212 assert(N->getOpcode() == ISD::SETCC &&
16213 "Should be called with a SETCC node");
16214
16215 // Check if the pattern (setcc (and X, 1), 0, eq) is present.
16216 // If it is, rewrite it as XORI (and X, 1), 1.
16218 return ConvertSETCCToXori(N, DCI.DAG);
16219
16220 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16221 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
16222 SDValue LHS = N->getOperand(0);
16223 SDValue RHS = N->getOperand(1);
16224
16225 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
16226 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
16227 LHS.hasOneUse())
16228 std::swap(LHS, RHS);
16229
16230 // x == 0-y --> x+y == 0
16231 // x != 0-y --> x+y != 0
16232 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
16233 RHS.hasOneUse()) {
16234 SDLoc DL(N);
16235 SelectionDAG &DAG = DCI.DAG;
16236 EVT VT = N->getValueType(0);
16237 EVT OpVT = LHS.getValueType();
16238 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
16239 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
16240 }
16241
16242 // Optimization: Fold i128 equality/inequality compares of two loads into a
16243 // vectorized compare using vcmpequb.p when Altivec is available.
16244 //
16245 // Rationale:
16246 // A scalar i128 SETCC (eq/ne) normally lowers to multiple scalar ops.
16247 // On VSX-capable subtargets, we can instead reinterpret the i128 loads
16248 // as v16i8 vectors and use the Altive vcmpequb.p instruction to
16249 // perform a full 128-bit equality check in a single vector compare.
16250 //
16251 // Example Result:
16252 // This transformation replaces memcmp(a, b, 16) with two vector loads
16253 // and one vector compare instruction.
16254
16255 if (Subtarget.hasAltivec() &&
16256 canConvertToVcmpequb(LHS, RHS, Subtarget.isPPC64()))
16257 return convertTwoLoadsAndCmpToVCMPEQUB(DCI.DAG, N, SDLoc(N));
16258 }
16259
16260 return DAGCombineTruncBoolExt(N, DCI);
16261}
16262
16263// Is this an extending load from an f32 to an f64?
16264static bool isFPExtLoad(SDValue Op) {
16265 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
16266 return LD->getExtensionType() == ISD::EXTLOAD &&
16267 Op.getValueType() == MVT::f64;
16268 return false;
16269}
16270
16271/// Reduces the number of fp-to-int conversion when building a vector.
16272///
16273/// If this vector is built out of floating to integer conversions,
16274/// transform it to a vector built out of floating point values followed by a
16275/// single floating to integer conversion of the vector.
16276/// Namely (build_vector (fptosi $A), (fptosi $B), ...)
16277/// becomes (fptosi (build_vector ($A, $B, ...)))
16278SDValue PPCTargetLowering::
16279combineElementTruncationToVectorTruncation(SDNode *N,
16280 DAGCombinerInfo &DCI) const {
16281 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16282 "Should be called with a BUILD_VECTOR node");
16283
16284 SelectionDAG &DAG = DCI.DAG;
16285 SDLoc dl(N);
16286
16287 SDValue FirstInput = N->getOperand(0);
16288 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
16289 "The input operand must be an fp-to-int conversion.");
16290
16291 // This combine happens after legalization so the fp_to_[su]i nodes are
16292 // already converted to PPCSISD nodes.
16293 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
16294 if (FirstConversion == PPCISD::FCTIDZ ||
16295 FirstConversion == PPCISD::FCTIDUZ ||
16296 FirstConversion == PPCISD::FCTIWZ ||
16297 FirstConversion == PPCISD::FCTIWUZ) {
16298 bool IsSplat = true;
16299 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
16300 FirstConversion == PPCISD::FCTIWUZ;
16301 EVT SrcVT = FirstInput.getOperand(0).getValueType();
16303 EVT TargetVT = N->getValueType(0);
16304 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16305 SDValue NextOp = N->getOperand(i);
16306 if (NextOp.getOpcode() != PPCISD::MFVSR)
16307 return SDValue();
16308 unsigned NextConversion = NextOp.getOperand(0).getOpcode();
16309 if (NextConversion != FirstConversion)
16310 return SDValue();
16311 // If we are converting to 32-bit integers, we need to add an FP_ROUND.
16312 // This is not valid if the input was originally double precision. It is
16313 // also not profitable to do unless this is an extending load in which
16314 // case doing this combine will allow us to combine consecutive loads.
16315 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
16316 return SDValue();
16317 if (N->getOperand(i) != FirstInput)
16318 IsSplat = false;
16319 }
16320
16321 // If this is a splat, we leave it as-is since there will be only a single
16322 // fp-to-int conversion followed by a splat of the integer. This is better
16323 // for 32-bit and smaller ints and neutral for 64-bit ints.
16324 if (IsSplat)
16325 return SDValue();
16326
16327 // Now that we know we have the right type of node, get its operands
16328 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16329 SDValue In = N->getOperand(i).getOperand(0);
16330 if (Is32Bit) {
16331 // For 32-bit values, we need to add an FP_ROUND node (if we made it
16332 // here, we know that all inputs are extending loads so this is safe).
16333 if (In.isUndef())
16334 Ops.push_back(DAG.getUNDEF(SrcVT));
16335 else {
16336 SDValue Trunc =
16337 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0),
16338 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
16339 Ops.push_back(Trunc);
16340 }
16341 } else
16342 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
16343 }
16344
16345 unsigned Opcode;
16346 if (FirstConversion == PPCISD::FCTIDZ ||
16347 FirstConversion == PPCISD::FCTIWZ)
16348 Opcode = ISD::FP_TO_SINT;
16349 else
16350 Opcode = ISD::FP_TO_UINT;
16351
16352 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
16353 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
16354 return DAG.getNode(Opcode, dl, TargetVT, BV);
16355 }
16356 return SDValue();
16357}
16358
16359// LXVKQ instruction load VSX vector with a special quadword value
16360// based on an immediate value. This helper method returns the details of the
16361// match as a tuple of {LXVKQ unsigned IMM Value, right_shift_amount}
16362// to help generate the LXVKQ instruction and the subsequent shift instruction
16363// required to match the original build vector pattern.
16364
16365// LXVKQPattern: {LXVKQ unsigned IMM Value, right_shift_amount}
16366using LXVKQPattern = std::tuple<uint32_t, uint8_t>;
16367
16368static std::optional<LXVKQPattern> getPatternInfo(const APInt &FullVal) {
16369
16370 // LXVKQ instruction loads the Quadword value:
16371 // 0x8000_0000_0000_0000_0000_0000_0000_0000 when imm = 0b10000
16372 static const APInt BasePattern = APInt(128, 0x8000000000000000ULL) << 64;
16373 static const uint32_t Uim = 16;
16374
16375 // Check for direct LXVKQ match (no shift needed)
16376 if (FullVal == BasePattern)
16377 return std::make_tuple(Uim, uint8_t{0});
16378
16379 // Check if FullValue is 1 (the result of the base pattern >> 127)
16380 if (FullVal == APInt(128, 1))
16381 return std::make_tuple(Uim, uint8_t{127});
16382
16383 return std::nullopt;
16384}
16385
16386/// Combine vector loads to a single load (using lxvkq) or splat with shift of a
16387/// constant (xxspltib + vsrq) by recognising patterns in the Build Vector.
16388/// LXVKQ instruction load VSX vector with a special quadword value based on an
16389/// immediate value. if UIM=0b10000 then LXVKQ loads VSR[32×TX+T] with value
16390/// 0x8000_0000_0000_0000_0000_0000_0000_0000.
16391/// This can be used to inline the build vector constants that have the
16392/// following patterns:
16393///
16394/// 0x8000_0000_0000_0000_0000_0000_0000_0000 (MSB set pattern)
16395/// 0x0000_0000_0000_0000_0000_0000_0000_0001 (LSB set pattern)
16396/// MSB pattern can directly loaded using LXVKQ while LSB is loaded using a
16397/// combination of splatting and right shift instructions.
16398
16399SDValue PPCTargetLowering::combineBVLoadsSpecialValue(SDValue Op,
16400 SelectionDAG &DAG) const {
16401
16402 assert((Op.getNode() && Op.getOpcode() == ISD::BUILD_VECTOR) &&
16403 "Expected a BuildVectorSDNode in combineBVLoadsSpecialValue");
16404
16405 // This transformation is only supported if we are loading either a byte,
16406 // halfword, word, or doubleword.
16407 EVT VT = Op.getValueType();
16408 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
16409 VT == MVT::v2i64))
16410 return SDValue();
16411
16412 LLVM_DEBUG(llvm::dbgs() << "\ncombineBVLoadsSpecialValue: Build vector ("
16413 << VT.getEVTString() << "): ";
16414 Op->dump());
16415
16416 unsigned NumElems = VT.getVectorNumElements();
16417 unsigned ElemBits = VT.getScalarSizeInBits();
16418
16419 bool IsLittleEndian = DAG.getDataLayout().isLittleEndian();
16420
16421 // Check for Non-constant operand in the build vector.
16422 for (const SDValue &Operand : Op.getNode()->op_values()) {
16423 if (!isa<ConstantSDNode>(Operand))
16424 return SDValue();
16425 }
16426
16427 // Assemble build vector operands as a 128-bit register value
16428 // We need to reconstruct what the 128-bit register pattern would be
16429 // that produces this vector when interpreted with the current endianness
16430 APInt FullVal = APInt::getZero(128);
16431
16432 for (unsigned Index = 0; Index < NumElems; ++Index) {
16433 auto *C = cast<ConstantSDNode>(Op.getOperand(Index));
16434
16435 // Get element value as raw bits (zero-extended)
16436 uint64_t ElemValue = C->getZExtValue();
16437
16438 // Mask to element size to ensure we only get the relevant bits
16439 if (ElemBits < 64)
16440 ElemValue &= ((1ULL << ElemBits) - 1);
16441
16442 // Calculate bit position for this element in the 128-bit register
16443 unsigned BitPos =
16444 (IsLittleEndian) ? (Index * ElemBits) : (128 - (Index + 1) * ElemBits);
16445
16446 // Create APInt for the element value and shift it to correct position
16447 APInt ElemAPInt(128, ElemValue);
16448 ElemAPInt <<= BitPos;
16449
16450 // Place the element value at the correct bit position
16451 FullVal |= ElemAPInt;
16452 }
16453
16454 if (FullVal.isZero() || FullVal.isAllOnes())
16455 return SDValue();
16456
16457 if (auto UIMOpt = getPatternInfo(FullVal)) {
16458 const auto &[Uim, ShiftAmount] = *UIMOpt;
16459 SDLoc Dl(Op);
16460
16461 // Generate LXVKQ instruction if the shift amount is zero.
16462 if (ShiftAmount == 0) {
16463 SDValue UimVal = DAG.getTargetConstant(Uim, Dl, MVT::i32);
16464 SDValue LxvkqInstr =
16465 SDValue(DAG.getMachineNode(PPC::LXVKQ, Dl, VT, UimVal), 0);
16467 << "combineBVLoadsSpecialValue: Instruction Emitted ";
16468 LxvkqInstr.dump());
16469 return LxvkqInstr;
16470 }
16471
16472 assert(ShiftAmount == 127 && "Unexpected lxvkq shift amount value");
16473
16474 // The right shifted pattern can be constructed using a combination of
16475 // XXSPLTIB and VSRQ instruction. VSRQ uses the shift amount from the lower
16476 // 7 bits of byte 15. This can be specified using XXSPLTIB with immediate
16477 // value 255.
16478 SDValue ShiftAmountVec =
16479 SDValue(DAG.getMachineNode(PPC::XXSPLTIB, Dl, MVT::v4i32,
16480 DAG.getTargetConstant(255, Dl, MVT::i32)),
16481 0);
16482 // Generate appropriate right shift instruction
16483 SDValue ShiftVec = SDValue(
16484 DAG.getMachineNode(PPC::VSRQ, Dl, VT, ShiftAmountVec, ShiftAmountVec),
16485 0);
16487 << "\n combineBVLoadsSpecialValue: Instruction Emitted ";
16488 ShiftVec.dump());
16489 return ShiftVec;
16490 }
16491 // No patterns matched for build vectors.
16492 return SDValue();
16493}
16494
16495/// Reduce the number of loads when building a vector.
16496///
16497/// Building a vector out of multiple loads can be converted to a load
16498/// of the vector type if the loads are consecutive. If the loads are
16499/// consecutive but in descending order, a shuffle is added at the end
16500/// to reorder the vector.
16502 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16503 "Should be called with a BUILD_VECTOR node");
16504
16505 SDLoc dl(N);
16506
16507 // Return early for non byte-sized type, as they can't be consecutive.
16508 if (!N->getValueType(0).getVectorElementType().isByteSized())
16509 return SDValue();
16510
16511 bool InputsAreConsecutiveLoads = true;
16512 bool InputsAreReverseConsecutive = true;
16513 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
16514 SDValue FirstInput = N->getOperand(0);
16515 bool IsRoundOfExtLoad = false;
16516 LoadSDNode *FirstLoad = nullptr;
16517
16518 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
16519 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
16520 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0));
16521 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD;
16522 }
16523 // Not a build vector of (possibly fp_rounded) loads.
16524 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
16525 N->getNumOperands() == 1)
16526 return SDValue();
16527
16528 if (!IsRoundOfExtLoad)
16529 FirstLoad = cast<LoadSDNode>(FirstInput);
16530
16532 InputLoads.push_back(FirstLoad);
16533 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
16534 // If any inputs are fp_round(extload), they all must be.
16535 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
16536 return SDValue();
16537
16538 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
16539 N->getOperand(i);
16540 if (NextInput.getOpcode() != ISD::LOAD)
16541 return SDValue();
16542
16543 SDValue PreviousInput =
16544 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
16545 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput);
16546 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput);
16547
16548 // If any inputs are fp_round(extload), they all must be.
16549 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
16550 return SDValue();
16551
16552 // We only care about regular loads. The PPC-specific load intrinsics
16553 // will not lead to a merge opportunity.
16554 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1))
16555 InputsAreConsecutiveLoads = false;
16556 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1))
16557 InputsAreReverseConsecutive = false;
16558
16559 // Exit early if the loads are neither consecutive nor reverse consecutive.
16560 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
16561 return SDValue();
16562 InputLoads.push_back(LD2);
16563 }
16564
16565 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
16566 "The loads cannot be both consecutive and reverse consecutive.");
16567
16568 SDValue WideLoad;
16569 SDValue ReturnSDVal;
16570 if (InputsAreConsecutiveLoads) {
16571 assert(FirstLoad && "Input needs to be a LoadSDNode.");
16572 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(),
16573 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
16574 FirstLoad->getAlign());
16575 ReturnSDVal = WideLoad;
16576 } else if (InputsAreReverseConsecutive) {
16577 LoadSDNode *LastLoad = InputLoads.back();
16578 assert(LastLoad && "Input needs to be a LoadSDNode.");
16579 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(),
16580 LastLoad->getBasePtr(), LastLoad->getPointerInfo(),
16581 LastLoad->getAlign());
16583 for (int i = N->getNumOperands() - 1; i >= 0; i--)
16584 Ops.push_back(i);
16585
16586 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad,
16587 DAG.getUNDEF(N->getValueType(0)), Ops);
16588 } else
16589 return SDValue();
16590
16591 for (auto *LD : InputLoads)
16592 DAG.makeEquivalentMemoryOrdering(LD, WideLoad);
16593 return ReturnSDVal;
16594}
16595
16596// This function adds the required vector_shuffle needed to get
16597// the elements of the vector extract in the correct position
16598// as specified by the CorrectElems encoding.
16600 SDValue Input, uint64_t Elems,
16601 uint64_t CorrectElems) {
16602 SDLoc dl(N);
16603
16604 unsigned NumElems = Input.getValueType().getVectorNumElements();
16605 SmallVector<int, 16> ShuffleMask(NumElems, -1);
16606
16607 // Knowing the element indices being extracted from the original
16608 // vector and the order in which they're being inserted, just put
16609 // them at element indices required for the instruction.
16610 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16611 if (DAG.getDataLayout().isLittleEndian())
16612 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
16613 else
16614 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
16615 CorrectElems = CorrectElems >> 8;
16616 Elems = Elems >> 8;
16617 }
16618
16619 SDValue Shuffle =
16620 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
16621 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
16622
16623 EVT VT = N->getValueType(0);
16624 SDValue Conv = DAG.getBitcast(VT, Shuffle);
16625
16626 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
16627 Input.getValueType().getVectorElementType(),
16629 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
16630 DAG.getValueType(ExtVT));
16631}
16632
16633// Look for build vector patterns where input operands come from sign
16634// extended vector_extract elements of specific indices. If the correct indices
16635// aren't used, add a vector shuffle to fix up the indices and create
16636// SIGN_EXTEND_INREG node which selects the vector sign extend instructions
16637// during instruction selection.
16639 // This array encodes the indices that the vector sign extend instructions
16640 // extract from when extending from one type to another for both BE and LE.
16641 // The right nibble of each byte corresponds to the LE incides.
16642 // and the left nibble of each byte corresponds to the BE incides.
16643 // For example: 0x3074B8FC byte->word
16644 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
16645 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
16646 // For example: 0x000070F8 byte->double word
16647 // For LE: the allowed indices are: 0x0,0x8
16648 // For BE: the allowed indices are: 0x7,0xF
16649 uint64_t TargetElems[] = {
16650 0x3074B8FC, // b->w
16651 0x000070F8, // b->d
16652 0x10325476, // h->w
16653 0x00003074, // h->d
16654 0x00001032, // w->d
16655 };
16656
16657 uint64_t Elems = 0;
16658 int Index;
16659 SDValue Input;
16660
16661 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
16662 if (!Op)
16663 return false;
16664 if (Op.getOpcode() != ISD::SIGN_EXTEND &&
16665 Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
16666 return false;
16667
16668 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
16669 // of the right width.
16670 SDValue Extract = Op.getOperand(0);
16671 if (Extract.getOpcode() == ISD::ANY_EXTEND)
16672 Extract = Extract.getOperand(0);
16673 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16674 return false;
16675
16677 if (!ExtOp)
16678 return false;
16679
16680 Index = ExtOp->getZExtValue();
16681 if (Input && Input != Extract.getOperand(0))
16682 return false;
16683
16684 if (!Input)
16685 Input = Extract.getOperand(0);
16686
16687 Elems = Elems << 8;
16688 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
16689 Elems |= Index;
16690
16691 return true;
16692 };
16693
16694 // If the build vector operands aren't sign extended vector extracts,
16695 // of the same input vector, then return.
16696 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16697 if (!isSExtOfVecExtract(N->getOperand(i))) {
16698 return SDValue();
16699 }
16700 }
16701
16702 // If the vector extract indices are not correct, add the appropriate
16703 // vector_shuffle.
16704 int TgtElemArrayIdx;
16705 int InputSize = Input.getValueType().getScalarSizeInBits();
16706 int OutputSize = N->getValueType(0).getScalarSizeInBits();
16707 if (InputSize + OutputSize == 40)
16708 TgtElemArrayIdx = 0;
16709 else if (InputSize + OutputSize == 72)
16710 TgtElemArrayIdx = 1;
16711 else if (InputSize + OutputSize == 48)
16712 TgtElemArrayIdx = 2;
16713 else if (InputSize + OutputSize == 80)
16714 TgtElemArrayIdx = 3;
16715 else if (InputSize + OutputSize == 96)
16716 TgtElemArrayIdx = 4;
16717 else
16718 return SDValue();
16719
16720 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
16721 CorrectElems = DAG.getDataLayout().isLittleEndian()
16722 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
16723 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
16724 if (Elems != CorrectElems) {
16725 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
16726 }
16727
16728 // Regular lowering will catch cases where a shuffle is not needed.
16729 return SDValue();
16730}
16731
16732// Look for the pattern of a load from a narrow width to i128, feeding
16733// into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
16734// (LXVRZX). This node represents a zero extending load that will be matched
16735// to the Load VSX Vector Rightmost instructions.
16737 SDLoc DL(N);
16738
16739 // This combine is only eligible for a BUILD_VECTOR of v1i128.
16740 if (N->getValueType(0) != MVT::v1i128)
16741 return SDValue();
16742
16743 SDValue Operand = N->getOperand(0);
16744 // Proceed with the transformation if the operand to the BUILD_VECTOR
16745 // is a load instruction.
16746 if (Operand.getOpcode() != ISD::LOAD)
16747 return SDValue();
16748
16749 auto *LD = cast<LoadSDNode>(Operand);
16750 EVT MemoryType = LD->getMemoryVT();
16751
16752 // This transformation is only valid if the we are loading either a byte,
16753 // halfword, word, or doubleword.
16754 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
16755 MemoryType == MVT::i32 || MemoryType == MVT::i64;
16756
16757 // Ensure that the load from the narrow width is being zero extended to i128.
16758 if (!ValidLDType ||
16759 (LD->getExtensionType() != ISD::ZEXTLOAD &&
16760 LD->getExtensionType() != ISD::EXTLOAD))
16761 return SDValue();
16762
16763 SDValue LoadOps[] = {
16764 LD->getChain(), LD->getBasePtr(),
16765 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
16766
16767 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
16768 DAG.getVTList(MVT::v1i128, MVT::Other),
16769 LoadOps, MemoryType, LD->getMemOperand());
16770}
16771
16772SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
16773 DAGCombinerInfo &DCI) const {
16774 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16775 "Should be called with a BUILD_VECTOR node");
16776
16777 SelectionDAG &DAG = DCI.DAG;
16778 SDLoc dl(N);
16779
16780 if (!Subtarget.hasVSX())
16781 return SDValue();
16782
16783 // The target independent DAG combiner will leave a build_vector of
16784 // float-to-int conversions intact. We can generate MUCH better code for
16785 // a float-to-int conversion of a vector of floats.
16786 SDValue FirstInput = N->getOperand(0);
16787 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
16788 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
16789 if (Reduced)
16790 return Reduced;
16791 }
16792
16793 // If we're building a vector out of consecutive loads, just load that
16794 // vector type.
16795 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
16796 if (Reduced)
16797 return Reduced;
16798
16799 // If we're building a vector out of extended elements from another vector
16800 // we have P9 vector integer extend instructions. The code assumes legal
16801 // input types (i.e. it can't handle things like v4i16) so do not run before
16802 // legalization.
16803 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
16804 Reduced = combineBVOfVecSExt(N, DAG);
16805 if (Reduced)
16806 return Reduced;
16807 }
16808
16809 // On Power10, the Load VSX Vector Rightmost instructions can be utilized
16810 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
16811 // is a load from <valid narrow width> to i128.
16812 if (Subtarget.isISA3_1()) {
16813 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
16814 if (BVOfZLoad)
16815 return BVOfZLoad;
16816 }
16817
16818 if (N->getValueType(0) != MVT::v2f64)
16819 return SDValue();
16820
16821 // Looking for:
16822 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
16823 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
16824 FirstInput.getOpcode() != ISD::UINT_TO_FP)
16825 return SDValue();
16826 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
16827 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
16828 return SDValue();
16829 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
16830 return SDValue();
16831
16832 SDValue Ext1 = FirstInput.getOperand(0);
16833 SDValue Ext2 = N->getOperand(1).getOperand(0);
16834 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
16836 return SDValue();
16837
16838 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
16839 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
16840 if (!Ext1Op || !Ext2Op)
16841 return SDValue();
16842 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
16843 Ext1.getOperand(0) != Ext2.getOperand(0))
16844 return SDValue();
16845
16846 int FirstElem = Ext1Op->getZExtValue();
16847 int SecondElem = Ext2Op->getZExtValue();
16848 int SubvecIdx;
16849 if (FirstElem == 0 && SecondElem == 1)
16850 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
16851 else if (FirstElem == 2 && SecondElem == 3)
16852 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
16853 else
16854 return SDValue();
16855
16856 SDValue SrcVec = Ext1.getOperand(0);
16857 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
16858 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
16859 return DAG.getNode(NodeType, dl, MVT::v2f64,
16860 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
16861}
16862
16863SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
16864 DAGCombinerInfo &DCI) const {
16865 assert((N->getOpcode() == ISD::SINT_TO_FP ||
16866 N->getOpcode() == ISD::UINT_TO_FP) &&
16867 "Need an int -> FP conversion node here");
16868
16869 if (useSoftFloat() || !Subtarget.has64BitSupport())
16870 return SDValue();
16871
16872 SelectionDAG &DAG = DCI.DAG;
16873 SDLoc dl(N);
16874 SDValue Op(N, 0);
16875
16876 // Don't handle ppc_fp128 here or conversions that are out-of-range capable
16877 // from the hardware.
16878 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
16879 return SDValue();
16880 if (!Op.getOperand(0).getValueType().isSimple())
16881 return SDValue();
16882 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
16883 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
16884 return SDValue();
16885
16886 SDValue FirstOperand(Op.getOperand(0));
16887 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
16888 (FirstOperand.getValueType() == MVT::i8 ||
16889 FirstOperand.getValueType() == MVT::i16);
16890 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
16891 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
16892 bool DstDouble = Op.getValueType() == MVT::f64;
16893 unsigned ConvOp = Signed ?
16894 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
16895 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
16896 SDValue WidthConst =
16897 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
16898 dl, false);
16899 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
16900 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
16901 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
16902 DAG.getVTList(MVT::f64, MVT::Other),
16903 Ops, MVT::i8, LDN->getMemOperand());
16904 DAG.makeEquivalentMemoryOrdering(LDN, Ld);
16905
16906 // For signed conversion, we need to sign-extend the value in the VSR
16907 if (Signed) {
16908 SDValue ExtOps[] = { Ld, WidthConst };
16909 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
16910 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
16911 } else
16912 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
16913 }
16914
16915
16916 // For i32 intermediate values, unfortunately, the conversion functions
16917 // leave the upper 32 bits of the value are undefined. Within the set of
16918 // scalar instructions, we have no method for zero- or sign-extending the
16919 // value. Thus, we cannot handle i32 intermediate values here.
16920 if (Op.getOperand(0).getValueType() == MVT::i32)
16921 return SDValue();
16922
16923 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
16924 "UINT_TO_FP is supported only with FPCVT");
16925
16926 // If we have FCFIDS, then use it when converting to single-precision.
16927 // Otherwise, convert to double-precision and then round.
16928 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
16929 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
16930 : PPCISD::FCFIDS)
16931 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
16932 : PPCISD::FCFID);
16933 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
16934 ? MVT::f32
16935 : MVT::f64;
16936
16937 // If we're converting from a float, to an int, and back to a float again,
16938 // then we don't need the store/load pair at all.
16939 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
16940 Subtarget.hasFPCVT()) ||
16941 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
16942 SDValue Src = Op.getOperand(0).getOperand(0);
16943 if (Src.getValueType() == MVT::f32) {
16944 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
16945 DCI.AddToWorklist(Src.getNode());
16946 } else if (Src.getValueType() != MVT::f64) {
16947 // Make sure that we don't pick up a ppc_fp128 source value.
16948 return SDValue();
16949 }
16950
16951 unsigned FCTOp =
16952 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
16953 PPCISD::FCTIDUZ;
16954
16955 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
16956 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
16957
16958 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
16959 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
16960 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
16961 DCI.AddToWorklist(FP.getNode());
16962 }
16963
16964 return FP;
16965 }
16966
16967 return SDValue();
16968}
16969
16970// expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
16971// builtins) into loads with swaps.
16973 DAGCombinerInfo &DCI) const {
16974 // Delay VSX load for LE combine until after LegalizeOps to prioritize other
16975 // load combines.
16976 if (DCI.isBeforeLegalizeOps())
16977 return SDValue();
16978
16979 SelectionDAG &DAG = DCI.DAG;
16980 SDLoc dl(N);
16981 SDValue Chain;
16982 SDValue Base;
16983 MachineMemOperand *MMO;
16984
16985 switch (N->getOpcode()) {
16986 default:
16987 llvm_unreachable("Unexpected opcode for little endian VSX load");
16988 case ISD::LOAD: {
16990 Chain = LD->getChain();
16991 Base = LD->getBasePtr();
16992 MMO = LD->getMemOperand();
16993 // If the MMO suggests this isn't a load of a full vector, leave
16994 // things alone. For a built-in, we have to make the change for
16995 // correctness, so if there is a size problem that will be a bug.
16996 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
16997 return SDValue();
16998 break;
16999 }
17002 Chain = Intrin->getChain();
17003 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
17004 // us what we want. Get operand 2 instead.
17005 Base = Intrin->getOperand(2);
17006 MMO = Intrin->getMemOperand();
17007 break;
17008 }
17009 }
17010
17011 MVT VecTy = N->getValueType(0).getSimpleVT();
17012
17013 SDValue LoadOps[] = { Chain, Base };
17014 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
17015 DAG.getVTList(MVT::v2f64, MVT::Other),
17016 LoadOps, MVT::v2f64, MMO);
17017
17018 DCI.AddToWorklist(Load.getNode());
17019 Chain = Load.getValue(1);
17020 SDValue Swap = DAG.getNode(
17021 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
17022 DCI.AddToWorklist(Swap.getNode());
17023
17024 // Add a bitcast if the resulting load type doesn't match v2f64.
17025 if (VecTy != MVT::v2f64) {
17026 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
17027 DCI.AddToWorklist(N.getNode());
17028 // Package {bitcast value, swap's chain} to match Load's shape.
17029 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
17030 N, Swap.getValue(1));
17031 }
17032
17033 return Swap;
17034}
17035
17036// expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
17037// builtins) into stores with swaps.
17039 DAGCombinerInfo &DCI) const {
17040 // Delay VSX store for LE combine until after LegalizeOps to prioritize other
17041 // store combines.
17042 if (DCI.isBeforeLegalizeOps())
17043 return SDValue();
17044
17045 SelectionDAG &DAG = DCI.DAG;
17046 SDLoc dl(N);
17047 SDValue Chain;
17048 SDValue Base;
17049 unsigned SrcOpnd;
17050 MachineMemOperand *MMO;
17051
17052 switch (N->getOpcode()) {
17053 default:
17054 llvm_unreachable("Unexpected opcode for little endian VSX store");
17055 case ISD::STORE: {
17057 Chain = ST->getChain();
17058 Base = ST->getBasePtr();
17059 MMO = ST->getMemOperand();
17060 SrcOpnd = 1;
17061 // If the MMO suggests this isn't a store of a full vector, leave
17062 // things alone. For a built-in, we have to make the change for
17063 // correctness, so if there is a size problem that will be a bug.
17064 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
17065 return SDValue();
17066 break;
17067 }
17068 case ISD::INTRINSIC_VOID: {
17070 Chain = Intrin->getChain();
17071 // Intrin->getBasePtr() oddly does not get what we want.
17072 Base = Intrin->getOperand(3);
17073 MMO = Intrin->getMemOperand();
17074 SrcOpnd = 2;
17075 break;
17076 }
17077 }
17078
17079 SDValue Src = N->getOperand(SrcOpnd);
17080 MVT VecTy = Src.getValueType().getSimpleVT();
17081
17082 // All stores are done as v2f64 and possible bit cast.
17083 if (VecTy != MVT::v2f64) {
17084 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
17085 DCI.AddToWorklist(Src.getNode());
17086 }
17087
17088 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
17089 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
17090 DCI.AddToWorklist(Swap.getNode());
17091 Chain = Swap.getValue(1);
17092 SDValue StoreOps[] = { Chain, Swap, Base };
17093 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
17094 DAG.getVTList(MVT::Other),
17095 StoreOps, VecTy, MMO);
17096 DCI.AddToWorklist(Store.getNode());
17097 return Store;
17098}
17099
17100// Handle DAG combine for STORE (FP_TO_INT F).
17101SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
17102 DAGCombinerInfo &DCI) const {
17103 SelectionDAG &DAG = DCI.DAG;
17104 SDLoc dl(N);
17105 unsigned Opcode = N->getOperand(1).getOpcode();
17106 (void)Opcode;
17107 bool Strict = N->getOperand(1)->isStrictFPOpcode();
17108
17109 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
17110 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT)
17111 && "Not a FP_TO_INT Instruction!");
17112
17113 SDValue Val = N->getOperand(1).getOperand(Strict ? 1 : 0);
17114 EVT Op1VT = N->getOperand(1).getValueType();
17115 EVT ResVT = Val.getValueType();
17116
17117 if (!Subtarget.hasVSX() || !Subtarget.hasFPCVT() || !isTypeLegal(ResVT))
17118 return SDValue();
17119
17120 // Only perform combine for conversion to i64/i32 or power9 i16/i8.
17121 bool ValidTypeForStoreFltAsInt =
17122 (Op1VT == MVT::i32 || (Op1VT == MVT::i64 && Subtarget.isPPC64()) ||
17123 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
17124
17125 // TODO: Lower conversion from f128 on all VSX targets
17126 if (ResVT == MVT::ppcf128 || (ResVT == MVT::f128 && !Subtarget.hasP9Vector()))
17127 return SDValue();
17128
17129 if ((Op1VT != MVT::i64 && !Subtarget.hasP8Vector()) ||
17130 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
17131 return SDValue();
17132
17133 Val = convertFPToInt(N->getOperand(1), DAG, Subtarget);
17134
17135 // Set number of bytes being converted.
17136 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
17137 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2),
17138 DAG.getIntPtrConstant(ByteSize, dl, false),
17139 DAG.getValueType(Op1VT)};
17140
17141 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
17142 DAG.getVTList(MVT::Other), Ops,
17143 cast<StoreSDNode>(N)->getMemoryVT(),
17144 cast<StoreSDNode>(N)->getMemOperand());
17145
17146 return Val;
17147}
17148
17149static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
17150 // Check that the source of the element keeps flipping
17151 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
17152 bool PrevElemFromFirstVec = Mask[0] < NumElts;
17153 for (int i = 1, e = Mask.size(); i < e; i++) {
17154 if (PrevElemFromFirstVec && Mask[i] < NumElts)
17155 return false;
17156 if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
17157 return false;
17158 PrevElemFromFirstVec = !PrevElemFromFirstVec;
17159 }
17160 return true;
17161}
17162
17163static bool isSplatBV(SDValue Op) {
17164 if (Op.getOpcode() != ISD::BUILD_VECTOR)
17165 return false;
17166 SDValue FirstOp;
17167
17168 // Find first non-undef input.
17169 for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
17170 FirstOp = Op.getOperand(i);
17171 if (!FirstOp.isUndef())
17172 break;
17173 }
17174
17175 // All inputs are undef or the same as the first non-undef input.
17176 for (int i = 1, e = Op.getNumOperands(); i < e; i++)
17177 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
17178 return false;
17179 return true;
17180}
17181
17183 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17184 return Op;
17185 if (Op.getOpcode() != ISD::BITCAST)
17186 return SDValue();
17187 Op = Op.getOperand(0);
17188 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17189 return Op;
17190 return SDValue();
17191}
17192
17193// Fix up the shuffle mask to account for the fact that the result of
17194// scalar_to_vector is not in lane zero. This just takes all values in
17195// the ranges specified by the min/max indices and adds the number of
17196// elements required to ensure each element comes from the respective
17197// position in the valid lane.
17198// On little endian, that's just the corresponding element in the other
17199// half of the vector. On big endian, it is in the same half but right
17200// justified rather than left justified in that half.
17202 SmallVectorImpl<int> &ShuffV, int LHSFirstElt, int LHSLastElt,
17203 int RHSFirstElt, int RHSLastElt, int HalfVec, unsigned LHSNumValidElts,
17204 unsigned RHSNumValidElts, const PPCSubtarget &Subtarget) {
17205 int LHSEltFixup =
17206 Subtarget.isLittleEndian() ? HalfVec : HalfVec - LHSNumValidElts;
17207 int RHSEltFixup =
17208 Subtarget.isLittleEndian() ? HalfVec : HalfVec - RHSNumValidElts;
17209 for (int I = 0, E = ShuffV.size(); I < E; ++I) {
17210 int Idx = ShuffV[I];
17211 if (Idx >= LHSFirstElt && Idx <= LHSLastElt)
17212 ShuffV[I] += LHSEltFixup;
17213 else if (Idx >= RHSFirstElt && Idx <= RHSLastElt)
17214 ShuffV[I] += RHSEltFixup;
17215 }
17216}
17217
17218// Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
17219// the original is:
17220// (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
17221// In such a case, just change the shuffle mask to extract the element
17222// from the permuted index.
17224 const PPCSubtarget &Subtarget) {
17225 SDLoc dl(OrigSToV);
17226 EVT VT = OrigSToV.getValueType();
17227 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
17228 "Expecting a SCALAR_TO_VECTOR here");
17229 SDValue Input = OrigSToV.getOperand(0);
17230
17231 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17232 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
17233 SDValue OrigVector = Input.getOperand(0);
17234
17235 // Can't handle non-const element indices or different vector types
17236 // for the input to the extract and the output of the scalar_to_vector.
17237 if (Idx && VT == OrigVector.getValueType()) {
17238 unsigned NumElts = VT.getVectorNumElements();
17239 assert(
17240 NumElts > 1 &&
17241 "Cannot produce a permuted scalar_to_vector for one element vector");
17242 SmallVector<int, 16> NewMask(NumElts, -1);
17243 unsigned ResultInElt = NumElts / 2;
17244 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
17245 NewMask[ResultInElt] = Idx->getZExtValue();
17246 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
17247 }
17248 }
17249 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
17250 OrigSToV.getOperand(0));
17251}
17252
17254 int HalfVec, int LHSLastElementDefined,
17255 int RHSLastElementDefined) {
17256 for (int Index : ShuffV) {
17257 if (Index < 0) // Skip explicitly undefined mask indices.
17258 continue;
17259 // Handle first input vector of the vector_shuffle.
17260 if ((LHSLastElementDefined >= 0) && (Index < HalfVec) &&
17261 (Index > LHSLastElementDefined))
17262 return false;
17263 // Handle second input vector of the vector_shuffle.
17264 if ((RHSLastElementDefined >= 0) &&
17265 (Index > HalfVec + RHSLastElementDefined))
17266 return false;
17267 }
17268 return true;
17269}
17270
17272 int ScalarSize, uint64_t ShuffleEltWidth, unsigned &NumValidElts,
17273 int FirstElt, int &LastElt, SDValue VecShuffOperand, SDValue SToVNode,
17274 SelectionDAG &DAG, const PPCSubtarget &Subtarget) {
17275 EVT VecShuffOperandType = VecShuffOperand.getValueType();
17276 // Set up the values for the shuffle vector fixup.
17277 NumValidElts = ScalarSize / VecShuffOperandType.getScalarSizeInBits();
17278 // The last element depends on if the input comes from the LHS or RHS.
17279 //
17280 // For example:
17281 // (shuff (s_to_v i32), (bitcast (s_to_v i64), v4i32), ...)
17282 //
17283 // For the LHS: The last element that comes from the LHS is actually 0, not 3
17284 // because elements 1 and higher of a scalar_to_vector are undefined.
17285 // For the RHS: The last element that comes from the RHS is actually 5, not 7
17286 // because elements 1 and higher of a scalar_to_vector are undefined.
17287 // It is also not 4 because the original scalar_to_vector is wider and
17288 // actually contains two i32 elements.
17289 LastElt = (uint64_t)ScalarSize > ShuffleEltWidth
17290 ? ScalarSize / ShuffleEltWidth - 1 + FirstElt
17291 : FirstElt;
17292 SDValue SToVPermuted = getSToVPermuted(SToVNode, DAG, Subtarget);
17293 if (SToVPermuted.getValueType() != VecShuffOperandType)
17294 SToVPermuted = DAG.getBitcast(VecShuffOperandType, SToVPermuted);
17295 return SToVPermuted;
17296}
17297
17298// On little endian subtargets, combine shuffles such as:
17299// vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
17300// into:
17301// vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
17302// because the latter can be matched to a single instruction merge.
17303// Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
17304// to put the value into element zero. Adjust the shuffle mask so that the
17305// vector can remain in permuted form (to prevent a swap prior to a shuffle).
17306// On big endian targets, this is still useful for SCALAR_TO_VECTOR
17307// nodes with elements smaller than doubleword because all the ways
17308// of getting scalar data into a vector register put the value in the
17309// rightmost element of the left half of the vector.
17310SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
17311 SelectionDAG &DAG) const {
17312 SDValue LHS = SVN->getOperand(0);
17313 SDValue RHS = SVN->getOperand(1);
17314 auto Mask = SVN->getMask();
17315 int NumElts = LHS.getValueType().getVectorNumElements();
17316 SDValue Res(SVN, 0);
17317 SDLoc dl(SVN);
17318 bool IsLittleEndian = Subtarget.isLittleEndian();
17319
17320 // On big endian targets this is only useful for subtargets with direct moves.
17321 // On little endian targets it would be useful for all subtargets with VSX.
17322 // However adding special handling for LE subtargets without direct moves
17323 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
17324 // which includes direct moves.
17325 if (!Subtarget.hasDirectMove())
17326 return Res;
17327
17328 // If this is not a shuffle of a shuffle and the first element comes from
17329 // the second vector, canonicalize to the commuted form. This will make it
17330 // more likely to match one of the single instruction patterns.
17331 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17332 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
17333 std::swap(LHS, RHS);
17334 Res = DAG.getCommutedVectorShuffle(*SVN);
17335
17336 if (!isa<ShuffleVectorSDNode>(Res))
17337 return Res;
17338
17339 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17340 }
17341
17342 // Adjust the shuffle mask if either input vector comes from a
17343 // SCALAR_TO_VECTOR and keep the respective input vector in permuted
17344 // form (to prevent the need for a swap).
17345 SmallVector<int, 16> ShuffV(Mask);
17346 SDValue SToVLHS = isScalarToVec(LHS);
17347 SDValue SToVRHS = isScalarToVec(RHS);
17348 if (SToVLHS || SToVRHS) {
17349 EVT VT = SVN->getValueType(0);
17350 uint64_t ShuffleEltWidth = VT.getVectorElementType().getSizeInBits();
17351 int ShuffleNumElts = ShuffV.size();
17352 int HalfVec = ShuffleNumElts / 2;
17353 // The width of the "valid lane" (i.e. the lane that contains the value that
17354 // is vectorized) needs to be expressed in terms of the number of elements
17355 // of the shuffle. It is thereby the ratio of the values before and after
17356 // any bitcast, which will be set later on if the LHS or RHS are
17357 // SCALAR_TO_VECTOR nodes.
17358 unsigned LHSNumValidElts = HalfVec;
17359 unsigned RHSNumValidElts = HalfVec;
17360
17361 // Initially assume that neither input is permuted. These will be adjusted
17362 // accordingly if either input is. Note, that -1 means that all elements
17363 // are undefined.
17364 int LHSFirstElt = 0;
17365 int RHSFirstElt = ShuffleNumElts;
17366 int LHSLastElt = -1;
17367 int RHSLastElt = -1;
17368
17369 // Get the permuted scalar to vector nodes for the source(s) that come from
17370 // ISD::SCALAR_TO_VECTOR.
17371 // On big endian systems, this only makes sense for element sizes smaller
17372 // than 64 bits since for 64-bit elements, all instructions already put
17373 // the value into element zero. Since scalar size of LHS and RHS may differ
17374 // after isScalarToVec, this should be checked using their own sizes.
17375 int LHSScalarSize = 0;
17376 int RHSScalarSize = 0;
17377 if (SToVLHS) {
17378 LHSScalarSize = SToVLHS.getValueType().getScalarSizeInBits();
17379 if (!IsLittleEndian && LHSScalarSize >= 64)
17380 return Res;
17381 }
17382 if (SToVRHS) {
17383 RHSScalarSize = SToVRHS.getValueType().getScalarSizeInBits();
17384 if (!IsLittleEndian && RHSScalarSize >= 64)
17385 return Res;
17386 }
17387 if (LHSScalarSize != 0)
17389 LHSScalarSize, ShuffleEltWidth, LHSNumValidElts, LHSFirstElt,
17390 LHSLastElt, LHS, SToVLHS, DAG, Subtarget);
17391 if (RHSScalarSize != 0)
17393 RHSScalarSize, ShuffleEltWidth, RHSNumValidElts, RHSFirstElt,
17394 RHSLastElt, RHS, SToVRHS, DAG, Subtarget);
17395
17396 if (!isShuffleMaskInRange(ShuffV, HalfVec, LHSLastElt, RHSLastElt))
17397 return Res;
17398
17399 // Fix up the shuffle mask to reflect where the desired element actually is.
17400 // The minimum and maximum indices that correspond to element zero for both
17401 // the LHS and RHS are computed and will control which shuffle mask entries
17402 // are to be changed. For example, if the RHS is permuted, any shuffle mask
17403 // entries in the range [RHSFirstElt,RHSLastElt] will be adjusted.
17405 ShuffV, LHSFirstElt, LHSLastElt, RHSFirstElt, RHSLastElt, HalfVec,
17406 LHSNumValidElts, RHSNumValidElts, Subtarget);
17407 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17408
17409 // We may have simplified away the shuffle. We won't be able to do anything
17410 // further with it here.
17411 if (!isa<ShuffleVectorSDNode>(Res))
17412 return Res;
17413 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17414 }
17415
17416 SDValue TheSplat = IsLittleEndian ? RHS : LHS;
17417 // The common case after we commuted the shuffle is that the RHS is a splat
17418 // and we have elements coming in from the splat at indices that are not
17419 // conducive to using a merge.
17420 // Example:
17421 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
17422 if (!isSplatBV(TheSplat))
17423 return Res;
17424
17425 // We are looking for a mask such that all even elements are from
17426 // one vector and all odd elements from the other.
17427 if (!isAlternatingShuffMask(Mask, NumElts))
17428 return Res;
17429
17430 // Adjust the mask so we are pulling in the same index from the splat
17431 // as the index from the interesting vector in consecutive elements.
17432 if (IsLittleEndian) {
17433 // Example (even elements from first vector):
17434 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
17435 if (Mask[0] < NumElts)
17436 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17437 if (ShuffV[i] < 0)
17438 continue;
17439 // If element from non-splat is undef, pick first element from splat.
17440 ShuffV[i] = (ShuffV[i - 1] >= 0 ? ShuffV[i - 1] : 0) + NumElts;
17441 }
17442 // Example (odd elements from first vector):
17443 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
17444 else
17445 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17446 if (ShuffV[i] < 0)
17447 continue;
17448 // If element from non-splat is undef, pick first element from splat.
17449 ShuffV[i] = (ShuffV[i + 1] >= 0 ? ShuffV[i + 1] : 0) + NumElts;
17450 }
17451 } else {
17452 // Example (even elements from first vector):
17453 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
17454 if (Mask[0] < NumElts)
17455 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17456 if (ShuffV[i] < 0)
17457 continue;
17458 // If element from non-splat is undef, pick first element from splat.
17459 ShuffV[i] = ShuffV[i + 1] >= 0 ? ShuffV[i + 1] - NumElts : 0;
17460 }
17461 // Example (odd elements from first vector):
17462 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
17463 else
17464 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17465 if (ShuffV[i] < 0)
17466 continue;
17467 // If element from non-splat is undef, pick first element from splat.
17468 ShuffV[i] = ShuffV[i - 1] >= 0 ? ShuffV[i - 1] - NumElts : 0;
17469 }
17470 }
17471
17472 // If the RHS has undefs, we need to remove them since we may have created
17473 // a shuffle that adds those instead of the splat value.
17474 SDValue SplatVal =
17475 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
17476 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
17477
17478 if (IsLittleEndian)
17479 RHS = TheSplat;
17480 else
17481 LHS = TheSplat;
17482 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17483}
17484
17485SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
17486 LSBaseSDNode *LSBase,
17487 DAGCombinerInfo &DCI) const {
17488 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
17489 "Not a reverse memop pattern!");
17490
17491 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
17492 auto Mask = SVN->getMask();
17493 int i = 0;
17494 auto I = Mask.rbegin();
17495 auto E = Mask.rend();
17496
17497 for (; I != E; ++I) {
17498 if (*I != i)
17499 return false;
17500 i++;
17501 }
17502 return true;
17503 };
17504
17505 SelectionDAG &DAG = DCI.DAG;
17506 EVT VT = SVN->getValueType(0);
17507
17508 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
17509 return SDValue();
17510
17511 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
17512 // See comment in PPCVSXSwapRemoval.cpp.
17513 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
17514 if (!Subtarget.hasP9Vector())
17515 return SDValue();
17516
17517 if(!IsElementReverse(SVN))
17518 return SDValue();
17519
17520 if (LSBase->getOpcode() == ISD::LOAD) {
17521 // If the load return value 0 has more than one user except the
17522 // shufflevector instruction, it is not profitable to replace the
17523 // shufflevector with a reverse load.
17524 for (SDUse &Use : LSBase->uses())
17525 if (Use.getResNo() == 0 &&
17526 Use.getUser()->getOpcode() != ISD::VECTOR_SHUFFLE)
17527 return SDValue();
17528
17529 SDLoc dl(LSBase);
17530 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
17531 return DAG.getMemIntrinsicNode(
17532 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
17533 LSBase->getMemoryVT(), LSBase->getMemOperand());
17534 }
17535
17536 if (LSBase->getOpcode() == ISD::STORE) {
17537 // If there are other uses of the shuffle, the swap cannot be avoided.
17538 // Forcing the use of an X-Form (since swapped stores only have
17539 // X-Forms) without removing the swap is unprofitable.
17540 if (!SVN->hasOneUse())
17541 return SDValue();
17542
17543 SDLoc dl(LSBase);
17544 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
17545 LSBase->getBasePtr()};
17546 return DAG.getMemIntrinsicNode(
17547 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
17548 LSBase->getMemoryVT(), LSBase->getMemOperand());
17549 }
17550
17551 llvm_unreachable("Expected a load or store node here");
17552}
17553
17554static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) {
17555 unsigned IntrinsicID = Intrin.getConstantOperandVal(1);
17556 if (IntrinsicID == Intrinsic::ppc_stdcx)
17557 StoreWidth = 8;
17558 else if (IntrinsicID == Intrinsic::ppc_stwcx)
17559 StoreWidth = 4;
17560 else if (IntrinsicID == Intrinsic::ppc_sthcx)
17561 StoreWidth = 2;
17562 else if (IntrinsicID == Intrinsic::ppc_stbcx)
17563 StoreWidth = 1;
17564 else
17565 return false;
17566 return true;
17567}
17568
17571 if (N->getOpcode() == PPCISD::ADDC && N->hasAnyUseOfValue(1)) {
17572 // (ADDC (ADDE 0, 0, C), -1) -> C
17573 SDValue LHS = N->getOperand(0);
17574 SDValue RHS = N->getOperand(1);
17575 if (LHS->getOpcode() == PPCISD::ADDE &&
17576 isNullConstant(LHS->getOperand(0)) &&
17577 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
17578 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
17579 }
17580 }
17581 return SDValue();
17582}
17583
17586 if (N->getOpcode() == PPCISD::SUBE) {
17587 SDValue LHS = N->getOperand(0);
17588 SDValue RHS = N->getOperand(1);
17589 SDValue Carry = N->getOperand(2);
17590
17591 // SUBE(ADDC(ADDE(0, 0, C), -1), same, C) -> ADDC(ADDE(0, 0, C), -1)
17592 if (LHS == RHS && LHS.getOpcode() == PPCISD::ADDC) {
17593 SDValue AddcLHS = LHS.getOperand(0);
17594 SDValue AddcRHS = LHS.getOperand(1);
17595 if (AddcLHS.getOpcode() == PPCISD::ADDE &&
17596 isNullConstant(AddcLHS.getOperand(0)) &&
17597 isNullConstant(AddcLHS.getOperand(1)) && isAllOnesConstant(AddcRHS) &&
17598 Carry == AddcLHS.getOperand(2)) {
17599 return LHS;
17600 }
17601 }
17602 }
17603 return SDValue();
17604}
17605
17606/// Optimize the bitfloor(X) pattern for PowerPC.
17607/// Transforms: select_cc X, 0, 0, (srl MinSignedValue, (ctlz X)), seteq
17608/// Into: srl MinSignedValue, (ctlz X)
17609///
17610/// This is safe on PowerPC because the srw instruction returns 0 when the
17611/// shift amount is == bitwidth, which matches the behavior we need for X=0.
17613 if (N->getOpcode() != ISD::SELECT_CC)
17614 return SDValue();
17615
17616 // SELECT_CC operands: LHS, RHS, TrueVal, FalseVal, CC
17617 SDValue CmpLHS = N->getOperand(0);
17618 SDValue CmpRHS = N->getOperand(1);
17619 SDValue TrueVal = N->getOperand(2);
17620 SDValue FalseVal = N->getOperand(3);
17621 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
17622
17623 // Check if condition is (X == 0)
17624 if (CC != ISD::SETEQ || !isNullConstant(CmpRHS))
17625 return SDValue();
17626
17627 // Check if TrueVal is constant 0
17628 if (!isNullConstant(TrueVal))
17629 return SDValue();
17630
17631 // This combine is replacing a select_cc with a PPC srl, not an srl with a
17632 // PPC srl. If the original srl had multiple uses it would just remain in the
17633 // code. This is at most a performance consideration.
17634 if (FalseVal.getOpcode() != ISD::SRL || !FalseVal.hasOneUse())
17635 return SDValue();
17636
17637 SDValue ShiftVal = FalseVal.getOperand(0);
17638 SDValue ShiftAmt = FalseVal.getOperand(1);
17639
17640 // Check if ShiftVal is MinSignedValue
17641 auto *ShiftConst = dyn_cast<ConstantSDNode>(ShiftVal);
17642 if (!ShiftConst || !ShiftConst->getAPIntValue().isMinSignedValue())
17643 return SDValue();
17644
17645 SDValue CtlzArg;
17646 // Check if ShiftAmt is (ctlz CmpLHS) or (truncate (ctlz ...))
17647 if (ShiftAmt.getOpcode() != ISD::CTLZ) {
17648 // Look through truncate if present (for i64 ctlz truncated to i32 shift
17649 // amount)
17650 if (ShiftAmt.getOpcode() != ISD::TRUNCATE)
17651 return SDValue();
17652
17653 // Verify the truncate target type is appropriate for shift amount (i32, not
17654 // i1 or other)
17655 if (ShiftAmt.getValueType() != MVT::i32)
17656 return SDValue();
17657
17658 SDValue CtlzNode = ShiftAmt.getOperand(0);
17659
17660 if (CtlzNode.getOpcode() != ISD::CTLZ)
17661 return SDValue();
17662
17663 CtlzArg = CtlzNode.getOperand(0);
17664 } else {
17665 CtlzArg = ShiftAmt.getOperand(0);
17666 }
17667
17668 // Check if ctlz operates on the same value as the comparison
17669 if (CtlzArg != CmpLHS)
17670 return SDValue();
17671
17672 // Using PPCISD::SRL to ensure well-defined behavior.
17673 // On PowerPC, PPCISD::SRL guarantees that shift by bitwidth returns 0,
17674 // which is exactly what we need for the bitfloor(0) case.
17675 SDLoc DL(N);
17676 SDValue PPCSrl =
17677 DAG.getNode(PPCISD::SRL, DL, FalseVal.getValueType(), ShiftVal, ShiftAmt);
17678 return PPCSrl;
17679}
17680
17681// Optimize zero-extension of setcc when the compared value is known to be 0
17682// or 1.
17683//
17684// Pattern: zext(setcc(Value, 0, seteq/setne)) where Value is 0 or 1
17685// -> zext(xor(Value, 1)) for seteq
17686// -> zext(Value) for setne
17687//
17688// This optimization avoids the i32 -> i1 -> i32/i64 conversion sequence
17689// by keeping the value in its original i32 type throughout.
17690//
17691// Example:
17692// Before: zext(setcc(test_data_class(...), 0, seteq))
17693// // test_data_class returns 0 or 1 in i32
17694// // setcc converts i32 -> i1
17695// // zext converts i1 -> i64
17696// After: zext(xor(test_data_class(...), 1))
17697// // Stays in i32, then extends to i64
17698//
17699// This is beneficial because:
17700// 1. Eliminates the setcc instruction
17701// 2. Avoids i32 -> i1 truncation
17702// 3. Keeps computation in native integer width
17703
17705 // Check if this is a zero_extend
17706 if (N->getOpcode() != ISD::ZERO_EXTEND)
17707 return SDValue();
17708
17709 SDValue Src = N->getOperand(0);
17710
17711 // Check if the source is a setcc
17712 if (Src.getOpcode() != ISD::SETCC)
17713 return SDValue();
17714
17715 SDValue LHS = Src.getOperand(0);
17716 SDValue RHS = Src.getOperand(1);
17717 ISD::CondCode CC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
17718
17720 return SDValue();
17721
17722 SDValue NonNullConstant = isNullConstant(RHS) ? LHS : RHS;
17723
17724 auto isZeroOrOne = [=](SDValue &V) {
17725 if (V.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
17726 V.getConstantOperandVal(0) == Intrinsic::ppc_test_data_class)
17727 return true;
17728 return false;
17729 };
17730
17731 if (!isZeroOrOne(NonNullConstant))
17732 return SDValue();
17733
17734 // Check for pattern: zext(setcc (Value), 0, seteq)) or
17735 // zext(setcc (Value), 0, setne))
17736 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
17737 // Replace with: zext(xor(Value, 1)) for seteq
17738 // or: zext(Value) for setne
17739 // This keeps the value in i32 instead of converting to i1
17740 SDLoc DL(N);
17741 EVT VType = N->getValueType(0);
17742 SDValue NewNonNullConstant = DAG.getZExtOrTrunc(NonNullConstant, DL, VType);
17743
17744 if (CC == ISD::SETNE)
17745 return NewNonNullConstant;
17746
17747 SDValue One = DAG.getConstant(1, DL, VType);
17748 return DAG.getNode(ISD::XOR, DL, VType, NewNonNullConstant, One);
17749 }
17750
17751 return SDValue();
17752}
17753
17754// Combine XOR patterns with SELECT_CC_I4/I8, for Example:
17755// 1. XOR(SELECT_CC_I4(cond, 1, 0, cc), 1) -> SELECT_CC_I4(cond, 0, 1, cc)
17756// 2. XOR(ZEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond, 0,
17757// 1, cc))
17758// 3. XOR(ANYEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond,
17759// 0, 1, cc))
17760// 4. etc
17762 assert(N->getOpcode() == ISD::XOR && "Expected XOR node");
17763
17764 EVT XorVT = N->getValueType(0);
17765 if ((XorVT != MVT::i32 && XorVT != MVT::i64))
17766 return SDValue();
17767
17768 SDValue LHS = N->getOperand(0);
17769 SDValue RHS = N->getOperand(1);
17770
17771 // Check for XOR with constant 1
17773 if (!XorConst || !XorConst->isOne()) {
17774 XorConst = dyn_cast<ConstantSDNode>(LHS);
17775 if (!XorConst || !XorConst->isOne())
17776 return SDValue();
17777 // Swap so LHS is the SELECT_CC_I4 (or extension) and RHS is the constant
17778 std::swap(LHS, RHS);
17779 }
17780
17781 // Check if LHS has only one use
17782 if (!LHS.hasOneUse())
17783 return SDValue();
17784
17785 // Handle extensions: ZEXT, ANYEXT
17786 SDValue SelectNode = LHS;
17787
17788 if (LHS.getOpcode() == ISD::ZERO_EXTEND ||
17789 LHS.getOpcode() == ISD::ANY_EXTEND) {
17790 SelectNode = LHS.getOperand(0);
17791
17792 // Check if the extension input has only one use
17793 if (!SelectNode.hasOneUse())
17794 return SDValue();
17795 }
17796
17797 // Check if SelectNode is a MachineSDNode with SELECT_CC_I4/I8 opcode
17798 if (!SelectNode.isMachineOpcode())
17799 return SDValue();
17800
17801 unsigned MachineOpc = SelectNode.getMachineOpcode();
17802
17803 // Handle both SELECT_CC_I4 and SELECT_CC_I8
17804 if (MachineOpc != PPC::SELECT_CC_I4 && MachineOpc != PPC::SELECT_CC_I8)
17805 return SDValue();
17806
17807 // SELECT_CC_I4 operands: (cond, true_val, false_val, bropc)
17808 if (SelectNode.getNumOperands() != 4)
17809 return SDValue();
17810
17811 ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(1));
17812 ConstantSDNode *ConstOp2 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(2));
17813
17814 if (!ConstOp1 || !ConstOp2)
17815 return SDValue();
17816
17817 // Only optimize if operands are {0, 1} or {1, 0}
17818 if (!((ConstOp1->isOne() && ConstOp2->isZero()) ||
17819 (ConstOp1->isZero() && ConstOp2->isOne())))
17820 return SDValue();
17821
17822 // Pattern matched! Create new SELECT_CC with swapped 0/1 operands to
17823 // eliminate XOR. If original was SELECT_CC(cond, 1, 0, pred), create
17824 // SELECT_CC(cond, 0, 1, pred). If original was SELECT_CC(cond, 0, 1, pred),
17825 // create SELECT_CC(cond, 1, 0, pred).
17826 SDLoc DL(N);
17827 MachineOpc = (XorVT == MVT::i32) ? PPC::SELECT_CC_I4 : PPC::SELECT_CC_I8;
17828
17829 bool ConstOp1IsOne = ConstOp1->isOne();
17830 return SDValue(
17831 DAG.getMachineNode(MachineOpc, DL, XorVT,
17832 {SelectNode.getOperand(0),
17833 DAG.getConstant(ConstOp1IsOne ? 0 : 1, DL, XorVT),
17834 DAG.getConstant(ConstOp1IsOne ? 1 : 0, DL, XorVT),
17835 SelectNode.getOperand(3)}),
17836 0);
17837}
17838
17840 DAGCombinerInfo &DCI) const {
17841 SelectionDAG &DAG = DCI.DAG;
17842 SDLoc dl(N);
17843 switch (N->getOpcode()) {
17844 default: break;
17845 case ISD::ADD:
17846 return combineADD(N, DCI);
17847 case ISD::AND: {
17848 // We don't want (and (zext (shift...)), C) if C fits in the width of the
17849 // original input as that will prevent us from selecting optimal rotates.
17850 // This only matters if the input to the extend is i32 widened to i64.
17851 SDValue Op1 = N->getOperand(0);
17852 SDValue Op2 = N->getOperand(1);
17853 if ((Op1.getOpcode() != ISD::ZERO_EXTEND &&
17854 Op1.getOpcode() != ISD::ANY_EXTEND) ||
17855 !isa<ConstantSDNode>(Op2) || N->getValueType(0) != MVT::i64 ||
17856 Op1.getOperand(0).getValueType() != MVT::i32)
17857 break;
17858 SDValue NarrowOp = Op1.getOperand(0);
17859 if (NarrowOp.getOpcode() != ISD::SHL && NarrowOp.getOpcode() != ISD::SRL &&
17860 NarrowOp.getOpcode() != ISD::ROTL && NarrowOp.getOpcode() != ISD::ROTR)
17861 break;
17862
17863 uint64_t Imm = Op2->getAsZExtVal();
17864 // Make sure that the constant is narrow enough to fit in the narrow type.
17865 if (!isUInt<32>(Imm))
17866 break;
17867 SDValue ConstOp = DAG.getConstant(Imm, dl, MVT::i32);
17868 SDValue NarrowAnd = DAG.getNode(ISD::AND, dl, MVT::i32, NarrowOp, ConstOp);
17869 return DAG.getZExtOrTrunc(NarrowAnd, dl, N->getValueType(0));
17870 }
17871 case ISD::XOR: {
17872 // Optimize XOR(ISEL(1,0,CR), 1) -> ISEL(0,1,CR)
17873 if (SDValue V = combineXorSelectCC(N, DAG))
17874 return V;
17875 break;
17876 }
17877 case ISD::SHL:
17878 return combineSHL(N, DCI);
17879 case ISD::SRA:
17880 return combineSRA(N, DCI);
17881 case ISD::SRL:
17882 return combineSRL(N, DCI);
17883 case ISD::MUL:
17884 return combineMUL(N, DCI);
17885 case ISD::FMA:
17886 case PPCISD::FNMSUB:
17887 return combineFMALike(N, DCI);
17888 case PPCISD::SHL:
17889 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
17890 return N->getOperand(0);
17891 break;
17892 case PPCISD::SRL:
17893 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
17894 return N->getOperand(0);
17895 break;
17896 case PPCISD::SRA:
17897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
17898 if (C->isZero() || // 0 >>s V -> 0.
17899 C->isAllOnes()) // -1 >>s V -> -1.
17900 return N->getOperand(0);
17901 }
17902 break;
17903 case ISD::SIGN_EXTEND:
17904 if (SDValue SECC = combineSignExtendSetCC(N, DCI))
17905 return SECC;
17906 [[fallthrough]];
17907 case ISD::ZERO_EXTEND:
17908 if (SDValue RetV = combineZextSetccWithZero(N, DCI.DAG))
17909 return RetV;
17910 [[fallthrough]];
17911 case ISD::ANY_EXTEND:
17912 return DAGCombineExtBoolTrunc(N, DCI);
17913 case ISD::TRUNCATE:
17914 return combineTRUNCATE(N, DCI);
17915 case ISD::SETCC:
17916 if (SDValue CSCC = combineSetCC(N, DCI))
17917 return CSCC;
17918 [[fallthrough]];
17919 case ISD::SELECT_CC:
17920 if (SDValue V = combineSELECT_CCBitFloor(N, DAG))
17921 return V;
17922 return DAGCombineTruncBoolExt(N, DCI);
17923 case ISD::SINT_TO_FP:
17924 case ISD::UINT_TO_FP:
17925 return combineFPToIntToFP(N, DCI);
17927 if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
17928 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
17929 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
17930 }
17931 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
17932 case ISD::STORE: {
17933
17934 EVT Op1VT = N->getOperand(1).getValueType();
17935 unsigned Opcode = N->getOperand(1).getOpcode();
17936
17937 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
17938 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT) {
17939 SDValue Val = combineStoreFPToInt(N, DCI);
17940 if (Val)
17941 return Val;
17942 }
17943
17944 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
17945 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
17946 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
17947 if (Val)
17948 return Val;
17949 }
17950
17951 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
17952 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
17953 N->getOperand(1).getNode()->hasOneUse() &&
17954 (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
17955 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
17956
17957 // STBRX can only handle simple types and it makes no sense to store less
17958 // two bytes in byte-reversed order.
17959 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
17960 if (mVT.isExtended() || mVT.getSizeInBits() < 16)
17961 break;
17962
17963 SDValue BSwapOp = N->getOperand(1).getOperand(0);
17964 // Do an any-extend to 32-bits if this is a half-word input.
17965 if (BSwapOp.getValueType() == MVT::i16)
17966 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
17967
17968 // If the type of BSWAP operand is wider than stored memory width
17969 // it need to be shifted to the right side before STBRX.
17970 if (Op1VT.bitsGT(mVT)) {
17971 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
17972 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
17973 DAG.getConstant(Shift, dl, MVT::i32));
17974 // Need to truncate if this is a bswap of i64 stored as i32/i16.
17975 if (Op1VT == MVT::i64)
17976 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
17977 }
17978
17979 SDValue Ops[] = {
17980 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
17981 };
17982 return
17983 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
17984 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
17985 cast<StoreSDNode>(N)->getMemOperand());
17986 }
17987
17988 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
17989 // So it can increase the chance of CSE constant construction.
17990 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
17991 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
17992 // Need to sign-extended to 64-bits to handle negative values.
17993 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
17994 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
17995 MemVT.getSizeInBits());
17996 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
17997
17998 auto *ST = cast<StoreSDNode>(N);
17999 SDValue NewST = DAG.getStore(ST->getChain(), dl, Const64,
18000 ST->getBasePtr(), ST->getOffset(), MemVT,
18001 ST->getMemOperand(), ST->getAddressingMode(),
18002 /*IsTruncating=*/true);
18003 // Note we use CombineTo here to prevent DAGCombiner from visiting the
18004 // new store which will change the constant by removing non-demanded bits.
18005 return ST->isUnindexed()
18006 ? DCI.CombineTo(N, NewST, /*AddTo=*/false)
18007 : DCI.CombineTo(N, NewST, NewST.getValue(1), /*AddTo=*/false);
18008 }
18009
18010 // For little endian, VSX stores require generating xxswapd/lxvd2x.
18011 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18012 if (Op1VT.isSimple()) {
18013 MVT StoreVT = Op1VT.getSimpleVT();
18014 if (Subtarget.needsSwapsForVSXMemOps() &&
18015 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
18016 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
18017 return expandVSXStoreForLE(N, DCI);
18018 }
18019 break;
18020 }
18021 case ISD::LOAD: {
18023 EVT VT = LD->getValueType(0);
18024
18025 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18026 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18027 if (VT.isSimple()) {
18028 MVT LoadVT = VT.getSimpleVT();
18029 if (Subtarget.needsSwapsForVSXMemOps() &&
18030 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
18031 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
18032 return expandVSXLoadForLE(N, DCI);
18033 }
18034
18035 // We sometimes end up with a 64-bit integer load, from which we extract
18036 // two single-precision floating-point numbers. This happens with
18037 // std::complex<float>, and other similar structures, because of the way we
18038 // canonicalize structure copies. However, if we lack direct moves,
18039 // then the final bitcasts from the extracted integer values to the
18040 // floating-point numbers turn into store/load pairs. Even with direct moves,
18041 // just loading the two floating-point numbers is likely better.
18042 auto ReplaceTwoFloatLoad = [&]() {
18043 if (VT != MVT::i64)
18044 return false;
18045
18046 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
18047 LD->isVolatile())
18048 return false;
18049
18050 // We're looking for a sequence like this:
18051 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
18052 // t16: i64 = srl t13, Constant:i32<32>
18053 // t17: i32 = truncate t16
18054 // t18: f32 = bitcast t17
18055 // t19: i32 = truncate t13
18056 // t20: f32 = bitcast t19
18057
18058 if (!LD->hasNUsesOfValue(2, 0))
18059 return false;
18060
18061 auto UI = LD->user_begin();
18062 while (UI.getUse().getResNo() != 0) ++UI;
18063 SDNode *Trunc = *UI++;
18064 while (UI.getUse().getResNo() != 0) ++UI;
18065 SDNode *RightShift = *UI;
18066 if (Trunc->getOpcode() != ISD::TRUNCATE)
18067 std::swap(Trunc, RightShift);
18068
18069 if (Trunc->getOpcode() != ISD::TRUNCATE ||
18070 Trunc->getValueType(0) != MVT::i32 ||
18071 !Trunc->hasOneUse())
18072 return false;
18073 if (RightShift->getOpcode() != ISD::SRL ||
18074 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
18075 RightShift->getConstantOperandVal(1) != 32 ||
18076 !RightShift->hasOneUse())
18077 return false;
18078
18079 SDNode *Trunc2 = *RightShift->user_begin();
18080 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
18081 Trunc2->getValueType(0) != MVT::i32 ||
18082 !Trunc2->hasOneUse())
18083 return false;
18084
18085 SDNode *Bitcast = *Trunc->user_begin();
18086 SDNode *Bitcast2 = *Trunc2->user_begin();
18087
18088 if (Bitcast->getOpcode() != ISD::BITCAST ||
18089 Bitcast->getValueType(0) != MVT::f32)
18090 return false;
18091 if (Bitcast2->getOpcode() != ISD::BITCAST ||
18092 Bitcast2->getValueType(0) != MVT::f32)
18093 return false;
18094
18095 if (Subtarget.isLittleEndian())
18096 std::swap(Bitcast, Bitcast2);
18097
18098 // Bitcast has the second float (in memory-layout order) and Bitcast2
18099 // has the first one.
18100
18101 SDValue BasePtr = LD->getBasePtr();
18102 if (LD->isIndexed()) {
18103 assert(LD->getAddressingMode() == ISD::PRE_INC &&
18104 "Non-pre-inc AM on PPC?");
18105 BasePtr =
18106 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18107 LD->getOffset());
18108 }
18109
18110 auto MMOFlags =
18111 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
18112 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
18113 LD->getPointerInfo(), LD->getAlign(),
18114 MMOFlags, LD->getAAInfo());
18115 SDValue AddPtr =
18116 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
18117 BasePtr, DAG.getIntPtrConstant(4, dl));
18118 SDValue FloatLoad2 = DAG.getLoad(
18119 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
18120 LD->getPointerInfo().getWithOffset(4),
18121 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo());
18122
18123 if (LD->isIndexed()) {
18124 // Note that DAGCombine should re-form any pre-increment load(s) from
18125 // what is produced here if that makes sense.
18126 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
18127 }
18128
18129 DCI.CombineTo(Bitcast2, FloatLoad);
18130 DCI.CombineTo(Bitcast, FloatLoad2);
18131
18132 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
18133 SDValue(FloatLoad2.getNode(), 1));
18134 return true;
18135 };
18136
18137 if (ReplaceTwoFloatLoad())
18138 return SDValue(N, 0);
18139
18140 EVT MemVT = LD->getMemoryVT();
18141 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
18142 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
18143 if (LD->isUnindexed() && VT.isVector() &&
18144 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
18145 // P8 and later hardware should just use LOAD.
18146 !Subtarget.hasP8Vector() &&
18147 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
18148 VT == MVT::v4f32))) &&
18149 LD->getAlign() < ABIAlignment) {
18150 // This is a type-legal unaligned Altivec load.
18151 SDValue Chain = LD->getChain();
18152 SDValue Ptr = LD->getBasePtr();
18153 bool isLittleEndian = Subtarget.isLittleEndian();
18154
18155 // This implements the loading of unaligned vectors as described in
18156 // the venerable Apple Velocity Engine overview. Specifically:
18157 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
18158 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
18159 //
18160 // The general idea is to expand a sequence of one or more unaligned
18161 // loads into an alignment-based permutation-control instruction (lvsl
18162 // or lvsr), a series of regular vector loads (which always truncate
18163 // their input address to an aligned address), and a series of
18164 // permutations. The results of these permutations are the requested
18165 // loaded values. The trick is that the last "extra" load is not taken
18166 // from the address you might suspect (sizeof(vector) bytes after the
18167 // last requested load), but rather sizeof(vector) - 1 bytes after the
18168 // last requested vector. The point of this is to avoid a page fault if
18169 // the base address happened to be aligned. This works because if the
18170 // base address is aligned, then adding less than a full vector length
18171 // will cause the last vector in the sequence to be (re)loaded.
18172 // Otherwise, the next vector will be fetched as you might suspect was
18173 // necessary.
18174
18175 // We might be able to reuse the permutation generation from
18176 // a different base address offset from this one by an aligned amount.
18177 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
18178 // optimization later.
18179 Intrinsic::ID Intr, IntrLD, IntrPerm;
18180 MVT PermCntlTy, PermTy, LDTy;
18181 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18182 : Intrinsic::ppc_altivec_lvsl;
18183 IntrLD = Intrinsic::ppc_altivec_lvx;
18184 IntrPerm = Intrinsic::ppc_altivec_vperm;
18185 PermCntlTy = MVT::v16i8;
18186 PermTy = MVT::v4i32;
18187 LDTy = MVT::v4i32;
18188
18189 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
18190
18191 // Create the new MMO for the new base load. It is like the original MMO,
18192 // but represents an area in memory almost twice the vector size centered
18193 // on the original address. If the address is unaligned, we might start
18194 // reading up to (sizeof(vector)-1) bytes below the address of the
18195 // original unaligned load.
18197 MachineMemOperand *BaseMMO =
18198 MF.getMachineMemOperand(LD->getMemOperand(),
18199 -(int64_t)MemVT.getStoreSize()+1,
18200 2*MemVT.getStoreSize()-1);
18201
18202 // Create the new base load.
18203 SDValue LDXIntID =
18204 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
18205 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
18206 SDValue BaseLoad =
18208 DAG.getVTList(PermTy, MVT::Other),
18209 BaseLoadOps, LDTy, BaseMMO);
18210
18211 // Note that the value of IncOffset (which is provided to the next
18212 // load's pointer info offset value, and thus used to calculate the
18213 // alignment), and the value of IncValue (which is actually used to
18214 // increment the pointer value) are different! This is because we
18215 // require the next load to appear to be aligned, even though it
18216 // is actually offset from the base pointer by a lesser amount.
18217 int IncOffset = VT.getSizeInBits() / 8;
18218 int IncValue = IncOffset;
18219
18220 // Walk (both up and down) the chain looking for another load at the real
18221 // (aligned) offset (the alignment of the other load does not matter in
18222 // this case). If found, then do not use the offset reduction trick, as
18223 // that will prevent the loads from being later combined (as they would
18224 // otherwise be duplicates).
18225 if (!findConsecutiveLoad(LD, DAG))
18226 --IncValue;
18227
18229 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
18230 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18231
18232 MachineMemOperand *ExtraMMO =
18233 MF.getMachineMemOperand(LD->getMemOperand(),
18234 1, 2*MemVT.getStoreSize()-1);
18235 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
18236 SDValue ExtraLoad =
18238 DAG.getVTList(PermTy, MVT::Other),
18239 ExtraLoadOps, LDTy, ExtraMMO);
18240
18241 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18242 BaseLoad.getValue(1), ExtraLoad.getValue(1));
18243
18244 // Because vperm has a big-endian bias, we must reverse the order
18245 // of the input vectors and complement the permute control vector
18246 // when generating little endian code. We have already handled the
18247 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
18248 // and ExtraLoad here.
18249 SDValue Perm;
18250 if (isLittleEndian)
18251 Perm = BuildIntrinsicOp(IntrPerm,
18252 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
18253 else
18254 Perm = BuildIntrinsicOp(IntrPerm,
18255 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
18256
18257 if (VT != PermTy)
18258 Perm = Subtarget.hasAltivec()
18259 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
18260 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
18261 DAG.getTargetConstant(1, dl, MVT::i64));
18262 // second argument is 1 because this rounding
18263 // is always exact.
18264
18265 // The output of the permutation is our loaded result, the TokenFactor is
18266 // our new chain.
18267 DCI.CombineTo(N, Perm, TF);
18268 return SDValue(N, 0);
18269 }
18270 }
18271 break;
18273 bool isLittleEndian = Subtarget.isLittleEndian();
18274 unsigned IID = N->getConstantOperandVal(0);
18275 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18276 : Intrinsic::ppc_altivec_lvsl);
18277 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
18278 SDValue Add = N->getOperand(1);
18279
18280 int Bits = 4 /* 16 byte alignment */;
18281
18282 if (DAG.MaskedValueIsZero(Add->getOperand(1),
18283 APInt::getAllOnes(Bits /* alignment */)
18284 .zext(Add.getScalarValueSizeInBits()))) {
18285 SDNode *BasePtr = Add->getOperand(0).getNode();
18286 for (SDNode *U : BasePtr->users()) {
18287 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18288 U->getConstantOperandVal(0) == IID) {
18289 // We've found another LVSL/LVSR, and this address is an aligned
18290 // multiple of that one. The results will be the same, so use the
18291 // one we've just found instead.
18292
18293 return SDValue(U, 0);
18294 }
18295 }
18296 }
18297
18298 if (isa<ConstantSDNode>(Add->getOperand(1))) {
18299 SDNode *BasePtr = Add->getOperand(0).getNode();
18300 for (SDNode *U : BasePtr->users()) {
18301 if (U->getOpcode() == ISD::ADD &&
18302 isa<ConstantSDNode>(U->getOperand(1)) &&
18303 (Add->getConstantOperandVal(1) - U->getConstantOperandVal(1)) %
18304 (1ULL << Bits) ==
18305 0) {
18306 SDNode *OtherAdd = U;
18307 for (SDNode *V : OtherAdd->users()) {
18308 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18309 V->getConstantOperandVal(0) == IID) {
18310 return SDValue(V, 0);
18311 }
18312 }
18313 }
18314 }
18315 }
18316 }
18317
18318 // Combine vmaxsw/h/b(a, a's negation) to abs(a)
18319 // Expose the vabsduw/h/b opportunity for down stream
18320 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
18321 (IID == Intrinsic::ppc_altivec_vmaxsw ||
18322 IID == Intrinsic::ppc_altivec_vmaxsh ||
18323 IID == Intrinsic::ppc_altivec_vmaxsb)) {
18324 SDValue V1 = N->getOperand(1);
18325 SDValue V2 = N->getOperand(2);
18326 if ((V1.getSimpleValueType() == MVT::v4i32 ||
18327 V1.getSimpleValueType() == MVT::v8i16 ||
18328 V1.getSimpleValueType() == MVT::v16i8) &&
18329 V1.getSimpleValueType() == V2.getSimpleValueType()) {
18330 // (0-a, a)
18331 if (V1.getOpcode() == ISD::SUB &&
18332 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
18333 V1.getOperand(1) == V2) {
18334 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
18335 }
18336 // (a, 0-a)
18337 if (V2.getOpcode() == ISD::SUB &&
18339 V2.getOperand(1) == V1) {
18340 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18341 }
18342 // (x-y, y-x)
18343 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
18344 V1.getOperand(0) == V2.getOperand(1) &&
18345 V1.getOperand(1) == V2.getOperand(0)) {
18346 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18347 }
18348 }
18349 }
18350 }
18351
18352 break;
18354 switch (N->getConstantOperandVal(1)) {
18355 default:
18356 break;
18357 case Intrinsic::ppc_altivec_vsum4sbs:
18358 case Intrinsic::ppc_altivec_vsum4shs:
18359 case Intrinsic::ppc_altivec_vsum4ubs: {
18360 // These sum-across intrinsics only have a chain due to the side effect
18361 // that they may set the SAT bit. If we know the SAT bit will not be set
18362 // for some inputs, we can replace any uses of their chain with the
18363 // input chain.
18364 if (BuildVectorSDNode *BVN =
18365 dyn_cast<BuildVectorSDNode>(N->getOperand(3))) {
18366 APInt APSplatBits, APSplatUndef;
18367 unsigned SplatBitSize;
18368 bool HasAnyUndefs;
18369 bool BVNIsConstantSplat = BVN->isConstantSplat(
18370 APSplatBits, APSplatUndef, SplatBitSize, HasAnyUndefs, 0,
18371 !Subtarget.isLittleEndian());
18372 // If the constant splat vector is 0, the SAT bit will not be set.
18373 if (BVNIsConstantSplat && APSplatBits == 0)
18374 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), N->getOperand(0));
18375 }
18376 return SDValue();
18377 }
18378 case Intrinsic::ppc_vsx_lxvw4x:
18379 case Intrinsic::ppc_vsx_lxvd2x:
18380 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18381 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18382 if (Subtarget.needsSwapsForVSXMemOps())
18383 return expandVSXLoadForLE(N, DCI);
18384 break;
18385 }
18386 break;
18388 // For little endian, VSX stores require generating xxswapd/stxvd2x.
18389 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18390 if (Subtarget.needsSwapsForVSXMemOps()) {
18391 switch (N->getConstantOperandVal(1)) {
18392 default:
18393 break;
18394 case Intrinsic::ppc_vsx_stxvw4x:
18395 case Intrinsic::ppc_vsx_stxvd2x:
18396 return expandVSXStoreForLE(N, DCI);
18397 }
18398 }
18399 break;
18400 case ISD::BSWAP: {
18401 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
18402 // For subtargets without LDBRX, we can still do better than the default
18403 // expansion even for 64-bit BSWAP (LOAD).
18404 bool Is64BitBswapOn64BitTgt =
18405 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
18406 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
18407 N->getOperand(0).hasOneUse();
18408 if (IsSingleUseNormalLd &&
18409 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
18410 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
18411 SDValue Load = N->getOperand(0);
18413 // Create the byte-swapping load.
18414 SDValue Ops[] = {
18415 LD->getChain(), // Chain
18416 LD->getBasePtr(), // Ptr
18417 DAG.getValueType(N->getValueType(0)) // VT
18418 };
18419 SDValue BSLoad =
18420 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
18421 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
18422 MVT::i64 : MVT::i32, MVT::Other),
18423 Ops, LD->getMemoryVT(), LD->getMemOperand());
18424
18425 // If this is an i16 load, insert the truncate.
18426 SDValue ResVal = BSLoad;
18427 if (N->getValueType(0) == MVT::i16)
18428 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
18429
18430 // First, combine the bswap away. This makes the value produced by the
18431 // load dead.
18432 DCI.CombineTo(N, ResVal);
18433
18434 // Next, combine the load away, we give it a bogus result value but a real
18435 // chain result. The result value is dead because the bswap is dead.
18436 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
18437
18438 // Return N so it doesn't get rechecked!
18439 return SDValue(N, 0);
18440 }
18441 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
18442 // before legalization so that the BUILD_PAIR is handled correctly.
18443 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
18444 !IsSingleUseNormalLd)
18445 return SDValue();
18446 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
18447
18448 // Can't split volatile or atomic loads.
18449 if (!LD->isSimple())
18450 return SDValue();
18451 SDValue BasePtr = LD->getBasePtr();
18452 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
18453 LD->getPointerInfo(), LD->getAlign());
18454 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
18455 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18456 DAG.getIntPtrConstant(4, dl));
18458 LD->getMemOperand(), 4, 4);
18459 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
18460 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
18461 SDValue Res;
18462 if (Subtarget.isLittleEndian())
18463 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
18464 else
18465 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
18466 SDValue TF =
18467 DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18468 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
18469 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
18470 return Res;
18471 }
18472 case PPCISD::VCMP:
18473 // If a VCMP_rec node already exists with exactly the same operands as this
18474 // node, use its result instead of this node (VCMP_rec computes both a CR6
18475 // and a normal output).
18476 //
18477 if (!N->getOperand(0).hasOneUse() &&
18478 !N->getOperand(1).hasOneUse() &&
18479 !N->getOperand(2).hasOneUse()) {
18480
18481 // Scan all of the users of the LHS, looking for VCMP_rec's that match.
18482 SDNode *VCMPrecNode = nullptr;
18483
18484 SDNode *LHSN = N->getOperand(0).getNode();
18485 for (SDNode *User : LHSN->users())
18486 if (User->getOpcode() == PPCISD::VCMP_rec &&
18487 User->getOperand(1) == N->getOperand(1) &&
18488 User->getOperand(2) == N->getOperand(2) &&
18489 User->getOperand(0) == N->getOperand(0)) {
18490 VCMPrecNode = User;
18491 break;
18492 }
18493
18494 // If there is no VCMP_rec node, or if the flag value has a single use,
18495 // don't transform this.
18496 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
18497 break;
18498
18499 // Look at the (necessarily single) use of the flag value. If it has a
18500 // chain, this transformation is more complex. Note that multiple things
18501 // could use the value result, which we should ignore.
18502 SDNode *FlagUser = nullptr;
18503 for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
18504 FlagUser == nullptr; ++UI) {
18505 assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
18506 SDNode *User = UI->getUser();
18507 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
18508 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
18509 FlagUser = User;
18510 break;
18511 }
18512 }
18513 }
18514
18515 // If the user is a MFOCRF instruction, we know this is safe.
18516 // Otherwise we give up for right now.
18517 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
18518 return SDValue(VCMPrecNode, 0);
18519 }
18520 break;
18521 case ISD::BR_CC: {
18522 // If this is a branch on an altivec predicate comparison, lower this so
18523 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
18524 // lowering is done pre-legalize, because the legalizer lowers the predicate
18525 // compare down to code that is difficult to reassemble.
18526 // This code also handles branches that depend on the result of a store
18527 // conditional.
18528 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18529 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
18530
18531 int CompareOpc;
18532 bool isDot;
18533
18534 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE))
18535 break;
18536
18537 // Since we are doing this pre-legalize, the RHS can be a constant of
18538 // arbitrary bitwidth which may cause issues when trying to get the value
18539 // from the underlying APInt.
18540 auto RHSAPInt = RHS->getAsAPIntVal();
18541 if (!RHSAPInt.isIntN(64))
18542 break;
18543
18544 unsigned Val = RHSAPInt.getZExtValue();
18545 auto isImpossibleCompare = [&]() {
18546 // If this is a comparison against something other than 0/1, then we know
18547 // that the condition is never/always true.
18548 if (Val != 0 && Val != 1) {
18549 if (CC == ISD::SETEQ) // Cond never true, remove branch.
18550 return N->getOperand(0);
18551 // Always !=, turn it into an unconditional branch.
18552 return DAG.getNode(ISD::BR, dl, MVT::Other,
18553 N->getOperand(0), N->getOperand(4));
18554 }
18555 return SDValue();
18556 };
18557 // Combine branches fed by store conditional instructions (st[bhwd]cx).
18558 unsigned StoreWidth = 0;
18559 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
18560 isStoreConditional(LHS, StoreWidth)) {
18561 if (SDValue Impossible = isImpossibleCompare())
18562 return Impossible;
18563 PPC::Predicate CompOpc;
18564 // eq 0 => ne
18565 // ne 0 => eq
18566 // eq 1 => eq
18567 // ne 1 => ne
18568 if (Val == 0)
18569 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ;
18570 else
18571 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE;
18572
18573 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3),
18574 DAG.getConstant(StoreWidth, dl, MVT::i32)};
18575 auto *MemNode = cast<MemSDNode>(LHS);
18576 SDValue ConstSt = DAG.getMemIntrinsicNode(
18577 PPCISD::STORE_COND, dl,
18578 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops,
18579 MemNode->getMemoryVT(), MemNode->getMemOperand());
18580
18581 SDValue InChain;
18582 // Unchain the branch from the original store conditional.
18583 if (N->getOperand(0) == LHS.getValue(1))
18584 InChain = LHS.getOperand(0);
18585 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) {
18586 SmallVector<SDValue, 4> InChains;
18587 SDValue InTF = N->getOperand(0);
18588 for (int i = 0, e = InTF.getNumOperands(); i < e; i++)
18589 if (InTF.getOperand(i) != LHS.getValue(1))
18590 InChains.push_back(InTF.getOperand(i));
18591 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains);
18592 }
18593
18594 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain,
18595 DAG.getConstant(CompOpc, dl, MVT::i32),
18596 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4),
18597 ConstSt.getValue(2));
18598 }
18599
18600 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18601 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
18602 assert(isDot && "Can't compare against a vector result!");
18603
18604 if (SDValue Impossible = isImpossibleCompare())
18605 return Impossible;
18606
18607 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
18608 // Create the PPCISD altivec 'dot' comparison node.
18609 SDValue Ops[] = {
18610 LHS.getOperand(2), // LHS of compare
18611 LHS.getOperand(3), // RHS of compare
18612 DAG.getConstant(CompareOpc, dl, MVT::i32)
18613 };
18614 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
18615 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
18616
18617 // Unpack the result based on how the target uses it.
18618 PPC::Predicate CompOpc;
18619 switch (LHS.getConstantOperandVal(1)) {
18620 default: // Can't happen, don't crash on invalid number though.
18621 case 0: // Branch on the value of the EQ bit of CR6.
18622 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
18623 break;
18624 case 1: // Branch on the inverted value of the EQ bit of CR6.
18625 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
18626 break;
18627 case 2: // Branch on the value of the LT bit of CR6.
18628 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
18629 break;
18630 case 3: // Branch on the inverted value of the LT bit of CR6.
18631 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
18632 break;
18633 }
18634
18635 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
18636 DAG.getConstant(CompOpc, dl, MVT::i32),
18637 DAG.getRegister(PPC::CR6, MVT::i32),
18638 N->getOperand(4), CompNode.getValue(1));
18639 }
18640 break;
18641 }
18642 case ISD::BUILD_VECTOR:
18643 return DAGCombineBuildVector(N, DCI);
18644 case PPCISD::ADDC:
18645 return DAGCombineAddc(N, DCI);
18646 case PPCISD::SUBE:
18647 return DAGCombineSube(N, DCI);
18648
18649 case ISD::BITCAST:
18650 return DAGCombineBitcast(N, DCI);
18651 }
18652
18653 return SDValue();
18654}
18655
18656SDValue
18658 SelectionDAG &DAG,
18659 SmallVectorImpl<SDNode *> &Created) const {
18660 // fold (sdiv X, pow2)
18661 EVT VT = N->getValueType(0);
18662 if (VT == MVT::i64 && !Subtarget.isPPC64())
18663 return SDValue();
18664 if ((VT != MVT::i32 && VT != MVT::i64) ||
18665 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
18666 return SDValue();
18667
18668 SDLoc DL(N);
18669 SDValue N0 = N->getOperand(0);
18670
18671 bool IsNegPow2 = Divisor.isNegatedPowerOf2();
18672 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countr_zero();
18673 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
18674
18675 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
18676 Created.push_back(Op.getNode());
18677
18678 if (IsNegPow2) {
18679 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
18680 Created.push_back(Op.getNode());
18681 }
18682
18683 return Op;
18684}
18685
18686//===----------------------------------------------------------------------===//
18687// Inline Assembly Support
18688//===----------------------------------------------------------------------===//
18689
18692 const APInt &DemandedElts,
18693 const SelectionDAG &DAG,
18694 unsigned Depth) const {
18695 Known.resetAll();
18696 switch (Op.getOpcode()) {
18697 default: break;
18698 case PPCISD::LBRX: {
18699 // lhbrx is known to have the top bits cleared out.
18700 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
18701 Known.Zero = 0xFFFF0000;
18702 break;
18703 }
18704 case PPCISD::ADDE: {
18705 if (Op.getResNo() == 0) {
18706 // (0|1), _ = ADDE 0, 0, CARRY
18707 SDValue LHS = Op.getOperand(0);
18708 SDValue RHS = Op.getOperand(1);
18709 if (isNullConstant(LHS) && isNullConstant(RHS))
18710 Known.Zero = ~1ULL;
18711 }
18712 break;
18713 }
18715 switch (Op.getConstantOperandVal(0)) {
18716 default: break;
18717 case Intrinsic::ppc_altivec_vcmpbfp_p:
18718 case Intrinsic::ppc_altivec_vcmpeqfp_p:
18719 case Intrinsic::ppc_altivec_vcmpequb_p:
18720 case Intrinsic::ppc_altivec_vcmpequh_p:
18721 case Intrinsic::ppc_altivec_vcmpequw_p:
18722 case Intrinsic::ppc_altivec_vcmpequd_p:
18723 case Intrinsic::ppc_altivec_vcmpequq_p:
18724 case Intrinsic::ppc_altivec_vcmpgefp_p:
18725 case Intrinsic::ppc_altivec_vcmpgtfp_p:
18726 case Intrinsic::ppc_altivec_vcmpgtsb_p:
18727 case Intrinsic::ppc_altivec_vcmpgtsh_p:
18728 case Intrinsic::ppc_altivec_vcmpgtsw_p:
18729 case Intrinsic::ppc_altivec_vcmpgtsd_p:
18730 case Intrinsic::ppc_altivec_vcmpgtsq_p:
18731 case Intrinsic::ppc_altivec_vcmpgtub_p:
18732 case Intrinsic::ppc_altivec_vcmpgtuh_p:
18733 case Intrinsic::ppc_altivec_vcmpgtuw_p:
18734 case Intrinsic::ppc_altivec_vcmpgtud_p:
18735 case Intrinsic::ppc_altivec_vcmpgtuq_p:
18736 Known.Zero = ~1U; // All bits but the low one are known to be zero.
18737 break;
18738 }
18739 break;
18740 }
18742 switch (Op.getConstantOperandVal(1)) {
18743 default:
18744 break;
18745 case Intrinsic::ppc_load2r:
18746 // Top bits are cleared for load2r (which is the same as lhbrx).
18747 Known.Zero = 0xFFFF0000;
18748 break;
18749 }
18750 break;
18751 }
18752 }
18753}
18754
18756 switch (Subtarget.getCPUDirective()) {
18757 default: break;
18758 case PPC::DIR_970:
18759 case PPC::DIR_PWR4:
18760 case PPC::DIR_PWR5:
18761 case PPC::DIR_PWR5X:
18762 case PPC::DIR_PWR6:
18763 case PPC::DIR_PWR6X:
18764 case PPC::DIR_PWR7:
18765 case PPC::DIR_PWR8:
18766 case PPC::DIR_PWR9:
18767 case PPC::DIR_PWR10:
18768 case PPC::DIR_PWR11:
18769 case PPC::DIR_PWR_FUTURE: {
18770 if (!ML)
18771 break;
18772
18774 // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
18775 // so that we can decrease cache misses and branch-prediction misses.
18776 // Actual alignment of the loop will depend on the hotness check and other
18777 // logic in alignBlocks.
18778 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
18779 return Align(32);
18780 }
18781
18782 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
18783
18784 // For small loops (between 5 and 8 instructions), align to a 32-byte
18785 // boundary so that the entire loop fits in one instruction-cache line.
18786 uint64_t LoopSize = 0;
18787 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
18788 for (const MachineInstr &J : **I) {
18789 LoopSize += TII->getInstSizeInBytes(J);
18790 if (LoopSize > 32)
18791 break;
18792 }
18793
18794 if (LoopSize > 16 && LoopSize <= 32)
18795 return Align(32);
18796
18797 break;
18798 }
18799 }
18800
18802}
18803
18804/// getConstraintType - Given a constraint, return the type of
18805/// constraint it is for this target.
18808 if (Constraint.size() == 1) {
18809 switch (Constraint[0]) {
18810 default: break;
18811 case 'b':
18812 case 'r':
18813 case 'f':
18814 case 'd':
18815 case 'v':
18816 case 'y':
18817 return C_RegisterClass;
18818 case 'Z':
18819 // FIXME: While Z does indicate a memory constraint, it specifically
18820 // indicates an r+r address (used in conjunction with the 'y' modifier
18821 // in the replacement string). Currently, we're forcing the base
18822 // register to be r0 in the asm printer (which is interpreted as zero)
18823 // and forming the complete address in the second register. This is
18824 // suboptimal.
18825 return C_Memory;
18826 }
18827 } else if (Constraint == "wc") { // individual CR bits.
18828 return C_RegisterClass;
18829 } else if (Constraint == "wa" || Constraint == "wd" ||
18830 Constraint == "wf" || Constraint == "ws" ||
18831 Constraint == "wi" || Constraint == "ww") {
18832 return C_RegisterClass; // VSX registers.
18833 }
18834 return TargetLowering::getConstraintType(Constraint);
18835}
18836
18837/// Examine constraint type and operand type and determine a weight value.
18838/// This object must already have been set up with the operand type
18839/// and the current alternative constraint selected.
18842 AsmOperandInfo &info, const char *constraint) const {
18844 Value *CallOperandVal = info.CallOperandVal;
18845 // If we don't have a value, we can't do a match,
18846 // but allow it at the lowest weight.
18847 if (!CallOperandVal)
18848 return CW_Default;
18849 Type *type = CallOperandVal->getType();
18850
18851 // Look at the constraint type.
18852 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
18853 return CW_Register; // an individual CR bit.
18854 else if ((StringRef(constraint) == "wa" ||
18855 StringRef(constraint) == "wd" ||
18856 StringRef(constraint) == "wf") &&
18857 type->isVectorTy())
18858 return CW_Register;
18859 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
18860 return CW_Register; // just hold 64-bit integers data.
18861 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
18862 return CW_Register;
18863 else if (StringRef(constraint) == "ww" && type->isFloatTy())
18864 return CW_Register;
18865
18866 switch (*constraint) {
18867 default:
18869 break;
18870 case 'b':
18871 if (type->isIntegerTy())
18872 weight = CW_Register;
18873 break;
18874 case 'f':
18875 if (type->isFloatTy())
18876 weight = CW_Register;
18877 break;
18878 case 'd':
18879 if (type->isDoubleTy())
18880 weight = CW_Register;
18881 break;
18882 case 'v':
18883 if (type->isVectorTy())
18884 weight = CW_Register;
18885 break;
18886 case 'y':
18887 weight = CW_Register;
18888 break;
18889 case 'Z':
18890 weight = CW_Memory;
18891 break;
18892 }
18893 return weight;
18894}
18895
18896std::pair<unsigned, const TargetRegisterClass *>
18898 StringRef Constraint,
18899 MVT VT) const {
18900 if (Constraint.size() == 1) {
18901 // GCC RS6000 Constraint Letters
18902 switch (Constraint[0]) {
18903 case 'b': // R1-R31
18904 if (VT == MVT::i64 && Subtarget.isPPC64())
18905 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
18906 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
18907 case 'r': // R0-R31
18908 if (VT == MVT::i64 && Subtarget.isPPC64())
18909 return std::make_pair(0U, &PPC::G8RCRegClass);
18910 return std::make_pair(0U, &PPC::GPRCRegClass);
18911 // 'd' and 'f' constraints are both defined to be "the floating point
18912 // registers", where one is for 32-bit and the other for 64-bit. We don't
18913 // really care overly much here so just give them all the same reg classes.
18914 case 'd':
18915 case 'f':
18916 if (Subtarget.hasSPE()) {
18917 if (VT == MVT::f32 || VT == MVT::i32)
18918 return std::make_pair(0U, &PPC::GPRCRegClass);
18919 if (VT == MVT::f64 || VT == MVT::i64)
18920 return std::make_pair(0U, &PPC::SPERCRegClass);
18921 } else {
18922 if (VT == MVT::f32 || VT == MVT::i32)
18923 return std::make_pair(0U, &PPC::F4RCRegClass);
18924 if (VT == MVT::f64 || VT == MVT::i64)
18925 return std::make_pair(0U, &PPC::F8RCRegClass);
18926 }
18927 break;
18928 case 'v':
18929 if (Subtarget.hasAltivec() && VT.isVector())
18930 return std::make_pair(0U, &PPC::VRRCRegClass);
18931 else if (Subtarget.hasVSX())
18932 // Scalars in Altivec registers only make sense with VSX.
18933 return std::make_pair(0U, &PPC::VFRCRegClass);
18934 break;
18935 case 'y': // crrc
18936 return std::make_pair(0U, &PPC::CRRCRegClass);
18937 }
18938 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
18939 // An individual CR bit.
18940 return std::make_pair(0U, &PPC::CRBITRCRegClass);
18941 } else if ((Constraint == "wa" || Constraint == "wd" ||
18942 Constraint == "wf" || Constraint == "wi") &&
18943 Subtarget.hasVSX()) {
18944 // A VSX register for either a scalar (FP) or vector. There is no
18945 // support for single precision scalars on subtargets prior to Power8.
18946 if (VT.isVector())
18947 return std::make_pair(0U, &PPC::VSRCRegClass);
18948 if (VT == MVT::f32 && Subtarget.hasP8Vector())
18949 return std::make_pair(0U, &PPC::VSSRCRegClass);
18950 return std::make_pair(0U, &PPC::VSFRCRegClass);
18951 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
18952 if (VT == MVT::f32 && Subtarget.hasP8Vector())
18953 return std::make_pair(0U, &PPC::VSSRCRegClass);
18954 else
18955 return std::make_pair(0U, &PPC::VSFRCRegClass);
18956 } else if (Constraint == "lr") {
18957 if (VT == MVT::i64)
18958 return std::make_pair(0U, &PPC::LR8RCRegClass);
18959 else
18960 return std::make_pair(0U, &PPC::LRRCRegClass);
18961 }
18962
18963 // Handle special cases of physical registers that are not properly handled
18964 // by the base class.
18965 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
18966 // If we name a VSX register, we can't defer to the base class because it
18967 // will not recognize the correct register (their names will be VSL{0-31}
18968 // and V{0-31} so they won't match). So we match them here.
18969 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
18970 int VSNum = atoi(Constraint.data() + 3);
18971 assert(VSNum >= 0 && VSNum <= 63 &&
18972 "Attempted to access a vsr out of range");
18973 if (VSNum < 32)
18974 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
18975 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
18976 }
18977
18978 // For float registers, we can't defer to the base class as it will match
18979 // the SPILLTOVSRRC class.
18980 if (Constraint.size() > 3 && Constraint[1] == 'f') {
18981 int RegNum = atoi(Constraint.data() + 2);
18982 if (RegNum > 31 || RegNum < 0)
18983 report_fatal_error("Invalid floating point register number");
18984 if (VT == MVT::f32 || VT == MVT::i32)
18985 return Subtarget.hasSPE()
18986 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
18987 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
18988 if (VT == MVT::f64 || VT == MVT::i64)
18989 return Subtarget.hasSPE()
18990 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
18991 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
18992 }
18993 }
18994
18995 std::pair<unsigned, const TargetRegisterClass *> R =
18997
18998 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
18999 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
19000 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
19001 // register.
19002 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
19003 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
19004 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
19005 PPC::GPRCRegClass.contains(R.first))
19006 return std::make_pair(TRI->getMatchingSuperReg(R.first,
19007 PPC::sub_32, &PPC::G8RCRegClass),
19008 &PPC::G8RCRegClass);
19009
19010 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
19011 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
19012 R.first = PPC::CR0;
19013 R.second = &PPC::CRRCRegClass;
19014 }
19015 // FIXME: This warning should ideally be emitted in the front end.
19016 const auto &TM = getTargetMachine();
19017 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
19018 if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
19019 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
19020 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
19021 errs() << "warning: vector registers 20 to 32 are reserved in the "
19022 "default AIX AltiVec ABI and cannot be used\n";
19023 }
19024
19025 return R;
19026}
19027
19028/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19029/// vector. If it is invalid, don't add anything to Ops.
19031 StringRef Constraint,
19032 std::vector<SDValue> &Ops,
19033 SelectionDAG &DAG) const {
19034 SDValue Result;
19035
19036 // Only support length 1 constraints.
19037 if (Constraint.size() > 1)
19038 return;
19039
19040 char Letter = Constraint[0];
19041 switch (Letter) {
19042 default: break;
19043 case 'I':
19044 case 'J':
19045 case 'K':
19046 case 'L':
19047 case 'M':
19048 case 'N':
19049 case 'O':
19050 case 'P': {
19052 if (!CST) return; // Must be an immediate to match.
19053 SDLoc dl(Op);
19054 int64_t Value = CST->getSExtValue();
19055 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
19056 // numbers are printed as such.
19057 switch (Letter) {
19058 default: llvm_unreachable("Unknown constraint letter!");
19059 case 'I': // "I" is a signed 16-bit constant.
19060 if (isInt<16>(Value))
19061 Result = DAG.getTargetConstant(Value, dl, TCVT);
19062 break;
19063 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
19065 Result = DAG.getTargetConstant(Value, dl, TCVT);
19066 break;
19067 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
19069 Result = DAG.getTargetConstant(Value, dl, TCVT);
19070 break;
19071 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
19072 if (isUInt<16>(Value))
19073 Result = DAG.getTargetConstant(Value, dl, TCVT);
19074 break;
19075 case 'M': // "M" is a constant that is greater than 31.
19076 if (Value > 31)
19077 Result = DAG.getTargetConstant(Value, dl, TCVT);
19078 break;
19079 case 'N': // "N" is a positive constant that is an exact power of two.
19080 if (Value > 0 && isPowerOf2_64(Value))
19081 Result = DAG.getTargetConstant(Value, dl, TCVT);
19082 break;
19083 case 'O': // "O" is the constant zero.
19084 if (Value == 0)
19085 Result = DAG.getTargetConstant(Value, dl, TCVT);
19086 break;
19087 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
19088 if (isInt<16>(-Value))
19089 Result = DAG.getTargetConstant(Value, dl, TCVT);
19090 break;
19091 }
19092 break;
19093 }
19094 }
19095
19096 if (Result.getNode()) {
19097 Ops.push_back(Result);
19098 return;
19099 }
19100
19101 // Handle standard constraint letters.
19103}
19104
19107 SelectionDAG &DAG) const {
19108 if (I.getNumOperands() <= 1)
19109 return;
19110 if (!isa<ConstantSDNode>(Ops[1].getNode()))
19111 return;
19112 auto IntrinsicID = Ops[1].getNode()->getAsZExtVal();
19113 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
19114 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap)
19115 return;
19116
19117 if (MDNode *MDN = I.getMetadata(LLVMContext::MD_annotation))
19118 Ops.push_back(DAG.getMDNode(MDN));
19119}
19120
19121// isLegalAddressingMode - Return true if the addressing mode represented
19122// by AM is legal for this target, for a load/store of the specified type.
19124 const AddrMode &AM, Type *Ty,
19125 unsigned AS,
19126 Instruction *I) const {
19127 // Vector type r+i form is supported since power9 as DQ form. We don't check
19128 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
19129 // imm form is preferred and the offset can be adjusted to use imm form later
19130 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
19131 // max offset to check legal addressing mode, we should be a little aggressive
19132 // to contain other offsets for that LSRUse.
19133 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
19134 return false;
19135
19136 // PPC allows a sign-extended 16-bit immediate field.
19137 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
19138 return false;
19139
19140 // No global is ever allowed as a base.
19141 if (AM.BaseGV)
19142 return false;
19143
19144 // PPC only support r+r,
19145 switch (AM.Scale) {
19146 case 0: // "r+i" or just "i", depending on HasBaseReg.
19147 break;
19148 case 1:
19149 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
19150 return false;
19151 // Otherwise we have r+r or r+i.
19152 break;
19153 case 2:
19154 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
19155 return false;
19156 // Allow 2*r as r+r.
19157 break;
19158 default:
19159 // No other scales are supported.
19160 return false;
19161 }
19162
19163 return true;
19164}
19165
19166SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
19167 SelectionDAG &DAG) const {
19169 MachineFrameInfo &MFI = MF.getFrameInfo();
19170 MFI.setReturnAddressIsTaken(true);
19171
19172 SDLoc dl(Op);
19173 unsigned Depth = Op.getConstantOperandVal(0);
19174
19175 // Make sure the function does not optimize away the store of the RA to
19176 // the stack.
19177 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
19178 FuncInfo->setLRStoreRequired();
19179 auto PtrVT = getPointerTy(MF.getDataLayout());
19180
19181 if (Depth > 0) {
19182 // The link register (return address) is saved in the caller's frame
19183 // not the callee's stack frame. So we must get the caller's frame
19184 // address and load the return address at the LR offset from there.
19185 SDValue FrameAddr =
19186 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19188 SDValue Offset =
19189 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
19190 Subtarget.getScalarIntVT());
19191 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
19192 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
19194 }
19195
19196 // Just load the return address off the stack.
19197 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
19198 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
19200}
19201
19202SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
19203 SelectionDAG &DAG) const {
19204 SDLoc dl(Op);
19205 unsigned Depth = Op.getConstantOperandVal(0);
19206
19208 MachineFrameInfo &MFI = MF.getFrameInfo();
19209 MFI.setFrameAddressIsTaken(true);
19210
19211 EVT PtrVT = getPointerTy(MF.getDataLayout());
19212 bool isPPC64 = PtrVT == MVT::i64;
19213
19214 // Naked functions never have a frame pointer, and so we use r1. For all
19215 // other functions, this decision must be delayed until during PEI.
19216 unsigned FrameReg;
19217 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
19218 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
19219 else
19220 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
19221
19222 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
19223 PtrVT);
19224 while (Depth--)
19225 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19226 FrameAddr, MachinePointerInfo());
19227 return FrameAddr;
19228}
19229
19230#define GET_REGISTER_MATCHER
19231#include "PPCGenAsmMatcher.inc"
19232
19234 const MachineFunction &MF) const {
19235 bool IsPPC64 = Subtarget.isPPC64();
19236
19237 bool Is64Bit = IsPPC64 && VT == LLT::scalar(64);
19238 if (!Is64Bit && VT != LLT::scalar(32))
19239 report_fatal_error("Invalid register global variable type");
19240
19242 if (!Reg)
19243 return Reg;
19244
19245 // FIXME: Unable to generate code for `-O2` but okay for `-O0`.
19246 // Need followup investigation as to why.
19247 if ((IsPPC64 && Reg == PPC::R2) || Reg == PPC::R0)
19248 report_fatal_error(Twine("Trying to reserve an invalid register \"" +
19249 StringRef(RegName) + "\"."));
19250
19251 // Convert GPR to GP8R register for 64bit.
19252 if (Is64Bit && StringRef(RegName).starts_with_insensitive("r"))
19253 Reg = Reg.id() - PPC::R0 + PPC::X0;
19254
19255 return Reg;
19256}
19257
19259 // 32-bit SVR4 ABI access everything as got-indirect.
19260 if (Subtarget.is32BitELFABI())
19261 return true;
19262
19263 // AIX accesses everything indirectly through the TOC, which is similar to
19264 // the GOT.
19265 if (Subtarget.isAIXABI())
19266 return true;
19267
19269 // If it is small or large code model, module locals are accessed
19270 // indirectly by loading their address from .toc/.got.
19271 if (CModel == CodeModel::Small || CModel == CodeModel::Large)
19272 return true;
19273
19274 // JumpTable and BlockAddress are accessed as got-indirect.
19276 return true;
19277
19279 return Subtarget.isGVIndirectSymbol(G->getGlobal());
19280
19281 return false;
19282}
19283
19284bool
19286 // The PowerPC target isn't yet aware of offsets.
19287 return false;
19288}
19289
19292 MachineFunction &MF, unsigned Intrinsic) const {
19293 IntrinsicInfo Info;
19294 switch (Intrinsic) {
19295 case Intrinsic::ppc_atomicrmw_xchg_i128:
19296 case Intrinsic::ppc_atomicrmw_add_i128:
19297 case Intrinsic::ppc_atomicrmw_sub_i128:
19298 case Intrinsic::ppc_atomicrmw_nand_i128:
19299 case Intrinsic::ppc_atomicrmw_and_i128:
19300 case Intrinsic::ppc_atomicrmw_or_i128:
19301 case Intrinsic::ppc_atomicrmw_xor_i128:
19302 case Intrinsic::ppc_cmpxchg_i128:
19303 Info.opc = ISD::INTRINSIC_W_CHAIN;
19304 Info.memVT = MVT::i128;
19305 Info.ptrVal = I.getArgOperand(0);
19306 Info.offset = 0;
19307 Info.align = Align(16);
19310 Infos.push_back(Info);
19311 return;
19312 case Intrinsic::ppc_atomic_load_i128:
19313 Info.opc = ISD::INTRINSIC_W_CHAIN;
19314 Info.memVT = MVT::i128;
19315 Info.ptrVal = I.getArgOperand(0);
19316 Info.offset = 0;
19317 Info.align = Align(16);
19319 Infos.push_back(Info);
19320 return;
19321 case Intrinsic::ppc_atomic_store_i128:
19322 Info.opc = ISD::INTRINSIC_VOID;
19323 Info.memVT = MVT::i128;
19324 Info.ptrVal = I.getArgOperand(2);
19325 Info.offset = 0;
19326 Info.align = Align(16);
19328 Infos.push_back(Info);
19329 return;
19330 case Intrinsic::ppc_altivec_lvx:
19331 case Intrinsic::ppc_altivec_lvxl:
19332 case Intrinsic::ppc_altivec_lvebx:
19333 case Intrinsic::ppc_altivec_lvehx:
19334 case Intrinsic::ppc_altivec_lvewx:
19335 case Intrinsic::ppc_vsx_lxvd2x:
19336 case Intrinsic::ppc_vsx_lxvw4x:
19337 case Intrinsic::ppc_vsx_lxvd2x_be:
19338 case Intrinsic::ppc_vsx_lxvw4x_be:
19339 case Intrinsic::ppc_vsx_lxvl:
19340 case Intrinsic::ppc_vsx_lxvll: {
19341 EVT VT;
19342 switch (Intrinsic) {
19343 case Intrinsic::ppc_altivec_lvebx:
19344 VT = MVT::i8;
19345 break;
19346 case Intrinsic::ppc_altivec_lvehx:
19347 VT = MVT::i16;
19348 break;
19349 case Intrinsic::ppc_altivec_lvewx:
19350 VT = MVT::i32;
19351 break;
19352 case Intrinsic::ppc_vsx_lxvd2x:
19353 case Intrinsic::ppc_vsx_lxvd2x_be:
19354 VT = MVT::v2f64;
19355 break;
19356 default:
19357 VT = MVT::v4i32;
19358 break;
19359 }
19360
19361 Info.opc = ISD::INTRINSIC_W_CHAIN;
19362 Info.memVT = VT;
19363 Info.ptrVal = I.getArgOperand(0);
19364 Info.offset = -VT.getStoreSize()+1;
19365 Info.size = 2*VT.getStoreSize()-1;
19366 Info.align = Align(1);
19367 Info.flags = MachineMemOperand::MOLoad;
19368 Infos.push_back(Info);
19369 return;
19370 }
19371 case Intrinsic::ppc_altivec_stvx:
19372 case Intrinsic::ppc_altivec_stvxl:
19373 case Intrinsic::ppc_altivec_stvebx:
19374 case Intrinsic::ppc_altivec_stvehx:
19375 case Intrinsic::ppc_altivec_stvewx:
19376 case Intrinsic::ppc_vsx_stxvd2x:
19377 case Intrinsic::ppc_vsx_stxvw4x:
19378 case Intrinsic::ppc_vsx_stxvd2x_be:
19379 case Intrinsic::ppc_vsx_stxvw4x_be:
19380 case Intrinsic::ppc_vsx_stxvl:
19381 case Intrinsic::ppc_vsx_stxvll: {
19382 EVT VT;
19383 switch (Intrinsic) {
19384 case Intrinsic::ppc_altivec_stvebx:
19385 VT = MVT::i8;
19386 break;
19387 case Intrinsic::ppc_altivec_stvehx:
19388 VT = MVT::i16;
19389 break;
19390 case Intrinsic::ppc_altivec_stvewx:
19391 VT = MVT::i32;
19392 break;
19393 case Intrinsic::ppc_vsx_stxvd2x:
19394 case Intrinsic::ppc_vsx_stxvd2x_be:
19395 VT = MVT::v2f64;
19396 break;
19397 default:
19398 VT = MVT::v4i32;
19399 break;
19400 }
19401
19402 Info.opc = ISD::INTRINSIC_VOID;
19403 Info.memVT = VT;
19404 Info.ptrVal = I.getArgOperand(1);
19405 Info.offset = -VT.getStoreSize()+1;
19406 Info.size = 2*VT.getStoreSize()-1;
19407 Info.align = Align(1);
19408 Info.flags = MachineMemOperand::MOStore;
19409 Infos.push_back(Info);
19410 return;
19411 }
19412 case Intrinsic::ppc_stdcx:
19413 case Intrinsic::ppc_stwcx:
19414 case Intrinsic::ppc_sthcx:
19415 case Intrinsic::ppc_stbcx: {
19416 EVT VT;
19417 auto Alignment = Align(8);
19418 switch (Intrinsic) {
19419 case Intrinsic::ppc_stdcx:
19420 VT = MVT::i64;
19421 break;
19422 case Intrinsic::ppc_stwcx:
19423 VT = MVT::i32;
19424 Alignment = Align(4);
19425 break;
19426 case Intrinsic::ppc_sthcx:
19427 VT = MVT::i16;
19428 Alignment = Align(2);
19429 break;
19430 case Intrinsic::ppc_stbcx:
19431 VT = MVT::i8;
19432 Alignment = Align(1);
19433 break;
19434 }
19435 Info.opc = ISD::INTRINSIC_W_CHAIN;
19436 Info.memVT = VT;
19437 Info.ptrVal = I.getArgOperand(0);
19438 Info.offset = 0;
19439 Info.align = Alignment;
19441 Infos.push_back(Info);
19442 return;
19443 }
19444 default:
19445 break;
19446 }
19447}
19448
19449/// It returns EVT::Other if the type should be determined using generic
19450/// target-independent logic.
19452 LLVMContext &Context, const MemOp &Op,
19453 const AttributeList &FuncAttributes) const {
19454 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None) {
19455 // We should use Altivec/VSX loads and stores when available. For unaligned
19456 // addresses, unaligned VSX loads are only fast starting with the P8.
19457 if (Subtarget.hasAltivec() && Op.size() >= 16) {
19458 if (Op.isMemset() && Subtarget.hasVSX()) {
19459 uint64_t TailSize = Op.size() % 16;
19460 // For memset lowering, EXTRACT_VECTOR_ELT tries to return constant
19461 // element if vector element type matches tail store. For tail size
19462 // 3/4, the tail store is i32, v4i32 cannot be used, need a legal one.
19463 if (TailSize > 2 && TailSize <= 4) {
19464 return MVT::v8i16;
19465 }
19466 return MVT::v4i32;
19467 }
19468 if (Op.isAligned(Align(16)) || Subtarget.hasP8Vector())
19469 return MVT::v4i32;
19470 }
19471 }
19472
19473 if (Subtarget.isPPC64()) {
19474 return MVT::i64;
19475 }
19476
19477 return MVT::i32;
19478}
19479
19480/// Returns true if it is beneficial to convert a load of a constant
19481/// to just the constant itself.
19483 Type *Ty) const {
19484 assert(Ty->isIntegerTy());
19485
19486 unsigned BitSize = Ty->getPrimitiveSizeInBits();
19487 return !(BitSize == 0 || BitSize > 64);
19488}
19489
19491 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19492 return false;
19493 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19494 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19495 return NumBits1 == 64 && NumBits2 == 32;
19496}
19497
19499 if (!VT1.isInteger() || !VT2.isInteger())
19500 return false;
19501 unsigned NumBits1 = VT1.getSizeInBits();
19502 unsigned NumBits2 = VT2.getSizeInBits();
19503 return NumBits1 == 64 && NumBits2 == 32;
19504}
19505
19507 // Generally speaking, zexts are not free, but they are free when they can be
19508 // folded with other operations.
19509 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
19510 EVT MemVT = LD->getMemoryVT();
19511 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
19512 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
19513 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
19514 LD->getExtensionType() == ISD::ZEXTLOAD))
19515 return true;
19516 }
19517
19518 // FIXME: Add other cases...
19519 // - 32-bit shifts with a zext to i64
19520 // - zext after ctlz, bswap, etc.
19521 // - zext after and by a constant mask
19522
19523 return TargetLowering::isZExtFree(Val, VT2);
19524}
19525
19526bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
19527 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
19528 "invalid fpext types");
19529 // Extending to float128 is not free.
19530 if (DestVT == MVT::f128)
19531 return false;
19532 return true;
19533}
19534
19536 return isInt<16>(Imm) || isUInt<16>(Imm);
19537}
19538
19540 return isInt<16>(Imm) || isUInt<16>(Imm);
19541}
19542
19545 unsigned *Fast) const {
19547 return false;
19548
19549 // PowerPC supports unaligned memory access for simple non-vector types.
19550 // Although accessing unaligned addresses is not as efficient as accessing
19551 // aligned addresses, it is generally more efficient than manual expansion,
19552 // and generally only traps for software emulation when crossing page
19553 // boundaries.
19554
19555 if (!VT.isSimple())
19556 return false;
19557
19558 if (VT.isFloatingPoint() && !VT.isVector() &&
19559 !Subtarget.allowsUnalignedFPAccess())
19560 return false;
19561
19562 if (VT.getSimpleVT().isVector()) {
19563 if (Subtarget.hasVSX()) {
19564 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
19565 VT != MVT::v4f32 && VT != MVT::v4i32)
19566 return false;
19567 } else {
19568 return false;
19569 }
19570 }
19571
19572 if (VT == MVT::ppcf128)
19573 return false;
19574
19575 if (Fast)
19576 *Fast = 1;
19577
19578 return true;
19579}
19580
19582 SDValue C) const {
19583 // Check integral scalar types.
19584 if (!VT.isScalarInteger())
19585 return false;
19586 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
19587 if (!ConstNode->getAPIntValue().isSignedIntN(64))
19588 return false;
19589 // This transformation will generate >= 2 operations. But the following
19590 // cases will generate <= 2 instructions during ISEL. So exclude them.
19591 // 1. If the constant multiplier fits 16 bits, it can be handled by one
19592 // HW instruction, ie. MULLI
19593 // 2. If the multiplier after shifted fits 16 bits, an extra shift
19594 // instruction is needed than case 1, ie. MULLI and RLDICR
19595 int64_t Imm = ConstNode->getSExtValue();
19596 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
19597 Imm >>= Shift;
19598 if (isInt<16>(Imm))
19599 return false;
19600 uint64_t UImm = static_cast<uint64_t>(Imm);
19601 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
19602 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
19603 return true;
19604 }
19605 return false;
19606}
19607
19613
19615 Type *Ty) const {
19616 if (Subtarget.hasSPE() || Subtarget.useSoftFloat())
19617 return false;
19618 switch (Ty->getScalarType()->getTypeID()) {
19619 case Type::FloatTyID:
19620 case Type::DoubleTyID:
19621 return true;
19622 case Type::FP128TyID:
19623 return Subtarget.hasP9Vector();
19624 default:
19625 return false;
19626 }
19627}
19628
19629// FIXME: add more patterns which are not profitable to hoist.
19631 if (!I->hasOneUse())
19632 return true;
19633
19634 Instruction *User = I->user_back();
19635 assert(User && "A single use instruction with no uses.");
19636
19637 switch (I->getOpcode()) {
19638 case Instruction::FMul: {
19639 // Don't break FMA, PowerPC prefers FMA.
19640 if (User->getOpcode() != Instruction::FSub &&
19641 User->getOpcode() != Instruction::FAdd)
19642 return true;
19643
19645 const Function *F = I->getFunction();
19646 const DataLayout &DL = F->getDataLayout();
19647 Type *Ty = User->getOperand(0)->getType();
19648 bool AllowContract = I->getFastMathFlags().allowContract() &&
19649 User->getFastMathFlags().allowContract();
19650
19651 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
19653 (AllowContract || Options.AllowFPOpFusion == FPOpFusion::Fast));
19654 }
19655 case Instruction::Load: {
19656 // Don't break "store (load float*)" pattern, this pattern will be combined
19657 // to "store (load int32)" in later InstCombine pass. See function
19658 // combineLoadToOperationType. On PowerPC, loading a float point takes more
19659 // cycles than loading a 32 bit integer.
19660 LoadInst *LI = cast<LoadInst>(I);
19661 // For the loads that combineLoadToOperationType does nothing, like
19662 // ordered load, it should be profitable to hoist them.
19663 // For swifterror load, it can only be used for pointer to pointer type, so
19664 // later type check should get rid of this case.
19665 if (!LI->isUnordered())
19666 return true;
19667
19668 if (User->getOpcode() != Instruction::Store)
19669 return true;
19670
19671 if (I->getType()->getTypeID() != Type::FloatTyID)
19672 return true;
19673
19674 return false;
19675 }
19676 default:
19677 return true;
19678 }
19679 return true;
19680}
19681
19682const MCPhysReg *
19684 // LR is a callee-save register, but we must treat it as clobbered by any call
19685 // site. Hence we include LR in the scratch registers, which are in turn added
19686 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
19687 // to CTR, which is used by any indirect call.
19688 static const MCPhysReg ScratchRegs[] = {
19689 PPC::X12, PPC::LR8, PPC::CTR8, 0
19690 };
19691
19692 return ScratchRegs;
19693}
19694
19696 ExceptionHandling EH, const Constant *PersonalityFn) const {
19697 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
19698}
19699
19701 ExceptionHandling EH, const Constant *PersonalityFn) const {
19702 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
19703}
19704
19705bool
19707 EVT VT , unsigned DefinedValues) const {
19708 if (VT == MVT::v2i64)
19709 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
19710
19711 if (Subtarget.hasVSX())
19712 return true;
19713
19715}
19716
19718 if (DisableILPPref || Subtarget.enableMachineScheduler())
19720
19721 return Sched::ILP;
19722}
19723
19724// Create a fast isel object.
19726 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo,
19727 const LibcallLoweringInfo *LibcallLowering) const {
19728 return PPC::createFastISel(FuncInfo, LibInfo, LibcallLowering);
19729}
19730
19731// 'Inverted' means the FMA opcode after negating one multiplicand.
19732// For example, (fma -a b c) = (fnmsub a b c)
19733static unsigned invertFMAOpcode(unsigned Opc) {
19734 switch (Opc) {
19735 default:
19736 llvm_unreachable("Invalid FMA opcode for PowerPC!");
19737 case ISD::FMA:
19738 return PPCISD::FNMSUB;
19739 case PPCISD::FNMSUB:
19740 return ISD::FMA;
19741 }
19742}
19743
19745 bool LegalOps, bool OptForSize,
19747 unsigned Depth) const {
19749 return SDValue();
19750
19751 unsigned Opc = Op.getOpcode();
19752 EVT VT = Op.getValueType();
19753 SDNodeFlags Flags = Op.getNode()->getFlags();
19754
19755 switch (Opc) {
19756 case PPCISD::FNMSUB:
19757 if (!Op.hasOneUse() || !isTypeLegal(VT))
19758 break;
19759
19760 SDValue N0 = Op.getOperand(0);
19761 SDValue N1 = Op.getOperand(1);
19762 SDValue N2 = Op.getOperand(2);
19763 SDLoc Loc(Op);
19764
19766 SDValue NegN2 =
19767 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
19768
19769 if (!NegN2)
19770 return SDValue();
19771
19772 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
19773 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
19774 // These transformations may change sign of zeroes. For example,
19775 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
19776 if (Flags.hasNoSignedZeros()) {
19777 // Try and choose the cheaper one to negate.
19779 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
19780 N0Cost, Depth + 1);
19781
19783 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
19784 N1Cost, Depth + 1);
19785
19786 if (NegN0 && N0Cost <= N1Cost) {
19787 Cost = std::min(N0Cost, N2Cost);
19788 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
19789 } else if (NegN1) {
19790 Cost = std::min(N1Cost, N2Cost);
19791 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
19792 }
19793 }
19794
19795 // (fneg (fnmsub a b c)) => (fma a b (fneg c))
19796 if (isOperationLegal(ISD::FMA, VT)) {
19797 Cost = N2Cost;
19798 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
19799 }
19800
19801 break;
19802 }
19803
19804 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
19805 Cost, Depth);
19806}
19807
19808// Override to enable LOAD_STACK_GUARD lowering on Linux.
19810 if (M.getStackProtectorGuard() == "tls" || Subtarget.isTargetLinux())
19811 return true;
19813}
19814
19816 bool ForCodeSize) const {
19817 if (!VT.isSimple() || !Subtarget.hasVSX())
19818 return false;
19819
19820 switch(VT.getSimpleVT().SimpleTy) {
19821 default:
19822 // For FP types that are currently not supported by PPC backend, return
19823 // false. Examples: f16, f80.
19824 return false;
19825 case MVT::f32:
19826 case MVT::f64: {
19827 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
19828 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
19829 return true;
19830 }
19831 bool IsExact;
19832 APSInt IntResult(16, false);
19833 // The rounding mode doesn't really matter because we only care about floats
19834 // that can be converted to integers exactly.
19835 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
19836 // For exact values in the range [-16, 15] we can materialize the float.
19837 if (IsExact && IntResult <= 15 && IntResult >= -16)
19838 return true;
19839 return Imm.isZero();
19840 }
19841 case MVT::ppcf128:
19842 return Imm.isPosZero();
19843 }
19844}
19845
19846// For vector shift operation op, fold
19847// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
19849 SelectionDAG &DAG) {
19850 SDValue N0 = N->getOperand(0);
19851 SDValue N1 = N->getOperand(1);
19852 EVT VT = N0.getValueType();
19853 unsigned OpSizeInBits = VT.getScalarSizeInBits();
19854 unsigned Opcode = N->getOpcode();
19855 unsigned TargetOpcode;
19856
19857 switch (Opcode) {
19858 default:
19859 llvm_unreachable("Unexpected shift operation");
19860 case ISD::SHL:
19861 TargetOpcode = PPCISD::SHL;
19862 break;
19863 case ISD::SRL:
19864 TargetOpcode = PPCISD::SRL;
19865 break;
19866 case ISD::SRA:
19867 TargetOpcode = PPCISD::SRA;
19868 break;
19869 }
19870
19871 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
19872 N1->getOpcode() == ISD::AND)
19873 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
19874 if (Mask->getZExtValue() == OpSizeInBits - 1)
19875 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
19876
19877 return SDValue();
19878}
19879
19880SDValue PPCTargetLowering::combineVectorShift(SDNode *N,
19881 DAGCombinerInfo &DCI) const {
19882 EVT VT = N->getValueType(0);
19883 assert(VT.isVector() && "Vector type expected.");
19884
19885 unsigned Opc = N->getOpcode();
19886 assert((Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
19887 "Unexpected opcode.");
19888
19889 if (!isOperationLegal(Opc, VT))
19890 return SDValue();
19891
19892 EVT EltTy = VT.getScalarType();
19893 unsigned EltBits = EltTy.getSizeInBits();
19894 if (EltTy != MVT::i64 && EltTy != MVT::i32)
19895 return SDValue();
19896
19897 SDValue N1 = N->getOperand(1);
19898 uint64_t SplatBits = 0;
19899 bool AddSplatCase = false;
19900 unsigned OpcN1 = N1.getOpcode();
19901 if (OpcN1 == PPCISD::VADD_SPLAT &&
19903 AddSplatCase = true;
19904 SplatBits = N1.getConstantOperandVal(0);
19905 }
19906
19907 if (!AddSplatCase) {
19908 if (OpcN1 != ISD::BUILD_VECTOR)
19909 return SDValue();
19910
19911 unsigned SplatBitSize;
19912 bool HasAnyUndefs;
19913 APInt APSplatBits, APSplatUndef;
19914 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(N1);
19915 bool BVNIsConstantSplat =
19916 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
19917 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
19918 if (!BVNIsConstantSplat || SplatBitSize != EltBits)
19919 return SDValue();
19920 SplatBits = APSplatBits.getZExtValue();
19921 }
19922
19923 SDLoc DL(N);
19924 SDValue N0 = N->getOperand(0);
19925 // PPC vector shifts by word/double look at only the low 5/6 bits of the
19926 // shift vector, which means the max value is 31/63. A shift vector of all
19927 // 1s will be truncated to 31/63, which is useful as vspltiw is limited to
19928 // -16 to 15 range.
19929 if (SplatBits == (EltBits - 1)) {
19930 unsigned NewOpc;
19931 switch (Opc) {
19932 case ISD::SHL:
19933 NewOpc = PPCISD::SHL;
19934 break;
19935 case ISD::SRL:
19936 NewOpc = PPCISD::SRL;
19937 break;
19938 case ISD::SRA:
19939 NewOpc = PPCISD::SRA;
19940 break;
19941 }
19942 SDValue SplatOnes = getCanonicalConstSplat(255, 1, VT, DCI.DAG, DL);
19943 return DCI.DAG.getNode(NewOpc, DL, VT, N0, SplatOnes);
19944 }
19945
19946 if (Opc != ISD::SHL || !isOperationLegal(ISD::ADD, VT))
19947 return SDValue();
19948
19949 // For 64-bit there is no splat immediate so we want to catch shift by 1 here
19950 // before the BUILD_VECTOR is replaced by a load.
19951 if (EltTy != MVT::i64 || SplatBits != 1)
19952 return SDValue();
19953
19954 return DCI.DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19955}
19956
19957SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
19958 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
19959 return Value;
19960
19961 if (N->getValueType(0).isVector())
19962 return combineVectorShift(N, DCI);
19963
19964 SDValue N0 = N->getOperand(0);
19965 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
19966 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
19967 N0.getOpcode() != ISD::SIGN_EXTEND ||
19968 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
19969 N->getValueType(0) != MVT::i64)
19970 return SDValue();
19971
19972 // We can't save an operation here if the value is already extended, and
19973 // the existing shift is easier to combine.
19974 SDValue ExtsSrc = N0.getOperand(0);
19975 if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
19976 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
19977 return SDValue();
19978
19979 SDLoc DL(N0);
19980 SDValue ShiftBy = SDValue(CN1, 0);
19981 // We want the shift amount to be i32 on the extswli, but the shift could
19982 // have an i64.
19983 if (ShiftBy.getValueType() == MVT::i64)
19984 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
19985
19986 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
19987 ShiftBy);
19988}
19989
19990SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
19991 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
19992 return Value;
19993
19994 if (N->getValueType(0).isVector())
19995 return combineVectorShift(N, DCI);
19996
19997 return SDValue();
19998}
19999
20000SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
20001 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
20002 return Value;
20003
20004 if (N->getValueType(0).isVector())
20005 return combineVectorShift(N, DCI);
20006
20007 return SDValue();
20008}
20009
20010// Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
20011// Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
20012// When C is zero, the equation (addi Z, -C) can be simplified to Z
20013// Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
20015 const PPCSubtarget &Subtarget) {
20016 if (!Subtarget.isPPC64())
20017 return SDValue();
20018
20019 SDValue LHS = N->getOperand(0);
20020 SDValue RHS = N->getOperand(1);
20021
20022 auto isZextOfCompareWithConstant = [](SDValue Op) {
20023 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
20024 Op.getValueType() != MVT::i64)
20025 return false;
20026
20027 SDValue Cmp = Op.getOperand(0);
20028 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
20029 Cmp.getOperand(0).getValueType() != MVT::i64)
20030 return false;
20031
20032 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
20033 int64_t NegConstant = 0 - Constant->getSExtValue();
20034 // Due to the limitations of the addi instruction,
20035 // -C is required to be [-32768, 32767].
20036 return isInt<16>(NegConstant);
20037 }
20038
20039 return false;
20040 };
20041
20042 bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
20043 bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
20044
20045 // If there is a pattern, canonicalize a zext operand to the RHS.
20046 if (LHSHasPattern && !RHSHasPattern)
20047 std::swap(LHS, RHS);
20048 else if (!LHSHasPattern && !RHSHasPattern)
20049 return SDValue();
20050
20051 SDLoc DL(N);
20052 EVT CarryType = Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
20053 SDVTList VTs = DAG.getVTList(MVT::i64, CarryType);
20054 SDValue Cmp = RHS.getOperand(0);
20055 SDValue Z = Cmp.getOperand(0);
20056 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
20057 int64_t NegConstant = 0 - Constant->getSExtValue();
20058
20059 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
20060 default: break;
20061 case ISD::SETNE: {
20062 // when C == 0
20063 // --> addze X, (addic Z, -1).carry
20064 // /
20065 // add X, (zext(setne Z, C))--
20066 // \ when -32768 <= -C <= 32767 && C != 0
20067 // --> addze X, (addic (addi Z, -C), -1).carry
20068 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20069 DAG.getConstant(NegConstant, DL, MVT::i64));
20070 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20071 SDValue Addc =
20072 DAG.getNode(ISD::UADDO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20073 AddOrZ, DAG.getAllOnesConstant(DL, MVT::i64),
20074 DAG.getConstant(0, DL, CarryType));
20075 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20076 DAG.getConstant(0, DL, MVT::i64),
20077 SDValue(Addc.getNode(), 1));
20078 }
20079 case ISD::SETEQ: {
20080 // when C == 0
20081 // --> addze X, (subfic Z, 0).carry
20082 // /
20083 // add X, (zext(sete Z, C))--
20084 // \ when -32768 <= -C <= 32767 && C != 0
20085 // --> addze X, (subfic (addi Z, -C), 0).carry
20086 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20087 DAG.getConstant(NegConstant, DL, MVT::i64));
20088 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20089 SDValue Subc =
20090 DAG.getNode(ISD::USUBO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20091 DAG.getConstant(0, DL, MVT::i64), AddOrZ,
20092 DAG.getConstant(0, DL, CarryType));
20093 SDValue Invert = DAG.getNode(ISD::XOR, DL, CarryType, Subc.getValue(1),
20094 DAG.getConstant(1UL, DL, CarryType));
20095 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20096 DAG.getConstant(0, DL, MVT::i64), Invert);
20097 }
20098 }
20099
20100 return SDValue();
20101}
20102
20103// Transform
20104// (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
20105// (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
20106// In this case both C1 and C2 must be known constants.
20107// C1+C2 must fit into a 34 bit signed integer.
20109 const PPCSubtarget &Subtarget) {
20110 if (!Subtarget.isUsingPCRelativeCalls())
20111 return SDValue();
20112
20113 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
20114 // If we find that node try to cast the Global Address and the Constant.
20115 SDValue LHS = N->getOperand(0);
20116 SDValue RHS = N->getOperand(1);
20117
20118 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20119 std::swap(LHS, RHS);
20120
20121 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20122 return SDValue();
20123
20124 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
20127
20128 // Check that both casts succeeded.
20129 if (!GSDN || !ConstNode)
20130 return SDValue();
20131
20132 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
20133 SDLoc DL(GSDN);
20134
20135 // The signed int offset needs to fit in 34 bits.
20136 if (!isInt<34>(NewOffset))
20137 return SDValue();
20138
20139 // The new global address is a copy of the old global address except
20140 // that it has the updated Offset.
20141 SDValue GA =
20142 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
20143 NewOffset, GSDN->getTargetFlags());
20144 SDValue MatPCRel =
20145 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
20146 return MatPCRel;
20147}
20148
20149// Transform (add X, (build_vector (T 1), (T 1), ...)) -> (sub X, (XXLEQVOnes))
20150// XXLEQVOnes creates an all-1s vector (0xFFFFFFFF...) efficiently via xxleqv
20151// Mathematical identity: X + 1 = X - (-1)
20152// Applies to v4i32, v2i64, v8i16, v16i8 where all elements are constant 1
20153// Requirement: VSX feature for efficient xxleqv generation
20155 const PPCSubtarget &Subtarget) {
20156
20157 EVT VT = N->getValueType(0);
20158 if (!Subtarget.hasVSX())
20159 return SDValue();
20160
20161 // Handle v2i64, v4i32, v8i16 and v16i8 types
20162 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
20163 VT == MVT::v2i64))
20164 return SDValue();
20165
20166 SDValue LHS = N->getOperand(0);
20167 SDValue RHS = N->getOperand(1);
20168
20169 // Check if RHS is BUILD_VECTOR
20170 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
20171 return SDValue();
20172
20173 // Check if all the elements are 1
20174 unsigned NumOfEles = RHS.getNumOperands();
20175 for (unsigned i = 0; i < NumOfEles; ++i) {
20176 auto *CN = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
20177 if (!CN || CN->getSExtValue() != 1)
20178 return SDValue();
20179 }
20180 SDLoc DL(N);
20181
20182 SDValue MinusOne = DAG.getConstant(APInt::getAllOnes(32), DL, MVT::i32);
20183 SmallVector<SDValue, 4> Ops(4, MinusOne);
20184 SDValue AllOnesVec = DAG.getBuildVector(MVT::v4i32, DL, Ops);
20185
20186 // Bitcast to the target vector type
20187 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT, AllOnesVec);
20188
20189 return DAG.getNode(ISD::SUB, DL, VT, LHS, Bitcast);
20190}
20191
20192SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
20193 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
20194 return Value;
20195
20196 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
20197 return Value;
20198
20199 if (auto Value = combineADDToSUB(N, DCI.DAG, Subtarget))
20200 return Value;
20201 return SDValue();
20202}
20203
20204// Detect TRUNCATE operations on bitcasts of float128 values.
20205// What we are looking for here is the situtation where we extract a subset
20206// of bits from a 128 bit float.
20207// This can be of two forms:
20208// 1) BITCAST of f128 feeding TRUNCATE
20209// 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
20210// The reason this is required is because we do not have a legal i128 type
20211// and so we want to prevent having to store the f128 and then reload part
20212// of it.
20213SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
20214 DAGCombinerInfo &DCI) const {
20215 // If we are using CRBits then try that first.
20216 if (Subtarget.useCRBits()) {
20217 // Check if CRBits did anything and return that if it did.
20218 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
20219 return CRTruncValue;
20220 }
20221
20222 SDLoc dl(N);
20223 SDValue Op0 = N->getOperand(0);
20224
20225 // Looking for a truncate of i128 to i64.
20226 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
20227 return SDValue();
20228
20229 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
20230
20231 // SRL feeding TRUNCATE.
20232 if (Op0.getOpcode() == ISD::SRL) {
20233 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
20234 // The right shift has to be by 64 bits.
20235 if (!ConstNode || ConstNode->getZExtValue() != 64)
20236 return SDValue();
20237
20238 // Switch the element number to extract.
20239 EltToExtract = EltToExtract ? 0 : 1;
20240 // Update Op0 past the SRL.
20241 Op0 = Op0.getOperand(0);
20242 }
20243
20244 // BITCAST feeding a TRUNCATE possibly via SRL.
20245 if (Op0.getOpcode() == ISD::BITCAST &&
20246 Op0.getValueType() == MVT::i128 &&
20247 Op0.getOperand(0).getValueType() == MVT::f128) {
20248 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
20249 return DCI.DAG.getNode(
20250 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
20251 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
20252 }
20253 return SDValue();
20254}
20255
20256SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
20257 SelectionDAG &DAG = DCI.DAG;
20258
20259 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
20260 if (!ConstOpOrElement)
20261 return SDValue();
20262
20263 // An imul is usually smaller than the alternative sequence for legal type.
20265 isOperationLegal(ISD::MUL, N->getValueType(0)))
20266 return SDValue();
20267
20268 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
20269 switch (this->Subtarget.getCPUDirective()) {
20270 default:
20271 // TODO: enhance the condition for subtarget before pwr8
20272 return false;
20273 case PPC::DIR_PWR8:
20274 // type mul add shl
20275 // scalar 4 1 1
20276 // vector 7 2 2
20277 return true;
20278 case PPC::DIR_PWR9:
20279 case PPC::DIR_PWR10:
20280 case PPC::DIR_PWR11:
20282 // type mul add shl
20283 // scalar 5 2 2
20284 // vector 7 2 2
20285
20286 // The cycle RATIO of related operations are showed as a table above.
20287 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
20288 // scalar and vector type. For 2 instrs patterns, add/sub + shl
20289 // are 4, it is always profitable; but for 3 instrs patterns
20290 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
20291 // So we should only do it for vector type.
20292 return IsAddOne && IsNeg ? VT.isVector() : true;
20293 }
20294 };
20295
20296 EVT VT = N->getValueType(0);
20297 SDLoc DL(N);
20298
20299 const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
20300 bool IsNeg = MulAmt.isNegative();
20301 APInt MulAmtAbs = MulAmt.abs();
20302
20303 if ((MulAmtAbs - 1).isPowerOf2()) {
20304 // (mul x, 2^N + 1) => (add (shl x, N), x)
20305 // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
20306
20307 if (!IsProfitable(IsNeg, true, VT))
20308 return SDValue();
20309
20310 SDValue Op0 = N->getOperand(0);
20311 SDValue Op1 =
20312 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20313 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
20314 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
20315
20316 if (!IsNeg)
20317 return Res;
20318
20319 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
20320 } else if ((MulAmtAbs + 1).isPowerOf2()) {
20321 // (mul x, 2^N - 1) => (sub (shl x, N), x)
20322 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
20323
20324 if (!IsProfitable(IsNeg, false, VT))
20325 return SDValue();
20326
20327 SDValue Op0 = N->getOperand(0);
20328 SDValue Op1 =
20329 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20330 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
20331
20332 if (!IsNeg)
20333 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
20334 else
20335 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
20336
20337 } else {
20338 return SDValue();
20339 }
20340}
20341
20342// Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
20343// in combiner since we need to check SD flags and other subtarget features.
20344SDValue PPCTargetLowering::combineFMALike(SDNode *N,
20345 DAGCombinerInfo &DCI) const {
20346 SDValue N0 = N->getOperand(0);
20347 SDValue N1 = N->getOperand(1);
20348 SDValue N2 = N->getOperand(2);
20349 SDNodeFlags Flags = N->getFlags();
20350 EVT VT = N->getValueType(0);
20351 SelectionDAG &DAG = DCI.DAG;
20352 unsigned Opc = N->getOpcode();
20354 bool LegalOps = !DCI.isBeforeLegalizeOps();
20355 SDLoc Loc(N);
20356
20357 if (!isOperationLegal(ISD::FMA, VT))
20358 return SDValue();
20359
20360 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
20361 // since (fnmsub a b c)=-0 while c-ab=+0.
20362 if (!Flags.hasNoSignedZeros())
20363 return SDValue();
20364
20365 // (fma (fneg a) b c) => (fnmsub a b c)
20366 // (fnmsub (fneg a) b c) => (fma a b c)
20367 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
20368 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
20369
20370 // (fma a (fneg b) c) => (fnmsub a b c)
20371 // (fnmsub a (fneg b) c) => (fma a b c)
20372 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
20373 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
20374
20375 return SDValue();
20376}
20377
20378bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
20379 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
20380 if (!Subtarget.is64BitELFABI())
20381 return false;
20382
20383 // If not a tail call then no need to proceed.
20384 if (!CI->isTailCall())
20385 return false;
20386
20387 // If sibling calls have been disabled and tail-calls aren't guaranteed
20388 // there is no reason to duplicate.
20389 auto &TM = getTargetMachine();
20390 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
20391 return false;
20392
20393 // Can't tail call a function called indirectly, or if it has variadic args.
20394 const Function *Callee = CI->getCalledFunction();
20395 if (!Callee || Callee->isVarArg())
20396 return false;
20397
20398 // Make sure the callee and caller calling conventions are eligible for tco.
20399 const Function *Caller = CI->getParent()->getParent();
20400 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
20401 CI->getCallingConv()))
20402 return false;
20403
20404 // If the function is local then we have a good chance at tail-calling it
20405 return getTargetMachine().shouldAssumeDSOLocal(Callee);
20406}
20407
20408bool PPCTargetLowering::
20409isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
20410 const Value *Mask = AndI.getOperand(1);
20411 // If the mask is suitable for andi. or andis. we should sink the and.
20412 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
20413 // Can't handle constants wider than 64-bits.
20414 if (CI->getBitWidth() > 64)
20415 return false;
20416 int64_t ConstVal = CI->getZExtValue();
20417 return isUInt<16>(ConstVal) ||
20418 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
20419 }
20420
20421 // For non-constant masks, we can always use the record-form and.
20422 return true;
20423}
20424
20425/// getAddrModeForFlags - Based on the set of address flags, select the most
20426/// optimal instruction format to match by.
20427PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
20428 // This is not a node we should be handling here.
20429 if (Flags == PPC::MOF_None)
20430 return PPC::AM_None;
20431 // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
20432 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
20433 if ((Flags & FlagSet) == FlagSet)
20434 return PPC::AM_DForm;
20435 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
20436 if ((Flags & FlagSet) == FlagSet)
20437 return PPC::AM_DSForm;
20438 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
20439 if ((Flags & FlagSet) == FlagSet)
20440 return PPC::AM_DQForm;
20441 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
20442 if ((Flags & FlagSet) == FlagSet)
20443 return PPC::AM_PrefixDForm;
20444 // If no other forms are selected, return an X-Form as it is the most
20445 // general addressing mode.
20446 return PPC::AM_XForm;
20447}
20448
20449/// Set alignment flags based on whether or not the Frame Index is aligned.
20450/// Utilized when computing flags for address computation when selecting
20451/// load and store instructions.
20452static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
20453 SelectionDAG &DAG) {
20454 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
20455 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
20456 if (!FI)
20457 return;
20459 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
20460 // If this is (add $FI, $S16Imm), the alignment flags are already set
20461 // based on the immediate. We just need to clear the alignment flags
20462 // if the FI alignment is weaker.
20463 if ((FrameIndexAlign % 4) != 0)
20464 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
20465 if ((FrameIndexAlign % 16) != 0)
20466 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
20467 // If the address is a plain FrameIndex, set alignment flags based on
20468 // FI alignment.
20469 if (!IsAdd) {
20470 if ((FrameIndexAlign % 4) == 0)
20471 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20472 if ((FrameIndexAlign % 16) == 0)
20473 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20474 }
20475}
20476
20477/// Given a node, compute flags that are used for address computation when
20478/// selecting load and store instructions. The flags computed are stored in
20479/// FlagSet. This function takes into account whether the node is a constant,
20480/// an ADD, OR, or a constant, and computes the address flags accordingly.
20481static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
20482 SelectionDAG &DAG) {
20483 // Set the alignment flags for the node depending on if the node is
20484 // 4-byte or 16-byte aligned.
20485 auto SetAlignFlagsForImm = [&](uint64_t Imm) {
20486 if ((Imm & 0x3) == 0)
20487 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20488 if ((Imm & 0xf) == 0)
20489 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20490 };
20491
20493 // All 32-bit constants can be computed as LIS + Disp.
20494 const APInt &ConstImm = CN->getAPIntValue();
20495 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
20496 FlagSet |= PPC::MOF_AddrIsSImm32;
20497 SetAlignFlagsForImm(ConstImm.getZExtValue());
20498 setAlignFlagsForFI(N, FlagSet, DAG);
20499 }
20500 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
20501 FlagSet |= PPC::MOF_RPlusSImm34;
20502 else // Let constant materialization handle large constants.
20503 FlagSet |= PPC::MOF_NotAddNorCst;
20504 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
20505 // This address can be represented as an addition of:
20506 // - Register + Imm16 (possibly a multiple of 4/16)
20507 // - Register + Imm34
20508 // - Register + PPCISD::Lo
20509 // - Register + Register
20510 // In any case, we won't have to match this as Base + Zero.
20511 SDValue RHS = N.getOperand(1);
20513 const APInt &ConstImm = CN->getAPIntValue();
20514 if (ConstImm.isSignedIntN(16)) {
20515 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
20516 SetAlignFlagsForImm(ConstImm.getZExtValue());
20517 setAlignFlagsForFI(N, FlagSet, DAG);
20518 }
20519 if (ConstImm.isSignedIntN(34))
20520 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
20521 else
20522 FlagSet |= PPC::MOF_RPlusR; // Register.
20523 } else if (RHS.getOpcode() == PPCISD::Lo && !RHS.getConstantOperandVal(1))
20524 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
20525 else
20526 FlagSet |= PPC::MOF_RPlusR;
20527 } else { // The address computation is not a constant or an addition.
20528 setAlignFlagsForFI(N, FlagSet, DAG);
20529 FlagSet |= PPC::MOF_NotAddNorCst;
20530 }
20531}
20532
20533static bool isPCRelNode(SDValue N) {
20534 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
20539}
20540
20541/// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
20542/// the address flags of the load/store instruction that is to be matched.
20543unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
20544 SelectionDAG &DAG) const {
20545 unsigned FlagSet = PPC::MOF_None;
20546
20547 // Compute subtarget flags.
20548 if (!Subtarget.hasP9Vector())
20549 FlagSet |= PPC::MOF_SubtargetBeforeP9;
20550 else
20551 FlagSet |= PPC::MOF_SubtargetP9;
20552
20553 if (Subtarget.hasPrefixInstrs())
20554 FlagSet |= PPC::MOF_SubtargetP10;
20555
20556 if (Subtarget.hasSPE())
20557 FlagSet |= PPC::MOF_SubtargetSPE;
20558
20559 // Check if we have a PCRel node and return early.
20560 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
20561 return FlagSet;
20562
20563 // If the node is the paired load/store intrinsics, compute flags for
20564 // address computation and return early.
20565 unsigned ParentOp = Parent->getOpcode();
20566 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
20567 (ParentOp == ISD::INTRINSIC_VOID))) {
20568 unsigned ID = Parent->getConstantOperandVal(1);
20569 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
20570 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
20571 ? Parent->getOperand(2)
20572 : Parent->getOperand(3);
20573 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
20574 FlagSet |= PPC::MOF_Vector;
20575 return FlagSet;
20576 }
20577 }
20578
20579 // Mark this as something we don't want to handle here if it is atomic
20580 // or pre-increment instruction.
20581 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
20582 if (LSB->isIndexed())
20583 return PPC::MOF_None;
20584
20585 // Compute in-memory type flags. This is based on if there are scalars,
20586 // floats or vectors.
20587 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
20588 assert(MN && "Parent should be a MemSDNode!");
20589 EVT MemVT = MN->getMemoryVT();
20590 unsigned Size = MemVT.getSizeInBits();
20591 if (MemVT.isScalarInteger()) {
20592 assert(Size <= 128 &&
20593 "Not expecting scalar integers larger than 16 bytes!");
20594 if (Size < 32)
20595 FlagSet |= PPC::MOF_SubWordInt;
20596 else if (Size == 32)
20597 FlagSet |= PPC::MOF_WordInt;
20598 else
20599 FlagSet |= PPC::MOF_DoubleWordInt;
20600 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
20601 if (Size == 128)
20602 FlagSet |= PPC::MOF_Vector;
20603 else if (Size == 256) {
20604 assert(Subtarget.pairedVectorMemops() &&
20605 "256-bit vectors are only available when paired vector memops is "
20606 "enabled!");
20607 FlagSet |= PPC::MOF_Vector;
20608 } else
20609 llvm_unreachable("Not expecting illegal vectors!");
20610 } else { // Floating point type: can be scalar, f128 or vector types.
20611 if (Size == 32 || Size == 64)
20612 FlagSet |= PPC::MOF_ScalarFloat;
20613 else if (MemVT == MVT::f128 || MemVT.isVector())
20614 FlagSet |= PPC::MOF_Vector;
20615 else
20616 llvm_unreachable("Not expecting illegal scalar floats!");
20617 }
20618
20619 // Compute flags for address computation.
20620 computeFlagsForAddressComputation(N, FlagSet, DAG);
20621
20622 // Compute type extension flags.
20623 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
20624 switch (LN->getExtensionType()) {
20625 case ISD::SEXTLOAD:
20626 FlagSet |= PPC::MOF_SExt;
20627 break;
20628 case ISD::EXTLOAD:
20629 case ISD::ZEXTLOAD:
20630 FlagSet |= PPC::MOF_ZExt;
20631 break;
20632 case ISD::NON_EXTLOAD:
20633 FlagSet |= PPC::MOF_NoExt;
20634 break;
20635 }
20636 } else
20637 FlagSet |= PPC::MOF_NoExt;
20638
20639 // For integers, no extension is the same as zero extension.
20640 // We set the extension mode to zero extension so we don't have
20641 // to add separate entries in AddrModesMap for loads and stores.
20642 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
20643 FlagSet |= PPC::MOF_ZExt;
20644 FlagSet &= ~PPC::MOF_NoExt;
20645 }
20646
20647 // If we don't have prefixed instructions, 34-bit constants should be
20648 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
20649 bool IsNonP1034BitConst =
20651 FlagSet) == PPC::MOF_RPlusSImm34;
20652 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
20653 IsNonP1034BitConst)
20654 FlagSet |= PPC::MOF_NotAddNorCst;
20655
20656 return FlagSet;
20657}
20658
20659/// SelectForceXFormMode - Given the specified address, force it to be
20660/// represented as an indexed [r+r] operation (an XForm instruction).
20662 SDValue &Base,
20663 SelectionDAG &DAG) const {
20664
20666 int16_t ForceXFormImm = 0;
20667 if (provablyDisjointOr(DAG, N) &&
20668 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
20669 Disp = N.getOperand(0);
20670 Base = N.getOperand(1);
20671 return Mode;
20672 }
20673
20674 // If the address is the result of an add, we will utilize the fact that the
20675 // address calculation includes an implicit add. However, we can reduce
20676 // register pressure if we do not materialize a constant just for use as the
20677 // index register. We only get rid of the add if it is not an add of a
20678 // value and a 16-bit signed constant and both have a single use.
20679 if (N.getOpcode() == ISD::ADD &&
20680 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
20681 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
20682 Disp = N.getOperand(0);
20683 Base = N.getOperand(1);
20684 return Mode;
20685 }
20686
20687 // Otherwise, use R0 as the base register.
20688 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20689 N.getValueType());
20690 Base = N;
20691
20692 return Mode;
20693}
20694
20696 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
20697 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
20698 EVT ValVT = Val.getValueType();
20699 // If we are splitting a scalar integer into f64 parts (i.e. so they
20700 // can be placed into VFRC registers), we need to zero extend and
20701 // bitcast the values. This will ensure the value is placed into a
20702 // VSR using direct moves or stack operations as needed.
20703 if (PartVT == MVT::f64 &&
20704 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
20705 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
20706 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
20707 Parts[0] = Val;
20708 return true;
20709 }
20710 return false;
20711}
20712
20713SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
20714 SelectionDAG &DAG) const {
20715 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20717 EVT RetVT = Op.getValueType();
20718 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
20719 SDValue Callee =
20720 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
20721 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetTy, false);
20723 for (const SDValue &N : Op->op_values()) {
20724 EVT ArgVT = N.getValueType();
20725 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
20726 TargetLowering::ArgListEntry Entry(N, ArgTy);
20727 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, SignExtend);
20728 Entry.IsZExt = !Entry.IsSExt;
20729 Args.push_back(Entry);
20730 }
20731
20732 SDValue InChain = DAG.getEntryNode();
20733 SDValue TCChain = InChain;
20734 const Function &F = DAG.getMachineFunction().getFunction();
20735 bool isTailCall =
20736 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
20737 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
20738 if (isTailCall)
20739 InChain = TCChain;
20740 CLI.setDebugLoc(SDLoc(Op))
20741 .setChain(InChain)
20742 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
20743 .setTailCall(isTailCall)
20744 .setSExtResult(SignExtend)
20745 .setZExtResult(!SignExtend)
20747 return TLI.LowerCallTo(CLI).first;
20748}
20749
20750SDValue PPCTargetLowering::lowerLibCallBasedOnType(
20751 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
20752 SelectionDAG &DAG) const {
20753 if (Op.getValueType() == MVT::f32)
20754 return lowerToLibCall(LibCallFloatName, Op, DAG);
20755
20756 if (Op.getValueType() == MVT::f64)
20757 return lowerToLibCall(LibCallDoubleName, Op, DAG);
20758
20759 return SDValue();
20760}
20761
20762bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
20763 SDNodeFlags Flags = Op.getNode()->getFlags();
20764 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
20765 Flags.hasNoNaNs() && Flags.hasNoInfs();
20766}
20767
20768bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
20769 return Op.getNode()->getFlags().hasApproximateFuncs();
20770}
20771
20772bool PPCTargetLowering::isScalarMASSConversionEnabled() const {
20774}
20775
20776SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
20777 const char *LibCallFloatName,
20778 const char *LibCallDoubleNameFinite,
20779 const char *LibCallFloatNameFinite,
20780 SDValue Op,
20781 SelectionDAG &DAG) const {
20782 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op))
20783 return SDValue();
20784
20785 if (!isLowringToMASSFiniteSafe(Op))
20786 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
20787 DAG);
20788
20789 return lowerLibCallBasedOnType(LibCallFloatNameFinite,
20790 LibCallDoubleNameFinite, Op, DAG);
20791}
20792
20793SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
20794 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
20795 "__xl_powf_finite", Op, DAG);
20796}
20797
20798SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
20799 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
20800 "__xl_sinf_finite", Op, DAG);
20801}
20802
20803SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
20804 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
20805 "__xl_cosf_finite", Op, DAG);
20806}
20807
20808SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
20809 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
20810 "__xl_logf_finite", Op, DAG);
20811}
20812
20813SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
20814 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
20815 "__xl_log10f_finite", Op, DAG);
20816}
20817
20818SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
20819 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
20820 "__xl_expf_finite", Op, DAG);
20821}
20822
20823// If we happen to match to an aligned D-Form, check if the Frame Index is
20824// adequately aligned. If it is not, reset the mode to match to X-Form.
20825static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
20828 return;
20829 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
20832}
20833
20834/// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
20835/// compute the address flags of the node, get the optimal address mode based
20836/// on the flags, and set the Base and Disp based on the address mode.
20838 SDValue N, SDValue &Disp,
20839 SDValue &Base,
20840 SelectionDAG &DAG,
20841 MaybeAlign Align) const {
20842 SDLoc DL(Parent);
20843
20844 // Compute the address flags.
20845 unsigned Flags = computeMOFlags(Parent, N, DAG);
20846
20847 // Get the optimal address mode based on the Flags.
20848 PPC::AddrMode Mode = getAddrModeForFlags(Flags);
20849
20850 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
20851 // Select an X-Form load if it is not.
20852 setXFormForUnalignedFI(N, Flags, Mode);
20853
20854 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
20855 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
20856 assert(Subtarget.isUsingPCRelativeCalls() &&
20857 "Must be using PC-Relative calls when a valid PC-Relative node is "
20858 "present!");
20859 Mode = PPC::AM_PCRel;
20860 }
20861
20862 // Set Base and Disp accordingly depending on the address mode.
20863 switch (Mode) {
20864 case PPC::AM_DForm:
20865 case PPC::AM_DSForm:
20866 case PPC::AM_DQForm: {
20867 // This is a register plus a 16-bit immediate. The base will be the
20868 // register and the displacement will be the immediate unless it
20869 // isn't sufficiently aligned.
20870 if (Flags & PPC::MOF_RPlusSImm16) {
20871 SDValue Op0 = N.getOperand(0);
20872 SDValue Op1 = N.getOperand(1);
20873 int16_t Imm = Op1->getAsZExtVal();
20874 if (!Align || isAligned(*Align, Imm)) {
20875 Disp = DAG.getSignedTargetConstant(Imm, DL, N.getValueType());
20876 Base = Op0;
20878 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20879 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
20880 }
20881 break;
20882 }
20883 }
20884 // This is a register plus the @lo relocation. The base is the register
20885 // and the displacement is the global address.
20886 else if (Flags & PPC::MOF_RPlusLo) {
20887 Disp = N.getOperand(1).getOperand(0); // The global address.
20892 Base = N.getOperand(0);
20893 break;
20894 }
20895 // This is a constant address at most 32 bits. The base will be
20896 // zero or load-immediate-shifted and the displacement will be
20897 // the low 16 bits of the address.
20898 else if (Flags & PPC::MOF_AddrIsSImm32) {
20899 auto *CN = cast<ConstantSDNode>(N);
20900 EVT CNType = CN->getValueType(0);
20901 uint64_t CNImm = CN->getZExtValue();
20902 // If this address fits entirely in a 16-bit sext immediate field, codegen
20903 // this as "d, 0".
20904 int16_t Imm;
20905 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
20906 Disp = DAG.getSignedTargetConstant(Imm, DL, CNType);
20907 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20908 CNType);
20909 break;
20910 }
20911 // Handle 32-bit sext immediate with LIS + Addr mode.
20912 if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
20913 (!Align || isAligned(*Align, CNImm))) {
20914 int32_t Addr = (int32_t)CNImm;
20915 // Otherwise, break this down into LIS + Disp.
20916 Disp = DAG.getSignedTargetConstant((int16_t)Addr, DL, MVT::i32);
20917 Base = DAG.getSignedTargetConstant((Addr - (int16_t)Addr) >> 16, DL,
20918 MVT::i32);
20919 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
20920 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
20921 break;
20922 }
20923 }
20924 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
20925 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
20927 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20928 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
20929 } else
20930 Base = N;
20931 break;
20932 }
20933 case PPC::AM_PrefixDForm: {
20934 int64_t Imm34 = 0;
20935 unsigned Opcode = N.getOpcode();
20936 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
20937 (isIntS34Immediate(N.getOperand(1), Imm34))) {
20938 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
20939 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
20940 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
20941 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
20942 else
20943 Base = N.getOperand(0);
20944 } else if (isIntS34Immediate(N, Imm34)) {
20945 // The address is a 34-bit signed immediate.
20946 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
20947 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
20948 }
20949 break;
20950 }
20951 case PPC::AM_PCRel: {
20952 // When selecting PC-Relative instructions, "Base" is not utilized as
20953 // we select the address as [PC+imm].
20954 Disp = N;
20955 break;
20956 }
20957 case PPC::AM_None:
20958 break;
20959 default: { // By default, X-Form is always available to be selected.
20960 // When a frame index is not aligned, we also match by XForm.
20962 Base = FI ? N : N.getOperand(1);
20963 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20964 N.getValueType())
20965 : N.getOperand(0);
20966 break;
20967 }
20968 }
20969 return Mode;
20970}
20971
20973 bool Return,
20974 bool IsVarArg) const {
20975 switch (CC) {
20976 case CallingConv::Cold:
20977 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF);
20978 default:
20979 return CC_PPC64_ELF;
20980 }
20981}
20982
20984 return Subtarget.isPPC64() && Subtarget.hasQuadwordAtomics();
20985}
20986
20989 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
20990 if (shouldInlineQuadwordAtomics() && Size == 128)
20992
20993 switch (AI->getOperation()) {
20999 default:
21001 }
21002
21003 llvm_unreachable("unreachable atomicrmw operation");
21004}
21005
21014
21015static Intrinsic::ID
21017 switch (BinOp) {
21018 default:
21019 llvm_unreachable("Unexpected AtomicRMW BinOp");
21021 return Intrinsic::ppc_atomicrmw_xchg_i128;
21022 case AtomicRMWInst::Add:
21023 return Intrinsic::ppc_atomicrmw_add_i128;
21024 case AtomicRMWInst::Sub:
21025 return Intrinsic::ppc_atomicrmw_sub_i128;
21026 case AtomicRMWInst::And:
21027 return Intrinsic::ppc_atomicrmw_and_i128;
21028 case AtomicRMWInst::Or:
21029 return Intrinsic::ppc_atomicrmw_or_i128;
21030 case AtomicRMWInst::Xor:
21031 return Intrinsic::ppc_atomicrmw_xor_i128;
21033 return Intrinsic::ppc_atomicrmw_nand_i128;
21034 }
21035}
21036
21038 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
21039 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
21040 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21041 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21042 Type *ValTy = Incr->getType();
21043 assert(ValTy->getPrimitiveSizeInBits() == 128);
21044 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21045 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
21046 Value *IncrHi =
21047 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
21048 Value *LoHi = Builder.CreateIntrinsic(
21050 {AlignedAddr, IncrLo, IncrHi});
21051 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21052 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21053 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21054 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21055 return Builder.CreateOr(
21056 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21057}
21058
21060 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
21061 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
21062 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21063 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21064 Type *ValTy = CmpVal->getType();
21065 assert(ValTy->getPrimitiveSizeInBits() == 128);
21066 Function *IntCmpXchg =
21067 Intrinsic::getOrInsertDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
21068 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21069 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
21070 Value *CmpHi =
21071 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
21072 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
21073 Value *NewHi =
21074 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
21075 emitLeadingFence(Builder, CI, Ord);
21076 Value *LoHi =
21077 Builder.CreateCall(IntCmpXchg, {AlignedAddr, CmpLo, CmpHi, NewLo, NewHi});
21078 emitTrailingFence(Builder, CI, Ord);
21079 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21080 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21081 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21082 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21083 return Builder.CreateOr(
21084 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21085}
21086
21088 return Subtarget.useCRBits();
21089}
21090
21091/// Shuffle masks for vectors of bits are not legal as such vectors are
21092/// reserved for MMA/DM.
21093bool PPCTargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
21094 if (VT.getScalarType() == MVT::i1)
21095 return false;
21096 return TargetLowering::isShuffleMaskLegal(Mask, VT);
21097}
21098
21099// Optimize the following patterns using vbpermq/vbpermd:
21100// i16 = bitcast(v16i1 truncate(v16i8))
21101// i8 = bitcast(v8i1 truncate(v8i16))
21102// i8 = bitcast(v8i1 truncate(v8i8))
21103SDValue PPCTargetLowering::DAGCombineBitcast(SDNode *N,
21104 DAGCombinerInfo &DCI) const {
21105 SDValue Op0 = N->getOperand(0);
21106 if (Op0.getOpcode() != ISD::TRUNCATE)
21107 return SDValue();
21108 SDValue Src = Op0.getOperand(0);
21109 EVT ResVT = N->getValueType(0);
21110 EVT TruncResVT = Op0.getValueType();
21111 EVT SrcVT = Src.getValueType();
21112 SDLoc dl(N);
21113 SelectionDAG &DAG = DCI.DAG;
21114 bool IsLittleEndian = Subtarget.isLittleEndian();
21115
21116 if (ResVT != MVT::i16 && ResVT != MVT::i8)
21117 return SDValue();
21118 SDValue VBPerm =
21119 GenerateVBPERM(DAG, dl, Src, SrcVT, TruncResVT, IsLittleEndian);
21120 if (!VBPerm)
21121 return SDValue();
21122 SDValue ForExtract = DAG.getBitcast(MVT::v4i32, VBPerm);
21123 SDValue Extracted =
21124 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, ForExtract,
21125 DAG.getIntPtrConstant(IsLittleEndian ? 2 : 1, dl));
21126 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, Extracted);
21127}
21128
21129SDValue PPCTargetLowering::GenerateVBPERM(SelectionDAG &DAG, SDLoc dl,
21130 SDValue Src, EVT SrcVT, EVT ResVT,
21131 bool IsLE) const {
21132 bool IsV16i8 = (ResVT == MVT::v16i1 && SrcVT == MVT::v16i8);
21133 bool IsV8i16 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i16);
21134 bool IsV8i8 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i8);
21135
21136 if (!IsV16i8 && !IsV8i16 && !IsV8i8)
21137 return SDValue();
21138
21139 if (IsV8i8) {
21140 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i8,
21141 DAG.getUNDEF(MVT::v16i8), Src,
21142 DAG.getIntPtrConstant(0, dl));
21143 }
21144 SmallVector<int, 16> BitIndices(16, 128);
21145 unsigned NumElts = SrcVT.getVectorNumElements();
21146 unsigned EltSize = SrcVT.getScalarType().getSizeInBits();
21147 for (int Idx = 0, End = SrcVT.getVectorNumElements(); Idx < End; Idx++) {
21148 BitIndices[Idx] = EltSize * (NumElts - Idx) - 1;
21149 if (IsV8i8 && IsLE)
21150 BitIndices[Idx] += 64;
21151 }
21152 if (!IsLE)
21153 std::reverse(BitIndices.begin(), BitIndices.end());
21155 for (auto Idx : BitIndices)
21156 BVOps.push_back(DAG.getConstant(Idx, dl, MVT::i8));
21157 SDValue VRB = DAG.getBuildVector(MVT::v16i8, dl, BVOps);
21158 return DAG.getNode(
21159 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v16i8,
21160 DAG.getConstant(Intrinsic::ppc_altivec_vbpermq, dl, MVT::i32),
21161 DAG.getBitcast(MVT::v16i8, Src), VRB);
21162}
21163
21164// For Power8/9, optimize vec splats of small FP values that can be
21165// represented as integers. Use vspltisw + xvcvsxwdp/xvcvsxwsp instead of
21166// loading from constant pool.
21167SDValue PPCTargetLowering::LowerVecSplatSmallFP(SDValue Op, SelectionDAG &DAG,
21168 bool BVNIsConstantSplat,
21169 unsigned SplatBitSize) const {
21170
21171 if (!BVNIsConstantSplat || !Subtarget.hasVSX() || !Subtarget.hasP8Vector() ||
21172 Subtarget.hasP10Vector())
21173 return SDValue();
21174
21175 EVT VT = Op->getValueType(0);
21176 if (!((SplatBitSize == 64 && VT == MVT::v2f64) ||
21177 (SplatBitSize == 32 && VT == MVT::v4f32)))
21178 return SDValue();
21179
21180 auto *CN = dyn_cast<ConstantFPSDNode>(Op.getOperand(0));
21181 if (!CN)
21182 return SDValue();
21183
21184 APFloat APFloatVal = CN->getValueAPF();
21185 bool IsExact;
21186 APSInt IntResult(16, false);
21187 APFloatVal.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
21188
21189 if (!(IsExact && IntResult <= 15 && IntResult >= -16 && !APFloatVal.isZero()))
21190 return SDValue();
21191
21192 int64_t IntVal = IntResult.getSExtValue();
21193
21194 SDLoc dl(Op);
21195 SDValue IntSplat = getCanonicalConstSplat(IntVal, 4, MVT::v4i32, DAG, dl);
21196
21197 if (SplatBitSize == 64)
21198 return DAG.getNode(
21199 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v2f64,
21200 DAG.getConstant(Intrinsic::ppc_vsx_xvcvsxwdp, dl, MVT::i32), IntSplat);
21201
21202 return DAG.getNode(PPCISD::XVCVSXWSP, dl, MVT::v4f32, IntSplat);
21203}
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)
unsigned Imm
unsigned uint64_t
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:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< 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
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static bool isConstantOrUndef(const SDValue Op)
#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:304
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:307
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6010
bool isDenormal() const
Definition APFloat.h:1584
bool isZero() const
Definition APFloat.h:1579
APInt bitcastToAPInt() const
Definition APFloat.h:1475
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
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:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:446
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1417
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:432
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
double bitsToDouble() const
Converts APInt bits to a double.
Definition APInt.h:1743
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
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:699
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:360
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:777
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
arg_iterator arg_begin()
Definition Function.h:853
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
size_t arg_size() const
Definition Function.h:886
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
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:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
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 or function.
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.
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...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & 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:68
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.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
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
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
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.
bool isJumpTableRelative() const override
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(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
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...
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 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 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
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 SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI 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 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 getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI 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 SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI 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
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:274
@ 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:149
@ MO_PIC_LO_FLAG
MO_PIC_LO_FLAG = MO_PIC_FLAG | MO_LO.
Definition PPC.h:197
@ MO_TPREL_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TPREL_FLAG.
Definition PPC.h:200
@ 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:175
@ MO_GOT_PCREL_FLAG
MO_GOT_PCREL_FLAG = MO_PCREL_FLAG | MO_GOT_FLAG.
Definition PPC.h:206
@ 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:157
@ MO_PCREL_FLAG
MO_PCREL_FLAG - If this bit is set, the symbol reference is relative to the current instruction addre...
Definition PPC.h:124
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition PPC.h:153
@ MO_TLS_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TLS.
Definition PPC.h:203
@ MO_TPREL_HA
Definition PPC.h:182
@ MO_PLT
On PPC, the 12 bits are not enough for all target operand flags.
Definition PPC.h:116
@ MO_TLS
Symbol for VK_TLS fixup attached to an ADD instruction.
Definition PPC.h:191
@ 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:143
@ MO_TPREL_LO
Definition PPC.h:181
@ MO_LO
MO_LO, MO_HA - lo16(symbol) and ha16(symbol)
Definition PPC.h:178
@ 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:169
@ MO_PIC_HA_FLAG
MO_PIC_HA_FLAG = MO_PIC_FLAG | MO_HA.
Definition PPC.h:194
@ 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:138
@ 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:163
@ MO_HA
Definition PPC.h:179
@ MO_PIC_FLAG
MO_PIC_FLAG - If this bit is set, the symbol reference is relative to the function's picbase,...
Definition PPC.h:120
@ 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:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
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:577
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:102
@ 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
@ Fast
Assign the register banks as fast as possible (default).
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:549
constexpr unsigned BitWidth
bool CC_PPC32_SVR4_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:567
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.