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 RC = &PPC::VRRCRegClass;
4285 break;
4286 case MVT::v4f32:
4287 RC = &PPC::VRRCRegClass;
4288 break;
4289 case MVT::v2f64:
4290 case MVT::v2i64:
4291 RC = &PPC::VRRCRegClass;
4292 break;
4293 }
4294
4295 SDValue ArgValue;
4296 // Transform the arguments stored in physical registers into
4297 // virtual ones.
4298 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4299 assert(i + 1 < e && "No second half of double precision argument");
4300 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4301 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4302 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4303 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4304 if (!Subtarget.isLittleEndian())
4305 std::swap (ArgValueLo, ArgValueHi);
4306 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4307 ArgValueHi);
4308 } else {
4309 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4310 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4311 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4312 if (ValVT == MVT::i1)
4313 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4314 }
4315
4316 InVals.push_back(ArgValue);
4317 } else {
4318 // Argument stored in memory.
4319 assert(VA.isMemLoc());
4320
4321 // Get the extended size of the argument type in stack
4322 unsigned ArgSize = VA.getLocVT().getStoreSize();
4323 // Get the actual size of the argument type
4324 unsigned ObjSize = VA.getValVT().getStoreSize();
4325 unsigned ArgOffset = VA.getLocMemOffset();
4326 // Stack objects in PPC32 are right justified.
4327 ArgOffset += ArgSize - ObjSize;
4328 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4329
4330 // Create load nodes to retrieve arguments from the stack.
4331 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4332 InVals.push_back(
4333 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4334 }
4335 }
4336
4337 // Assign locations to all of the incoming aggregate by value arguments.
4338 // Aggregates passed by value are stored in the local variable space of the
4339 // caller's stack frame, right above the parameter list area.
4340 SmallVector<CCValAssign, 16> ByValArgLocs;
4341 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4342 ByValArgLocs, *DAG.getContext());
4343
4344 // Reserve stack space for the allocations in CCInfo.
4345 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
4346
4347 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4348
4349 // Area that is at least reserved in the caller of this function.
4350 unsigned MinReservedArea = CCByValInfo.getStackSize();
4351 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4352
4353 // Set the size that is at least reserved in caller of this function. Tail
4354 // call optimized function's reserved stack space needs to be aligned so that
4355 // taking the difference between two stack areas will result in an aligned
4356 // stack.
4357 MinReservedArea =
4358 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4359 FuncInfo->setMinReservedArea(MinReservedArea);
4360
4362
4363 // If the function takes variable number of arguments, make a frame index for
4364 // the start of the first vararg value... for expansion of llvm.va_start.
4365 if (isVarArg) {
4366 static const MCPhysReg GPArgRegs[] = {
4367 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4368 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4369 };
4370 const unsigned NumGPArgRegs = std::size(GPArgRegs);
4371
4372 static const MCPhysReg FPArgRegs[] = {
4373 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4374 PPC::F8
4375 };
4376 unsigned NumFPArgRegs = std::size(FPArgRegs);
4377
4378 if (useSoftFloat() || hasSPE())
4379 NumFPArgRegs = 0;
4380
4381 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4382 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4383
4384 // Make room for NumGPArgRegs and NumFPArgRegs.
4385 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4386 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4387
4389 PtrVT.getSizeInBits() / 8, CCInfo.getStackSize(), true));
4390
4391 FuncInfo->setVarArgsFrameIndex(
4392 MFI.CreateStackObject(Depth, Align(8), false));
4393 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4394
4395 // The fixed integer arguments of a variadic function are stored to the
4396 // VarArgsFrameIndex on the stack so that they may be loaded by
4397 // dereferencing the result of va_next.
4398 for (MCPhysReg GPArgReg : GPArgRegs) {
4399 // Get an existing live-in vreg, or add a new one.
4400 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgReg);
4401 if (!VReg)
4402 VReg = MF.addLiveIn(GPArgReg, &PPC::GPRCRegClass);
4403
4404 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4405 SDValue Store =
4406 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4407 MemOps.push_back(Store);
4408 // Increment the address by four for the next argument to store
4409 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4410 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4411 }
4412
4413 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4414 // is set.
4415 // The double arguments are stored to the VarArgsFrameIndex
4416 // on the stack.
4417 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4418 // Get an existing live-in vreg, or add a new one.
4419 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4420 if (!VReg)
4421 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4422
4423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4424 SDValue Store =
4425 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4426 MemOps.push_back(Store);
4427 // Increment the address by eight for the next argument to store
4428 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4429 PtrVT);
4430 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4431 }
4432 }
4433
4434 if (!MemOps.empty())
4435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4436
4437 return Chain;
4438}
4439
4440// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4441// value to MVT::i64 and then truncate to the correct register size.
4442SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4443 EVT ObjectVT, SelectionDAG &DAG,
4444 SDValue ArgVal,
4445 const SDLoc &dl) const {
4446 if (Flags.isSExt())
4447 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4448 DAG.getValueType(ObjectVT));
4449 else if (Flags.isZExt())
4450 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4451 DAG.getValueType(ObjectVT));
4452
4453 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4454}
4455
4456SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4457 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4458 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4459 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4460 // TODO: add description of PPC stack frame format, or at least some docs.
4461 //
4462 bool isELFv2ABI = Subtarget.isELFv2ABI();
4463 bool isLittleEndian = Subtarget.isLittleEndian();
4465 MachineFrameInfo &MFI = MF.getFrameInfo();
4466 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4467
4468 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4469 "fastcc not supported on varargs functions");
4470
4471 EVT PtrVT = getPointerTy(MF.getDataLayout());
4472 // Potential tail calls could cause overwriting of argument stack slots.
4473 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4474 (CallConv == CallingConv::Fast));
4475 unsigned PtrByteSize = 8;
4476 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4477
4478 static const MCPhysReg GPR[] = {
4479 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4480 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4481 };
4482 static const MCPhysReg VR[] = {
4483 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4484 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4485 };
4486
4487 const unsigned Num_GPR_Regs = std::size(GPR);
4488 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4489 const unsigned Num_VR_Regs = std::size(VR);
4490
4491 // Do a first pass over the arguments to determine whether the ABI
4492 // guarantees that our caller has allocated the parameter save area
4493 // on its stack frame. In the ELFv1 ABI, this is always the case;
4494 // in the ELFv2 ABI, it is true if this is a vararg function or if
4495 // any parameter is located in a stack slot.
4496
4497 bool HasParameterArea = !isELFv2ABI || isVarArg;
4498 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4499 unsigned NumBytes = LinkageSize;
4500 unsigned AvailableFPRs = Num_FPR_Regs;
4501 unsigned AvailableVRs = Num_VR_Regs;
4502 for (const ISD::InputArg &In : Ins) {
4503 if (In.Flags.isNest())
4504 continue;
4505
4506 if (CalculateStackSlotUsed(In.VT, In.ArgVT, In.Flags, PtrByteSize,
4507 LinkageSize, ParamAreaSize, NumBytes,
4508 AvailableFPRs, AvailableVRs))
4509 HasParameterArea = true;
4510 }
4511
4512 // Add DAG nodes to load the arguments or copy them out of registers. On
4513 // entry to a function on PPC, the arguments start after the linkage area,
4514 // although the first ones are often in registers.
4515
4516 unsigned ArgOffset = LinkageSize;
4517 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4520 unsigned CurArgIdx = 0;
4521 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4522 SDValue ArgVal;
4523 bool needsLoad = false;
4524 EVT ObjectVT = Ins[ArgNo].VT;
4525 EVT OrigVT = Ins[ArgNo].ArgVT;
4526 unsigned ObjSize = ObjectVT.getStoreSize();
4527 unsigned ArgSize = ObjSize;
4528 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4529 if (Ins[ArgNo].isOrigArg()) {
4530 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4531 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4532 }
4533 // We re-align the argument offset for each argument, except when using the
4534 // fast calling convention, when we need to make sure we do that only when
4535 // we'll actually use a stack slot.
4536 unsigned CurArgOffset;
4538 auto ComputeArgOffset = [&]() {
4539 /* Respect alignment of argument on the stack. */
4540 Alignment =
4541 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4542 ArgOffset = alignTo(ArgOffset, Alignment);
4543 CurArgOffset = ArgOffset;
4544 };
4545
4546 if (CallConv != CallingConv::Fast) {
4547 ComputeArgOffset();
4548
4549 /* Compute GPR index associated with argument offset. */
4550 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4551 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4552 }
4553
4554 // FIXME the codegen can be much improved in some cases.
4555 // We do not have to keep everything in memory.
4556 if (Flags.isByVal()) {
4557 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4558
4559 if (CallConv == CallingConv::Fast)
4560 ComputeArgOffset();
4561
4562 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4563 ObjSize = Flags.getByValSize();
4564 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4565 // Empty aggregate parameters do not take up registers. Examples:
4566 // struct { } a;
4567 // union { } b;
4568 // int c[0];
4569 // etc. However, we have to provide a place-holder in InVals, so
4570 // pretend we have an 8-byte item at the current address for that
4571 // purpose.
4572 if (!ObjSize) {
4573 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4574 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4575 InVals.push_back(FIN);
4576 continue;
4577 }
4578
4579 // Create a stack object covering all stack doublewords occupied
4580 // by the argument. If the argument is (fully or partially) on
4581 // the stack, or if the argument is fully in registers but the
4582 // caller has allocated the parameter save anyway, we can refer
4583 // directly to the caller's stack frame. Otherwise, create a
4584 // local copy in our own frame.
4585 int FI;
4586 if (HasParameterArea ||
4587 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4588 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4589 else
4590 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4591 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4592
4593 // Handle aggregates smaller than 8 bytes.
4594 if (ObjSize < PtrByteSize) {
4595 // The value of the object is its address, which differs from the
4596 // address of the enclosing doubleword on big-endian systems.
4597 SDValue Arg = FIN;
4598 if (!isLittleEndian) {
4599 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4600 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4601 }
4602 InVals.push_back(Arg);
4603
4604 if (GPR_idx != Num_GPR_Regs) {
4605 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4606 FuncInfo->addLiveInAttr(VReg, Flags);
4607 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4608 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4609 SDValue Store =
4610 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4611 MachinePointerInfo(&*FuncArg), ObjType);
4612 MemOps.push_back(Store);
4613 }
4614 // Whether we copied from a register or not, advance the offset
4615 // into the parameter save area by a full doubleword.
4616 ArgOffset += PtrByteSize;
4617 continue;
4618 }
4619
4620 // The value of the object is its address, which is the address of
4621 // its first stack doubleword.
4622 InVals.push_back(FIN);
4623
4624 // Store whatever pieces of the object are in registers to memory.
4625 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4626 if (GPR_idx == Num_GPR_Regs)
4627 break;
4628
4629 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4630 FuncInfo->addLiveInAttr(VReg, Flags);
4631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4632 SDValue Addr = FIN;
4633 if (j) {
4634 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4635 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4636 }
4637 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4638 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4639 SDValue Store =
4640 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4641 MachinePointerInfo(&*FuncArg, j), ObjType);
4642 MemOps.push_back(Store);
4643 ++GPR_idx;
4644 }
4645 ArgOffset += ArgSize;
4646 continue;
4647 }
4648
4649 switch (ObjectVT.getSimpleVT().SimpleTy) {
4650 default: llvm_unreachable("Unhandled argument type!");
4651 case MVT::i1:
4652 case MVT::i32:
4653 case MVT::i64:
4654 if (Flags.isNest()) {
4655 // The 'nest' parameter, if any, is passed in R11.
4656 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4657 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4658
4659 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4660 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4661
4662 break;
4663 }
4664
4665 // These can be scalar arguments or elements of an integer array type
4666 // passed directly. Clang may use those instead of "byval" aggregate
4667 // types to avoid forcing arguments to memory unnecessarily.
4668 if (GPR_idx != Num_GPR_Regs) {
4669 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4670 FuncInfo->addLiveInAttr(VReg, Flags);
4671 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4672
4673 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4674 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4675 // value to MVT::i64 and then truncate to the correct register size.
4676 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4677 } else {
4678 if (CallConv == CallingConv::Fast)
4679 ComputeArgOffset();
4680
4681 needsLoad = true;
4682 ArgSize = PtrByteSize;
4683 }
4684 if (CallConv != CallingConv::Fast || needsLoad)
4685 ArgOffset += 8;
4686 break;
4687
4688 case MVT::f32:
4689 case MVT::f64:
4690 // These can be scalar arguments or elements of a float array type
4691 // passed directly. The latter are used to implement ELFv2 homogenous
4692 // float aggregates.
4693 if (FPR_idx != Num_FPR_Regs) {
4694 unsigned VReg;
4695
4696 if (ObjectVT == MVT::f32)
4697 VReg = MF.addLiveIn(FPR[FPR_idx],
4698 Subtarget.hasP8Vector()
4699 ? &PPC::VSSRCRegClass
4700 : &PPC::F4RCRegClass);
4701 else
4702 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4703 ? &PPC::VSFRCRegClass
4704 : &PPC::F8RCRegClass);
4705
4706 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4707 ++FPR_idx;
4708 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4709 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4710 // once we support fp <-> gpr moves.
4711
4712 // This can only ever happen in the presence of f32 array types,
4713 // since otherwise we never run out of FPRs before running out
4714 // of GPRs.
4715 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4716 FuncInfo->addLiveInAttr(VReg, Flags);
4717 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4718
4719 if (ObjectVT == MVT::f32) {
4720 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4721 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4722 DAG.getConstant(32, dl, MVT::i32));
4723 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4724 }
4725
4726 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4727 } else {
4728 if (CallConv == CallingConv::Fast)
4729 ComputeArgOffset();
4730
4731 needsLoad = true;
4732 }
4733
4734 // When passing an array of floats, the array occupies consecutive
4735 // space in the argument area; only round up to the next doubleword
4736 // at the end of the array. Otherwise, each float takes 8 bytes.
4737 if (CallConv != CallingConv::Fast || needsLoad) {
4738 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4739 ArgOffset += ArgSize;
4740 if (Flags.isInConsecutiveRegsLast())
4741 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4742 }
4743 break;
4744 case MVT::v4f32:
4745 case MVT::v4i32:
4746 case MVT::v8i16:
4747 case MVT::v16i8:
4748 case MVT::v2f64:
4749 case MVT::v2i64:
4750 case MVT::v1i128:
4751 case MVT::f128:
4752 // These can be scalar arguments or elements of a vector array type
4753 // passed directly. The latter are used to implement ELFv2 homogenous
4754 // vector aggregates.
4755 if (VR_idx != Num_VR_Regs) {
4756 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4757 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4758 ++VR_idx;
4759 } else {
4760 if (CallConv == CallingConv::Fast)
4761 ComputeArgOffset();
4762 needsLoad = true;
4763 }
4764 if (CallConv != CallingConv::Fast || needsLoad)
4765 ArgOffset += 16;
4766 break;
4767 }
4768
4769 // We need to load the argument to a virtual register if we determined
4770 // above that we ran out of physical registers of the appropriate type.
4771 if (needsLoad) {
4772 if (ObjSize < ArgSize && !isLittleEndian)
4773 CurArgOffset += ArgSize - ObjSize;
4774 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4775 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4776 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4777 }
4778
4779 InVals.push_back(ArgVal);
4780 }
4781
4782 // Area that is at least reserved in the caller of this function.
4783 unsigned MinReservedArea;
4784 if (HasParameterArea)
4785 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4786 else
4787 MinReservedArea = LinkageSize;
4788
4789 // Set the size that is at least reserved in caller of this function. Tail
4790 // call optimized functions' reserved stack space needs to be aligned so that
4791 // taking the difference between two stack areas will result in an aligned
4792 // stack.
4793 MinReservedArea =
4794 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4795 FuncInfo->setMinReservedArea(MinReservedArea);
4796
4797 // If the function takes variable number of arguments, make a frame index for
4798 // the start of the first vararg value... for expansion of llvm.va_start.
4799 // On ELFv2ABI spec, it writes:
4800 // C programs that are intended to be *portable* across different compilers
4801 // and architectures must use the header file <stdarg.h> to deal with variable
4802 // argument lists.
4803 if (isVarArg && MFI.hasVAStart()) {
4804 int Depth = ArgOffset;
4805
4806 FuncInfo->setVarArgsFrameIndex(
4807 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4808 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4809
4810 // If this function is vararg, store any remaining integer argument regs
4811 // to their spots on the stack so that they may be loaded by dereferencing
4812 // the result of va_next.
4813 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4814 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4815 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4816 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4817 SDValue Store =
4818 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4819 MemOps.push_back(Store);
4820 // Increment the address by four for the next argument to store
4821 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4822 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4823 }
4824 }
4825
4826 if (!MemOps.empty())
4827 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4828
4829 return Chain;
4830}
4831
4832/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4833/// adjusted to accommodate the arguments for the tailcall.
4834static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4835 unsigned ParamSize) {
4836
4837 if (!isTailCall) return 0;
4838
4840 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4841 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4842 // Remember only if the new adjustment is bigger.
4843 if (SPDiff < FI->getTailCallSPDelta())
4844 FI->setTailCallSPDelta(SPDiff);
4845
4846 return SPDiff;
4847}
4848
4849static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV);
4850
4851static bool callsShareTOCBase(const Function *Caller,
4852 const GlobalValue *CalleeGV,
4853 const TargetMachine &TM) {
4854 // It does not make sense to call callsShareTOCBase() with a caller that
4855 // is PC Relative since PC Relative callers do not have a TOC.
4856#ifndef NDEBUG
4857 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4858 assert(!STICaller->isUsingPCRelativeCalls() &&
4859 "PC Relative callers do not have a TOC and cannot share a TOC Base");
4860#endif
4861
4862 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4863 // don't have enough information to determine if the caller and callee share
4864 // the same TOC base, so we have to pessimistically assume they don't for
4865 // correctness.
4866 if (!CalleeGV)
4867 return false;
4868
4869 // If the callee is preemptable, then the static linker will use a plt-stub
4870 // which saves the toc to the stack, and needs a nop after the call
4871 // instruction to convert to a toc-restore.
4872 if (!TM.shouldAssumeDSOLocal(CalleeGV))
4873 return false;
4874
4875 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4876 // We may need a TOC restore in the situation where the caller requires a
4877 // valid TOC but the callee is PC Relative and does not.
4878 const Function *F = dyn_cast<Function>(CalleeGV);
4879 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(CalleeGV);
4880
4881 // If we have an Alias we can try to get the function from there.
4882 if (Alias) {
4883 const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4884 F = dyn_cast<Function>(GlobalObj);
4885 }
4886
4887 // If we still have no valid function pointer we do not have enough
4888 // information to determine if the callee uses PC Relative calls so we must
4889 // assume that it does.
4890 if (!F)
4891 return false;
4892
4893 // If the callee uses PC Relative we cannot guarantee that the callee won't
4894 // clobber the TOC of the caller and so we must assume that the two
4895 // functions do not share a TOC base.
4896 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4897 if (STICallee->isUsingPCRelativeCalls())
4898 return false;
4899
4900 // If the GV is not a strong definition then we need to assume it can be
4901 // replaced by another function at link time. The function that replaces
4902 // it may not share the same TOC as the caller since the callee may be
4903 // replaced by a PC Relative version of the same function.
4904 if (!CalleeGV->isStrongDefinitionForLinker())
4905 return false;
4906
4907 // The medium and large code models are expected to provide a sufficiently
4908 // large TOC to provide all data addressing needs of a module with a
4909 // single TOC.
4910 if (CodeModel::Medium == TM.getCodeModel() ||
4912 return true;
4913
4914 // Any explicitly-specified sections and section prefixes must also match.
4915 // Also, if we're using -ffunction-sections, then each function is always in
4916 // a different section (the same is true for COMDAT functions).
4917 if (TM.getFunctionSections() || CalleeGV->hasComdat() ||
4918 Caller->hasComdat() || CalleeGV->getSection() != Caller->getSection())
4919 return false;
4920 if (const auto *F = dyn_cast<Function>(CalleeGV)) {
4921 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4922 return false;
4923 }
4924
4925 return true;
4926}
4927
4928static bool
4930 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4931 assert(Subtarget.is64BitELFABI());
4932
4933 const unsigned PtrByteSize = 8;
4934 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4935
4936 static const MCPhysReg GPR[] = {
4937 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4938 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4939 };
4940 static const MCPhysReg VR[] = {
4941 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4942 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4943 };
4944
4945 const unsigned NumGPRs = std::size(GPR);
4946 const unsigned NumFPRs = 13;
4947 const unsigned NumVRs = std::size(VR);
4948 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4949
4950 unsigned NumBytes = LinkageSize;
4951 unsigned AvailableFPRs = NumFPRs;
4952 unsigned AvailableVRs = NumVRs;
4953
4954 for (const ISD::OutputArg& Param : Outs) {
4955 if (Param.Flags.isNest()) continue;
4956
4957 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4958 LinkageSize, ParamAreaSize, NumBytes,
4959 AvailableFPRs, AvailableVRs))
4960 return true;
4961 }
4962 return false;
4963}
4964
4965static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4966 if (CB.arg_size() != CallerFn->arg_size())
4967 return false;
4968
4969 auto CalleeArgIter = CB.arg_begin();
4970 auto CalleeArgEnd = CB.arg_end();
4971 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4972
4973 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4974 const Value* CalleeArg = *CalleeArgIter;
4975 const Value* CallerArg = &(*CallerArgIter);
4976 if (CalleeArg == CallerArg)
4977 continue;
4978
4979 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4980 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4981 // }
4982 // 1st argument of callee is undef and has the same type as caller.
4983 if (CalleeArg->getType() == CallerArg->getType() &&
4984 isa<UndefValue>(CalleeArg))
4985 continue;
4986
4987 return false;
4988 }
4989
4990 return true;
4991}
4992
4993// Returns true if TCO is possible between the callers and callees
4994// calling conventions.
4995static bool
4997 CallingConv::ID CalleeCC) {
4998 // Tail calls are possible with fastcc and ccc.
4999 auto isTailCallableCC = [] (CallingConv::ID CC){
5000 return CC == CallingConv::C || CC == CallingConv::Fast;
5001 };
5002 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
5003 return false;
5004
5005 // We can safely tail call both fastcc and ccc callees from a c calling
5006 // convention caller. If the caller is fastcc, we may have less stack space
5007 // than a non-fastcc caller with the same signature so disable tail-calls in
5008 // that case.
5009 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
5010}
5011
5012bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
5013 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5014 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5016 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5017 bool isCalleeExternalSymbol) const {
5018 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
5019
5020 if (DisableSCO && !TailCallOpt) return false;
5021
5022 // Variadic argument functions are not supported.
5023 if (isVarArg) return false;
5024
5025 // Check that the calling conventions are compatible for tco.
5026 if (!areCallingConvEligibleForTCO_64SVR4(CallerCC, CalleeCC))
5027 return false;
5028
5029 // Caller contains any byval parameter is not supported.
5030 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5031 return false;
5032
5033 // Callee contains any byval parameter is not supported, too.
5034 // Note: This is a quick work around, because in some cases, e.g.
5035 // caller's stack size > callee's stack size, we are still able to apply
5036 // sibling call optimization. For example, gcc is able to do SCO for caller1
5037 // in the following example, but not for caller2.
5038 // struct test {
5039 // long int a;
5040 // char ary[56];
5041 // } gTest;
5042 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
5043 // b->a = v.a;
5044 // return 0;
5045 // }
5046 // void caller1(struct test a, struct test c, struct test *b) {
5047 // callee(gTest, b); }
5048 // void caller2(struct test *b) { callee(gTest, b); }
5049 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
5050 return false;
5051
5052 // If callee and caller use different calling conventions, we cannot pass
5053 // parameters on stack since offsets for the parameter area may be different.
5054 if (CallerCC != CalleeCC && needStackSlotPassParameters(Subtarget, Outs))
5055 return false;
5056
5057 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
5058 // the caller and callee share the same TOC for TCO/SCO. If the caller and
5059 // callee potentially have different TOC bases then we cannot tail call since
5060 // we need to restore the TOC pointer after the call.
5061 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
5062 // We cannot guarantee this for indirect calls or calls to external functions.
5063 // When PC-Relative addressing is used, the concept of the TOC is no longer
5064 // applicable so this check is not required.
5065 // Check first for indirect calls.
5066 if (!Subtarget.isUsingPCRelativeCalls() &&
5067 !isFunctionGlobalAddress(CalleeGV) && !isCalleeExternalSymbol)
5068 return false;
5069
5070 // Check if we share the TOC base.
5071 if (!Subtarget.isUsingPCRelativeCalls() &&
5072 !callsShareTOCBase(CallerFunc, CalleeGV, getTargetMachine()))
5073 return false;
5074
5075 // TCO allows altering callee ABI, so we don't have to check further.
5076 if (CalleeCC == CallingConv::Fast && TailCallOpt)
5077 return true;
5078
5079 if (DisableSCO) return false;
5080
5081 // If callee use the same argument list that caller is using, then we can
5082 // apply SCO on this case. If it is not, then we need to check if callee needs
5083 // stack for passing arguments.
5084 // PC Relative tail calls may not have a CallBase.
5085 // If there is no CallBase we cannot verify if we have the same argument
5086 // list so assume that we don't have the same argument list.
5087 if (CB && !hasSameArgumentList(CallerFunc, *CB) &&
5088 needStackSlotPassParameters(Subtarget, Outs))
5089 return false;
5090 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5091 return false;
5092
5093 return true;
5094}
5095
5096/// IsEligibleForTailCallOptimization - Check whether the call is eligible
5097/// for tail call optimization. Targets which want to do tail call
5098/// optimization should implement this function.
5099bool PPCTargetLowering::IsEligibleForTailCallOptimization(
5100 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5101 CallingConv::ID CallerCC, bool isVarArg,
5102 const SmallVectorImpl<ISD::InputArg> &Ins) const {
5103 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5104 return false;
5105
5106 // Variable argument functions are not supported.
5107 if (isVarArg)
5108 return false;
5109
5110 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5111 // Functions containing by val parameters are not supported.
5112 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5113 return false;
5114
5115 // Non-PIC/GOT tail calls are supported.
5116 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5117 return true;
5118
5119 // At the moment we can only do local tail calls (in same module, hidden
5120 // or protected) if we are generating PIC.
5121 if (CalleeGV)
5122 return CalleeGV->hasHiddenVisibility() ||
5123 CalleeGV->hasProtectedVisibility();
5124 }
5125
5126 return false;
5127}
5128
5129/// isCallCompatibleAddress - Return the immediate to use if the specified
5130/// 32-bit value is representable in the immediate field of a BxA instruction.
5133 if (!C) return nullptr;
5134
5135 int Addr = C->getZExtValue();
5136 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
5137 SignExtend32<26>(Addr) != Addr)
5138 return nullptr; // Top 6 bits have to be sext of immediate.
5139
5140 return DAG
5142 (int)C->getZExtValue() >> 2, SDLoc(Op),
5144 .getNode();
5145}
5146
5147namespace {
5148
5149struct TailCallArgumentInfo {
5150 SDValue Arg;
5151 SDValue FrameIdxOp;
5152 int FrameIdx = 0;
5153
5154 TailCallArgumentInfo() = default;
5155};
5156
5157} // end anonymous namespace
5158
5159/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5161 SelectionDAG &DAG, SDValue Chain,
5162 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5163 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5164 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5165 SDValue Arg = TailCallArgs[i].Arg;
5166 SDValue FIN = TailCallArgs[i].FrameIdxOp;
5167 int FI = TailCallArgs[i].FrameIdx;
5168 // Store relative to framepointer.
5169 MemOpChains.push_back(DAG.getStore(
5170 Chain, dl, Arg, FIN,
5172 }
5173}
5174
5175/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5176/// the appropriate stack slot for the tail call optimized function call.
5178 SDValue OldRetAddr, SDValue OldFP,
5179 int SPDiff, const SDLoc &dl) {
5180 if (SPDiff) {
5181 // Calculate the new stack slot for the return address.
5183 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5184 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5185 int SlotSize = Subtarget.isPPC64() ? 8 : 4;
5186 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5187 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5188 NewRetAddrLoc, true);
5189 SDValue NewRetAddrFrIdx =
5190 DAG.getFrameIndex(NewRetAddr, Subtarget.getScalarIntVT());
5191 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5192 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5193 }
5194 return Chain;
5195}
5196
5197/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5198/// the position of the argument.
5200 SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg,
5201 int SPDiff, unsigned ArgOffset,
5202 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5203 int Offset = ArgOffset + SPDiff;
5204 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5205 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5206 EVT VT = IsPPC64 ? MVT::i64 : MVT::i32;
5207 SDValue FIN = DAG.getFrameIndex(FI, VT);
5208 TailCallArgumentInfo Info;
5209 Info.Arg = Arg;
5210 Info.FrameIdxOp = FIN;
5211 Info.FrameIdx = FI;
5212 TailCallArguments.push_back(Info);
5213}
5214
5215/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5216/// stack slot. Returns the chain as result and the loaded frame pointers in
5217/// LROpOut/FPOpout. Used when tail calling.
5218SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5219 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5220 SDValue &FPOpOut, const SDLoc &dl) const {
5221 if (SPDiff) {
5222 // Load the LR and FP stack slot for later adjusting.
5223 LROpOut = getReturnAddrFrameIndex(DAG);
5224 LROpOut = DAG.getLoad(Subtarget.getScalarIntVT(), dl, Chain, LROpOut,
5225 MachinePointerInfo());
5226 Chain = SDValue(LROpOut.getNode(), 1);
5227 }
5228 return Chain;
5229}
5230
5231/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5232/// by "Src" to address "Dst" of size "Size". Alignment information is
5233/// specified by the specific parameter attribute. The copy will be passed as
5234/// a byval function parameter.
5235/// Sometimes what we are copying is the end of a larger object, the part that
5236/// does not fit in registers.
5238 SDValue Chain, ISD::ArgFlagsTy Flags,
5239 SelectionDAG &DAG, const SDLoc &dl) {
5240 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5241 Align Alignment = Flags.getNonZeroByValAlign();
5242 return DAG.getMemcpy(
5243 Chain, dl, Dst, Src, SizeNode, Alignment, Alignment, false, false,
5244 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
5245}
5246
5247/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5248/// tail calls.
5250 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5251 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5252 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5253 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5255 if (!isTailCall) {
5256 if (isVector) {
5257 SDValue StackPtr;
5258 if (isPPC64)
5259 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5260 else
5261 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5262 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5263 DAG.getConstant(ArgOffset, dl, PtrVT));
5264 }
5265 MemOpChains.push_back(
5266 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5267 // Calculate and remember argument location.
5268 } else
5269 CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5270 TailCallArguments);
5271}
5272
5273static void
5275 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5276 SDValue FPOp,
5277 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5278 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5279 // might overwrite each other in case of tail call optimization.
5280 SmallVector<SDValue, 8> MemOpChains2;
5281 // Do not flag preceding copytoreg stuff together with the following stuff.
5282 InGlue = SDValue();
5283 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5284 MemOpChains2, dl);
5285 if (!MemOpChains2.empty())
5286 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5287
5288 // Store the return address to the appropriate stack slot.
5289 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5290
5291 // Emit callseq_end just before tailcall node.
5292 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
5293 InGlue = Chain.getValue(1);
5294}
5295
5296// Is this global address that of a function that can be called by name? (as
5297// opposed to something that must hold a descriptor for an indirect call).
5298static bool isFunctionGlobalAddress(const GlobalValue *GV) {
5299 if (GV) {
5300 if (GV->isThreadLocal())
5301 return false;
5302
5303 return GV->getValueType()->isFunctionTy();
5304 }
5305
5306 return false;
5307}
5308
5309SDValue PPCTargetLowering::LowerCallResult(
5310 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
5311 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5312 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5314 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5315 *DAG.getContext());
5316
5317 CCRetInfo.AnalyzeCallResult(
5318 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5320 : RetCC_PPC);
5321
5322 // Copy all of the result registers out of their specified physreg.
5323 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5324 CCValAssign &VA = RVLocs[i];
5325 assert(VA.isRegLoc() && "Can only return in registers!");
5326
5327 SDValue Val;
5328
5329 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5330 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5331 InGlue);
5332 Chain = Lo.getValue(1);
5333 InGlue = Lo.getValue(2);
5334 VA = RVLocs[++i]; // skip ahead to next loc
5335 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5336 InGlue);
5337 Chain = Hi.getValue(1);
5338 InGlue = Hi.getValue(2);
5339 if (!Subtarget.isLittleEndian())
5340 std::swap (Lo, Hi);
5341 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5342 } else {
5343 Val = DAG.getCopyFromReg(Chain, dl,
5344 VA.getLocReg(), VA.getLocVT(), InGlue);
5345 Chain = Val.getValue(1);
5346 InGlue = Val.getValue(2);
5347 }
5348
5349 switch (VA.getLocInfo()) {
5350 default: llvm_unreachable("Unknown loc info!");
5351 case CCValAssign::Full: break;
5352 case CCValAssign::AExt:
5353 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5354 break;
5355 case CCValAssign::ZExt:
5356 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5357 DAG.getValueType(VA.getValVT()));
5358 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5359 break;
5360 case CCValAssign::SExt:
5361 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5362 DAG.getValueType(VA.getValVT()));
5363 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5364 break;
5365 }
5366
5367 InVals.push_back(Val);
5368 }
5369
5370 return Chain;
5371}
5372
5373static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5374 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5375 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5376 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5377
5378 // PatchPoint calls are not indirect.
5379 if (isPatchPoint)
5380 return false;
5381
5383 return false;
5384
5385 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5386 // becuase the immediate function pointer points to a descriptor instead of
5387 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5388 // pointer immediate points to the global entry point, while the BLA would
5389 // need to jump to the local entry point (see rL211174).
5390 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5391 isBLACompatibleAddress(Callee, DAG))
5392 return false;
5393
5394 return true;
5395}
5396
5397// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5398static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5399 return Subtarget.isAIXABI() ||
5400 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5401}
5402
5404 const Function &Caller, const SDValue &Callee,
5405 const PPCSubtarget &Subtarget,
5406 const TargetMachine &TM,
5407 bool IsStrictFPCall = false) {
5408 if (CFlags.IsTailCall)
5409 return PPCISD::TC_RETURN;
5410
5411 unsigned RetOpc = 0;
5412 // This is a call through a function pointer.
5413 if (CFlags.IsIndirect) {
5414 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5415 // indirect calls. The save of the caller's TOC pointer to the stack will be
5416 // inserted into the DAG as part of call lowering. The restore of the TOC
5417 // pointer is modeled by using a pseudo instruction for the call opcode that
5418 // represents the 2 instruction sequence of an indirect branch and link,
5419 // immediately followed by a load of the TOC pointer from the stack save
5420 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5421 // as it is not saved or used.
5422 if (Subtarget.usePointerGlueHelper())
5423 RetOpc = PPCISD::BL_LOAD_TOC;
5424 else
5425 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5426 : PPCISD::BCTRL;
5427 } else if (Subtarget.isUsingPCRelativeCalls()) {
5428 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5429 RetOpc = PPCISD::CALL_NOTOC;
5430 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) {
5431 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5432 // immediately following the call instruction if the caller and callee may
5433 // have different TOC bases. At link time if the linker determines the calls
5434 // may not share a TOC base, the call is redirected to a trampoline inserted
5435 // by the linker. The trampoline will (among other things) save the callers
5436 // TOC pointer at an ABI designated offset in the linkage area and the
5437 // linker will rewrite the nop to be a load of the TOC pointer from the
5438 // linkage area into gpr2.
5439 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5440 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5441 RetOpc =
5442 callsShareTOCBase(&Caller, GV, TM) ? PPCISD::CALL : PPCISD::CALL_NOP;
5443 } else
5444 RetOpc = PPCISD::CALL;
5445 if (IsStrictFPCall) {
5446 switch (RetOpc) {
5447 default:
5448 llvm_unreachable("Unknown call opcode");
5449 case PPCISD::BCTRL_LOAD_TOC:
5450 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5451 break;
5452 case PPCISD::BCTRL:
5453 RetOpc = PPCISD::BCTRL_RM;
5454 break;
5455 case PPCISD::BL_LOAD_TOC:
5456 RetOpc = PPCISD::BL_LOAD_TOC_RM;
5457 break;
5458 case PPCISD::CALL_NOTOC:
5459 RetOpc = PPCISD::CALL_NOTOC_RM;
5460 break;
5461 case PPCISD::CALL:
5462 RetOpc = PPCISD::CALL_RM;
5463 break;
5464 case PPCISD::CALL_NOP:
5465 RetOpc = PPCISD::CALL_NOP_RM;
5466 break;
5467 }
5468 }
5469 return RetOpc;
5470}
5471
5472static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5473 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5474 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5475 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5476 return SDValue(Dest, 0);
5477
5478 // Returns true if the callee is local, and false otherwise.
5479 auto isLocalCallee = [&]() {
5481 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5482
5483 return DAG.getTarget().shouldAssumeDSOLocal(GV) &&
5485 };
5486
5487 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5488 // a static relocation model causes some versions of GNU LD (2.17.50, at
5489 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5490 // built with secure-PLT.
5491 bool UsePlt =
5492 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5494
5495 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5496 const TargetMachine &TM = Subtarget.getTargetMachine();
5498 auto *S =
5499 static_cast<MCSymbolXCOFF *>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5500
5502 return DAG.getMCSymbol(S, PtrVT);
5503 };
5504
5505 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5506 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5507 if (isFunctionGlobalAddress(GV)) {
5508 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5509
5510 if (Subtarget.isAIXABI()) {
5511 return getAIXFuncEntryPointSymbolSDNode(GV);
5512 }
5513 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5514 UsePlt ? PPCII::MO_PLT : 0);
5515 }
5516
5518 const char *SymName = S->getSymbol();
5519 if (Subtarget.isAIXABI()) {
5520 // If there exists a user-declared function whose name is the same as the
5521 // ExternalSymbol's, then we pick up the user-declared version.
5523 if (const Function *F =
5524 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5525 return getAIXFuncEntryPointSymbolSDNode(F);
5526
5527 // On AIX, direct function calls reference the symbol for the function's
5528 // entry point, which is named by prepending a "." before the function's
5529 // C-linkage name. A Qualname is returned here because an external
5530 // function entry point is a csect with XTY_ER property.
5531 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5532 auto &Context = DAG.getMachineFunction().getContext();
5533 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5534 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5536 return Sec->getQualNameSymbol();
5537 };
5538
5539 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5540 }
5541 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5542 UsePlt ? PPCII::MO_PLT : 0);
5543 }
5544
5545 // No transformation needed.
5546 assert(Callee.getNode() && "What no callee?");
5547 return Callee;
5548}
5549
5551 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5552 "Expected a CALLSEQ_STARTSDNode.");
5553
5554 // The last operand is the chain, except when the node has glue. If the node
5555 // has glue, then the last operand is the glue, and the chain is the second
5556 // last operand.
5557 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5558 if (LastValue.getValueType() != MVT::Glue)
5559 return LastValue;
5560
5561 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5562}
5563
5564// Creates the node that moves a functions address into the count register
5565// to prepare for an indirect call instruction.
5566static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5567 SDValue &Glue, SDValue &Chain,
5568 const SDLoc &dl) {
5569 SDValue MTCTROps[] = {Chain, Callee, Glue};
5570 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5571 Chain = DAG.getNode(PPCISD::MTCTR, dl, ReturnTypes,
5572 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5573 // The glue is the second value produced.
5574 Glue = Chain.getValue(1);
5575}
5576
5578 SDValue &Glue, SDValue &Chain,
5579 SDValue CallSeqStart,
5580 const CallBase *CB, const SDLoc &dl,
5581 bool hasNest,
5582 const PPCSubtarget &Subtarget) {
5583 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5584 // entry point, but to the function descriptor (the function entry point
5585 // address is part of the function descriptor though).
5586 // The function descriptor is a three doubleword structure with the
5587 // following fields: function entry point, TOC base address and
5588 // environment pointer.
5589 // Thus for a call through a function pointer, the following actions need
5590 // to be performed:
5591 // 1. Save the TOC of the caller in the TOC save area of its stack
5592 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5593 // 2. Load the address of the function entry point from the function
5594 // descriptor.
5595 // 3. Load the TOC of the callee from the function descriptor into r2.
5596 // 4. Load the environment pointer from the function descriptor into
5597 // r11.
5598 // 5. Branch to the function entry point address.
5599 // 6. On return of the callee, the TOC of the caller needs to be
5600 // restored (this is done in FinishCall()).
5601 //
5602 // The loads are scheduled at the beginning of the call sequence, and the
5603 // register copies are flagged together to ensure that no other
5604 // operations can be scheduled in between. E.g. without flagging the
5605 // copies together, a TOC access in the caller could be scheduled between
5606 // the assignment of the callee TOC and the branch to the callee, which leads
5607 // to incorrect code.
5608
5609 // Start by loading the function address from the descriptor.
5610 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5611 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5615
5616 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5617
5618 // Registers used in building the DAG.
5619 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5620 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5621
5622 // Offsets of descriptor members.
5623 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5624 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5625
5626 const MVT RegVT = Subtarget.getScalarIntVT();
5627 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
5628
5629 // One load for the functions entry point address.
5630 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5631 Alignment, MMOFlags);
5632
5633 // One for loading the TOC anchor for the module that contains the called
5634 // function.
5635 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5636 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5637 SDValue TOCPtr =
5638 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5639 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5640
5641 // One for loading the environment pointer.
5642 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5643 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5644 SDValue LoadEnvPtr =
5645 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5646 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5647
5648
5649 // Then copy the newly loaded TOC anchor to the TOC pointer.
5650 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5651 Chain = TOCVal.getValue(0);
5652 Glue = TOCVal.getValue(1);
5653
5654 // If the function call has an explicit 'nest' parameter, it takes the
5655 // place of the environment pointer.
5656 assert((!hasNest || !Subtarget.isAIXABI()) &&
5657 "Nest parameter is not supported on AIX.");
5658 if (!hasNest) {
5659 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5660 Chain = EnvVal.getValue(0);
5661 Glue = EnvVal.getValue(1);
5662 }
5663
5664 // The rest of the indirect call sequence is the same as the non-descriptor
5665 // DAG.
5666 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5667}
5668
5670 SDValue &Glue, SDValue &Chain,
5671 SDValue CallSeqStart, const CallBase *CB,
5672 const SDLoc &dl, bool hasNest,
5673 const PPCSubtarget &Subtarget) {
5674 // On AIX there is a feature ("out of line glue code") which uses a special
5675 // trampoline function ._ptrgl to do the indirect call. If this option is
5676 // enabled we instead simply load the address of the descriptor into gpr11,
5677 // with the arguments in the 'normal' registers and branch to the ._ptrgl
5678 // stub.
5679 const MCRegister PtrGlueReg = Subtarget.getGlueCodeDescriptorRegister();
5680 SDValue MoveToPhysicalReg =
5681 DAG.getCopyToReg(Chain, dl, PtrGlueReg, Callee, Glue);
5682 Chain = MoveToPhysicalReg.getValue(0);
5683 Glue = MoveToPhysicalReg.getValue(1);
5684}
5685
5686static void
5688 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5689 SelectionDAG &DAG,
5690 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5691 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5692 const PPCSubtarget &Subtarget) {
5693 const bool IsPPC64 = Subtarget.isPPC64();
5694 // MVT for a general purpose register.
5695 const MVT RegVT = Subtarget.getScalarIntVT();
5696
5697 // First operand is always the chain.
5698 Ops.push_back(Chain);
5699
5700 // If it's a direct call pass the callee as the second operand.
5701 if (!CFlags.IsIndirect)
5702 Ops.push_back(Callee);
5703 else if (Subtarget.usePointerGlueHelper()) {
5704 Ops.push_back(Callee);
5705 // Add the register used to pass the descriptor address.
5706 Ops.push_back(
5707 DAG.getRegister(Subtarget.getGlueCodeDescriptorRegister(), RegVT));
5708 } else {
5709 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5710
5711 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5712 // on the stack (this would have been done in `LowerCall_64SVR4` or
5713 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5714 // represents both the indirect branch and a load that restores the TOC
5715 // pointer from the linkage area. The operand for the TOC restore is an add
5716 // of the TOC save offset to the stack pointer. This must be the second
5717 // operand: after the chain input but before any other variadic arguments.
5718 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5719 // saved or used.
5720 if (isTOCSaveRestoreRequired(Subtarget)) {
5721 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5722
5723 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5724 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5725 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5726 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5727 Ops.push_back(AddTOC);
5728 }
5729
5730 // Add the register used for the environment pointer.
5731 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5732 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5733 RegVT));
5734
5735
5736 // Add CTR register as callee so a bctr can be emitted later.
5737 if (CFlags.IsTailCall)
5738 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5739 }
5740
5741 // If this is a tail call add stack pointer delta.
5742 if (CFlags.IsTailCall)
5743 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5744
5745 // Add argument registers to the end of the list so that they are known live
5746 // into the call.
5747 for (const auto &[Reg, N] : RegsToPass)
5748 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
5749
5750 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5751 // no way to mark dependencies as implicit here.
5752 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5753 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5754 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5755 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5756
5757 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5758 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5759 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5760
5761 // Add a register mask operand representing the call-preserved registers.
5762 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5763 const uint32_t *Mask =
5764 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5765 assert(Mask && "Missing call preserved mask for calling convention");
5766 Ops.push_back(DAG.getRegisterMask(Mask));
5767
5768 // If the glue is valid, it is the last operand.
5769 if (Glue.getNode())
5770 Ops.push_back(Glue);
5771}
5772
5773SDValue PPCTargetLowering::FinishCall(
5774 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5775 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5776 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5777 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5778 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5779
5780 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5781 Subtarget.isAIXABI())
5782 setUsesTOCBasePtr(DAG);
5783
5784 unsigned CallOpc =
5785 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5786 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5787
5788 if (!CFlags.IsIndirect)
5789 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5790 else if (Subtarget.usesFunctionDescriptors()) {
5791 if (Subtarget.usePointerGlueHelper()) {
5792 prepareOutOfLineGlueCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, dl,
5793 CFlags.HasNest, Subtarget);
5794 SDValue PtrGlueCallee =
5795 DAG.getExternalSymbol("_ptrgl", getPointerTy(DAG.getDataLayout()));
5796 Callee = transformCallee(PtrGlueCallee, DAG, dl, Subtarget);
5797 } else {
5798 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5799 dl, CFlags.HasNest, Subtarget);
5800 }
5801 } else {
5802 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5803 }
5804
5805 // Build the operand list for the call instruction.
5807 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5808 SPDiff, Subtarget);
5809
5810 // Emit tail call.
5811 if (CFlags.IsTailCall) {
5812 // Indirect tail call when using PC Relative calls do not have the same
5813 // constraints.
5814 assert(((Callee.getOpcode() == ISD::Register &&
5815 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5816 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5817 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5818 isa<ConstantSDNode>(Callee) ||
5819 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5820 "Expecting a global address, external symbol, absolute value, "
5821 "register or an indirect tail call when PC Relative calls are "
5822 "used.");
5823 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5824 assert(CallOpc == PPCISD::TC_RETURN &&
5825 "Unexpected call opcode for a tail call.");
5827 SDValue Ret = DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5828 DAG.addNoMergeSiteInfo(Ret.getNode(), CFlags.NoMerge);
5829 return Ret;
5830 }
5831
5832 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5833 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5834 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5835 Glue = Chain.getValue(1);
5836
5837 // When performing tail call optimization the callee pops its arguments off
5838 // the stack. Account for this here so these bytes can be pushed back on in
5839 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5840 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5842 ? NumBytes
5843 : 0;
5844
5845 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
5846 Glue = Chain.getValue(1);
5847
5848 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5849 DAG, InVals);
5850}
5851
5853 CallingConv::ID CalleeCC = CB->getCallingConv();
5854 const Function *CallerFunc = CB->getCaller();
5855 CallingConv::ID CallerCC = CallerFunc->getCallingConv();
5856 const Function *CalleeFunc = CB->getCalledFunction();
5857 if (!CalleeFunc)
5858 return false;
5859 const GlobalValue *CalleeGV = dyn_cast<GlobalValue>(CalleeFunc);
5860
5863
5864 GetReturnInfo(CalleeCC, CalleeFunc->getReturnType(),
5865 CalleeFunc->getAttributes(), Outs, *this,
5866 CalleeFunc->getDataLayout());
5867
5868 return isEligibleForTCO(CalleeGV, CalleeCC, CallerCC, CB,
5869 CalleeFunc->isVarArg(), Outs, Ins, CallerFunc,
5870 false /*isCalleeExternalSymbol*/);
5871}
5872
5873bool PPCTargetLowering::isEligibleForTCO(
5874 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5875 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5877 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5878 bool isCalleeExternalSymbol) const {
5879 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5880 return false;
5881
5882 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5883 return IsEligibleForTailCallOptimization_64SVR4(
5884 CalleeGV, CalleeCC, CallerCC, CB, isVarArg, Outs, Ins, CallerFunc,
5885 isCalleeExternalSymbol);
5886 else
5887 return IsEligibleForTailCallOptimization(CalleeGV, CalleeCC, CallerCC,
5888 isVarArg, Ins);
5889}
5890
5891SDValue
5892PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5893 SmallVectorImpl<SDValue> &InVals) const {
5894 SelectionDAG &DAG = CLI.DAG;
5895 SDLoc &dl = CLI.DL;
5897 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5899 SDValue Chain = CLI.Chain;
5900 SDValue Callee = CLI.Callee;
5901 bool &isTailCall = CLI.IsTailCall;
5902 CallingConv::ID CallConv = CLI.CallConv;
5903 bool isVarArg = CLI.IsVarArg;
5904 bool isPatchPoint = CLI.IsPatchPoint;
5905 const CallBase *CB = CLI.CB;
5906
5907 if (isTailCall) {
5909 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5910 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5911 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5912 bool IsCalleeExternalSymbol = isa<ExternalSymbolSDNode>(Callee);
5913
5914 isTailCall =
5915 isEligibleForTCO(GV, CallConv, CallerCC, CB, isVarArg, Outs, Ins,
5916 &(MF.getFunction()), IsCalleeExternalSymbol);
5917 if (isTailCall) {
5918 ++NumTailCalls;
5919 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5920 ++NumSiblingCalls;
5921
5922 // PC Relative calls no longer guarantee that the callee is a Global
5923 // Address Node. The callee could be an indirect tail call in which
5924 // case the SDValue for the callee could be a load (to load the address
5925 // of a function pointer) or it may be a register copy (to move the
5926 // address of the callee from a function parameter into a virtual
5927 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5928 assert((Subtarget.isUsingPCRelativeCalls() ||
5929 isa<GlobalAddressSDNode>(Callee)) &&
5930 "Callee should be an llvm::Function object.");
5931
5932 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5933 << "\nTCO callee: ");
5934 LLVM_DEBUG(Callee.dump());
5935 }
5936 }
5937
5938 if (!isTailCall && CB && CB->isMustTailCall())
5939 report_fatal_error("failed to perform tail call elimination on a call "
5940 "site marked musttail");
5941
5942 // When long calls (i.e. indirect calls) are always used, calls are always
5943 // made via function pointer. If we have a function name, first translate it
5944 // into a pointer.
5945 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5946 !isTailCall)
5947 Callee = LowerGlobalAddress(Callee, DAG);
5948
5949 CallFlags CFlags(
5950 CallConv, isTailCall, isVarArg, isPatchPoint,
5951 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5952 // hasNest
5953 Subtarget.is64BitELFABI() &&
5954 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5955 CLI.NoMerge);
5956
5957 if (Subtarget.isAIXABI())
5958 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5959 InVals, CB);
5960
5961 assert(Subtarget.isSVR4ABI());
5962 if (Subtarget.isPPC64())
5963 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5964 InVals, CB);
5965 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5966 InVals, CB);
5967}
5968
5969SDValue PPCTargetLowering::LowerCall_32SVR4(
5970 SDValue Chain, SDValue Callee, CallFlags CFlags,
5972 const SmallVectorImpl<SDValue> &OutVals,
5973 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5975 const CallBase *CB) const {
5976 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5977 // of the 32-bit SVR4 ABI stack frame layout.
5978
5979 const CallingConv::ID CallConv = CFlags.CallConv;
5980 const bool IsVarArg = CFlags.IsVarArg;
5981 const bool IsTailCall = CFlags.IsTailCall;
5982
5983 assert((CallConv == CallingConv::C ||
5984 CallConv == CallingConv::Cold ||
5985 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5986
5987 const Align PtrAlign(4);
5988
5990
5991 // Mark this function as potentially containing a function that contains a
5992 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5993 // and restoring the callers stack pointer in this functions epilog. This is
5994 // done because by tail calling the called function might overwrite the value
5995 // in this function's (MF) stack pointer stack slot 0(SP).
5996 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5997 CallConv == CallingConv::Fast)
5998 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5999
6000 // Count how many bytes are to be pushed on the stack, including the linkage
6001 // area, parameter list area and the part of the local variable space which
6002 // contains copies of aggregates which are passed by value.
6003
6004 // Assign locations to all of the outgoing arguments.
6006 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6007
6008 // Reserve space for the linkage area on the stack.
6009 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
6010 PtrAlign);
6011
6012 if (IsVarArg) {
6013 // Handle fixed and variable vector arguments differently.
6014 // Fixed vector arguments go into registers as long as registers are
6015 // available. Variable vector arguments always go into memory.
6016 unsigned NumArgs = Outs.size();
6017
6018 for (unsigned i = 0; i != NumArgs; ++i) {
6019 MVT ArgVT = Outs[i].VT;
6020 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6021 bool Result;
6022
6023 if (!ArgFlags.isVarArg()) {
6024 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
6025 Outs[i].OrigTy, CCInfo);
6026 } else {
6028 ArgFlags, Outs[i].OrigTy, CCInfo);
6029 }
6030
6031 if (Result) {
6032#ifndef NDEBUG
6033 errs() << "Call operand #" << i << " has unhandled type "
6034 << ArgVT << "\n";
6035#endif
6036 llvm_unreachable(nullptr);
6037 }
6038 }
6039 } else {
6040 // All arguments are treated the same.
6041 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
6042 }
6043
6044 // Assign locations to all of the outgoing aggregate by value arguments.
6045 SmallVector<CCValAssign, 16> ByValArgLocs;
6046 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
6047
6048 // Reserve stack space for the allocations in CCInfo.
6049 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
6050
6051 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
6052
6053 // Size of the linkage area, parameter list area and the part of the local
6054 // space variable where copies of aggregates which are passed by value are
6055 // stored.
6056 unsigned NumBytes = CCByValInfo.getStackSize();
6057
6058 // Calculate by how many bytes the stack has to be adjusted in case of tail
6059 // call optimization.
6060 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
6061
6062 // Adjust the stack pointer for the new arguments...
6063 // These operations are automatically eliminated by the prolog/epilog pass
6064 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6065 SDValue CallSeqStart = Chain;
6066
6067 // Load the return address and frame pointer so it can be moved somewhere else
6068 // later.
6069 SDValue LROp, FPOp;
6070 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6071
6072 // Set up a copy of the stack pointer for use loading and storing any
6073 // arguments that may not fit in the registers available for argument
6074 // passing.
6075 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6076
6078 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6079 SmallVector<SDValue, 8> MemOpChains;
6080
6081 bool seenFloatArg = false;
6082 // Walk the register/memloc assignments, inserting copies/loads.
6083 // i - Tracks the index into the list of registers allocated for the call
6084 // RealArgIdx - Tracks the index into the list of actual function arguments
6085 // j - Tracks the index into the list of byval arguments
6086 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
6087 i != e;
6088 ++i, ++RealArgIdx) {
6089 CCValAssign &VA = ArgLocs[i];
6090 SDValue Arg = OutVals[RealArgIdx];
6091 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
6092
6093 if (Flags.isByVal()) {
6094 // Argument is an aggregate which is passed by value, thus we need to
6095 // create a copy of it in the local variable space of the current stack
6096 // frame (which is the stack frame of the caller) and pass the address of
6097 // this copy to the callee.
6098 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
6099 CCValAssign &ByValVA = ByValArgLocs[j++];
6100 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
6101
6102 // Memory reserved in the local variable space of the callers stack frame.
6103 unsigned LocMemOffset = ByValVA.getLocMemOffset();
6104
6105 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6106 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6107 StackPtr, PtrOff);
6108
6109 // Create a copy of the argument in the local area of the current
6110 // stack frame.
6111 SDValue MemcpyCall =
6112 CreateCopyOfByValArgument(Arg, PtrOff,
6113 CallSeqStart.getNode()->getOperand(0),
6114 Flags, DAG, dl);
6115
6116 // This must go outside the CALLSEQ_START..END.
6117 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
6118 SDLoc(MemcpyCall));
6119 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6120 NewCallSeqStart.getNode());
6121 Chain = CallSeqStart = NewCallSeqStart;
6122
6123 // Pass the address of the aggregate copy on the stack either in a
6124 // physical register or in the parameter list area of the current stack
6125 // frame to the callee.
6126 Arg = PtrOff;
6127 }
6128
6129 // When useCRBits() is true, there can be i1 arguments.
6130 // It is because getRegisterType(MVT::i1) => MVT::i1,
6131 // and for other integer types getRegisterType() => MVT::i32.
6132 // Extend i1 and ensure callee will get i32.
6133 if (Arg.getValueType() == MVT::i1)
6134 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6135 dl, MVT::i32, Arg);
6136
6137 if (VA.isRegLoc()) {
6138 seenFloatArg |= VA.getLocVT().isFloatingPoint();
6139 // Put argument in a physical register.
6140 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
6141 bool IsLE = Subtarget.isLittleEndian();
6142 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6143 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
6144 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
6145 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6146 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
6147 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
6148 SVal.getValue(0)));
6149 } else
6150 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
6151 } else {
6152 // Put argument in the parameter list area of the current stack frame.
6153 assert(VA.isMemLoc());
6154 unsigned LocMemOffset = VA.getLocMemOffset();
6155
6156 if (!IsTailCall) {
6157 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6158 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6159 StackPtr, PtrOff);
6160
6161 MemOpChains.push_back(
6162 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6163 } else {
6164 // Calculate and remember argument location.
6165 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
6166 TailCallArguments);
6167 }
6168 }
6169 }
6170
6171 if (!MemOpChains.empty())
6172 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6173
6174 // Build a sequence of copy-to-reg nodes chained together with token chain
6175 // and flag operands which copy the outgoing args into the appropriate regs.
6176 SDValue InGlue;
6177 for (const auto &[Reg, N] : RegsToPass) {
6178 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6179 InGlue = Chain.getValue(1);
6180 }
6181
6182 // Set CR bit 6 to true if this is a vararg call with floating args passed in
6183 // registers.
6184 if (IsVarArg) {
6185 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6186 SDValue Ops[] = { Chain, InGlue };
6187
6188 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
6189 VTs, ArrayRef(Ops, InGlue.getNode() ? 2 : 1));
6190
6191 InGlue = Chain.getValue(1);
6192 }
6193
6194 if (IsTailCall)
6195 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6196 TailCallArguments);
6197
6198 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6199 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6200}
6201
6202// Copy an argument into memory, being careful to do this outside the
6203// call sequence for the call to which the argument belongs.
6204SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6205 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6206 SelectionDAG &DAG, const SDLoc &dl) const {
6207 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6208 CallSeqStart.getNode()->getOperand(0),
6209 Flags, DAG, dl);
6210 // The MEMCPY must go outside the CALLSEQ_START..END.
6211 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6212 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6213 SDLoc(MemcpyCall));
6214 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6215 NewCallSeqStart.getNode());
6216 return NewCallSeqStart;
6217}
6218
6219SDValue PPCTargetLowering::LowerCall_64SVR4(
6220 SDValue Chain, SDValue Callee, CallFlags CFlags,
6222 const SmallVectorImpl<SDValue> &OutVals,
6223 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6225 const CallBase *CB) const {
6226 bool isELFv2ABI = Subtarget.isELFv2ABI();
6227 bool isLittleEndian = Subtarget.isLittleEndian();
6228 unsigned NumOps = Outs.size();
6229 bool IsSibCall = false;
6230 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6231
6232 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6233 unsigned PtrByteSize = 8;
6234
6236
6237 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6238 IsSibCall = true;
6239
6240 // Mark this function as potentially containing a function that contains a
6241 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6242 // and restoring the callers stack pointer in this functions epilog. This is
6243 // done because by tail calling the called function might overwrite the value
6244 // in this function's (MF) stack pointer stack slot 0(SP).
6245 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6246 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6247
6248 assert(!(IsFastCall && CFlags.IsVarArg) &&
6249 "fastcc not supported on varargs functions");
6250
6251 // Count how many bytes are to be pushed on the stack, including the linkage
6252 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
6253 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6254 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6255 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6256 unsigned NumBytes = LinkageSize;
6257 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6258
6259 static const MCPhysReg GPR[] = {
6260 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6261 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6262 };
6263 static const MCPhysReg VR[] = {
6264 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6265 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6266 };
6267
6268 const unsigned NumGPRs = std::size(GPR);
6269 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6270 const unsigned NumVRs = std::size(VR);
6271
6272 // On ELFv2, we can avoid allocating the parameter area if all the arguments
6273 // can be passed to the callee in registers.
6274 // For the fast calling convention, there is another check below.
6275 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6276 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6277 if (!HasParameterArea) {
6278 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6279 unsigned AvailableFPRs = NumFPRs;
6280 unsigned AvailableVRs = NumVRs;
6281 unsigned NumBytesTmp = NumBytes;
6282 for (unsigned i = 0; i != NumOps; ++i) {
6283 if (Outs[i].Flags.isNest()) continue;
6284 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6285 PtrByteSize, LinkageSize, ParamAreaSize,
6286 NumBytesTmp, AvailableFPRs, AvailableVRs))
6287 HasParameterArea = true;
6288 }
6289 }
6290
6291 // When using the fast calling convention, we don't provide backing for
6292 // arguments that will be in registers.
6293 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6294
6295 // Avoid allocating parameter area for fastcc functions if all the arguments
6296 // can be passed in the registers.
6297 if (IsFastCall)
6298 HasParameterArea = false;
6299
6300 // Add up all the space actually used.
6301 for (unsigned i = 0; i != NumOps; ++i) {
6302 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6303 EVT ArgVT = Outs[i].VT;
6304 EVT OrigVT = Outs[i].ArgVT;
6305
6306 if (Flags.isNest())
6307 continue;
6308
6309 if (IsFastCall) {
6310 if (Flags.isByVal()) {
6311 NumGPRsUsed += (Flags.getByValSize()+7)/8;
6312 if (NumGPRsUsed > NumGPRs)
6313 HasParameterArea = true;
6314 } else {
6315 switch (ArgVT.getSimpleVT().SimpleTy) {
6316 default: llvm_unreachable("Unexpected ValueType for argument!");
6317 case MVT::i1:
6318 case MVT::i32:
6319 case MVT::i64:
6320 if (++NumGPRsUsed <= NumGPRs)
6321 continue;
6322 break;
6323 case MVT::v4i32:
6324 case MVT::v8i16:
6325 case MVT::v16i8:
6326 case MVT::v2f64:
6327 case MVT::v2i64:
6328 case MVT::v1i128:
6329 case MVT::f128:
6330 if (++NumVRsUsed <= NumVRs)
6331 continue;
6332 break;
6333 case MVT::v4f32:
6334 if (++NumVRsUsed <= NumVRs)
6335 continue;
6336 break;
6337 case MVT::f32:
6338 case MVT::f64:
6339 if (++NumFPRsUsed <= NumFPRs)
6340 continue;
6341 break;
6342 }
6343 HasParameterArea = true;
6344 }
6345 }
6346
6347 /* Respect alignment of argument on the stack. */
6348 auto Alignement =
6349 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6350 NumBytes = alignTo(NumBytes, Alignement);
6351
6352 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6353 if (Flags.isInConsecutiveRegsLast())
6354 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6355 }
6356
6357 unsigned NumBytesActuallyUsed = NumBytes;
6358
6359 // In the old ELFv1 ABI,
6360 // the prolog code of the callee may store up to 8 GPR argument registers to
6361 // the stack, allowing va_start to index over them in memory if its varargs.
6362 // Because we cannot tell if this is needed on the caller side, we have to
6363 // conservatively assume that it is needed. As such, make sure we have at
6364 // least enough stack space for the caller to store the 8 GPRs.
6365 // In the ELFv2 ABI, we allocate the parameter area iff a callee
6366 // really requires memory operands, e.g. a vararg function.
6367 if (HasParameterArea)
6368 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6369 else
6370 NumBytes = LinkageSize;
6371
6372 // Tail call needs the stack to be aligned.
6373 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6374 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6375
6376 int SPDiff = 0;
6377
6378 // Calculate by how many bytes the stack has to be adjusted in case of tail
6379 // call optimization.
6380 if (!IsSibCall)
6381 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6382
6383 // To protect arguments on the stack from being clobbered in a tail call,
6384 // force all the loads to happen before doing any other lowering.
6385 if (CFlags.IsTailCall)
6386 Chain = DAG.getStackArgumentTokenFactor(Chain);
6387
6388 // Adjust the stack pointer for the new arguments...
6389 // These operations are automatically eliminated by the prolog/epilog pass
6390 if (!IsSibCall)
6391 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6392 SDValue CallSeqStart = Chain;
6393
6394 // Load the return address and frame pointer so it can be move somewhere else
6395 // later.
6396 SDValue LROp, FPOp;
6397 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6398
6399 // Set up a copy of the stack pointer for use loading and storing any
6400 // arguments that may not fit in the registers available for argument
6401 // passing.
6402 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6403
6404 // Figure out which arguments are going to go in registers, and which in
6405 // memory. Also, if this is a vararg function, floating point operations
6406 // must be stored to our stack, and loaded into integer regs as well, if
6407 // any integer regs are available for argument passing.
6408 unsigned ArgOffset = LinkageSize;
6409
6411 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6412
6413 SmallVector<SDValue, 8> MemOpChains;
6414 for (unsigned i = 0; i != NumOps; ++i) {
6415 SDValue Arg = OutVals[i];
6416 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6417 EVT ArgVT = Outs[i].VT;
6418 EVT OrigVT = Outs[i].ArgVT;
6419
6420 // PtrOff will be used to store the current argument to the stack if a
6421 // register cannot be found for it.
6422 SDValue PtrOff;
6423
6424 // We re-align the argument offset for each argument, except when using the
6425 // fast calling convention, when we need to make sure we do that only when
6426 // we'll actually use a stack slot.
6427 auto ComputePtrOff = [&]() {
6428 /* Respect alignment of argument on the stack. */
6429 auto Alignment =
6430 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6431 ArgOffset = alignTo(ArgOffset, Alignment);
6432
6433 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6434
6435 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6436 };
6437
6438 if (!IsFastCall) {
6439 ComputePtrOff();
6440
6441 /* Compute GPR index associated with argument offset. */
6442 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6443 GPR_idx = std::min(GPR_idx, NumGPRs);
6444 }
6445
6446 // Promote integers to 64-bit values.
6447 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6448 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6449 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6450 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6451 }
6452
6453 // FIXME memcpy is used way more than necessary. Correctness first.
6454 // Note: "by value" is code for passing a structure by value, not
6455 // basic types.
6456 if (Flags.isByVal()) {
6457 // Note: Size includes alignment padding, so
6458 // struct x { short a; char b; }
6459 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
6460 // These are the proper values we need for right-justifying the
6461 // aggregate in a parameter register.
6462 unsigned Size = Flags.getByValSize();
6463
6464 // An empty aggregate parameter takes up no storage and no
6465 // registers.
6466 if (Size == 0)
6467 continue;
6468
6469 if (IsFastCall)
6470 ComputePtrOff();
6471
6472 // All aggregates smaller than 8 bytes must be passed right-justified.
6473 if (Size==1 || Size==2 || Size==4) {
6474 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6475 if (GPR_idx != NumGPRs) {
6476 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6477 MachinePointerInfo(), VT);
6478 MemOpChains.push_back(Load.getValue(1));
6479 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6480
6481 ArgOffset += PtrByteSize;
6482 continue;
6483 }
6484 }
6485
6486 if (GPR_idx == NumGPRs && Size < 8) {
6487 SDValue AddPtr = PtrOff;
6488 if (!isLittleEndian) {
6489 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6490 PtrOff.getValueType());
6491 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6492 }
6493 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6494 CallSeqStart,
6495 Flags, DAG, dl);
6496 ArgOffset += PtrByteSize;
6497 continue;
6498 }
6499 // Copy the object to parameter save area if it can not be entirely passed
6500 // by registers.
6501 // FIXME: we only need to copy the parts which need to be passed in
6502 // parameter save area. For the parts passed by registers, we don't need
6503 // to copy them to the stack although we need to allocate space for them
6504 // in parameter save area.
6505 if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6506 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6507 CallSeqStart,
6508 Flags, DAG, dl);
6509
6510 // When a register is available, pass a small aggregate right-justified.
6511 if (Size < 8 && GPR_idx != NumGPRs) {
6512 // The easiest way to get this right-justified in a register
6513 // is to copy the structure into the rightmost portion of a
6514 // local variable slot, then load the whole slot into the
6515 // register.
6516 // FIXME: The memcpy seems to produce pretty awful code for
6517 // small aggregates, particularly for packed ones.
6518 // FIXME: It would be preferable to use the slot in the
6519 // parameter save area instead of a new local variable.
6520 SDValue AddPtr = PtrOff;
6521 if (!isLittleEndian) {
6522 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6523 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6524 }
6525 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6526 CallSeqStart,
6527 Flags, DAG, dl);
6528
6529 // Load the slot into the register.
6530 SDValue Load =
6531 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6532 MemOpChains.push_back(Load.getValue(1));
6533 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6534
6535 // Done with this argument.
6536 ArgOffset += PtrByteSize;
6537 continue;
6538 }
6539
6540 // For aggregates larger than PtrByteSize, copy the pieces of the
6541 // object that fit into registers from the parameter save area.
6542 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6543 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6544 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6545 if (GPR_idx != NumGPRs) {
6546 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6547 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6548 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6549 MachinePointerInfo(), ObjType);
6550
6551 MemOpChains.push_back(Load.getValue(1));
6552 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6553 ArgOffset += PtrByteSize;
6554 } else {
6555 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6556 break;
6557 }
6558 }
6559 continue;
6560 }
6561
6562 switch (Arg.getSimpleValueType().SimpleTy) {
6563 default: llvm_unreachable("Unexpected ValueType for argument!");
6564 case MVT::i1:
6565 case MVT::i32:
6566 case MVT::i64:
6567 if (Flags.isNest()) {
6568 // The 'nest' parameter, if any, is passed in R11.
6569 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6570 break;
6571 }
6572
6573 // These can be scalar arguments or elements of an integer array type
6574 // passed directly. Clang may use those instead of "byval" aggregate
6575 // types to avoid forcing arguments to memory unnecessarily.
6576 if (GPR_idx != NumGPRs) {
6577 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6578 } else {
6579 if (IsFastCall)
6580 ComputePtrOff();
6581
6582 assert(HasParameterArea &&
6583 "Parameter area must exist to pass an argument in memory.");
6584 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6585 true, CFlags.IsTailCall, false, MemOpChains,
6586 TailCallArguments, dl);
6587 if (IsFastCall)
6588 ArgOffset += PtrByteSize;
6589 }
6590 if (!IsFastCall)
6591 ArgOffset += PtrByteSize;
6592 break;
6593 case MVT::f32:
6594 case MVT::f64: {
6595 // These can be scalar arguments or elements of a float array type
6596 // passed directly. The latter are used to implement ELFv2 homogenous
6597 // float aggregates.
6598
6599 // Named arguments go into FPRs first, and once they overflow, the
6600 // remaining arguments go into GPRs and then the parameter save area.
6601 // Unnamed arguments for vararg functions always go to GPRs and
6602 // then the parameter save area. For now, put all arguments to vararg
6603 // routines always in both locations (FPR *and* GPR or stack slot).
6604 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6605 bool NeededLoad = false;
6606
6607 // First load the argument into the next available FPR.
6608 if (FPR_idx != NumFPRs)
6609 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6610
6611 // Next, load the argument into GPR or stack slot if needed.
6612 if (!NeedGPROrStack)
6613 ;
6614 else if (GPR_idx != NumGPRs && !IsFastCall) {
6615 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6616 // once we support fp <-> gpr moves.
6617
6618 // In the non-vararg case, this can only ever happen in the
6619 // presence of f32 array types, since otherwise we never run
6620 // out of FPRs before running out of GPRs.
6621 SDValue ArgVal;
6622
6623 // Double values are always passed in a single GPR.
6624 if (Arg.getValueType() != MVT::f32) {
6625 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6626
6627 // Non-array float values are extended and passed in a GPR.
6628 } else if (!Flags.isInConsecutiveRegs()) {
6629 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6630 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6631
6632 // If we have an array of floats, we collect every odd element
6633 // together with its predecessor into one GPR.
6634 } else if (ArgOffset % PtrByteSize != 0) {
6635 SDValue Lo, Hi;
6636 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6637 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6638 if (!isLittleEndian)
6639 std::swap(Lo, Hi);
6640 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6641
6642 // The final element, if even, goes into the first half of a GPR.
6643 } else if (Flags.isInConsecutiveRegsLast()) {
6644 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6645 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6646 if (!isLittleEndian)
6647 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6648 DAG.getConstant(32, dl, MVT::i32));
6649
6650 // Non-final even elements are skipped; they will be handled
6651 // together the with subsequent argument on the next go-around.
6652 } else
6653 ArgVal = SDValue();
6654
6655 if (ArgVal.getNode())
6656 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6657 } else {
6658 if (IsFastCall)
6659 ComputePtrOff();
6660
6661 // Single-precision floating-point values are mapped to the
6662 // second (rightmost) word of the stack doubleword.
6663 if (Arg.getValueType() == MVT::f32 &&
6664 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6665 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6666 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6667 }
6668
6669 assert(HasParameterArea &&
6670 "Parameter area must exist to pass an argument in memory.");
6671 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6672 true, CFlags.IsTailCall, false, MemOpChains,
6673 TailCallArguments, dl);
6674
6675 NeededLoad = true;
6676 }
6677 // When passing an array of floats, the array occupies consecutive
6678 // space in the argument area; only round up to the next doubleword
6679 // at the end of the array. Otherwise, each float takes 8 bytes.
6680 if (!IsFastCall || NeededLoad) {
6681 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6682 Flags.isInConsecutiveRegs()) ? 4 : 8;
6683 if (Flags.isInConsecutiveRegsLast())
6684 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6685 }
6686 break;
6687 }
6688 case MVT::v4f32:
6689 case MVT::v4i32:
6690 case MVT::v8i16:
6691 case MVT::v16i8:
6692 case MVT::v2f64:
6693 case MVT::v2i64:
6694 case MVT::v1i128:
6695 case MVT::f128:
6696 // These can be scalar arguments or elements of a vector array type
6697 // passed directly. The latter are used to implement ELFv2 homogenous
6698 // vector aggregates.
6699
6700 // For a varargs call, named arguments go into VRs or on the stack as
6701 // usual; unnamed arguments always go to the stack or the corresponding
6702 // GPRs when within range. For now, we always put the value in both
6703 // locations (or even all three).
6704 if (CFlags.IsVarArg) {
6705 assert(HasParameterArea &&
6706 "Parameter area must exist if we have a varargs call.");
6707 // We could elide this store in the case where the object fits
6708 // entirely in R registers. Maybe later.
6709 SDValue Store =
6710 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6711 MemOpChains.push_back(Store);
6712 if (VR_idx != NumVRs) {
6713 SDValue Load =
6714 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6715 MemOpChains.push_back(Load.getValue(1));
6716 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6717 }
6718 ArgOffset += 16;
6719 for (unsigned i=0; i<16; i+=PtrByteSize) {
6720 if (GPR_idx == NumGPRs)
6721 break;
6722 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6723 DAG.getConstant(i, dl, PtrVT));
6724 SDValue Load =
6725 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6726 MemOpChains.push_back(Load.getValue(1));
6727 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6728 }
6729 break;
6730 }
6731
6732 // Non-varargs Altivec params go into VRs or on the stack.
6733 if (VR_idx != NumVRs) {
6734 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6735 } else {
6736 if (IsFastCall)
6737 ComputePtrOff();
6738
6739 assert(HasParameterArea &&
6740 "Parameter area must exist to pass an argument in memory.");
6741 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6742 true, CFlags.IsTailCall, true, MemOpChains,
6743 TailCallArguments, dl);
6744 if (IsFastCall)
6745 ArgOffset += 16;
6746 }
6747
6748 if (!IsFastCall)
6749 ArgOffset += 16;
6750 break;
6751 }
6752 }
6753
6754 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6755 "mismatch in size of parameter area");
6756 (void)NumBytesActuallyUsed;
6757
6758 if (!MemOpChains.empty())
6759 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6760
6761 // Check if this is an indirect call (MTCTR/BCTRL).
6762 // See prepareDescriptorIndirectCall and buildCallOperands for more
6763 // information about calls through function pointers in the 64-bit SVR4 ABI.
6764 if (CFlags.IsIndirect) {
6765 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6766 // caller in the TOC save area.
6767 if (isTOCSaveRestoreRequired(Subtarget)) {
6768 assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6769 // Load r2 into a virtual register and store it to the TOC save area.
6770 setUsesTOCBasePtr(DAG);
6771 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6772 // TOC save area offset.
6773 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6774 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6775 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6776 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6778 DAG.getMachineFunction(), TOCSaveOffset));
6779 }
6780 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6781 // This does not mean the MTCTR instruction must use R12; it's easier
6782 // to model this as an extra parameter, so do that.
6783 if (isELFv2ABI && !CFlags.IsPatchPoint)
6784 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6785 }
6786
6787 // Build a sequence of copy-to-reg nodes chained together with token chain
6788 // and flag operands which copy the outgoing args into the appropriate regs.
6789 SDValue InGlue;
6790 for (const auto &[Reg, N] : RegsToPass) {
6791 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6792 InGlue = Chain.getValue(1);
6793 }
6794
6795 if (CFlags.IsTailCall && !IsSibCall)
6796 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6797 TailCallArguments);
6798
6799 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6800 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6801}
6802
6803// Returns true when the shadow of a general purpose argument register
6804// in the parameter save area is aligned to at least 'RequiredAlign'.
6805static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6806 assert(RequiredAlign.value() <= 16 &&
6807 "Required alignment greater than stack alignment.");
6808 switch (Reg) {
6809 default:
6810 report_fatal_error("called on invalid register.");
6811 case PPC::R5:
6812 case PPC::R9:
6813 case PPC::X3:
6814 case PPC::X5:
6815 case PPC::X7:
6816 case PPC::X9:
6817 // These registers are 16 byte aligned which is the most strict aligment
6818 // we can support.
6819 return true;
6820 case PPC::R3:
6821 case PPC::R7:
6822 case PPC::X4:
6823 case PPC::X6:
6824 case PPC::X8:
6825 case PPC::X10:
6826 // The shadow of these registers in the PSA is 8 byte aligned.
6827 return RequiredAlign <= 8;
6828 case PPC::R4:
6829 case PPC::R6:
6830 case PPC::R8:
6831 case PPC::R10:
6832 return RequiredAlign <= 4;
6833 }
6834}
6835
6836static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6837 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6838 Type *OrigTy, CCState &State) {
6839 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6840 State.getMachineFunction().getSubtarget());
6841 const bool IsPPC64 = Subtarget.isPPC64();
6842 const unsigned PtrSize = IsPPC64 ? 8 : 4;
6843 const Align PtrAlign(PtrSize);
6844 const Align StackAlign(16);
6845 const MVT RegVT = Subtarget.getScalarIntVT();
6846
6847 if (ValVT == MVT::f128)
6848 report_fatal_error("f128 is unimplemented on AIX.");
6849
6850 static const MCPhysReg GPR_32[] = {// 32-bit registers.
6851 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6852 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6853 static const MCPhysReg GPR_64[] = {// 64-bit registers.
6854 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6855 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6856
6857 static const MCPhysReg VR[] = {// Vector registers.
6858 PPC::V2, PPC::V3, PPC::V4, PPC::V5,
6859 PPC::V6, PPC::V7, PPC::V8, PPC::V9,
6860 PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6861
6862 const ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6863
6864 if (ArgFlags.isNest()) {
6865 MCRegister EnvReg = State.AllocateReg(IsPPC64 ? PPC::X11 : PPC::R11);
6866 if (!EnvReg)
6867 report_fatal_error("More then one nest argument.");
6868 State.addLoc(CCValAssign::getReg(ValNo, ValVT, EnvReg, RegVT, LocInfo));
6869 return false;
6870 }
6871
6872 if (ArgFlags.isByVal()) {
6873 const Align ByValAlign(ArgFlags.getNonZeroByValAlign());
6874 if (ByValAlign > StackAlign)
6875 report_fatal_error("Pass-by-value arguments with alignment greater than "
6876 "16 are not supported.");
6877
6878 const unsigned ByValSize = ArgFlags.getByValSize();
6879 const Align ObjAlign = ByValAlign > PtrAlign ? ByValAlign : PtrAlign;
6880
6881 // An empty aggregate parameter takes up no storage and no registers,
6882 // but needs a MemLoc for a stack slot for the formal arguments side.
6883 if (ByValSize == 0) {
6885 State.getStackSize(), RegVT, LocInfo));
6886 return false;
6887 }
6888
6889 // Shadow allocate any registers that are not properly aligned.
6890 unsigned NextReg = State.getFirstUnallocated(GPRs);
6891 while (NextReg != GPRs.size() &&
6892 !isGPRShadowAligned(GPRs[NextReg], ObjAlign)) {
6893 // Shadow allocate next registers since its aligment is not strict enough.
6894 MCRegister Reg = State.AllocateReg(GPRs);
6895 // Allocate the stack space shadowed by said register.
6896 State.AllocateStack(PtrSize, PtrAlign);
6897 assert(Reg && "Alocating register unexpectedly failed.");
6898 (void)Reg;
6899 NextReg = State.getFirstUnallocated(GPRs);
6900 }
6901
6902 const unsigned StackSize = alignTo(ByValSize, ObjAlign);
6903 unsigned Offset = State.AllocateStack(StackSize, ObjAlign);
6904 for (const unsigned E = Offset + StackSize; Offset < E; Offset += PtrSize) {
6905 if (MCRegister Reg = State.AllocateReg(GPRs))
6906 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6907 else {
6910 LocInfo));
6911 break;
6912 }
6913 }
6914 return false;
6915 }
6916
6917 // Arguments always reserve parameter save area.
6918 switch (ValVT.SimpleTy) {
6919 default:
6920 report_fatal_error("Unhandled value type for argument.");
6921 case MVT::i64:
6922 // i64 arguments should have been split to i32 for PPC32.
6923 assert(IsPPC64 && "PPC32 should have split i64 values.");
6924 [[fallthrough]];
6925 case MVT::i1:
6926 case MVT::i32: {
6927 const unsigned Offset = State.AllocateStack(PtrSize, PtrAlign);
6928 // AIX integer arguments are always passed in register width.
6929 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6930 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6932 if (MCRegister Reg = State.AllocateReg(GPRs))
6933 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6934 else
6935 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6936
6937 return false;
6938 }
6939 case MVT::f32:
6940 case MVT::f64: {
6941 // Parameter save area (PSA) is reserved even if the float passes in fpr.
6942 const unsigned StoreSize = LocVT.getStoreSize();
6943 // Floats are always 4-byte aligned in the PSA on AIX.
6944 // This includes f64 in 64-bit mode for ABI compatibility.
6945 const unsigned Offset =
6946 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6947 MCRegister FReg = State.AllocateReg(FPR);
6948 if (FReg)
6949 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6950
6951 // Reserve and initialize GPRs or initialize the PSA as required.
6952 for (unsigned I = 0; I < StoreSize; I += PtrSize) {
6953 if (MCRegister Reg = State.AllocateReg(GPRs)) {
6954 assert(FReg && "An FPR should be available when a GPR is reserved.");
6955 if (State.isVarArg()) {
6956 // Successfully reserved GPRs are only initialized for vararg calls.
6957 // Custom handling is required for:
6958 // f64 in PPC32 needs to be split into 2 GPRs.
6959 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6960 State.addLoc(
6961 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6962 }
6963 } else {
6964 // If there are insufficient GPRs, the PSA needs to be initialized.
6965 // Initialization occurs even if an FPR was initialized for
6966 // compatibility with the AIX XL compiler. The full memory for the
6967 // argument will be initialized even if a prior word is saved in GPR.
6968 // A custom memLoc is used when the argument also passes in FPR so
6969 // that the callee handling can skip over it easily.
6970 State.addLoc(
6971 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6972 LocInfo)
6973 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6974 break;
6975 }
6976 }
6977
6978 return false;
6979 }
6980 case MVT::v4f32:
6981 case MVT::v4i32:
6982 case MVT::v8i16:
6983 case MVT::v16i8:
6984 case MVT::v2i64:
6985 case MVT::v2f64:
6986 case MVT::v1i128: {
6987 const unsigned VecSize = 16;
6988 const Align VecAlign(VecSize);
6989
6990 if (!State.isVarArg()) {
6991 // If there are vector registers remaining we don't consume any stack
6992 // space.
6993 if (MCRegister VReg = State.AllocateReg(VR)) {
6994 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6995 return false;
6996 }
6997 // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6998 // might be allocated in the portion of the PSA that is shadowed by the
6999 // GPRs.
7000 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7001 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7002 return false;
7003 }
7004
7005 unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
7006 // Burn any underaligned registers and their shadowed stack space until
7007 // we reach the required alignment.
7008 while (NextRegIndex != GPRs.size() &&
7009 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
7010 // Shadow allocate register and its stack shadow.
7011 MCRegister Reg = State.AllocateReg(GPRs);
7012 State.AllocateStack(PtrSize, PtrAlign);
7013 assert(Reg && "Allocating register unexpectedly failed.");
7014 (void)Reg;
7015 NextRegIndex = State.getFirstUnallocated(GPRs);
7016 }
7017
7018 // Vectors that are passed as fixed arguments are handled differently.
7019 // They are passed in VRs if any are available (unlike arguments passed
7020 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
7021 // functions)
7022 if (!ArgFlags.isVarArg()) {
7023 if (MCRegister VReg = State.AllocateReg(VR)) {
7024 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7025 // Shadow allocate GPRs and stack space even though we pass in a VR.
7026 for (unsigned I = 0; I != VecSize; I += PtrSize)
7027 State.AllocateReg(GPRs);
7028 State.AllocateStack(VecSize, VecAlign);
7029 return false;
7030 }
7031 // No vector registers remain so pass on the stack.
7032 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7033 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7034 return false;
7035 }
7036
7037 // If all GPRS are consumed then we pass the argument fully on the stack.
7038 if (NextRegIndex == GPRs.size()) {
7039 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7040 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7041 return false;
7042 }
7043
7044 // Corner case for 32-bit codegen. We have 2 registers to pass the first
7045 // half of the argument, and then need to pass the remaining half on the
7046 // stack.
7047 if (GPRs[NextRegIndex] == PPC::R9) {
7048 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7049 State.addLoc(
7050 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7051
7052 const MCRegister FirstReg = State.AllocateReg(PPC::R9);
7053 const MCRegister SecondReg = State.AllocateReg(PPC::R10);
7054 assert(FirstReg && SecondReg &&
7055 "Allocating R9 or R10 unexpectedly failed.");
7056 State.addLoc(
7057 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
7058 State.addLoc(
7059 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
7060 return false;
7061 }
7062
7063 // We have enough GPRs to fully pass the vector argument, and we have
7064 // already consumed any underaligned registers. Start with the custom
7065 // MemLoc and then the custom RegLocs.
7066 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7067 State.addLoc(
7068 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7069 for (unsigned I = 0; I != VecSize; I += PtrSize) {
7070 const MCRegister Reg = State.AllocateReg(GPRs);
7071 assert(Reg && "Failed to allocated register for vararg vector argument");
7072 State.addLoc(
7073 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7074 }
7075 return false;
7076 }
7077 }
7078 return true;
7079}
7080
7081// So far, this function is only used by LowerFormalArguments_AIX()
7083 bool IsPPC64,
7084 bool HasP8Vector,
7085 bool HasVSX) {
7086 assert((IsPPC64 || SVT != MVT::i64) &&
7087 "i64 should have been split for 32-bit codegen.");
7088
7089 switch (SVT) {
7090 default:
7091 report_fatal_error("Unexpected value type for formal argument");
7092 case MVT::i1:
7093 case MVT::i32:
7094 case MVT::i64:
7095 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7096 case MVT::f32:
7097 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
7098 case MVT::f64:
7099 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
7100 case MVT::v4f32:
7101 case MVT::v4i32:
7102 case MVT::v8i16:
7103 case MVT::v16i8:
7104 case MVT::v2i64:
7105 case MVT::v2f64:
7106 case MVT::v1i128:
7107 return &PPC::VRRCRegClass;
7108 }
7109}
7110
7112 SelectionDAG &DAG, SDValue ArgValue,
7113 MVT LocVT, const SDLoc &dl) {
7114 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7115 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7116
7117 if (Flags.isSExt())
7118 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7119 DAG.getValueType(ValVT));
7120 else if (Flags.isZExt())
7121 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7122 DAG.getValueType(ValVT));
7123
7124 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7125}
7126
7127static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7128 const unsigned LASize = FL->getLinkageSize();
7129
7130 if (PPC::GPRCRegClass.contains(Reg)) {
7131 assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7132 "Reg must be a valid argument register!");
7133 return LASize + 4 * (Reg - PPC::R3);
7134 }
7135
7136 if (PPC::G8RCRegClass.contains(Reg)) {
7137 assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7138 "Reg must be a valid argument register!");
7139 return LASize + 8 * (Reg - PPC::X3);
7140 }
7141
7142 llvm_unreachable("Only general purpose registers expected.");
7143}
7144
7145// AIX ABI Stack Frame Layout:
7146//
7147// Low Memory +--------------------------------------------+
7148// SP +---> | Back chain | ---+
7149// | +--------------------------------------------+ |
7150// | | Saved Condition Register | |
7151// | +--------------------------------------------+ |
7152// | | Saved Linkage Register | |
7153// | +--------------------------------------------+ | Linkage Area
7154// | | Reserved for compilers | |
7155// | +--------------------------------------------+ |
7156// | | Reserved for binders | |
7157// | +--------------------------------------------+ |
7158// | | Saved TOC pointer | ---+
7159// | +--------------------------------------------+
7160// | | Parameter save area |
7161// | +--------------------------------------------+
7162// | | Alloca space |
7163// | +--------------------------------------------+
7164// | | Local variable space |
7165// | +--------------------------------------------+
7166// | | Float/int conversion temporary |
7167// | +--------------------------------------------+
7168// | | Save area for AltiVec registers |
7169// | +--------------------------------------------+
7170// | | AltiVec alignment padding |
7171// | +--------------------------------------------+
7172// | | Save area for VRSAVE register |
7173// | +--------------------------------------------+
7174// | | Save area for General Purpose registers |
7175// | +--------------------------------------------+
7176// | | Save area for Floating Point registers |
7177// | +--------------------------------------------+
7178// +---- | Back chain |
7179// High Memory +--------------------------------------------+
7180//
7181// Specifications:
7182// AIX 7.2 Assembler Language Reference
7183// Subroutine linkage convention
7184
7185SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7186 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7187 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7188 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7189
7190 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7191 CallConv == CallingConv::Fast) &&
7192 "Unexpected calling convention!");
7193
7194 if (getTargetMachine().Options.GuaranteedTailCallOpt)
7195 report_fatal_error("Tail call support is unimplemented on AIX.");
7196
7197 if (useSoftFloat())
7198 report_fatal_error("Soft float support is unimplemented on AIX.");
7199
7200 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7201
7202 const bool IsPPC64 = Subtarget.isPPC64();
7203 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7204
7205 // Assign locations to all of the incoming arguments.
7208 MachineFrameInfo &MFI = MF.getFrameInfo();
7209 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7210 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7211
7212 const EVT PtrVT = getPointerTy(MF.getDataLayout());
7213 // Reserve space for the linkage area on the stack.
7214 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7215 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7216 uint64_t SaveStackPos = CCInfo.getStackSize();
7217 bool SaveParams = MF.getFunction().hasFnAttribute("save-reg-params");
7218 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7219
7221
7222 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7223 CCValAssign &VA = ArgLocs[I++];
7224 MVT LocVT = VA.getLocVT();
7225 MVT ValVT = VA.getValVT();
7226 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7227
7228 EVT ArgVT = Ins[VA.getValNo()].ArgVT;
7229 bool ArgSignExt = Ins[VA.getValNo()].Flags.isSExt();
7230 // For compatibility with the AIX XL compiler, the float args in the
7231 // parameter save area are initialized even if the argument is available
7232 // in register. The caller is required to initialize both the register
7233 // and memory, however, the callee can choose to expect it in either.
7234 // The memloc is dismissed here because the argument is retrieved from
7235 // the register.
7236 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
7237 continue;
7238
7239 if (SaveParams && VA.isRegLoc() && !Flags.isByVal() && !VA.needsCustom()) {
7240 const TargetRegisterClass *RegClass = getRegClassForSVT(
7241 LocVT.SimpleTy, IsPPC64, Subtarget.hasP8Vector(), Subtarget.hasVSX());
7242 // On PPC64, debugger assumes extended 8-byte values are stored from GPR.
7243 MVT SaveVT = RegClass == &PPC::G8RCRegClass ? MVT::i64 : LocVT;
7244 const Register VReg = MF.addLiveIn(VA.getLocReg(), RegClass);
7245 SDValue Parm = DAG.getCopyFromReg(Chain, dl, VReg, SaveVT);
7246 int FI = MFI.CreateFixedObject(SaveVT.getStoreSize(), SaveStackPos, true);
7247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7248 SDValue StoreReg = DAG.getStore(Chain, dl, Parm, FIN,
7249 MachinePointerInfo(), Align(PtrByteSize));
7250 SaveStackPos = alignTo(SaveStackPos + SaveVT.getStoreSize(), PtrByteSize);
7251 MemOps.push_back(StoreReg);
7252 }
7253
7254 if (SaveParams && (VA.isMemLoc() || Flags.isByVal()) && !VA.needsCustom()) {
7255 unsigned StoreSize =
7256 Flags.isByVal() ? Flags.getByValSize() : LocVT.getStoreSize();
7257 SaveStackPos = alignTo(SaveStackPos + StoreSize, PtrByteSize);
7258 }
7259
7260 auto HandleMemLoc = [&]() {
7261 const unsigned LocSize = LocVT.getStoreSize();
7262 const unsigned ValSize = ValVT.getStoreSize();
7263 assert((ValSize <= LocSize) &&
7264 "Object size is larger than size of MemLoc");
7265 int CurArgOffset = VA.getLocMemOffset();
7266 // Objects are right-justified because AIX is big-endian.
7267 if (LocSize > ValSize)
7268 CurArgOffset += LocSize - ValSize;
7269 // Potential tail calls could cause overwriting of argument stack slots.
7270 const bool IsImmutable =
7272 (CallConv == CallingConv::Fast));
7273 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7274 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7275 SDValue ArgValue =
7276 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7277
7278 // While the ABI specifies the argument type is (sign or zero) extended
7279 // out to register width, not all code is compliant. We truncate and
7280 // re-extend to be more forgiving of these callers when the argument type
7281 // is smaller than register width.
7282 if (!ArgVT.isVector() && !ValVT.isVector() && ArgVT.isInteger() &&
7283 ValVT.isInteger() &&
7284 ArgVT.getScalarSizeInBits() < ValVT.getScalarSizeInBits()) {
7285 // It is possible to have either real integer values
7286 // or integers that were not originally integers.
7287 // In the latter case, these could have came from structs,
7288 // and these integers would not have an extend on the parameter.
7289 // Since these types of integers do not have an extend specified
7290 // in the first place, the type of extend that we do should not matter.
7291 EVT TruncatedArgVT = ArgVT.isSimple() && ArgVT.getSimpleVT() == MVT::i1
7292 ? MVT::i8
7293 : ArgVT;
7294 SDValue ArgValueTrunc =
7295 DAG.getNode(ISD::TRUNCATE, dl, TruncatedArgVT, ArgValue);
7296 SDValue ArgValueExt =
7297 ArgSignExt ? DAG.getSExtOrTrunc(ArgValueTrunc, dl, ValVT)
7298 : DAG.getZExtOrTrunc(ArgValueTrunc, dl, ValVT);
7299 InVals.push_back(ArgValueExt);
7300 } else {
7301 InVals.push_back(ArgValue);
7302 }
7303 };
7304
7305 // Vector arguments to VaArg functions are passed both on the stack, and
7306 // in any available GPRs. Load the value from the stack and add the GPRs
7307 // as live ins.
7308 if (VA.isMemLoc() && VA.needsCustom()) {
7309 assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
7310 assert(isVarArg && "Only use custom memloc for vararg.");
7311 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
7312 // matching custom RegLocs.
7313 const unsigned OriginalValNo = VA.getValNo();
7314 (void)OriginalValNo;
7315
7316 auto HandleCustomVecRegLoc = [&]() {
7317 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7318 "Missing custom RegLoc.");
7319 VA = ArgLocs[I++];
7320 assert(VA.getValVT().isVector() &&
7321 "Unexpected Val type for custom RegLoc.");
7322 assert(VA.getValNo() == OriginalValNo &&
7323 "ValNo mismatch between custom MemLoc and RegLoc.");
7325 MF.addLiveIn(VA.getLocReg(),
7326 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7327 Subtarget.hasVSX()));
7328 };
7329
7330 HandleMemLoc();
7331 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7332 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7333 // R10.
7334 HandleCustomVecRegLoc();
7335 HandleCustomVecRegLoc();
7336
7337 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7338 // we passed the vector in R5, R6, R7 and R8.
7339 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7340 assert(!IsPPC64 &&
7341 "Only 2 custom RegLocs expected for 64-bit codegen.");
7342 HandleCustomVecRegLoc();
7343 HandleCustomVecRegLoc();
7344 }
7345
7346 continue;
7347 }
7348
7349 if (VA.isRegLoc()) {
7350 if (VA.getValVT().isScalarInteger())
7352 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7353 switch (VA.getValVT().SimpleTy) {
7354 default:
7355 report_fatal_error("Unhandled value type for argument.");
7356 case MVT::f32:
7358 break;
7359 case MVT::f64:
7361 break;
7362 }
7363 } else if (VA.getValVT().isVector()) {
7364 switch (VA.getValVT().SimpleTy) {
7365 default:
7366 report_fatal_error("Unhandled value type for argument.");
7367 case MVT::v16i8:
7369 break;
7370 case MVT::v8i16:
7372 break;
7373 case MVT::v4i32:
7374 case MVT::v2i64:
7375 case MVT::v1i128:
7377 break;
7378 case MVT::v4f32:
7379 case MVT::v2f64:
7381 break;
7382 }
7383 }
7384 }
7385
7386 if (Flags.isByVal() && VA.isMemLoc()) {
7387 const unsigned Size =
7388 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7389 PtrByteSize);
7390 const int FI = MF.getFrameInfo().CreateFixedObject(
7391 Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7392 /* IsAliased */ true);
7393 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7394 InVals.push_back(FIN);
7395
7396 continue;
7397 }
7398
7399 if (Flags.isByVal()) {
7400 assert(VA.isRegLoc() && "MemLocs should already be handled.");
7401
7402 const MCPhysReg ArgReg = VA.getLocReg();
7403 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7404
7405 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7406 const int FI = MF.getFrameInfo().CreateFixedObject(
7407 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7408 /* IsAliased */ true);
7409 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7410 InVals.push_back(FIN);
7411
7412 // Add live ins for all the RegLocs for the same ByVal.
7413 const TargetRegisterClass *RegClass =
7414 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7415
7416 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7417 unsigned Offset) {
7418 const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7419 // Since the callers side has left justified the aggregate in the
7420 // register, we can simply store the entire register into the stack
7421 // slot.
7422 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7423 // The store to the fixedstack object is needed becuase accessing a
7424 // field of the ByVal will use a gep and load. Ideally we will optimize
7425 // to extracting the value from the register directly, and elide the
7426 // stores when the arguments address is not taken, but that will need to
7427 // be future work.
7428 SDValue Store = DAG.getStore(
7429 CopyFrom.getValue(1), dl, CopyFrom,
7432
7433 MemOps.push_back(Store);
7434 };
7435
7436 unsigned Offset = 0;
7437 HandleRegLoc(VA.getLocReg(), Offset);
7438 Offset += PtrByteSize;
7439 for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7440 Offset += PtrByteSize) {
7441 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7442 "RegLocs should be for ByVal argument.");
7443
7444 const CCValAssign RL = ArgLocs[I++];
7445 HandleRegLoc(RL.getLocReg(), Offset);
7447 }
7448
7449 if (Offset != StackSize) {
7450 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7451 "Expected MemLoc for remaining bytes.");
7452 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7453 // Consume the MemLoc.The InVal has already been emitted, so nothing
7454 // more needs to be done.
7455 ++I;
7456 }
7457
7458 continue;
7459 }
7460
7461 if (VA.isRegLoc() && !VA.needsCustom()) {
7462 MVT::SimpleValueType SVT = ValVT.SimpleTy;
7463 Register VReg =
7464 MF.addLiveIn(VA.getLocReg(),
7465 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7466 Subtarget.hasVSX()));
7467 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7468 if (ValVT.isScalarInteger() &&
7469 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7470 ArgValue =
7471 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7472 }
7473 InVals.push_back(ArgValue);
7474 continue;
7475 }
7476 if (VA.isMemLoc()) {
7477 HandleMemLoc();
7478 continue;
7479 }
7480 }
7481
7482 // On AIX a minimum of 8 words is saved to the parameter save area.
7483 const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7484 // Area that is at least reserved in the caller of this function.
7485 unsigned CallerReservedArea = std::max<unsigned>(
7486 CCInfo.getStackSize(), LinkageSize + MinParameterSaveArea);
7487
7488 // Set the size that is at least reserved in caller of this function. Tail
7489 // call optimized function's reserved stack space needs to be aligned so
7490 // that taking the difference between two stack areas will result in an
7491 // aligned stack.
7492 CallerReservedArea =
7493 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7494 FuncInfo->setMinReservedArea(CallerReservedArea);
7495
7496 if (isVarArg) {
7497 int VAListIndex = 0;
7498 // If any of the optional arguments are passed in register then the fixed
7499 // stack object we spill into is not immutable. Create a fixed stack object
7500 // that overlaps the remainder of the parameter save area.
7501 if (CCInfo.getStackSize() < (LinkageSize + MinParameterSaveArea)) {
7502 unsigned FixedStackSize =
7503 LinkageSize + MinParameterSaveArea - CCInfo.getStackSize();
7504 VAListIndex =
7505 MFI.CreateFixedObject(FixedStackSize, CCInfo.getStackSize(),
7506 /* IsImmutable */ false, /* IsAliased */ true);
7507 } else {
7508 // All the arguments passed through ellipses are on the stack. Create a
7509 // dummy fixed stack object the same size as a pointer since we don't
7510 // know the actual size.
7511 VAListIndex =
7512 MFI.CreateFixedObject(PtrByteSize, CCInfo.getStackSize(),
7513 /* IsImmutable */ true, /* IsAliased */ true);
7514 }
7515
7516 FuncInfo->setVarArgsFrameIndex(VAListIndex);
7517 SDValue FIN = DAG.getFrameIndex(VAListIndex, PtrVT);
7518
7519 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7520 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7521
7522 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7523 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7524 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
7525
7526 // The fixed integer arguments of a variadic function are stored to the
7527 // VarArgsFrameIndex on the stack so that they may be loaded by
7528 // dereferencing the result of va_next.
7529 for (unsigned
7530 GPRIndex = (CCInfo.getStackSize() - LinkageSize) / PtrByteSize,
7531 Offset = 0;
7532 GPRIndex < NumGPArgRegs; ++GPRIndex, Offset += PtrByteSize) {
7533
7534 const Register VReg =
7535 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7536 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7537
7538 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7539 MachinePointerInfo MPI =
7540 MachinePointerInfo::getFixedStack(MF, VAListIndex, Offset);
7541 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MPI);
7542 MemOps.push_back(Store);
7543 // Increment the address for the next argument to store.
7544 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7545 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7546 }
7547 }
7548
7549 if (!MemOps.empty())
7550 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7551
7552 return Chain;
7553}
7554
7555SDValue PPCTargetLowering::LowerCall_AIX(
7556 SDValue Chain, SDValue Callee, CallFlags CFlags,
7558 const SmallVectorImpl<SDValue> &OutVals,
7559 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7561 const CallBase *CB) const {
7562 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7563 // AIX ABI stack frame layout.
7564
7565 assert((CFlags.CallConv == CallingConv::C ||
7566 CFlags.CallConv == CallingConv::Cold ||
7567 CFlags.CallConv == CallingConv::Fast) &&
7568 "Unexpected calling convention!");
7569
7570 if (CFlags.IsPatchPoint)
7571 report_fatal_error("This call type is unimplemented on AIX.");
7572
7573 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7574
7577 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7578 *DAG.getContext());
7579
7580 // Reserve space for the linkage save area (LSA) on the stack.
7581 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7582 // [SP][CR][LR][2 x reserved][TOC].
7583 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7584 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7585 const bool IsPPC64 = Subtarget.isPPC64();
7586 const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7587 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7588 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7589 CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7590
7591 // The prolog code of the callee may store up to 8 GPR argument registers to
7592 // the stack, allowing va_start to index over them in memory if the callee
7593 // is variadic.
7594 // Because we cannot tell if this is needed on the caller side, we have to
7595 // conservatively assume that it is needed. As such, make sure we have at
7596 // least enough stack space for the caller to store the 8 GPRs.
7597 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7598 const unsigned NumBytes = std::max<unsigned>(
7599 LinkageSize + MinParameterSaveAreaSize, CCInfo.getStackSize());
7600
7601 // Adjust the stack pointer for the new arguments...
7602 // These operations are automatically eliminated by the prolog/epilog pass.
7603 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7604 SDValue CallSeqStart = Chain;
7605
7607 SmallVector<SDValue, 8> MemOpChains;
7608
7609 // Set up a copy of the stack pointer for loading and storing any
7610 // arguments that may not fit in the registers available for argument
7611 // passing.
7612 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7613 : DAG.getRegister(PPC::R1, MVT::i32);
7614
7615 for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7616 const unsigned ValNo = ArgLocs[I].getValNo();
7617 SDValue Arg = OutVals[ValNo];
7618 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7619
7620 if (Flags.isByVal()) {
7621 const unsigned ByValSize = Flags.getByValSize();
7622
7623 // Nothing to do for zero-sized ByVals on the caller side.
7624 if (!ByValSize) {
7625 ++I;
7626 continue;
7627 }
7628
7629 auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7630 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7631 (LoadOffset != 0)
7632 ? DAG.getObjectPtrOffset(
7633 dl, Arg, TypeSize::getFixed(LoadOffset))
7634 : Arg,
7635 MachinePointerInfo(), VT);
7636 };
7637
7638 unsigned LoadOffset = 0;
7639
7640 // Initialize registers, which are fully occupied by the by-val argument.
7641 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7642 SDValue Load = GetLoad(PtrVT, LoadOffset);
7643 MemOpChains.push_back(Load.getValue(1));
7644 LoadOffset += PtrByteSize;
7645 const CCValAssign &ByValVA = ArgLocs[I++];
7646 assert(ByValVA.getValNo() == ValNo &&
7647 "Unexpected location for pass-by-value argument.");
7648 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7649 }
7650
7651 if (LoadOffset == ByValSize)
7652 continue;
7653
7654 // There must be one more loc to handle the remainder.
7655 assert(ArgLocs[I].getValNo() == ValNo &&
7656 "Expected additional location for by-value argument.");
7657
7658 if (ArgLocs[I].isMemLoc()) {
7659 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7660 const CCValAssign &ByValVA = ArgLocs[I++];
7661 ISD::ArgFlagsTy MemcpyFlags = Flags;
7662 // Only memcpy the bytes that don't pass in register.
7663 MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7664 Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7665 (LoadOffset != 0) ? DAG.getObjectPtrOffset(
7666 dl, Arg, TypeSize::getFixed(LoadOffset))
7667 : Arg,
7669 dl, StackPtr, TypeSize::getFixed(ByValVA.getLocMemOffset())),
7670 CallSeqStart, MemcpyFlags, DAG, dl);
7671 continue;
7672 }
7673
7674 // Initialize the final register residue.
7675 // Any residue that occupies the final by-val arg register must be
7676 // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7677 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7678 // 2 and 1 byte loads.
7679 const unsigned ResidueBytes = ByValSize % PtrByteSize;
7680 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7681 "Unexpected register residue for by-value argument.");
7682 SDValue ResidueVal;
7683 for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7684 const unsigned N = llvm::bit_floor(ResidueBytes - Bytes);
7685 const MVT VT =
7686 N == 1 ? MVT::i8
7687 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7688 SDValue Load = GetLoad(VT, LoadOffset);
7689 MemOpChains.push_back(Load.getValue(1));
7690 LoadOffset += N;
7691 Bytes += N;
7692
7693 // By-val arguments are passed left-justfied in register.
7694 // Every load here needs to be shifted, otherwise a full register load
7695 // should have been used.
7696 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7697 "Unexpected load emitted during handling of pass-by-value "
7698 "argument.");
7699 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7700 EVT ShiftAmountTy =
7701 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7702 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7703 SDValue ShiftedLoad =
7704 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7705 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7706 ShiftedLoad)
7707 : ShiftedLoad;
7708 }
7709
7710 const CCValAssign &ByValVA = ArgLocs[I++];
7711 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7712 continue;
7713 }
7714
7715 CCValAssign &VA = ArgLocs[I++];
7716 const MVT LocVT = VA.getLocVT();
7717 const MVT ValVT = VA.getValVT();
7718
7719 switch (VA.getLocInfo()) {
7720 default:
7721 report_fatal_error("Unexpected argument extension type.");
7722 case CCValAssign::Full:
7723 break;
7724 case CCValAssign::ZExt:
7725 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7726 break;
7727 case CCValAssign::SExt:
7728 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7729 break;
7730 }
7731
7732 if (VA.isRegLoc() && !VA.needsCustom()) {
7733 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7734 continue;
7735 }
7736
7737 // Vector arguments passed to VarArg functions need custom handling when
7738 // they are passed (at least partially) in GPRs.
7739 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7740 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7741 // Store value to its stack slot.
7742 SDValue PtrOff =
7743 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7744 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7745 SDValue Store =
7746 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7747 MemOpChains.push_back(Store);
7748 const unsigned OriginalValNo = VA.getValNo();
7749 // Then load the GPRs from the stack
7750 unsigned LoadOffset = 0;
7751 auto HandleCustomVecRegLoc = [&]() {
7752 assert(I != E && "Unexpected end of CCvalAssigns.");
7753 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7754 "Expected custom RegLoc.");
7755 CCValAssign RegVA = ArgLocs[I++];
7756 assert(RegVA.getValNo() == OriginalValNo &&
7757 "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7758 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7759 DAG.getConstant(LoadOffset, dl, PtrVT));
7760 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7761 MemOpChains.push_back(Load.getValue(1));
7762 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7763 LoadOffset += PtrByteSize;
7764 };
7765
7766 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7767 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7768 // R10.
7769 HandleCustomVecRegLoc();
7770 HandleCustomVecRegLoc();
7771
7772 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7773 ArgLocs[I].getValNo() == OriginalValNo) {
7774 assert(!IsPPC64 &&
7775 "Only 2 custom RegLocs expected for 64-bit codegen.");
7776 HandleCustomVecRegLoc();
7777 HandleCustomVecRegLoc();
7778 }
7779
7780 continue;
7781 }
7782
7783 if (VA.isMemLoc()) {
7784 SDValue PtrOff =
7785 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7786 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7787 MemOpChains.push_back(
7788 DAG.getStore(Chain, dl, Arg, PtrOff,
7790 Subtarget.getFrameLowering()->getStackAlign()));
7791
7792 continue;
7793 }
7794
7795 if (!ValVT.isFloatingPoint())
7797 "Unexpected register handling for calling convention.");
7798
7799 // Custom handling is used for GPR initializations for vararg float
7800 // arguments.
7801 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7802 LocVT.isInteger() &&
7803 "Custom register handling only expected for VarArg.");
7804
7805 SDValue ArgAsInt =
7806 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7807
7808 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7809 // f32 in 32-bit GPR
7810 // f64 in 64-bit GPR
7811 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7812 else if (Arg.getValueType().getFixedSizeInBits() <
7813 LocVT.getFixedSizeInBits())
7814 // f32 in 64-bit GPR.
7815 RegsToPass.push_back(std::make_pair(
7816 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7817 else {
7818 // f64 in two 32-bit GPRs
7819 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7820 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7821 "Unexpected custom register for argument!");
7822 CCValAssign &GPR1 = VA;
7823 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7824 DAG.getConstant(32, dl, MVT::i8));
7825 RegsToPass.push_back(std::make_pair(
7826 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7827
7828 if (I != E) {
7829 // If only 1 GPR was available, there will only be one custom GPR and
7830 // the argument will also pass in memory.
7831 CCValAssign &PeekArg = ArgLocs[I];
7832 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7833 assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7834 CCValAssign &GPR2 = ArgLocs[I++];
7835 RegsToPass.push_back(std::make_pair(
7836 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7837 }
7838 }
7839 }
7840 }
7841
7842 if (!MemOpChains.empty())
7843 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7844
7845 // For indirect calls, we need to save the TOC base to the stack for
7846 // restoration after the call.
7847 if (CFlags.IsIndirect && !Subtarget.usePointerGlueHelper()) {
7848 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7849 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7850 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7851 const MVT PtrVT = Subtarget.getScalarIntVT();
7852 const unsigned TOCSaveOffset =
7853 Subtarget.getFrameLowering()->getTOCSaveOffset();
7854
7855 setUsesTOCBasePtr(DAG);
7856 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7857 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7858 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7859 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7860 Chain = DAG.getStore(
7861 Val.getValue(1), dl, Val, AddPtr,
7862 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7863 }
7864
7865 // Build a sequence of copy-to-reg nodes chained together with token chain
7866 // and flag operands which copy the outgoing args into the appropriate regs.
7867 SDValue InGlue;
7868 for (auto Reg : RegsToPass) {
7869 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InGlue);
7870 InGlue = Chain.getValue(1);
7871 }
7872
7873 const int SPDiff = 0;
7874 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
7875 Callee, SPDiff, NumBytes, Ins, InVals, CB);
7876}
7877
7878bool
7879PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7880 MachineFunction &MF, bool isVarArg,
7883 const Type *RetTy) const {
7885 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7886 return CCInfo.CheckReturn(
7887 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7889 : RetCC_PPC);
7890}
7891
7892SDValue
7893PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7894 bool isVarArg,
7896 const SmallVectorImpl<SDValue> &OutVals,
7897 const SDLoc &dl, SelectionDAG &DAG) const {
7899 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7900 *DAG.getContext());
7901 CCInfo.AnalyzeReturn(Outs,
7902 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7904 : RetCC_PPC);
7905
7906 SDValue Glue;
7907 SmallVector<SDValue, 4> RetOps(1, Chain);
7908
7909 // Copy the result values into the output registers.
7910 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7911 CCValAssign &VA = RVLocs[i];
7912 assert(VA.isRegLoc() && "Can only return in registers!");
7913
7914 SDValue Arg = OutVals[RealResIdx];
7915
7916 switch (VA.getLocInfo()) {
7917 default: llvm_unreachable("Unknown loc info!");
7918 case CCValAssign::Full: break;
7919 case CCValAssign::AExt:
7920 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7921 break;
7922 case CCValAssign::ZExt:
7923 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7924 break;
7925 case CCValAssign::SExt:
7926 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7927 break;
7928 }
7929 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7930 bool isLittleEndian = Subtarget.isLittleEndian();
7931 // Legalize ret f64 -> ret 2 x i32.
7932 SDValue SVal =
7933 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7934 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7935 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7936 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7937 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7938 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7939 Glue = Chain.getValue(1);
7940 VA = RVLocs[++i]; // skip ahead to next loc
7941 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7942 } else
7943 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
7944 Glue = Chain.getValue(1);
7945 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7946 }
7947
7948 RetOps[0] = Chain; // Update chain.
7949
7950 // Add the glue if we have it.
7951 if (Glue.getNode())
7952 RetOps.push_back(Glue);
7953
7954 return DAG.getNode(PPCISD::RET_GLUE, dl, MVT::Other, RetOps);
7955}
7956
7957SDValue
7958PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7959 SelectionDAG &DAG) const {
7960 SDLoc dl(Op);
7961
7962 // Get the correct type for integers.
7963 EVT IntVT = Op.getValueType();
7964
7965 // Get the inputs.
7966 SDValue Chain = Op.getOperand(0);
7967 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7968 // Build a DYNAREAOFFSET node.
7969 SDValue Ops[2] = {Chain, FPSIdx};
7970 SDVTList VTs = DAG.getVTList(IntVT);
7971 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7972}
7973
7974SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7975 SelectionDAG &DAG) const {
7976 // When we pop the dynamic allocation we need to restore the SP link.
7977 SDLoc dl(Op);
7978
7979 // Get the correct type for pointers.
7980 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7981
7982 // Construct the stack pointer operand.
7983 bool isPPC64 = Subtarget.isPPC64();
7984 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7985 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7986
7987 // Get the operands for the STACKRESTORE.
7988 SDValue Chain = Op.getOperand(0);
7989 SDValue SaveSP = Op.getOperand(1);
7990
7991 // Load the old link SP.
7992 SDValue LoadLinkSP =
7993 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7994
7995 // Restore the stack pointer.
7996 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7997
7998 // Store the old link SP.
7999 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
8000}
8001
8002SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
8004 bool isPPC64 = Subtarget.isPPC64();
8005 EVT PtrVT = getPointerTy(MF.getDataLayout());
8006
8007 // Get current frame pointer save index. The users of this index will be
8008 // primarily DYNALLOC instructions.
8009 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8010 int RASI = FI->getReturnAddrSaveIndex();
8011
8012 // If the frame pointer save index hasn't been defined yet.
8013 if (!RASI) {
8014 // Find out what the fix offset of the frame pointer save area.
8015 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
8016 // Allocate the frame index for frame pointer save area.
8017 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
8018 // Save the result.
8019 FI->setReturnAddrSaveIndex(RASI);
8020 }
8021 return DAG.getFrameIndex(RASI, PtrVT);
8022}
8023
8024SDValue
8025PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
8027 bool isPPC64 = Subtarget.isPPC64();
8028 EVT PtrVT = getPointerTy(MF.getDataLayout());
8029
8030 // Get current frame pointer save index. The users of this index will be
8031 // primarily DYNALLOC instructions.
8032 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8033 int FPSI = FI->getFramePointerSaveIndex();
8034
8035 // If the frame pointer save index hasn't been defined yet.
8036 if (!FPSI) {
8037 // Find out what the fix offset of the frame pointer save area.
8038 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
8039 // Allocate the frame index for frame pointer save area.
8040 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
8041 // Save the result.
8042 FI->setFramePointerSaveIndex(FPSI);
8043 }
8044 return DAG.getFrameIndex(FPSI, PtrVT);
8045}
8046
8047SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8048 SelectionDAG &DAG) const {
8050 // Get the inputs.
8051 SDValue Chain = Op.getOperand(0);
8052 SDValue Size = Op.getOperand(1);
8053 SDLoc dl(Op);
8054
8055 // Get the correct type for pointers.
8056 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8057 // Negate the size.
8058 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
8059 DAG.getConstant(0, dl, PtrVT), Size);
8060 // Construct a node for the frame pointer save index.
8061 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
8062 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
8063 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
8064 if (hasInlineStackProbe(MF))
8065 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
8066 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
8067}
8068
8069SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
8070 SelectionDAG &DAG) const {
8072
8073 bool isPPC64 = Subtarget.isPPC64();
8074 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8075
8076 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
8077 return DAG.getFrameIndex(FI, PtrVT);
8078}
8079
8080SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
8081 SelectionDAG &DAG) const {
8082 SDLoc DL(Op);
8083 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
8084 DAG.getVTList(MVT::i32, MVT::Other),
8085 Op.getOperand(0), Op.getOperand(1));
8086}
8087
8088SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
8089 SelectionDAG &DAG) const {
8090 SDLoc DL(Op);
8091 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
8092 Op.getOperand(0), Op.getOperand(1));
8093}
8094
8095SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8096 if (Op.getValueType().isVector())
8097 return LowerVectorLoad(Op, DAG);
8098
8099 assert(Op.getValueType() == MVT::i1 &&
8100 "Custom lowering only for i1 loads");
8101
8102 // First, load 8 bits into 32 bits, then truncate to 1 bit.
8103
8104 SDLoc dl(Op);
8105 LoadSDNode *LD = cast<LoadSDNode>(Op);
8106
8107 SDValue Chain = LD->getChain();
8108 SDValue BasePtr = LD->getBasePtr();
8109 MachineMemOperand *MMO = LD->getMemOperand();
8110
8111 SDValue NewLD =
8112 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8113 BasePtr, MVT::i8, MMO);
8114 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8115
8116 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8117 return DAG.getMergeValues(Ops, dl);
8118}
8119
8120SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8121 if (Op.getOperand(1).getValueType().isVector())
8122 return LowerVectorStore(Op, DAG);
8123
8124 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8125 "Custom lowering only for i1 stores");
8126
8127 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8128
8129 SDLoc dl(Op);
8130 StoreSDNode *ST = cast<StoreSDNode>(Op);
8131
8132 SDValue Chain = ST->getChain();
8133 SDValue BasePtr = ST->getBasePtr();
8134 SDValue Value = ST->getValue();
8135 MachineMemOperand *MMO = ST->getMemOperand();
8136
8138 Value);
8139 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8140}
8141
8142// FIXME: Remove this once the ANDI glue bug is fixed:
8143SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8144 assert(Op.getValueType() == MVT::i1 &&
8145 "Custom lowering only for i1 results");
8146
8147 SDLoc DL(Op);
8148 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8149}
8150
8151SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8152 SelectionDAG &DAG) const {
8153
8154 // Implements a vector truncate that fits in a vector register as a shuffle.
8155 // We want to legalize vector truncates down to where the source fits in
8156 // a vector register (and target is therefore smaller than vector register
8157 // size). At that point legalization will try to custom lower the sub-legal
8158 // result and get here - where we can contain the truncate as a single target
8159 // operation.
8160
8161 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8162 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8163 //
8164 // We will implement it for big-endian ordering as this (where x denotes
8165 // undefined):
8166 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8167 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8168 //
8169 // The same operation in little-endian ordering will be:
8170 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8171 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8172
8173 EVT TrgVT = Op.getValueType();
8174 assert(TrgVT.isVector() && "Vector type expected.");
8175 unsigned TrgNumElts = TrgVT.getVectorNumElements();
8176 EVT EltVT = TrgVT.getVectorElementType();
8177 if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8178 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8180 return SDValue();
8181
8182 SDValue N1 = Op.getOperand(0);
8183 EVT SrcVT = N1.getValueType();
8184 unsigned SrcSize = SrcVT.getSizeInBits();
8185 if (SrcSize > 256 || !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8188 return SDValue();
8189 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8190 return SDValue();
8191
8192 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8193 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8194
8195 SDLoc DL(Op);
8196 SDValue Op1, Op2;
8197 if (SrcSize == 256) {
8198 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8199 EVT SplitVT =
8201 unsigned SplitNumElts = SplitVT.getVectorNumElements();
8202 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8203 DAG.getConstant(0, DL, VecIdxTy));
8204 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8205 DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8206 }
8207 else {
8208 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8209 Op2 = DAG.getUNDEF(WideVT);
8210 }
8211
8212 // First list the elements we want to keep.
8213 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8214 SmallVector<int, 16> ShuffV;
8215 if (Subtarget.isLittleEndian())
8216 for (unsigned i = 0; i < TrgNumElts; ++i)
8217 ShuffV.push_back(i * SizeMult);
8218 else
8219 for (unsigned i = 1; i <= TrgNumElts; ++i)
8220 ShuffV.push_back(i * SizeMult - 1);
8221
8222 // Populate the remaining elements with undefs.
8223 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8224 // ShuffV.push_back(i + WideNumElts);
8225 ShuffV.push_back(WideNumElts + 1);
8226
8227 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8228 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8229 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8230}
8231
8232/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8233/// possible.
8234SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8235 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8236 EVT ResVT = Op.getValueType();
8237 EVT CmpVT = Op.getOperand(0).getValueType();
8238 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8239 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
8240 SDLoc dl(Op);
8241
8242 // Without power9-vector, we don't have native instruction for f128 comparison.
8243 // Following transformation to libcall is needed for setcc:
8244 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
8245 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
8246 SDValue Z = DAG.getSetCC(
8247 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
8248 LHS, RHS, CC);
8249 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
8250 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
8251 }
8252
8253 // Not FP, or using SPE? Not a fsel.
8254 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
8255 Subtarget.hasSPE())
8256 return Op;
8257
8258 SDNodeFlags Flags = Op.getNode()->getFlags();
8259
8260 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
8261 // presence of infinities.
8262 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8263 switch (CC) {
8264 default:
8265 break;
8266 case ISD::SETOGT:
8267 case ISD::SETGT:
8268 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
8269 case ISD::SETOLT:
8270 case ISD::SETLT:
8271 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
8272 }
8273 }
8274
8275 // We might be able to do better than this under some circumstances, but in
8276 // general, fsel-based lowering of select is a finite-math-only optimization.
8277 // For more information, see section F.3 of the 2.06 ISA specification.
8278 // With ISA 3.0
8279 if (!Flags.hasNoInfs() || !Flags.hasNoNaNs() || ResVT == MVT::f128)
8280 return Op;
8281
8282 // If the RHS of the comparison is a 0.0, we don't need to do the
8283 // subtraction at all.
8284 SDValue Sel1;
8286 switch (CC) {
8287 default: break; // SETUO etc aren't handled by fsel.
8288 case ISD::SETNE:
8289 std::swap(TV, FV);
8290 [[fallthrough]];
8291 case ISD::SETEQ:
8292 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8293 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8294 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8295 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8296 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8297 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8298 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8299 case ISD::SETULT:
8300 case ISD::SETLT:
8301 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8302 [[fallthrough]];
8303 case ISD::SETOGE:
8304 case ISD::SETGE:
8305 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8306 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8307 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8308 case ISD::SETUGT:
8309 case ISD::SETGT:
8310 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8311 [[fallthrough]];
8312 case ISD::SETOLE:
8313 case ISD::SETLE:
8314 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8315 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8316 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8317 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8318 }
8319
8320 SDValue Cmp;
8321 switch (CC) {
8322 default: break; // SETUO etc aren't handled by fsel.
8323 case ISD::SETNE:
8324 std::swap(TV, FV);
8325 [[fallthrough]];
8326 case ISD::SETEQ:
8327 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8328 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8329 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8330 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8331 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
8332 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8333 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8334 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8335 case ISD::SETULT:
8336 case ISD::SETLT:
8337 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8338 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8339 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8340 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8341 case ISD::SETOGE:
8342 case ISD::SETGE:
8343 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8344 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8345 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8346 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8347 case ISD::SETUGT:
8348 case ISD::SETGT:
8349 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8350 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8351 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8352 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8353 case ISD::SETOLE:
8354 case ISD::SETLE:
8355 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8356 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8357 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8358 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8359 }
8360 return Op;
8361}
8362
8363static unsigned getPPCStrictOpcode(unsigned Opc) {
8364 switch (Opc) {
8365 default:
8366 llvm_unreachable("No strict version of this opcode!");
8367 case PPCISD::FCTIDZ:
8368 return PPCISD::STRICT_FCTIDZ;
8369 case PPCISD::FCTIWZ:
8370 return PPCISD::STRICT_FCTIWZ;
8371 case PPCISD::FCTIDUZ:
8372 return PPCISD::STRICT_FCTIDUZ;
8373 case PPCISD::FCTIWUZ:
8374 return PPCISD::STRICT_FCTIWUZ;
8375 case PPCISD::FCFID:
8376 return PPCISD::STRICT_FCFID;
8377 case PPCISD::FCFIDU:
8378 return PPCISD::STRICT_FCFIDU;
8379 case PPCISD::FCFIDS:
8380 return PPCISD::STRICT_FCFIDS;
8381 case PPCISD::FCFIDUS:
8382 return PPCISD::STRICT_FCFIDUS;
8383 }
8384}
8385
8387 const PPCSubtarget &Subtarget) {
8388 SDLoc dl(Op);
8389 bool IsStrict = Op->isStrictFPOpcode();
8390 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8391 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8392
8393 // TODO: Any other flags to propagate?
8394 SDNodeFlags Flags;
8395 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8396
8397 // For strict nodes, source is the second operand.
8398 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8399 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8400 MVT DestTy = Op.getSimpleValueType();
8401 assert(Src.getValueType().isFloatingPoint() &&
8402 (DestTy == MVT::i8 || DestTy == MVT::i16 || DestTy == MVT::i32 ||
8403 DestTy == MVT::i64) &&
8404 "Invalid FP_TO_INT types");
8405 if (Src.getValueType() == MVT::f32) {
8406 if (IsStrict) {
8407 Src =
8409 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8410 Chain = Src.getValue(1);
8411 } else
8412 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8413 }
8414 if ((DestTy == MVT::i8 || DestTy == MVT::i16) && Subtarget.hasP9Vector())
8415 DestTy = Subtarget.getScalarIntVT();
8416 unsigned Opc = ISD::DELETED_NODE;
8417 switch (DestTy.SimpleTy) {
8418 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8419 case MVT::i32:
8420 Opc = IsSigned ? PPCISD::FCTIWZ
8421 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8422 break;
8423 case MVT::i64:
8424 assert((IsSigned || Subtarget.hasFPCVT()) &&
8425 "i64 FP_TO_UINT is supported only with FPCVT");
8426 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8427 }
8428 EVT ConvTy = Src.getValueType() == MVT::f128 ? MVT::f128 : MVT::f64;
8429 SDValue Conv;
8430 if (IsStrict) {
8432 Conv = DAG.getNode(Opc, dl, DAG.getVTList(ConvTy, MVT::Other), {Chain, Src},
8433 Flags);
8434 } else {
8435 Conv = DAG.getNode(Opc, dl, ConvTy, Src);
8436 }
8437 return Conv;
8438}
8439
8440void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8441 SelectionDAG &DAG,
8442 const SDLoc &dl) const {
8443 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8444 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8445 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8446 bool IsStrict = Op->isStrictFPOpcode();
8447
8448 // Convert the FP value to an int value through memory.
8449 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8450 (IsSigned || Subtarget.hasFPCVT());
8451 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8452 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8453 MachinePointerInfo MPI =
8455
8456 // Emit a store to the stack slot.
8457 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8459 if (i32Stack) {
8461 Alignment = Align(4);
8462 MachineMemOperand *MMO =
8463 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8464 SDValue Ops[] = { Chain, Tmp, FIPtr };
8465 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8466 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8467 } else
8468 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8469
8470 // Result is a load from the stack slot. If loading 4 bytes, make sure to
8471 // add in a bias on big endian.
8472 if (Op.getValueType() == MVT::i32 && !i32Stack &&
8473 !Subtarget.isLittleEndian()) {
8474 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8475 DAG.getConstant(4, dl, FIPtr.getValueType()));
8476 MPI = MPI.getWithOffset(4);
8477 }
8478
8479 RLI.Chain = Chain;
8480 RLI.Ptr = FIPtr;
8481 RLI.MPI = MPI;
8482 RLI.Alignment = Alignment;
8483}
8484
8485/// Custom lowers floating point to integer conversions to use
8486/// the direct move instructions available in ISA 2.07 to avoid the
8487/// need for load/store combinations.
8488SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8489 SelectionDAG &DAG,
8490 const SDLoc &dl) const {
8491 SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8492 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8493 if (Op->isStrictFPOpcode())
8494 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8495 else
8496 return Mov;
8497}
8498
8499SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8500 const SDLoc &dl) const {
8501 bool IsStrict = Op->isStrictFPOpcode();
8502 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8503 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8504 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8505 EVT SrcVT = Src.getValueType();
8506 EVT DstVT = Op.getValueType();
8507
8508