Bug Summary

File:clang/lib/CodeGen/TargetInfo.cpp
Warning:line 876, column 26
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name TargetInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/TargetInfo.cpp
1//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
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// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TargetInfo.h"
15#include "ABIInfo.h"
16#include "CGBlocks.h"
17#include "CGCXXABI.h"
18#include "CGValue.h"
19#include "CodeGenFunction.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/Basic/CodeGenOptions.h"
23#include "clang/Basic/DiagnosticFrontend.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/CodeGen/CGFunctionInfo.h"
26#include "clang/CodeGen/SwiftCallingConv.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/IntrinsicsNVPTX.h"
34#include "llvm/IR/IntrinsicsS390.h"
35#include "llvm/IR/Type.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm> // std::sort
38
39using namespace clang;
40using namespace CodeGen;
41
42// Helper for coercing an aggregate argument or return value into an integer
43// array of the same size (including padding) and alignment. This alternate
44// coercion happens only for the RenderScript ABI and can be removed after
45// runtimes that rely on it are no longer supported.
46//
47// RenderScript assumes that the size of the argument / return value in the IR
48// is the same as the size of the corresponding qualified type. This helper
49// coerces the aggregate type into an array of the same size (including
50// padding). This coercion is used in lieu of expansion of struct members or
51// other canonical coercions that return a coerced-type of larger size.
52//
53// Ty - The argument / return value type
54// Context - The associated ASTContext
55// LLVMContext - The associated LLVMContext
56static ABIArgInfo coerceToIntArray(QualType Ty,
57 ASTContext &Context,
58 llvm::LLVMContext &LLVMContext) {
59 // Alignment and Size are measured in bits.
60 const uint64_t Size = Context.getTypeSize(Ty);
61 const uint64_t Alignment = Context.getTypeAlign(Ty);
62 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
63 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
64 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
65}
66
67static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68 llvm::Value *Array,
69 llvm::Value *Value,
70 unsigned FirstIndex,
71 unsigned LastIndex) {
72 // Alternatively, we could emit this as a loop in the source.
73 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
74 llvm::Value *Cell =
75 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
76 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
77 }
78}
79
80static bool isAggregateTypeForABI(QualType T) {
81 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
6
Returning the value 1, which participates in a condition later
82 T->isMemberFunctionPointerType();
83}
84
85ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
86 bool Realign,
87 llvm::Type *Padding) const {
88 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
89 Realign, Padding);
90}
91
92ABIArgInfo
93ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
94 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
95 /*ByVal*/ false, Realign);
96}
97
98Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
99 QualType Ty) const {
100 return Address::invalid();
101}
102
103bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
104 if (Ty->isPromotableIntegerType())
105 return true;
106
107 if (const auto *EIT = Ty->getAs<ExtIntType>())
108 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
109 return true;
110
111 return false;
112}
113
114ABIInfo::~ABIInfo() {}
115
116/// Does the given lowering require more than the given number of
117/// registers when expanded?
118///
119/// This is intended to be the basis of a reasonable basic implementation
120/// of should{Pass,Return}IndirectlyForSwift.
121///
122/// For most targets, a limit of four total registers is reasonable; this
123/// limits the amount of code required in order to move around the value
124/// in case it wasn't produced immediately prior to the call by the caller
125/// (or wasn't produced in exactly the right registers) or isn't used
126/// immediately within the callee. But some targets may need to further
127/// limit the register count due to an inability to support that many
128/// return registers.
129static bool occupiesMoreThan(CodeGenTypes &cgt,
130 ArrayRef<llvm::Type*> scalarTypes,
131 unsigned maxAllRegisters) {
132 unsigned intCount = 0, fpCount = 0;
133 for (llvm::Type *type : scalarTypes) {
134 if (type->isPointerTy()) {
135 intCount++;
136 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
137 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
138 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
139 } else {
140 assert(type->isVectorTy() || type->isFloatingPointTy())(static_cast<void> (0));
141 fpCount++;
142 }
143 }
144
145 return (intCount + fpCount > maxAllRegisters);
146}
147
148bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
149 llvm::Type *eltTy,
150 unsigned numElts) const {
151 // The default implementation of this assumes that the target guarantees
152 // 128-bit SIMD support but nothing more.
153 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
154}
155
156static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
157 CGCXXABI &CXXABI) {
158 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
159 if (!RD) {
160 if (!RT->getDecl()->canPassInRegisters())
161 return CGCXXABI::RAA_Indirect;
162 return CGCXXABI::RAA_Default;
163 }
164 return CXXABI.getRecordArgABI(RD);
165}
166
167static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
168 CGCXXABI &CXXABI) {
169 const RecordType *RT = T->getAs<RecordType>();
10
Assuming the object is not a 'RecordType'
170 if (!RT
10.1
'RT' is null
)
11
Taking true branch
171 return CGCXXABI::RAA_Default;
12
Returning zero, which participates in a condition later
172 return getRecordArgABI(RT, CXXABI);
173}
174
175static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
176 const ABIInfo &Info) {
177 QualType Ty = FI.getReturnType();
178
179 if (const auto *RT = Ty->getAs<RecordType>())
180 if (!isa<CXXRecordDecl>(RT->getDecl()) &&
181 !RT->getDecl()->canPassInRegisters()) {
182 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
183 return true;
184 }
185
186 return CXXABI.classifyReturnType(FI);
187}
188
189/// Pass transparent unions as if they were the type of the first element. Sema
190/// should ensure that all elements of the union have the same "machine type".
191static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
192 if (const RecordType *UT = Ty->getAsUnionType()) {
193 const RecordDecl *UD = UT->getDecl();
194 if (UD->hasAttr<TransparentUnionAttr>()) {
195 assert(!UD->field_empty() && "sema created an empty transparent union")(static_cast<void> (0));
196 return UD->field_begin()->getType();
197 }
198 }
199 return Ty;
200}
201
202CGCXXABI &ABIInfo::getCXXABI() const {
203 return CGT.getCXXABI();
204}
205
206ASTContext &ABIInfo::getContext() const {
207 return CGT.getContext();
208}
209
210llvm::LLVMContext &ABIInfo::getVMContext() const {
211 return CGT.getLLVMContext();
212}
213
214const llvm::DataLayout &ABIInfo::getDataLayout() const {
215 return CGT.getDataLayout();
216}
217
218const TargetInfo &ABIInfo::getTarget() const {
219 return CGT.getTarget();
220}
221
222const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
223 return CGT.getCodeGenOpts();
224}
225
226bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
227
228bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
229 return false;
230}
231
232bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
233 uint64_t Members) const {
234 return false;
235}
236
237LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ABIArgInfo::dump() const {
238 raw_ostream &OS = llvm::errs();
239 OS << "(ABIArgInfo Kind=";
240 switch (TheKind) {
241 case Direct:
242 OS << "Direct Type=";
243 if (llvm::Type *Ty = getCoerceToType())
244 Ty->print(OS);
245 else
246 OS << "null";
247 break;
248 case Extend:
249 OS << "Extend";
250 break;
251 case Ignore:
252 OS << "Ignore";
253 break;
254 case InAlloca:
255 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
256 break;
257 case Indirect:
258 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
259 << " ByVal=" << getIndirectByVal()
260 << " Realign=" << getIndirectRealign();
261 break;
262 case IndirectAliased:
263 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264 << " AadrSpace=" << getIndirectAddrSpace()
265 << " Realign=" << getIndirectRealign();
266 break;
267 case Expand:
268 OS << "Expand";
269 break;
270 case CoerceAndExpand:
271 OS << "CoerceAndExpand Type=";
272 getCoerceAndExpandType()->print(OS);
273 break;
274 }
275 OS << ")\n";
276}
277
278// Dynamically round a pointer up to a multiple of the given alignment.
279static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
280 llvm::Value *Ptr,
281 CharUnits Align) {
282 llvm::Value *PtrAsInt = Ptr;
283 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
284 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
285 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
286 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
287 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
288 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
289 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
290 Ptr->getType(),
291 Ptr->getName() + ".aligned");
292 return PtrAsInt;
293}
294
295/// Emit va_arg for a platform using the common void* representation,
296/// where arguments are simply emitted in an array of slots on the stack.
297///
298/// This version implements the core direct-value passing rules.
299///
300/// \param SlotSize - The size and alignment of a stack slot.
301/// Each argument will be allocated to a multiple of this number of
302/// slots, and all the slots will be aligned to this value.
303/// \param AllowHigherAlign - The slot alignment is not a cap;
304/// an argument type with an alignment greater than the slot size
305/// will be emitted on a higher-alignment address, potentially
306/// leaving one or more empty slots behind as padding. If this
307/// is false, the returned address might be less-aligned than
308/// DirectAlign.
309static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
310 Address VAListAddr,
311 llvm::Type *DirectTy,
312 CharUnits DirectSize,
313 CharUnits DirectAlign,
314 CharUnits SlotSize,
315 bool AllowHigherAlign) {
316 // Cast the element type to i8* if necessary. Some platforms define
317 // va_list as a struct containing an i8* instead of just an i8*.
318 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
319 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
320
321 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
322
323 // If the CC aligns values higher than the slot size, do so if needed.
324 Address Addr = Address::invalid();
325 if (AllowHigherAlign && DirectAlign > SlotSize) {
326 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
327 DirectAlign);
328 } else {
329 Addr = Address(Ptr, SlotSize);
330 }
331
332 // Advance the pointer past the argument, then store that back.
333 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
334 Address NextPtr =
335 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
336 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
337
338 // If the argument is smaller than a slot, and this is a big-endian
339 // target, the argument will be right-adjusted in its slot.
340 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
341 !DirectTy->isStructTy()) {
342 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
343 }
344
345 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
346 return Addr;
347}
348
349/// Emit va_arg for a platform using the common void* representation,
350/// where arguments are simply emitted in an array of slots on the stack.
351///
352/// \param IsIndirect - Values of this type are passed indirectly.
353/// \param ValueInfo - The size and alignment of this type, generally
354/// computed with getContext().getTypeInfoInChars(ValueTy).
355/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
356/// Each argument will be allocated to a multiple of this number of
357/// slots, and all the slots will be aligned to this value.
358/// \param AllowHigherAlign - The slot alignment is not a cap;
359/// an argument type with an alignment greater than the slot size
360/// will be emitted on a higher-alignment address, potentially
361/// leaving one or more empty slots behind as padding.
362static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
363 QualType ValueTy, bool IsIndirect,
364 TypeInfoChars ValueInfo,
365 CharUnits SlotSizeAndAlign,
366 bool AllowHigherAlign) {
367 // The size and alignment of the value that was passed directly.
368 CharUnits DirectSize, DirectAlign;
369 if (IsIndirect) {
370 DirectSize = CGF.getPointerSize();
371 DirectAlign = CGF.getPointerAlign();
372 } else {
373 DirectSize = ValueInfo.Width;
374 DirectAlign = ValueInfo.Align;
375 }
376
377 // Cast the address we've calculated to the right type.
378 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
379 if (IsIndirect)
380 DirectTy = DirectTy->getPointerTo(0);
381
382 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
383 DirectSize, DirectAlign,
384 SlotSizeAndAlign,
385 AllowHigherAlign);
386
387 if (IsIndirect) {
388 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
389 }
390
391 return Addr;
392
393}
394
395static Address emitMergePHI(CodeGenFunction &CGF,
396 Address Addr1, llvm::BasicBlock *Block1,
397 Address Addr2, llvm::BasicBlock *Block2,
398 const llvm::Twine &Name = "") {
399 assert(Addr1.getType() == Addr2.getType())(static_cast<void> (0));
400 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
401 PHI->addIncoming(Addr1.getPointer(), Block1);
402 PHI->addIncoming(Addr2.getPointer(), Block2);
403 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
404 return Address(PHI, Align);
405}
406
407TargetCodeGenInfo::~TargetCodeGenInfo() = default;
408
409// If someone can figure out a general rule for this, that would be great.
410// It's probably just doomed to be platform-dependent, though.
411unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
412 // Verified for:
413 // x86-64 FreeBSD, Linux, Darwin
414 // x86-32 FreeBSD, Linux, Darwin
415 // PowerPC Linux, Darwin
416 // ARM Darwin (*not* EABI)
417 // AArch64 Linux
418 return 32;
419}
420
421bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
422 const FunctionNoProtoType *fnType) const {
423 // The following conventions are known to require this to be false:
424 // x86_stdcall
425 // MIPS
426 // For everything else, we just prefer false unless we opt out.
427 return false;
428}
429
430void
431TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
432 llvm::SmallString<24> &Opt) const {
433 // This assumes the user is passing a library name like "rt" instead of a
434 // filename like "librt.a/so", and that they don't care whether it's static or
435 // dynamic.
436 Opt = "-l";
437 Opt += Lib;
438}
439
440unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
441 // OpenCL kernels are called via an explicit runtime API with arguments
442 // set with clSetKernelArg(), not as normal sub-functions.
443 // Return SPIR_KERNEL by default as the kernel calling convention to
444 // ensure the fingerprint is fixed such way that each OpenCL argument
445 // gets one matching argument in the produced kernel function argument
446 // list to enable feasible implementation of clSetKernelArg() with
447 // aggregates etc. In case we would use the default C calling conv here,
448 // clSetKernelArg() might break depending on the target-specific
449 // conventions; different targets might split structs passed as values
450 // to multiple function arguments etc.
451 return llvm::CallingConv::SPIR_KERNEL;
452}
453
454llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
455 llvm::PointerType *T, QualType QT) const {
456 return llvm::ConstantPointerNull::get(T);
457}
458
459LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
460 const VarDecl *D) const {
461 assert(!CGM.getLangOpts().OpenCL &&(static_cast<void> (0))
462 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&(static_cast<void> (0))
463 "Address space agnostic languages only")(static_cast<void> (0));
464 return D ? D->getType().getAddressSpace() : LangAS::Default;
465}
466
467llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
468 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
469 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
470 // Since target may map different address spaces in AST to the same address
471 // space, an address space conversion may end up as a bitcast.
472 if (auto *C = dyn_cast<llvm::Constant>(Src))
473 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
474 // Try to preserve the source's name to make IR more readable.
475 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
476 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
477}
478
479llvm::Constant *
480TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
481 LangAS SrcAddr, LangAS DestAddr,
482 llvm::Type *DestTy) const {
483 // Since target may map different address spaces in AST to the same address
484 // space, an address space conversion may end up as a bitcast.
485 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
486}
487
488llvm::SyncScope::ID
489TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
490 SyncScope Scope,
491 llvm::AtomicOrdering Ordering,
492 llvm::LLVMContext &Ctx) const {
493 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
494}
495
496static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
497
498/// isEmptyField - Return true iff a the field is "empty", that is it
499/// is an unnamed bit-field or an (array of) empty record(s).
500static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
501 bool AllowArrays) {
502 if (FD->isUnnamedBitfield())
503 return true;
504
505 QualType FT = FD->getType();
506
507 // Constant arrays of empty records count as empty, strip them off.
508 // Constant arrays of zero length always count as empty.
509 bool WasArray = false;
510 if (AllowArrays)
511 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
512 if (AT->getSize() == 0)
513 return true;
514 FT = AT->getElementType();
515 // The [[no_unique_address]] special case below does not apply to
516 // arrays of C++ empty records, so we need to remember this fact.
517 WasArray = true;
518 }
519
520 const RecordType *RT = FT->getAs<RecordType>();
521 if (!RT)
522 return false;
523
524 // C++ record fields are never empty, at least in the Itanium ABI.
525 //
526 // FIXME: We should use a predicate for whether this behavior is true in the
527 // current ABI.
528 //
529 // The exception to the above rule are fields marked with the
530 // [[no_unique_address]] attribute (since C++20). Those do count as empty
531 // according to the Itanium ABI. The exception applies only to records,
532 // not arrays of records, so we must also check whether we stripped off an
533 // array type above.
534 if (isa<CXXRecordDecl>(RT->getDecl()) &&
535 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
536 return false;
537
538 return isEmptyRecord(Context, FT, AllowArrays);
539}
540
541/// isEmptyRecord - Return true iff a structure contains only empty
542/// fields. Note that a structure with a flexible array member is not
543/// considered empty.
544static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
545 const RecordType *RT = T->getAs<RecordType>();
546 if (!RT)
547 return false;
548 const RecordDecl *RD = RT->getDecl();
549 if (RD->hasFlexibleArrayMember())
550 return false;
551
552 // If this is a C++ record, check the bases first.
553 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
554 for (const auto &I : CXXRD->bases())
555 if (!isEmptyRecord(Context, I.getType(), true))
556 return false;
557
558 for (const auto *I : RD->fields())
559 if (!isEmptyField(Context, I, AllowArrays))
560 return false;
561 return true;
562}
563
564/// isSingleElementStruct - Determine if a structure is a "single
565/// element struct", i.e. it has exactly one non-empty field or
566/// exactly one field which is itself a single element
567/// struct. Structures with flexible array members are never
568/// considered single element structs.
569///
570/// \return The field declaration for the single non-empty field, if
571/// it exists.
572static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
573 const RecordType *RT = T->getAs<RecordType>();
574 if (!RT)
575 return nullptr;
576
577 const RecordDecl *RD = RT->getDecl();
578 if (RD->hasFlexibleArrayMember())
579 return nullptr;
580
581 const Type *Found = nullptr;
582
583 // If this is a C++ record, check the bases first.
584 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
585 for (const auto &I : CXXRD->bases()) {
586 // Ignore empty records.
587 if (isEmptyRecord(Context, I.getType(), true))
588 continue;
589
590 // If we already found an element then this isn't a single-element struct.
591 if (Found)
592 return nullptr;
593
594 // If this is non-empty and not a single element struct, the composite
595 // cannot be a single element struct.
596 Found = isSingleElementStruct(I.getType(), Context);
597 if (!Found)
598 return nullptr;
599 }
600 }
601
602 // Check for single element.
603 for (const auto *FD : RD->fields()) {
604 QualType FT = FD->getType();
605
606 // Ignore empty fields.
607 if (isEmptyField(Context, FD, true))
608 continue;
609
610 // If we already found an element then this isn't a single-element
611 // struct.
612 if (Found)
613 return nullptr;
614
615 // Treat single element arrays as the element.
616 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
617 if (AT->getSize().getZExtValue() != 1)
618 break;
619 FT = AT->getElementType();
620 }
621
622 if (!isAggregateTypeForABI(FT)) {
623 Found = FT.getTypePtr();
624 } else {
625 Found = isSingleElementStruct(FT, Context);
626 if (!Found)
627 return nullptr;
628 }
629 }
630
631 // We don't consider a struct a single-element struct if it has
632 // padding beyond the element type.
633 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
634 return nullptr;
635
636 return Found;
637}
638
639namespace {
640Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
641 const ABIArgInfo &AI) {
642 // This default implementation defers to the llvm backend's va_arg
643 // instruction. It can handle only passing arguments directly
644 // (typically only handled in the backend for primitive types), or
645 // aggregates passed indirectly by pointer (NOTE: if the "byval"
646 // flag has ABI impact in the callee, this implementation cannot
647 // work.)
648
649 // Only a few cases are covered here at the moment -- those needed
650 // by the default abi.
651 llvm::Value *Val;
652
653 if (AI.isIndirect()) {
654 assert(!AI.getPaddingType() &&(static_cast<void> (0))
655 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
656 assert((static_cast<void> (0))
657 !AI.getIndirectRealign() &&(static_cast<void> (0))
658 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
659
660 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
661 CharUnits TyAlignForABI = TyInfo.Align;
662
663 llvm::Type *BaseTy =
664 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
665 llvm::Value *Addr =
666 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
667 return Address(Addr, TyAlignForABI);
668 } else {
669 assert((AI.isDirect() || AI.isExtend()) &&(static_cast<void> (0))
670 "Unexpected ArgInfo Kind in generic VAArg emitter!")(static_cast<void> (0));
671
672 assert(!AI.getInReg() &&(static_cast<void> (0))
673 "Unexpected InReg seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
674 assert(!AI.getPaddingType() &&(static_cast<void> (0))
675 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
676 assert(!AI.getDirectOffset() &&(static_cast<void> (0))
677 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
678 assert(!AI.getCoerceToType() &&(static_cast<void> (0))
679 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!")(static_cast<void> (0));
680
681 Address Temp = CGF.CreateMemTemp(Ty, "varet");
682 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
683 CGF.Builder.CreateStore(Val, Temp);
684 return Temp;
685 }
686}
687
688/// DefaultABIInfo - The default implementation for ABI specific
689/// details. This implementation provides information which results in
690/// self-consistent and sensible LLVM IR generation, but does not
691/// conform to any particular ABI.
692class DefaultABIInfo : public ABIInfo {
693public:
694 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
695
696 ABIArgInfo classifyReturnType(QualType RetTy) const;
697 ABIArgInfo classifyArgumentType(QualType RetTy) const;
698
699 void computeInfo(CGFunctionInfo &FI) const override {
700 if (!getCXXABI().classifyReturnType(FI))
701 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
702 for (auto &I : FI.arguments())
703 I.info = classifyArgumentType(I.type);
704 }
705
706 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
707 QualType Ty) const override {
708 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
709 }
710};
711
712class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
713public:
714 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
715 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
716};
717
718ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
719 Ty = useFirstFieldIfTransparentUnion(Ty);
720
721 if (isAggregateTypeForABI(Ty)) {
722 // Records with non-trivial destructors/copy-constructors should not be
723 // passed by value.
724 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
725 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
726
727 return getNaturalAlignIndirect(Ty);
728 }
729
730 // Treat an enum type as its underlying type.
731 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
732 Ty = EnumTy->getDecl()->getIntegerType();
733
734 ASTContext &Context = getContext();
735 if (const auto *EIT = Ty->getAs<ExtIntType>())
736 if (EIT->getNumBits() >
737 Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
738 ? Context.Int128Ty
739 : Context.LongLongTy))
740 return getNaturalAlignIndirect(Ty);
741
742 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
743 : ABIArgInfo::getDirect());
744}
745
746ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
747 if (RetTy->isVoidType())
748 return ABIArgInfo::getIgnore();
749
750 if (isAggregateTypeForABI(RetTy))
751 return getNaturalAlignIndirect(RetTy);
752
753 // Treat an enum type as its underlying type.
754 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
755 RetTy = EnumTy->getDecl()->getIntegerType();
756
757 if (const auto *EIT = RetTy->getAs<ExtIntType>())
758 if (EIT->getNumBits() >
759 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
760 ? getContext().Int128Ty
761 : getContext().LongLongTy))
762 return getNaturalAlignIndirect(RetTy);
763
764 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
765 : ABIArgInfo::getDirect());
766}
767
768//===----------------------------------------------------------------------===//
769// WebAssembly ABI Implementation
770//
771// This is a very simple ABI that relies a lot on DefaultABIInfo.
772//===----------------------------------------------------------------------===//
773
774class WebAssemblyABIInfo final : public SwiftABIInfo {
775public:
776 enum ABIKind {
777 MVP = 0,
778 ExperimentalMV = 1,
779 };
780
781private:
782 DefaultABIInfo defaultInfo;
783 ABIKind Kind;
784
785public:
786 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
787 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
788
789private:
790 ABIArgInfo classifyReturnType(QualType RetTy) const;
791 ABIArgInfo classifyArgumentType(QualType Ty) const;
792
793 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
794 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
795 // overload them.
796 void computeInfo(CGFunctionInfo &FI) const override {
797 if (!getCXXABI().classifyReturnType(FI))
1
Assuming the condition is false
2
Taking false branch
798 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
799 for (auto &Arg : FI.arguments())
3
Assuming '__begin2' is not equal to '__end2'
800 Arg.info = classifyArgumentType(Arg.type);
4
Calling 'WebAssemblyABIInfo::classifyArgumentType'
801 }
802
803 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
804 QualType Ty) const override;
805
806 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
807 bool asReturnValue) const override {
808 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
809 }
810
811 bool isSwiftErrorInRegister() const override {
812 return false;
813 }
814};
815
816class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
817public:
818 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
819 WebAssemblyABIInfo::ABIKind K)
820 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
821
822 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
823 CodeGen::CodeGenModule &CGM) const override {
824 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
825 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
826 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
827 llvm::Function *Fn = cast<llvm::Function>(GV);
828 llvm::AttrBuilder B;
829 B.addAttribute("wasm-import-module", Attr->getImportModule());
830 Fn->addFnAttrs(B);
831 }
832 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
833 llvm::Function *Fn = cast<llvm::Function>(GV);
834 llvm::AttrBuilder B;
835 B.addAttribute("wasm-import-name", Attr->getImportName());
836 Fn->addFnAttrs(B);
837 }
838 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
839 llvm::Function *Fn = cast<llvm::Function>(GV);
840 llvm::AttrBuilder B;
841 B.addAttribute("wasm-export-name", Attr->getExportName());
842 Fn->addFnAttrs(B);
843 }
844 }
845
846 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
847 llvm::Function *Fn = cast<llvm::Function>(GV);
848 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
849 Fn->addFnAttr("no-prototype");
850 }
851 }
852};
853
854/// Classify argument of given type \p Ty.
855ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
856 Ty = useFirstFieldIfTransparentUnion(Ty);
857
858 if (isAggregateTypeForABI(Ty)) {
5
Calling 'isAggregateTypeForABI'
7
Returning from 'isAggregateTypeForABI'
8
Taking true branch
859 // Records with non-trivial destructors/copy-constructors should not be
860 // passed by value.
861 if (auto RAA
13.1
'RAA' is 0
= getRecordArgABI(Ty, getCXXABI()))
9
Calling 'getRecordArgABI'
13
Returning from 'getRecordArgABI'
14
Taking false branch
862 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
863 // Ignore empty structs/unions.
864 if (isEmptyRecord(getContext(), Ty, true))
15
Assuming the condition is false
16
Taking false branch
865 return ABIArgInfo::getIgnore();
866 // Lower single-element structs to just pass a regular value. TODO: We
867 // could do reasonable-size multiple-element structs too, using getExpand(),
868 // though watch out for things like bitfields.
869 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
17
Assuming 'SeltTy' is null
18
Taking false branch
870 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
871 // For the experimental multivalue ABI, fully expand all other aggregates
872 if (Kind == ABIKind::ExperimentalMV) {
19
Assuming field 'Kind' is equal to ExperimentalMV
20
Taking true branch
873 const RecordType *RT = Ty->getAs<RecordType>();
21
Assuming the object is not a 'RecordType'
22
'RT' initialized to a null pointer value
874 assert(RT)(static_cast<void> (0));
875 bool HasBitField = false;
876 for (auto *Field : RT->getDecl()->fields()) {
23
Called C++ object pointer is null
877 if (Field->isBitField()) {
878 HasBitField = true;
879 break;
880 }
881 }
882 if (!HasBitField)
883 return ABIArgInfo::getExpand();
884 }
885 }
886
887 // Otherwise just do the default thing.
888 return defaultInfo.classifyArgumentType(Ty);
889}
890
891ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
892 if (isAggregateTypeForABI(RetTy)) {
893 // Records with non-trivial destructors/copy-constructors should not be
894 // returned by value.
895 if (!getRecordArgABI(RetTy, getCXXABI())) {
896 // Ignore empty structs/unions.
897 if (isEmptyRecord(getContext(), RetTy, true))
898 return ABIArgInfo::getIgnore();
899 // Lower single-element structs to just return a regular value. TODO: We
900 // could do reasonable-size multiple-element structs too, using
901 // ABIArgInfo::getDirect().
902 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
903 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
904 // For the experimental multivalue ABI, return all other aggregates
905 if (Kind == ABIKind::ExperimentalMV)
906 return ABIArgInfo::getDirect();
907 }
908 }
909
910 // Otherwise just do the default thing.
911 return defaultInfo.classifyReturnType(RetTy);
912}
913
914Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
915 QualType Ty) const {
916 bool IsIndirect = isAggregateTypeForABI(Ty) &&
917 !isEmptyRecord(getContext(), Ty, true) &&
918 !isSingleElementStruct(Ty, getContext());
919 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
920 getContext().getTypeInfoInChars(Ty),
921 CharUnits::fromQuantity(4),
922 /*AllowHigherAlign=*/true);
923}
924
925//===----------------------------------------------------------------------===//
926// le32/PNaCl bitcode ABI Implementation
927//
928// This is a simplified version of the x86_32 ABI. Arguments and return values
929// are always passed on the stack.
930//===----------------------------------------------------------------------===//
931
932class PNaClABIInfo : public ABIInfo {
933 public:
934 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
935
936 ABIArgInfo classifyReturnType(QualType RetTy) const;
937 ABIArgInfo classifyArgumentType(QualType RetTy) const;
938
939 void computeInfo(CGFunctionInfo &FI) const override;
940 Address EmitVAArg(CodeGenFunction &CGF,
941 Address VAListAddr, QualType Ty) const override;
942};
943
944class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
945 public:
946 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
947 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
948};
949
950void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
951 if (!getCXXABI().classifyReturnType(FI))
952 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
953
954 for (auto &I : FI.arguments())
955 I.info = classifyArgumentType(I.type);
956}
957
958Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
959 QualType Ty) const {
960 // The PNaCL ABI is a bit odd, in that varargs don't use normal
961 // function classification. Structs get passed directly for varargs
962 // functions, through a rewriting transform in
963 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
964 // this target to actually support a va_arg instructions with an
965 // aggregate type, unlike other targets.
966 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
967}
968
969/// Classify argument of given type \p Ty.
970ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
971 if (isAggregateTypeForABI(Ty)) {
972 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
973 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
974 return getNaturalAlignIndirect(Ty);
975 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
976 // Treat an enum type as its underlying type.
977 Ty = EnumTy->getDecl()->getIntegerType();
978 } else if (Ty->isFloatingType()) {
979 // Floating-point types don't go inreg.
980 return ABIArgInfo::getDirect();
981 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
982 // Treat extended integers as integers if <=64, otherwise pass indirectly.
983 if (EIT->getNumBits() > 64)
984 return getNaturalAlignIndirect(Ty);
985 return ABIArgInfo::getDirect();
986 }
987
988 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
989 : ABIArgInfo::getDirect());
990}
991
992ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
993 if (RetTy->isVoidType())
994 return ABIArgInfo::getIgnore();
995
996 // In the PNaCl ABI we always return records/structures on the stack.
997 if (isAggregateTypeForABI(RetTy))
998 return getNaturalAlignIndirect(RetTy);
999
1000 // Treat extended integers as integers if <=64, otherwise pass indirectly.
1001 if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
1002 if (EIT->getNumBits() > 64)
1003 return getNaturalAlignIndirect(RetTy);
1004 return ABIArgInfo::getDirect();
1005 }
1006
1007 // Treat an enum type as its underlying type.
1008 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1009 RetTy = EnumTy->getDecl()->getIntegerType();
1010
1011 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1012 : ABIArgInfo::getDirect());
1013}
1014
1015/// IsX86_MMXType - Return true if this is an MMX type.
1016bool IsX86_MMXType(llvm::Type *IRType) {
1017 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1018 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1019 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1020 IRType->getScalarSizeInBits() != 64;
1021}
1022
1023static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1024 StringRef Constraint,
1025 llvm::Type* Ty) {
1026 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1027 .Cases("y", "&y", "^Ym", true)
1028 .Default(false);
1029 if (IsMMXCons && Ty->isVectorTy()) {
1030 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1031 64) {
1032 // Invalid MMX constraint
1033 return nullptr;
1034 }
1035
1036 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1037 }
1038
1039 // No operation needed
1040 return Ty;
1041}
1042
1043/// Returns true if this type can be passed in SSE registers with the
1044/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1045static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1046 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1047 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1048 if (BT->getKind() == BuiltinType::LongDouble) {
1049 if (&Context.getTargetInfo().getLongDoubleFormat() ==
1050 &llvm::APFloat::x87DoubleExtended())
1051 return false;
1052 }
1053 return true;
1054 }
1055 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1056 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1057 // registers specially.
1058 unsigned VecSize = Context.getTypeSize(VT);
1059 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1060 return true;
1061 }
1062 return false;
1063}
1064
1065/// Returns true if this aggregate is small enough to be passed in SSE registers
1066/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1067static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1068 return NumMembers <= 4;
1069}
1070
1071/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1072static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1073 auto AI = ABIArgInfo::getDirect(T);
1074 AI.setInReg(true);
1075 AI.setCanBeFlattened(false);
1076 return AI;
1077}
1078
1079//===----------------------------------------------------------------------===//
1080// X86-32 ABI Implementation
1081//===----------------------------------------------------------------------===//
1082
1083/// Similar to llvm::CCState, but for Clang.
1084struct CCState {
1085 CCState(CGFunctionInfo &FI)
1086 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1087
1088 llvm::SmallBitVector IsPreassigned;
1089 unsigned CC = CallingConv::CC_C;
1090 unsigned FreeRegs = 0;
1091 unsigned FreeSSERegs = 0;
1092};
1093
1094/// X86_32ABIInfo - The X86-32 ABI information.
1095class X86_32ABIInfo : public SwiftABIInfo {
1096 enum Class {
1097 Integer,
1098 Float
1099 };
1100
1101 static const unsigned MinABIStackAlignInBytes = 4;
1102
1103 bool IsDarwinVectorABI;
1104 bool IsRetSmallStructInRegABI;
1105 bool IsWin32StructABI;
1106 bool IsSoftFloatABI;
1107 bool IsMCUABI;
1108 bool IsLinuxABI;
1109 unsigned DefaultNumRegisterParameters;
1110
1111 static bool isRegisterSize(unsigned Size) {
1112 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1113 }
1114
1115 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1116 // FIXME: Assumes vectorcall is in use.
1117 return isX86VectorTypeForVectorCall(getContext(), Ty);
1118 }
1119
1120 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1121 uint64_t NumMembers) const override {
1122 // FIXME: Assumes vectorcall is in use.
1123 return isX86VectorCallAggregateSmallEnough(NumMembers);
1124 }
1125
1126 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1127
1128 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1129 /// such that the argument will be passed in memory.
1130 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1131
1132 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1133
1134 /// Return the alignment to use for the given type on the stack.
1135 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1136
1137 Class classify(QualType Ty) const;
1138 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1139 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1140
1141 /// Updates the number of available free registers, returns
1142 /// true if any registers were allocated.
1143 bool updateFreeRegs(QualType Ty, CCState &State) const;
1144
1145 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1146 bool &NeedsPadding) const;
1147 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1148
1149 bool canExpandIndirectArgument(QualType Ty) const;
1150
1151 /// Rewrite the function info so that all memory arguments use
1152 /// inalloca.
1153 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1154
1155 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1156 CharUnits &StackOffset, ABIArgInfo &Info,
1157 QualType Type) const;
1158 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1159
1160public:
1161
1162 void computeInfo(CGFunctionInfo &FI) const override;
1163 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1164 QualType Ty) const override;
1165
1166 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1167 bool RetSmallStructInRegABI, bool Win32StructABI,
1168 unsigned NumRegisterParameters, bool SoftFloatABI)
1169 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1170 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1171 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1172 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1173 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux()),
1174 DefaultNumRegisterParameters(NumRegisterParameters) {}
1175
1176 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1177 bool asReturnValue) const override {
1178 // LLVM's x86-32 lowering currently only assigns up to three
1179 // integer registers and three fp registers. Oddly, it'll use up to
1180 // four vector registers for vectors, but those can overlap with the
1181 // scalar registers.
1182 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1183 }
1184
1185 bool isSwiftErrorInRegister() const override {
1186 // x86-32 lowering does not support passing swifterror in a register.
1187 return false;
1188 }
1189};
1190
1191class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1192public:
1193 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1194 bool RetSmallStructInRegABI, bool Win32StructABI,
1195 unsigned NumRegisterParameters, bool SoftFloatABI)
1196 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1197 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1198 NumRegisterParameters, SoftFloatABI)) {}
1199
1200 static bool isStructReturnInRegABI(
1201 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1202
1203 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1204 CodeGen::CodeGenModule &CGM) const override;
1205
1206 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1207 // Darwin uses different dwarf register numbers for EH.
1208 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1209 return 4;
1210 }
1211
1212 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1213 llvm::Value *Address) const override;
1214
1215 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1216 StringRef Constraint,
1217 llvm::Type* Ty) const override {
1218 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1219 }
1220
1221 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1222 std::string &Constraints,
1223 std::vector<llvm::Type *> &ResultRegTypes,
1224 std::vector<llvm::Type *> &ResultTruncRegTypes,
1225 std::vector<LValue> &ResultRegDests,
1226 std::string &AsmString,
1227 unsigned NumOutputs) const override;
1228
1229 llvm::Constant *
1230 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1231 unsigned Sig = (0xeb << 0) | // jmp rel8
1232 (0x06 << 8) | // .+0x08
1233 ('v' << 16) |
1234 ('2' << 24);
1235 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1236 }
1237
1238 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1239 return "movl\t%ebp, %ebp"
1240 "\t\t// marker for objc_retainAutoreleaseReturnValue";
1241 }
1242};
1243
1244}
1245
1246/// Rewrite input constraint references after adding some output constraints.
1247/// In the case where there is one output and one input and we add one output,
1248/// we need to replace all operand references greater than or equal to 1:
1249/// mov $0, $1
1250/// mov eax, $1
1251/// The result will be:
1252/// mov $0, $2
1253/// mov eax, $2
1254static void rewriteInputConstraintReferences(unsigned FirstIn,
1255 unsigned NumNewOuts,
1256 std::string &AsmString) {
1257 std::string Buf;
1258 llvm::raw_string_ostream OS(Buf);
1259 size_t Pos = 0;
1260 while (Pos < AsmString.size()) {
1261 size_t DollarStart = AsmString.find('$', Pos);
1262 if (DollarStart == std::string::npos)
1263 DollarStart = AsmString.size();
1264 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1265 if (DollarEnd == std::string::npos)
1266 DollarEnd = AsmString.size();
1267 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1268 Pos = DollarEnd;
1269 size_t NumDollars = DollarEnd - DollarStart;
1270 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1271 // We have an operand reference.
1272 size_t DigitStart = Pos;
1273 if (AsmString[DigitStart] == '{') {
1274 OS << '{';
1275 ++DigitStart;
1276 }
1277 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1278 if (DigitEnd == std::string::npos)
1279 DigitEnd = AsmString.size();
1280 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1281 unsigned OperandIndex;
1282 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1283 if (OperandIndex >= FirstIn)
1284 OperandIndex += NumNewOuts;
1285 OS << OperandIndex;
1286 } else {
1287 OS << OperandStr;
1288 }
1289 Pos = DigitEnd;
1290 }
1291 }
1292 AsmString = std::move(OS.str());
1293}
1294
1295/// Add output constraints for EAX:EDX because they are return registers.
1296void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1297 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1298 std::vector<llvm::Type *> &ResultRegTypes,
1299 std::vector<llvm::Type *> &ResultTruncRegTypes,
1300 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1301 unsigned NumOutputs) const {
1302 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1303
1304 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1305 // larger.
1306 if (!Constraints.empty())
1307 Constraints += ',';
1308 if (RetWidth <= 32) {
1309 Constraints += "={eax}";
1310 ResultRegTypes.push_back(CGF.Int32Ty);
1311 } else {
1312 // Use the 'A' constraint for EAX:EDX.
1313 Constraints += "=A";
1314 ResultRegTypes.push_back(CGF.Int64Ty);
1315 }
1316
1317 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1318 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1319 ResultTruncRegTypes.push_back(CoerceTy);
1320
1321 // Coerce the integer by bitcasting the return slot pointer.
1322 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1323 CoerceTy->getPointerTo()));
1324 ResultRegDests.push_back(ReturnSlot);
1325
1326 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1327}
1328
1329/// shouldReturnTypeInRegister - Determine if the given type should be
1330/// returned in a register (for the Darwin and MCU ABI).
1331bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1332 ASTContext &Context) const {
1333 uint64_t Size = Context.getTypeSize(Ty);
1334
1335 // For i386, type must be register sized.
1336 // For the MCU ABI, it only needs to be <= 8-byte
1337 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1338 return false;
1339
1340 if (Ty->isVectorType()) {
1341 // 64- and 128- bit vectors inside structures are not returned in
1342 // registers.
1343 if (Size == 64 || Size == 128)
1344 return false;
1345
1346 return true;
1347 }
1348
1349 // If this is a builtin, pointer, enum, complex type, member pointer, or
1350 // member function pointer it is ok.
1351 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1352 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1353 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1354 return true;
1355
1356 // Arrays are treated like records.
1357 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1358 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1359
1360 // Otherwise, it must be a record type.
1361 const RecordType *RT = Ty->getAs<RecordType>();
1362 if (!RT) return false;
1363
1364 // FIXME: Traverse bases here too.
1365
1366 // Structure types are passed in register if all fields would be
1367 // passed in a register.
1368 for (const auto *FD : RT->getDecl()->fields()) {
1369 // Empty fields are ignored.
1370 if (isEmptyField(Context, FD, true))
1371 continue;
1372
1373 // Check fields recursively.
1374 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1375 return false;
1376 }
1377 return true;
1378}
1379
1380static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1381 // Treat complex types as the element type.
1382 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1383 Ty = CTy->getElementType();
1384
1385 // Check for a type which we know has a simple scalar argument-passing
1386 // convention without any padding. (We're specifically looking for 32
1387 // and 64-bit integer and integer-equivalents, float, and double.)
1388 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1389 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1390 return false;
1391
1392 uint64_t Size = Context.getTypeSize(Ty);
1393 return Size == 32 || Size == 64;
1394}
1395
1396static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1397 uint64_t &Size) {
1398 for (const auto *FD : RD->fields()) {
1399 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1400 // argument is smaller than 32-bits, expanding the struct will create
1401 // alignment padding.
1402 if (!is32Or64BitBasicType(FD->getType(), Context))
1403 return false;
1404
1405 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1406 // how to expand them yet, and the predicate for telling if a bitfield still
1407 // counts as "basic" is more complicated than what we were doing previously.
1408 if (FD->isBitField())
1409 return false;
1410
1411 Size += Context.getTypeSize(FD->getType());
1412 }
1413 return true;
1414}
1415
1416static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1417 uint64_t &Size) {
1418 // Don't do this if there are any non-empty bases.
1419 for (const CXXBaseSpecifier &Base : RD->bases()) {
1420 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1421 Size))
1422 return false;
1423 }
1424 if (!addFieldSizes(Context, RD, Size))
1425 return false;
1426 return true;
1427}
1428
1429/// Test whether an argument type which is to be passed indirectly (on the
1430/// stack) would have the equivalent layout if it was expanded into separate
1431/// arguments. If so, we prefer to do the latter to avoid inhibiting
1432/// optimizations.
1433bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1434 // We can only expand structure types.
1435 const RecordType *RT = Ty->getAs<RecordType>();
1436 if (!RT)
1437 return false;
1438 const RecordDecl *RD = RT->getDecl();
1439 uint64_t Size = 0;
1440 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1441 if (!IsWin32StructABI) {
1442 // On non-Windows, we have to conservatively match our old bitcode
1443 // prototypes in order to be ABI-compatible at the bitcode level.
1444 if (!CXXRD->isCLike())
1445 return false;
1446 } else {
1447 // Don't do this for dynamic classes.
1448 if (CXXRD->isDynamicClass())
1449 return false;
1450 }
1451 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1452 return false;
1453 } else {
1454 if (!addFieldSizes(getContext(), RD, Size))
1455 return false;
1456 }
1457
1458 // We can do this if there was no alignment padding.
1459 return Size == getContext().getTypeSize(Ty);
1460}
1461
1462ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1463 // If the return value is indirect, then the hidden argument is consuming one
1464 // integer register.
1465 if (State.FreeRegs) {
1466 --State.FreeRegs;
1467 if (!IsMCUABI)
1468 return getNaturalAlignIndirectInReg(RetTy);
1469 }
1470 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1471}
1472
1473ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1474 CCState &State) const {
1475 if (RetTy->isVoidType())
1476 return ABIArgInfo::getIgnore();
1477
1478 const Type *Base = nullptr;
1479 uint64_t NumElts = 0;
1480 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1481 State.CC == llvm::CallingConv::X86_RegCall) &&
1482 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1483 // The LLVM struct type for such an aggregate should lower properly.
1484 return ABIArgInfo::getDirect();
1485 }
1486
1487 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1488 // On Darwin, some vectors are returned in registers.
1489 if (IsDarwinVectorABI) {
1490 uint64_t Size = getContext().getTypeSize(RetTy);
1491
1492 // 128-bit vectors are a special case; they are returned in
1493 // registers and we need to make sure to pick a type the LLVM
1494 // backend will like.
1495 if (Size == 128)
1496 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1497 llvm::Type::getInt64Ty(getVMContext()), 2));
1498
1499 // Always return in register if it fits in a general purpose
1500 // register, or if it is 64 bits and has a single element.
1501 if ((Size == 8 || Size == 16 || Size == 32) ||
1502 (Size == 64 && VT->getNumElements() == 1))
1503 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1504 Size));
1505
1506 return getIndirectReturnResult(RetTy, State);
1507 }
1508
1509 return ABIArgInfo::getDirect();
1510 }
1511
1512 if (isAggregateTypeForABI(RetTy)) {
1513 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1514 // Structures with flexible arrays are always indirect.
1515 if (RT->getDecl()->hasFlexibleArrayMember())
1516 return getIndirectReturnResult(RetTy, State);
1517 }
1518
1519 // If specified, structs and unions are always indirect.
1520 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1521 return getIndirectReturnResult(RetTy, State);
1522
1523 // Ignore empty structs/unions.
1524 if (isEmptyRecord(getContext(), RetTy, true))
1525 return ABIArgInfo::getIgnore();
1526
1527 // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1528 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1529 QualType ET = getContext().getCanonicalType(CT->getElementType());
1530 if (ET->isFloat16Type())
1531 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1532 llvm::Type::getHalfTy(getVMContext()), 2));
1533 }
1534
1535 // Small structures which are register sized are generally returned
1536 // in a register.
1537 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1538 uint64_t Size = getContext().getTypeSize(RetTy);
1539
1540 // As a special-case, if the struct is a "single-element" struct, and
1541 // the field is of type "float" or "double", return it in a
1542 // floating-point register. (MSVC does not apply this special case.)
1543 // We apply a similar transformation for pointer types to improve the
1544 // quality of the generated IR.
1545 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1546 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1547 || SeltTy->hasPointerRepresentation())
1548 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1549
1550 // FIXME: We should be able to narrow this integer in cases with dead
1551 // padding.
1552 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1553 }
1554
1555 return getIndirectReturnResult(RetTy, State);
1556 }
1557
1558 // Treat an enum type as its underlying type.
1559 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1560 RetTy = EnumTy->getDecl()->getIntegerType();
1561
1562 if (const auto *EIT = RetTy->getAs<ExtIntType>())
1563 if (EIT->getNumBits() > 64)
1564 return getIndirectReturnResult(RetTy, State);
1565
1566 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1567 : ABIArgInfo::getDirect());
1568}
1569
1570static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1571 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1572}
1573
1574static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1575 const RecordType *RT = Ty->getAs<RecordType>();
1576 if (!RT)
1577 return 0;
1578 const RecordDecl *RD = RT->getDecl();
1579
1580 // If this is a C++ record, check the bases first.
1581 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1582 for (const auto &I : CXXRD->bases())
1583 if (!isRecordWithSIMDVectorType(Context, I.getType()))
1584 return false;
1585
1586 for (const auto *i : RD->fields()) {
1587 QualType FT = i->getType();
1588
1589 if (isSIMDVectorType(Context, FT))
1590 return true;
1591
1592 if (isRecordWithSIMDVectorType(Context, FT))
1593 return true;
1594 }
1595
1596 return false;
1597}
1598
1599unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1600 unsigned Align) const {
1601 // Otherwise, if the alignment is less than or equal to the minimum ABI
1602 // alignment, just use the default; the backend will handle this.
1603 if (Align <= MinABIStackAlignInBytes)
1604 return 0; // Use default alignment.
1605
1606 if (IsLinuxABI) {
1607 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1608 // want to spend any effort dealing with the ramifications of ABI breaks.
1609 //
1610 // If the vector type is __m128/__m256/__m512, return the default alignment.
1611 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1612 return Align;
1613 }
1614 // On non-Darwin, the stack type alignment is always 4.
1615 if (!IsDarwinVectorABI) {
1616 // Set explicit alignment, since we may need to realign the top.
1617 return MinABIStackAlignInBytes;
1618 }
1619
1620 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1621 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1622 isRecordWithSIMDVectorType(getContext(), Ty)))
1623 return 16;
1624
1625 return MinABIStackAlignInBytes;
1626}
1627
1628ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1629 CCState &State) const {
1630 if (!ByVal) {
1631 if (State.FreeRegs) {
1632 --State.FreeRegs; // Non-byval indirects just use one pointer.
1633 if (!IsMCUABI)
1634 return getNaturalAlignIndirectInReg(Ty);
1635 }
1636 return getNaturalAlignIndirect(Ty, false);
1637 }
1638
1639 // Compute the byval alignment.
1640 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1641 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1642 if (StackAlign == 0)
1643 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1644
1645 // If the stack alignment is less than the type alignment, realign the
1646 // argument.
1647 bool Realign = TypeAlign > StackAlign;
1648 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1649 /*ByVal=*/true, Realign);
1650}
1651
1652X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1653 const Type *T = isSingleElementStruct(Ty, getContext());
1654 if (!T)
1655 T = Ty.getTypePtr();
1656
1657 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1658 BuiltinType::Kind K = BT->getKind();
1659 if (K == BuiltinType::Float || K == BuiltinType::Double)
1660 return Float;
1661 }
1662 return Integer;
1663}
1664
1665bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1666 if (!IsSoftFloatABI) {
1667 Class C = classify(Ty);
1668 if (C == Float)
1669 return false;
1670 }
1671
1672 unsigned Size = getContext().getTypeSize(Ty);
1673 unsigned SizeInRegs = (Size + 31) / 32;
1674
1675 if (SizeInRegs == 0)
1676 return false;
1677
1678 if (!IsMCUABI) {
1679 if (SizeInRegs > State.FreeRegs) {
1680 State.FreeRegs = 0;
1681 return false;
1682 }
1683 } else {
1684 // The MCU psABI allows passing parameters in-reg even if there are
1685 // earlier parameters that are passed on the stack. Also,
1686 // it does not allow passing >8-byte structs in-register,
1687 // even if there are 3 free registers available.
1688 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1689 return false;
1690 }
1691
1692 State.FreeRegs -= SizeInRegs;
1693 return true;
1694}
1695
1696bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1697 bool &InReg,
1698 bool &NeedsPadding) const {
1699 // On Windows, aggregates other than HFAs are never passed in registers, and
1700 // they do not consume register slots. Homogenous floating-point aggregates
1701 // (HFAs) have already been dealt with at this point.
1702 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1703 return false;
1704
1705 NeedsPadding = false;
1706 InReg = !IsMCUABI;
1707
1708 if (!updateFreeRegs(Ty, State))
1709 return false;
1710
1711 if (IsMCUABI)
1712 return true;
1713
1714 if (State.CC == llvm::CallingConv::X86_FastCall ||
1715 State.CC == llvm::CallingConv::X86_VectorCall ||
1716 State.CC == llvm::CallingConv::X86_RegCall) {
1717 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1718 NeedsPadding = true;
1719
1720 return false;
1721 }
1722
1723 return true;
1724}
1725
1726bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1727 if (!updateFreeRegs(Ty, State))
1728 return false;
1729
1730 if (IsMCUABI)
1731 return false;
1732
1733 if (State.CC == llvm::CallingConv::X86_FastCall ||
1734 State.CC == llvm::CallingConv::X86_VectorCall ||
1735 State.CC == llvm::CallingConv::X86_RegCall) {
1736 if (getContext().getTypeSize(Ty) > 32)
1737 return false;
1738
1739 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1740 Ty->isReferenceType());
1741 }
1742
1743 return true;
1744}
1745
1746void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1747 // Vectorcall x86 works subtly different than in x64, so the format is
1748 // a bit different than the x64 version. First, all vector types (not HVAs)
1749 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1750 // This differs from the x64 implementation, where the first 6 by INDEX get
1751 // registers.
1752 // In the second pass over the arguments, HVAs are passed in the remaining
1753 // vector registers if possible, or indirectly by address. The address will be
1754 // passed in ECX/EDX if available. Any other arguments are passed according to
1755 // the usual fastcall rules.
1756 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1757 for (int I = 0, E = Args.size(); I < E; ++I) {
1758 const Type *Base = nullptr;
1759 uint64_t NumElts = 0;
1760 const QualType &Ty = Args[I].type;
1761 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1762 isHomogeneousAggregate(Ty, Base, NumElts)) {
1763 if (State.FreeSSERegs >= NumElts) {
1764 State.FreeSSERegs -= NumElts;
1765 Args[I].info = ABIArgInfo::getDirectInReg();
1766 State.IsPreassigned.set(I);
1767 }
1768 }
1769 }
1770}
1771
1772ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1773 CCState &State) const {
1774 // FIXME: Set alignment on indirect arguments.
1775 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1776 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1777 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1778
1779 Ty = useFirstFieldIfTransparentUnion(Ty);
1780 TypeInfo TI = getContext().getTypeInfo(Ty);
1781
1782 // Check with the C++ ABI first.
1783 const RecordType *RT = Ty->getAs<RecordType>();
1784 if (RT) {
1785 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1786 if (RAA == CGCXXABI::RAA_Indirect) {
1787 return getIndirectResult(Ty, false, State);
1788 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1789 // The field index doesn't matter, we'll fix it up later.
1790 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1791 }
1792 }
1793
1794 // Regcall uses the concept of a homogenous vector aggregate, similar
1795 // to other targets.
1796 const Type *Base = nullptr;
1797 uint64_t NumElts = 0;
1798 if ((IsRegCall || IsVectorCall) &&
1799 isHomogeneousAggregate(Ty, Base, NumElts)) {
1800 if (State.FreeSSERegs >= NumElts) {
1801 State.FreeSSERegs -= NumElts;
1802
1803 // Vectorcall passes HVAs directly and does not flatten them, but regcall
1804 // does.
1805 if (IsVectorCall)
1806 return getDirectX86Hva();
1807
1808 if (Ty->isBuiltinType() || Ty->isVectorType())
1809 return ABIArgInfo::getDirect();
1810 return ABIArgInfo::getExpand();
1811 }
1812 return getIndirectResult(Ty, /*ByVal=*/false, State);
1813 }
1814
1815 if (isAggregateTypeForABI(Ty)) {
1816 // Structures with flexible arrays are always indirect.
1817 // FIXME: This should not be byval!
1818 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1819 return getIndirectResult(Ty, true, State);
1820
1821 // Ignore empty structs/unions on non-Windows.
1822 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1823 return ABIArgInfo::getIgnore();
1824
1825 llvm::LLVMContext &LLVMContext = getVMContext();
1826 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1827 bool NeedsPadding = false;
1828 bool InReg;
1829 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1830 unsigned SizeInRegs = (TI.Width + 31) / 32;
1831 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1832 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1833 if (InReg)
1834 return ABIArgInfo::getDirectInReg(Result);
1835 else
1836 return ABIArgInfo::getDirect(Result);
1837 }
1838 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1839
1840 // Pass over-aligned aggregates on Windows indirectly. This behavior was
1841 // added in MSVC 2015.
1842 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1843 return getIndirectResult(Ty, /*ByVal=*/false, State);
1844
1845 // Expand small (<= 128-bit) record types when we know that the stack layout
1846 // of those arguments will match the struct. This is important because the
1847 // LLVM backend isn't smart enough to remove byval, which inhibits many
1848 // optimizations.
1849 // Don't do this for the MCU if there are still free integer registers
1850 // (see X86_64 ABI for full explanation).
1851 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1852 canExpandIndirectArgument(Ty))
1853 return ABIArgInfo::getExpandWithPadding(
1854 IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1855
1856 return getIndirectResult(Ty, true, State);
1857 }
1858
1859 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1860 // On Windows, vectors are passed directly if registers are available, or
1861 // indirectly if not. This avoids the need to align argument memory. Pass
1862 // user-defined vector types larger than 512 bits indirectly for simplicity.
1863 if (IsWin32StructABI) {
1864 if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1865 --State.FreeSSERegs;
1866 return ABIArgInfo::getDirectInReg();
1867 }
1868 return getIndirectResult(Ty, /*ByVal=*/false, State);
1869 }
1870
1871 // On Darwin, some vectors are passed in memory, we handle this by passing
1872 // it as an i8/i16/i32/i64.
1873 if (IsDarwinVectorABI) {
1874 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1875 (TI.Width == 64 && VT->getNumElements() == 1))
1876 return ABIArgInfo::getDirect(
1877 llvm::IntegerType::get(getVMContext(), TI.Width));
1878 }
1879
1880 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1881 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1882
1883 return ABIArgInfo::getDirect();
1884 }
1885
1886
1887 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1888 Ty = EnumTy->getDecl()->getIntegerType();
1889
1890 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1891
1892 if (isPromotableIntegerTypeForABI(Ty)) {
1893 if (InReg)
1894 return ABIArgInfo::getExtendInReg(Ty);
1895 return ABIArgInfo::getExtend(Ty);
1896 }
1897
1898 if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1899 if (EIT->getNumBits() <= 64) {
1900 if (InReg)
1901 return ABIArgInfo::getDirectInReg();
1902 return ABIArgInfo::getDirect();
1903 }
1904 return getIndirectResult(Ty, /*ByVal=*/false, State);
1905 }
1906
1907 if (InReg)
1908 return ABIArgInfo::getDirectInReg();
1909 return ABIArgInfo::getDirect();
1910}
1911
1912void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1913 CCState State(FI);
1914 if (IsMCUABI)
1915 State.FreeRegs = 3;
1916 else if (State.CC == llvm::CallingConv::X86_FastCall) {
1917 State.FreeRegs = 2;
1918 State.FreeSSERegs = 3;
1919 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1920 State.FreeRegs = 2;
1921 State.FreeSSERegs = 6;
1922 } else if (FI.getHasRegParm())
1923 State.FreeRegs = FI.getRegParm();
1924 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1925 State.FreeRegs = 5;
1926 State.FreeSSERegs = 8;
1927 } else if (IsWin32StructABI) {
1928 // Since MSVC 2015, the first three SSE vectors have been passed in
1929 // registers. The rest are passed indirectly.
1930 State.FreeRegs = DefaultNumRegisterParameters;
1931 State.FreeSSERegs = 3;
1932 } else
1933 State.FreeRegs = DefaultNumRegisterParameters;
1934
1935 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1936 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1937 } else if (FI.getReturnInfo().isIndirect()) {
1938 // The C++ ABI is not aware of register usage, so we have to check if the
1939 // return value was sret and put it in a register ourselves if appropriate.
1940 if (State.FreeRegs) {
1941 --State.FreeRegs; // The sret parameter consumes a register.
1942 if (!IsMCUABI)
1943 FI.getReturnInfo().setInReg(true);
1944 }
1945 }
1946
1947 // The chain argument effectively gives us another free register.
1948 if (FI.isChainCall())
1949 ++State.FreeRegs;
1950
1951 // For vectorcall, do a first pass over the arguments, assigning FP and vector
1952 // arguments to XMM registers as available.
1953 if (State.CC == llvm::CallingConv::X86_VectorCall)
1954 runVectorCallFirstPass(FI, State);
1955
1956 bool UsedInAlloca = false;
1957 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1958 for (int I = 0, E = Args.size(); I < E; ++I) {
1959 // Skip arguments that have already been assigned.
1960 if (State.IsPreassigned.test(I))
1961 continue;
1962
1963 Args[I].info = classifyArgumentType(Args[I].type, State);
1964 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1965 }
1966
1967 // If we needed to use inalloca for any argument, do a second pass and rewrite
1968 // all the memory arguments to use inalloca.
1969 if (UsedInAlloca)
1970 rewriteWithInAlloca(FI);
1971}
1972
1973void
1974X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1975 CharUnits &StackOffset, ABIArgInfo &Info,
1976 QualType Type) const {
1977 // Arguments are always 4-byte-aligned.
1978 CharUnits WordSize = CharUnits::fromQuantity(4);
1979 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct")(static_cast<void> (0));
1980
1981 // sret pointers and indirect things will require an extra pointer
1982 // indirection, unless they are byval. Most things are byval, and will not
1983 // require this indirection.
1984 bool IsIndirect = false;
1985 if (Info.isIndirect() && !Info.getIndirectByVal())
1986 IsIndirect = true;
1987 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1988 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1989 if (IsIndirect)
1990 LLTy = LLTy->getPointerTo(0);
1991 FrameFields.push_back(LLTy);
1992 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1993
1994 // Insert padding bytes to respect alignment.
1995 CharUnits FieldEnd = StackOffset;
1996 StackOffset = FieldEnd.alignTo(WordSize);
1997 if (StackOffset != FieldEnd) {
1998 CharUnits NumBytes = StackOffset - FieldEnd;
1999 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2000 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2001 FrameFields.push_back(Ty);
2002 }
2003}
2004
2005static bool isArgInAlloca(const ABIArgInfo &Info) {
2006 // Leave ignored and inreg arguments alone.
2007 switch (Info.getKind()) {
2008 case ABIArgInfo::InAlloca:
2009 return true;
2010 case ABIArgInfo::Ignore:
2011 case ABIArgInfo::IndirectAliased:
2012 return false;
2013 case ABIArgInfo::Indirect:
2014 case ABIArgInfo::Direct:
2015 case ABIArgInfo::Extend:
2016 return !Info.getInReg();
2017 case ABIArgInfo::Expand:
2018 case ABIArgInfo::CoerceAndExpand:
2019 // These are aggregate types which are never passed in registers when
2020 // inalloca is involved.
2021 return true;
2022 }
2023 llvm_unreachable("invalid enum")__builtin_unreachable();
2024}
2025
2026void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2027 assert(IsWin32StructABI && "inalloca only supported on win32")(static_cast<void> (0));
2028
2029 // Build a packed struct type for all of the arguments in memory.
2030 SmallVector<llvm::Type *, 6> FrameFields;
2031
2032 // The stack alignment is always 4.
2033 CharUnits StackAlign = CharUnits::fromQuantity(4);
2034
2035 CharUnits StackOffset;
2036 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2037
2038 // Put 'this' into the struct before 'sret', if necessary.
2039 bool IsThisCall =
2040 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2041 ABIArgInfo &Ret = FI.getReturnInfo();
2042 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2043 isArgInAlloca(I->info)) {
2044 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2045 ++I;
2046 }
2047
2048 // Put the sret parameter into the inalloca struct if it's in memory.
2049 if (Ret.isIndirect() && !Ret.getInReg()) {
2050 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2051 // On Windows, the hidden sret parameter is always returned in eax.
2052 Ret.setInAllocaSRet(IsWin32StructABI);
2053 }
2054
2055 // Skip the 'this' parameter in ecx.
2056 if (IsThisCall)
2057 ++I;
2058
2059 // Put arguments passed in memory into the struct.
2060 for (; I != E; ++I) {
2061 if (isArgInAlloca(I->info))
2062 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2063 }
2064
2065 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2066 /*isPacked=*/true),
2067 StackAlign);
2068}
2069
2070Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2071 Address VAListAddr, QualType Ty) const {
2072
2073 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2074
2075 // x86-32 changes the alignment of certain arguments on the stack.
2076 //
2077 // Just messing with TypeInfo like this works because we never pass
2078 // anything indirectly.
2079 TypeInfo.Align = CharUnits::fromQuantity(
2080 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2081
2082 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2083 TypeInfo, CharUnits::fromQuantity(4),
2084 /*AllowHigherAlign*/ true);
2085}
2086
2087bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2088 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2089 assert(Triple.getArch() == llvm::Triple::x86)(static_cast<void> (0));
2090
2091 switch (Opts.getStructReturnConvention()) {
2092 case CodeGenOptions::SRCK_Default:
2093 break;
2094 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
2095 return false;
2096 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
2097 return true;
2098 }
2099
2100 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2101 return true;
2102
2103 switch (Triple.getOS()) {
2104 case llvm::Triple::DragonFly:
2105 case llvm::Triple::FreeBSD:
2106 case llvm::Triple::OpenBSD:
2107 case llvm::Triple::Win32:
2108 return true;
2109 default:
2110 return false;
2111 }
2112}
2113
2114static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2115 CodeGen::CodeGenModule &CGM) {
2116 if (!FD->hasAttr<AnyX86InterruptAttr>())
2117 return;
2118
2119 llvm::Function *Fn = cast<llvm::Function>(GV);
2120 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2121 if (FD->getNumParams() == 0)
2122 return;
2123
2124 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2125 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2126 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2127 Fn->getContext(), ByValTy);
2128 Fn->addParamAttr(0, NewAttr);
2129}
2130
2131void X86_32TargetCodeGenInfo::setTargetAttributes(
2132 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2133 if (GV->isDeclaration())
2134 return;
2135 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2136 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2137 llvm::Function *Fn = cast<llvm::Function>(GV);
2138 Fn->addFnAttr("stackrealign");
2139 }
2140
2141 addX86InterruptAttrs(FD, GV, CGM);
2142 }
2143}
2144
2145bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2146 CodeGen::CodeGenFunction &CGF,
2147 llvm::Value *Address) const {
2148 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2149
2150 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2151
2152 // 0-7 are the eight integer registers; the order is different
2153 // on Darwin (for EH), but the range is the same.
2154 // 8 is %eip.
2155 AssignToArrayRange(Builder, Address, Four8, 0, 8);
2156
2157 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2158 // 12-16 are st(0..4). Not sure why we stop at 4.
2159 // These have size 16, which is sizeof(long double) on
2160 // platforms with 8-byte alignment for that type.
2161 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2162 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2163
2164 } else {
2165 // 9 is %eflags, which doesn't get a size on Darwin for some
2166 // reason.
2167 Builder.CreateAlignedStore(
2168 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2169 CharUnits::One());
2170
2171 // 11-16 are st(0..5). Not sure why we stop at 5.
2172 // These have size 12, which is sizeof(long double) on
2173 // platforms with 4-byte alignment for that type.
2174 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2175 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2176 }
2177
2178 return false;
2179}
2180
2181//===----------------------------------------------------------------------===//
2182// X86-64 ABI Implementation
2183//===----------------------------------------------------------------------===//
2184
2185
2186namespace {
2187/// The AVX ABI level for X86 targets.
2188enum class X86AVXABILevel {
2189 None,
2190 AVX,
2191 AVX512
2192};
2193
2194/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2195static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2196 switch (AVXLevel) {
2197 case X86AVXABILevel::AVX512:
2198 return 512;
2199 case X86AVXABILevel::AVX:
2200 return 256;
2201 case X86AVXABILevel::None:
2202 return 128;
2203 }
2204 llvm_unreachable("Unknown AVXLevel")__builtin_unreachable();
2205}
2206
2207/// X86_64ABIInfo - The X86_64 ABI information.
2208class X86_64ABIInfo : public SwiftABIInfo {
2209 enum Class {
2210 Integer = 0,
2211 SSE,
2212 SSEUp,
2213 X87,
2214 X87Up,
2215 ComplexX87,
2216 NoClass,
2217 Memory
2218 };
2219
2220 /// merge - Implement the X86_64 ABI merging algorithm.
2221 ///
2222 /// Merge an accumulating classification \arg Accum with a field
2223 /// classification \arg Field.
2224 ///
2225 /// \param Accum - The accumulating classification. This should
2226 /// always be either NoClass or the result of a previous merge
2227 /// call. In addition, this should never be Memory (the caller
2228 /// should just return Memory for the aggregate).
2229 static Class merge(Class Accum, Class Field);
2230
2231 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2232 ///
2233 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2234 /// final MEMORY or SSE classes when necessary.
2235 ///
2236 /// \param AggregateSize - The size of the current aggregate in
2237 /// the classification process.
2238 ///
2239 /// \param Lo - The classification for the parts of the type
2240 /// residing in the low word of the containing object.
2241 ///
2242 /// \param Hi - The classification for the parts of the type
2243 /// residing in the higher words of the containing object.
2244 ///
2245 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2246
2247 /// classify - Determine the x86_64 register classes in which the
2248 /// given type T should be passed.
2249 ///
2250 /// \param Lo - The classification for the parts of the type
2251 /// residing in the low word of the containing object.
2252 ///
2253 /// \param Hi - The classification for the parts of the type
2254 /// residing in the high word of the containing object.
2255 ///
2256 /// \param OffsetBase - The bit offset of this type in the
2257 /// containing object. Some parameters are classified different
2258 /// depending on whether they straddle an eightbyte boundary.
2259 ///
2260 /// \param isNamedArg - Whether the argument in question is a "named"
2261 /// argument, as used in AMD64-ABI 3.5.7.
2262 ///
2263 /// If a word is unused its result will be NoClass; if a type should
2264 /// be passed in Memory then at least the classification of \arg Lo
2265 /// will be Memory.
2266 ///
2267 /// The \arg Lo class will be NoClass iff the argument is ignored.
2268 ///
2269 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2270 /// also be ComplexX87.
2271 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2272 bool isNamedArg) const;
2273
2274 llvm::Type *GetByteVectorType(QualType Ty) const;
2275 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2276 unsigned IROffset, QualType SourceTy,
2277 unsigned SourceOffset) const;
2278 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2279 unsigned IROffset, QualType SourceTy,
2280 unsigned SourceOffset) const;
2281
2282 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2283 /// such that the argument will be returned in memory.
2284 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2285
2286 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2287 /// such that the argument will be passed in memory.
2288 ///
2289 /// \param freeIntRegs - The number of free integer registers remaining
2290 /// available.
2291 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2292
2293 ABIArgInfo classifyReturnType(QualType RetTy) const;
2294
2295 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2296 unsigned &neededInt, unsigned &neededSSE,
2297 bool isNamedArg) const;
2298
2299 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2300 unsigned &NeededSSE) const;
2301
2302 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2303 unsigned &NeededSSE) const;
2304
2305 bool IsIllegalVectorType(QualType Ty) const;
2306
2307 /// The 0.98 ABI revision clarified a lot of ambiguities,
2308 /// unfortunately in ways that were not always consistent with
2309 /// certain previous compilers. In particular, platforms which
2310 /// required strict binary compatibility with older versions of GCC
2311 /// may need to exempt themselves.
2312 bool honorsRevision0_98() const {
2313 return !getTarget().getTriple().isOSDarwin();
2314 }
2315
2316 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2317 /// classify it as INTEGER (for compatibility with older clang compilers).
2318 bool classifyIntegerMMXAsSSE() const {
2319 // Clang <= 3.8 did not do this.
2320 if (getContext().getLangOpts().getClangABICompat() <=
2321 LangOptions::ClangABI::Ver3_8)
2322 return false;
2323
2324 const llvm::Triple &Triple = getTarget().getTriple();
2325 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2326 return false;
2327 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2328 return false;
2329 return true;
2330 }
2331
2332 // GCC classifies vectors of __int128 as memory.
2333 bool passInt128VectorsInMem() const {
2334 // Clang <= 9.0 did not do this.
2335 if (getContext().getLangOpts().getClangABICompat() <=
2336 LangOptions::ClangABI::Ver9)
2337 return false;
2338
2339 const llvm::Triple &T = getTarget().getTriple();
2340 return T.isOSLinux() || T.isOSNetBSD();
2341 }
2342
2343 X86AVXABILevel AVXLevel;
2344 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2345 // 64-bit hardware.
2346 bool Has64BitPointers;
2347
2348public:
2349 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2350 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2351 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2352 }
2353
2354 bool isPassedUsingAVXType(QualType type) const {
2355 unsigned neededInt, neededSSE;
2356 // The freeIntRegs argument doesn't matter here.
2357 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2358 /*isNamedArg*/true);
2359 if (info.isDirect()) {
2360 llvm::Type *ty = info.getCoerceToType();
2361 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2362 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2363 }
2364 return false;
2365 }
2366
2367 void computeInfo(CGFunctionInfo &FI) const override;
2368
2369 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2370 QualType Ty) const override;
2371 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2372 QualType Ty) const override;
2373
2374 bool has64BitPointers() const {
2375 return Has64BitPointers;
2376 }
2377
2378 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2379 bool asReturnValue) const override {
2380 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2381 }
2382 bool isSwiftErrorInRegister() const override {
2383 return true;
2384 }
2385};
2386
2387/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2388class WinX86_64ABIInfo : public SwiftABIInfo {
2389public:
2390 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2391 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2392 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2393
2394 void computeInfo(CGFunctionInfo &FI) const override;
2395
2396 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2397 QualType Ty) const override;
2398
2399 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2400 // FIXME: Assumes vectorcall is in use.
2401 return isX86VectorTypeForVectorCall(getContext(), Ty);
2402 }
2403
2404 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2405 uint64_t NumMembers) const override {
2406 // FIXME: Assumes vectorcall is in use.
2407 return isX86VectorCallAggregateSmallEnough(NumMembers);
2408 }
2409
2410 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2411 bool asReturnValue) const override {
2412 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2413 }
2414
2415 bool isSwiftErrorInRegister() const override {
2416 return true;
2417 }
2418
2419private:
2420 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2421 bool IsVectorCall, bool IsRegCall) const;
2422 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2423 const ABIArgInfo &current) const;
2424
2425 X86AVXABILevel AVXLevel;
2426
2427 bool IsMingw64;
2428};
2429
2430class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2431public:
2432 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2433 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2434
2435 const X86_64ABIInfo &getABIInfo() const {
2436 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2437 }
2438
2439 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2440 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2441 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2442
2443 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2444 return 7;
2445 }
2446
2447 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2448 llvm::Value *Address) const override {
2449 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2450
2451 // 0-15 are the 16 integer registers.
2452 // 16 is %rip.
2453 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2454 return false;
2455 }
2456
2457 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2458 StringRef Constraint,
2459 llvm::Type* Ty) const override {
2460 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2461 }
2462
2463 bool isNoProtoCallVariadic(const CallArgList &args,
2464 const FunctionNoProtoType *fnType) const override {
2465 // The default CC on x86-64 sets %al to the number of SSA
2466 // registers used, and GCC sets this when calling an unprototyped
2467 // function, so we override the default behavior. However, don't do
2468 // that when AVX types are involved: the ABI explicitly states it is
2469 // undefined, and it doesn't work in practice because of how the ABI
2470 // defines varargs anyway.
2471 if (fnType->getCallConv() == CC_C) {
2472 bool HasAVXType = false;
2473 for (CallArgList::const_iterator
2474 it = args.begin(), ie = args.end(); it != ie; ++it) {
2475 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2476 HasAVXType = true;
2477 break;
2478 }
2479 }
2480
2481 if (!HasAVXType)
2482 return true;
2483 }
2484
2485 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2486 }
2487
2488 llvm::Constant *
2489 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2490 unsigned Sig = (0xeb << 0) | // jmp rel8
2491 (0x06 << 8) | // .+0x08
2492 ('v' << 16) |
2493 ('2' << 24);
2494 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2495 }
2496
2497 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2498 CodeGen::CodeGenModule &CGM) const override {
2499 if (GV->isDeclaration())
2500 return;
2501 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2502 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2503 llvm::Function *Fn = cast<llvm::Function>(GV);
2504 Fn->addFnAttr("stackrealign");
2505 }
2506
2507 addX86InterruptAttrs(FD, GV, CGM);
2508 }
2509 }
2510
2511 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2512 const FunctionDecl *Caller,
2513 const FunctionDecl *Callee,
2514 const CallArgList &Args) const override;
2515};
2516
2517static void initFeatureMaps(const ASTContext &Ctx,
2518 llvm::StringMap<bool> &CallerMap,
2519 const FunctionDecl *Caller,
2520 llvm::StringMap<bool> &CalleeMap,
2521 const FunctionDecl *Callee) {
2522 if (CalleeMap.empty() && CallerMap.empty()) {
2523 // The caller is potentially nullptr in the case where the call isn't in a
2524 // function. In this case, the getFunctionFeatureMap ensures we just get
2525 // the TU level setting (since it cannot be modified by 'target'..
2526 Ctx.getFunctionFeatureMap(CallerMap, Caller);
2527 Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2528 }
2529}
2530
2531static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2532 SourceLocation CallLoc,
2533 const llvm::StringMap<bool> &CallerMap,
2534 const llvm::StringMap<bool> &CalleeMap,
2535 QualType Ty, StringRef Feature,
2536 bool IsArgument) {
2537 bool CallerHasFeat = CallerMap.lookup(Feature);
2538 bool CalleeHasFeat = CalleeMap.lookup(Feature);
2539 if (!CallerHasFeat && !CalleeHasFeat)
2540 return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2541 << IsArgument << Ty << Feature;
2542
2543 // Mixing calling conventions here is very clearly an error.
2544 if (!CallerHasFeat || !CalleeHasFeat)
2545 return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2546 << IsArgument << Ty << Feature;
2547
2548 // Else, both caller and callee have the required feature, so there is no need
2549 // to diagnose.
2550 return false;
2551}
2552
2553static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2554 SourceLocation CallLoc,
2555 const llvm::StringMap<bool> &CallerMap,
2556 const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2557 bool IsArgument) {
2558 uint64_t Size = Ctx.getTypeSize(Ty);
2559 if (Size > 256)
2560 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2561 "avx512f", IsArgument);
2562
2563 if (Size > 128)
2564 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2565 IsArgument);
2566
2567 return false;
2568}
2569
2570void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2571 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2572 const FunctionDecl *Callee, const CallArgList &Args) const {
2573 llvm::StringMap<bool> CallerMap;
2574 llvm::StringMap<bool> CalleeMap;
2575 unsigned ArgIndex = 0;
2576
2577 // We need to loop through the actual call arguments rather than the the
2578 // function's parameters, in case this variadic.
2579 for (const CallArg &Arg : Args) {
2580 // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2581 // additionally changes how vectors >256 in size are passed. Like GCC, we
2582 // warn when a function is called with an argument where this will change.
2583 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2584 // the caller and callee features are mismatched.
2585 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2586 // change its ABI with attribute-target after this call.
2587 if (Arg.getType()->isVectorType() &&
2588 CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2589 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2590 QualType Ty = Arg.getType();
2591 // The CallArg seems to have desugared the type already, so for clearer
2592 // diagnostics, replace it with the type in the FunctionDecl if possible.
2593 if (ArgIndex < Callee->getNumParams())
2594 Ty = Callee->getParamDecl(ArgIndex)->getType();
2595
2596 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2597 CalleeMap, Ty, /*IsArgument*/ true))
2598 return;
2599 }
2600 ++ArgIndex;
2601 }
2602
2603 // Check return always, as we don't have a good way of knowing in codegen
2604 // whether this value is used, tail-called, etc.
2605 if (Callee->getReturnType()->isVectorType() &&
2606 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2607 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2608 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2609 CalleeMap, Callee->getReturnType(),
2610 /*IsArgument*/ false);
2611 }
2612}
2613
2614static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2615 // If the argument does not end in .lib, automatically add the suffix.
2616 // If the argument contains a space, enclose it in quotes.
2617 // This matches the behavior of MSVC.
2618 bool Quote = (Lib.find(' ') != StringRef::npos);
2619 std::string ArgStr = Quote ? "\"" : "";
2620 ArgStr += Lib;
2621 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2622 ArgStr += ".lib";
2623 ArgStr += Quote ? "\"" : "";
2624 return ArgStr;
2625}
2626
2627class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2628public:
2629 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2630 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2631 unsigned NumRegisterParameters)
2632 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2633 Win32StructABI, NumRegisterParameters, false) {}
2634
2635 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2636 CodeGen::CodeGenModule &CGM) const override;
2637
2638 void getDependentLibraryOption(llvm::StringRef Lib,
2639 llvm::SmallString<24> &Opt) const override {
2640 Opt = "/DEFAULTLIB:";
2641 Opt += qualifyWindowsLibrary(Lib);
2642 }
2643
2644 void getDetectMismatchOption(llvm::StringRef Name,
2645 llvm::StringRef Value,
2646 llvm::SmallString<32> &Opt) const override {
2647 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2648 }
2649};
2650
2651static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2652 CodeGen::CodeGenModule &CGM) {
2653 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2654
2655 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2656 Fn->addFnAttr("stack-probe-size",
2657 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2658 if (CGM.getCodeGenOpts().NoStackArgProbe)
2659 Fn->addFnAttr("no-stack-arg-probe");
2660 }
2661}
2662
2663void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2664 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2665 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2666 if (GV->isDeclaration())
2667 return;
2668 addStackProbeTargetAttributes(D, GV, CGM);
2669}
2670
2671class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2672public:
2673 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2674 X86AVXABILevel AVXLevel)
2675 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2676
2677 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2678 CodeGen::CodeGenModule &CGM) const override;
2679
2680 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2681 return 7;
2682 }
2683
2684 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2685 llvm::Value *Address) const override {
2686 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2687
2688 // 0-15 are the 16 integer registers.
2689 // 16 is %rip.
2690 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2691 return false;
2692 }
2693
2694 void getDependentLibraryOption(llvm::StringRef Lib,
2695 llvm::SmallString<24> &Opt) const override {
2696 Opt = "/DEFAULTLIB:";
2697 Opt += qualifyWindowsLibrary(Lib);
2698 }
2699
2700 void getDetectMismatchOption(llvm::StringRef Name,
2701 llvm::StringRef Value,
2702 llvm::SmallString<32> &Opt) const override {
2703 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2704 }
2705};
2706
2707void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2708 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2709 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2710 if (GV->isDeclaration())
2711 return;
2712 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2713 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2714 llvm::Function *Fn = cast<llvm::Function>(GV);
2715 Fn->addFnAttr("stackrealign");
2716 }
2717
2718 addX86InterruptAttrs(FD, GV, CGM);
2719 }
2720
2721 addStackProbeTargetAttributes(D, GV, CGM);
2722}
2723}
2724
2725void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2726 Class &Hi) const {
2727 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2728 //
2729 // (a) If one of the classes is Memory, the whole argument is passed in
2730 // memory.
2731 //
2732 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2733 // memory.
2734 //
2735 // (c) If the size of the aggregate exceeds two eightbytes and the first
2736 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2737 // argument is passed in memory. NOTE: This is necessary to keep the
2738 // ABI working for processors that don't support the __m256 type.
2739 //
2740 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2741 //
2742 // Some of these are enforced by the merging logic. Others can arise
2743 // only with unions; for example:
2744 // union { _Complex double; unsigned; }
2745 //
2746 // Note that clauses (b) and (c) were added in 0.98.
2747 //
2748 if (Hi == Memory)
2749 Lo = Memory;
2750 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2751 Lo = Memory;
2752 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2753 Lo = Memory;
2754 if (Hi == SSEUp && Lo != SSE)
2755 Hi = SSE;
2756}
2757
2758X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2759 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2760 // classified recursively so that always two fields are
2761 // considered. The resulting class is calculated according to
2762 // the classes of the fields in the eightbyte:
2763 //
2764 // (a) If both classes are equal, this is the resulting class.
2765 //
2766 // (b) If one of the classes is NO_CLASS, the resulting class is
2767 // the other class.
2768 //
2769 // (c) If one of the classes is MEMORY, the result is the MEMORY
2770 // class.
2771 //
2772 // (d) If one of the classes is INTEGER, the result is the
2773 // INTEGER.
2774 //
2775 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2776 // MEMORY is used as class.
2777 //
2778 // (f) Otherwise class SSE is used.
2779
2780 // Accum should never be memory (we should have returned) or
2781 // ComplexX87 (because this cannot be passed in a structure).
2782 assert((Accum != Memory && Accum != ComplexX87) &&(static_cast<void> (0))
2783 "Invalid accumulated classification during merge.")(static_cast<void> (0));
2784 if (Accum == Field || Field == NoClass)
2785 return Accum;
2786 if (Field == Memory)
2787 return Memory;
2788 if (Accum == NoClass)
2789 return Field;
2790 if (Accum == Integer || Field == Integer)
2791 return Integer;
2792 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2793 Accum == X87 || Accum == X87Up)
2794 return Memory;
2795 return SSE;
2796}
2797
2798void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2799 Class &Lo, Class &Hi, bool isNamedArg) const {
2800 // FIXME: This code can be simplified by introducing a simple value class for
2801 // Class pairs with appropriate constructor methods for the various
2802 // situations.
2803
2804 // FIXME: Some of the split computations are wrong; unaligned vectors
2805 // shouldn't be passed in registers for example, so there is no chance they
2806 // can straddle an eightbyte. Verify & simplify.
2807
2808 Lo = Hi = NoClass;
2809
2810 Class &Current = OffsetBase < 64 ? Lo : Hi;
2811 Current = Memory;
2812
2813 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2814 BuiltinType::Kind k = BT->getKind();
2815
2816 if (k == BuiltinType::Void) {
2817 Current = NoClass;
2818 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2819 Lo = Integer;
2820 Hi = Integer;
2821 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2822 Current = Integer;
2823 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2824 k == BuiltinType::Float16) {
2825 Current = SSE;
2826 } else if (k == BuiltinType::LongDouble) {
2827 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2828 if (LDF == &llvm::APFloat::IEEEquad()) {
2829 Lo = SSE;
2830 Hi = SSEUp;
2831 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2832 Lo = X87;
2833 Hi = X87Up;
2834 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2835 Current = SSE;
2836 } else
2837 llvm_unreachable("unexpected long double representation!")__builtin_unreachable();
2838 }
2839 // FIXME: _Decimal32 and _Decimal64 are SSE.
2840 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2841 return;
2842 }
2843
2844 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2845 // Classify the underlying integer type.
2846 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2847 return;
2848 }
2849
2850 if (Ty->hasPointerRepresentation()) {
2851 Current = Integer;
2852 return;
2853 }
2854
2855 if (Ty->isMemberPointerType()) {
2856 if (Ty->isMemberFunctionPointerType()) {
2857 if (Has64BitPointers) {
2858 // If Has64BitPointers, this is an {i64, i64}, so classify both
2859 // Lo and Hi now.
2860 Lo = Hi = Integer;
2861 } else {
2862 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2863 // straddles an eightbyte boundary, Hi should be classified as well.
2864 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2865 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2866 if (EB_FuncPtr != EB_ThisAdj) {
2867 Lo = Hi = Integer;
2868 } else {
2869 Current = Integer;
2870 }
2871 }
2872 } else {
2873 Current = Integer;
2874 }
2875 return;
2876 }
2877
2878 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2879 uint64_t Size = getContext().getTypeSize(VT);
2880 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2881 // gcc passes the following as integer:
2882 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2883 // 2 bytes - <2 x char>, <1 x short>
2884 // 1 byte - <1 x char>
2885 Current = Integer;
2886
2887 // If this type crosses an eightbyte boundary, it should be
2888 // split.
2889 uint64_t EB_Lo = (OffsetBase) / 64;
2890 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2891 if (EB_Lo != EB_Hi)
2892 Hi = Lo;
2893 } else if (Size == 64) {
2894 QualType ElementType = VT->getElementType();
2895
2896 // gcc passes <1 x double> in memory. :(
2897 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2898 return;
2899
2900 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2901 // pass them as integer. For platforms where clang is the de facto
2902 // platform compiler, we must continue to use integer.
2903 if (!classifyIntegerMMXAsSSE() &&
2904 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2905 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2906 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2907 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2908 Current = Integer;
2909 else
2910 Current = SSE;
2911
2912 // If this type crosses an eightbyte boundary, it should be
2913 // split.
2914 if (OffsetBase && OffsetBase != 64)
2915 Hi = Lo;
2916 } else if (Size == 128 ||
2917 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2918 QualType ElementType = VT->getElementType();
2919
2920 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2921 if (passInt128VectorsInMem() && Size != 128 &&
2922 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2923 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2924 return;
2925
2926 // Arguments of 256-bits are split into four eightbyte chunks. The
2927 // least significant one belongs to class SSE and all the others to class
2928 // SSEUP. The original Lo and Hi design considers that types can't be
2929 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2930 // This design isn't correct for 256-bits, but since there're no cases
2931 // where the upper parts would need to be inspected, avoid adding
2932 // complexity and just consider Hi to match the 64-256 part.
2933 //
2934 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2935 // registers if they are "named", i.e. not part of the "..." of a
2936 // variadic function.
2937 //
2938 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2939 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2940 Lo = SSE;
2941 Hi = SSEUp;
2942 }
2943 return;
2944 }
2945
2946 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2947 QualType ET = getContext().getCanonicalType(CT->getElementType());
2948
2949 uint64_t Size = getContext().getTypeSize(Ty);
2950 if (ET->isIntegralOrEnumerationType()) {
2951 if (Size <= 64)
2952 Current = Integer;
2953 else if (Size <= 128)
2954 Lo = Hi = Integer;
2955 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2956 Current = SSE;
2957 } else if (ET == getContext().DoubleTy) {
2958 Lo = Hi = SSE;
2959 } else if (ET == getContext().LongDoubleTy) {
2960 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2961 if (LDF == &llvm::APFloat::IEEEquad())
2962 Current = Memory;
2963 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2964 Current = ComplexX87;
2965 else if (LDF == &llvm::APFloat::IEEEdouble())
2966 Lo = Hi = SSE;
2967 else
2968 llvm_unreachable("unexpected long double representation!")__builtin_unreachable();
2969 }
2970
2971 // If this complex type crosses an eightbyte boundary then it
2972 // should be split.
2973 uint64_t EB_Real = (OffsetBase) / 64;
2974 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2975 if (Hi == NoClass && EB_Real != EB_Imag)
2976 Hi = Lo;
2977
2978 return;
2979 }
2980
2981 if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2982 if (EITy->getNumBits() <= 64)
2983 Current = Integer;
2984 else if (EITy->getNumBits() <= 128)
2985 Lo = Hi = Integer;
2986 // Larger values need to get passed in memory.
2987 return;
2988 }
2989
2990 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2991 // Arrays are treated like structures.
2992
2993 uint64_t Size = getContext().getTypeSize(Ty);
2994
2995 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2996 // than eight eightbytes, ..., it has class MEMORY.
2997 if (Size > 512)
2998 return;
2999
3000 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3001 // fields, it has class MEMORY.
3002 //
3003 // Only need to check alignment of array base.
3004 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3005 return;
3006
3007 // Otherwise implement simplified merge. We could be smarter about
3008 // this, but it isn't worth it and would be harder to verify.
3009 Current = NoClass;
3010 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3011 uint64_t ArraySize = AT->getSize().getZExtValue();
3012
3013 // The only case a 256-bit wide vector could be used is when the array
3014 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3015 // to work for sizes wider than 128, early check and fallback to memory.
3016 //
3017 if (Size > 128 &&
3018 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3019 return;
3020
3021 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3022 Class FieldLo, FieldHi;
3023 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3024 Lo = merge(Lo, FieldLo);
3025 Hi = merge(Hi, FieldHi);
3026 if (Lo == Memory || Hi == Memory)
3027 break;
3028 }
3029
3030 postMerge(Size, Lo, Hi);
3031 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.")(static_cast<void> (0));
3032 return;
3033 }
3034
3035 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3036 uint64_t Size = getContext().getTypeSize(Ty);
3037
3038 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3039 // than eight eightbytes, ..., it has class MEMORY.
3040 if (Size > 512)
3041 return;
3042
3043 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3044 // copy constructor or a non-trivial destructor, it is passed by invisible
3045 // reference.
3046 if (getRecordArgABI(RT, getCXXABI()))
3047 return;
3048
3049 const RecordDecl *RD = RT->getDecl();
3050
3051 // Assume variable sized types are passed in memory.
3052 if (RD->hasFlexibleArrayMember())
3053 return;
3054
3055 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3056
3057 // Reset Lo class, this will be recomputed.
3058 Current = NoClass;
3059
3060 // If this is a C++ record, classify the bases first.
3061 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3062 for (const auto &I : CXXRD->bases()) {
3063 assert(!I.isVirtual() && !I.getType()->isDependentType() &&(static_cast<void> (0))
3064 "Unexpected base class!")(static_cast<void> (0));
3065 const auto *Base =
3066 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3067
3068 // Classify this field.
3069 //
3070 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3071 // single eightbyte, each is classified separately. Each eightbyte gets
3072 // initialized to class NO_CLASS.
3073 Class FieldLo, FieldHi;
3074 uint64_t Offset =
3075 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3076 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3077 Lo = merge(Lo, FieldLo);
3078 Hi = merge(Hi, FieldHi);
3079 if (Lo == Memory || Hi == Memory) {
3080 postMerge(Size, Lo, Hi);
3081 return;
3082 }
3083 }
3084 }
3085
3086 // Classify the fields one at a time, merging the results.
3087 unsigned idx = 0;
3088 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3089 LangOptions::ClangABI::Ver11 ||
3090 getContext().getTargetInfo().getTriple().isPS4();
3091 bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3092
3093 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3094 i != e; ++i, ++idx) {
3095 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3096 bool BitField = i->isBitField();
3097
3098 // Ignore padding bit-fields.
3099 if (BitField && i->isUnnamedBitfield())
3100 continue;
3101
3102 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3103 // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3104 //
3105 // The only case a 256-bit or a 512-bit wide vector could be used is when
3106 // the struct contains a single 256-bit or 512-bit element. Early check
3107 // and fallback to memory.
3108 //
3109 // FIXME: Extended the Lo and Hi logic properly to work for size wider
3110 // than 128.
3111 if (Size > 128 &&
3112 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3113 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3114 Lo = Memory;
3115 postMerge(Size, Lo, Hi);
3116 return;
3117 }
3118 // Note, skip this test for bit-fields, see below.
3119 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3120 Lo = Memory;
3121 postMerge(Size, Lo, Hi);
3122 return;
3123 }
3124
3125 // Classify this field.
3126 //
3127 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3128 // exceeds a single eightbyte, each is classified
3129 // separately. Each eightbyte gets initialized to class
3130 // NO_CLASS.
3131 Class FieldLo, FieldHi;
3132
3133 // Bit-fields require special handling, they do not force the
3134 // structure to be passed in memory even if unaligned, and
3135 // therefore they can straddle an eightbyte.
3136 if (BitField) {
3137 assert(!i->isUnnamedBitfield())(static_cast<void> (0));
3138 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3139 uint64_t Size = i->getBitWidthValue(getContext());
3140
3141 uint64_t EB_Lo = Offset / 64;
3142 uint64_t EB_Hi = (Offset + Size - 1) / 64;
3143
3144 if (EB_Lo) {
3145 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.")(static_cast<void> (0));
3146 FieldLo = NoClass;
3147 FieldHi = Integer;
3148 } else {
3149 FieldLo = Integer;
3150 FieldHi = EB_Hi ? Integer : NoClass;
3151 }
3152 } else
3153 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3154 Lo = merge(Lo, FieldLo);
3155 Hi = merge(Hi, FieldHi);
3156 if (Lo == Memory || Hi == Memory)
3157 break;
3158 }
3159
3160 postMerge(Size, Lo, Hi);
3161 }
3162}
3163
3164ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3165 // If this is a scalar LLVM value then assume LLVM will pass it in the right
3166 // place naturally.
3167 if (!isAggregateTypeForABI(Ty)) {
3168 // Treat an enum type as its underlying type.
3169 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3170 Ty = EnumTy->getDecl()->getIntegerType();
3171
3172 if (Ty->isExtIntType())
3173 return getNaturalAlignIndirect(Ty);
3174
3175 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3176 : ABIArgInfo::getDirect());
3177 }
3178
3179 return getNaturalAlignIndirect(Ty);
3180}
3181
3182bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3183 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3184 uint64_t Size = getContext().getTypeSize(VecTy);
3185 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3186 if (Size <= 64 || Size > LargestVector)
3187 return true;
3188 QualType EltTy = VecTy->getElementType();
3189 if (passInt128VectorsInMem() &&
3190 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3191 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3192 return true;
3193 }
3194
3195 return false;
3196}
3197
3198ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3199 unsigned freeIntRegs) const {
3200 // If this is a scalar LLVM value then assume LLVM will pass it in the right
3201 // place naturally.
3202 //
3203 // This assumption is optimistic, as there could be free registers available
3204 // when we need to pass this argument in memory, and LLVM could try to pass
3205 // the argument in the free register. This does not seem to happen currently,
3206 // but this code would be much safer if we could mark the argument with
3207 // 'onstack'. See PR12193.
3208 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3209 !Ty->isExtIntType()) {
3210 // Treat an enum type as its underlying type.
3211 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3212 Ty = EnumTy->getDecl()->getIntegerType();
3213
3214 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3215 : ABIArgInfo::getDirect());
3216 }
3217
3218 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3219 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3220
3221 // Compute the byval alignment. We specify the alignment of the byval in all
3222 // cases so that the mid-level optimizer knows the alignment of the byval.
3223 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3224
3225 // Attempt to avoid passing indirect results using byval when possible. This
3226 // is important for good codegen.
3227 //
3228 // We do this by coercing the value into a scalar type which the backend can
3229 // handle naturally (i.e., without using byval).
3230 //
3231 // For simplicity, we currently only do this when we have exhausted all of the
3232 // free integer registers. Doing this when there are free integer registers
3233 // would require more care, as we would have to ensure that the coerced value
3234 // did not claim the unused register. That would require either reording the
3235 // arguments to the function (so that any subsequent inreg values came first),
3236 // or only doing this optimization when there were no following arguments that
3237 // might be inreg.
3238 //
3239 // We currently expect it to be rare (particularly in well written code) for
3240 // arguments to be passed on the stack when there are still free integer
3241 // registers available (this would typically imply large structs being passed
3242 // by value), so this seems like a fair tradeoff for now.
3243 //
3244 // We can revisit this if the backend grows support for 'onstack' parameter
3245 // attributes. See PR12193.
3246 if (freeIntRegs == 0) {
3247 uint64_t Size = getContext().getTypeSize(Ty);
3248
3249 // If this type fits in an eightbyte, coerce it into the matching integral
3250 // type, which will end up on the stack (with alignment 8).
3251 if (Align == 8 && Size <= 64)
3252 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3253 Size));
3254 }
3255
3256 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3257}
3258
3259/// The ABI specifies that a value should be passed in a full vector XMM/YMM
3260/// register. Pick an LLVM IR type that will be passed as a vector register.
3261llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3262 // Wrapper structs/arrays that only contain vectors are passed just like
3263 // vectors; strip them off if present.
3264 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3265 Ty = QualType(InnerTy, 0);
3266
3267 llvm::Type *IRType = CGT.ConvertType(Ty);
3268 if (isa<llvm::VectorType>(IRType)) {
3269 // Don't pass vXi128 vectors in their native type, the backend can't
3270 // legalize them.
3271 if (passInt128VectorsInMem() &&
3272 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3273 // Use a vXi64 vector.
3274 uint64_t Size = getContext().getTypeSize(Ty);
3275 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3276 Size / 64);
3277 }
3278
3279 return IRType;
3280 }
3281
3282 if (IRType->getTypeID() == llvm::Type::FP128TyID)
3283 return IRType;
3284
3285 // We couldn't find the preferred IR vector type for 'Ty'.
3286 uint64_t Size = getContext().getTypeSize(Ty);
3287 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!")(static_cast<void> (0));
3288
3289
3290 // Return a LLVM IR vector type based on the size of 'Ty'.
3291 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3292 Size / 64);
3293}
3294
3295/// BitsContainNoUserData - Return true if the specified [start,end) bit range
3296/// is known to either be off the end of the specified type or being in
3297/// alignment padding. The user type specified is known to be at most 128 bits
3298/// in size, and have passed through X86_64ABIInfo::classify with a successful
3299/// classification that put one of the two halves in the INTEGER class.
3300///
3301/// It is conservatively correct to return false.
3302static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3303 unsigned EndBit, ASTContext &Context) {
3304 // If the bytes being queried are off the end of the type, there is no user
3305 // data hiding here. This handles analysis of builtins, vectors and other
3306 // types that don't contain interesting padding.
3307 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3308 if (TySize <= StartBit)
3309 return true;
3310
3311 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3312 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3313 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3314
3315 // Check each element to see if the element overlaps with the queried range.
3316 for (unsigned i = 0; i != NumElts; ++i) {
3317 // If the element is after the span we care about, then we're done..
3318 unsigned EltOffset = i*EltSize;
3319 if (EltOffset >= EndBit) break;
3320
3321 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3322 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3323 EndBit-EltOffset, Context))
3324 return false;
3325 }
3326 // If it overlaps no elements, then it is safe to process as padding.
3327 return true;
3328 }
3329
3330 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3331 const RecordDecl *RD = RT->getDecl();
3332 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3333
3334 // If this is a C++ record, check the bases first.
3335 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3336 for (const auto &I : CXXRD->bases()) {
3337 assert(!I.isVirtual() && !I.getType()->isDependentType() &&(static_cast<void> (0))
3338 "Unexpected base class!")(static_cast<void> (0));
3339 const auto *Base =
3340 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3341
3342 // If the base is after the span we care about, ignore it.
3343 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3344 if (BaseOffset >= EndBit) continue;
3345
3346 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3347 if (!BitsContainNoUserData(I.getType(), BaseStart,
3348 EndBit-BaseOffset, Context))
3349 return false;
3350 }
3351 }
3352
3353 // Verify that no field has data that overlaps the region of interest. Yes
3354 // this could be sped up a lot by being smarter about queried fields,
3355 // however we're only looking at structs up to 16 bytes, so we don't care
3356 // much.
3357 unsigned idx = 0;
3358 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3359 i != e; ++i, ++idx) {
3360 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3361
3362 // If we found a field after the region we care about, then we're done.
3363 if (FieldOffset >= EndBit) break;
3364
3365 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3366 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3367 Context))
3368 return false;
3369 }
3370
3371 // If nothing in this record overlapped the area of interest, then we're
3372 // clean.
3373 return true;
3374 }
3375
3376 return false;
3377}
3378
3379/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3380/// float member at the specified offset. For example, {int,{float}} has a
3381/// float at offset 4. It is conservatively correct for this routine to return
3382/// false.
3383static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3384 const llvm::DataLayout &TD) {
3385 // Base case if we find a float.
3386 if (IROffset == 0 && IRType->isFloatTy())
3387 return true;
3388
3389 // If this is a struct, recurse into the field at the specified offset.
3390 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3391 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3392 unsigned Elt = SL->getElementContainingOffset(IROffset);
3393 IROffset -= SL->getElementOffset(Elt);
3394 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3395 }
3396
3397 // If this is an array, recurse into the field at the specified offset.
3398 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3399 llvm::Type *EltTy = ATy->getElementType();
3400 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3401 IROffset -= IROffset/EltSize*EltSize;
3402 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3403 }
3404
3405 return false;
3406}
3407
3408/// ContainsHalfAtOffset - Return true if the specified LLVM IR type has a
3409/// half member at the specified offset. For example, {int,{half}} has a
3410/// half at offset 4. It is conservatively correct for this routine to return
3411/// false.
3412/// FIXME: Merge with ContainsFloatAtOffset
3413static bool ContainsHalfAtOffset(llvm::Type *IRType, unsigned IROffset,
3414 const llvm::DataLayout &TD) {
3415 // Base case if we find a float.
3416 if (IROffset == 0 && IRType->isHalfTy())
3417 return true;
3418
3419 // If this is a struct, recurse into the field at the specified offset.
3420 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3421 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3422 unsigned Elt = SL->getElementContainingOffset(IROffset);
3423 IROffset -= SL->getElementOffset(Elt);
3424 return ContainsHalfAtOffset(STy->getElementType(Elt), IROffset, TD);
3425 }
3426
3427 // If this is an array, recurse into the field at the specified offset.
3428 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3429 llvm::Type *EltTy = ATy->getElementType();
3430 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3431 IROffset -= IROffset / EltSize * EltSize;
3432 return ContainsHalfAtOffset(EltTy, IROffset, TD);
3433 }
3434
3435 return false;
3436}
3437
3438/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3439/// low 8 bytes of an XMM register, corresponding to the SSE class.
3440llvm::Type *X86_64ABIInfo::
3441GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3442 QualType SourceTy, unsigned SourceOffset) const {
3443 // If the high 32 bits are not used, we have three choices. Single half,
3444 // single float or two halfs.
3445 if (BitsContainNoUserData(SourceTy, SourceOffset * 8 + 32,
3446 SourceOffset * 8 + 64, getContext())) {
3447 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()))
3448 return llvm::Type::getFloatTy(getVMContext());
3449 if (ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout()))
3450 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()),
3451 2);
3452
3453 return llvm::Type::getHalfTy(getVMContext());
3454 }
3455
3456 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3457 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3458 // case.
3459 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3460 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout()))
3461 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3462 2);
3463
3464 // We want to pass as <4 x half> if the LLVM IR type contains a half at
3465 // offset+0, +2, +4. Walk the LLVM IR type to find out if this is the case.
3466 if (ContainsHalfAtOffset(IRType, IROffset, getDataLayout()) &&
3467 ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout()) &&
3468 ContainsHalfAtOffset(IRType, IROffset + 4, getDataLayout()))
3469 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3470
3471 // We want to pass as <4 x half> if the LLVM IR type contains a mix of float
3472 // and half.
3473 // FIXME: Do we have a better representation for the mixed type?
3474 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) ||
3475 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout()))
3476 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3477
3478 return llvm::Type::getDoubleTy(getVMContext());
3479}
3480
3481
3482/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3483/// an 8-byte GPR. This means that we either have a scalar or we are talking
3484/// about the high or low part of an up-to-16-byte struct. This routine picks
3485/// the best LLVM IR type to represent this, which may be i64 or may be anything
3486/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3487/// etc).
3488///
3489/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3490/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3491/// the 8-byte value references. PrefType may be null.
3492///
3493/// SourceTy is the source-level type for the entire argument. SourceOffset is
3494/// an offset into this that we're processing (which is always either 0 or 8).
3495///
3496llvm::Type *X86_64ABIInfo::
3497GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3498 QualType SourceTy, unsigned SourceOffset) const {
3499 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3500 // returning an 8-byte unit starting with it. See if we can safely use it.
3501 if (IROffset == 0) {
3502 // Pointers and int64's always fill the 8-byte unit.
3503 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3504 IRType->isIntegerTy(64))
3505 return IRType;
3506
3507 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3508 // goodness in the source type is just tail padding. This is allowed to
3509 // kick in for struct {double,int} on the int, but not on
3510 // struct{double,int,int} because we wouldn't return the second int. We
3511 // have to do this analysis on the source type because we can't depend on
3512 // unions being lowered a specific way etc.
3513 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3514 IRType->isIntegerTy(32) ||
3515 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3516 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3517 cast<llvm::IntegerType>(IRType)->getBitWidth();
3518
3519 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3520 SourceOffset*8+64, getContext()))
3521 return IRType;
3522 }
3523 }
3524
3525 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3526 // If this is a struct, recurse into the field at the specified offset.
3527 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3528 if (IROffset < SL->getSizeInBytes()) {
3529 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3530 IROffset -= SL->getElementOffset(FieldIdx);
3531
3532 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3533 SourceTy, SourceOffset);
3534 }
3535 }
3536
3537 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3538 llvm::Type *EltTy = ATy->getElementType();
3539 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3540 unsigned EltOffset = IROffset/EltSize*EltSize;
3541 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3542 SourceOffset);
3543 }
3544
3545 // Okay, we don't have any better idea of what to pass, so we pass this in an
3546 // integer register that isn't too big to fit the rest of the struct.
3547 unsigned TySizeInBytes =
3548 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3549
3550 assert(TySizeInBytes != SourceOffset && "Empty field?")(static_cast<void> (0));
3551
3552 // It is always safe to classify this as an integer type up to i64 that
3553 // isn't larger than the structure.
3554 return llvm::IntegerType::get(getVMContext(),
3555 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3556}
3557
3558
3559/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3560/// be used as elements of a two register pair to pass or return, return a
3561/// first class aggregate to represent them. For example, if the low part of
3562/// a by-value argument should be passed as i32* and the high part as float,
3563/// return {i32*, float}.
3564static llvm::Type *
3565GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3566 const llvm::DataLayout &TD) {
3567 // In order to correctly satisfy the ABI, we need to the high part to start
3568 // at offset 8. If the high and low parts we inferred are both 4-byte types
3569 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3570 // the second element at offset 8. Check for this:
3571 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3572 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3573 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3574 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!")(static_cast<void> (0));
3575
3576 // To handle this, we have to increase the size of the low part so that the
3577 // second element will start at an 8 byte offset. We can't increase the size
3578 // of the second element because it might make us access off the end of the
3579 // struct.
3580 if (HiStart != 8) {
3581 // There are usually two sorts of types the ABI generation code can produce
3582 // for the low part of a pair that aren't 8 bytes in size: half, float or
3583 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3584 // NaCl).
3585 // Promote these to a larger type.
3586 if (Lo->isHalfTy() || Lo->isFloatTy())
3587 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3588 else {
3589 assert((Lo->isIntegerTy() || Lo->isPointerTy())(static_cast<void> (0))
3590 && "Invalid/unknown lo type")(static_cast<void> (0));
3591 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3592 }
3593 }
3594
3595 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3596
3597 // Verify that the second element is at an 8-byte offset.
3598 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&(static_cast<void> (0))
3599 "Invalid x86-64 argument pair!")(static_cast<void> (0));
3600 return Result;
3601}
3602
3603ABIArgInfo X86_64ABIInfo::
3604classifyReturnType(QualType RetTy) const {
3605 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3606 // classification algorithm.
3607 X86_64ABIInfo::Class Lo, Hi;
3608 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3609
3610 // Check some invariants.
3611 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.")(static_cast<void> (0));
3612 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.")(static_cast<void> (0));
3613
3614 llvm::Type *ResType = nullptr;
3615 switch (Lo) {
3616 case NoClass:
3617 if (Hi == NoClass)
3618 return ABIArgInfo::getIgnore();
3619 // If the low part is just padding, it takes no register, leave ResType
3620 // null.
3621 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&(static_cast<void> (0))
3622 "Unknown missing lo part")(static_cast<void> (0));
3623 break;
3624
3625 case SSEUp:
3626 case X87Up:
3627 llvm_unreachable("Invalid classification for lo word.")__builtin_unreachable();
3628
3629 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3630 // hidden argument.
3631 case Memory:
3632 return getIndirectReturnResult(RetTy);
3633
3634 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3635 // available register of the sequence %rax, %rdx is used.
3636 case Integer:
3637 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3638
3639 // If we have a sign or zero extended integer, make sure to return Extend
3640 // so that the parameter gets the right LLVM IR attributes.
3641 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3642 // Treat an enum type as its underlying type.
3643 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3644 RetTy = EnumTy->getDecl()->getIntegerType();
3645
3646 if (RetTy->isIntegralOrEnumerationType() &&
3647 isPromotableIntegerTypeForABI(RetTy))
3648 return ABIArgInfo::getExtend(RetTy);
3649 }
3650 break;
3651
3652 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3653 // available SSE register of the sequence %xmm0, %xmm1 is used.
3654 case SSE:
3655 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3656 break;
3657
3658 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3659 // returned on the X87 stack in %st0 as 80-bit x87 number.
3660 case X87:
3661 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3662 break;
3663
3664 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3665 // part of the value is returned in %st0 and the imaginary part in
3666 // %st1.
3667 case ComplexX87:
3668 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.")(static_cast<void> (0));
3669 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3670 llvm::Type::getX86_FP80Ty(getVMContext()));
3671 break;
3672 }
3673
3674 llvm::Type *HighPart = nullptr;
3675 switch (Hi) {
3676 // Memory was handled previously and X87 should
3677 // never occur as a hi class.
3678 case Memory:
3679 case X87:
3680 llvm_unreachable("Invalid classification for hi word.")__builtin_unreachable();
3681
3682 case ComplexX87: // Previously handled.
3683 case NoClass:
3684 break;
3685
3686 case Integer:
3687 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3688 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3689 return ABIArgInfo::getDirect(HighPart, 8);
3690 break;
3691 case SSE:
3692 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3693 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3694 return ABIArgInfo::getDirect(HighPart, 8);
3695 break;
3696
3697 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3698 // is passed in the next available eightbyte chunk if the last used
3699 // vector register.
3700 //
3701 // SSEUP should always be preceded by SSE, just widen.
3702 case SSEUp:
3703 assert(Lo == SSE && "Unexpected SSEUp classification.")(static_cast<void> (0));
3704 ResType = GetByteVectorType(RetTy);
3705 break;
3706
3707 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3708 // returned together with the previous X87 value in %st0.
3709 case X87Up:
3710 // If X87Up is preceded by X87, we don't need to do
3711 // anything. However, in some cases with unions it may not be
3712 // preceded by X87. In such situations we follow gcc and pass the
3713 // extra bits in an SSE reg.
3714 if (Lo != X87) {
3715 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3716 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3717 return ABIArgInfo::getDirect(HighPart, 8);
3718 }
3719 break;
3720 }
3721
3722 // If a high part was specified, merge it together with the low part. It is
3723 // known to pass in the high eightbyte of the result. We do this by forming a
3724 // first class struct aggregate with the high and low part: {low, high}
3725 if (HighPart)
3726 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3727
3728 return ABIArgInfo::getDirect(ResType);
3729}
3730
3731ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3732 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3733 bool isNamedArg)
3734 const
3735{
3736 Ty = useFirstFieldIfTransparentUnion(Ty);
3737
3738 X86_64ABIInfo::Class Lo, Hi;
3739 classify(Ty, 0, Lo, Hi, isNamedArg);
3740
3741 // Check some invariants.
3742 // FIXME: Enforce these by construction.
3743 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.")(static_cast<void> (0));
3744 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.")(static_cast<void> (0));
3745
3746 neededInt = 0;
3747 neededSSE = 0;
3748 llvm::Type *ResType = nullptr;
3749 switch (Lo) {
3750 case NoClass:
3751 if (Hi == NoClass)
3752 return ABIArgInfo::getIgnore();
3753 // If the low part is just padding, it takes no register, leave ResType
3754 // null.
3755 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&(static_cast<void> (0))
3756 "Unknown missing lo part")(static_cast<void> (0));
3757 break;
3758
3759 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3760 // on the stack.
3761 case Memory:
3762
3763 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3764 // COMPLEX_X87, it is passed in memory.
3765 case X87:
3766 case ComplexX87:
3767 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3768 ++neededInt;
3769 return getIndirectResult(Ty, freeIntRegs);
3770
3771 case SSEUp:
3772 case X87Up:
3773 llvm_unreachable("Invalid classification for lo word.")__builtin_unreachable();
3774
3775 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3776 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3777 // and %r9 is used.
3778 case Integer:
3779 ++neededInt;
3780
3781 // Pick an 8-byte type based on the preferred type.
3782 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3783
3784 // If we have a sign or zero extended integer, make sure to return Extend
3785 // so that the parameter gets the right LLVM IR attributes.
3786 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3787 // Treat an enum type as its underlying type.
3788 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3789 Ty = EnumTy->getDecl()->getIntegerType();
3790
3791 if (Ty->isIntegralOrEnumerationType() &&
3792 isPromotableIntegerTypeForABI(Ty))
3793 return ABIArgInfo::getExtend(Ty);
3794 }
3795
3796 break;
3797
3798 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3799 // available SSE register is used, the registers are taken in the
3800 // order from %xmm0 to %xmm7.
3801 case SSE: {
3802 llvm::Type *IRType = CGT.ConvertType(Ty);
3803 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3804 ++neededSSE;
3805 break;
3806 }
3807 }
3808
3809 llvm::Type *HighPart = nullptr;
3810 switch (Hi) {
3811 // Memory was handled previously, ComplexX87 and X87 should
3812 // never occur as hi classes, and X87Up must be preceded by X87,
3813 // which is passed in memory.
3814 case Memory:
3815 case X87:
3816 case ComplexX87:
3817 llvm_unreachable("Invalid classification for hi word.")__builtin_unreachable();
3818
3819 case NoClass: break;
3820
3821 case Integer:
3822 ++neededInt;
3823 // Pick an 8-byte type based on the preferred type.
3824 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3825
3826 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3827 return ABIArgInfo::getDirect(HighPart, 8);
3828 break;
3829
3830 // X87Up generally doesn't occur here (long double is passed in
3831 // memory), except in situations involving unions.
3832 case X87Up:
3833 case SSE:
3834 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3835
3836 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3837 return ABIArgInfo::getDirect(HighPart, 8);
3838
3839 ++neededSSE;
3840 break;
3841
3842 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3843 // eightbyte is passed in the upper half of the last used SSE
3844 // register. This only happens when 128-bit vectors are passed.
3845 case SSEUp:
3846 assert(Lo == SSE && "Unexpected SSEUp classification")(static_cast<void> (0));
3847 ResType = GetByteVectorType(Ty);
3848 break;
3849 }
3850
3851 // If a high part was specified, merge it together with the low part. It is
3852 // known to pass in the high eightbyte of the result. We do this by forming a
3853 // first class struct aggregate with the high and low part: {low, high}
3854 if (HighPart)
3855 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3856
3857 return ABIArgInfo::getDirect(ResType);
3858}
3859
3860ABIArgInfo
3861X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3862 unsigned &NeededSSE) const {
3863 auto RT = Ty->getAs<RecordType>();
3864 assert(RT && "classifyRegCallStructType only valid with struct types")(static_cast<void> (0));
3865
3866 if (RT->getDecl()->hasFlexibleArrayMember())
3867 return getIndirectReturnResult(Ty);
3868
3869 // Sum up bases
3870 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3871 if (CXXRD->isDynamicClass()) {
3872 NeededInt = NeededSSE = 0;
3873 return getIndirectReturnResult(Ty);
3874 }
3875
3876 for (const auto &I : CXXRD->bases())
3877 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3878 .isIndirect()) {
3879 NeededInt = NeededSSE = 0;
3880 return getIndirectReturnResult(Ty);
3881 }
3882 }
3883
3884 // Sum up members
3885 for (const auto *FD : RT->getDecl()->fields()) {
3886 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3887 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3888 .isIndirect()) {
3889 NeededInt = NeededSSE = 0;
3890 return getIndirectReturnResult(Ty);
3891 }
3892 } else {
3893 unsigned LocalNeededInt, LocalNeededSSE;
3894 if (classifyArgumentType(FD->getType(), UINT_MAX(2147483647 *2U +1U), LocalNeededInt,
3895 LocalNeededSSE, true)
3896 .isIndirect()) {
3897 NeededInt = NeededSSE = 0;
3898 return getIndirectReturnResult(Ty);
3899 }
3900 NeededInt += LocalNeededInt;
3901 NeededSSE += LocalNeededSSE;
3902 }
3903 }
3904
3905 return ABIArgInfo::getDirect();
3906}
3907
3908ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3909 unsigned &NeededInt,
3910 unsigned &NeededSSE) const {
3911
3912 NeededInt = 0;
3913 NeededSSE = 0;
3914
3915 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3916}
3917
3918void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3919
3920 const unsigned CallingConv = FI.getCallingConvention();
3921 // It is possible to force Win64 calling convention on any x86_64 target by
3922 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3923 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3924 if (CallingConv == llvm::CallingConv::Win64) {
3925 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3926 Win64ABIInfo.computeInfo(FI);
3927 return;
3928 }
3929
3930 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3931
3932 // Keep track of the number of assigned registers.
3933 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3934 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3935 unsigned NeededInt, NeededSSE;
3936
3937 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3938 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3939 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3940 FI.getReturnInfo() =
3941 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3942 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3943 FreeIntRegs -= NeededInt;
3944 FreeSSERegs -= NeededSSE;
3945 } else {
3946 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3947 }
3948 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3949 getContext().getCanonicalType(FI.getReturnType()
3950 ->getAs<ComplexType>()
3951 ->getElementType()) ==
3952 getContext().LongDoubleTy)
3953 // Complex Long Double Type is passed in Memory when Regcall
3954 // calling convention is used.
3955 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3956 else
3957 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3958 }
3959
3960 // If the return value is indirect, then the hidden argument is consuming one
3961 // integer register.
3962 if (FI.getReturnInfo().isIndirect())
3963 --FreeIntRegs;
3964
3965 // The chain argument effectively gives us another free register.
3966 if (FI.isChainCall())
3967 ++FreeIntRegs;
3968
3969 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3970 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3971 // get assigned (in left-to-right order) for passing as follows...
3972 unsigned ArgNo = 0;
3973 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3974 it != ie; ++it, ++ArgNo) {
3975 bool IsNamedArg = ArgNo < NumRequiredArgs;
3976
3977 if (IsRegCall && it->type->isStructureOrClassType())
3978 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3979 else
3980 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3981 NeededSSE, IsNamedArg);
3982
3983 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3984 // eightbyte of an argument, the whole argument is passed on the
3985 // stack. If registers have already been assigned for some
3986 // eightbytes of such an argument, the assignments get reverted.
3987 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3988 FreeIntRegs -= NeededInt;
3989 FreeSSERegs -= NeededSSE;
3990 } else {
3991 it->info = getIndirectResult(it->type, FreeIntRegs);
3992 }
3993 }
3994}
3995
3996static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3997 Address VAListAddr, QualType Ty) {
3998 Address overflow_arg_area_p =
3999 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4000 llvm::Value *overflow_arg_area =
4001 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4002
4003 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4004 // byte boundary if alignment needed by type exceeds 8 byte boundary.
4005 // It isn't stated explicitly in the standard, but in practice we use
4006 // alignment greater than 16 where necessary.
4007 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4008 if (Align > CharUnits::fromQuantity(8)) {
4009 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4010 Align);
4011 }
4012
4013 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4014 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4015 llvm::Value *Res =
4016 CGF.Builder.CreateBitCast(overflow_arg_area,
4017 llvm::PointerType::getUnqual(LTy));
4018
4019 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4020 // l->overflow_arg_area + sizeof(type).
4021 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4022 // an 8 byte boundary.
4023
4024 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4025 llvm::Value *Offset =
4026 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
4027 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4028 Offset, "overflow_arg_area.next");
4029 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4030
4031 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4032 return Address(Res, Align);
4033}
4034
4035Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4036 QualType Ty) const {
4037 // Assume that va_list type is correct; should be pointer to LLVM type:
4038 // struct {
4039 // i32 gp_offset;
4040 // i32 fp_offset;
4041 // i8* overflow_arg_area;
4042 // i8* reg_save_area;
4043 // };
4044 unsigned neededInt, neededSSE;
4045
4046 Ty = getContext().getCanonicalType(Ty);
4047 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4048 /*isNamedArg*/false);
4049
4050 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4051 // in the registers. If not go to step 7.
4052 if (!neededInt && !neededSSE)
4053 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4054
4055 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4056 // general purpose registers needed to pass type and num_fp to hold
4057 // the number of floating point registers needed.
4058
4059 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4060 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4061 // l->fp_offset > 304 - num_fp * 16 go to step 7.
4062 //
4063 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4064 // register save space).
4065
4066 llvm::Value *InRegs = nullptr;
4067 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4068 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4069 if (neededInt) {
4070 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4071 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4072 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4073 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4074 }
4075
4076 if (neededSSE) {
4077 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4078 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4079 llvm::Value *FitsInFP =
4080 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4081 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4082 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4083 }
4084
4085 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4086 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4087 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4088 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4089
4090 // Emit code to load the value if it was passed in registers.
4091
4092 CGF.EmitBlock(InRegBlock);
4093
4094 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4095 // an offset of l->gp_offset and/or l->fp_offset. This may require
4096 // copying to a temporary location in case the parameter is passed
4097 // in different register classes or requires an alignment greater
4098 // than 8 for general purpose registers and 16 for XMM registers.
4099 //
4100 // FIXME: This really results in shameful code when we end up needing to
4101 // collect arguments from different places; often what should result in a
4102 // simple assembling of a structure from scattered addresses has many more
4103 // loads than necessary. Can we clean this up?
4104 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4105 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4106 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4107
4108 Address RegAddr = Address::invalid();
4109 if (neededInt && neededSSE) {
4110 // FIXME: Cleanup.
4111 assert(AI.isDirect() && "Unexpected ABI info for mixed regs")(static_cast<void> (0));
4112 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4113 Address Tmp = CGF.CreateMemTemp(Ty);
4114 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4115 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs")(static_cast<void> (0));
4116 llvm::Type *TyLo = ST->getElementType(0);
4117 llvm::Type *TyHi = ST->getElementType(1);
4118 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&(static_cast<void> (0))
4119 "Unexpected ABI info for mixed regs")(static_cast<void> (0));
4120 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4121 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4122 llvm::Value *GPAddr =
4123 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4124 llvm::Value *FPAddr =
4125 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4126 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4127 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4128
4129 // Copy the first element.
4130 // FIXME: Our choice of alignment here and below is probably pessimistic.
4131 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4132 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4133 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4134 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4135
4136 // Copy the second element.
4137 V = CGF.Builder.CreateAlignedLoad(
4138 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4139 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4140 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4141
4142 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4143 } else if (neededInt) {
4144 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4145 CharUnits::fromQuantity(8));
4146 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4147
4148 // Copy to a temporary if necessary to ensure the appropriate alignment.
4149 auto TInfo = getContext().getTypeInfoInChars(Ty);
4150 uint64_t TySize = TInfo.Width.getQuantity();
4151 CharUnits TyAlign = TInfo.Align;
4152
4153 // Copy into a temporary if the type is more aligned than the
4154 // register save area.
4155 if (TyAlign.getQuantity() > 8) {
4156 Address Tmp = CGF.CreateMemTemp(Ty);
4157 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4158 RegAddr = Tmp;
4159 }
4160
4161 } else if (neededSSE == 1) {
4162 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4163 CharUnits::fromQuantity(16));
4164 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4165 } else {
4166 assert(neededSSE == 2 && "Invalid number of needed registers!")(static_cast<void> (0));
4167 // SSE registers are spaced 16 bytes apart in the register save
4168 // area, we need to collect the two eightbytes together.
4169 // The ABI isn't explicit about this, but it seems reasonable
4170 // to assume that the slots are 16-byte aligned, since the stack is
4171 // naturally 16-byte aligned and the prologue is expected to store
4172 // all the SSE registers to the RSA.
4173 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4174 fp_offset),
4175 CharUnits::fromQuantity(16));
4176 Address RegAddrHi =
4177 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4178 CharUnits::fromQuantity(16));
4179 llvm::Type *ST = AI.canHaveCoerceToType()
4180 ? AI.getCoerceToType()
4181 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4182 llvm::Value *V;
4183 Address Tmp = CGF.CreateMemTemp(Ty);
4184 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4185 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4186 RegAddrLo, ST->getStructElementType(0)));
4187 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4188 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4189 RegAddrHi, ST->getStructElementType(1)));
4190 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4191
4192 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4193 }
4194
4195 // AMD64-ABI 3.5.7p5: Step 5. Set:
4196 // l->gp_offset = l->gp_offset + num_gp * 8
4197 // l->fp_offset = l->fp_offset + num_fp * 16.
4198 if (neededInt) {
4199 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4200 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4201 gp_offset_p);
4202 }
4203 if (neededSSE) {
4204 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4205 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4206 fp_offset_p);
4207 }
4208 CGF.EmitBranch(ContBlock);
4209
4210 // Emit code to load the value if it was passed in memory.
4211
4212 CGF.EmitBlock(InMemBlock);
4213 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4214
4215 // Return the appropriate result.
4216
4217 CGF.EmitBlock(ContBlock);
4218 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4219 "vaarg.addr");
4220 return ResAddr;
4221}
4222
4223Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4224 QualType Ty) const {
4225 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4226 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4227 uint64_t Width = getContext().getTypeSize(Ty);
4228 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4229
4230 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4231 CGF.getContext().getTypeInfoInChars(Ty),
4232 CharUnits::fromQuantity(8),
4233 /*allowHigherAlign*/ false);
4234}
4235
4236ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4237 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4238 const Type *Base = nullptr;
4239 uint64_t NumElts = 0;
4240
4241 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4242 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4243 FreeSSERegs -= NumElts;
4244 return getDirectX86Hva();
4245 }
4246 return current;
4247}
4248
4249ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4250 bool IsReturnType, bool IsVectorCall,
4251 bool IsRegCall) const {
4252
4253 if (Ty->isVoidType())
4254 return ABIArgInfo::getIgnore();
4255
4256 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4257 Ty = EnumTy->getDecl()->getIntegerType();
4258
4259 TypeInfo Info = getContext().getTypeInfo(Ty);
4260 uint64_t Width = Info.Width;
4261 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4262
4263 const RecordType *RT = Ty->getAs<RecordType>();
4264 if (RT) {
4265 if (!IsReturnType) {
4266 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4267 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4268 }
4269
4270 if (RT->getDecl()->hasFlexibleArrayMember())
4271 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4272
4273 }
4274
4275 const Type *Base = nullptr;
4276 uint64_t NumElts = 0;
4277 // vectorcall adds the concept of a homogenous vector aggregate, similar to
4278 // other targets.
4279 if ((IsVectorCall || IsRegCall) &&
4280 isHomogeneousAggregate(Ty, Base, NumElts)) {
4281 if (IsRegCall) {
4282 if (FreeSSERegs >= NumElts) {
4283 FreeSSERegs -= NumElts;
4284 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4285 return ABIArgInfo::getDirect();
4286 return ABIArgInfo::getExpand();
4287 }
4288 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4289 } else if (IsVectorCall) {
4290 if (FreeSSERegs >= NumElts &&
4291 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4292 FreeSSERegs -= NumElts;
4293 return ABIArgInfo::getDirect();
4294 } else if (IsReturnType) {
4295 return ABIArgInfo::getExpand();
4296 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4297 // HVAs are delayed and reclassified in the 2nd step.
4298 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4299 }
4300 }
4301 }
4302
4303 if (Ty->isMemberPointerType()) {
4304 // If the member pointer is represented by an LLVM int or ptr, pass it
4305 // directly.
4306 llvm::Type *LLTy = CGT.ConvertType(Ty);
4307 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4308 return ABIArgInfo::getDirect();
4309 }
4310
4311 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4312 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4313 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4314 if (Width > 64 || !llvm::isPowerOf2_64(Width))
4315 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4316
4317 // Otherwise, coerce it to a small integer.
4318 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4319 }
4320
4321 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4322 switch (BT->getKind()) {
4323 case BuiltinType::Bool:
4324 // Bool type is always extended to the ABI, other builtin types are not
4325 // extended.
4326 return ABIArgInfo::getExtend(Ty);
4327
4328 case BuiltinType::LongDouble:
4329 // Mingw64 GCC uses the old 80 bit extended precision floating point
4330 // unit. It passes them indirectly through memory.
4331 if (IsMingw64) {
4332 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4333 if (LDF == &llvm::APFloat::x87DoubleExtended())
4334 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4335 }
4336 break;
4337
4338 case BuiltinType::Int128:
4339 case BuiltinType::UInt128:
4340 // If it's a parameter type, the normal ABI rule is that arguments larger
4341 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4342 // even though it isn't particularly efficient.
4343 if (!IsReturnType)
4344 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4345
4346 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4347 // Clang matches them for compatibility.
4348 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4349 llvm::Type::getInt64Ty(getVMContext()), 2));
4350
4351 default:
4352 break;
4353 }
4354 }
4355
4356 if (Ty->isExtIntType()) {
4357 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4358 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4359 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4360 // anyway as long is it fits in them, so we don't have to check the power of
4361 // 2.
4362 if (Width <= 64)
4363 return ABIArgInfo::getDirect();
4364 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4365 }
4366
4367 return ABIArgInfo::getDirect();
4368}
4369
4370void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4371 const unsigned CC = FI.getCallingConvention();
4372 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4373 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4374
4375 // If __attribute__((sysv_abi)) is in use, use the SysV argument
4376 // classification rules.
4377 if (CC == llvm::CallingConv::X86_64_SysV) {
4378 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4379 SysVABIInfo.computeInfo(FI);
4380 return;
4381 }
4382
4383 unsigned FreeSSERegs = 0;
4384 if (IsVectorCall) {
4385 // We can use up to 4 SSE return registers with vectorcall.
4386 FreeSSERegs = 4;
4387 } else if (IsRegCall) {
4388 // RegCall gives us 16 SSE registers.
4389 FreeSSERegs = 16;
4390 }
4391
4392 if (!getCXXABI().classifyReturnType(FI))
4393 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4394 IsVectorCall, IsRegCall);
4395
4396 if (IsVectorCall) {
4397 // We can use up to 6 SSE register parameters with vectorcall.
4398 FreeSSERegs = 6;
4399 } else if (IsRegCall) {
4400 // RegCall gives us 16 SSE registers, we can reuse the return registers.
4401 FreeSSERegs = 16;
4402 }
4403
4404 unsigned ArgNum = 0;
4405 unsigned ZeroSSERegs = 0;
4406 for (auto &I : FI.arguments()) {
4407 // Vectorcall in x64 only permits the first 6 arguments to be passed as
4408 // XMM/YMM registers. After the sixth argument, pretend no vector
4409 // registers are left.
4410 unsigned *MaybeFreeSSERegs =
4411 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4412 I.info =
4413 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4414 ++ArgNum;
4415 }
4416
4417 if (IsVectorCall) {
4418 // For vectorcall, assign aggregate HVAs to any free vector registers in a
4419 // second pass.
4420 for (auto &I : FI.arguments())
4421 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4422 }
4423}
4424
4425Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4426 QualType Ty) const {
4427 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4428 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4429 uint64_t Width = getContext().getTypeSize(Ty);
4430 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4431
4432 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4433 CGF.getContext().getTypeInfoInChars(Ty),
4434 CharUnits::fromQuantity(8),
4435 /*allowHigherAlign*/ false);
4436}
4437
4438static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4439 llvm::Value *Address, bool Is64Bit,
4440 bool IsAIX) {
4441 // This is calculated from the LLVM and GCC tables and verified
4442 // against gcc output. AFAIK all PPC ABIs use the same encoding.
4443
4444 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4445
4446 llvm::IntegerType *i8 = CGF.Int8Ty;
4447 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4448 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4449 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4450
4451 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4452 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4453
4454 // 32-63: fp0-31, the 8-byte floating-point registers
4455 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4456
4457 // 64-67 are various 4-byte or 8-byte special-purpose registers:
4458 // 64: mq
4459 // 65: lr
4460 // 66: ctr
4461 // 67: ap
4462 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4463
4464 // 68-76 are various 4-byte special-purpose registers:
4465 // 68-75 cr0-7
4466 // 76: xer
4467 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4468
4469 // 77-108: v0-31, the 16-byte vector registers
4470 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4471
4472 // 109: vrsave
4473 // 110: vscr
4474 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4475
4476 // AIX does not utilize the rest of the registers.
4477 if (IsAIX)
4478 return false;
4479
4480 // 111: spe_acc
4481 // 112: spefscr
4482 // 113: sfp
4483 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4484
4485 if (!Is64Bit)
4486 return false;
4487
4488 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4489 // or above CPU.
4490 // 64-bit only registers:
4491 // 114: tfhar
4492 // 115: tfiar
4493 // 116: texasr
4494 AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4495
4496 return false;
4497}
4498
4499// AIX
4500namespace {
4501/// AIXABIInfo - The AIX XCOFF ABI information.
4502class AIXABIInfo : public ABIInfo {
4503 const bool Is64Bit;
4504 const unsigned PtrByteSize;
4505 CharUnits getParamTypeAlignment(QualType Ty) const;
4506
4507public:
4508 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4509 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4510
4511 bool isPromotableTypeForABI(QualType Ty) const;
4512
4513 ABIArgInfo classifyReturnType(QualType RetTy) const;
4514 ABIArgInfo classifyArgumentType(QualType Ty) const;
4515
4516 void computeInfo(CGFunctionInfo &FI) const override {
4517 if (!getCXXABI().classifyReturnType(FI))
4518 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4519
4520 for (auto &I : FI.arguments())
4521 I.info = classifyArgumentType(I.type);
4522 }
4523
4524 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4525 QualType Ty) const override;
4526};
4527
4528class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4529 const bool Is64Bit;
4530
4531public:
4532 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4533 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4534 Is64Bit(Is64Bit) {}
4535 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4536 return 1; // r1 is the dedicated stack pointer
4537 }
4538
4539 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4540 llvm::Value *Address) const override;
4541};
4542} // namespace
4543
4544// Return true if the ABI requires Ty to be passed sign- or zero-
4545// extended to 32/64 bits.
4546bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4547 // Treat an enum type as its underlying type.
4548 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4549 Ty = EnumTy->getDecl()->getIntegerType();
4550
4551 // Promotable integer types are required to be promoted by the ABI.
4552 if (Ty->isPromotableIntegerType())
4553 return true;
4554
4555 if (!Is64Bit)
4556 return false;
4557
4558 // For 64 bit mode, in addition to the usual promotable integer types, we also
4559 // need to extend all 32-bit types, since the ABI requires promotion to 64
4560 // bits.
4561 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4562 switch (BT->getKind()) {
4563 case BuiltinType::Int:
4564 case BuiltinType::UInt:
4565 return true;
4566 default:
4567 break;
4568 }
4569
4570 return false;
4571}
4572
4573ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4574 if (RetTy->isAnyComplexType())
4575 return ABIArgInfo::getDirect();
4576
4577 if (RetTy->isVectorType())
4578 return ABIArgInfo::getDirect();
4579
4580 if (RetTy->isVoidType())
4581 return ABIArgInfo::getIgnore();
4582
4583 if (isAggregateTypeForABI(RetTy))
4584 return getNaturalAlignIndirect(RetTy);
4585
4586 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4587 : ABIArgInfo::getDirect());
4588}
4589
4590ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4591 Ty = useFirstFieldIfTransparentUnion(Ty);
4592
4593 if (Ty->isAnyComplexType())
4594 return ABIArgInfo::getDirect();
4595
4596 if (Ty->isVectorType())
4597 return ABIArgInfo::getDirect();
4598
4599 if (isAggregateTypeForABI(Ty)) {
4600 // Records with non-trivial destructors/copy-constructors should not be
4601 // passed by value.
4602 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4603 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4604
4605 CharUnits CCAlign = getParamTypeAlignment(Ty);
4606 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4607
4608 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4609 /*Realign*/ TyAlign > CCAlign);
4610 }
4611
4612 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4613 : ABIArgInfo::getDirect());
4614}
4615
4616CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4617 // Complex types are passed just like their elements.
4618 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4619 Ty = CTy->getElementType();
4620
4621 if (Ty->isVectorType())
4622 return CharUnits::fromQuantity(16);
4623
4624 // If the structure contains a vector type, the alignment is 16.
4625 if (isRecordWithSIMDVectorType(getContext(), Ty))
4626 return CharUnits::fromQuantity(16);
4627
4628 return CharUnits::fromQuantity(PtrByteSize);
4629}
4630
4631Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4632 QualType Ty) const {
4633 if (Ty->isAnyComplexType())
4634 llvm::report_fatal_error("complex type is not supported on AIX yet");
4635
4636 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4637 TypeInfo.Align = getParamTypeAlignment(Ty);
4638
4639 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4640
4641 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4642 SlotSize, /*AllowHigher*/ true);
4643}
4644
4645bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4646 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4647 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4648}
4649
4650// PowerPC-32
4651namespace {
4652/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4653class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4654 bool IsSoftFloatABI;
4655 bool IsRetSmallStructInRegABI;
4656
4657 CharUnits getParamTypeAlignment(QualType Ty) const;
4658
4659public:
4660 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4661 bool RetSmallStructInRegABI)
4662 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4663 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4664
4665 ABIArgInfo classifyReturnType(QualType RetTy) const;
4666
4667 void computeInfo(CGFunctionInfo &FI) const override {
4668 if (!getCXXABI().classifyReturnType(FI))
4669 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4670 for (auto &I : FI.arguments())
4671 I.info = classifyArgumentType(I.type);
4672 }
4673
4674 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4675 QualType Ty) const override;
4676};
4677
4678class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4679public:
4680 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4681 bool RetSmallStructInRegABI)
4682 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4683 CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4684
4685 static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4686 const CodeGenOptions &Opts);
4687
4688 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4689 // This is recovered from gcc output.
4690 return 1; // r1 is the dedicated stack pointer
4691 }
4692
4693 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4694 llvm::Value *Address) const override;
4695};
4696}
4697
4698CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4699 // Complex types are passed just like their elements.
4700 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4701 Ty = CTy->getElementType();
4702
4703 if (Ty->isVectorType())
4704 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4705 : 4);
4706
4707 // For single-element float/vector structs, we consider the whole type
4708 // to have the same alignment requirements as its single element.
4709 const Type *AlignTy = nullptr;
4710 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4711 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4712 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4713 (BT && BT->isFloatingPoint()))
4714 AlignTy = EltType;
4715 }
4716
4717 if (AlignTy)
4718 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4719 return CharUnits::fromQuantity(4);
4720}
4721
4722ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4723 uint64_t Size;
4724
4725 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4726 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4727 (Size = getContext().getTypeSize(RetTy)) <= 64) {
4728 // System V ABI (1995), page 3-22, specified:
4729 // > A structure or union whose size is less than or equal to 8 bytes
4730 // > shall be returned in r3 and r4, as if it were first stored in the
4731 // > 8-byte aligned memory area and then the low addressed word were
4732 // > loaded into r3 and the high-addressed word into r4. Bits beyond
4733 // > the last member of the structure or union are not defined.
4734 //
4735 // GCC for big-endian PPC32 inserts the pad before the first member,
4736 // not "beyond the last member" of the struct. To stay compatible
4737 // with GCC, we coerce the struct to an integer of the same size.
4738 // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4739 if (Size == 0)
4740 return ABIArgInfo::getIgnore();
4741 else {
4742 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4743 return ABIArgInfo::getDirect(CoerceTy);
4744 }
4745 }
4746
4747 return DefaultABIInfo::classifyReturnType(RetTy);
4748}
4749
4750// TODO: this implementation is now likely redundant with
4751// DefaultABIInfo::EmitVAArg.
4752Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4753 QualType Ty) const {
4754 if (getTarget().getTriple().isOSDarwin()) {
4755 auto TI = getContext().getTypeInfoInChars(Ty);
4756 TI.Align = getParamTypeAlignment(Ty);
4757
4758 CharUnits SlotSize = CharUnits::fromQuantity(4);
4759 return emitVoidPtrVAArg(CGF, VAList, Ty,
4760 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4761 /*AllowHigherAlign=*/true);
4762 }
4763
4764 const unsigned OverflowLimit = 8;
4765 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4766 // TODO: Implement this. For now ignore.
4767 (void)CTy;
4768 return Address::invalid(); // FIXME?
4769 }
4770
4771 // struct __va_list_tag {
4772 // unsigned char gpr;
4773 // unsigned char fpr;
4774 // unsigned short reserved;
4775 // void *overflow_arg_area;
4776 // void *reg_save_area;
4777 // };
4778
4779 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4780 bool isInt = !Ty->isFloatingType();
4781 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4782
4783 // All aggregates are passed indirectly? That doesn't seem consistent
4784 // with the argument-lowering code.
4785 bool isIndirect = isAggregateTypeForABI(Ty);
4786
4787 CGBuilderTy &Builder = CGF.Builder;
4788
4789 // The calling convention either uses 1-2 GPRs or 1 FPR.
4790 Address NumRegsAddr = Address::invalid();
4791 if (isInt || IsSoftFloatABI) {
4792 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4793 } else {
4794 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4795 }
4796
4797 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4798
4799 // "Align" the register count when TY is i64.
4800 if (isI64 || (isF64 && IsSoftFloatABI)) {
4801 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4802 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4803 }
4804
4805 llvm::Value *CC =
4806 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4807
4808 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4809 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4810 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4811
4812 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4813
4814 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4815 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4816
4817 // Case 1: consume registers.
4818 Address RegAddr = Address::invalid();
4819 {
4820 CGF.EmitBlock(UsingRegs);
4821
4822 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4823 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4824 CharUnits::fromQuantity(8));
4825 assert(RegAddr.getElementType() == CGF.Int8Ty)(static_cast<void> (0));
4826
4827 // Floating-point registers start after the general-purpose registers.
4828 if (!(isInt || IsSoftFloatABI)) {
4829 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4830 CharUnits::fromQuantity(32));
4831 }
4832
4833 // Get the address of the saved value by scaling the number of
4834 // registers we've used by the number of
4835 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4836 llvm::Value *RegOffset =
4837 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4838 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4839 RegAddr.getPointer(), RegOffset),
4840 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4841 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4842
4843 // Increase the used-register count.
4844 NumRegs =
4845 Builder.CreateAdd(NumRegs,
4846 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4847 Builder.CreateStore(NumRegs, NumRegsAddr);
4848
4849 CGF.EmitBranch(Cont);
4850 }
4851
4852 // Case 2: consume space in the overflow area.
4853 Address MemAddr = Address::invalid();
4854 {
4855 CGF.EmitBlock(UsingOverflow);
4856
4857 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4858
4859 // Everything in the overflow area is rounded up to a size of at least 4.
4860 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4861
4862 CharUnits Size;
4863 if (!isIndirect) {
4864 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4865 Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4866 } else {
4867 Size = CGF.getPointerSize();
4868 }
4869
4870 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4871 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4872 OverflowAreaAlign);
4873 // Round up address of argument to alignment
4874 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4875 if (Align > OverflowAreaAlign) {
4876 llvm::Value *Ptr = OverflowArea.getPointer();
4877 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4878 Align);
4879 }
4880
4881 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4882
4883 // Increase the overflow area.
4884 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4885 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4886 CGF.EmitBranch(Cont);
4887 }
4888
4889 CGF.EmitBlock(Cont);
4890
4891 // Merge the cases with a phi.
4892 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4893 "vaarg.addr");
4894
4895 // Load the pointer if the argument was passed indirectly.
4896 if (isIndirect) {
4897 Result = Address(Builder.CreateLoad(Result, "aggr"),
4898 getContext().getTypeAlignInChars(Ty));
4899 }
4900
4901 return Result;
4902}
4903
4904bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4905 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4906 assert(Triple.isPPC32())(static_cast<void> (0));
4907
4908 switch (Opts.getStructReturnConvention()) {
4909 case CodeGenOptions::SRCK_Default:
4910 break;
4911 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4912 return false;
4913 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4914 return true;
4915 }
4916
4917 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4918 return true;
4919
4920 return false;
4921}
4922
4923bool
4924PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4925 llvm::Value *Address) const {
4926 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4927 /*IsAIX*/ false);
4928}
4929
4930// PowerPC-64
4931
4932namespace {
4933/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4934class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4935public:
4936 enum ABIKind {
4937 ELFv1 = 0,
4938 ELFv2
4939 };
4940
4941private:
4942 static const unsigned GPRBits = 64;
4943 ABIKind Kind;
4944 bool IsSoftFloatABI;
4945
4946public:
4947 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4948 bool SoftFloatABI)
4949 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4950
4951 bool isPromotableTypeForABI(QualType Ty) const;
4952 CharUnits getParamTypeAlignment(QualType Ty) const;
4953
4954 ABIArgInfo classifyReturnType(QualType RetTy) const;
4955 ABIArgInfo classifyArgumentType(QualType Ty) const;
4956
4957 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4958 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4959 uint64_t Members) const override;
4960
4961 // TODO: We can add more logic to computeInfo to improve performance.
4962 // Example: For aggregate arguments that fit in a register, we could
4963 // use getDirectInReg (as is done below for structs containing a single
4964 // floating-point value) to avoid pushing them to memory on function
4965 // entry. This would require changing the logic in PPCISelLowering
4966 // when lowering the parameters in the caller and args in the callee.
4967 void computeInfo(CGFunctionInfo &FI) const override {
4968 if (!getCXXABI().classifyReturnType(FI))
4969 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4970 for (auto &I : FI.arguments()) {
4971 // We rely on the default argument classification for the most part.
4972 // One exception: An aggregate containing a single floating-point
4973 // or vector item must be passed in a register if one is available.
4974 const Type *T = isSingleElementStruct(I.type, getContext());
4975 if (T) {
4976 const BuiltinType *BT = T->getAs<BuiltinType>();
4977 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4978 (BT && BT->isFloatingPoint())) {
4979 QualType QT(T, 0);
4980 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4981 continue;
4982 }
4983 }
4984 I.info = classifyArgumentType(I.type);
4985 }
4986 }
4987
4988 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4989 QualType Ty) const override;
4990
4991 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4992 bool asReturnValue) const override {
4993 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4994 }
4995
4996 bool isSwiftErrorInRegister() const override {
4997 return false;
4998 }
4999};
5000
5001class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5002
5003public:
5004 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5005 PPC64_SVR4_ABIInfo::ABIKind Kind,
5006 bool SoftFloatABI)
5007 : TargetCodeGenInfo(
5008 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5009
5010 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5011 // This is recovered from gcc output.
5012 return 1; // r1 is the dedicated stack pointer
5013 }
5014
5015 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5016 llvm::Value *Address) const override;
5017};
5018
5019class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5020public:
5021 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5022
5023 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5024 // This is recovered from gcc output.
5025 return 1; // r1 is the dedicated stack pointer
5026 }
5027
5028 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5029 llvm::Value *Address) const override;
5030};
5031
5032}
5033
5034// Return true if the ABI requires Ty to be passed sign- or zero-
5035// extended to 64 bits.
5036bool
5037PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5038 // Treat an enum type as its underlying type.
5039 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5040 Ty = EnumTy->getDecl()->getIntegerType();
5041
5042 // Promotable integer types are required to be promoted by the ABI.
5043 if (isPromotableIntegerTypeForABI(Ty))
5044 return true;
5045
5046 // In addition to the usual promotable integer types, we also need to
5047 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5048 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5049 switch (BT->getKind()) {
5050 case BuiltinType::Int:
5051 case BuiltinType::UInt:
5052 return true;
5053 default:
5054 break;
5055 }
5056
5057 if (const auto *EIT = Ty->getAs<ExtIntType>())
5058 if (EIT->getNumBits() < 64)
5059 return true;
5060
5061 return false;
5062}
5063
5064/// isAlignedParamType - Determine whether a type requires 16-byte or
5065/// higher alignment in the parameter area. Always returns at least 8.
5066CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5067 // Complex types are passed just like their elements.
5068 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5069 Ty = CTy->getElementType();
5070
5071 // Only vector types of size 16 bytes need alignment (larger types are
5072 // passed via reference, smaller types are not aligned).
5073 if (Ty->isVectorType()) {
5074 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5075 } else if (Ty->isRealFloatingType() &&
5076 &getContext().getFloatTypeSemantics(Ty) ==
5077 &llvm::APFloat::IEEEquad()) {
5078 // According to ABI document section 'Optional Save Areas': If extended
5079 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5080 // format are supported, map them to a single quadword, quadword aligned.
5081 return CharUnits::fromQuantity(16);
5082 }
5083
5084 // For single-element float/vector structs, we consider the whole type
5085 // to have the same alignment requirements as its single element.
5086 const Type *AlignAsType = nullptr;
5087 const Type *EltType = isSingleElementStruct(Ty, getContext());
5088 if (EltType) {
5089 const BuiltinType *BT = EltType->getAs<BuiltinType>();
5090 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5091 (BT && BT->isFloatingPoint()))
5092 AlignAsType = EltType;
5093 }
5094
5095 // Likewise for ELFv2 homogeneous aggregates.
5096 const Type *Base = nullptr;
5097 uint64_t Members = 0;
5098 if (!AlignAsType && Kind == ELFv2 &&
5099 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5100 AlignAsType = Base;
5101
5102 // With special case aggregates, only vector base types need alignment.
5103 if (AlignAsType) {
5104 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5105 }
5106
5107 // Otherwise, we only need alignment for any aggregate type that
5108 // has an alignment requirement of >= 16 bytes.
5109 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5110 return CharUnits::fromQuantity(16);
5111 }
5112
5113 return CharUnits::fromQuantity(8);
5114}
5115
5116/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5117/// aggregate. Base is set to the base element type, and Members is set
5118/// to the number of base elements.
5119bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5120 uint64_t &Members) const {
5121 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5122 uint64_t NElements = AT->getSize().getZExtValue();
5123 if (NElements == 0)
5124 return false;
5125 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5126 return false;
5127 Members *= NElements;
5128 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5129 const RecordDecl *RD = RT->getDecl();
5130 if (RD->hasFlexibleArrayMember())
5131 return false;
5132
5133 Members = 0;
5134
5135 // If this is a C++ record, check the properties of the record such as
5136 // bases and ABI specific restrictions
5137 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5138 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5139 return false;
5140
5141 for (const auto &I : CXXRD->bases()) {
5142 // Ignore empty records.
5143 if (isEmptyRecord(getContext(), I.getType(), true))
5144 continue;
5145
5146 uint64_t FldMembers;
5147 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5148 return false;
5149
5150 Members += FldMembers;
5151 }
5152 }
5153
5154 for (const auto *FD : RD->fields()) {
5155 // Ignore (non-zero arrays of) empty records.
5156 QualType FT = FD->getType();
5157 while (const ConstantArrayType *AT =
5158 getContext().getAsConstantArrayType(FT)) {
5159 if (AT->getSize().getZExtValue() == 0)
5160 return false;
5161 FT = AT->getElementType();
5162 }
5163 if (isEmptyRecord(getContext(), FT, true))
5164 continue;
5165
5166 // For compatibility with GCC, ignore empty bitfields in C++ mode.
5167 if (getContext().getLangOpts().CPlusPlus &&
5168 FD->isZeroLengthBitField(getContext()))
5169 continue;
5170
5171 uint64_t FldMembers;
5172 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5173 return false;
5174
5175 Members = (RD->isUnion() ?
5176 std::max(Members, FldMembers) : Members + FldMembers);
5177 }
5178
5179 if (!Base)
5180 return false;
5181
5182 // Ensure there is no padding.
5183 if (getContext().getTypeSize(Base) * Members !=
5184 getContext().getTypeSize(Ty))
5185 return false;
5186 } else {
5187 Members = 1;
5188 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5189 Members = 2;
5190 Ty = CT->getElementType();
5191 }
5192
5193 // Most ABIs only support float, double, and some vector type widths.
5194 if (!isHomogeneousAggregateBaseType(Ty))
5195 return false;
5196
5197 // The base type must be the same for all members. Types that
5198 // agree in both total size and mode (float vs. vector) are
5199 // treated as being equivalent here.
5200 const Type *TyPtr = Ty.getTypePtr();
5201 if (!Base) {
5202 Base = TyPtr;
5203 // If it's a non-power-of-2 vector, its size is already a power-of-2,
5204 // so make sure to widen it explicitly.
5205 if (const VectorType *VT = Base->getAs<VectorType>()) {
5206 QualType EltTy = VT->getElementType();
5207 unsigned NumElements =
5208 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5209 Base = getContext()
5210 .getVectorType(EltTy, NumElements, VT->getVectorKind())
5211 .getTypePtr();
5212 }
5213 }
5214
5215 if (Base->isVectorType() != TyPtr->isVectorType() ||
5216 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5217 return false;
5218 }
5219 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5220}
5221
5222bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5223 // Homogeneous aggregates for ELFv2 must have base types of float,
5224 // double, long double, or 128-bit vectors.
5225 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5226 if (BT->getKind() == BuiltinType::Float ||
5227 BT->getKind() == BuiltinType::Double ||
5228 BT->getKind() == BuiltinType::LongDouble ||
5229 (getContext().getTargetInfo().hasFloat128Type() &&
5230 (BT->getKind() == BuiltinType::Float128))) {
5231 if (IsSoftFloatABI)
5232 return false;
5233 return true;
5234 }
5235 }
5236 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5237 if (getContext().getTypeSize(VT) == 128)
5238 return true;
5239 }
5240 return false;
5241}
5242
5243bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5244 const Type *Base, uint64_t Members) const {
5245 // Vector and fp128 types require one register, other floating point types
5246 // require one or two registers depending on their size.
5247 uint32_t NumRegs =
5248 ((getContext().getTargetInfo().hasFloat128Type() &&
5249 Base->isFloat128Type()) ||
5250 Base->isVectorType()) ? 1
5251 : (getContext().getTypeSize(Base) + 63) / 64;
5252
5253 // Homogeneous Aggregates may occupy at most 8 registers.
5254 return Members * NumRegs <= 8;
5255}
5256
5257ABIArgInfo
5258PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5259 Ty = useFirstFieldIfTransparentUnion(Ty);
5260
5261 if (Ty->isAnyComplexType())
5262 return ABIArgInfo::getDirect();
5263
5264 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5265 // or via reference (larger than 16 bytes).
5266 if (Ty->isVectorType()) {
5267 uint64_t Size = getContext().getTypeSize(Ty);
5268 if (Size > 128)
5269 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5270 else if (Size < 128) {
5271 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5272 return ABIArgInfo::getDirect(CoerceTy);
5273 }
5274 }
5275
5276 if (const auto *EIT = Ty->getAs<ExtIntType>())
5277 if (EIT->getNumBits() > 128)
5278 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5279
5280 if (isAggregateTypeForABI(Ty)) {
5281 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5282 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5283
5284 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5285 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5286
5287 // ELFv2 homogeneous aggregates are passed as array types.
5288 const Type *Base = nullptr;
5289 uint64_t Members = 0;
5290 if (Kind == ELFv2 &&
5291 isHomogeneousAggregate(Ty, Base, Members)) {
5292 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5293 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5294 return ABIArgInfo::getDirect(CoerceTy);
5295 }
5296
5297 // If an aggregate may end up fully in registers, we do not
5298 // use the ByVal method, but pass the aggregate as array.
5299 // This is usually beneficial since we avoid forcing the
5300 // back-end to store the argument to memory.
5301 uint64_t Bits = getContext().getTypeSize(Ty);
5302 if (Bits > 0 && Bits <= 8 * GPRBits) {
5303 llvm::Type *CoerceTy;
5304
5305 // Types up to 8 bytes are passed as integer type (which will be
5306 // properly aligned in the argument save area doubleword).
5307 if (Bits <= GPRBits)
5308 CoerceTy =
5309 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5310 // Larger types are passed as arrays, with the base type selected
5311 // according to the required alignment in the save area.
5312 else {
5313 uint64_t RegBits = ABIAlign * 8;
5314 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5315 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5316 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5317 }
5318
5319 return ABIArgInfo::getDirect(CoerceTy);
5320 }
5321
5322 // All other aggregates are passed ByVal.
5323 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5324 /*ByVal=*/true,
5325 /*Realign=*/TyAlign > ABIAlign);
5326 }
5327
5328 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5329 : ABIArgInfo::getDirect());
5330}
5331
5332ABIArgInfo
5333PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5334 if (RetTy->isVoidType())
5335 return ABIArgInfo::getIgnore();
5336
5337 if (RetTy->isAnyComplexType())
5338 return ABIArgInfo::getDirect();
5339
5340 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5341 // or via reference (larger than 16 bytes).
5342 if (RetTy->isVectorType()) {
5343 uint64_t Size = getContext().getTypeSize(RetTy);
5344 if (Size > 128)
5345 return getNaturalAlignIndirect(RetTy);
5346 else if (Size < 128) {
5347 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5348 return ABIArgInfo::getDirect(CoerceTy);
5349 }
5350 }
5351
5352 if (const auto *EIT = RetTy->getAs<ExtIntType>())
5353 if (EIT->getNumBits() > 128)
5354 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5355
5356 if (isAggregateTypeForABI(RetTy)) {
5357 // ELFv2 homogeneous aggregates are returned as array types.
5358 const Type *Base = nullptr;
5359 uint64_t Members = 0;
5360 if (Kind == ELFv2 &&
5361 isHomogeneousAggregate(RetTy, Base, Members)) {
5362 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5363 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5364 return ABIArgInfo::getDirect(CoerceTy);
5365 }
5366
5367 // ELFv2 small aggregates are returned in up to two registers.
5368 uint64_t Bits = getContext().getTypeSize(RetTy);
5369 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5370 if (Bits == 0)
5371 return ABIArgInfo::getIgnore();
5372
5373 llvm::Type *CoerceTy;
5374 if (Bits > GPRBits) {
5375 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5376 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5377 } else
5378 CoerceTy =
5379 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5380 return ABIArgInfo::getDirect(CoerceTy);
5381 }
5382
5383 // All other aggregates are returned indirectly.
5384 return getNaturalAlignIndirect(RetTy);
5385 }
5386
5387 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5388 : ABIArgInfo::getDirect());
5389}
5390
5391// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5392Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5393 QualType Ty) const {
5394 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5395 TypeInfo.Align = getParamTypeAlignment(Ty);
5396
5397 CharUnits SlotSize = CharUnits::fromQuantity(8);
5398
5399 // If we have a complex type and the base type is smaller than 8 bytes,
5400 // the ABI calls for the real and imaginary parts to be right-adjusted
5401 // in separate doublewords. However, Clang expects us to produce a
5402 // pointer to a structure with the two parts packed tightly. So generate
5403 // loads of the real and imaginary parts relative to the va_list pointer,
5404 // and store them to a temporary structure.
5405 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5406 CharUnits EltSize = TypeInfo.Width / 2;
5407 if (EltSize < SlotSize) {
5408 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5409 SlotSize * 2, SlotSize,
5410 SlotSize, /*AllowHigher*/ true);
5411
5412 Address RealAddr = Addr;
5413 Address ImagAddr = RealAddr;
5414 if (CGF.CGM.getDataLayout().isBigEndian()) {
5415 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5416 SlotSize - EltSize);
5417 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5418 2 * SlotSize - EltSize);
5419 } else {
5420 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5421 }
5422
5423 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5424 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5425 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5426 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5427 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5428
5429 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5430 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5431 /*init*/ true);
5432 return Temp;
5433 }
5434 }
5435
5436 // Otherwise, just use the general rule.
5437 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5438 TypeInfo, SlotSize, /*AllowHigher*/ true);
5439}
5440
5441bool
5442PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5443 CodeGen::CodeGenFunction &CGF,
5444 llvm::Value *Address) const {
5445 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5446 /*IsAIX*/ false);
5447}
5448
5449bool
5450PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5451 llvm::Value *Address) const {
5452 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5453 /*IsAIX*/ false);
5454}
5455
5456//===----------------------------------------------------------------------===//
5457// AArch64 ABI Implementation
5458//===----------------------------------------------------------------------===//
5459
5460namespace {
5461
5462class AArch64ABIInfo : public SwiftABIInfo {
5463public:
5464 enum ABIKind {
5465 AAPCS = 0,
5466 DarwinPCS,
5467 Win64
5468 };
5469
5470private:
5471 ABIKind Kind;
5472
5473public:
5474 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5475 : SwiftABIInfo(CGT), Kind(Kind) {}
5476
5477private:
5478 ABIKind getABIKind() const { return Kind; }
5479 bool isDarwinPCS() const { return Kind == DarwinPCS; }
5480
5481 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5482 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5483 unsigned CallingConvention) const;
5484 ABIArgInfo coerceIllegalVector(QualType Ty) const;
5485 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5486 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5487 uint64_t Members) const override;
5488
5489 bool isIllegalVectorType(QualType Ty) const;
5490
5491 void computeInfo(CGFunctionInfo &FI) const override {
5492 if (!::classifyReturnType(getCXXABI(), FI, *this))
5493 FI.getReturnInfo() =
5494 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5495
5496 for (auto &it : FI.arguments())
5497 it.info = classifyArgumentType(it.type, FI.isVariadic(),
5498 FI.getCallingConvention());
5499 }
5500
5501 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5502 CodeGenFunction &CGF) const;
5503
5504 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5505 CodeGenFunction &CGF) const;
5506
5507 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5508 QualType Ty) const override {
5509 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5510 if (isa<llvm::ScalableVectorType>(BaseTy))
5511 llvm::report_fatal_error("Passing SVE types to variadic functions is "
5512 "currently not supported");
5513
5514 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5515 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5516 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5517 }
5518
5519 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5520 QualType Ty) const override;
5521
5522 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5523 bool asReturnValue) const override {
5524 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5525 }
5526 bool isSwiftErrorInRegister() const override {
5527 return true;
5528 }
5529
5530 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5531 unsigned elts) const override;
5532
5533 bool allowBFloatArgsAndRet() const override {
5534 return getTarget().hasBFloat16Type();
5535 }
5536};
5537
5538class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5539public:
5540 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5541 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5542
5543 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5544 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5545 }
5546
5547 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5548 return 31;
5549 }
5550
5551 bool doesReturnSlotInterfereWithArgs() const override { return false; }
5552
5553 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5554 CodeGen::CodeGenModule &CGM) const override {
5555 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5556 if (!FD)
5557 return;
5558
5559 const auto *TA = FD->getAttr<TargetAttr>();
5560 if (TA == nullptr)
5561 return;
5562
5563 ParsedTargetAttr Attr = TA->parse();
5564 if (Attr.BranchProtection.empty())
5565 return;
5566
5567 TargetInfo::BranchProtectionInfo BPI;
5568 StringRef Error;
5569 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5570 BPI, Error);
5571 assert(Error.empty())(static_cast<void> (0));
5572
5573 auto *Fn = cast<llvm::Function>(GV);
5574 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5575 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5576
5577 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5578 Fn->addFnAttr("sign-return-address-key",
5579 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5580 ? "a_key"
5581 : "b_key");
5582 }
5583
5584 Fn->addFnAttr("branch-target-enforcement",
5585 BPI.BranchTargetEnforcement ? "true" : "false");
5586 }
5587
5588 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5589 llvm::Type *Ty) const override {
5590 if (CGF.getTarget().hasFeature("ls64")) {
5591 auto *ST = dyn_cast<llvm::StructType>(Ty);
5592 if (ST && ST->getNumElements() == 1) {
5593 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5594 if (AT && AT->getNumElements() == 8 &&
5595 AT->getElementType()->isIntegerTy(64))
5596 return true;
5597 }
5598 }
5599 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5600 }
5601};
5602
5603class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5604public:
5605 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5606 : AArch64TargetCodeGenInfo(CGT, K) {}
5607
5608 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5609 CodeGen::CodeGenModule &CGM) const override;
5610
5611 void getDependentLibraryOption(llvm::StringRef Lib,
5612 llvm::SmallString<24> &Opt) const override {
5613 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5614 }
5615
5616 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5617 llvm::SmallString<32> &Opt) const override {
5618 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5619 }
5620};
5621
5622void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5623 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5624 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5625 if (GV->isDeclaration())
5626 return;
5627 addStackProbeTargetAttributes(D, GV, CGM);
5628}
5629}
5630
5631ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5632 assert(Ty->isVectorType() && "expected vector type!")(static_cast<void> (0));
5633
5634 const auto *VT = Ty->castAs<VectorType>();
5635 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5636 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!")(static_cast<void> (0));
5637 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==(static_cast<void> (0))
5638 BuiltinType::UChar &&(static_cast<void> (0))
5639 "unexpected builtin type for SVE predicate!")(static_cast<void> (0));
5640 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5641 llvm::Type::getInt1Ty(getVMContext()), 16));
5642 }
5643
5644 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5645 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!")(static_cast<void> (0));
5646
5647 const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5648 llvm::ScalableVectorType *ResType = nullptr;
5649 switch (BT->getKind()) {
5650 default:
5651 llvm_unreachable("unexpected builtin type for SVE vector!")__builtin_unreachable();
5652 case BuiltinType::SChar:
5653 case BuiltinType::UChar:
5654 ResType = llvm::ScalableVectorType::get(
5655 llvm::Type::getInt8Ty(getVMContext()), 16);
5656 break;
5657 case BuiltinType::Short:
5658 case BuiltinType::UShort:
5659 ResType = llvm::ScalableVectorType::get(
5660 llvm::Type::getInt16Ty(getVMContext()), 8);
5661 break;
5662 case BuiltinType::Int:
5663 case BuiltinType::UInt:
5664 ResType = llvm::ScalableVectorType::get(
5665 llvm::Type::getInt32Ty(getVMContext()), 4);
5666 break;
5667 case BuiltinType::Long:
5668 case BuiltinType::ULong:
5669 ResType = llvm::ScalableVectorType::get(
5670 llvm::Type::getInt64Ty(getVMContext()), 2);
5671 break;
5672 case BuiltinType::Half:
5673 ResType = llvm::ScalableVectorType::get(
5674 llvm::Type::getHalfTy(getVMContext()), 8);
5675 break;
5676 case BuiltinType::Float:
5677 ResType = llvm::ScalableVectorType::get(
5678 llvm::Type::getFloatTy(getVMContext()), 4);
5679 break;
5680 case BuiltinType::Double:
5681 ResType = llvm::ScalableVectorType::get(
5682 llvm::Type::getDoubleTy(getVMContext()), 2);
5683 break;
5684 case BuiltinType::BFloat16:
5685 ResType = llvm::ScalableVectorType::get(
5686 llvm::Type::getBFloatTy(getVMContext()), 8);
5687 break;
5688 }
5689 return ABIArgInfo::getDirect(ResType);
5690 }
5691
5692 uint64_t Size = getContext().getTypeSize(Ty);
5693 // Android promotes <2 x i8> to i16, not i32
5694 if (isAndroid() && (Size <= 16)) {
5695 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5696 return ABIArgInfo::getDirect(ResType);
5697 }
5698 if (Size <= 32) {
5699 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5700 return ABIArgInfo::getDirect(ResType);
5701 }
5702 if (Size == 64) {
5703 auto *ResType =
5704 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5705 return ABIArgInfo::getDirect(ResType);
5706 }
5707 if (Size == 128) {
5708 auto *ResType =
5709 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5710 return ABIArgInfo::getDirect(ResType);
5711 }
5712 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5713}
5714
5715ABIArgInfo
5716AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5717 unsigned CallingConvention) const {
5718 Ty = useFirstFieldIfTransparentUnion(Ty);
5719
5720 // Handle illegal vector types here.
5721 if (isIllegalVectorType(Ty))
5722 return coerceIllegalVector(Ty);
5723
5724 if (!isAggregateTypeForABI(Ty)) {
5725 // Treat an enum type as its underlying type.
5726 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5727 Ty = EnumTy->getDecl()->getIntegerType();
5728
5729 if (const auto *EIT = Ty->getAs<ExtIntType>())
5730 if (EIT->getNumBits() > 128)
5731 return getNaturalAlignIndirect(Ty);
5732
5733 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5734 ? ABIArgInfo::getExtend(Ty)
5735 : ABIArgInfo::getDirect());
5736 }
5737
5738 // Structures with either a non-trivial destructor or a non-trivial
5739 // copy constructor are always indirect.
5740 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5741 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5742 CGCXXABI::RAA_DirectInMemory);
5743 }
5744
5745 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5746 // elsewhere for GNU compatibility.
5747 uint64_t Size = getContext().getTypeSize(Ty);
5748 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5749 if (IsEmpty || Size == 0) {
5750 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5751 return ABIArgInfo::getIgnore();
5752
5753 // GNU C mode. The only argument that gets ignored is an empty one with size
5754 // 0.
5755 if (IsEmpty && Size == 0)
5756 return ABIArgInfo::getIgnore();
5757 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5758 }
5759
5760 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5761 const Type *Base = nullptr;
5762 uint64_t Members = 0;
5763 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5764 bool IsWinVariadic = IsWin64 && IsVariadic;
5765 // In variadic functions on Windows, all composite types are treated alike,
5766 // no special handling of HFAs/HVAs.
5767 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5768 if (Kind != AArch64ABIInfo::AAPCS)
5769 return ABIArgInfo::getDirect(
5770 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5771
5772 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5773 // default otherwise.
5774 unsigned Align =
5775 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5776 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5777 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5778 return ABIArgInfo::getDirect(
5779 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5780 nullptr, true, Align);
5781 }
5782
5783 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5784 if (Size <= 128) {
5785 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5786 // same size and alignment.
5787 if (getTarget().isRenderScriptTarget()) {
5788 return coerceToIntArray(Ty, getContext(), getVMContext());
5789 }
5790 unsigned Alignment;
5791 if (Kind == AArch64ABIInfo::AAPCS) {
5792 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5793 Alignment = Alignment < 128 ? 64 : 128;
5794 } else {
5795 Alignment = std::max(getContext().getTypeAlign(Ty),
5796 (unsigned)getTarget().getPointerWidth(0));
5797 }
5798 Size = llvm::alignTo(Size, Alignment);
5799
5800 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5801 // For aggregates with 16-byte alignment, we use i128.
5802 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5803 return ABIArgInfo::getDirect(
5804 Size == Alignment ? BaseTy
5805 : llvm::ArrayType::get(BaseTy, Size / Alignment));
5806 }
5807
5808 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5809}
5810
5811ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5812 bool IsVariadic) const {
5813 if (RetTy->isVoidType())
5814 return ABIArgInfo::getIgnore();
5815
5816 if (const auto *VT = RetTy->getAs<VectorType>()) {
5817 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5818 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5819 return coerceIllegalVector(RetTy);
5820 }
5821
5822 // Large vector types should be returned via memory.
5823 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5824 return getNaturalAlignIndirect(RetTy);
5825
5826 if (!isAggregateTypeForABI(RetTy)) {
5827 // Treat an enum type as its underlying type.
5828 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5829 RetTy = EnumTy->getDecl()->getIntegerType();
5830
5831 if (const auto *EIT = RetTy->getAs<ExtIntType>())
5832 if (EIT->getNumBits() > 128)
5833 return getNaturalAlignIndirect(RetTy);
5834
5835 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5836 ? ABIArgInfo::getExtend(RetTy)
5837 : ABIArgInfo::getDirect());
5838 }
5839
5840 uint64_t Size = getContext().getTypeSize(RetTy);
5841 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5842 return ABIArgInfo::getIgnore();
5843
5844 const Type *Base = nullptr;
5845 uint64_t Members = 0;
5846 if (isHomogeneousAggregate(RetTy, Base, Members) &&
5847 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5848 IsVariadic))
5849 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5850 return ABIArgInfo::getDirect();
5851
5852 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5853 if (Size <= 128) {
5854 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5855 // same size and alignment.
5856 if (getTarget().isRenderScriptTarget()) {
5857 return coerceToIntArray(RetTy, getContext(), getVMContext());
5858 }
5859
5860 if (Size <= 64 && getDataLayout().isLittleEndian()) {
5861 // Composite types are returned in lower bits of a 64-bit register for LE,
5862 // and in higher bits for BE. However, integer types are always returned
5863 // in lower bits for both LE and BE, and they are not rounded up to
5864 // 64-bits. We can skip rounding up of composite types for LE, but not for
5865 // BE, otherwise composite types will be indistinguishable from integer
5866 // types.
5867 return ABIArgInfo::getDirect(
5868 llvm::IntegerType::get(getVMContext(), Size));
5869 }
5870
5871 unsigned Alignment = getContext().getTypeAlign(RetTy);
5872 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5873
5874 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5875 // For aggregates with 16-byte alignment, we use i128.
5876 if (Alignment < 128 && Size == 128) {
5877 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5878 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5879 }
5880 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5881 }
5882
5883 return getNaturalAlignIndirect(RetTy);
5884}
5885
5886/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5887bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5888 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5889 // Check whether VT is a fixed-length SVE vector. These types are
5890 // represented as scalable vectors in function args/return and must be
5891 // coerced from fixed vectors.
5892 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5893 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5894 return true;
5895
5896 // Check whether VT is legal.
5897 unsigned NumElements = VT->getNumElements();
5898 uint64_t Size = getContext().getTypeSize(VT);
5899 // NumElements should be power of 2.
5900 if (!llvm::isPowerOf2_32(NumElements))
5901 return true;
5902
5903 // arm64_32 has to be compatible with the ARM logic here, which allows huge
5904 // vectors for some reason.
5905 llvm::Triple Triple = getTarget().getTriple();
5906 if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5907 Triple.isOSBinFormatMachO())
5908 return Size <= 32;
5909
5910 return Size != 64 && (Size != 128 || NumElements == 1);
5911 }
5912 return false;
5913}
5914
5915bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5916 llvm::Type *eltTy,
5917 unsigned elts) const {
5918 if (!llvm::isPowerOf2_32(elts))
5919 return false;
5920 if (totalSize.getQuantity() != 8 &&
5921 (totalSize.getQuantity() != 16 || elts == 1))
5922 return false;
5923 return true;
5924}
5925
5926bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5927 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5928 // point type or a short-vector type. This is the same as the 32-bit ABI,
5929 // but with the difference that any floating-point type is allowed,
5930 // including __fp16.
5931 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5932 if (BT->isFloatingPoint())
5933 return true;
5934 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5935 unsigned VecSize = getContext().getTypeSize(VT);
5936 if (VecSize == 64 || VecSize == 128)
5937 return true;
5938 }
5939 return false;
5940}
5941
5942bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5943 uint64_t Members) const {
5944 return Members <= 4;
5945}
5946
5947Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5948 CodeGenFunction &CGF) const {
5949 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5950 CGF.CurFnInfo->getCallingConvention());
5951 bool IsIndirect = AI.isIndirect();
5952
5953 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5954 if (IsIndirect)
5955 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5956 else if (AI.getCoerceToType())
5957 BaseTy = AI.getCoerceToType();
5958
5959 unsigned NumRegs = 1;
5960 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5961 BaseTy = ArrTy->getElementType();
5962 NumRegs = ArrTy->getNumElements();
5963 }
5964 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5965
5966 // The AArch64 va_list type and handling is specified in the Procedure Call
5967 // Standard, section B.4:
5968 //
5969 // struct {
5970 // void *__stack;
5971 // void *__gr_top;
5972 // void *__vr_top;
5973 // int __gr_offs;
5974 // int __vr_offs;
5975 // };
5976
5977 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5978 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5979 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5980 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5981
5982 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5983 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5984
5985 Address reg_offs_p = Address::invalid();
5986 llvm::Value *reg_offs = nullptr;
5987 int reg_top_index;
5988 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5989 if (!IsFPR) {
5990 // 3 is the field number of __gr_offs
5991 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5992 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5993 reg_top_index = 1; // field number for __gr_top
5994 RegSize = llvm::alignTo(RegSize, 8);
5995 } else {
5996 // 4 is the field number of __vr_offs.
5997 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5998 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5999 reg_top_index = 2; // field number for __vr_top
6000 RegSize = 16 * NumRegs;
6001 }
6002
6003 //=======================================
6004 // Find out where argument was passed