Bug Summary

File:llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Warning:line 16117, column 9
Assigned value is garbage or undefined

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 -fhalf-no-semantic-interposition -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-13~++20210506100649+6304c0836a4d/build-llvm/lib/Target/PowerPC -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/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-13/lib/clang/13.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-13~++20210506100649+6304c0836a4d/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -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-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/lib/Target/PowerPC/PPCISelLowering.cpp

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