Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/CodeGen/TargetInfo.cpp

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