Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-8~svn350071/lib/Target/PowerPC -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/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-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Target/PowerPC -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/lib/Target/PowerPC/PPCISelLowering.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/lib/Target/PowerPC/PPCISelLowering.cpp

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