Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1122, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name PPCISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/PowerPC -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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"
14#include "MCTargetDesc/PPCPredicates.h"
15#include "PPC.h"
16#include "PPCCCState.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
20#include "PPCMachineFunctionInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSubtarget.h"
24#include "PPCTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/CodeGen/CallingConvLower.h"
38#include "llvm/CodeGen/ISDOpcodes.h"
39#include "llvm/CodeGen/MachineBasicBlock.h"
40#include "llvm/CodeGen/MachineFrameInfo.h"
41#include "llvm/CodeGen/MachineFunction.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineJumpTableInfo.h"
45#include "llvm/CodeGen/MachineLoopInfo.h"
46#include "llvm/CodeGen/MachineMemOperand.h"
47#include "llvm/CodeGen/MachineModuleInfo.h"
48#include "llvm/CodeGen/MachineOperand.h"
49#include "llvm/CodeGen/MachineRegisterInfo.h"
50#include "llvm/CodeGen/RuntimeLibcalls.h"
51#include "llvm/CodeGen/SelectionDAG.h"
52#include "llvm/CodeGen/SelectionDAGNodes.h"
53#include "llvm/CodeGen/TargetInstrInfo.h"
54#include "llvm/CodeGen/TargetLowering.h"
55#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56#include "llvm/CodeGen/TargetRegisterInfo.h"
57#include "llvm/CodeGen/ValueTypes.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"
63#include "llvm/IR/DerivedTypes.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalValue.h"
66#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/Instructions.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"
76#include "llvm/MC/MCRegisterInfo.h"
77#include "llvm/MC/MCSectionXCOFF.h"
78#include "llvm/MC/MCSymbolXCOFF.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/BranchProbability.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/CodeGen.h"
83#include "llvm/Support/CommandLine.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/Debug.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/Format.h"
88#include "llvm/Support/KnownBits.h"
89#include "llvm/Support/MachineValueType.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/Target/TargetMachine.h"
93#include "llvm/Target/TargetOptions.h"
94#include <algorithm>
95#include <cassert>
96#include <cstdint>
97#include <iterator>
98#include <list>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103
104#define DEBUG_TYPE"ppc-lowering" "ppc-lowering"
105
106static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108
109static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111
112static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114
115static cl::opt<bool> DisableSCO("disable-ppc-sco",
116cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117
118static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120
121static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123
124static cl::opt<bool> EnableQuadwordAtomics(
125 "ppc-quadword-atomics",
126 cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127 cl::Hidden);
128
129STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"ppc-lowering", "NumTailCalls"
, "Number of tail calls"}
;
130STATISTIC(NumSiblingCalls, "Number of sibling calls")static llvm::Statistic NumSiblingCalls = {"ppc-lowering", "NumSiblingCalls"
, "Number of sibling calls"}
;
131STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM")static llvm::Statistic ShufflesHandledWithVPERM = {"ppc-lowering"
, "ShufflesHandledWithVPERM", "Number of shuffles lowered to a VPERM"
}
;
132STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed")static llvm::Statistic NumDynamicAllocaProbed = {"ppc-lowering"
, "NumDynamicAllocaProbed", "Number of dynamic stack allocation probed"
}
;
133
134static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135
136static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137
138static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
139
140// FIXME: Remove this once the bug has been fixed!
141extern cl::opt<bool> ANDIGlueBug;
142
143PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
144 const PPCSubtarget &STI)
145 : TargetLowering(TM), Subtarget(STI) {
146 // Initialize map that relates the PPC addressing modes to the computed flags
147 // of a load/store instruction. The map is used to determine the optimal
148 // addressing mode when selecting load and stores.
149 initializeAddrModeMap();
150 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
151 // arguments are at least 4/8 bytes aligned.
152 bool isPPC64 = Subtarget.isPPC64();
153 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
154
155 // Set up the register classes.
156 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
157 if (!useSoftFloat()) {
158 if (hasSPE()) {
159 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
160 // EFPU2 APU only supports f32
161 if (!Subtarget.hasEFPU2())
162 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
163 } else {
164 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
165 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
166 }
167 }
168
169 // Match BITREVERSE to customized fast code sequence in the td file.
170 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
171 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
172
173 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
174 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
175
176 // Custom lower inline assembly to check for special registers.
177 setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
178 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
179
180 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
181 for (MVT VT : MVT::integer_valuetypes()) {
182 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
183 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
184 }
185
186 if (Subtarget.isISA3_0()) {
187 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
188 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
189 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
190 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
191 } else {
192 // No extending loads from f16 or HW conversions back and forth.
193 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
194 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
195 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
196 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
197 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
198 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
199 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
200 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
201 }
202
203 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
204
205 // PowerPC has pre-inc load and store's.
206 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
207 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
208 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
209 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
210 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
211 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
212 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
213 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
214 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
215 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
216 if (!Subtarget.hasSPE()) {
217 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
218 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
219 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
220 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
221 }
222
223 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
224 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
225 for (MVT VT : ScalarIntVTs) {
226 setOperationAction(ISD::ADDC, VT, Legal);
227 setOperationAction(ISD::ADDE, VT, Legal);
228 setOperationAction(ISD::SUBC, VT, Legal);
229 setOperationAction(ISD::SUBE, VT, Legal);
230 }
231
232 if (Subtarget.useCRBits()) {
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
234
235 if (isPPC64 || Subtarget.hasFPCVT()) {
236 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
237 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
238 isPPC64 ? MVT::i64 : MVT::i32);
239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
240 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
241 isPPC64 ? MVT::i64 : MVT::i32);
242
243 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
244 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
245 isPPC64 ? MVT::i64 : MVT::i32);
246 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
247 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
248 isPPC64 ? MVT::i64 : MVT::i32);
249
250 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
251 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
252 isPPC64 ? MVT::i64 : MVT::i32);
253 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
254 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
255 isPPC64 ? MVT::i64 : MVT::i32);
256
257 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
258 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
259 isPPC64 ? MVT::i64 : MVT::i32);
260 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
261 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
262 isPPC64 ? MVT::i64 : MVT::i32);
263 } else {
264 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
265 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
266 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
267 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
268 }
269
270 // PowerPC does not support direct load/store of condition registers.
271 setOperationAction(ISD::LOAD, MVT::i1, Custom);
272 setOperationAction(ISD::STORE, MVT::i1, Custom);
273
274 // FIXME: Remove this once the ANDI glue bug is fixed:
275 if (ANDIGlueBug)
276 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
277
278 for (MVT VT : MVT::integer_valuetypes()) {
279 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
280 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
281 setTruncStoreAction(VT, MVT::i1, Expand);
282 }
283
284 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
285 }
286
287 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
288 // PPC (the libcall is not available).
289 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
290 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
291 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
292 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
293
294 // We do not currently implement these libm ops for PowerPC.
295 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
296 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
297 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
298 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
299 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
300 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
301
302 // PowerPC has no SREM/UREM instructions unless we are on P9
303 // On P9 we may use a hardware instruction to compute the remainder.
304 // When the result of both the remainder and the division is required it is
305 // more efficient to compute the remainder from the result of the division
306 // rather than use the remainder instruction. The instructions are legalized
307 // directly because the DivRemPairsPass performs the transformation at the IR
308 // level.
309 if (Subtarget.isISA3_0()) {
310 setOperationAction(ISD::SREM, MVT::i32, Legal);
311 setOperationAction(ISD::UREM, MVT::i32, Legal);
312 setOperationAction(ISD::SREM, MVT::i64, Legal);
313 setOperationAction(ISD::UREM, MVT::i64, Legal);
314 } else {
315 setOperationAction(ISD::SREM, MVT::i32, Expand);
316 setOperationAction(ISD::UREM, MVT::i32, Expand);
317 setOperationAction(ISD::SREM, MVT::i64, Expand);
318 setOperationAction(ISD::UREM, MVT::i64, Expand);
319 }
320
321 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
322 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
323 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
324 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
325 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
326 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
327 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
328 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
329 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
330
331 // Handle constrained floating-point operations of scalar.
332 // TODO: Handle SPE specific operation.
333 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
334 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
335 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
336 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
337 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
338
339 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
340 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
341 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
342 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
343
344 if (!Subtarget.hasSPE()) {
345 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
346 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
347 }
348
349 if (Subtarget.hasVSX()) {
350 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
351 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
352 }
353
354 if (Subtarget.hasFSQRT()) {
355 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
356 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
357 }
358
359 if (Subtarget.hasFPRND()) {
360 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
361 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal);
362 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
363 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
364
365 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
366 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal);
367 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
368 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
369 }
370
371 // We don't support sin/cos/sqrt/fmod/pow
372 setOperationAction(ISD::FSIN , MVT::f64, Expand);
373 setOperationAction(ISD::FCOS , MVT::f64, Expand);
374 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
375 setOperationAction(ISD::FREM , MVT::f64, Expand);
376 setOperationAction(ISD::FPOW , MVT::f64, Expand);
377 setOperationAction(ISD::FSIN , MVT::f32, Expand);
378 setOperationAction(ISD::FCOS , MVT::f32, Expand);
379 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
380 setOperationAction(ISD::FREM , MVT::f32, Expand);
381 setOperationAction(ISD::FPOW , MVT::f32, Expand);
382 if (Subtarget.hasSPE()) {
383 setOperationAction(ISD::FMA , MVT::f64, Expand);
384 setOperationAction(ISD::FMA , MVT::f32, Expand);
385 } else {
386 setOperationAction(ISD::FMA , MVT::f64, Legal);
387 setOperationAction(ISD::FMA , MVT::f32, Legal);
388 }
389
390 if (Subtarget.hasSPE())
391 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
392
393 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
394
395 // If we're enabling GP optimizations, use hardware square root
396 if (!Subtarget.hasFSQRT() &&
397 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
398 Subtarget.hasFRE()))
399 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
400
401 if (!Subtarget.hasFSQRT() &&
402 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
403 Subtarget.hasFRES()))
404 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
405
406 if (Subtarget.hasFCPSGN()) {
407 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
409 } else {
410 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
412 }
413
414 if (Subtarget.hasFPRND()) {
415 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
416 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
417 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
418 setOperationAction(ISD::FROUND, MVT::f64, Legal);
419
420 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
421 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
422 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
423 setOperationAction(ISD::FROUND, MVT::f32, Legal);
424 }
425
426 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
427 // to speed up scalar BSWAP64.
428 // CTPOP or CTTZ were introduced in P8/P9 respectively
429 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
430 if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
431 setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
432 else
433 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
434 if (Subtarget.isISA3_0()) {
435 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
436 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
437 } else {
438 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
439 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
440 }
441
442 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
443 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
444 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
445 } else {
446 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
447 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
448 }
449
450 // PowerPC does not have ROTR
451 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
452 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
453
454 if (!Subtarget.useCRBits()) {
455 // PowerPC does not have Select
456 setOperationAction(ISD::SELECT, MVT::i32, Expand);
457 setOperationAction(ISD::SELECT, MVT::i64, Expand);
458 setOperationAction(ISD::SELECT, MVT::f32, Expand);
459 setOperationAction(ISD::SELECT, MVT::f64, Expand);
460 }
461
462 // PowerPC wants to turn select_cc of FP into fsel when possible.
463 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
464 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
465
466 // PowerPC wants to optimize integer setcc a bit
467 if (!Subtarget.useCRBits())
468 setOperationAction(ISD::SETCC, MVT::i32, Custom);
469
470 if (Subtarget.hasFPU()) {
471 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
472 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
473 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
474
475 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
476 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
477 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
478 }
479
480 // PowerPC does not have BRCOND which requires SetCC
481 if (!Subtarget.useCRBits())
482 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
483
484 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
485
486 if (Subtarget.hasSPE()) {
487 // SPE has built-in conversions
488 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
489 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
490 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
491 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
492 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
493 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
494
495 // SPE supports signaling compare of f32/f64.
496 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
497 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
498 } else {
499 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
500 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
501 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
502
503 // PowerPC does not have [U|S]INT_TO_FP
504 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
505 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
506 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
507 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
508 }
509
510 if (Subtarget.hasDirectMove() && isPPC64) {
511 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
512 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
513 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
514 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
515 if (TM.Options.UnsafeFPMath) {
516 setOperationAction(ISD::LRINT, MVT::f64, Legal);
517 setOperationAction(ISD::LRINT, MVT::f32, Legal);
518 setOperationAction(ISD::LLRINT, MVT::f64, Legal);
519 setOperationAction(ISD::LLRINT, MVT::f32, Legal);
520 setOperationAction(ISD::LROUND, MVT::f64, Legal);
521 setOperationAction(ISD::LROUND, MVT::f32, Legal);
522 setOperationAction(ISD::LLROUND, MVT::f64, Legal);
523 setOperationAction(ISD::LLROUND, MVT::f32, Legal);
524 }
525 } else {
526 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
527 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
528 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
529 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
530 }
531
532 // We cannot sextinreg(i1). Expand to shifts.
533 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
534
535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537 // support continuation, user-level threading, and etc.. As a result, no
538 // other SjLj exception interfaces are implemented and please don't build
539 // your own exception handling based on them.
540 // LLVM/Clang supports zero-cost DWARF exception handling.
541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543
544 // We want to legalize GlobalAddress and ConstantPool nodes into the
545 // appropriate instructions to materialize the address.
546 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
548 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
549 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
550 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
551 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
552 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
553 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
554 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
555 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
556
557 // TRAP is legal.
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559
560 // TRAMPOLINE is custom lowered.
561 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
562 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
563
564 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
565 setOperationAction(ISD::VASTART , MVT::Other, Custom);
566
567 if (Subtarget.is64BitELFABI()) {
568 // VAARG always uses double-word chunks, so promote anything smaller.
569 setOperationAction(ISD::VAARG, MVT::i1, Promote);
570 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
571 setOperationAction(ISD::VAARG, MVT::i8, Promote);
572 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
573 setOperationAction(ISD::VAARG, MVT::i16, Promote);
574 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
575 setOperationAction(ISD::VAARG, MVT::i32, Promote);
576 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
577 setOperationAction(ISD::VAARG, MVT::Other, Expand);
578 } else if (Subtarget.is32BitELFABI()) {
579 // VAARG is custom lowered with the 32-bit SVR4 ABI.
580 setOperationAction(ISD::VAARG, MVT::Other, Custom);
581 setOperationAction(ISD::VAARG, MVT::i64, Custom);
582 } else
583 setOperationAction(ISD::VAARG, MVT::Other, Expand);
584
585 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
586 if (Subtarget.is32BitELFABI())
587 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
588 else
589 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
590
591 // Use the default implementation.
592 setOperationAction(ISD::VAEND , MVT::Other, Expand);
593 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
594 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
595 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
596 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
597 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
598 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
599 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
600 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
601
602 // We want to custom lower some of our intrinsics.
603 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
604
605 // To handle counter-based loop conditions.
606 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
607
608 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
609 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
610 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
611 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
612
613 // Comparisons that require checking two conditions.
614 if (Subtarget.hasSPE()) {
615 setCondCodeAction(ISD::SETO, MVT::f32, Expand);
616 setCondCodeAction(ISD::SETO, MVT::f64, Expand);
617 setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
618 setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
619 }
620 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
621 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
622 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
623 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
624 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
625 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
626 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
627 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
628 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
629 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
630 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
631 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
632
633 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
634 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
635
636 if (Subtarget.has64BitSupport()) {
637 // They also have instructions for converting between i64 and fp.
638 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
639 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
640 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
641 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
642 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
643 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
644 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
645 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
646 // This is just the low 32 bits of a (signed) fp->i64 conversion.
647 // We cannot do this with Promote because i64 is not a legal type.
648 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
649 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
650
651 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
652 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
653 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
654 }
655 } else {
656 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
657 if (Subtarget.hasSPE()) {
658 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
659 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
660 } else {
661 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
662 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
663 }
664 }
665
666 // With the instructions enabled under FPCVT, we can do everything.
667 if (Subtarget.hasFPCVT()) {
668 if (Subtarget.has64BitSupport()) {
669 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
670 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
671 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
672 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
673 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
674 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
675 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
676 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
677 }
678
679 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
680 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
681 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
682 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
683 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
684 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
685 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
686 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
687 }
688
689 if (Subtarget.use64BitRegs()) {
690 // 64-bit PowerPC implementations can support i64 types directly
691 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
692 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
693 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
694 // 64-bit PowerPC wants to expand i128 shifts itself.
695 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
696 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
697 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
698 } else {
699 // 32-bit PowerPC wants to expand i64 shifts itself.
700 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
702 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
703 }
704
705 // PowerPC has better expansions for funnel shifts than the generic
706 // TargetLowering::expandFunnelShift.
707 if (Subtarget.has64BitSupport()) {
708 setOperationAction(ISD::FSHL, MVT::i64, Custom);
709 setOperationAction(ISD::FSHR, MVT::i64, Custom);
710 }
711 setOperationAction(ISD::FSHL, MVT::i32, Custom);
712 setOperationAction(ISD::FSHR, MVT::i32, Custom);
713
714 if (Subtarget.hasVSX()) {
715 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
716 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
717 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
718 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
719 }
720
721 if (Subtarget.hasAltivec()) {
722 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
723 setOperationAction(ISD::SADDSAT, VT, Legal);
724 setOperationAction(ISD::SSUBSAT, VT, Legal);
725 setOperationAction(ISD::UADDSAT, VT, Legal);
726 setOperationAction(ISD::USUBSAT, VT, Legal);
727 }
728 // First set operation action for all vector types to expand. Then we
729 // will selectively turn on ones that can be effectively codegen'd.
730 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
731 // add/sub are legal for all supported vector VT's.
732 setOperationAction(ISD::ADD, VT, Legal);
733 setOperationAction(ISD::SUB, VT, Legal);
734
735 // For v2i64, these are only valid with P8Vector. This is corrected after
736 // the loop.
737 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
738 setOperationAction(ISD::SMAX, VT, Legal);
739 setOperationAction(ISD::SMIN, VT, Legal);
740 setOperationAction(ISD::UMAX, VT, Legal);
741 setOperationAction(ISD::UMIN, VT, Legal);
742 }
743 else {
744 setOperationAction(ISD::SMAX, VT, Expand);
745 setOperationAction(ISD::SMIN, VT, Expand);
746 setOperationAction(ISD::UMAX, VT, Expand);
747 setOperationAction(ISD::UMIN, VT, Expand);
748 }
749
750 if (Subtarget.hasVSX()) {
751 setOperationAction(ISD::FMAXNUM, VT, Legal);
752 setOperationAction(ISD::FMINNUM, VT, Legal);
753 }
754
755 // Vector instructions introduced in P8
756 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
757 setOperationAction(ISD::CTPOP, VT, Legal);
758 setOperationAction(ISD::CTLZ, VT, Legal);
759 }
760 else {
761 setOperationAction(ISD::CTPOP, VT, Expand);
762 setOperationAction(ISD::CTLZ, VT, Expand);
763 }
764
765 // Vector instructions introduced in P9
766 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
767 setOperationAction(ISD::CTTZ, VT, Legal);
768 else
769 setOperationAction(ISD::CTTZ, VT, Expand);
770
771 // We promote all shuffles to v16i8.
772 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
773 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
774
775 // We promote all non-typed operations to v4i32.
776 setOperationAction(ISD::AND , VT, Promote);
777 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
778 setOperationAction(ISD::OR , VT, Promote);
779 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
780 setOperationAction(ISD::XOR , VT, Promote);
781 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
782 setOperationAction(ISD::LOAD , VT, Promote);
783 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
784 setOperationAction(ISD::SELECT, VT, Promote);
785 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
786 setOperationAction(ISD::VSELECT, VT, Legal);
787 setOperationAction(ISD::SELECT_CC, VT, Promote);
788 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
789 setOperationAction(ISD::STORE, VT, Promote);
790 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
791
792 // No other operations are legal.
793 setOperationAction(ISD::MUL , VT, Expand);
794 setOperationAction(ISD::SDIV, VT, Expand);
795 setOperationAction(ISD::SREM, VT, Expand);
796 setOperationAction(ISD::UDIV, VT, Expand);
797 setOperationAction(ISD::UREM, VT, Expand);
798 setOperationAction(ISD::FDIV, VT, Expand);
799 setOperationAction(ISD::FREM, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSQRT, VT, Expand);
802 setOperationAction(ISD::FLOG, VT, Expand);
803 setOperationAction(ISD::FLOG10, VT, Expand);
804 setOperationAction(ISD::FLOG2, VT, Expand);
805 setOperationAction(ISD::FEXP, VT, Expand);
806 setOperationAction(ISD::FEXP2, VT, Expand);
807 setOperationAction(ISD::FSIN, VT, Expand);
808 setOperationAction(ISD::FCOS, VT, Expand);
809 setOperationAction(ISD::FABS, VT, Expand);
810 setOperationAction(ISD::FFLOOR, VT, Expand);
811 setOperationAction(ISD::FCEIL, VT, Expand);
812 setOperationAction(ISD::FTRUNC, VT, Expand);
813 setOperationAction(ISD::FRINT, VT, Expand);
814 setOperationAction(ISD::FNEARBYINT, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
818 setOperationAction(ISD::MULHU, VT, Expand);
819 setOperationAction(ISD::MULHS, VT, Expand);
820 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
821 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
822 setOperationAction(ISD::UDIVREM, VT, Expand);
823 setOperationAction(ISD::SDIVREM, VT, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
825 setOperationAction(ISD::FPOW, VT, Expand);
826 setOperationAction(ISD::BSWAP, VT, Expand);
827 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
828 setOperationAction(ISD::ROTL, VT, Expand);
829 setOperationAction(ISD::ROTR, VT, Expand);
830
831 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
832 setTruncStoreAction(VT, InnerVT, Expand);
833 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
834 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
835 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
836 }
837 }
838 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
839 if (!Subtarget.hasP8Vector()) {
840 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
841 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
842 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
843 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
844 }
845
846 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
847 // with merges, splats, etc.
848 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
849
850 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
851 // are cheap, so handle them before they get expanded to scalar.
852 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
853 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
854 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
855 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
856 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
857
858 setOperationAction(ISD::AND , MVT::v4i32, Legal);
859 setOperationAction(ISD::OR , MVT::v4i32, Legal);
860 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
861 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
862 setOperationAction(ISD::SELECT, MVT::v4i32,
863 Subtarget.useCRBits() ? Legal : Expand);
864 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
865 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
866 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
867 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
868 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
869 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
870 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
871 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
872 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
873 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
874 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
875 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
876 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
877
878 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
879 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
880 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
881 if (Subtarget.hasAltivec())
882 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
883 setOperationAction(ISD::ROTL, VT, Legal);
884 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
885 if (Subtarget.hasP8Altivec())
886 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
887
888 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
889 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
890 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
891 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
892
893 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
894 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
895
896 if (Subtarget.hasVSX()) {
897 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
898 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
899 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
900 }
901
902 if (Subtarget.hasP8Altivec())
903 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
904 else
905 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
906
907 if (Subtarget.isISA3_1()) {
908 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
909 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
910 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
911 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
912 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
913 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
914 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
915 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
916 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
917 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
918 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
919 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
920 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
921 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
922 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
923 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
924 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
925 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
926 }
927
928 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
929 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
930
931 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
932 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
933
934 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
935 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
936 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
937 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
938
939 // Altivec does not contain unordered floating-point compare instructions
940 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
941 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
942 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
943 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
944
945 if (Subtarget.hasVSX()) {
946 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
948 if (Subtarget.hasP8Vector()) {
949 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
951 }
952 if (Subtarget.hasDirectMove() && isPPC64) {
953 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
954 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
955 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
956 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
958 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
959 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
961 }
962 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
963
964 // The nearbyint variants are not allowed to raise the inexact exception
965 // so we can only code-gen them with unsafe math.
966 if (TM.Options.UnsafeFPMath) {
967 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
968 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
969 }
970
971 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
972 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
973 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
975 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
976 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
977 setOperationAction(ISD::FROUND, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979
980 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
981 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
982 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
983 setOperationAction(ISD::FROUND, MVT::f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::f32, Legal);
985
986 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
987 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
988
989 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
990 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
991
992 // Share the Altivec comparison restrictions.
993 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
994 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
995 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
996 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
997
998 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
999 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1000
1001 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1002
1003 if (Subtarget.hasP8Vector())
1004 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1005
1006 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1007
1008 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1009 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1010 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1011
1012 if (Subtarget.hasP8Altivec()) {
1013 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1014 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1015 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1016
1017 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1018 // SRL, but not for SRA because of the instructions available:
1019 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1020 // doing
1021 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1022 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1023 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1024
1025 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1026 }
1027 else {
1028 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1029 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1030 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1031
1032 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1033
1034 // VSX v2i64 only supports non-arithmetic operations.
1035 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1036 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1037 }
1038
1039 if (Subtarget.isISA3_1())
1040 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1041 else
1042 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1043
1044 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1045 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1046 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1047 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1048
1049 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1050
1051 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1052 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1053 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1054 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1055 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1056 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1057 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1058 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1059
1060 // Custom handling for partial vectors of integers converted to
1061 // floating point. We already have optimal handling for v2i32 through
1062 // the DAG combine, so those aren't necessary.
1063 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1064 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1065 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1066 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1067 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1068 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1069 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1070 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1071 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1072 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1076 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1077 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1078 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1079
1080 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1081 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1082 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1083 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1084 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1085 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1086
1087 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1088 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1089
1090 // Handle constrained floating-point operations of vector.
1091 // The predictor is `hasVSX` because altivec instruction has
1092 // no exception but VSX vector instruction has.
1093 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1094 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1095 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1096 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1097 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1098 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1099 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1100 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1101 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1102 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1103 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
1104 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1105 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1106
1107 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1108 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1109 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1110 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1111 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1112 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1113 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1114 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1115 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1116 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1117 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
1118 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1119 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1120
1121 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1122 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1123
1124 for (MVT FPT : MVT::fp_valuetypes())
1125 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1126
1127 // Expand the SELECT to SELECT_CC
1128 setOperationAction(ISD::SELECT, MVT::f128, Expand);
1129
1130 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1131 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1132
1133 // No implementation for these ops for PowerPC.
1134 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1135 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1136 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1137 setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1138 setOperationAction(ISD::FREM, MVT::f128, Expand);
1139 }
1140
1141 if (Subtarget.hasP8Altivec()) {
1142 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1143 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1144 }
1145
1146 if (Subtarget.hasP9Vector()) {
1147 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1149
1150 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1151 // SRL, but not for SRA because of the instructions available:
1152 // VS{RL} and VS{RL}O.
1153 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1154 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1155 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1156
1157 setOperationAction(ISD::FADD, MVT::f128, Legal);
1158 setOperationAction(ISD::FSUB, MVT::f128, Legal);
1159 setOperationAction(ISD::FDIV, MVT::f128, Legal);
1160 setOperationAction(ISD::FMUL, MVT::f128, Legal);
1161 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1162
1163 setOperationAction(ISD::FMA, MVT::f128, Legal);
1164 setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1165 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1166 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1167 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1168 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1169 setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1170
1171 setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1172 setOperationAction(ISD::FRINT, MVT::f128, Legal);
1173 setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1174 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1175 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1176 setOperationAction(ISD::FROUND, MVT::f128, Legal);
1177
1178 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1179 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1180 setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1181
1182 // Handle constrained floating-point operations of fp128
1183 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1184 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1185 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1186 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1187 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1188 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1189 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1190 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1191 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1192 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1193 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1194 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1195 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1196 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1197 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1198 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1199 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1200 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1201 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1202 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1203 } else if (Subtarget.hasVSX()) {
1204 setOperationAction(ISD::LOAD, MVT::f128, Promote);
1205 setOperationAction(ISD::STORE, MVT::f128, Promote);
1206
1207 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1208 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1209
1210 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1211 // fp_to_uint and int_to_fp.
1212 setOperationAction(ISD::FADD, MVT::f128, LibCall);
1213 setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1214
1215 setOperationAction(ISD::FMUL, MVT::f128, Expand);
1216 setOperationAction(ISD::FDIV, MVT::f128, Expand);
1217 setOperationAction(ISD::FNEG, MVT::f128, Expand);
1218 setOperationAction(ISD::FABS, MVT::f128, Expand);
1219 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1220 setOperationAction(ISD::FMA, MVT::f128, Expand);
1221 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1222
1223 // Expand the fp_extend if the target type is fp128.
1224 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1225 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1226
1227 // Expand the fp_round if the source type is fp128.
1228 for (MVT VT : {MVT::f32, MVT::f64}) {
1229 setOperationAction(ISD::FP_ROUND, VT, Custom);
1230 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1231 }
1232
1233 setOperationAction(ISD::SETCC, MVT::f128, Custom);
1234 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1235 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1236 setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1237
1238 // Lower following f128 select_cc pattern:
1239 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1240 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1241
1242 // We need to handle f128 SELECT_CC with integer result type.
1243 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1244 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1245 }
1246
1247 if (Subtarget.hasP9Altivec()) {
1248 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1249 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1250
1251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
1252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1254 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal);
1255 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1256 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1257 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1258 }
1259
1260 if (Subtarget.isISA3_1())
1261 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1262 }
1263
1264 if (Subtarget.pairedVectorMemops()) {
1265 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1266 setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1267 setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1268 }
1269 if (Subtarget.hasMMA()) {
1270 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1271 setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1272 setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1273 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1274 }
1275
1276 if (Subtarget.has64BitSupport())
1277 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1278
1279 if (Subtarget.isISA3_1())
1280 setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1281
1282 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1283
1284 if (!isPPC64) {
1285 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
1286 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1287 }
1288
1289 if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics())
1290 setMaxAtomicSizeInBitsSupported(128);
1291
1292 setBooleanContents(ZeroOrOneBooleanContent);
1293
1294 if (Subtarget.hasAltivec()) {
1295 // Altivec instructions set fields to all zeros or all ones.
1296 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1297 }
1298
1299 if (!isPPC64) {
1300 // These libcalls are not available in 32-bit.
1301 setLibcallName(RTLIB::SHL_I128, nullptr);
1302 setLibcallName(RTLIB::SRL_I128, nullptr);
1303 setLibcallName(RTLIB::SRA_I128, nullptr);
1304 }
1305
1306 if (!isPPC64)
1307 setMaxAtomicSizeInBitsSupported(32);
1308
1309 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1310
1311 // We have target-specific dag combine patterns for the following nodes:
1312 setTargetDAGCombine(ISD::ADD);
1313 setTargetDAGCombine(ISD::SHL);
1314 setTargetDAGCombine(ISD::SRA);
1315 setTargetDAGCombine(ISD::SRL);
1316 setTargetDAGCombine(ISD::MUL);
1317 setTargetDAGCombine(ISD::FMA);
1318 setTargetDAGCombine(ISD::SINT_TO_FP);
1319 setTargetDAGCombine(ISD::BUILD_VECTOR);
1320 if (Subtarget.hasFPCVT())
1321 setTargetDAGCombine(ISD::UINT_TO_FP);
1322 setTargetDAGCombine(ISD::LOAD);
1323 setTargetDAGCombine(ISD::STORE);
1324 setTargetDAGCombine(ISD::BR_CC);
1325 if (Subtarget.useCRBits())
1326 setTargetDAGCombine(ISD::BRCOND);
1327 setTargetDAGCombine(ISD::BSWAP);
1328 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1329 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1330 setTargetDAGCombine(ISD::INTRINSIC_VOID);
1331
1332 setTargetDAGCombine(ISD::SIGN_EXTEND);
1333 setTargetDAGCombine(ISD::ZERO_EXTEND);
1334 setTargetDAGCombine(ISD::ANY_EXTEND);
1335
1336 setTargetDAGCombine(ISD::TRUNCATE);
1337 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1338
1339
1340 if (Subtarget.useCRBits()) {
1341 setTargetDAGCombine(ISD::TRUNCATE);
1342 setTargetDAGCombine(ISD::SETCC);
1343 setTargetDAGCombine(ISD::SELECT_CC);
1344 }
1345
1346 if (Subtarget.hasP9Altivec()) {
1347 setTargetDAGCombine(ISD::ABS);
1348 setTargetDAGCombine(ISD::VSELECT);
1349 }
1350
1351 setLibcallName(RTLIB::LOG_F128, "logf128");
1352 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1353 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1354 setLibcallName(RTLIB::EXP_F128, "expf128");
1355 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1356 setLibcallName(RTLIB::SIN_F128, "sinf128");
1357 setLibcallName(RTLIB::COS_F128, "cosf128");
1358 setLibcallName(RTLIB::POW_F128, "powf128");
1359 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1360 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1361 setLibcallName(RTLIB::REM_F128, "fmodf128");
1362 setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1363 setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1364 setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1365 setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1366 setLibcallName(RTLIB::ROUND_F128, "roundf128");
1367 setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1368 setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1369 setLibcallName(RTLIB::RINT_F128, "rintf128");
1370 setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1371 setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1372 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1373 setLibcallName(RTLIB::FMA_F128, "fmaf128");
1374
1375 // With 32 condition bits, we don't need to sink (and duplicate) compares
1376 // aggressively in CodeGenPrep.
1377 if (Subtarget.useCRBits()) {
1378 setHasMultipleConditionRegisters();
1379 setJumpIsExpensive();
1380 }
1381
1382 setMinFunctionAlignment(Align(4));
1383
1384 switch (Subtarget.getCPUDirective()) {
1385 default: break;
1386 case PPC::DIR_970:
1387 case PPC::DIR_A2:
1388 case PPC::DIR_E500:
1389 case PPC::DIR_E500mc:
1390 case PPC::DIR_E5500:
1391 case PPC::DIR_PWR4:
1392 case PPC::DIR_PWR5:
1393 case PPC::DIR_PWR5X:
1394 case PPC::DIR_PWR6:
1395 case PPC::DIR_PWR6X:
1396 case PPC::DIR_PWR7:
1397 case PPC::DIR_PWR8:
1398 case PPC::DIR_PWR9:
1399 case PPC::DIR_PWR10:
1400 case PPC::DIR_PWR_FUTURE:
1401 setPrefLoopAlignment(Align(16));
1402 setPrefFunctionAlignment(Align(16));
1403 break;
1404 }
1405
1406 if (Subtarget.enableMachineScheduler())
1407 setSchedulingPreference(Sched::Source);
1408 else
1409 setSchedulingPreference(Sched::Hybrid);
1410
1411 computeRegisterProperties(STI.getRegisterInfo());
1412
1413 // The Freescale cores do better with aggressive inlining of memcpy and
1414 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1415 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1416 Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1417 MaxStoresPerMemset = 32;
1418 MaxStoresPerMemsetOptSize = 16;
1419 MaxStoresPerMemcpy = 32;
1420 MaxStoresPerMemcpyOptSize = 8;
1421 MaxStoresPerMemmove = 32;
1422 MaxStoresPerMemmoveOptSize = 8;
1423 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1424 // The A2 also benefits from (very) aggressive inlining of memcpy and
1425 // friends. The overhead of a the function call, even when warm, can be
1426 // over one hundred cycles.
1427 MaxStoresPerMemset = 128;
1428 MaxStoresPerMemcpy = 128;
1429 MaxStoresPerMemmove = 128;
1430 MaxLoadsPerMemcmp = 128;
1431 } else {
1432 MaxLoadsPerMemcmp = 8;
1433 MaxLoadsPerMemcmpOptSize = 4;
1434 }
1435
1436 IsStrictFPEnabled = true;
1437
1438 // Let the subtarget (CPU) decide if a predictable select is more expensive
1439 // than the corresponding branch. This information is used in CGP to decide
1440 // when to convert selects into branches.
1441 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1442}
1443
1444// *********************************** NOTE ************************************
1445// For selecting load and store instructions, the addressing modes are defined
1446// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1447// patterns to match the load the store instructions.
1448//
1449// The TD definitions for the addressing modes correspond to their respective
1450// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1451// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1452// address mode flags of a particular node. Afterwards, the computed address
1453// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1454// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1455// accordingly, based on the preferred addressing mode.
1456//
1457// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1458// MemOpFlags contains all the possible flags that can be used to compute the
1459// optimal addressing mode for load and store instructions.
1460// AddrMode contains all the possible load and store addressing modes available
1461// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1462//
1463// When adding new load and store instructions, it is possible that new address
1464// flags may need to be added into MemOpFlags, and a new addressing mode will
1465// need to be added to AddrMode. An entry of the new addressing mode (consisting
1466// of the minimal and main distinguishing address flags for the new load/store
1467// instructions) will need to be added into initializeAddrModeMap() below.
1468// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1469// need to be updated to account for selecting the optimal addressing mode.
1470// *****************************************************************************
1471/// Initialize the map that relates the different addressing modes of the load
1472/// and store instructions to a set of flags. This ensures the load/store
1473/// instruction is correctly matched during instruction selection.
1474void PPCTargetLowering::initializeAddrModeMap() {
1475 AddrModesMap[PPC::AM_DForm] = {
1476 // LWZ, STW
1477 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1478 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1479 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1480 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1481 // LBZ, LHZ, STB, STH
1482 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1483 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1484 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1485 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1486 // LHA
1487 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1488 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1489 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1490 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1491 // LFS, LFD, STFS, STFD
1492 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1493 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1494 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1495 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1496 };
1497 AddrModesMap[PPC::AM_DSForm] = {
1498 // LWA
1499 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1500 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1501 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1502 // LD, STD
1503 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1504 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1505 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1506 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1507 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1508 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1509 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1510 };
1511 AddrModesMap[PPC::AM_DQForm] = {
1512 // LXV, STXV
1513 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1514 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1515 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1516 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1517 PPC::MOF_NotAddNorCst | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1518 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector256 | PPC::MOF_SubtargetP10,
1519 };
1520}
1521
1522/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1523/// the desired ByVal argument alignment.
1524static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1525 if (MaxAlign == MaxMaxAlign)
1526 return;
1527 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1528 if (MaxMaxAlign >= 32 &&
1529 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1530 MaxAlign = Align(32);
1531 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1532 MaxAlign < 16)
1533 MaxAlign = Align(16);
1534 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1535 Align EltAlign;
1536 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1537 if (EltAlign > MaxAlign)
1538 MaxAlign = EltAlign;
1539 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1540 for (auto *EltTy : STy->elements()) {
1541 Align EltAlign;
1542 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1543 if (EltAlign > MaxAlign)
1544 MaxAlign = EltAlign;
1545 if (MaxAlign == MaxMaxAlign)
1546 break;
1547 }
1548 }
1549}
1550
1551/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1552/// function arguments in the caller parameter area.
1553unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1554 const DataLayout &DL) const {
1555 // 16byte and wider vectors are passed on 16byte boundary.
1556 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1557 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1558 if (Subtarget.hasAltivec())
1559 getMaxByValAlign(Ty, Alignment, Align(16));
1560 return Alignment.value();
1561}
1562
1563bool PPCTargetLowering::useSoftFloat() const {
1564 return Subtarget.useSoftFloat();
1565}
1566
1567bool PPCTargetLowering::hasSPE() const {
1568 return Subtarget.hasSPE();
1569}
1570
1571bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1572 return VT.isScalarInteger();
1573}
1574
1575const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1576 switch ((PPCISD::NodeType)Opcode) {
1577 case PPCISD::FIRST_NUMBER: break;
1578 case PPCISD::FSEL: return "PPCISD::FSEL";
1579 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
1580 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
1581 case PPCISD::FCFID: return "PPCISD::FCFID";
1582 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1583 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1584 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1585 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1586 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1587 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1588 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1589 case PPCISD::FP_TO_UINT_IN_VSR:
1590 return "PPCISD::FP_TO_UINT_IN_VSR,";
1591 case PPCISD::FP_TO_SINT_IN_VSR:
1592 return "PPCISD::FP_TO_SINT_IN_VSR";
1593 case PPCISD::FRE: return "PPCISD::FRE";
1594 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1595 case PPCISD::FTSQRT:
1596 return "PPCISD::FTSQRT";
1597 case PPCISD::FSQRT:
1598 return "PPCISD::FSQRT";
1599 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1600 case PPCISD::VPERM: return "PPCISD::VPERM";
1601 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1602 case PPCISD::XXSPLTI_SP_TO_DP:
1603 return "PPCISD::XXSPLTI_SP_TO_DP";
1604 case PPCISD::XXSPLTI32DX:
1605 return "PPCISD::XXSPLTI32DX";
1606 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1607 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1608 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1609 case PPCISD::CMPB: return "PPCISD::CMPB";
1610 case PPCISD::Hi: return "PPCISD::Hi";
1611 case PPCISD::Lo: return "PPCISD::Lo";
1612 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1613 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1614 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1615 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1616 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1617 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1618 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1619 case PPCISD::SRL: return "PPCISD::SRL";
1620 case PPCISD::SRA: return "PPCISD::SRA";
1621 case PPCISD::SHL: return "PPCISD::SHL";
1622 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1623 case PPCISD::CALL: return "PPCISD::CALL";
1624 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1625 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1626 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1627 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1628 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1629 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1630 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1631 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1632 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1633 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1634 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1635 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1636 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1637 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1638 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1639 case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1640 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1641 case PPCISD::ANDI_rec_1_EQ_BIT:
1642 return "PPCISD::ANDI_rec_1_EQ_BIT";
1643 case PPCISD::ANDI_rec_1_GT_BIT:
1644 return "PPCISD::ANDI_rec_1_GT_BIT";
1645 case PPCISD::VCMP: return "PPCISD::VCMP";
1646 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1647 case PPCISD::LBRX: return "PPCISD::LBRX";
1648 case PPCISD::STBRX: return "PPCISD::STBRX";
1649 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1650 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1651 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1652 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1653 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1654 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1655 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1656 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1657 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1658 case PPCISD::ST_VSR_SCAL_INT:
1659 return "PPCISD::ST_VSR_SCAL_INT";
1660 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1661 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1662 case PPCISD::BDZ: return "PPCISD::BDZ";
1663 case PPCISD::MFFS: return "PPCISD::MFFS";
1664 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1665 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1666 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1667 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1668 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1669 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1670 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1671 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1672 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1673 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1674 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1675 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1676 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1677 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1678 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1679 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1680 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1681 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1682 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1683 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1684 case PPCISD::PADDI_DTPREL:
1685 return "PPCISD::PADDI_DTPREL";
1686 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1687 case PPCISD::SC: return "PPCISD::SC";
1688 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1689 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1690 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1691 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1692 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1693 case PPCISD::VABSD: return "PPCISD::VABSD";
1694 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1695 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1696 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1697 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1698 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1699 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1700 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1701 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1702 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1703 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1704 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1705 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1706 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1707 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1708 case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1709 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1710 case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1711 case PPCISD::STRICT_FADDRTZ:
1712 return "PPCISD::STRICT_FADDRTZ";
1713 case PPCISD::STRICT_FCTIDZ:
1714 return "PPCISD::STRICT_FCTIDZ";
1715 case PPCISD::STRICT_FCTIWZ:
1716 return "PPCISD::STRICT_FCTIWZ";
1717 case PPCISD::STRICT_FCTIDUZ:
1718 return "PPCISD::STRICT_FCTIDUZ";
1719 case PPCISD::STRICT_FCTIWUZ:
1720 return "PPCISD::STRICT_FCTIWUZ";
1721 case PPCISD::STRICT_FCFID:
1722 return "PPCISD::STRICT_FCFID";
1723 case PPCISD::STRICT_FCFIDU:
1724 return "PPCISD::STRICT_FCFIDU";
1725 case PPCISD::STRICT_FCFIDS:
1726 return "PPCISD::STRICT_FCFIDS";
1727 case PPCISD::STRICT_FCFIDUS:
1728 return "PPCISD::STRICT_FCFIDUS";
1729 case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1730 }
1731 return nullptr;
1732}
1733
1734EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1735 EVT VT) const {
1736 if (!VT.isVector())
1737 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1738
1739 return VT.changeVectorElementTypeToInteger();
1740}
1741
1742bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1743 assert(VT.isFloatingPoint() && "Non-floating-point FMA?")(static_cast <bool> (VT.isFloatingPoint() && "Non-floating-point FMA?"
) ? void (0) : __assert_fail ("VT.isFloatingPoint() && \"Non-floating-point FMA?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1743, __extension__ __PRETTY_FUNCTION__))
;
1744 return true;
1745}
1746
1747//===----------------------------------------------------------------------===//
1748// Node matching predicates, for use by the tblgen matching code.
1749//===----------------------------------------------------------------------===//
1750
1751/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1752static bool isFloatingPointZero(SDValue Op) {
1753 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1754 return CFP->getValueAPF().isZero();
1755 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1756 // Maybe this has already been legalized into the constant pool?
1757 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1758 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1759 return CFP->getValueAPF().isZero();
1760 }
1761 return false;
1762}
1763
1764/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1765/// true if Op is undef or if it matches the specified value.
1766static bool isConstantOrUndef(int Op, int Val) {
1767 return Op < 0 || Op == Val;
1768}
1769
1770/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1771/// VPKUHUM instruction.
1772/// The ShuffleKind distinguishes between big-endian operations with
1773/// two different inputs (0), either-endian operations with two identical
1774/// inputs (1), and little-endian operations with two different inputs (2).
1775/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1776bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1777 SelectionDAG &DAG) {
1778 bool IsLE = DAG.getDataLayout().isLittleEndian();
1779 if (ShuffleKind == 0) {
1780 if (IsLE)
1781 return false;
1782 for (unsigned i = 0; i != 16; ++i)
1783 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1784 return false;
1785 } else if (ShuffleKind == 2) {
1786 if (!IsLE)
1787 return false;
1788 for (unsigned i = 0; i != 16; ++i)
1789 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1790 return false;
1791 } else if (ShuffleKind == 1) {
1792 unsigned j = IsLE ? 0 : 1;
1793 for (unsigned i = 0; i != 8; ++i)
1794 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1795 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1796 return false;
1797 }
1798 return true;
1799}
1800
1801/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1802/// VPKUWUM instruction.
1803/// The ShuffleKind distinguishes between big-endian operations with
1804/// two different inputs (0), either-endian operations with two identical
1805/// inputs (1), and little-endian operations with two different inputs (2).
1806/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1807bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1808 SelectionDAG &DAG) {
1809 bool IsLE = DAG.getDataLayout().isLittleEndian();
1810 if (ShuffleKind == 0) {
1811 if (IsLE)
1812 return false;
1813 for (unsigned i = 0; i != 16; i += 2)
1814 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1815 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1816 return false;
1817 } else if (ShuffleKind == 2) {
1818 if (!IsLE)
1819 return false;
1820 for (unsigned i = 0; i != 16; i += 2)
1821 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1822 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1823 return false;
1824 } else if (ShuffleKind == 1) {
1825 unsigned j = IsLE ? 0 : 2;
1826 for (unsigned i = 0; i != 8; i += 2)
1827 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1828 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1829 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1830 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1831 return false;
1832 }
1833 return true;
1834}
1835
1836/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1837/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1838/// current subtarget.
1839///
1840/// The ShuffleKind distinguishes between big-endian operations with
1841/// two different inputs (0), either-endian operations with two identical
1842/// inputs (1), and little-endian operations with two different inputs (2).
1843/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1844bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1845 SelectionDAG &DAG) {
1846 const PPCSubtarget& Subtarget =
1847 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1848 if (!Subtarget.hasP8Vector())
1849 return false;
1850
1851 bool IsLE = DAG.getDataLayout().isLittleEndian();
1852 if (ShuffleKind == 0) {
1853 if (IsLE)
1854 return false;
1855 for (unsigned i = 0; i != 16; i += 4)
1856 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1857 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1858 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1859 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1860 return false;
1861 } else if (ShuffleKind == 2) {
1862 if (!IsLE)
1863 return false;
1864 for (unsigned i = 0; i != 16; i += 4)
1865 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1866 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1867 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1868 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1869 return false;
1870 } else if (ShuffleKind == 1) {
1871 unsigned j = IsLE ? 0 : 4;
1872 for (unsigned i = 0; i != 8; i += 4)
1873 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1874 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1875 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1876 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1877 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1878 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1879 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1880 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1881 return false;
1882 }
1883 return true;
1884}
1885
1886/// isVMerge - Common function, used to match vmrg* shuffles.
1887///
1888static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1889 unsigned LHSStart, unsigned RHSStart) {
1890 if (N->getValueType(0) != MVT::v16i8)
1891 return false;
1892 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&(static_cast <bool> ((UnitSize == 1 || UnitSize == 2 ||
UnitSize == 4) && "Unsupported merge size!") ? void (
0) : __assert_fail ("(UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && \"Unsupported merge size!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1893, __extension__ __PRETTY_FUNCTION__))
1893 "Unsupported merge size!")(static_cast <bool> ((UnitSize == 1 || UnitSize == 2 ||
UnitSize == 4) && "Unsupported merge size!") ? void (
0) : __assert_fail ("(UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && \"Unsupported merge size!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 1893, __extension__ __PRETTY_FUNCTION__))
;
1894
1895 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1896 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1897 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1898 LHSStart+j+i*UnitSize) ||
1899 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1900 RHSStart+j+i*UnitSize))
1901 return false;
1902 }
1903 return true;
1904}
1905
1906/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1907/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1908/// The ShuffleKind distinguishes between big-endian merges with two
1909/// different inputs (0), either-endian merges with two identical inputs (1),
1910/// and little-endian merges with two different inputs (2). For the latter,
1911/// the input operands are swapped (see PPCInstrAltivec.td).
1912bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1913 unsigned ShuffleKind, SelectionDAG &DAG) {
1914 if (DAG.getDataLayout().isLittleEndian()) {
1915 if (ShuffleKind == 1) // unary
1916 return isVMerge(N, UnitSize, 0, 0);
1917 else if (ShuffleKind == 2) // swapped
1918 return isVMerge(N, UnitSize, 0, 16);
1919 else
1920 return false;
1921 } else {
1922 if (ShuffleKind == 1) // unary
1923 return isVMerge(N, UnitSize, 8, 8);
1924 else if (ShuffleKind == 0) // normal
1925 return isVMerge(N, UnitSize, 8, 24);
1926 else
1927 return false;
1928 }
1929}
1930
1931/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1932/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1933/// The ShuffleKind distinguishes between big-endian merges with two
1934/// different inputs (0), either-endian merges with two identical inputs (1),
1935/// and little-endian merges with two different inputs (2). For the latter,
1936/// the input operands are swapped (see PPCInstrAltivec.td).
1937bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1938 unsigned ShuffleKind, SelectionDAG &DAG) {
1939 if (DAG.getDataLayout().isLittleEndian()) {
1940 if (ShuffleKind == 1) // unary
1941 return isVMerge(N, UnitSize, 8, 8);
1942 else if (ShuffleKind == 2) // swapped
1943 return isVMerge(N, UnitSize, 8, 24);
1944 else
1945 return false;
1946 } else {
1947 if (ShuffleKind == 1) // unary
1948 return isVMerge(N, UnitSize, 0, 0);
1949 else if (ShuffleKind == 0) // normal
1950 return isVMerge(N, UnitSize, 0, 16);
1951 else
1952 return false;
1953 }
1954}
1955
1956/**
1957 * Common function used to match vmrgew and vmrgow shuffles
1958 *
1959 * The indexOffset determines whether to look for even or odd words in
1960 * the shuffle mask. This is based on the of the endianness of the target
1961 * machine.
1962 * - Little Endian:
1963 * - Use offset of 0 to check for odd elements
1964 * - Use offset of 4 to check for even elements
1965 * - Big Endian:
1966 * - Use offset of 0 to check for even elements
1967 * - Use offset of 4 to check for odd elements
1968 * A detailed description of the vector element ordering for little endian and
1969 * big endian can be found at
1970 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1971 * Targeting your applications - what little endian and big endian IBM XL C/C++
1972 * compiler differences mean to you
1973 *
1974 * The mask to the shuffle vector instruction specifies the indices of the
1975 * elements from the two input vectors to place in the result. The elements are
1976 * numbered in array-access order, starting with the first vector. These vectors
1977 * are always of type v16i8, thus each vector will contain 16 elements of size
1978 * 8. More info on the shuffle vector can be found in the
1979 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1980 * Language Reference.
1981 *
1982 * The RHSStartValue indicates whether the same input vectors are used (unary)
1983 * or two different input vectors are used, based on the following:
1984 * - If the instruction uses the same vector for both inputs, the range of the
1985 * indices will be 0 to 15. In this case, the RHSStart value passed should
1986 * be 0.
1987 * - If the instruction has two different vectors then the range of the
1988 * indices will be 0 to 31. In this case, the RHSStart value passed should
1989 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1990 * to 31 specify elements in the second vector).
1991 *
1992 * \param[in] N The shuffle vector SD Node to analyze
1993 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1994 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1995 * vector to the shuffle_vector instruction
1996 * \return true iff this shuffle vector represents an even or odd word merge
1997 */
1998static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1999 unsigned RHSStartValue) {
2000 if (N->getValueType(0) != MVT::v16i8)
2001 return false;
2002
2003 for (unsigned i = 0; i < 2; ++i)
2004 for (unsigned j = 0; j < 4; ++j)
2005 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2006 i*RHSStartValue+j+IndexOffset) ||
2007 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2008 i*RHSStartValue+j+IndexOffset+8))
2009 return false;
2010 return true;
2011}
2012
2013/**
2014 * Determine if the specified shuffle mask is suitable for the vmrgew or
2015 * vmrgow instructions.
2016 *
2017 * \param[in] N The shuffle vector SD Node to analyze
2018 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2019 * \param[in] ShuffleKind Identify the type of merge:
2020 * - 0 = big-endian merge with two different inputs;
2021 * - 1 = either-endian merge with two identical inputs;
2022 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2023 * little-endian merges).
2024 * \param[in] DAG The current SelectionDAG
2025 * \return true iff this shuffle mask
2026 */
2027bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2028 unsigned ShuffleKind, SelectionDAG &DAG) {
2029 if (DAG.getDataLayout().isLittleEndian()) {
2030 unsigned indexOffset = CheckEven ? 4 : 0;
2031 if (ShuffleKind == 1) // Unary
2032 return isVMerge(N, indexOffset, 0);
2033 else if (ShuffleKind == 2) // swapped
2034 return isVMerge(N, indexOffset, 16);
2035 else
2036 return false;
2037 }
2038 else {
2039 unsigned indexOffset = CheckEven ? 0 : 4;
2040 if (ShuffleKind == 1) // Unary
2041 return isVMerge(N, indexOffset, 0);
2042 else if (ShuffleKind == 0) // Normal
2043 return isVMerge(N, indexOffset, 16);
2044 else
2045 return false;
2046 }
2047 return false;
2048}
2049
2050/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2051/// amount, otherwise return -1.
2052/// The ShuffleKind distinguishes between big-endian operations with two
2053/// different inputs (0), either-endian operations with two identical inputs
2054/// (1), and little-endian operations with two different inputs (2). For the
2055/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2056int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2057 SelectionDAG &DAG) {
2058 if (N->getValueType(0) != MVT::v16i8)
2059 return -1;
2060
2061 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2062
2063 // Find the first non-undef value in the shuffle mask.
2064 unsigned i;
2065 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2066 /*search*/;
2067
2068 if (i == 16) return -1; // all undef.
2069
2070 // Otherwise, check to see if the rest of the elements are consecutively
2071 // numbered from this value.
2072 unsigned ShiftAmt = SVOp->getMaskElt(i);
2073 if (ShiftAmt < i) return -1;
2074
2075 ShiftAmt -= i;
2076 bool isLE = DAG.getDataLayout().isLittleEndian();
2077
2078 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2079 // Check the rest of the elements to see if they are consecutive.
2080 for (++i; i != 16; ++i)
2081 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2082 return -1;
2083 } else if (ShuffleKind == 1) {
2084 // Check the rest of the elements to see if they are consecutive.
2085 for (++i; i != 16; ++i)
2086 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2087 return -1;
2088 } else
2089 return -1;
2090
2091 if (isLE)
2092 ShiftAmt = 16 - ShiftAmt;
2093
2094 return ShiftAmt;
2095}
2096
2097/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2098/// specifies a splat of a single element that is suitable for input to
2099/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2100bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2101 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&(static_cast <bool> (N->getValueType(0) == MVT::v16i8
&& isPowerOf2_32(EltSize) && EltSize <= 8
&& "Can only handle 1,2,4,8 byte element sizes") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
2102 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes")(static_cast <bool> (N->getValueType(0) == MVT::v16i8
&& isPowerOf2_32(EltSize) && EltSize <= 8
&& "Can only handle 1,2,4,8 byte element sizes") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && EltSize <= 8 && \"Can only handle 1,2,4,8 byte element sizes\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2102, __extension__ __PRETTY_FUNCTION__))
;
2103
2104 // The consecutive indices need to specify an element, not part of two
2105 // different elements. So abandon ship early if this isn't the case.
2106 if (N->getMaskElt(0) % EltSize != 0)
2107 return false;
2108
2109 // This is a splat operation if each element of the permute is the same, and
2110 // if the value doesn't reference the second vector.
2111 unsigned ElementBase = N->getMaskElt(0);
2112
2113 // FIXME: Handle UNDEF elements too!
2114 if (ElementBase >= 16)
2115 return false;
2116
2117 // Check that the indices are consecutive, in the case of a multi-byte element
2118 // splatted with a v16i8 mask.
2119 for (unsigned i = 1; i != EltSize; ++i)
2120 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2121 return false;
2122
2123 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2124 if (N->getMaskElt(i) < 0) continue;
2125 for (unsigned j = 0; j != EltSize; ++j)
2126 if (N->getMaskElt(i+j) != N->getMaskElt(j))
2127 return false;
2128 }
2129 return true;
2130}
2131
2132/// Check that the mask is shuffling N byte elements. Within each N byte
2133/// element of the mask, the indices could be either in increasing or
2134/// decreasing order as long as they are consecutive.
2135/// \param[in] N the shuffle vector SD Node to analyze
2136/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2137/// Word/DoubleWord/QuadWord).
2138/// \param[in] StepLen the delta indices number among the N byte element, if
2139/// the mask is in increasing/decreasing order then it is 1/-1.
2140/// \return true iff the mask is shuffling N byte elements.
2141static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2142 int StepLen) {
2143 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&(static_cast <bool> ((Width == 2 || Width == 4 || Width
== 8 || Width == 16) && "Unexpected element width.")
? void (0) : __assert_fail ("(Width == 2 || Width == 4 || Width == 8 || Width == 16) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2144, __extension__ __PRETTY_FUNCTION__))
2144 "Unexpected element width.")(static_cast <bool> ((Width == 2 || Width == 4 || Width
== 8 || Width == 16) && "Unexpected element width.")
? void (0) : __assert_fail ("(Width == 2 || Width == 4 || Width == 8 || Width == 16) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2144, __extension__ __PRETTY_FUNCTION__))
;
2145 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.")(static_cast <bool> ((StepLen == 1 || StepLen == -1) &&
"Unexpected element width.") ? void (0) : __assert_fail ("(StepLen == 1 || StepLen == -1) && \"Unexpected element width.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2145, __extension__ __PRETTY_FUNCTION__))
;
2146
2147 unsigned NumOfElem = 16 / Width;
2148 unsigned MaskVal[16]; // Width is never greater than 16
2149 for (unsigned i = 0; i < NumOfElem; ++i) {
2150 MaskVal[0] = N->getMaskElt(i * Width);
2151 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2152 return false;
2153 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2154 return false;
2155 }
2156
2157 for (unsigned int j = 1; j < Width; ++j) {
2158 MaskVal[j] = N->getMaskElt(i * Width + j);
2159 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2160 return false;
2161 }
2162 }
2163 }
2164
2165 return true;
2166}
2167
2168bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2169 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2170 if (!isNByteElemShuffleMask(N, 4, 1))
2171 return false;
2172
2173 // Now we look at mask elements 0,4,8,12
2174 unsigned M0 = N->getMaskElt(0) / 4;
2175 unsigned M1 = N->getMaskElt(4) / 4;
2176 unsigned M2 = N->getMaskElt(8) / 4;
2177 unsigned M3 = N->getMaskElt(12) / 4;
2178 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2179 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2180
2181 // Below, let H and L be arbitrary elements of the shuffle mask
2182 // where H is in the range [4,7] and L is in the range [0,3].
2183 // H, 1, 2, 3 or L, 5, 6, 7
2184 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2185 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2186 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2187 InsertAtByte = IsLE ? 12 : 0;
2188 Swap = M0 < 4;
2189 return true;
2190 }
2191 // 0, H, 2, 3 or 4, L, 6, 7
2192 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2193 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2194 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2195 InsertAtByte = IsLE ? 8 : 4;
2196 Swap = M1 < 4;
2197 return true;
2198 }
2199 // 0, 1, H, 3 or 4, 5, L, 7
2200 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2201 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2202 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2203 InsertAtByte = IsLE ? 4 : 8;
2204 Swap = M2 < 4;
2205 return true;
2206 }
2207 // 0, 1, 2, H or 4, 5, 6, L
2208 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2209 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2210 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2211 InsertAtByte = IsLE ? 0 : 12;
2212 Swap = M3 < 4;
2213 return true;
2214 }
2215
2216 // If both vector operands for the shuffle are the same vector, the mask will
2217 // contain only elements from the first one and the second one will be undef.
2218 if (N->getOperand(1).isUndef()) {
2219 ShiftElts = 0;
2220 Swap = true;
2221 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2222 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2223 InsertAtByte = IsLE ? 12 : 0;
2224 return true;
2225 }
2226 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2227 InsertAtByte = IsLE ? 8 : 4;
2228 return true;
2229 }
2230 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2231 InsertAtByte = IsLE ? 4 : 8;
2232 return true;
2233 }
2234 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2235 InsertAtByte = IsLE ? 0 : 12;
2236 return true;
2237 }
2238 }
2239
2240 return false;
2241}
2242
2243bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2244 bool &Swap, bool IsLE) {
2245 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")(static_cast <bool> (N->getValueType(0) == MVT::v16i8
&& "Shuffle vector expects v16i8") ? void (0) : __assert_fail
("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 // Ensure each byte index of the word is consecutive.
2247 if (!isNByteElemShuffleMask(N, 4, 1))
2248 return false;
2249
2250 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2251 unsigned M0 = N->getMaskElt(0) / 4;
2252 unsigned M1 = N->getMaskElt(4) / 4;
2253 unsigned M2 = N->getMaskElt(8) / 4;
2254 unsigned M3 = N->getMaskElt(12) / 4;
2255
2256 // If both vector operands for the shuffle are the same vector, the mask will
2257 // contain only elements from the first one and the second one will be undef.
2258 if (N->getOperand(1).isUndef()) {
2259 assert(M0 < 4 && "Indexing into an undef vector?")(static_cast <bool> (M0 < 4 && "Indexing into an undef vector?"
) ? void (0) : __assert_fail ("M0 < 4 && \"Indexing into an undef vector?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2259, __extension__ __PRETTY_FUNCTION__))
;
2260 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2261 return false;
2262
2263 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2264 Swap = false;
2265 return true;
2266 }
2267
2268 // Ensure each word index of the ShuffleVector Mask is consecutive.
2269 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2270 return false;
2271
2272 if (IsLE) {
2273 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2274 // Input vectors don't need to be swapped if the leading element
2275 // of the result is one of the 3 left elements of the second vector
2276 // (or if there is no shift to be done at all).
2277 Swap = false;
2278 ShiftElts = (8 - M0) % 8;
2279 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2280 // Input vectors need to be swapped if the leading element
2281 // of the result is one of the 3 left elements of the first vector
2282 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2283 Swap = true;
2284 ShiftElts = (4 - M0) % 4;
2285 }
2286
2287 return true;
2288 } else { // BE
2289 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2290 // Input vectors don't need to be swapped if the leading element
2291 // of the result is one of the 4 elements of the first vector.
2292 Swap = false;
2293 ShiftElts = M0;
2294 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2295 // Input vectors need to be swapped if the leading element
2296 // of the result is one of the 4 elements of the right vector.
2297 Swap = true;
2298 ShiftElts = M0 - 4;
2299 }
2300
2301 return true;
2302 }
2303}
2304
2305bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2306 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")(static_cast <bool> (N->getValueType(0) == MVT::v16i8
&& "Shuffle vector expects v16i8") ? void (0) : __assert_fail
("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2306, __extension__ __PRETTY_FUNCTION__))
;
2307
2308 if (!isNByteElemShuffleMask(N, Width, -1))
2309 return false;
2310
2311 for (int i = 0; i < 16; i += Width)
2312 if (N->getMaskElt(i) != i + Width - 1)
2313 return false;
2314
2315 return true;
2316}
2317
2318bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2319 return isXXBRShuffleMaskHelper(N, 2);
2320}
2321
2322bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2323 return isXXBRShuffleMaskHelper(N, 4);
2324}
2325
2326bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2327 return isXXBRShuffleMaskHelper(N, 8);
2328}
2329
2330bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2331 return isXXBRShuffleMaskHelper(N, 16);
2332}
2333
2334/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2335/// if the inputs to the instruction should be swapped and set \p DM to the
2336/// value for the immediate.
2337/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2338/// AND element 0 of the result comes from the first input (LE) or second input
2339/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2340/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2341/// mask.
2342bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2343 bool &Swap, bool IsLE) {
2344 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8")(static_cast <bool> (N->getValueType(0) == MVT::v16i8
&& "Shuffle vector expects v16i8") ? void (0) : __assert_fail
("N->getValueType(0) == MVT::v16i8 && \"Shuffle vector expects v16i8\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2344, __extension__ __PRETTY_FUNCTION__))
;
2345
2346 // Ensure each byte index of the double word is consecutive.
2347 if (!isNByteElemShuffleMask(N, 8, 1))
2348 return false;
2349
2350 unsigned M0 = N->getMaskElt(0) / 8;
2351 unsigned M1 = N->getMaskElt(8) / 8;
2352 assert(((M0 | M1) < 4) && "A mask element out of bounds?")(static_cast <bool> (((M0 | M1) < 4) && "A mask element out of bounds?"
) ? void (0) : __assert_fail ("((M0 | M1) < 4) && \"A mask element out of bounds?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2352, __extension__ __PRETTY_FUNCTION__))
;
2353
2354 // If both vector operands for the shuffle are the same vector, the mask will
2355 // contain only elements from the first one and the second one will be undef.
2356 if (N->getOperand(1).isUndef()) {
2357 if ((M0 | M1) < 2) {
2358 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2359 Swap = false;
2360 return true;
2361 } else
2362 return false;
2363 }
2364
2365 if (IsLE) {
2366 if (M0 > 1 && M1 < 2) {
2367 Swap = false;
2368 } else if (M0 < 2 && M1 > 1) {
2369 M0 = (M0 + 2) % 4;
2370 M1 = (M1 + 2) % 4;
2371 Swap = true;
2372 } else
2373 return false;
2374
2375 // Note: if control flow comes here that means Swap is already set above
2376 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2377 return true;
2378 } else { // BE
2379 if (M0 < 2 && M1 > 1) {
2380 Swap = false;
2381 } else if (M0 > 1 && M1 < 2) {
2382 M0 = (M0 + 2) % 4;
2383 M1 = (M1 + 2) % 4;
2384 Swap = true;
2385 } else
2386 return false;
2387
2388 // Note: if control flow comes here that means Swap is already set above
2389 DM = (M0 << 1) + (M1 & 1);
2390 return true;
2391 }
2392}
2393
2394
2395/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2396/// appropriate for PPC mnemonics (which have a big endian bias - namely
2397/// elements are counted from the left of the vector register).
2398unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2399 SelectionDAG &DAG) {
2400 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2401 assert(isSplatShuffleMask(SVOp, EltSize))(static_cast <bool> (isSplatShuffleMask(SVOp, EltSize))
? void (0) : __assert_fail ("isSplatShuffleMask(SVOp, EltSize)"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2401, __extension__ __PRETTY_FUNCTION__))
;
2402 if (DAG.getDataLayout().isLittleEndian())
2403 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2404 else
2405 return SVOp->getMaskElt(0) / EltSize;
2406}
2407
2408/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2409/// by using a vspltis[bhw] instruction of the specified element size, return
2410/// the constant being splatted. The ByteSize field indicates the number of
2411/// bytes of each element [124] -> [bhw].
2412SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2413 SDValue OpVal(nullptr, 0);
2414
2415 // If ByteSize of the splat is bigger than the element size of the
2416 // build_vector, then we have a case where we are checking for a splat where
2417 // multiple elements of the buildvector are folded together into a single
2418 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2419 unsigned EltSize = 16/N->getNumOperands();
2420 if (EltSize < ByteSize) {
2421 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2422 SDValue UniquedVals[4];
2423 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?")(static_cast <bool> (Multiple > 1 && Multiple
<= 4 && "How can this happen?") ? void (0) : __assert_fail
("Multiple > 1 && Multiple <= 4 && \"How can this happen?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2423, __extension__ __PRETTY_FUNCTION__))
;
2424
2425 // See if all of the elements in the buildvector agree across.
2426 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2427 if (N->getOperand(i).isUndef()) continue;
2428 // If the element isn't a constant, bail fully out.
2429 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2430
2431 if (!UniquedVals[i&(Multiple-1)].getNode())
2432 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2433 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2434 return SDValue(); // no match.
2435 }
2436
2437 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2438 // either constant or undef values that are identical for each chunk. See
2439 // if these chunks can form into a larger vspltis*.
2440
2441 // Check to see if all of the leading entries are either 0 or -1. If
2442 // neither, then this won't fit into the immediate field.
2443 bool LeadingZero = true;
2444 bool LeadingOnes = true;
2445 for (unsigned i = 0; i != Multiple-1; ++i) {
2446 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2447
2448 LeadingZero &= isNullConstant(UniquedVals[i]);
2449 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2450 }
2451 // Finally, check the least significant entry.
2452 if (LeadingZero) {
2453 if (!UniquedVals[Multiple-1].getNode())
2454 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2455 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2456 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2457 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2458 }
2459 if (LeadingOnes) {
2460 if (!UniquedVals[Multiple-1].getNode())
2461 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2462 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2463 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2464 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2465 }
2466
2467 return SDValue();
2468 }
2469
2470 // Check to see if this buildvec has a single non-undef value in its elements.
2471 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2472 if (N->getOperand(i).isUndef()) continue;
2473 if (!OpVal.getNode())
2474 OpVal = N->getOperand(i);
2475 else if (OpVal != N->getOperand(i))
2476 return SDValue();
2477 }
2478
2479 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2480
2481 unsigned ValSizeInBytes = EltSize;
2482 uint64_t Value = 0;
2483 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2484 Value = CN->getZExtValue();
2485 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2486 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!")(static_cast <bool> (CN->getValueType(0) == MVT::f32
&& "Only one legal FP vector type!") ? void (0) : __assert_fail
("CN->getValueType(0) == MVT::f32 && \"Only one legal FP vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2486, __extension__ __PRETTY_FUNCTION__))
;
2487 Value = FloatToBits(CN->getValueAPF().convertToFloat());
2488 }
2489
2490 // If the splat value is larger than the element value, then we can never do
2491 // this splat. The only case that we could fit the replicated bits into our
2492 // immediate field for would be zero, and we prefer to use vxor for it.
2493 if (ValSizeInBytes < ByteSize) return SDValue();
2494
2495 // If the element value is larger than the splat value, check if it consists
2496 // of a repeated bit pattern of size ByteSize.
2497 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2498 return SDValue();
2499
2500 // Properly sign extend the value.
2501 int MaskVal = SignExtend32(Value, ByteSize * 8);
2502
2503 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2504 if (MaskVal == 0) return SDValue();
2505
2506 // Finally, if this value fits in a 5 bit sext field, return it
2507 if (SignExtend32<5>(MaskVal) == MaskVal)
2508 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2509 return SDValue();
2510}
2511
2512//===----------------------------------------------------------------------===//
2513// Addressing Mode Selection
2514//===----------------------------------------------------------------------===//
2515
2516/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2517/// or 64-bit immediate, and if the value can be accurately represented as a
2518/// sign extension from a 16-bit value. If so, this returns true and the
2519/// immediate.
2520bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2521 if (!isa<ConstantSDNode>(N))
2522 return false;
2523
2524 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2525 if (N->getValueType(0) == MVT::i32)
2526 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2527 else
2528 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2529}
2530bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2531 return isIntS16Immediate(Op.getNode(), Imm);
2532}
2533
2534/// Used when computing address flags for selecting loads and stores.
2535/// If we have an OR, check if the LHS and RHS are provably disjoint.
2536/// An OR of two provably disjoint values is equivalent to an ADD.
2537/// Most PPC load/store instructions compute the effective address as a sum,
2538/// so doing this conversion is useful.
2539static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2540 if (N.getOpcode() != ISD::OR)
2541 return false;
2542 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2543 if (!LHSKnown.Zero.getBoolValue())
2544 return false;
2545 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2546 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2547}
2548
2549/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2550/// be represented as an indexed [r+r] operation.
2551bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2552 SDValue &Index,
2553 SelectionDAG &DAG) const {
2554 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2555 UI != E; ++UI) {
2556 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2557 if (Memop->getMemoryVT() == MVT::f64) {
2558 Base = N.getOperand(0);
2559 Index = N.getOperand(1);
2560 return true;
2561 }
2562 }
2563 }
2564 return false;
2565}
2566
2567/// isIntS34Immediate - This method tests if value of node given can be
2568/// accurately represented as a sign extension from a 34-bit value. If so,
2569/// this returns true and the immediate.
2570bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2571 if (!isa<ConstantSDNode>(N))
2572 return false;
2573
2574 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2575 return isInt<34>(Imm);
2576}
2577bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2578 return isIntS34Immediate(Op.getNode(), Imm);
2579}
2580
2581/// SelectAddressRegReg - Given the specified addressed, check to see if it
2582/// can be represented as an indexed [r+r] operation. Returns false if it
2583/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2584/// non-zero and N can be represented by a base register plus a signed 16-bit
2585/// displacement, make a more precise judgement by checking (displacement % \p
2586/// EncodingAlignment).
2587bool PPCTargetLowering::SelectAddressRegReg(
2588 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2589 MaybeAlign EncodingAlignment) const {
2590 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2591 // a [pc+imm].
2592 if (SelectAddressPCRel(N, Base))
2593 return false;
2594
2595 int16_t Imm = 0;
2596 if (N.getOpcode() == ISD::ADD) {
2597 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2598 // SPE load/store can only handle 8-bit offsets.
2599 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2600 return true;
2601 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2602 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2603 return false; // r+i
2604 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2605 return false; // r+i
2606
2607 Base = N.getOperand(0);
2608 Index = N.getOperand(1);
2609 return true;
2610 } else if (N.getOpcode() == ISD::OR) {
2611 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2612 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2613 return false; // r+i can fold it if we can.
2614
2615 // If this is an or of disjoint bitfields, we can codegen this as an add
2616 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2617 // disjoint.
2618 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2619
2620 if (LHSKnown.Zero.getBoolValue()) {
2621 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2622 // If all of the bits are known zero on the LHS or RHS, the add won't
2623 // carry.
2624 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2625 Base = N.getOperand(0);
2626 Index = N.getOperand(1);
2627 return true;
2628 }
2629 }
2630 }
2631
2632 return false;
2633}
2634
2635// If we happen to be doing an i64 load or store into a stack slot that has
2636// less than a 4-byte alignment, then the frame-index elimination may need to
2637// use an indexed load or store instruction (because the offset may not be a
2638// multiple of 4). The extra register needed to hold the offset comes from the
2639// register scavenger, and it is possible that the scavenger will need to use
2640// an emergency spill slot. As a result, we need to make sure that a spill slot
2641// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2642// stack slot.
2643static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2644 // FIXME: This does not handle the LWA case.
2645 if (VT != MVT::i64)
2646 return;
2647
2648 // NOTE: We'll exclude negative FIs here, which come from argument
2649 // lowering, because there are no known test cases triggering this problem
2650 // using packed structures (or similar). We can remove this exclusion if
2651 // we find such a test case. The reason why this is so test-case driven is
2652 // because this entire 'fixup' is only to prevent crashes (from the
2653 // register scavenger) on not-really-valid inputs. For example, if we have:
2654 // %a = alloca i1
2655 // %b = bitcast i1* %a to i64*
2656 // store i64* a, i64 b
2657 // then the store should really be marked as 'align 1', but is not. If it
2658 // were marked as 'align 1' then the indexed form would have been
2659 // instruction-selected initially, and the problem this 'fixup' is preventing
2660 // won't happen regardless.
2661 if (FrameIdx < 0)
2662 return;
2663
2664 MachineFunction &MF = DAG.getMachineFunction();
2665 MachineFrameInfo &MFI = MF.getFrameInfo();
2666
2667 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2668 return;
2669
2670 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2671 FuncInfo->setHasNonRISpills();
2672}
2673
2674/// Returns true if the address N can be represented by a base register plus
2675/// a signed 16-bit displacement [r+imm], and if it is not better
2676/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2677/// displacements that are multiples of that value.
2678bool PPCTargetLowering::SelectAddressRegImm(
2679 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2680 MaybeAlign EncodingAlignment) const {
2681 // FIXME dl should come from parent load or store, not from address
2682 SDLoc dl(N);
2683
2684 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2685 // a [pc+imm].
2686 if (SelectAddressPCRel(N, Base))
2687 return false;
2688
2689 // If this can be more profitably realized as r+r, fail.
2690 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2691 return false;
2692
2693 if (N.getOpcode() == ISD::ADD) {
2694 int16_t imm = 0;
2695 if (isIntS16Immediate(N.getOperand(1), imm) &&
2696 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2697 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2698 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2699 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2700 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2701 } else {
2702 Base = N.getOperand(0);
2703 }
2704 return true; // [r+i]
2705 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2706 // Match LOAD (ADD (X, Lo(G))).
2707 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()(static_cast <bool> (!cast<ConstantSDNode>(N.getOperand
(1).getOperand(1))->getZExtValue() && "Cannot handle constant offsets yet!"
) ? void (0) : __assert_fail ("!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() && \"Cannot handle constant offsets yet!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
2708 && "Cannot handle constant offsets yet!")(static_cast <bool> (!cast<ConstantSDNode>(N.getOperand
(1).getOperand(1))->getZExtValue() && "Cannot handle constant offsets yet!"
) ? void (0) : __assert_fail ("!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() && \"Cannot handle constant offsets yet!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
;
2709 Disp = N.getOperand(1).getOperand(0); // The global address.
2710 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||(static_cast <bool> (Disp.getOpcode() == ISD::TargetGlobalAddress
|| Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode
() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? void (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
2711 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||(static_cast <bool> (Disp.getOpcode() == ISD::TargetGlobalAddress
|| Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode
() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? void (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
2712 Disp.getOpcode() == ISD::TargetConstantPool ||(static_cast <bool> (Disp.getOpcode() == ISD::TargetGlobalAddress
|| Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode
() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? void (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
2713 Disp.getOpcode() == ISD::TargetJumpTable)(static_cast <bool> (Disp.getOpcode() == ISD::TargetGlobalAddress
|| Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode
() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable
) ? void (0) : __assert_fail ("Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
;
2714 Base = N.getOperand(0);
2715 return true; // [&g+r]
2716 }
2717 } else if (N.getOpcode() == ISD::OR) {
2718 int16_t imm = 0;
2719 if (isIntS16Immediate(N.getOperand(1), imm) &&
2720 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2721 // If this is an or of disjoint bitfields, we can codegen this as an add
2722 // (for better address arithmetic) if the LHS and RHS of the OR are
2723 // provably disjoint.
2724 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2725
2726 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2727 // If all of the bits are known zero on the LHS or RHS, the add won't
2728 // carry.
2729 if (FrameIndexSDNode *FI =
2730 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2731 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2732 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2733 } else {
2734 Base = N.getOperand(0);
2735 }
2736 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2737 return true;
2738 }
2739 }
2740 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2741 // Loading from a constant address.
2742
2743 // If this address fits entirely in a 16-bit sext immediate field, codegen
2744 // this as "d, 0"
2745 int16_t Imm;
2746 if (isIntS16Immediate(CN, Imm) &&
2747 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2748 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2749 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2750 CN->getValueType(0));
2751 return true;
2752 }
2753
2754 // Handle 32-bit sext immediates with LIS + addr mode.
2755 if ((CN->getValueType(0) == MVT::i32 ||
2756 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2757 (!EncodingAlignment ||
2758 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2759 int Addr = (int)CN->getZExtValue();
2760
2761 // Otherwise, break this down into an LIS + disp.
2762 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2763
2764 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2765 MVT::i32);
2766 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2767 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2768 return true;
2769 }
2770 }
2771
2772 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2773 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2774 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2775 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2776 } else
2777 Base = N;
2778 return true; // [r+0]
2779}
2780
2781/// Similar to the 16-bit case but for instructions that take a 34-bit
2782/// displacement field (prefixed loads/stores).
2783bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2784 SDValue &Base,
2785 SelectionDAG &DAG) const {
2786 // Only on 64-bit targets.
2787 if (N.getValueType() != MVT::i64)
2788 return false;
2789
2790 SDLoc dl(N);
2791 int64_t Imm = 0;
2792
2793 if (N.getOpcode() == ISD::ADD) {
2794 if (!isIntS34Immediate(N.getOperand(1), Imm))
2795 return false;
2796 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2797 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2798 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2799 else
2800 Base = N.getOperand(0);
2801 return true;
2802 }
2803
2804 if (N.getOpcode() == ISD::OR) {
2805 if (!isIntS34Immediate(N.getOperand(1), Imm))
2806 return false;
2807 // If this is an or of disjoint bitfields, we can codegen this as an add
2808 // (for better address arithmetic) if the LHS and RHS of the OR are
2809 // provably disjoint.
2810 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2811 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2812 return false;
2813 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2814 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2815 else
2816 Base = N.getOperand(0);
2817 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2818 return true;
2819 }
2820
2821 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2822 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2823 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2824 return true;
2825 }
2826
2827 return false;
2828}
2829
2830/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2831/// represented as an indexed [r+r] operation.
2832bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2833 SDValue &Index,
2834 SelectionDAG &DAG) const {
2835 // Check to see if we can easily represent this as an [r+r] address. This
2836 // will fail if it thinks that the address is more profitably represented as
2837 // reg+imm, e.g. where imm = 0.
2838 if (SelectAddressRegReg(N, Base, Index, DAG))
2839 return true;
2840
2841 // If the address is the result of an add, we will utilize the fact that the
2842 // address calculation includes an implicit add. However, we can reduce
2843 // register pressure if we do not materialize a constant just for use as the
2844 // index register. We only get rid of the add if it is not an add of a
2845 // value and a 16-bit signed constant and both have a single use.
2846 int16_t imm = 0;
2847 if (N.getOpcode() == ISD::ADD &&
2848 (!isIntS16Immediate(N.getOperand(1), imm) ||
2849 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2850 Base = N.getOperand(0);
2851 Index = N.getOperand(1);
2852 return true;
2853 }
2854
2855 // Otherwise, do it the hard way, using R0 as the base register.
2856 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2857 N.getValueType());
2858 Index = N;
2859 return true;
2860}
2861
2862template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2863 Ty *PCRelCand = dyn_cast<Ty>(N);
2864 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2865}
2866
2867/// Returns true if this address is a PC Relative address.
2868/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2869/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2870bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2871 // This is a materialize PC Relative node. Always select this as PC Relative.
2872 Base = N;
2873 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2874 return true;
2875 if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2876 isValidPCRelNode<GlobalAddressSDNode>(N) ||
2877 isValidPCRelNode<JumpTableSDNode>(N) ||
2878 isValidPCRelNode<BlockAddressSDNode>(N))
2879 return true;
2880 return false;
2881}
2882
2883/// Returns true if we should use a direct load into vector instruction
2884/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2885static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2886
2887 // If there are any other uses other than scalar to vector, then we should
2888 // keep it as a scalar load -> direct move pattern to prevent multiple
2889 // loads.
2890 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2891 if (!LD)
2892 return false;
2893
2894 EVT MemVT = LD->getMemoryVT();
2895 if (!MemVT.isSimple())
2896 return false;
2897 switch(MemVT.getSimpleVT().SimpleTy) {
2898 case MVT::i64:
2899 break;
2900 case MVT::i32:
2901 if (!ST.hasP8Vector())
2902 return false;
2903 break;
2904 case MVT::i16:
2905 case MVT::i8:
2906 if (!ST.hasP9Vector())
2907 return false;
2908 break;
2909 default:
2910 return false;
2911 }
2912
2913 SDValue LoadedVal(N, 0);
2914 if (!LoadedVal.hasOneUse())
2915 return false;
2916
2917 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2918 UI != UE; ++UI)
2919 if (UI.getUse().get().getResNo() == 0 &&
2920 UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2921 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2922 return false;
2923
2924 return true;
2925}
2926
2927/// getPreIndexedAddressParts - returns true by value, base pointer and
2928/// offset pointer and addressing mode by reference if the node's address
2929/// can be legally represented as pre-indexed load / store address.
2930bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2931 SDValue &Offset,
2932 ISD::MemIndexedMode &AM,
2933 SelectionDAG &DAG) const {
2934 if (DisablePPCPreinc) return false;
2935
2936 bool isLoad = true;
2937 SDValue Ptr;
2938 EVT VT;
2939 unsigned Alignment;
2940 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2941 Ptr = LD->getBasePtr();
2942 VT = LD->getMemoryVT();
2943 Alignment = LD->getAlignment();
2944 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2945 Ptr = ST->getBasePtr();
2946 VT = ST->getMemoryVT();
2947 Alignment = ST->getAlignment();
2948 isLoad = false;
2949 } else
2950 return false;
2951
2952 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2953 // instructions because we can fold these into a more efficient instruction
2954 // instead, (such as LXSD).
2955 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2956 return false;
2957 }
2958
2959 // PowerPC doesn't have preinc load/store instructions for vectors
2960 if (VT.isVector())
2961 return false;
2962
2963 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2964 // Common code will reject creating a pre-inc form if the base pointer
2965 // is a frame index, or if N is a store and the base pointer is either
2966 // the same as or a predecessor of the value being stored. Check for
2967 // those situations here, and try with swapped Base/Offset instead.
2968 bool Swap = false;
2969
2970 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2971 Swap = true;
2972 else if (!isLoad) {
2973 SDValue Val = cast<StoreSDNode>(N)->getValue();
2974 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2975 Swap = true;
2976 }
2977
2978 if (Swap)
2979 std::swap(Base, Offset);
2980
2981 AM = ISD::PRE_INC;
2982 return true;
2983 }
2984
2985 // LDU/STU can only handle immediates that are a multiple of 4.
2986 if (VT != MVT::i64) {
2987 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2988 return false;
2989 } else {
2990 // LDU/STU need an address with at least 4-byte alignment.
2991 if (Alignment < 4)
2992 return false;
2993
2994 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2995 return false;
2996 }
2997
2998 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2999 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3000 // sext i32 to i64 when addr mode is r+i.
3001 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3002 LD->getExtensionType() == ISD::SEXTLOAD &&
3003 isa<ConstantSDNode>(Offset))
3004 return false;
3005 }
3006
3007 AM = ISD::PRE_INC;
3008 return true;
3009}
3010
3011//===----------------------------------------------------------------------===//
3012// LowerOperation implementation
3013//===----------------------------------------------------------------------===//
3014
3015/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3016/// and LoOpFlags to the target MO flags.
3017static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3018 unsigned &HiOpFlags, unsigned &LoOpFlags,
3019 const GlobalValue *GV = nullptr) {
3020 HiOpFlags = PPCII::MO_HA;
3021 LoOpFlags = PPCII::MO_LO;
3022
3023 // Don't use the pic base if not in PIC relocation model.
3024 if (IsPIC) {
3025 HiOpFlags |= PPCII::MO_PIC_FLAG;
3026 LoOpFlags |= PPCII::MO_PIC_FLAG;
3027 }
3028}
3029
3030static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3031 SelectionDAG &DAG) {
3032 SDLoc DL(HiPart);
3033 EVT PtrVT = HiPart.getValueType();
3034 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3035
3036 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3037 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3038
3039 // With PIC, the first instruction is actually "GR+hi(&G)".
3040 if (isPIC)
3041 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3042 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3043
3044 // Generate non-pic code that has direct accesses to the constant pool.
3045 // The address of the global is just (hi(&g)+lo(&g)).
3046 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3047}
3048
3049static void setUsesTOCBasePtr(MachineFunction &MF) {
3050 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3051 FuncInfo->setUsesTOCBasePtr();
3052}
3053
3054static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3055 setUsesTOCBasePtr(DAG.getMachineFunction());
3056}
3057
3058SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3059 SDValue GA) const {
3060 const bool Is64Bit = Subtarget.isPPC64();
3061 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3062 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3063 : Subtarget.isAIXABI()
3064 ? DAG.getRegister(PPC::R2, VT)
3065 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3066 SDValue Ops[] = { GA, Reg };
3067 return DAG.getMemIntrinsicNode(
3068 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3069 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3070 MachineMemOperand::MOLoad);
3071}
3072
3073SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3074 SelectionDAG &DAG) const {
3075 EVT PtrVT = Op.getValueType();
3076 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3077 const Constant *C = CP->getConstVal();
3078
3079 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3080 // The actual address of the GlobalValue is stored in the TOC.
3081 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3082 if (Subtarget.isUsingPCRelativeCalls()) {
3083 SDLoc DL(CP);
3084 EVT Ty = getPointerTy(DAG.getDataLayout());
3085 SDValue ConstPool = DAG.getTargetConstantPool(
3086 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3087 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3088 }
3089 setUsesTOCBasePtr(DAG);
3090 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3091 return getTOCEntry(DAG, SDLoc(CP), GA);
3092 }
3093
3094 unsigned MOHiFlag, MOLoFlag;
3095 bool IsPIC = isPositionIndependent();
3096 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3097
3098 if (IsPIC && Subtarget.isSVR4ABI()) {
3099 SDValue GA =
3100 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3101 return getTOCEntry(DAG, SDLoc(CP), GA);
3102 }
3103
3104 SDValue CPIHi =
3105 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3106 SDValue CPILo =
3107 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3108 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3109}
3110
3111// For 64-bit PowerPC, prefer the more compact relative encodings.
3112// This trades 32 bits per jump table entry for one or two instructions
3113// on the jump site.
3114unsigned PPCTargetLowering::getJumpTableEncoding() const {
3115 if (isJumpTableRelative())
3116 return MachineJumpTableInfo::EK_LabelDifference32;
3117
3118 return TargetLowering::getJumpTableEncoding();
3119}
3120
3121bool PPCTargetLowering::isJumpTableRelative() const {
3122 if (UseAbsoluteJumpTables)
3123 return false;
3124 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3125 return true;
3126 return TargetLowering::isJumpTableRelative();
3127}
3128
3129SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3130 SelectionDAG &DAG) const {
3131 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3132 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3133
3134 switch (getTargetMachine().getCodeModel()) {
3135 case CodeModel::Small:
3136 case CodeModel::Medium:
3137 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3138 default:
3139 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3140 getPointerTy(DAG.getDataLayout()));
3141 }
3142}
3143
3144const MCExpr *
3145PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3146 unsigned JTI,
3147 MCContext &Ctx) const {
3148 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3149 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3150
3151 switch (getTargetMachine().getCodeModel()) {
3152 case CodeModel::Small:
3153 case CodeModel::Medium:
3154 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3155 default:
3156 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3157 }
3158}
3159
3160SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3161 EVT PtrVT = Op.getValueType();
3162 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3163
3164 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3165 if (Subtarget.isUsingPCRelativeCalls()) {
3166 SDLoc DL(JT);
3167 EVT Ty = getPointerTy(DAG.getDataLayout());
3168 SDValue GA =
3169 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3170 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3171 return MatAddr;
3172 }
3173
3174 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3175 // The actual address of the GlobalValue is stored in the TOC.
3176 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3177 setUsesTOCBasePtr(DAG);
3178 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3179 return getTOCEntry(DAG, SDLoc(JT), GA);
3180 }
3181
3182 unsigned MOHiFlag, MOLoFlag;
3183 bool IsPIC = isPositionIndependent();
3184 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3185
3186 if (IsPIC && Subtarget.isSVR4ABI()) {
3187 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3188 PPCII::MO_PIC_FLAG);
3189 return getTOCEntry(DAG, SDLoc(GA), GA);
3190 }
3191
3192 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3193 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3194 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3195}
3196
3197SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3198 SelectionDAG &DAG) const {
3199 EVT PtrVT = Op.getValueType();
3200 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3201 const BlockAddress *BA = BASDN->getBlockAddress();
3202
3203 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3204 if (Subtarget.isUsingPCRelativeCalls()) {
3205 SDLoc DL(BASDN);
3206 EVT Ty = getPointerTy(DAG.getDataLayout());
3207 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3208 PPCII::MO_PCREL_FLAG);
3209 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3210 return MatAddr;
3211 }
3212
3213 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3214 // The actual BlockAddress is stored in the TOC.
3215 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3216 setUsesTOCBasePtr(DAG);
3217 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3218 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3219 }
3220
3221 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3222 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3223 return getTOCEntry(
3224 DAG, SDLoc(BASDN),
3225 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3226
3227 unsigned MOHiFlag, MOLoFlag;
3228 bool IsPIC = isPositionIndependent();
3229 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3230 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3231 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3232 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3233}
3234
3235SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3236 SelectionDAG &DAG) const {
3237 if (Subtarget.isAIXABI())
3238 return LowerGlobalTLSAddressAIX(Op, DAG);
3239
3240 return LowerGlobalTLSAddressLinux(Op, DAG);
3241}
3242
3243SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3244 SelectionDAG &DAG) const {
3245 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3246
3247 if (DAG.getTarget().useEmulatedTLS())
3248 report_fatal_error("Emulated TLS is not yet supported on AIX");
3249
3250 SDLoc dl(GA);
3251 const GlobalValue *GV = GA->getGlobal();
3252 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3253
3254 // The general-dynamic model is the only access model supported for now, so
3255 // all the GlobalTLSAddress nodes are lowered with this model.
3256 // We need to generate two TOC entries, one for the variable offset, one for
3257 // the region handle. The global address for the TOC entry of the region
3258 // handle is created with the MO_TLSGDM_FLAG flag and the global address
3259 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3260 SDValue VariableOffsetTGA =
3261 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3262 SDValue RegionHandleTGA =
3263 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3264 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3265 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3266 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3267 RegionHandle);
3268}
3269
3270SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3271 SelectionDAG &DAG) const {
3272 // FIXME: TLS addresses currently use medium model code sequences,
3273 // which is the most useful form. Eventually support for small and
3274 // large models could be added if users need it, at the cost of
3275 // additional complexity.
3276 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3277 if (DAG.getTarget().useEmulatedTLS())
3278 return LowerToTLSEmulatedModel(GA, DAG);
3279
3280 SDLoc dl(GA);
3281 const GlobalValue *GV = GA->getGlobal();
3282 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3283 bool is64bit = Subtarget.isPPC64();
3284 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3285 PICLevel::Level picLevel = M->getPICLevel();
3286
3287 const TargetMachine &TM = getTargetMachine();
3288 TLSModel::Model Model = TM.getTLSModel(GV);
3289
3290 if (Model == TLSModel::LocalExec) {
3291 if (Subtarget.isUsingPCRelativeCalls()) {
3292 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3293 SDValue TGA = DAG.getTargetGlobalAddress(
3294 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3295 SDValue MatAddr =
3296 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3297 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3298 }
3299
3300 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3301 PPCII::MO_TPREL_HA);
3302 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3303 PPCII::MO_TPREL_LO);
3304 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3305 : DAG.getRegister(PPC::R2, MVT::i32);
3306
3307 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3308 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3309 }
3310
3311 if (Model == TLSModel::InitialExec) {
3312 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3313 SDValue TGA = DAG.getTargetGlobalAddress(
3314 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3315 SDValue TGATLS = DAG.getTargetGlobalAddress(
3316 GV, dl, PtrVT, 0,
3317 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3318 SDValue TPOffset;
3319 if (IsPCRel) {
3320 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3321 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3322 MachinePointerInfo());
3323 } else {
3324 SDValue GOTPtr;
3325 if (is64bit) {
3326 setUsesTOCBasePtr(DAG);
3327 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3328 GOTPtr =
3329 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3330 } else {
3331 if (!TM.isPositionIndependent())
3332 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3333 else if (picLevel == PICLevel::SmallPIC)
3334 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3335 else
3336 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3337 }
3338 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3339 }
3340 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3341 }
3342
3343 if (Model == TLSModel::GeneralDynamic) {
3344 if (Subtarget.isUsingPCRelativeCalls()) {
3345 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3346 PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3347 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3348 }
3349
3350 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3351 SDValue GOTPtr;
3352 if (is64bit) {
3353 setUsesTOCBasePtr(DAG);
3354 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3355 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3356 GOTReg, TGA);
3357 } else {
3358 if (picLevel == PICLevel::SmallPIC)
3359 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3360 else
3361 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3362 }
3363 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3364 GOTPtr, TGA, TGA);
3365 }
3366
3367 if (Model == TLSModel::LocalDynamic) {
3368 if (Subtarget.isUsingPCRelativeCalls()) {
3369 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3370 PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3371 SDValue MatPCRel =
3372 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3373 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3374 }
3375
3376 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3377 SDValue GOTPtr;
3378 if (is64bit) {
3379 setUsesTOCBasePtr(DAG);
3380 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3381 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3382 GOTReg, TGA);
3383 } else {
3384 if (picLevel == PICLevel::SmallPIC)
3385 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3386 else
3387 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3388 }
3389 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3390 PtrVT, GOTPtr, TGA, TGA);
3391 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3392 PtrVT, TLSAddr, TGA);
3393 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3394 }
3395
3396 llvm_unreachable("Unknown TLS model!")::llvm::llvm_unreachable_internal("Unknown TLS model!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3396)
;
3397}
3398
3399SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3400 SelectionDAG &DAG) const {
3401 EVT PtrVT = Op.getValueType();
3402 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3403 SDLoc DL(GSDN);
3404 const GlobalValue *GV = GSDN->getGlobal();
3405
3406 // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3407 // The actual address of the GlobalValue is stored in the TOC.
3408 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3409 if (Subtarget.isUsingPCRelativeCalls()) {
3410 EVT Ty = getPointerTy(DAG.getDataLayout());
3411 if (isAccessedAsGotIndirect(Op)) {
3412 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3413 PPCII::MO_PCREL_FLAG |
3414 PPCII::MO_GOT_FLAG);
3415 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3416 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3417 MachinePointerInfo());
3418 return Load;
3419 } else {
3420 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3421 PPCII::MO_PCREL_FLAG);
3422 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3423 }
3424 }
3425 setUsesTOCBasePtr(DAG);
3426 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3427 return getTOCEntry(DAG, DL, GA);
3428 }
3429
3430 unsigned MOHiFlag, MOLoFlag;
3431 bool IsPIC = isPositionIndependent();
3432 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3433
3434 if (IsPIC && Subtarget.isSVR4ABI()) {
3435 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3436 GSDN->getOffset(),
3437 PPCII::MO_PIC_FLAG);
3438 return getTOCEntry(DAG, DL, GA);
3439 }
3440
3441 SDValue GAHi =
3442 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3443 SDValue GALo =
3444 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3445
3446 return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3447}
3448
3449SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3450 bool IsStrict = Op->isStrictFPOpcode();
3451 ISD::CondCode CC =
3452 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3453 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3454 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3455 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3456 EVT LHSVT = LHS.getValueType();
3457 SDLoc dl(Op);
3458
3459 // Soften the setcc with libcall if it is fp128.
3460 if (LHSVT == MVT::f128) {
3461 assert(!Subtarget.hasP9Vector() &&(static_cast <bool> (!Subtarget.hasP9Vector() &&
"SETCC for f128 is already legal under Power9!") ? void (0) :
__assert_fail ("!Subtarget.hasP9Vector() && \"SETCC for f128 is already legal under Power9!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3462, __extension__ __PRETTY_FUNCTION__))
3462 "SETCC for f128 is already legal under Power9!")(static_cast <bool> (!Subtarget.hasP9Vector() &&
"SETCC for f128 is already legal under Power9!") ? void (0) :
__assert_fail ("!Subtarget.hasP9Vector() && \"SETCC for f128 is already legal under Power9!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3462, __extension__ __PRETTY_FUNCTION__))
;
3463 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3464 Op->getOpcode() == ISD::STRICT_FSETCCS);
3465 if (RHS.getNode())
3466 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3467 DAG.getCondCode(CC));
3468 if (IsStrict)
3469 return DAG.getMergeValues({LHS, Chain}, dl);
3470 return LHS;
3471 }
3472
3473 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!")(static_cast <bool> (!IsStrict && "Don't know how to handle STRICT_FSETCC!"
) ? void (0) : __assert_fail ("!IsStrict && \"Don't know how to handle STRICT_FSETCC!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3473, __extension__ __PRETTY_FUNCTION__))
;
3474
3475 if (Op.getValueType() == MVT::v2i64) {
3476 // When the operands themselves are v2i64 values, we need to do something
3477 // special because VSX has no underlying comparison operations for these.
3478 if (LHS.getValueType() == MVT::v2i64) {
3479 // Equality can be handled by casting to the legal type for Altivec
3480 // comparisons, everything else needs to be expanded.
3481 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3482 return DAG.getNode(
3483 ISD::BITCAST, dl, MVT::v2i64,
3484 DAG.getSetCC(dl, MVT::v4i32,
3485 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3486 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3487 }
3488
3489 return SDValue();
3490 }
3491
3492 // We handle most of these in the usual way.
3493 return Op;
3494 }
3495
3496 // If we're comparing for equality to zero, expose the fact that this is
3497 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3498 // fold the new nodes.
3499 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3500 return V;
3501
3502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3503 // Leave comparisons against 0 and -1 alone for now, since they're usually
3504 // optimized. FIXME: revisit this when we can custom lower all setcc
3505 // optimizations.
3506 if (C->isAllOnesValue() || C->isNullValue())
3507 return SDValue();
3508 }
3509
3510 // If we have an integer seteq/setne, turn it into a compare against zero
3511 // by xor'ing the rhs with the lhs, which is faster than setting a
3512 // condition register, reading it back out, and masking the correct bit. The
3513 // normal approach here uses sub to do this instead of xor. Using xor exposes
3514 // the result to other bit-twiddling opportunities.
3515 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3516 EVT VT = Op.getValueType();
3517 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3518 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3519 }
3520 return SDValue();
3521}
3522
3523SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3524 SDNode *Node = Op.getNode();
3525 EVT VT = Node->getValueType(0);
3526 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3527 SDValue InChain = Node->getOperand(0);
3528 SDValue VAListPtr = Node->getOperand(1);
3529 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3530 SDLoc dl(Node);
3531
3532 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only")(static_cast <bool> (!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"
) ? void (0) : __assert_fail ("!Subtarget.isPPC64() && \"LowerVAARG is PPC32 only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3532, __extension__ __PRETTY_FUNCTION__))
;
3533
3534 // gpr_index
3535 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3536 VAListPtr, MachinePointerInfo(SV), MVT::i8);
3537 InChain = GprIndex.getValue(1);
3538
3539 if (VT == MVT::i64) {
3540 // Check if GprIndex is even
3541 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3542 DAG.getConstant(1, dl, MVT::i32));
3543 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3544 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3545 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3546 DAG.getConstant(1, dl, MVT::i32));
3547 // Align GprIndex to be even if it isn't
3548 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3549 GprIndex);
3550 }
3551
3552 // fpr index is 1 byte after gpr
3553 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3554 DAG.getConstant(1, dl, MVT::i32));
3555
3556 // fpr
3557 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3558 FprPtr, MachinePointerInfo(SV), MVT::i8);
3559 InChain = FprIndex.getValue(1);
3560
3561 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3562 DAG.getConstant(8, dl, MVT::i32));
3563
3564 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3565 DAG.getConstant(4, dl, MVT::i32));
3566
3567 // areas
3568 SDValue OverflowArea =
3569 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3570 InChain = OverflowArea.getValue(1);
3571
3572 SDValue RegSaveArea =
3573 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3574 InChain = RegSaveArea.getValue(1);
3575
3576 // select overflow_area if index > 8
3577 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3578 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3579
3580 // adjustment constant gpr_index * 4/8
3581 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3582 VT.isInteger() ? GprIndex : FprIndex,
3583 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3584 MVT::i32));
3585
3586 // OurReg = RegSaveArea + RegConstant
3587 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3588 RegConstant);
3589
3590 // Floating types are 32 bytes into RegSaveArea
3591 if (VT.isFloatingPoint())
3592 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3593 DAG.getConstant(32, dl, MVT::i32));
3594
3595 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3596 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3597 VT.isInteger() ? GprIndex : FprIndex,
3598 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3599 MVT::i32));
3600
3601 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3602 VT.isInteger() ? VAListPtr : FprPtr,
3603 MachinePointerInfo(SV), MVT::i8);
3604
3605 // determine if we should load from reg_save_area or overflow_area
3606 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3607
3608 // increase overflow_area by 4/8 if gpr/fpr > 8
3609 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3610 DAG.getConstant(VT.isInteger() ? 4 : 8,
3611 dl, MVT::i32));
3612
3613 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3614 OverflowAreaPlusN);
3615
3616 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3617 MachinePointerInfo(), MVT::i32);
3618
3619 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3620}
3621
3622SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3623 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only")(static_cast <bool> (!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"
) ? void (0) : __assert_fail ("!Subtarget.isPPC64() && \"LowerVACOPY is PPC32 only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3623, __extension__ __PRETTY_FUNCTION__))
;
3624
3625 // We have to copy the entire va_list struct:
3626 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3627 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3628 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3629 false, true, false, MachinePointerInfo(),
3630 MachinePointerInfo());
3631}
3632
3633SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3634 SelectionDAG &DAG) const {
3635 if (Subtarget.isAIXABI())
3636 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3637
3638 return Op.getOperand(0);
3639}
3640
3641SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3642 MachineFunction &MF = DAG.getMachineFunction();
3643 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3644
3645 assert((Op.getOpcode() == ISD::INLINEASM ||(static_cast <bool> ((Op.getOpcode() == ISD::INLINEASM ||
Op.getOpcode() == ISD::INLINEASM_BR) && "Expecting Inline ASM node."
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::INLINEASM || Op.getOpcode() == ISD::INLINEASM_BR) && \"Expecting Inline ASM node.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3647, __extension__ __PRETTY_FUNCTION__))
3646 Op.getOpcode() == ISD::INLINEASM_BR) &&(static_cast <bool> ((Op.getOpcode() == ISD::INLINEASM ||
Op.getOpcode() == ISD::INLINEASM_BR) && "Expecting Inline ASM node."
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::INLINEASM || Op.getOpcode() == ISD::INLINEASM_BR) && \"Expecting Inline ASM node.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3647, __extension__ __PRETTY_FUNCTION__))
3647 "Expecting Inline ASM node.")(static_cast <bool> ((Op.getOpcode() == ISD::INLINEASM ||
Op.getOpcode() == ISD::INLINEASM_BR) && "Expecting Inline ASM node."
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::INLINEASM || Op.getOpcode() == ISD::INLINEASM_BR) && \"Expecting Inline ASM node.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3647, __extension__ __PRETTY_FUNCTION__))
;
3648
3649 // If an LR store is already known to be required then there is not point in
3650 // checking this ASM as well.
3651 if (MFI.isLRStoreRequired())
3652 return Op;
3653
3654 // Inline ASM nodes have an optional last operand that is an incoming Flag of
3655 // type MVT::Glue. We want to ignore this last operand if that is the case.
3656 unsigned NumOps = Op.getNumOperands();
3657 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3658 --NumOps;
3659
3660 // Check all operands that may contain the LR.
3661 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3662 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3663 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3664 ++i; // Skip the ID value.
3665
3666 switch (InlineAsm::getKind(Flags)) {
3667 default:
3668 llvm_unreachable("Bad flags!")::llvm::llvm_unreachable_internal("Bad flags!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3668)
;
3669 case InlineAsm::Kind_RegUse:
3670 case InlineAsm::Kind_Imm:
3671 case InlineAsm::Kind_Mem:
3672 i += NumVals;
3673 break;
3674 case InlineAsm::Kind_Clobber:
3675 case InlineAsm::Kind_RegDef:
3676 case InlineAsm::Kind_RegDefEarlyClobber: {
3677 for (; NumVals; --NumVals, ++i) {
3678 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3679 if (Reg != PPC::LR && Reg != PPC::LR8)
3680 continue;
3681 MFI.setLRStoreRequired();
3682 return Op;
3683 }
3684 break;
3685 }
3686 }
3687 }
3688
3689 return Op;
3690}
3691
3692SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3693 SelectionDAG &DAG) const {
3694 if (Subtarget.isAIXABI())
3695 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3696
3697 SDValue Chain = Op.getOperand(0);
3698 SDValue Trmp = Op.getOperand(1); // trampoline
3699 SDValue FPtr = Op.getOperand(2); // nested function
3700 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3701 SDLoc dl(Op);
3702
3703 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3704 bool isPPC64 = (PtrVT == MVT::i64);
3705 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3706
3707 TargetLowering::ArgListTy Args;
3708 TargetLowering::ArgListEntry Entry;
3709
3710 Entry.Ty = IntPtrTy;
3711 Entry.Node = Trmp; Args.push_back(Entry);
3712
3713 // TrampSize == (isPPC64 ? 48 : 40);
3714 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3715 isPPC64 ? MVT::i64 : MVT::i32);
3716 Args.push_back(Entry);
3717
3718 Entry.Node = FPtr; Args.push_back(Entry);
3719 Entry.Node = Nest; Args.push_back(Entry);
3720
3721 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3722 TargetLowering::CallLoweringInfo CLI(DAG);
3723 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3724 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3725 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3726
3727 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3728 return CallResult.second;
3729}
3730
3731SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3732 MachineFunction &MF = DAG.getMachineFunction();
3733 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3734 EVT PtrVT = getPointerTy(MF.getDataLayout());
3735
3736 SDLoc dl(Op);
3737
3738 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3739 // vastart just stores the address of the VarArgsFrameIndex slot into the
3740 // memory location argument.
3741 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3742 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3743 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3744 MachinePointerInfo(SV));
3745 }
3746
3747 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3748 // We suppose the given va_list is already allocated.
3749 //
3750 // typedef struct {
3751 // char gpr; /* index into the array of 8 GPRs
3752 // * stored in the register save area
3753 // * gpr=0 corresponds to r3,
3754 // * gpr=1 to r4, etc.
3755 // */
3756 // char fpr; /* index into the array of 8 FPRs
3757 // * stored in the register save area
3758 // * fpr=0 corresponds to f1,
3759 // * fpr=1 to f2, etc.
3760 // */
3761 // char *overflow_arg_area;
3762 // /* location on stack that holds
3763 // * the next overflow argument
3764 // */
3765 // char *reg_save_area;
3766 // /* where r3:r10 and f1:f8 (if saved)
3767 // * are stored
3768 // */
3769 // } va_list[1];
3770
3771 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3772 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3773 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3774 PtrVT);
3775 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3776 PtrVT);
3777
3778 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3779 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3780
3781 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3782 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3783
3784 uint64_t FPROffset = 1;
3785 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3786
3787 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3788
3789 // Store first byte : number of int regs
3790 SDValue firstStore =
3791 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3792 MachinePointerInfo(SV), MVT::i8);
3793 uint64_t nextOffset = FPROffset;
3794 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3795 ConstFPROffset);
3796
3797 // Store second byte : number of float regs
3798 SDValue secondStore =
3799 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3800 MachinePointerInfo(SV, nextOffset), MVT::i8);
3801 nextOffset += StackOffset;
3802 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3803
3804 // Store second word : arguments given on stack
3805 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3806 MachinePointerInfo(SV, nextOffset));
3807 nextOffset += FrameOffset;
3808 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3809
3810 // Store third word : arguments given in registers
3811 return DAG.getStore(thirdStore, dl, FR, nextPtr,
3812 MachinePointerInfo(SV, nextOffset));
3813}
3814
3815/// FPR - The set of FP registers that should be allocated for arguments
3816/// on Darwin and AIX.
3817static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3818 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3819 PPC::F11, PPC::F12, PPC::F13};
3820
3821/// CalculateStackSlotSize - Calculates the size reserved for this argument on
3822/// the stack.
3823static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3824 unsigned PtrByteSize) {
3825 unsigned ArgSize = ArgVT.getStoreSize();
3826 if (Flags.isByVal())
3827 ArgSize = Flags.getByValSize();
3828
3829 // Round up to multiples of the pointer size, except for array members,
3830 // which are always packed.
3831 if (!Flags.isInConsecutiveRegs())
3832 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3833
3834 return ArgSize;
3835}
3836
3837/// CalculateStackSlotAlignment - Calculates the alignment of this argument
3838/// on the stack.
3839static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3840 ISD::ArgFlagsTy Flags,
3841 unsigned PtrByteSize) {
3842 Align Alignment(PtrByteSize);
3843
3844 // Altivec parameters are padded to a 16 byte boundary.
3845 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3846 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3847 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3848 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3849 Alignment = Align(16);
3850
3851 // ByVal parameters are aligned as requested.
3852 if (Flags.isByVal()) {
3853 auto BVAlign = Flags.getNonZeroByValAlign();
3854 if (BVAlign > PtrByteSize) {
3855 if (BVAlign.value() % PtrByteSize != 0)
3856 llvm_unreachable(::llvm::llvm_unreachable_internal("ByVal alignment is not a multiple of the pointer size"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3857)
3857 "ByVal alignment is not a multiple of the pointer size")::llvm::llvm_unreachable_internal("ByVal alignment is not a multiple of the pointer size"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3857)
;
3858
3859 Alignment = BVAlign;
3860 }
3861 }
3862
3863 // Array members are always packed to their original alignment.
3864 if (Flags.isInConsecutiveRegs()) {
3865 // If the array member was split into multiple registers, the first
3866 // needs to be aligned to the size of the full type. (Except for
3867 // ppcf128, which is only aligned as its f64 components.)
3868 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3869 Alignment = Align(OrigVT.getStoreSize());
3870 else
3871 Alignment = Align(ArgVT.getStoreSize());
3872 }
3873
3874 return Alignment;
3875}
3876
3877/// CalculateStackSlotUsed - Return whether this argument will use its
3878/// stack slot (instead of being passed in registers). ArgOffset,
3879/// AvailableFPRs, and AvailableVRs must hold the current argument
3880/// position, and will be updated to account for this argument.
3881static bool CalculateStackSlotUsed(const PPCSubtarget &Subtarget, EVT ArgVT,
3882 EVT OrigVT, ISD::ArgFlagsTy Flags,
3883 unsigned PtrByteSize, unsigned LinkageSize,
3884 unsigned ParamAreaSize, unsigned &ArgOffset,
3885 unsigned &AvailableFPRs,
3886 unsigned &AvailableVRs) {
3887 bool UseMemory = false;
3888
3889 // Respect alignment of argument on the stack.
3890 Align Alignment =
3891 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3892 ArgOffset = alignTo(ArgOffset, Alignment);
3893 // If there's no space left in the argument save area, we must
3894 // use memory (this check also catches zero-sized arguments).
3895 if (ArgOffset >= LinkageSize + ParamAreaSize)
3896 UseMemory = true;
3897
3898 // Allocate argument on the stack.
3899 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3900 if (Flags.isInConsecutiveRegsLast())
3901 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3902 // If we overran the argument save area, we must use memory
3903 // (this check catches arguments passed partially in memory)
3904 if (ArgOffset > LinkageSize + ParamAreaSize)
3905 UseMemory = true;
3906
3907 // However, if the argument is actually passed in an FPR or a VR,
3908 // we don't use memory after all.
3909 if (!Flags.isByVal()) {
3910 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3911 if (AvailableFPRs > 0) {
3912 --AvailableFPRs;
3913 return false;
3914 }
3915 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3916 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3917 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3918 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3919 if (AvailableVRs > 0) {
3920 --AvailableVRs;
3921 return false;
3922 }
3923 } else if (Subtarget.isPPC64() && Subtarget.isELFv2ABI() &&
3924 Flags.getByValSize() >= 8)
3925 // For 64-bit ELF v2, passing by value object whose size is no less than 8
3926 // bytes will be copied to parameter save area. This is for compatibility
3927 // for other compiler which requires byval parameters to be stored in
3928 // caller's parameter save area.
3929 return true;
3930
3931 return UseMemory;
3932}
3933
3934/// EnsureStackAlignment - Round stack frame size up from NumBytes to
3935/// ensure minimum alignment required for target.
3936static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3937 unsigned NumBytes) {
3938 return alignTo(NumBytes, Lowering->getStackAlign());
3939}
3940
3941SDValue PPCTargetLowering::LowerFormalArguments(
3942 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3943 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3944 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3945 if (Subtarget.isAIXABI())
3946 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3947 InVals);
3948 if (Subtarget.is64BitELFABI())
3949 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3950 InVals);
3951 assert(Subtarget.is32BitELFABI())(static_cast <bool> (Subtarget.is32BitELFABI()) ? void (
0) : __assert_fail ("Subtarget.is32BitELFABI()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 3951, __extension__ __PRETTY_FUNCTION__))
;
3952 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3953 InVals);
3954}
3955
3956SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3957 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3958 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3959 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3960
3961 // 32-bit SVR4 ABI Stack Frame Layout:
3962 // +-----------------------------------+
3963 // +--> | Back chain |
3964 // | +-----------------------------------+
3965 // | | Floating-point register save area |
3966 // | +-----------------------------------+
3967 // | | General register save area |
3968 // | +-----------------------------------+
3969 // | | CR save word |
3970 // | +-----------------------------------+
3971 // | | VRSAVE save word |
3972 // | +-----------------------------------+
3973 // | | Alignment padding |
3974 // | +-----------------------------------+
3975 // | | Vector register save area |
3976 // | +-----------------------------------+
3977 // | | Local variable space |
3978 // | +-----------------------------------+
3979 // | | Parameter list area |
3980 // | +-----------------------------------+
3981 // | | LR save word |
3982 // | +-----------------------------------+
3983 // SP--> +--- | Back chain |
3984 // +-----------------------------------+
3985 //
3986 // Specifications:
3987 // System V Application Binary Interface PowerPC Processor Supplement
3988 // AltiVec Technology Programming Interface Manual
3989
3990 MachineFunction &MF = DAG.getMachineFunction();
3991 MachineFrameInfo &MFI = MF.getFrameInfo();
3992 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3993
3994 EVT PtrVT = getPointerTy(MF.getDataLayout());
3995 // Potential tail calls could cause overwriting of argument stack slots.
3996 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3997 (CallConv == CallingConv::Fast));
3998 const Align PtrAlign(4);
3999
4000 // Assign locations to all of the incoming arguments.
4001 SmallVector<CCValAssign, 16> ArgLocs;
4002 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4003 *DAG.getContext());
4004
4005 // Reserve space for the linkage area on the stack.
4006 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4007 CCInfo.AllocateStack(LinkageSize, PtrAlign);
4008 if (useSoftFloat())
4009 CCInfo.PreAnalyzeFormalArguments(Ins);
4010
4011 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4012 CCInfo.clearWasPPCF128();
4013
4014 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4015 CCValAssign &VA = ArgLocs[i];
4016
4017 // Arguments stored in registers.
4018 if (VA.isRegLoc()) {
4019 const TargetRegisterClass *RC;
4020 EVT ValVT = VA.getValVT();
4021
4022 switch (ValVT.getSimpleVT().SimpleTy) {
4023 default:
4024 llvm_unreachable("ValVT not supported by formal arguments Lowering")::llvm::llvm_unreachable_internal("ValVT not supported by formal arguments Lowering"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4024)
;
4025 case MVT::i1:
4026 case MVT::i32:
4027 RC = &PPC::GPRCRegClass;
4028 break;
4029 case MVT::f32:
4030 if (Subtarget.hasP8Vector())
4031 RC = &PPC::VSSRCRegClass;
4032 else if (Subtarget.hasSPE())
4033 RC = &PPC::GPRCRegClass;
4034 else
4035 RC = &PPC::F4RCRegClass;
4036 break;
4037 case MVT::f64:
4038 if (Subtarget.hasVSX())
4039 RC = &PPC::VSFRCRegClass;
4040 else if (Subtarget.hasSPE())
4041 // SPE passes doubles in GPR pairs.
4042 RC = &PPC::GPRCRegClass;
4043 else
4044 RC = &PPC::F8RCRegClass;
4045 break;
4046 case MVT::v16i8:
4047 case MVT::v8i16:
4048 case MVT::v4i32:
4049 RC = &PPC::VRRCRegClass;
4050 break;
4051 case MVT::v4f32:
4052 RC = &PPC::VRRCRegClass;
4053 break;
4054 case MVT::v2f64:
4055 case MVT::v2i64:
4056 RC = &PPC::VRRCRegClass;
4057 break;
4058 }
4059
4060 SDValue ArgValue;
4061 // Transform the arguments stored in physical registers into
4062 // virtual ones.
4063 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4064 assert(i + 1 < e && "No second half of double precision argument")(static_cast <bool> (i + 1 < e && "No second half of double precision argument"
) ? void (0) : __assert_fail ("i + 1 < e && \"No second half of double precision argument\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4064, __extension__ __PRETTY_FUNCTION__))
;
4065 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4066 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4067 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4068 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4069 if (!Subtarget.isLittleEndian())
4070 std::swap (ArgValueLo, ArgValueHi);
4071 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4072 ArgValueHi);
4073 } else {
4074 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4075 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4076 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4077 if (ValVT == MVT::i1)
4078 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4079 }
4080
4081 InVals.push_back(ArgValue);
4082 } else {
4083 // Argument stored in memory.
4084 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4084, __extension__ __PRETTY_FUNCTION__))
;
4085
4086 // Get the extended size of the argument type in stack
4087 unsigned ArgSize = VA.getLocVT().getStoreSize();
4088 // Get the actual size of the argument type
4089 unsigned ObjSize = VA.getValVT().getStoreSize();
4090 unsigned ArgOffset = VA.getLocMemOffset();
4091 // Stack objects in PPC32 are right justified.
4092 ArgOffset += ArgSize - ObjSize;
4093 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4094
4095 // Create load nodes to retrieve arguments from the stack.
4096 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4097 InVals.push_back(
4098 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4099 }
4100 }
4101
4102 // Assign locations to all of the incoming aggregate by value arguments.
4103 // Aggregates passed by value are stored in the local variable space of the
4104 // caller's stack frame, right above the parameter list area.
4105 SmallVector<CCValAssign, 16> ByValArgLocs;
4106 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4107 ByValArgLocs, *DAG.getContext());
4108
4109 // Reserve stack space for the allocations in CCInfo.
4110 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4111
4112 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4113
4114 // Area that is at least reserved in the caller of this function.
4115 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4116 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4117
4118 // Set the size that is at least reserved in caller of this function. Tail
4119 // call optimized function's reserved stack space needs to be aligned so that
4120 // taking the difference between two stack areas will result in an aligned
4121 // stack.
4122 MinReservedArea =
4123 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4124 FuncInfo->setMinReservedArea(MinReservedArea);
4125
4126 SmallVector<SDValue, 8> MemOps;
4127
4128 // If the function takes variable number of arguments, make a frame index for
4129 // the start of the first vararg value... for expansion of llvm.va_start.
4130 if (isVarArg) {
4131 static const MCPhysReg GPArgRegs[] = {
4132 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4133 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4134 };
4135 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4136
4137 static const MCPhysReg FPArgRegs[] = {
4138 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4139 PPC::F8
4140 };
4141 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4142
4143 if (useSoftFloat() || hasSPE())
4144 NumFPArgRegs = 0;
4145
4146 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4147 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4148
4149 // Make room for NumGPArgRegs and NumFPArgRegs.
4150 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4151 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4152
4153 FuncInfo->setVarArgsStackOffset(
4154 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4155 CCInfo.getNextStackOffset(), true));
4156
4157 FuncInfo->setVarArgsFrameIndex(
4158 MFI.CreateStackObject(Depth, Align(8), false));
4159 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4160
4161 // The fixed integer arguments of a variadic function are stored to the
4162 // VarArgsFrameIndex on the stack so that they may be loaded by
4163 // dereferencing the result of va_next.
4164 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4165 // Get an existing live-in vreg, or add a new one.
4166 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4167 if (!VReg)
4168 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4169
4170 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4171 SDValue Store =
4172 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4173 MemOps.push_back(Store);
4174 // Increment the address by four for the next argument to store
4175 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4176 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4177 }
4178
4179 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4180 // is set.
4181 // The double arguments are stored to the VarArgsFrameIndex
4182 // on the stack.
4183 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4184 // Get an existing live-in vreg, or add a new one.
4185 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4186 if (!VReg)
4187 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4188
4189 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4190 SDValue Store =
4191 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4192 MemOps.push_back(Store);
4193 // Increment the address by eight for the next argument to store
4194 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4195 PtrVT);
4196 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4197 }
4198 }
4199
4200 if (!MemOps.empty())
4201 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4202
4203 return Chain;
4204}
4205
4206// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4207// value to MVT::i64 and then truncate to the correct register size.
4208SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4209 EVT ObjectVT, SelectionDAG &DAG,
4210 SDValue ArgVal,
4211 const SDLoc &dl) const {
4212 if (Flags.isSExt())
4213 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4214 DAG.getValueType(ObjectVT));
4215 else if (Flags.isZExt())
4216 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4217 DAG.getValueType(ObjectVT));
4218
4219 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4220}
4221
4222SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4223 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4224 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4225 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4226 // TODO: add description of PPC stack frame format, or at least some docs.
4227 //
4228 bool isELFv2ABI = Subtarget.isELFv2ABI();
4229 bool isLittleEndian = Subtarget.isLittleEndian();
4230 MachineFunction &MF = DAG.getMachineFunction();
4231 MachineFrameInfo &MFI = MF.getFrameInfo();
4232 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4233
4234 assert(!(CallConv == CallingConv::Fast && isVarArg) &&(static_cast <bool> (!(CallConv == CallingConv::Fast &&
isVarArg) && "fastcc not supported on varargs functions"
) ? void (0) : __assert_fail ("!(CallConv == CallingConv::Fast && isVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4235, __extension__ __PRETTY_FUNCTION__))
4235 "fastcc not supported on varargs functions")(static_cast <bool> (!(CallConv == CallingConv::Fast &&
isVarArg) && "fastcc not supported on varargs functions"
) ? void (0) : __assert_fail ("!(CallConv == CallingConv::Fast && isVarArg) && \"fastcc not supported on varargs functions\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4235, __extension__ __PRETTY_FUNCTION__))
;
4236
4237 EVT PtrVT = getPointerTy(MF.getDataLayout());
4238 // Potential tail calls could cause overwriting of argument stack slots.
4239 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4240 (CallConv == CallingConv::Fast));
4241 unsigned PtrByteSize = 8;
4242 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4243
4244 static const MCPhysReg GPR[] = {
4245 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4246 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4247 };
4248 static const MCPhysReg VR[] = {
4249 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4250 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4251 };
4252
4253 const unsigned Num_GPR_Regs = array_lengthof(GPR);
4254 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4255 const unsigned Num_VR_Regs = array_lengthof(VR);
4256
4257 // Do a first pass over the arguments to determine whether the ABI
4258 // guarantees that our caller has allocated the parameter save area
4259 // on its stack frame. In the ELFv1 ABI, this is always the case;
4260 // in the ELFv2 ABI, it is true if this is a vararg function or if
4261 // any parameter is located in a stack slot.
4262
4263 bool HasParameterArea = !isELFv2ABI || isVarArg;
4264 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4265 unsigned NumBytes = LinkageSize;
4266 unsigned AvailableFPRs = Num_FPR_Regs;
4267 unsigned AvailableVRs = Num_VR_Regs;
4268 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4269 if (Ins[i].Flags.isNest())
4270 continue;
4271
4272 if (CalculateStackSlotUsed(Subtarget, Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4273 PtrByteSize, LinkageSize, ParamAreaSize,
4274 NumBytes, AvailableFPRs, AvailableVRs))
4275 HasParameterArea = true;
4276 }
4277
4278 // Add DAG nodes to load the arguments or copy them out of registers. On
4279 // entry to a function on PPC, the arguments start after the linkage area,
4280 // although the first ones are often in registers.
4281
4282 unsigned ArgOffset = LinkageSize;
4283 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4284 SmallVector<SDValue, 8> MemOps;
4285 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4286 unsigned CurArgIdx = 0;
4287 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4288 SDValue ArgVal;
4289 bool needsLoad = false;
4290 EVT ObjectVT = Ins[ArgNo].VT;
4291 EVT OrigVT = Ins[ArgNo].ArgVT;
4292 unsigned ObjSize = ObjectVT.getStoreSize();
4293 unsigned ArgSize = ObjSize;
4294 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4295 if (Ins[ArgNo].isOrigArg()) {
4296 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4297 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4298 }
4299 // We re-align the argument offset for each argument, except when using the
4300 // fast calling convention, when we need to make sure we do that only when
4301 // we'll actually use a stack slot.
4302 unsigned CurArgOffset;
4303 Align Alignment;
4304 auto ComputeArgOffset = [&]() {
4305 /* Respect alignment of argument on the stack. */
4306 Alignment =
4307 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4308 ArgOffset = alignTo(ArgOffset, Alignment);
4309 CurArgOffset = ArgOffset;
4310 };
4311
4312 if (CallConv != CallingConv::Fast) {
4313 ComputeArgOffset();
4314
4315 /* Compute GPR index associated with argument offset. */
4316 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4317 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4318 }
4319
4320 // FIXME the codegen can be much improved in some cases.
4321 // We do not have to keep everything in memory.
4322 if (Flags.isByVal()) {
4323 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit")(static_cast <bool> (Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"
) ? void (0) : __assert_fail ("Ins[ArgNo].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4323, __extension__ __PRETTY_FUNCTION__))
;
4324
4325 if (CallConv == CallingConv::Fast)
4326 ComputeArgOffset();
4327
4328 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4329 ObjSize = Flags.getByValSize();
4330 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4331 // Empty aggregate parameters do not take up registers. Examples:
4332 // struct { } a;
4333 // union { } b;
4334 // int c[0];
4335 // etc. However, we have to provide a place-holder in InVals, so
4336 // pretend we have an 8-byte item at the current address for that
4337 // purpose.
4338 if (!ObjSize) {
4339 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4340 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4341 InVals.push_back(FIN);
4342 continue;
4343 }
4344
4345 // Create a stack object covering all stack doublewords occupied
4346 // by the argument. If the argument is (fully or partially) on
4347 // the stack, or if the argument is fully in registers but the
4348 // caller has allocated the parameter save anyway, we can refer
4349 // directly to the caller's stack frame. Otherwise, create a
4350 // local copy in our own frame.
4351 int FI;
4352 if (HasParameterArea ||
4353 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4354 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4355 else
4356 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4357 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4358
4359 // Handle aggregates smaller than 8 bytes.
4360 if (ObjSize < PtrByteSize) {
4361 // The value of the object is its address, which differs from the
4362 // address of the enclosing doubleword on big-endian systems.
4363 SDValue Arg = FIN;
4364 if (!isLittleEndian) {
4365 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4366 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4367 }
4368 InVals.push_back(Arg);
4369
4370 if (GPR_idx != Num_GPR_Regs) {
4371 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4372 FuncInfo->addLiveInAttr(VReg, Flags);
4373 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4374 SDValue Store;
4375
4376 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4377 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4378 (ObjSize == 2 ? MVT::i16 : MVT::i32));
4379 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4380 MachinePointerInfo(&*FuncArg), ObjType);
4381 } else {
4382 // For sizes that don't fit a truncating store (3, 5, 6, 7),
4383 // store the whole register as-is to the parameter save area
4384 // slot.
4385 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4386 MachinePointerInfo(&*FuncArg));
4387 }
4388
4389 MemOps.push_back(Store);
4390 }
4391 // Whether we copied from a register or not, advance the offset
4392 // into the parameter save area by a full doubleword.
4393 ArgOffset += PtrByteSize;
4394 continue;
4395 }
4396
4397 // The value of the object is its address, which is the address of
4398 // its first stack doubleword.
4399 InVals.push_back(FIN);
4400
4401 // Store whatever pieces of the object are in registers to memory.
4402 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4403 if (GPR_idx == Num_GPR_Regs)
4404 break;
4405
4406 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4407 FuncInfo->addLiveInAttr(VReg, Flags);
4408 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4409 SDValue Addr = FIN;
4410 if (j) {
4411 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4412 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4413 }
4414 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4415 MachinePointerInfo(&*FuncArg, j));
4416 MemOps.push_back(Store);
4417 ++GPR_idx;
4418 }
4419 ArgOffset += ArgSize;
4420 continue;
4421 }
4422
4423 switch (ObjectVT.getSimpleVT().SimpleTy) {
4424 default: llvm_unreachable("Unhandled argument type!")::llvm::llvm_unreachable_internal("Unhandled argument type!",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4424)
;
4425 case MVT::i1:
4426 case MVT::i32:
4427 case MVT::i64:
4428 if (Flags.isNest()) {
4429 // The 'nest' parameter, if any, is passed in R11.
4430 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4431 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4432
4433 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4434 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4435
4436 break;
4437 }
4438
4439 // These can be scalar arguments or elements of an integer array type
4440 // passed directly. Clang may use those instead of "byval" aggregate
4441 // types to avoid forcing arguments to memory unnecessarily.
4442 if (GPR_idx != Num_GPR_Regs) {
4443 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4444 FuncInfo->addLiveInAttr(VReg, Flags);
4445 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4446
4447 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4448 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4449 // value to MVT::i64 and then truncate to the correct register size.
4450 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4451 } else {
4452 if (CallConv == CallingConv::Fast)
4453 ComputeArgOffset();
4454
4455 needsLoad = true;
4456 ArgSize = PtrByteSize;
4457 }
4458 if (CallConv != CallingConv::Fast || needsLoad)
4459 ArgOffset += 8;
4460 break;
4461
4462 case MVT::f32:
4463 case MVT::f64:
4464 // These can be scalar arguments or elements of a float array type
4465 // passed directly. The latter are used to implement ELFv2 homogenous
4466 // float aggregates.
4467 if (FPR_idx != Num_FPR_Regs) {
4468 unsigned VReg;
4469
4470 if (ObjectVT == MVT::f32)
4471 VReg = MF.addLiveIn(FPR[FPR_idx],
4472 Subtarget.hasP8Vector()
4473 ? &PPC::VSSRCRegClass
4474 : &PPC::F4RCRegClass);
4475 else
4476 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4477 ? &PPC::VSFRCRegClass
4478 : &PPC::F8RCRegClass);
4479
4480 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4481 ++FPR_idx;
4482 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4483 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4484 // once we support fp <-> gpr moves.
4485
4486 // This can only ever happen in the presence of f32 array types,
4487 // since otherwise we never run out of FPRs before running out
4488 // of GPRs.
4489 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4490 FuncInfo->addLiveInAttr(VReg, Flags);
4491 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4492
4493 if (ObjectVT == MVT::f32) {
4494 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4495 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4496 DAG.getConstant(32, dl, MVT::i32));
4497 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4498 }
4499
4500 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4501 } else {
4502 if (CallConv == CallingConv::Fast)
4503 ComputeArgOffset();
4504
4505 needsLoad = true;
4506 }
4507
4508 // When passing an array of floats, the array occupies consecutive
4509 // space in the argument area; only round up to the next doubleword
4510 // at the end of the array. Otherwise, each float takes 8 bytes.
4511 if (CallConv != CallingConv::Fast || needsLoad) {
4512 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4513 ArgOffset += ArgSize;
4514 if (Flags.isInConsecutiveRegsLast())
4515 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4516 }
4517 break;
4518 case MVT::v4f32:
4519 case MVT::v4i32:
4520 case MVT::v8i16:
4521 case MVT::v16i8:
4522 case MVT::v2f64:
4523 case MVT::v2i64:
4524 case MVT::v1i128:
4525 case MVT::f128:
4526 // These can be scalar arguments or elements of a vector array type
4527 // passed directly. The latter are used to implement ELFv2 homogenous
4528 // vector aggregates.
4529 if (VR_idx != Num_VR_Regs) {
4530 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4531 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4532 ++VR_idx;
4533 } else {
4534 if (CallConv == CallingConv::Fast)
4535 ComputeArgOffset();
4536 needsLoad = true;
4537 }
4538 if (CallConv != CallingConv::Fast || needsLoad)
4539 ArgOffset += 16;
4540 break;
4541 }
4542
4543 // We need to load the argument to a virtual register if we determined
4544 // above that we ran out of physical registers of the appropriate type.
4545 if (needsLoad) {
4546 if (ObjSize < ArgSize && !isLittleEndian)
4547 CurArgOffset += ArgSize - ObjSize;
4548 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4549 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4550 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4551 }
4552
4553 InVals.push_back(ArgVal);
4554 }
4555
4556 // Area that is at least reserved in the caller of this function.
4557 unsigned MinReservedArea;
4558 if (HasParameterArea)
4559 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4560 else
4561 MinReservedArea = LinkageSize;
4562
4563 // Set the size that is at least reserved in caller of this function. Tail
4564 // call optimized functions' reserved stack space needs to be aligned so that
4565 // taking the difference between two stack areas will result in an aligned
4566 // stack.
4567 MinReservedArea =
4568 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4569 FuncInfo->setMinReservedArea(MinReservedArea);
4570
4571 // If the function takes variable number of arguments, make a frame index for
4572 // the start of the first vararg value... for expansion of llvm.va_start.
4573 // On ELFv2ABI spec, it writes:
4574 // C programs that are intended to be *portable* across different compilers
4575 // and architectures must use the header file <stdarg.h> to deal with variable
4576 // argument lists.
4577 if (isVarArg && MFI.hasVAStart()) {
4578 int Depth = ArgOffset;
4579
4580 FuncInfo->setVarArgsFrameIndex(
4581 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4582 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4583
4584 // If this function is vararg, store any remaining integer argument regs
4585 // to their spots on the stack so that they may be loaded by dereferencing
4586 // the result of va_next.
4587 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4588 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4589 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4590 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4591 SDValue Store =
4592 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4593 MemOps.push_back(Store);
4594 // Increment the address by four for the next argument to store
4595 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4596 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4597 }
4598 }
4599
4600 if (!MemOps.empty())
4601 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4602
4603 return Chain;
4604}
4605
4606/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4607/// adjusted to accommodate the arguments for the tailcall.
4608static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4609 unsigned ParamSize) {
4610
4611 if (!isTailCall) return 0;
4612
4613 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4614 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4615 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4616 // Remember only if the new adjustment is bigger.
4617 if (SPDiff < FI->getTailCallSPDelta())
4618 FI->setTailCallSPDelta(SPDiff);
4619
4620 return SPDiff;
4621}
4622
4623static bool isFunctionGlobalAddress(SDValue Callee);
4624
4625static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4626 const TargetMachine &TM) {
4627 // It does not make sense to call callsShareTOCBase() with a caller that
4628 // is PC Relative since PC Relative callers do not have a TOC.
4629#ifndef NDEBUG
4630 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4631 assert(!STICaller->isUsingPCRelativeCalls() &&(static_cast <bool> (!STICaller->isUsingPCRelativeCalls
() && "PC Relative callers do not have a TOC and cannot share a TOC Base"
) ? void (0) : __assert_fail ("!STICaller->isUsingPCRelativeCalls() && \"PC Relative callers do not have a TOC and cannot share a TOC Base\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4632, __extension__ __PRETTY_FUNCTION__))
4632 "PC Relative callers do not have a TOC and cannot share a TOC Base")(static_cast <bool> (!STICaller->isUsingPCRelativeCalls
() && "PC Relative callers do not have a TOC and cannot share a TOC Base"
) ? void (0) : __assert_fail ("!STICaller->isUsingPCRelativeCalls() && \"PC Relative callers do not have a TOC and cannot share a TOC Base\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4632, __extension__ __PRETTY_FUNCTION__))
;
4633#endif
4634
4635 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4636 // don't have enough information to determine if the caller and callee share
4637 // the same TOC base, so we have to pessimistically assume they don't for
4638 // correctness.
4639 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4640 if (!G)
4641 return false;
4642
4643 const GlobalValue *GV = G->getGlobal();
4644
4645 // If the callee is preemptable, then the static linker will use a plt-stub
4646 // which saves the toc to the stack, and needs a nop after the call
4647 // instruction to convert to a toc-restore.
4648 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4649 return false;
4650
4651 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4652 // We may need a TOC restore in the situation where the caller requires a
4653 // valid TOC but the callee is PC Relative and does not.
4654 const Function *F = dyn_cast<Function>(GV);
4655 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4656
4657 // If we have an Alias we can try to get the function from there.
4658 if (Alias) {
4659 const GlobalObject *GlobalObj = Alias->getBaseObject();
4660 F = dyn_cast<Function>(GlobalObj);
4661 }
4662
4663 // If we still have no valid function pointer we do not have enough
4664 // information to determine if the callee uses PC Relative calls so we must
4665 // assume that it does.
4666 if (!F)
4667 return false;
4668
4669 // If the callee uses PC Relative we cannot guarantee that the callee won't
4670 // clobber the TOC of the caller and so we must assume that the two
4671 // functions do not share a TOC base.
4672 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4673 if (STICallee->isUsingPCRelativeCalls())
4674 return false;
4675
4676 // If the GV is not a strong definition then we need to assume it can be
4677 // replaced by another function at link time. The function that replaces
4678 // it may not share the same TOC as the caller since the callee may be
4679 // replaced by a PC Relative version of the same function.
4680 if (!GV->isStrongDefinitionForLinker())
4681 return false;
4682
4683 // The medium and large code models are expected to provide a sufficiently
4684 // large TOC to provide all data addressing needs of a module with a
4685 // single TOC.
4686 if (CodeModel::Medium == TM.getCodeModel() ||
4687 CodeModel::Large == TM.getCodeModel())
4688 return true;
4689
4690 // Any explicitly-specified sections and section prefixes must also match.
4691 // Also, if we're using -ffunction-sections, then each function is always in
4692 // a different section (the same is true for COMDAT functions).
4693 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4694 GV->getSection() != Caller->getSection())
4695 return false;
4696 if (const auto *F = dyn_cast<Function>(GV)) {
4697 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4698 return false;
4699 }
4700
4701 return true;
4702}
4703
4704static bool
4705needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4706 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4707 assert(Subtarget.is64BitELFABI())(static_cast <bool> (Subtarget.is64BitELFABI()) ? void (
0) : __assert_fail ("Subtarget.is64BitELFABI()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 4707, __extension__ __PRETTY_FUNCTION__))
;
4708
4709 const unsigned PtrByteSize = 8;
4710 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4711
4712 static const MCPhysReg GPR[] = {
4713 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4714 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4715 };
4716 static const MCPhysReg VR[] = {
4717 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4718 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4719 };
4720
4721 const unsigned NumGPRs = array_lengthof(GPR);
4722 const unsigned NumFPRs = 13;
4723 const unsigned NumVRs = array_lengthof(VR);
4724 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4725
4726 unsigned NumBytes = LinkageSize;
4727 unsigned AvailableFPRs = NumFPRs;
4728 unsigned AvailableVRs = NumVRs;
4729
4730 for (const ISD::OutputArg& Param : Outs) {
4731 if (Param.Flags.isNest()) continue;
4732
4733 if (CalculateStackSlotUsed(Subtarget, Param.VT, Param.ArgVT, Param.Flags,
4734 PtrByteSize, LinkageSize, ParamAreaSize,
4735 NumBytes, AvailableFPRs, AvailableVRs))
4736 return true;
4737 }
4738 return false;
4739}
4740
4741static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4742 if (CB.arg_size() != CallerFn->arg_size())
4743 return false;
4744
4745 auto CalleeArgIter = CB.arg_begin();
4746 auto CalleeArgEnd = CB.arg_end();
4747 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4748
4749 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4750 const Value* CalleeArg = *CalleeArgIter;
4751 const Value* CallerArg = &(*CallerArgIter);
4752 if (CalleeArg == CallerArg)
4753 continue;
4754
4755 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4756 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4757 // }
4758 // 1st argument of callee is undef and has the same type as caller.
4759 if (CalleeArg->getType() == CallerArg->getType() &&
4760 isa<UndefValue>(CalleeArg))
4761 continue;
4762
4763 return false;
4764 }
4765
4766 return true;
4767}
4768
4769// Returns true if TCO is possible between the callers and callees
4770// calling conventions.
4771static bool
4772areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4773 CallingConv::ID CalleeCC) {
4774 // Tail calls are possible with fastcc and ccc.
4775 auto isTailCallableCC = [] (CallingConv::ID CC){
4776 return CC == CallingConv::C || CC == CallingConv::Fast;
4777 };
4778 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4779 return false;
4780
4781 // We can safely tail call both fastcc and ccc callees from a c calling
4782 // convention caller. If the caller is fastcc, we may have less stack space
4783 // than a non-fastcc caller with the same signature so disable tail-calls in
4784 // that case.
4785 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4786}
4787
4788bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4789 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4790 const SmallVectorImpl<ISD::OutputArg> &Outs,
4791 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4792 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4793
4794 if (DisableSCO && !TailCallOpt) return false;
4795
4796 // Variadic argument functions are not supported.
4797 if (isVarArg) return false;
4798
4799 auto &Caller = DAG.getMachineFunction().getFunction();
4800 // Check that the calling conventions are compatible for tco.
4801 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4802 return false;
4803
4804 // Caller contains any byval parameter is not supported.
4805 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4806 return false;
4807
4808 // Callee contains any byval parameter is not supported, too.
4809 // Note: This is a quick work around, because in some cases, e.g.
4810 // caller's stack size > callee's stack size, we are still able to apply
4811 // sibling call optimization. For example, gcc is able to do SCO for caller1
4812 // in the following example, but not for caller2.
4813 // struct test {
4814 // long int a;
4815 // char ary[56];
4816 // } gTest;
4817 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
4818 // b->a = v.a;
4819 // return 0;
4820 // }
4821 // void caller1(struct test a, struct test c, struct test *b) {
4822 // callee(gTest, b); }
4823 // void caller2(struct test *b) { callee(gTest, b); }
4824 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4825 return false;
4826
4827 // If callee and caller use different calling conventions, we cannot pass
4828 // parameters on stack since offsets for the parameter area may be different.
4829 if (Caller.getCallingConv() != CalleeCC &&
4830 needStackSlotPassParameters(Subtarget, Outs))
4831 return false;
4832
4833 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4834 // the caller and callee share the same TOC for TCO/SCO. If the caller and
4835 // callee potentially have different TOC bases then we cannot tail call since
4836 // we need to restore the TOC pointer after the call.
4837 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4838 // We cannot guarantee this for indirect calls or calls to external functions.
4839 // When PC-Relative addressing is used, the concept of the TOC is no longer
4840 // applicable so this check is not required.
4841 // Check first for indirect calls.
4842 if (!Subtarget.isUsingPCRelativeCalls() &&
4843 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4844 return false;
4845
4846 // Check if we share the TOC base.
4847 if (!Subtarget.isUsingPCRelativeCalls() &&
4848 !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4849 return false;
4850
4851 // TCO allows altering callee ABI, so we don't have to check further.
4852 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4853 return true;
4854
4855 if (DisableSCO) return false;
4856
4857 // If callee use the same argument list that caller is using, then we can
4858 // apply SCO on this case. If it is not, then we need to check if callee needs
4859 // stack for passing arguments.
4860 // PC Relative tail calls may not have a CallBase.
4861 // If there is no CallBase we cannot verify if we have the same argument
4862 // list so assume that we don't have the same argument list.
4863 if (CB && !hasSameArgumentList(&Caller, *CB) &&
4864 needStackSlotPassParameters(Subtarget, Outs))
4865 return false;
4866 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4867 return false;
4868
4869 return true;
4870}
4871
4872/// IsEligibleForTailCallOptimization - Check whether the call is eligible
4873/// for tail call optimization. Targets which want to do tail call
4874/// optimization should implement this function.
4875bool
4876PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4877 CallingConv::ID CalleeCC,
4878 bool isVarArg,
4879 const SmallVectorImpl<ISD::InputArg> &Ins,
4880 SelectionDAG& DAG) const {
4881 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4882 return false;
4883
4884 // Variable argument functions are not supported.
4885 if (isVarArg)
4886 return false;
4887
4888 MachineFunction &MF = DAG.getMachineFunction();
4889 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4890 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4891 // Functions containing by val parameters are not supported.
4892 for (unsigned i = 0; i != Ins.size(); i++) {
4893 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4894 if (Flags.isByVal()) return false;
4895 }
4896
4897 // Non-PIC/GOT tail calls are supported.
4898 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4899 return true;
4900
4901 // At the moment we can only do local tail calls (in same module, hidden
4902 // or protected) if we are generating PIC.
4903 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4904 return G->getGlobal()->hasHiddenVisibility()
4905 || G->getGlobal()->hasProtectedVisibility();
4906 }
4907
4908 return false;
4909}
4910
4911/// isCallCompatibleAddress - Return the immediate to use if the specified
4912/// 32-bit value is representable in the immediate field of a BxA instruction.
4913static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4914 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4915 if (!C) return nullptr;
4916
4917 int Addr = C->getZExtValue();
4918 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4919 SignExtend32<26>(Addr) != Addr)
4920 return nullptr; // Top 6 bits have to be sext of immediate.
4921
4922 return DAG
4923 .getConstant(
4924 (int)C->getZExtValue() >> 2, SDLoc(Op),
4925 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4926 .getNode();
4927}
4928
4929namespace {
4930
4931struct TailCallArgumentInfo {
4932 SDValue Arg;
4933 SDValue FrameIdxOp;
4934 int FrameIdx = 0;
4935
4936 TailCallArgumentInfo() = default;
4937};
4938
4939} // end anonymous namespace
4940
4941/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4942static void StoreTailCallArgumentsToStackSlot(
4943 SelectionDAG &DAG, SDValue Chain,
4944 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4945 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4946 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4947 SDValue Arg = TailCallArgs[i].Arg;
4948 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4949 int FI = TailCallArgs[i].FrameIdx;
4950 // Store relative to framepointer.
4951 MemOpChains.push_back(DAG.getStore(
4952 Chain, dl, Arg, FIN,
4953 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4954 }
4955}
4956
4957/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4958/// the appropriate stack slot for the tail call optimized function call.
4959static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4960 SDValue OldRetAddr, SDValue OldFP,
4961 int SPDiff, const SDLoc &dl) {
4962 if (SPDiff) {
4963 // Calculate the new stack slot for the return address.
4964 MachineFunction &MF = DAG.getMachineFunction();
4965 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4966 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4967 bool isPPC64 = Subtarget.isPPC64();
4968 int SlotSize = isPPC64 ? 8 : 4;
4969 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4970 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4971 NewRetAddrLoc, true);
4972 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4973 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4974 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4975 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4976 }
4977 return Chain;
4978}
4979
4980/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4981/// the position of the argument.
4982static void
4983CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4984 SDValue Arg, int SPDiff, unsigned ArgOffset,
4985 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4986 int Offset = ArgOffset + SPDiff;
4987 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4988 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4989 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4990 SDValue FIN = DAG.getFrameIndex(FI, VT);
4991 TailCallArgumentInfo Info;
4992 Info.Arg = Arg;
4993 Info.FrameIdxOp = FIN;
4994 Info.FrameIdx = FI;
4995 TailCallArguments.push_back(Info);
4996}
4997
4998/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4999/// stack slot. Returns the chain as result and the loaded frame pointers in
5000/// LROpOut/FPOpout. Used when tail calling.
5001SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5002 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5003 SDValue &FPOpOut, const SDLoc &dl) const {
5004 if (SPDiff) {
5005 // Load the LR and FP stack slot for later adjusting.
5006 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5007 LROpOut = getReturnAddrFrameIndex(DAG);
5008 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5009 Chain = SDValue(LROpOut.getNode(), 1);
5010 }
5011 return Chain;
5012}
5013
5014/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5015/// by "Src" to address "Dst" of size "Size". Alignment information is
5016/// specified by the specific parameter attribute. The copy will be passed as
5017/// a byval function parameter.
5018/// Sometimes what we are copying is the end of a larger object, the part that
5019/// does not fit in registers.
5020static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5021 SDValue Chain, ISD::ArgFlagsTy Flags,
5022 SelectionDAG &DAG, const SDLoc &dl) {
5023 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5024 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5025 Flags.getNonZeroByValAlign(), false, false, false,
5026 MachinePointerInfo(), MachinePointerInfo());
5027}
5028
5029/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5030/// tail calls.
5031static void LowerMemOpCallTo(
5032 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5033 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5034 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5035 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5036 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5037 if (!isTailCall) {
5038 if (isVector) {
5039 SDValue StackPtr;
5040 if (isPPC64)
5041 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5042 else
5043 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5044 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5045 DAG.getConstant(ArgOffset, dl, PtrVT));
5046 }
5047 MemOpChains.push_back(
5048 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5049 // Calculate and remember argument location.
5050 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5051 TailCallArguments);
5052}
5053
5054static void
5055PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5056 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5057 SDValue FPOp,
5058 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5059 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5060 // might overwrite each other in case of tail call optimization.
5061 SmallVector<SDValue, 8> MemOpChains2;
5062 // Do not flag preceding copytoreg stuff together with the following stuff.
5063 InFlag = SDValue();
5064 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5065 MemOpChains2, dl);
5066 if (!MemOpChains2.empty())
5067 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5068
5069 // Store the return address to the appropriate stack slot.
5070 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5071
5072 // Emit callseq_end just before tailcall node.
5073 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5074 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5075 InFlag = Chain.getValue(1);
5076}
5077
5078// Is this global address that of a function that can be called by name? (as
5079// opposed to something that must hold a descriptor for an indirect call).
5080static bool isFunctionGlobalAddress(SDValue Callee) {
5081 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5082 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5083 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5084 return false;
5085
5086 return G->getGlobal()->getValueType()->isFunctionTy();
5087 }
5088
5089 return false;
5090}
5091
5092SDValue PPCTargetLowering::LowerCallResult(
5093 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5094 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5095 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5096 SmallVector<CCValAssign, 16> RVLocs;
5097 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5098 *DAG.getContext());
5099
5100 CCRetInfo.AnalyzeCallResult(
5101 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5102 ? RetCC_PPC_Cold
5103 : RetCC_PPC);
5104
5105 // Copy all of the result registers out of their specified physreg.
5106 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5107 CCValAssign &VA = RVLocs[i];
5108 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5108, __extension__ __PRETTY_FUNCTION__))
;
5109
5110 SDValue Val;
5111
5112 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5113 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5114 InFlag);
5115 Chain = Lo.getValue(1);
5116 InFlag = Lo.getValue(2);
5117 VA = RVLocs[++i]; // skip ahead to next loc
5118 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5119 InFlag);
5120 Chain = Hi.getValue(1);
5121 InFlag = Hi.getValue(2);
5122 if (!Subtarget.isLittleEndian())
5123 std::swap (Lo, Hi);
5124 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5125 } else {
5126 Val = DAG.getCopyFromReg(Chain, dl,
5127 VA.getLocReg(), VA.getLocVT(), InFlag);
5128 Chain = Val.getValue(1);
5129 InFlag = Val.getValue(2);
5130 }
5131
5132 switch (VA.getLocInfo()) {
5133 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5133)
;
5134 case CCValAssign::Full: break;
5135 case CCValAssign::AExt:
5136 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5137 break;
5138 case CCValAssign::ZExt:
5139 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5140 DAG.getValueType(VA.getValVT()));
5141 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5142 break;
5143 case CCValAssign::SExt:
5144 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5145 DAG.getValueType(VA.getValVT()));
5146 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5147 break;
5148 }
5149
5150 InVals.push_back(Val);
5151 }
5152
5153 return Chain;
5154}
5155
5156static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5157 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5158 // PatchPoint calls are not indirect.
5159 if (isPatchPoint)
5160 return false;
5161
5162 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5163 return false;
5164
5165 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5166 // becuase the immediate function pointer points to a descriptor instead of
5167 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5168 // pointer immediate points to the global entry point, while the BLA would
5169 // need to jump to the local entry point (see rL211174).
5170 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5171 isBLACompatibleAddress(Callee, DAG))
5172 return false;
5173
5174 return true;
5175}
5176
5177// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5178static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5179 return Subtarget.isAIXABI() ||
5180 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5181}
5182
5183static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5184 const Function &Caller,
5185 const SDValue &Callee,
5186 const PPCSubtarget &Subtarget,
5187 const TargetMachine &TM) {
5188 if (CFlags.IsTailCall)
5189 return PPCISD::TC_RETURN;
5190
5191 // This is a call through a function pointer.
5192 if (CFlags.IsIndirect) {
5193 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5194 // indirect calls. The save of the caller's TOC pointer to the stack will be
5195 // inserted into the DAG as part of call lowering. The restore of the TOC
5196 // pointer is modeled by using a pseudo instruction for the call opcode that
5197 // represents the 2 instruction sequence of an indirect branch and link,
5198 // immediately followed by a load of the TOC pointer from the the stack save
5199 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5200 // as it is not saved or used.
5201 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5202 : PPCISD::BCTRL;
5203 }
5204
5205 if (Subtarget.isUsingPCRelativeCalls()) {
5206 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.")(static_cast <bool> (Subtarget.is64BitELFABI() &&
"PC Relative is only on ELF ABI.") ? void (0) : __assert_fail
("Subtarget.is64BitELFABI() && \"PC Relative is only on ELF ABI.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5206, __extension__ __PRETTY_FUNCTION__))
;
5207 return PPCISD::CALL_NOTOC;
5208 }
5209
5210 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5211 // immediately following the call instruction if the caller and callee may
5212 // have different TOC bases. At link time if the linker determines the calls
5213 // may not share a TOC base, the call is redirected to a trampoline inserted
5214 // by the linker. The trampoline will (among other things) save the callers
5215 // TOC pointer at an ABI designated offset in the linkage area and the linker
5216 // will rewrite the nop to be a load of the TOC pointer from the linkage area
5217 // into gpr2.
5218 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5219 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5220 : PPCISD::CALL_NOP;
5221
5222 return PPCISD::CALL;
5223}
5224
5225static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5226 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5227 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5228 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5229 return SDValue(Dest, 0);
5230
5231 // Returns true if the callee is local, and false otherwise.
5232 auto isLocalCallee = [&]() {
5233 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5234 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5235 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5236
5237 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5238 !dyn_cast_or_null<GlobalIFunc>(GV);
5239 };
5240
5241 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5242 // a static relocation model causes some versions of GNU LD (2.17.50, at
5243 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5244 // built with secure-PLT.
5245 bool UsePlt =
5246 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5247 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5248
5249 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5250 const TargetMachine &TM = Subtarget.getTargetMachine();
5251 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5252 MCSymbolXCOFF *S =
5253 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5254
5255 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5256 return DAG.getMCSymbol(S, PtrVT);
5257 };
5258
5259 if (isFunctionGlobalAddress(Callee)) {
5260 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5261
5262 if (Subtarget.isAIXABI()) {
5263 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.")(static_cast <bool> (!isa<GlobalIFunc>(GV) &&
"IFunc is not supported on AIX.") ? void (0) : __assert_fail
("!isa<GlobalIFunc>(GV) && \"IFunc is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5263, __extension__ __PRETTY_FUNCTION__))
;
5264 return getAIXFuncEntryPointSymbolSDNode(GV);
5265 }
5266 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5267 UsePlt ? PPCII::MO_PLT : 0);
5268 }
5269
5270 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5271 const char *SymName = S->getSymbol();
5272 if (Subtarget.isAIXABI()) {
5273 // If there exists a user-declared function whose name is the same as the
5274 // ExternalSymbol's, then we pick up the user-declared version.
5275 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5276 if (const Function *F =
5277 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5278 return getAIXFuncEntryPointSymbolSDNode(F);
5279
5280 // On AIX, direct function calls reference the symbol for the function's
5281 // entry point, which is named by prepending a "." before the function's
5282 // C-linkage name. A Qualname is returned here because an external
5283 // function entry point is a csect with XTY_ER property.
5284 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5285 auto &Context = DAG.getMachineFunction().getMMI().getContext();
5286 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5287 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5288 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5289 return Sec->getQualNameSymbol();
5290 };
5291
5292 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5293 }
5294 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5295 UsePlt ? PPCII::MO_PLT : 0);
5296 }
5297
5298 // No transformation needed.
5299 assert(Callee.getNode() && "What no callee?")(static_cast <bool> (Callee.getNode() && "What no callee?"
) ? void (0) : __assert_fail ("Callee.getNode() && \"What no callee?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5299, __extension__ __PRETTY_FUNCTION__))
;
5300 return Callee;
5301}
5302
5303static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5304 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&(static_cast <bool> (CallSeqStart.getOpcode() == ISD::CALLSEQ_START
&& "Expected a CALLSEQ_STARTSDNode.") ? void (0) : __assert_fail
("CallSeqStart.getOpcode() == ISD::CALLSEQ_START && \"Expected a CALLSEQ_STARTSDNode.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5305, __extension__ __PRETTY_FUNCTION__))
5305 "Expected a CALLSEQ_STARTSDNode.")(static_cast <bool> (CallSeqStart.getOpcode() == ISD::CALLSEQ_START
&& "Expected a CALLSEQ_STARTSDNode.") ? void (0) : __assert_fail
("CallSeqStart.getOpcode() == ISD::CALLSEQ_START && \"Expected a CALLSEQ_STARTSDNode.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5305, __extension__ __PRETTY_FUNCTION__))
;
5306
5307 // The last operand is the chain, except when the node has glue. If the node
5308 // has glue, then the last operand is the glue, and the chain is the second
5309 // last operand.
5310 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5311 if (LastValue.getValueType() != MVT::Glue)
5312 return LastValue;
5313
5314 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5315}
5316
5317// Creates the node that moves a functions address into the count register
5318// to prepare for an indirect call instruction.
5319static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5320 SDValue &Glue, SDValue &Chain,
5321 const SDLoc &dl) {
5322 SDValue MTCTROps[] = {Chain, Callee, Glue};
5323 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5324 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5325 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5326 // The glue is the second value produced.
5327 Glue = Chain.getValue(1);
5328}
5329
5330static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5331 SDValue &Glue, SDValue &Chain,
5332 SDValue CallSeqStart,
5333 const CallBase *CB, const SDLoc &dl,
5334 bool hasNest,
5335 const PPCSubtarget &Subtarget) {
5336 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5337 // entry point, but to the function descriptor (the function entry point
5338 // address is part of the function descriptor though).
5339 // The function descriptor is a three doubleword structure with the
5340 // following fields: function entry point, TOC base address and
5341 // environment pointer.
5342 // Thus for a call through a function pointer, the following actions need
5343 // to be performed:
5344 // 1. Save the TOC of the caller in the TOC save area of its stack
5345 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5346 // 2. Load the address of the function entry point from the function
5347 // descriptor.
5348 // 3. Load the TOC of the callee from the function descriptor into r2.
5349 // 4. Load the environment pointer from the function descriptor into
5350 // r11.
5351 // 5. Branch to the function entry point address.
5352 // 6. On return of the callee, the TOC of the caller needs to be
5353 // restored (this is done in FinishCall()).
5354 //
5355 // The loads are scheduled at the beginning of the call sequence, and the
5356 // register copies are flagged together to ensure that no other
5357 // operations can be scheduled in between. E.g. without flagging the
5358 // copies together, a TOC access in the caller could be scheduled between
5359 // the assignment of the callee TOC and the branch to the callee, which leads
5360 // to incorrect code.
5361
5362 // Start by loading the function address from the descriptor.
5363 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5364 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5365 ? (MachineMemOperand::MODereferenceable |
5366 MachineMemOperand::MOInvariant)
5367 : MachineMemOperand::MONone;
5368
5369 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5370
5371 // Registers used in building the DAG.
5372 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5373 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5374
5375 // Offsets of descriptor members.
5376 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5377 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5378
5379 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5380 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5381
5382 // One load for the functions entry point address.
5383 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5384 Alignment, MMOFlags);
5385
5386 // One for loading the TOC anchor for the module that contains the called
5387 // function.
5388 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5389 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5390 SDValue TOCPtr =
5391 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5392 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5393
5394 // One for loading the environment pointer.
5395 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5396 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5397 SDValue LoadEnvPtr =
5398 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5399 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5400
5401
5402 // Then copy the newly loaded TOC anchor to the TOC pointer.
5403 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5404 Chain = TOCVal.getValue(0);
5405 Glue = TOCVal.getValue(1);
5406
5407 // If the function call has an explicit 'nest' parameter, it takes the
5408 // place of the environment pointer.
5409 assert((!hasNest || !Subtarget.isAIXABI()) &&(static_cast <bool> ((!hasNest || !Subtarget.isAIXABI()
) && "Nest parameter is not supported on AIX.") ? void
(0) : __assert_fail ("(!hasNest || !Subtarget.isAIXABI()) && \"Nest parameter is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5410, __extension__ __PRETTY_FUNCTION__))
5410 "Nest parameter is not supported on AIX.")(static_cast <bool> ((!hasNest || !Subtarget.isAIXABI()
) && "Nest parameter is not supported on AIX.") ? void
(0) : __assert_fail ("(!hasNest || !Subtarget.isAIXABI()) && \"Nest parameter is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5410, __extension__ __PRETTY_FUNCTION__))
;
5411 if (!hasNest) {
5412 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5413 Chain = EnvVal.getValue(0);
5414 Glue = EnvVal.getValue(1);
5415 }
5416
5417 // The rest of the indirect call sequence is the same as the non-descriptor
5418 // DAG.
5419 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5420}
5421
5422static void
5423buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5424 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5425 SelectionDAG &DAG,
5426 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5427 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5428 const PPCSubtarget &Subtarget) {
5429 const bool IsPPC64 = Subtarget.isPPC64();
5430 // MVT for a general purpose register.
5431 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5432
5433 // First operand is always the chain.
5434 Ops.push_back(Chain);
5435
5436 // If it's a direct call pass the callee as the second operand.
5437 if (!CFlags.IsIndirect)
5438 Ops.push_back(Callee);
5439 else {
5440 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.")(static_cast <bool> (!CFlags.IsPatchPoint && "Patch point calls are not indirect."
) ? void (0) : __assert_fail ("!CFlags.IsPatchPoint && \"Patch point calls are not indirect.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5440, __extension__ __PRETTY_FUNCTION__))
;
5441
5442 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5443 // on the stack (this would have been done in `LowerCall_64SVR4` or
5444 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5445 // represents both the indirect branch and a load that restores the TOC
5446 // pointer from the linkage area. The operand for the TOC restore is an add
5447 // of the TOC save offset to the stack pointer. This must be the second
5448 // operand: after the chain input but before any other variadic arguments.
5449 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5450 // saved or used.
5451 if (isTOCSaveRestoreRequired(Subtarget)) {
5452 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5453
5454 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5455 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5456 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5457 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5458 Ops.push_back(AddTOC);
5459 }
5460
5461 // Add the register used for the environment pointer.
5462 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5463 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5464 RegVT));
5465
5466
5467 // Add CTR register as callee so a bctr can be emitted later.
5468 if (CFlags.IsTailCall)
5469 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5470 }
5471
5472 // If this is a tail call add stack pointer delta.
5473 if (CFlags.IsTailCall)
5474 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5475
5476 // Add argument registers to the end of the list so that they are known live
5477 // into the call.
5478 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5479 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5480 RegsToPass[i].second.getValueType()));
5481
5482 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5483 // no way to mark dependencies as implicit here.
5484 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5485 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5486 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5487 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5488
5489 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5490 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5491 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5492
5493 // Add a register mask operand representing the call-preserved registers.
5494 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5495 const uint32_t *Mask =
5496 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5497 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5497, __extension__ __PRETTY_FUNCTION__))
;
5498 Ops.push_back(DAG.getRegisterMask(Mask));
5499
5500 // If the glue is valid, it is the last operand.
5501 if (Glue.getNode())
5502 Ops.push_back(Glue);
5503}
5504
5505SDValue PPCTargetLowering::FinishCall(
5506 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5507 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5508 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5509 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5510 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5511
5512 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5513 Subtarget.isAIXABI())
5514 setUsesTOCBasePtr(DAG);
5515
5516 unsigned CallOpc =
5517 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5518 Subtarget, DAG.getTarget());
5519
5520 if (!CFlags.IsIndirect)
5521 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5522 else if (Subtarget.usesFunctionDescriptors())
5523 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5524 dl, CFlags.HasNest, Subtarget);
5525 else
5526 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5527
5528 // Build the operand list for the call instruction.
5529 SmallVector<SDValue, 8> Ops;
5530 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5531 SPDiff, Subtarget);
5532
5533 // Emit tail call.
5534 if (CFlags.IsTailCall) {
5535 // Indirect tail call when using PC Relative calls do not have the same
5536 // constraints.
5537 assert(((Callee.getOpcode() == ISD::Register &&(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5538 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5539 Callee.getOpcode() == ISD::TargetExternalSymbol ||(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5540 Callee.getOpcode() == ISD::TargetGlobalAddress ||(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5541 isa<ConstantSDNode>(Callee) ||(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5542 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5543 "Expecting a global address, external symbol, absolute value, "(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5544 "register or an indirect tail call when PC Relative calls are "(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
5545 "used.")(static_cast <bool> (((Callee.getOpcode() == ISD::Register
&& cast<RegisterSDNode>(Callee)->getReg() ==
PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol
|| Callee.getOpcode() == ISD::TargetGlobalAddress || isa<
ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget
.isUsingPCRelativeCalls())) && "Expecting a global address, external symbol, absolute value, "
"register or an indirect tail call when PC Relative calls are "
"used.") ? void (0) : __assert_fail ("((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee) || (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && \"Expecting a global address, external symbol, absolute value, \" \"register or an indirect tail call when PC Relative calls are \" \"used.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5545, __extension__ __PRETTY_FUNCTION__))
;
5546 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5547 assert(CallOpc == PPCISD::TC_RETURN &&(static_cast <bool> (CallOpc == PPCISD::TC_RETURN &&
"Unexpected call opcode for a tail call.") ? void (0) : __assert_fail
("CallOpc == PPCISD::TC_RETURN && \"Unexpected call opcode for a tail call.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5548, __extension__ __PRETTY_FUNCTION__))
5548 "Unexpected call opcode for a tail call.")(static_cast <bool> (CallOpc == PPCISD::TC_RETURN &&
"Unexpected call opcode for a tail call.") ? void (0) : __assert_fail
("CallOpc == PPCISD::TC_RETURN && \"Unexpected call opcode for a tail call.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5548, __extension__ __PRETTY_FUNCTION__))
;
5549 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5550 return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5551 }
5552
5553 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5554 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5555 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5556 Glue = Chain.getValue(1);
5557
5558 // When performing tail call optimization the callee pops its arguments off
5559 // the stack. Account for this here so these bytes can be pushed back on in
5560 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5561 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5562 getTargetMachine().Options.GuaranteedTailCallOpt)
5563 ? NumBytes
5564 : 0;
5565
5566 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5567 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5568 Glue, dl);
5569 Glue = Chain.getValue(1);
5570
5571 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5572 DAG, InVals);
5573}
5574
5575SDValue
5576PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5577 SmallVectorImpl<SDValue> &InVals) const {
5578 SelectionDAG &DAG = CLI.DAG;
5579 SDLoc &dl = CLI.DL;
5580 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5581 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5582 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5583 SDValue Chain = CLI.Chain;
5584 SDValue Callee = CLI.Callee;
5585 bool &isTailCall = CLI.IsTailCall;
5586 CallingConv::ID CallConv = CLI.CallConv;
5587 bool isVarArg = CLI.IsVarArg;
5588 bool isPatchPoint = CLI.IsPatchPoint;
5589 const CallBase *CB = CLI.CB;
5590
5591 if (isTailCall) {
5592 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5593 isTailCall = false;
5594 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5595 isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5596 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5597 else
5598 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5599 Ins, DAG);
5600 if (isTailCall) {
5601 ++NumTailCalls;
5602 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5603 ++NumSiblingCalls;
5604
5605 // PC Relative calls no longer guarantee that the callee is a Global
5606 // Address Node. The callee could be an indirect tail call in which
5607 // case the SDValue for the callee could be a load (to load the address
5608 // of a function pointer) or it may be a register copy (to move the
5609 // address of the callee from a function parameter into a virtual
5610 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5611 assert((Subtarget.isUsingPCRelativeCalls() ||(static_cast <bool> ((Subtarget.isUsingPCRelativeCalls(
) || isa<GlobalAddressSDNode>(Callee)) && "Callee should be an llvm::Function object."
) ? void (0) : __assert_fail ("(Subtarget.isUsingPCRelativeCalls() || isa<GlobalAddressSDNode>(Callee)) && \"Callee should be an llvm::Function object.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5613, __extension__ __PRETTY_FUNCTION__))
5612 isa<GlobalAddressSDNode>(Callee)) &&(static_cast <bool> ((Subtarget.isUsingPCRelativeCalls(
) || isa<GlobalAddressSDNode>(Callee)) && "Callee should be an llvm::Function object."
) ? void (0) : __assert_fail ("(Subtarget.isUsingPCRelativeCalls() || isa<GlobalAddressSDNode>(Callee)) && \"Callee should be an llvm::Function object.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5613, __extension__ __PRETTY_FUNCTION__))
5613 "Callee should be an llvm::Function object.")(static_cast <bool> ((Subtarget.isUsingPCRelativeCalls(
) || isa<GlobalAddressSDNode>(Callee)) && "Callee should be an llvm::Function object."
) ? void (0) : __assert_fail ("(Subtarget.isUsingPCRelativeCalls() || isa<GlobalAddressSDNode>(Callee)) && \"Callee should be an llvm::Function object.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5613, __extension__ __PRETTY_FUNCTION__))
;
5614
5615 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { dbgs() << "TCO caller: " << DAG
.getMachineFunction().getName() << "\nTCO callee: "; } }
while (false)
5616 << "\nTCO callee: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { dbgs() << "TCO caller: " << DAG
.getMachineFunction().getName() << "\nTCO callee: "; } }
while (false)
;
5617 LLVM_DEBUG(Callee.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("ppc-lowering")) { Callee.dump(); } } while (false)
;
5618 }
5619 }
5620
5621 if (!isTailCall && CB && CB->isMustTailCall())
5622 report_fatal_error("failed to perform tail call elimination on a call "
5623 "site marked musttail");
5624
5625 // When long calls (i.e. indirect calls) are always used, calls are always
5626 // made via function pointer. If we have a function name, first translate it
5627 // into a pointer.
5628 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5629 !isTailCall)
5630 Callee = LowerGlobalAddress(Callee, DAG);
5631
5632 CallFlags CFlags(
5633 CallConv, isTailCall, isVarArg, isPatchPoint,
5634 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5635 // hasNest
5636 Subtarget.is64BitELFABI() &&
5637 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5638 CLI.NoMerge);
5639
5640 if (Subtarget.isAIXABI())
5641 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5642 InVals, CB);
5643
5644 assert(Subtarget.isSVR4ABI())(static_cast <bool> (Subtarget.isSVR4ABI()) ? void (0) :
__assert_fail ("Subtarget.isSVR4ABI()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5644, __extension__ __PRETTY_FUNCTION__))
;
5645 if (Subtarget.isPPC64())
5646 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5647 InVals, CB);
5648 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5649 InVals, CB);
5650}
5651
5652SDValue PPCTargetLowering::LowerCall_32SVR4(
5653 SDValue Chain, SDValue Callee, CallFlags CFlags,
5654 const SmallVectorImpl<ISD::OutputArg> &Outs,
5655 const SmallVectorImpl<SDValue> &OutVals,
5656 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5657 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5658 const CallBase *CB) const {
5659 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5660 // of the 32-bit SVR4 ABI stack frame layout.
5661
5662 const CallingConv::ID CallConv = CFlags.CallConv;
5663 const bool IsVarArg = CFlags.IsVarArg;
5664 const bool IsTailCall = CFlags.IsTailCall;
5665
5666 assert((CallConv == CallingConv::C ||(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unknown calling convention!") ? void (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5668, __extension__ __PRETTY_FUNCTION__))
5667 CallConv == CallingConv::Cold ||(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unknown calling convention!") ? void (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5668, __extension__ __PRETTY_FUNCTION__))
5668 CallConv == CallingConv::Fast) && "Unknown calling convention!")(static_cast <bool> ((CallConv == CallingConv::C || CallConv
== CallingConv::Cold || CallConv == CallingConv::Fast) &&
"Unknown calling convention!") ? void (0) : __assert_fail ("(CallConv == CallingConv::C || CallConv == CallingConv::Cold || CallConv == CallingConv::Fast) && \"Unknown calling convention!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5668, __extension__ __PRETTY_FUNCTION__))
;
5669
5670 const Align PtrAlign(4);
5671
5672 MachineFunction &MF = DAG.getMachineFunction();
5673
5674 // Mark this function as potentially containing a function that contains a
5675 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5676 // and restoring the callers stack pointer in this functions epilog. This is
5677 // done because by tail calling the called function might overwrite the value
5678 // in this function's (MF) stack pointer stack slot 0(SP).
5679 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5680 CallConv == CallingConv::Fast)
5681 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5682
5683 // Count how many bytes are to be pushed on the stack, including the linkage
5684 // area, parameter list area and the part of the local variable space which
5685 // contains copies of aggregates which are passed by value.
5686
5687 // Assign locations to all of the outgoing arguments.
5688 SmallVector<CCValAssign, 16> ArgLocs;
5689 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5690
5691 // Reserve space for the linkage area on the stack.
5692 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5693 PtrAlign);
5694 if (useSoftFloat())
5695 CCInfo.PreAnalyzeCallOperands(Outs);
5696
5697 if (IsVarArg) {
5698 // Handle fixed and variable vector arguments differently.
5699 // Fixed vector arguments go into registers as long as registers are
5700 // available. Variable vector arguments always go into memory.
5701 unsigned NumArgs = Outs.size();
5702
5703 for (unsigned i = 0; i != NumArgs; ++i) {
5704 MVT ArgVT = Outs[i].VT;
5705 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5706 bool Result;
5707
5708 if (Outs[i].IsFixed) {
5709 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5710 CCInfo);
5711 } else {
5712 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5713 ArgFlags, CCInfo);
5714 }
5715
5716 if (Result) {
5717#ifndef NDEBUG
5718 errs() << "Call operand #" << i << " has unhandled type "
5719 << EVT(ArgVT).getEVTString() << "\n";
5720#endif
5721 llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5721)
;
5722 }
5723 }
5724 } else {
5725 // All arguments are treated the same.
5726 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5727 }
5728 CCInfo.clearWasPPCF128();
5729
5730 // Assign locations to all of the outgoing aggregate by value arguments.
5731 SmallVector<CCValAssign, 16> ByValArgLocs;
5732 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5733
5734 // Reserve stack space for the allocations in CCInfo.
5735 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5736
5737 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5738
5739 // Size of the linkage area, parameter list area and the part of the local
5740 // space variable where copies of aggregates which are passed by value are
5741 // stored.
5742 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5743
5744 // Calculate by how many bytes the stack has to be adjusted in case of tail
5745 // call optimization.
5746 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5747
5748 // Adjust the stack pointer for the new arguments...
5749 // These operations are automatically eliminated by the prolog/epilog pass
5750 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5751 SDValue CallSeqStart = Chain;
5752
5753 // Load the return address and frame pointer so it can be moved somewhere else
5754 // later.
5755 SDValue LROp, FPOp;
5756 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5757
5758 // Set up a copy of the stack pointer for use loading and storing any
5759 // arguments that may not fit in the registers available for argument
5760 // passing.
5761 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5762
5763 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5764 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5765 SmallVector<SDValue, 8> MemOpChains;
5766
5767 bool seenFloatArg = false;
5768 // Walk the register/memloc assignments, inserting copies/loads.
5769 // i - Tracks the index into the list of registers allocated for the call
5770 // RealArgIdx - Tracks the index into the list of actual function arguments
5771 // j - Tracks the index into the list of byval arguments
5772 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5773 i != e;
5774 ++i, ++RealArgIdx) {
5775 CCValAssign &VA = ArgLocs[i];
5776 SDValue Arg = OutVals[RealArgIdx];
5777 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5778
5779 if (Flags.isByVal()) {
5780 // Argument is an aggregate which is passed by value, thus we need to
5781 // create a copy of it in the local variable space of the current stack
5782 // frame (which is the stack frame of the caller) and pass the address of
5783 // this copy to the callee.
5784 assert((j < ByValArgLocs.size()) && "Index out of bounds!")(static_cast <bool> ((j < ByValArgLocs.size()) &&
"Index out of bounds!") ? void (0) : __assert_fail ("(j < ByValArgLocs.size()) && \"Index out of bounds!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5784, __extension__ __PRETTY_FUNCTION__))
;
5785 CCValAssign &ByValVA = ByValArgLocs[j++];
5786 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!")(static_cast <bool> ((VA.getValNo() == ByValVA.getValNo
()) && "ValNo mismatch!") ? void (0) : __assert_fail (
"(VA.getValNo() == ByValVA.getValNo()) && \"ValNo mismatch!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/PowerPC/PPCISelLowering.cpp"
, 5786, __extension__ __PRETTY_FUNCTION__))
;
5787
5788 // Memory reserved in the local variable space of the callers stack frame.
5789 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5790
5791 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5792 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5793 StackPtr, PtrOff);
5794
5795 // Create a copy of the argument in the local area of the current
5796 // stack frame.
5797 SDValue MemcpyCall =
5798 CreateCopyOfByValArgument(Arg, PtrOff,
5799 CallSeqStart.getNode()->getOperand(0),
5800 Flags, DAG, dl);
5801
5802 // This must go outside the CALLSEQ_START..END.
5803 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5804 SDLoc(MemcpyCall));
5805 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5806 NewCallSeqStart.getNode());
5807 Chain = CallSeqStart = NewCallSeqStart;
5808
5809 // Pass the address of the aggregate copy on the stack either in a
5810 // physical register or in the parameter list area of the current stack