clang 20.0.0git
AArch64.cpp
Go to the documentation of this file.
1//===- AArch64.cpp --------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ABIInfoImpl.h"
10#include "TargetInfo.h"
11#include "clang/AST/Decl.h"
13#include "llvm/TargetParser/AArch64TargetParser.h"
14
15using namespace clang;
16using namespace clang::CodeGen;
17
18//===----------------------------------------------------------------------===//
19// AArch64 ABI Implementation
20//===----------------------------------------------------------------------===//
21
22namespace {
23
24class AArch64ABIInfo : public ABIInfo {
26
27public:
28 AArch64ABIInfo(CodeGenTypes &CGT, AArch64ABIKind Kind)
29 : ABIInfo(CGT), Kind(Kind) {}
30
31 bool isSoftFloat() const { return Kind == AArch64ABIKind::AAPCSSoft; }
32
33private:
34 AArch64ABIKind getABIKind() const { return Kind; }
35 bool isDarwinPCS() const { return Kind == AArch64ABIKind::DarwinPCS; }
36
37 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadicFn) const;
38 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadicFn,
39 bool IsNamedArg, unsigned CallingConvention,
40 unsigned &NSRN, unsigned &NPRN) const;
41 llvm::Type *convertFixedToScalableVectorType(const VectorType *VT) const;
42 ABIArgInfo coerceIllegalVector(QualType Ty, unsigned &NSRN,
43 unsigned &NPRN) const;
44 ABIArgInfo coerceAndExpandPureScalableAggregate(
45 QualType Ty, bool IsNamedArg, unsigned NVec, unsigned NPred,
46 const SmallVectorImpl<llvm::Type *> &UnpaddedCoerceToSeq, unsigned &NSRN,
47 unsigned &NPRN) const;
48 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
50 uint64_t Members) const override;
52
53 bool isIllegalVectorType(QualType Ty) const;
54
55 bool passAsAggregateType(QualType Ty) const;
56 bool passAsPureScalableType(QualType Ty, unsigned &NV, unsigned &NP,
57 SmallVectorImpl<llvm::Type *> &CoerceToSeq) const;
58
59 void flattenType(llvm::Type *Ty,
60 SmallVectorImpl<llvm::Type *> &Flattened) const;
61
62 void computeInfo(CGFunctionInfo &FI) const override {
63 if (!::classifyReturnType(getCXXABI(), FI, *this))
64 FI.getReturnInfo() =
66
67 unsigned ArgNo = 0;
68 unsigned NSRN = 0, NPRN = 0;
69 for (auto &it : FI.arguments()) {
70 const bool IsNamedArg =
71 !FI.isVariadic() || ArgNo < FI.getRequiredArgs().getNumRequiredArgs();
72 ++ArgNo;
73 it.info = classifyArgumentType(it.type, FI.isVariadic(), IsNamedArg,
74 FI.getCallingConvention(), NSRN, NPRN);
75 }
76 }
77
78 RValue EmitDarwinVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF,
79 AggValueSlot Slot) const;
80
81 RValue EmitAAPCSVAArg(Address VAListAddr, QualType Ty, CodeGenFunction &CGF,
82 AArch64ABIKind Kind, AggValueSlot Slot) const;
83
84 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
85 AggValueSlot Slot) const override {
86 llvm::Type *BaseTy = CGF.ConvertType(Ty);
87 if (isa<llvm::ScalableVectorType>(BaseTy))
88 llvm::report_fatal_error("Passing SVE types to variadic functions is "
89 "currently not supported");
90
91 return Kind == AArch64ABIKind::Win64
92 ? EmitMSVAArg(CGF, VAListAddr, Ty, Slot)
93 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF, Slot)
94 : EmitAAPCSVAArg(VAListAddr, Ty, CGF, Kind, Slot);
95 }
96
98 AggValueSlot Slot) const override;
99
100 bool allowBFloatArgsAndRet() const override {
101 return getTarget().hasBFloat16Type();
102 }
103
105 void appendAttributeMangling(TargetClonesAttr *Attr, unsigned Index,
106 raw_ostream &Out) const override;
107 void appendAttributeMangling(StringRef AttrStr,
108 raw_ostream &Out) const override;
109};
110
111class AArch64SwiftABIInfo : public SwiftABIInfo {
112public:
113 explicit AArch64SwiftABIInfo(CodeGenTypes &CGT)
114 : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/true) {}
115
116 bool isLegalVectorType(CharUnits VectorSize, llvm::Type *EltTy,
117 unsigned NumElts) const override;
118};
119
120class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
121public:
122 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIKind Kind)
123 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {
124 SwiftInfo = std::make_unique<AArch64SwiftABIInfo>(CGT);
125 }
126
127 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
128 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
129 }
130
131 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
132 return 31;
133 }
134
135 bool doesReturnSlotInterfereWithArgs() const override { return false; }
136
137 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
138 CodeGen::CodeGenModule &CGM) const override {
139 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
140 if (!FD)
141 return;
142
144
145 if (const auto *TA = FD->getAttr<TargetAttr>()) {
147 CGM.getTarget().parseTargetAttr(TA->getFeaturesStr());
148 if (!Attr.BranchProtection.empty()) {
149 StringRef Error;
150 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
151 Attr.CPU, BPI, Error);
152 assert(Error.empty());
153 }
154 }
155 auto *Fn = cast<llvm::Function>(GV);
157 }
158
160 llvm::Type *Ty) const override {
161 if (CGF.getTarget().hasFeature("ls64")) {
162 auto *ST = dyn_cast<llvm::StructType>(Ty);
163 if (ST && ST->getNumElements() == 1) {
164 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
165 if (AT && AT->getNumElements() == 8 &&
166 AT->getElementType()->isIntegerTy(64))
167 return true;
168 }
169 }
171 }
172
174 const FunctionDecl *Decl) const override;
175
177 const FunctionDecl *Caller,
178 const FunctionDecl *Callee, const CallArgList &Args,
179 QualType ReturnType) const override;
180
182 const FunctionDecl *Caller, const FunctionDecl *Callee) const override;
183
184private:
185 // Diagnose calls between functions with incompatible Streaming SVE
186 // attributes.
187 void checkFunctionCallABIStreaming(CodeGenModule &CGM, SourceLocation CallLoc,
188 const FunctionDecl *Caller,
189 const FunctionDecl *Callee) const;
190 // Diagnose calls which must pass arguments in floating-point registers when
191 // the selected target does not have floating-point registers.
192 void checkFunctionCallABISoftFloat(CodeGenModule &CGM, SourceLocation CallLoc,
193 const FunctionDecl *Caller,
194 const FunctionDecl *Callee,
195 const CallArgList &Args,
196 QualType ReturnType) const;
197};
198
199class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
200public:
201 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIKind K)
202 : AArch64TargetCodeGenInfo(CGT, K) {}
203
204 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
205 CodeGen::CodeGenModule &CGM) const override;
206
207 void getDependentLibraryOption(llvm::StringRef Lib,
208 llvm::SmallString<24> &Opt) const override {
209 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
210 }
211
212 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
213 llvm::SmallString<32> &Opt) const override {
214 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
215 }
216};
217
218void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
219 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
220 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
221 if (GV->isDeclaration())
222 return;
223 addStackProbeTargetAttributes(D, GV, CGM);
224}
225}
226
227llvm::Type *
228AArch64ABIInfo::convertFixedToScalableVectorType(const VectorType *VT) const {
229 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
230
231 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
232 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
233 BuiltinType::UChar &&
234 "unexpected builtin type for SVE predicate!");
235 return llvm::ScalableVectorType::get(llvm::Type::getInt1Ty(getVMContext()),
236 16);
237 }
238
239 if (VT->getVectorKind() == VectorKind::SveFixedLengthData) {
240 const auto *BT = VT->getElementType()->castAs<BuiltinType>();
241 switch (BT->getKind()) {
242 default:
243 llvm_unreachable("unexpected builtin type for SVE vector!");
244
245 case BuiltinType::SChar:
246 case BuiltinType::UChar:
247 return llvm::ScalableVectorType::get(
248 llvm::Type::getInt8Ty(getVMContext()), 16);
249
250 case BuiltinType::Short:
251 case BuiltinType::UShort:
252 return llvm::ScalableVectorType::get(
253 llvm::Type::getInt16Ty(getVMContext()), 8);
254
255 case BuiltinType::Int:
256 case BuiltinType::UInt:
257 return llvm::ScalableVectorType::get(
258 llvm::Type::getInt32Ty(getVMContext()), 4);
259
260 case BuiltinType::Long:
261 case BuiltinType::ULong:
262 return llvm::ScalableVectorType::get(
263 llvm::Type::getInt64Ty(getVMContext()), 2);
264
265 case BuiltinType::Half:
266 return llvm::ScalableVectorType::get(
267 llvm::Type::getHalfTy(getVMContext()), 8);
268
269 case BuiltinType::Float:
270 return llvm::ScalableVectorType::get(
271 llvm::Type::getFloatTy(getVMContext()), 4);
272
273 case BuiltinType::Double:
274 return llvm::ScalableVectorType::get(
275 llvm::Type::getDoubleTy(getVMContext()), 2);
276
277 case BuiltinType::BFloat16:
278 return llvm::ScalableVectorType::get(
279 llvm::Type::getBFloatTy(getVMContext()), 8);
280 }
281 }
282
283 llvm_unreachable("expected fixed-length SVE vector");
284}
285
286ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty, unsigned &NSRN,
287 unsigned &NPRN) const {
288 assert(Ty->isVectorType() && "expected vector type!");
289
290 const auto *VT = Ty->castAs<VectorType>();
291 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
292 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
293 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
294 BuiltinType::UChar &&
295 "unexpected builtin type for SVE predicate!");
296 NPRN = std::min(NPRN + 1, 4u);
297 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
298 llvm::Type::getInt1Ty(getVMContext()), 16));
299 }
300
301 if (VT->getVectorKind() == VectorKind::SveFixedLengthData) {
302 NSRN = std::min(NSRN + 1, 8u);
303 return ABIArgInfo::getDirect(convertFixedToScalableVectorType(VT));
304 }
305
306 uint64_t Size = getContext().getTypeSize(Ty);
307 // Android promotes <2 x i8> to i16, not i32
308 if ((isAndroid() || isOHOSFamily()) && (Size <= 16)) {
309 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
310 return ABIArgInfo::getDirect(ResType);
311 }
312 if (Size <= 32) {
313 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
314 return ABIArgInfo::getDirect(ResType);
315 }
316 if (Size == 64) {
317 NSRN = std::min(NSRN + 1, 8u);
318 auto *ResType =
319 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
320 return ABIArgInfo::getDirect(ResType);
321 }
322 if (Size == 128) {
323 NSRN = std::min(NSRN + 1, 8u);
324 auto *ResType =
325 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
326 return ABIArgInfo::getDirect(ResType);
327 }
328
329 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
330}
331
332ABIArgInfo AArch64ABIInfo::coerceAndExpandPureScalableAggregate(
333 QualType Ty, bool IsNamedArg, unsigned NVec, unsigned NPred,
334 const SmallVectorImpl<llvm::Type *> &UnpaddedCoerceToSeq, unsigned &NSRN,
335 unsigned &NPRN) const {
336 if (!IsNamedArg || NSRN + NVec > 8 || NPRN + NPred > 4)
337 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
338 NSRN += NVec;
339 NPRN += NPred;
340
341 // Handle SVE vector tuples.
342 if (Ty->isSVESizelessBuiltinType())
343 return ABIArgInfo::getDirect();
344
345 llvm::Type *UnpaddedCoerceToType =
346 UnpaddedCoerceToSeq.size() == 1
347 ? UnpaddedCoerceToSeq[0]
348 : llvm::StructType::get(CGT.getLLVMContext(), UnpaddedCoerceToSeq,
349 true);
350
351 SmallVector<llvm::Type *> CoerceToSeq;
352 flattenType(CGT.ConvertType(Ty), CoerceToSeq);
353 auto *CoerceToType =
354 llvm::StructType::get(CGT.getLLVMContext(), CoerceToSeq, false);
355
356 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
357}
358
359ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadicFn,
360 bool IsNamedArg,
361 unsigned CallingConvention,
362 unsigned &NSRN,
363 unsigned &NPRN) const {
365
366 // Handle illegal vector types here.
367 if (isIllegalVectorType(Ty))
368 return coerceIllegalVector(Ty, NSRN, NPRN);
369
370 if (!passAsAggregateType(Ty)) {
371 // Treat an enum type as its underlying type.
372 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
373 Ty = EnumTy->getDecl()->getIntegerType();
374
375 if (const auto *EIT = Ty->getAs<BitIntType>())
376 if (EIT->getNumBits() > 128)
377 return getNaturalAlignIndirect(Ty, false);
378
379 if (Ty->isVectorType())
380 NSRN = std::min(NSRN + 1, 8u);
381 else if (const auto *BT = Ty->getAs<BuiltinType>()) {
382 if (BT->isFloatingPoint())
383 NSRN = std::min(NSRN + 1, 8u);
384 else {
385 switch (BT->getKind()) {
386 case BuiltinType::MFloat8x8:
387 case BuiltinType::MFloat8x16:
388 NSRN = std::min(NSRN + 1, 8u);
389 break;
390 case BuiltinType::SveBool:
391 case BuiltinType::SveCount:
392 NPRN = std::min(NPRN + 1, 4u);
393 break;
394 case BuiltinType::SveBoolx2:
395 NPRN = std::min(NPRN + 2, 4u);
396 break;
397 case BuiltinType::SveBoolx4:
398 NPRN = std::min(NPRN + 4, 4u);
399 break;
400 default:
401 if (BT->isSVESizelessBuiltinType())
402 NSRN = std::min(
403 NSRN + getContext().getBuiltinVectorTypeInfo(BT).NumVectors,
404 8u);
405 }
406 }
407 }
408
409 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
410 ? ABIArgInfo::getExtend(Ty, CGT.ConvertType(Ty))
412 }
413
414 // Structures with either a non-trivial destructor or a non-trivial
415 // copy constructor are always indirect.
416 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
417 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
419 }
420
421 // Empty records are always ignored on Darwin, but actually passed in C++ mode
422 // elsewhere for GNU compatibility.
423 uint64_t Size = getContext().getTypeSize(Ty);
424 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
425 if (!Ty->isSVESizelessBuiltinType() && (IsEmpty || Size == 0)) {
426 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
427 return ABIArgInfo::getIgnore();
428
429 // GNU C mode. The only argument that gets ignored is an empty one with size
430 // 0.
431 if (IsEmpty && Size == 0)
432 return ABIArgInfo::getIgnore();
433 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
434 }
435
436 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
437 const Type *Base = nullptr;
438 uint64_t Members = 0;
439 bool IsWin64 = Kind == AArch64ABIKind::Win64 ||
440 CallingConvention == llvm::CallingConv::Win64;
441 bool IsWinVariadic = IsWin64 && IsVariadicFn;
442 // In variadic functions on Windows, all composite types are treated alike,
443 // no special handling of HFAs/HVAs.
444 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
445 NSRN = std::min(NSRN + Members, uint64_t(8));
446 if (Kind != AArch64ABIKind::AAPCS)
448 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
449
450 // For HFAs/HVAs, cap the argument alignment to 16, otherwise
451 // set it to 8 according to the AAPCS64 document.
452 unsigned Align =
453 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
454 Align = (Align >= 16) ? 16 : 8;
456 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
457 nullptr, true, Align);
458 }
459
460 // In AAPCS named arguments of a Pure Scalable Type are passed expanded in
461 // registers, or indirectly if there are not enough registers.
462 if (Kind == AArch64ABIKind::AAPCS) {
463 unsigned NVec = 0, NPred = 0;
464 SmallVector<llvm::Type *> UnpaddedCoerceToSeq;
465 if (passAsPureScalableType(Ty, NVec, NPred, UnpaddedCoerceToSeq) &&
466 (NVec + NPred) > 0)
467 return coerceAndExpandPureScalableAggregate(
468 Ty, IsNamedArg, NVec, NPred, UnpaddedCoerceToSeq, NSRN, NPRN);
469 }
470
471 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
472 if (Size <= 128) {
473 unsigned Alignment;
474 if (Kind == AArch64ABIKind::AAPCS) {
475 Alignment = getContext().getTypeUnadjustedAlign(Ty);
476 Alignment = Alignment < 128 ? 64 : 128;
477 } else {
478 Alignment =
479 std::max(getContext().getTypeAlign(Ty),
480 (unsigned)getTarget().getPointerWidth(LangAS::Default));
481 }
482 Size = llvm::alignTo(Size, Alignment);
483
484 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
485 // For aggregates with 16-byte alignment, we use i128.
486 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
488 Size == Alignment ? BaseTy
489 : llvm::ArrayType::get(BaseTy, Size / Alignment));
490 }
491
492 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
493}
494
495ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
496 bool IsVariadicFn) const {
497 if (RetTy->isVoidType())
498 return ABIArgInfo::getIgnore();
499
500 if (const auto *VT = RetTy->getAs<VectorType>()) {
501 if (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
502 VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
503 unsigned NSRN = 0, NPRN = 0;
504 return coerceIllegalVector(RetTy, NSRN, NPRN);
505 }
506 }
507
508 // Large vector types should be returned via memory.
509 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
510 return getNaturalAlignIndirect(RetTy);
511
512 if (!passAsAggregateType(RetTy)) {
513 // Treat an enum type as its underlying type.
514 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
515 RetTy = EnumTy->getDecl()->getIntegerType();
516
517 if (const auto *EIT = RetTy->getAs<BitIntType>())
518 if (EIT->getNumBits() > 128)
519 return getNaturalAlignIndirect(RetTy);
520
521 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
522 ? ABIArgInfo::getExtend(RetTy)
524 }
525
526 uint64_t Size = getContext().getTypeSize(RetTy);
527 if (!RetTy->isSVESizelessBuiltinType() &&
528 (isEmptyRecord(getContext(), RetTy, true) || Size == 0))
529 return ABIArgInfo::getIgnore();
530
531 const Type *Base = nullptr;
532 uint64_t Members = 0;
533 if (isHomogeneousAggregate(RetTy, Base, Members) &&
534 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
535 IsVariadicFn))
536 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
537 return ABIArgInfo::getDirect();
538
539 // In AAPCS return values of a Pure Scalable type are treated as a single
540 // named argument and passed expanded in registers, or indirectly if there are
541 // not enough registers.
542 if (Kind == AArch64ABIKind::AAPCS) {
543 unsigned NSRN = 0, NPRN = 0;
544 unsigned NVec = 0, NPred = 0;
545 SmallVector<llvm::Type *> UnpaddedCoerceToSeq;
546 if (passAsPureScalableType(RetTy, NVec, NPred, UnpaddedCoerceToSeq) &&
547 (NVec + NPred) > 0)
548 return coerceAndExpandPureScalableAggregate(
549 RetTy, /* IsNamedArg */ true, NVec, NPred, UnpaddedCoerceToSeq, NSRN,
550 NPRN);
551 }
552
553 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
554 if (Size <= 128) {
555 if (Size <= 64 && getDataLayout().isLittleEndian()) {
556 // Composite types are returned in lower bits of a 64-bit register for LE,
557 // and in higher bits for BE. However, integer types are always returned
558 // in lower bits for both LE and BE, and they are not rounded up to
559 // 64-bits. We can skip rounding up of composite types for LE, but not for
560 // BE, otherwise composite types will be indistinguishable from integer
561 // types.
563 llvm::IntegerType::get(getVMContext(), Size));
564 }
565
566 unsigned Alignment = getContext().getTypeAlign(RetTy);
567 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
568
569 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
570 // For aggregates with 16-byte alignment, we use i128.
571 if (Alignment < 128 && Size == 128) {
572 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
573 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
574 }
575 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
576 }
577
578 return getNaturalAlignIndirect(RetTy);
579}
580
581/// isIllegalVectorType - check whether the vector type is legal for AArch64.
582bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
583 if (const VectorType *VT = Ty->getAs<VectorType>()) {
584 // Check whether VT is a fixed-length SVE vector. These types are
585 // represented as scalable vectors in function args/return and must be
586 // coerced from fixed vectors.
587 if (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
588 VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
589 return true;
590
591 // Check whether VT is legal.
592 unsigned NumElements = VT->getNumElements();
593 uint64_t Size = getContext().getTypeSize(VT);
594 // NumElements should be power of 2.
595 if (!llvm::isPowerOf2_32(NumElements))
596 return true;
597
598 // arm64_32 has to be compatible with the ARM logic here, which allows huge
599 // vectors for some reason.
600 llvm::Triple Triple = getTarget().getTriple();
601 if (Triple.getArch() == llvm::Triple::aarch64_32 &&
602 Triple.isOSBinFormatMachO())
603 return Size <= 32;
604
605 return Size != 64 && (Size != 128 || NumElements == 1);
606 }
607 return false;
608}
609
610bool AArch64SwiftABIInfo::isLegalVectorType(CharUnits VectorSize,
611 llvm::Type *EltTy,
612 unsigned NumElts) const {
613 if (!llvm::isPowerOf2_32(NumElts))
614 return false;
615 if (VectorSize.getQuantity() != 8 &&
616 (VectorSize.getQuantity() != 16 || NumElts == 1))
617 return false;
618 return true;
619}
620
621bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
622 // For the soft-float ABI variant, no types are considered to be homogeneous
623 // aggregates.
624 if (isSoftFloat())
625 return false;
626
627 // Homogeneous aggregates for AAPCS64 must have base types of a floating
628 // point type or a short-vector type. This is the same as the 32-bit ABI,
629 // but with the difference that any floating-point type is allowed,
630 // including __fp16.
631 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
632 if (BT->isFloatingPoint() || BT->getKind() == BuiltinType::MFloat8x16 ||
633 BT->getKind() == BuiltinType::MFloat8x8)
634 return true;
635 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
636 if (auto Kind = VT->getVectorKind();
637 Kind == VectorKind::SveFixedLengthData ||
638 Kind == VectorKind::SveFixedLengthPredicate)
639 return false;
640
641 unsigned VecSize = getContext().getTypeSize(VT);
642 if (VecSize == 64 || VecSize == 128)
643 return true;
644 }
645 return false;
646}
647
648bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
649 uint64_t Members) const {
650 return Members <= 4;
651}
652
653bool AArch64ABIInfo::isZeroLengthBitfieldPermittedInHomogeneousAggregate()
654 const {
655 // AAPCS64 says that the rule for whether something is a homogeneous
656 // aggregate is applied to the output of the data layout decision. So
657 // anything that doesn't affect the data layout also does not affect
658 // homogeneity. In particular, zero-length bitfields don't stop a struct
659 // being homogeneous.
660 return true;
661}
662
663bool AArch64ABIInfo::passAsAggregateType(QualType Ty) const {
664 if (Kind == AArch64ABIKind::AAPCS && Ty->isSVESizelessBuiltinType()) {
665 const auto *BT = Ty->getAs<BuiltinType>();
666 return !BT->isSVECount() &&
667 getContext().getBuiltinVectorTypeInfo(BT).NumVectors > 1;
668 }
669 return isAggregateTypeForABI(Ty);
670}
671
672// Check if a type needs to be passed in registers as a Pure Scalable Type (as
673// defined by AAPCS64). Return the number of data vectors and the number of
674// predicate vectors in the type, into `NVec` and `NPred`, respectively. Upon
675// return `CoerceToSeq` contains an expanded sequence of LLVM IR types, one
676// element for each non-composite member. For practical purposes, limit the
677// length of `CoerceToSeq` to about 12 (the maximum that could possibly fit
678// in registers) and return false, the effect of which will be to pass the
679// argument under the rules for a large (> 128 bytes) composite.
680bool AArch64ABIInfo::passAsPureScalableType(
681 QualType Ty, unsigned &NVec, unsigned &NPred,
682 SmallVectorImpl<llvm::Type *> &CoerceToSeq) const {
683 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
684 uint64_t NElt = AT->getZExtSize();
685 if (NElt == 0)
686 return false;
687
688 unsigned NV = 0, NP = 0;
689 SmallVector<llvm::Type *> EltCoerceToSeq;
690 if (!passAsPureScalableType(AT->getElementType(), NV, NP, EltCoerceToSeq))
691 return false;
692
693 if (CoerceToSeq.size() + NElt * EltCoerceToSeq.size() > 12)
694 return false;
695
696 for (uint64_t I = 0; I < NElt; ++I)
697 llvm::copy(EltCoerceToSeq, std::back_inserter(CoerceToSeq));
698
699 NVec += NElt * NV;
700 NPred += NElt * NP;
701 return true;
702 }
703
704 if (const RecordType *RT = Ty->getAs<RecordType>()) {
705 // If the record cannot be passed in registers, then it's not a PST.
706 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
708 return false;
709
710 // Pure scalable types are never unions and never contain unions.
711 const RecordDecl *RD = RT->getDecl();
712 if (RD->isUnion())
713 return false;
714
715 // If this is a C++ record, check the bases.
716 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
717 for (const auto &I : CXXRD->bases()) {
718 if (isEmptyRecord(getContext(), I.getType(), true))
719 continue;
720 if (!passAsPureScalableType(I.getType(), NVec, NPred, CoerceToSeq))
721 return false;
722 }
723 }
724
725 // Check members.
726 for (const auto *FD : RD->fields()) {
727 QualType FT = FD->getType();
728 if (isEmptyField(getContext(), FD, /* AllowArrays */ true))
729 continue;
730 if (!passAsPureScalableType(FT, NVec, NPred, CoerceToSeq))
731 return false;
732 }
733
734 return true;
735 }
736
737 if (const auto *VT = Ty->getAs<VectorType>()) {
738 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
739 ++NPred;
740 if (CoerceToSeq.size() + 1 > 12)
741 return false;
742 CoerceToSeq.push_back(convertFixedToScalableVectorType(VT));
743 return true;
744 }
745
746 if (VT->getVectorKind() == VectorKind::SveFixedLengthData) {
747 ++NVec;
748 if (CoerceToSeq.size() + 1 > 12)
749 return false;
750 CoerceToSeq.push_back(convertFixedToScalableVectorType(VT));
751 return true;
752 }
753
754 return false;
755 }
756
757 if (!Ty->isBuiltinType())
758 return false;
759
760 bool isPredicate;
761 switch (Ty->getAs<BuiltinType>()->getKind()) {
762#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
763 case BuiltinType::Id: \
764 isPredicate = false; \
765 break;
766#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
767 case BuiltinType::Id: \
768 isPredicate = true; \
769 break;
770#define SVE_TYPE(Name, Id, SingletonId)
771#include "clang/Basic/AArch64SVEACLETypes.def"
772 default:
773 return false;
774 }
775
777 getContext().getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
778 assert(Info.NumVectors > 0 && Info.NumVectors <= 4 &&
779 "Expected 1, 2, 3 or 4 vectors!");
780 if (isPredicate)
781 NPred += Info.NumVectors;
782 else
783 NVec += Info.NumVectors;
784 auto VTy = llvm::ScalableVectorType::get(CGT.ConvertType(Info.ElementType),
785 Info.EC.getKnownMinValue());
786
787 if (CoerceToSeq.size() + Info.NumVectors > 12)
788 return false;
789 std::fill_n(std::back_inserter(CoerceToSeq), Info.NumVectors, VTy);
790
791 return true;
792}
793
794// Expand an LLVM IR type into a sequence with a element for each non-struct,
795// non-array member of the type, with the exception of the padding types, which
796// are retained.
797void AArch64ABIInfo::flattenType(
798 llvm::Type *Ty, SmallVectorImpl<llvm::Type *> &Flattened) const {
799
801 Flattened.push_back(Ty);
802 return;
803 }
804
805 if (const auto *AT = dyn_cast<llvm::ArrayType>(Ty)) {
806 uint64_t NElt = AT->getNumElements();
807 if (NElt == 0)
808 return;
809
810 SmallVector<llvm::Type *> EltFlattened;
811 flattenType(AT->getElementType(), EltFlattened);
812
813 for (uint64_t I = 0; I < NElt; ++I)
814 llvm::copy(EltFlattened, std::back_inserter(Flattened));
815 return;
816 }
817
818 if (const auto *ST = dyn_cast<llvm::StructType>(Ty)) {
819 for (auto *ET : ST->elements())
820 flattenType(ET, Flattened);
821 return;
822 }
823
824 Flattened.push_back(Ty);
825}
826
827RValue AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
829 AggValueSlot Slot) const {
830 // These numbers are not used for variadic arguments, hence it doesn't matter
831 // they don't retain their values across multiple calls to
832 // `classifyArgumentType` here.
833 unsigned NSRN = 0, NPRN = 0;
834 ABIArgInfo AI =
835 classifyArgumentType(Ty, /*IsVariadicFn=*/true, /* IsNamedArg */ false,
836 CGF.CurFnInfo->getCallingConvention(), NSRN, NPRN);
837 // Empty records are ignored for parameter passing purposes.
838 if (AI.isIgnore())
839 return Slot.asRValue();
840
841 bool IsIndirect = AI.isIndirect();
842
843 llvm::Type *BaseTy = CGF.ConvertType(Ty);
844 if (IsIndirect)
845 BaseTy = llvm::PointerType::getUnqual(BaseTy);
846 else if (AI.getCoerceToType())
847 BaseTy = AI.getCoerceToType();
848
849 unsigned NumRegs = 1;
850 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
851 BaseTy = ArrTy->getElementType();
852 NumRegs = ArrTy->getNumElements();
853 }
854 bool IsFPR =
855 !isSoftFloat() && (BaseTy->isFloatingPointTy() || BaseTy->isVectorTy());
856
857 // The AArch64 va_list type and handling is specified in the Procedure Call
858 // Standard, section B.4:
859 //
860 // struct {
861 // void *__stack;
862 // void *__gr_top;
863 // void *__vr_top;
864 // int __gr_offs;
865 // int __vr_offs;
866 // };
867
868 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
869 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
870 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
871 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
872
873 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
874 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
875
876 Address reg_offs_p = Address::invalid();
877 llvm::Value *reg_offs = nullptr;
878 int reg_top_index;
879 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
880 if (!IsFPR) {
881 // 3 is the field number of __gr_offs
882 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
883 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
884 reg_top_index = 1; // field number for __gr_top
885 RegSize = llvm::alignTo(RegSize, 8);
886 } else {
887 // 4 is the field number of __vr_offs.
888 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
889 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
890 reg_top_index = 2; // field number for __vr_top
891 RegSize = 16 * NumRegs;
892 }
893
894 //=======================================
895 // Find out where argument was passed
896 //=======================================
897
898 // If reg_offs >= 0 we're already using the stack for this type of
899 // argument. We don't want to keep updating reg_offs (in case it overflows,
900 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
901 // whatever they get).
902 llvm::Value *UsingStack = nullptr;
903 UsingStack = CGF.Builder.CreateICmpSGE(
904 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
905
906 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
907
908 // Otherwise, at least some kind of argument could go in these registers, the
909 // question is whether this particular type is too big.
910 CGF.EmitBlock(MaybeRegBlock);
911
912 // Integer arguments may need to correct register alignment (for example a
913 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
914 // align __gr_offs to calculate the potential address.
915 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
916 int Align = TyAlign.getQuantity();
917
918 reg_offs = CGF.Builder.CreateAdd(
919 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
920 "align_regoffs");
921 reg_offs = CGF.Builder.CreateAnd(
922 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
923 "aligned_regoffs");
924 }
925
926 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
927 // The fact that this is done unconditionally reflects the fact that
928 // allocating an argument to the stack also uses up all the remaining
929 // registers of the appropriate kind.
930 llvm::Value *NewOffset = nullptr;
931 NewOffset = CGF.Builder.CreateAdd(
932 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
933 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
934
935 // Now we're in a position to decide whether this argument really was in
936 // registers or not.
937 llvm::Value *InRegs = nullptr;
938 InRegs = CGF.Builder.CreateICmpSLE(
939 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
940
941 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
942
943 //=======================================
944 // Argument was in registers
945 //=======================================
946
947 // Now we emit the code for if the argument was originally passed in
948 // registers. First start the appropriate block:
949 CGF.EmitBlock(InRegBlock);
950
951 llvm::Value *reg_top = nullptr;
952 Address reg_top_p =
953 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
954 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
955 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
956 CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
957 Address RegAddr = Address::invalid();
958 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy;
959
960 if (IsIndirect) {
961 // If it's been passed indirectly (actually a struct), whatever we find from
962 // stored registers or on the stack will actually be a struct **.
963 MemTy = llvm::PointerType::getUnqual(MemTy);
964 }
965
966 const Type *Base = nullptr;
967 uint64_t NumMembers = 0;
968 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
969 if (IsHFA && NumMembers > 1) {
970 // Homogeneous aggregates passed in registers will have their elements split
971 // and stored 16-bytes apart regardless of size (they're notionally in qN,
972 // qN+1, ...). We reload and store into a temporary local variable
973 // contiguously.
974 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
975 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
976 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
977 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
978 Address Tmp = CGF.CreateTempAlloca(HFATy,
979 std::max(TyAlign, BaseTyInfo.Align));
980
981 // On big-endian platforms, the value will be right-aligned in its slot.
982 int Offset = 0;
983 if (CGF.CGM.getDataLayout().isBigEndian() &&
984 BaseTyInfo.Width.getQuantity() < 16)
985 Offset = 16 - BaseTyInfo.Width.getQuantity();
986
987 for (unsigned i = 0; i < NumMembers; ++i) {
988 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
989 Address LoadAddr =
990 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
991 LoadAddr = LoadAddr.withElementType(BaseTy);
992
993 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
994
995 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
996 CGF.Builder.CreateStore(Elem, StoreAddr);
997 }
998
999 RegAddr = Tmp.withElementType(MemTy);
1000 } else {
1001 // Otherwise the object is contiguous in memory.
1002
1003 // It might be right-aligned in its slot.
1004 CharUnits SlotSize = BaseAddr.getAlignment();
1005 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
1006 (IsHFA || !isAggregateTypeForABI(Ty)) &&
1007 TySize < SlotSize) {
1008 CharUnits Offset = SlotSize - TySize;
1009 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
1010 }
1011
1012 RegAddr = BaseAddr.withElementType(MemTy);
1013 }
1014
1015 CGF.EmitBranch(ContBlock);
1016
1017 //=======================================
1018 // Argument was on the stack
1019 //=======================================
1020 CGF.EmitBlock(OnStackBlock);
1021
1022 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
1023 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
1024
1025 // Again, stack arguments may need realignment. In this case both integer and
1026 // floating-point ones might be affected.
1027 if (!IsIndirect && TyAlign.getQuantity() > 8) {
1028 OnStackPtr = emitRoundPointerUpToAlignment(CGF, OnStackPtr, TyAlign);
1029 }
1030 Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty,
1031 std::max(CharUnits::fromQuantity(8), TyAlign));
1032
1033 // All stack slots are multiples of 8 bytes.
1034 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
1035 CharUnits StackSize;
1036 if (IsIndirect)
1037 StackSize = StackSlotSize;
1038 else
1039 StackSize = TySize.alignTo(StackSlotSize);
1040
1041 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
1042 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
1043 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
1044
1045 // Write the new value of __stack for the next call to va_arg
1046 CGF.Builder.CreateStore(NewStack, stack_p);
1047
1048 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
1049 TySize < StackSlotSize) {
1050 CharUnits Offset = StackSlotSize - TySize;
1051 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
1052 }
1053
1054 OnStackAddr = OnStackAddr.withElementType(MemTy);
1055
1056 CGF.EmitBranch(ContBlock);
1057
1058 //=======================================
1059 // Tidy up
1060 //=======================================
1061 CGF.EmitBlock(ContBlock);
1062
1063 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
1064 OnStackBlock, "vaargs.addr");
1065
1066 if (IsIndirect)
1067 return CGF.EmitLoadOfAnyValue(
1068 CGF.MakeAddrLValue(
1069 Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy,
1070 TyAlign),
1071 Ty),
1072 Slot);
1073
1074 return CGF.EmitLoadOfAnyValue(CGF.MakeAddrLValue(ResAddr, Ty), Slot);
1075}
1076
1077RValue AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
1078 CodeGenFunction &CGF,
1079 AggValueSlot Slot) const {
1080 // The backend's lowering doesn't support va_arg for aggregates or
1081 // illegal vector types. Lower VAArg here for these cases and use
1082 // the LLVM va_arg instruction for everything else.
1083 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
1084 return CGF.EmitLoadOfAnyValue(
1085 CGF.MakeAddrLValue(
1086 EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()), Ty),
1087 Slot);
1088
1089 uint64_t PointerSize = getTarget().getPointerWidth(LangAS::Default) / 8;
1090 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
1091
1092 // Empty records are ignored for parameter passing purposes.
1093 if (isEmptyRecord(getContext(), Ty, true))
1094 return Slot.asRValue();
1095
1096 // The size of the actual thing passed, which might end up just
1097 // being a pointer for indirect types.
1098 auto TyInfo = getContext().getTypeInfoInChars(Ty);
1099
1100 // Arguments bigger than 16 bytes which aren't homogeneous
1101 // aggregates should be passed indirectly.
1102 bool IsIndirect = false;
1103 if (TyInfo.Width.getQuantity() > 16) {
1104 const Type *Base = nullptr;
1105 uint64_t Members = 0;
1106 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
1107 }
1108
1109 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, SlotSize,
1110 /*AllowHigherAlign*/ true, Slot);
1111}
1112
1113RValue AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1114 QualType Ty, AggValueSlot Slot) const {
1115 bool IsIndirect = false;
1116
1117 // Composites larger than 16 bytes are passed by reference.
1118 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
1119 IsIndirect = true;
1120
1121 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
1124 /*allowHigherAlign*/ false, Slot);
1125}
1126
1128 if (const auto *T = F->getType()->getAs<FunctionProtoType>())
1129 return T->getAArch64SMEAttributes() &
1131 return false;
1132}
1133
1134// Report an error if an argument or return value of type Ty would need to be
1135// passed in a floating-point register.
1137 const StringRef ABIName,
1138 const AArch64ABIInfo &ABIInfo,
1139 const QualType &Ty, const NamedDecl *D,
1140 SourceLocation loc) {
1141 const Type *HABase = nullptr;
1142 uint64_t HAMembers = 0;
1143 if (Ty->isFloatingType() || Ty->isVectorType() ||
1144 ABIInfo.isHomogeneousAggregate(Ty, HABase, HAMembers)) {
1145 Diags.Report(loc, diag::err_target_unsupported_type_for_abi)
1146 << D->getDeclName() << Ty << ABIName;
1147 }
1148}
1149
1150// If we are using a hard-float ABI, but do not have floating point registers,
1151// then report an error for any function arguments or returns which would be
1152// passed in floating-pint registers.
1153void AArch64TargetCodeGenInfo::checkFunctionABI(
1154 CodeGenModule &CGM, const FunctionDecl *FuncDecl) const {
1155 const AArch64ABIInfo &ABIInfo = getABIInfo<AArch64ABIInfo>();
1157
1158 if (!TI.hasFeature("fp") && !ABIInfo.isSoftFloat()) {
1160 FuncDecl->getReturnType(), FuncDecl,
1161 FuncDecl->getLocation());
1162 for (ParmVarDecl *PVD : FuncDecl->parameters()) {
1163 diagnoseIfNeedsFPReg(CGM.getDiags(), TI.getABI(), ABIInfo, PVD->getType(),
1164 PVD, FuncDecl->getLocation());
1165 }
1166 }
1167}
1168
1169enum class ArmSMEInlinability : uint8_t {
1170 Ok = 0,
1171 ErrorCalleeRequiresNewZA = 1 << 0,
1174
1177
1179};
1180
1181/// Determines if there are any Arm SME ABI issues with inlining \p Callee into
1182/// \p Caller. Returns the issue (if any) in the ArmSMEInlinability bit enum.
1184 const FunctionDecl *Callee) {
1185 bool CallerIsStreaming =
1186 IsArmStreamingFunction(Caller, /*IncludeLocallyStreaming=*/true);
1187 bool CalleeIsStreaming =
1188 IsArmStreamingFunction(Callee, /*IncludeLocallyStreaming=*/true);
1189 bool CallerIsStreamingCompatible = isStreamingCompatible(Caller);
1190 bool CalleeIsStreamingCompatible = isStreamingCompatible(Callee);
1191
1193
1194 if (!CalleeIsStreamingCompatible &&
1195 (CallerIsStreaming != CalleeIsStreaming || CallerIsStreamingCompatible)) {
1196 if (CalleeIsStreaming)
1198 else
1200 }
1201 if (auto *NewAttr = Callee->getAttr<ArmNewAttr>())
1202 if (NewAttr->isNewZA())
1204
1205 return Inlinability;
1206}
1207
1208void AArch64TargetCodeGenInfo::checkFunctionCallABIStreaming(
1209 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
1210 const FunctionDecl *Callee) const {
1211 if (!Caller || !Callee || !Callee->hasAttr<AlwaysInlineAttr>())
1212 return;
1213
1214 ArmSMEInlinability Inlinability = GetArmSMEInlinability(Caller, Callee);
1215
1218 CGM.getDiags().Report(
1219 CallLoc,
1222 ? diag::err_function_always_inline_attribute_mismatch
1223 : diag::warn_function_always_inline_attribute_mismatch)
1224 << Caller->getDeclName() << Callee->getDeclName() << "streaming";
1225
1226 if ((Inlinability & ArmSMEInlinability::ErrorCalleeRequiresNewZA) ==
1228 CGM.getDiags().Report(CallLoc, diag::err_function_always_inline_new_za)
1229 << Callee->getDeclName();
1230}
1231
1232// If the target does not have floating-point registers, but we are using a
1233// hard-float ABI, there is no way to pass floating-point, vector or HFA values
1234// to functions, so we report an error.
1235void AArch64TargetCodeGenInfo::checkFunctionCallABISoftFloat(
1236 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
1237 const FunctionDecl *Callee, const CallArgList &Args,
1238 QualType ReturnType) const {
1239 const AArch64ABIInfo &ABIInfo = getABIInfo<AArch64ABIInfo>();
1241
1242 if (!Caller || TI.hasFeature("fp") || ABIInfo.isSoftFloat())
1243 return;
1244
1245 diagnoseIfNeedsFPReg(CGM.getDiags(), TI.getABI(), ABIInfo, ReturnType,
1246 Callee ? Callee : Caller, CallLoc);
1247
1248 for (const CallArg &Arg : Args)
1249 diagnoseIfNeedsFPReg(CGM.getDiags(), TI.getABI(), ABIInfo, Arg.getType(),
1250 Callee ? Callee : Caller, CallLoc);
1251}
1252
1253void AArch64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
1254 SourceLocation CallLoc,
1255 const FunctionDecl *Caller,
1256 const FunctionDecl *Callee,
1257 const CallArgList &Args,
1258 QualType ReturnType) const {
1259 checkFunctionCallABIStreaming(CGM, CallLoc, Caller, Callee);
1260 checkFunctionCallABISoftFloat(CGM, CallLoc, Caller, Callee, Args, ReturnType);
1261}
1262
1263bool AArch64TargetCodeGenInfo::wouldInliningViolateFunctionCallABI(
1264 const FunctionDecl *Caller, const FunctionDecl *Callee) const {
1265 return Caller && Callee &&
1267}
1268
1269void AArch64ABIInfo::appendAttributeMangling(TargetClonesAttr *Attr,
1270 unsigned Index,
1271 raw_ostream &Out) const {
1272 appendAttributeMangling(Attr->getFeatureStr(Index), Out);
1273}
1274
1275void AArch64ABIInfo::appendAttributeMangling(StringRef AttrStr,
1276 raw_ostream &Out) const {
1277 if (AttrStr == "default") {
1278 Out << ".default";
1279 return;
1280 }
1281
1282 Out << "._";
1284 AttrStr.split(Features, "+");
1285 for (auto &Feat : Features)
1286 Feat = Feat.trim();
1287
1288 llvm::sort(Features, [](const StringRef LHS, const StringRef RHS) {
1289 return LHS.compare(RHS) < 0;
1290 });
1291
1292 llvm::SmallDenseSet<StringRef, 8> UniqueFeats;
1293 for (auto &Feat : Features)
1294 if (auto Ext = llvm::AArch64::parseFMVExtension(Feat))
1295 if (UniqueFeats.insert(Ext->Name).second)
1296 Out << 'M' << Ext->Name;
1297}
1298
1299std::unique_ptr<TargetCodeGenInfo>
1301 AArch64ABIKind Kind) {
1302 return std::make_unique<AArch64TargetCodeGenInfo>(CGM.getTypes(), Kind);
1303}
1304
1305std::unique_ptr<TargetCodeGenInfo>
1307 AArch64ABIKind K) {
1308 return std::make_unique<WindowsAArch64TargetCodeGenInfo>(CGM.getTypes(), K);
1309}
const Decl * D
static bool isStreamingCompatible(const FunctionDecl *F)
Definition: AArch64.cpp:1127
ArmSMEInlinability
Definition: AArch64.cpp:1169
static ArmSMEInlinability GetArmSMEInlinability(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines if there are any Arm SME ABI issues with inlining Callee into Caller.
Definition: AArch64.cpp:1183
static void diagnoseIfNeedsFPReg(DiagnosticsEngine &Diags, const StringRef ABIName, const AArch64ABIInfo &ABIInfo, const QualType &Ty, const NamedDecl *D, SourceLocation loc)
Definition: AArch64.cpp:1136
TypeInfoChars getTypeInfoInChars(const Type *T) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
Attr - This represents one attribute.
Definition: Attr.h:43
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
This class is used for builtin types like 'int'.
Definition: Type.h:3034
bool isSVECount() const
Definition: Type.h:3113
Kind getKind() const
Definition: Type.h:3082
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
static ABIArgInfo getIgnore()
static bool isPaddingForCoerceAndExpand(llvm::Type *eltType)
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
static ABIArgInfo getExtend(QualType Ty, llvm::Type *T=nullptr)
static ABIArgInfo getCoerceAndExpand(llvm::StructType *coerceToType, llvm::Type *unpaddedCoerceToType)
llvm::Type * getCoerceToType() const
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
Definition: ABIInfo.h:47
virtual bool allowBFloatArgsAndRet() const
Definition: ABIInfo.h:58
bool isHomogeneousAggregate(QualType Ty, const Type *&Base, uint64_t &Members) const
isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous aggregate.
Definition: ABIInfo.cpp:61
CodeGen::CGCXXABI & getCXXABI() const
Definition: ABIInfo.cpp:18
ASTContext & getContext() const
Definition: ABIInfo.cpp:20
virtual bool isHomogeneousAggregateBaseType(QualType Ty) const
Definition: ABIInfo.cpp:47
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Definition: ABIInfo.cpp:187
virtual RValue EmitMSVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const
Emit the target dependent code to load a value of.
Definition: ABIInfo.cpp:42
virtual bool isHomogeneousAggregateSmallEnough(const Type *Base, uint64_t Members) const
Definition: ABIInfo.cpp:51
const TargetInfo & getTarget() const
Definition: ABIInfo.cpp:30
virtual RValue EmitVAArg(CodeGen::CodeGenFunction &CGF, CodeGen::Address VAListAddr, QualType Ty, AggValueSlot Slot) const =0
EmitVAArg - Emit the target dependent code to load a value of.
virtual bool isZeroLengthBitfieldPermittedInHomogeneousAggregate() const
Definition: ABIInfo.cpp:56
virtual void computeInfo(CodeGen::CGFunctionInfo &FI) const =0
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
An aggregate value slot.
Definition: CGValue.h:504
RValue asRValue() const
Definition: CGValue.h:666
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:305
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition: CGBuilder.h:241
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::ConstantInt * getSize(CharUnits N)
Definition: CGBuilder.h:99
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:346
RecordArgABI
Specify how one should pass an argument of a record type.
Definition: CGCXXABI.h:150
@ RAA_Default
Pass it using the normal C aggregate rules for the ABI, potentially introducing extra copies and pass...
Definition: CGCXXABI.h:153
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition: CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
RequiredArgs getRequiredArgs() const
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
llvm::Type * ConvertTypeForMem(QualType T)
const TargetInfo & getTarget() const
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
llvm::Type * ConvertType(QualType T)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
const CGFunctionInfo * CurFnInfo
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
This class organizes the cross-function state that is used while generating LLVM code.
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
unsigned getNumRequiredArgs() const
Target specific hooks for defining how a type should be passed or returned from functions with one of...
Definition: ABIInfo.h:130
virtual bool isLegalVectorType(CharUnits VectorSize, llvm::Type *EltTy, unsigned NumElts) const
Returns true if the given vector type is legal from Swift's calling convention perspective.
Definition: ABIInfo.cpp:278
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition: TargetInfo.h:47
virtual bool doesReturnSlotInterfereWithArgs() const
doesReturnSlotInterfereWithArgs - Return true if the target uses an argument slot for an 'sret' type.
Definition: TargetInfo.h:213
virtual bool wouldInliningViolateFunctionCallABI(const FunctionDecl *Caller, const FunctionDecl *Callee) const
Returns true if inlining the function call would produce incorrect code for the current target and sh...
Definition: TargetInfo.h:114
virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const
Retrieve the address of a function to call immediately before calling objc_retainAutoreleasedReturnVa...
Definition: TargetInfo.h:225
static void setBranchProtectionFnAttributes(const TargetInfo::BranchProtectionInfo &BPI, llvm::Function &F)
Definition: TargetInfo.cpp:210
virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, const FunctionDecl *Callee, const CallArgList &Args, QualType ReturnType) const
Any further codegen related checks that need to be done on a function call in a target specific manne...
Definition: TargetInfo.h:95
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:76
virtual void checkFunctionABI(CodeGenModule &CGM, const FunctionDecl *Decl) const
Any further codegen related checks that need to be done on a function signature in a target specific ...
Definition: TargetInfo.h:90
virtual bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, llvm::Type *Ty) const
Target hook to decide whether an inline asm operand can be passed by value.
Definition: TargetInfo.h:198
virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const
Determines the DWARF register number for the stack pointer, for exception-handling purposes.
Definition: TargetInfo.h:142
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
SourceLocation getLocation() const
Definition: DeclBase.h:442
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
Represents a function declaration or definition.
Definition: Decl.h:1935
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5561
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
This represents a decl that may have a name.
Definition: Decl.h:253
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Represents a parameter to a function.
Definition: Decl.h:1725
A (possibly-)qualified type.
Definition: Type.h:929
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
Encodes a location in the source.
bool isUnion() const
Definition: Decl.h:3770
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual StringRef getABI() const
Get the ABI currently in use.
Definition: TargetInfo.h:1330
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:565
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:709
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual bool validateBranchProtection(StringRef Spec, StringRef Arch, BranchProtectionInfo &BPI, StringRef &Err) const
Determine if this TargetInfo supports the given branch protection specification.
Definition: TargetInfo.h:1469
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8510
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isVectorType() const
Definition: Type.h:8298
bool isFloatingType() const
Definition: Type.cpp:2283
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
QualType getType() const
Definition: Decl.h:682
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, const ABIArgInfo &AI)
RValue emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, TypeInfoChars ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign, AggValueSlot Slot, bool ForceRightAdjust=false)
Emit va_arg for a platform using the common void* representation, where arguments are simply emitted ...
Address emitMergePHI(CodeGenFunction &CGF, Address Addr1, llvm::BasicBlock *Block1, Address Addr2, llvm::BasicBlock *Block2, const llvm::Twine &Name="")
bool isEmptyField(ASTContext &Context, const FieldDecl *FD, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyField - Return true iff a the field is "empty", that is it is an unnamed bit-field or an (arra...
llvm::Value * emitRoundPointerUpToAlignment(CodeGenFunction &CGF, llvm::Value *Ptr, CharUnits Align)
bool isAggregateTypeForABI(QualType T)
Definition: ABIInfoImpl.cpp:94
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
Definition: AArch64.cpp:1300
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
Definition: AArch64.cpp:1306
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus
Definition: LangStandard.h:55
const FunctionProtoType * T
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5782
unsigned long uint64_t
#define true
Definition: stdbool.h:25
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58