1//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
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 "CGCall.h"
15#include "ABIInfo.h"
16#include "ABIInfoImpl.h"
17#include "CGBlocks.h"
18#include "CGCXXABI.h"
19#include "CGCleanup.h"
20#include "CGDebugInfo.h"
21#include "CGRecordLayout.h"
22#include "CodeGenFunction.h"
23#include "CodeGenModule.h"
24#include "CodeGenPGO.h"
25#include "QualTypeMapper.h"
26#include "TargetInfo.h"
27#include "clang/AST/Attr.h"
28#include "clang/AST/Decl.h"
29#include "clang/AST/DeclCXX.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/RecordLayout.h"
32#include "clang/Basic/CodeGenOptions.h"
33#include "clang/Basic/DiagnosticFrontend.h"
34#include "clang/Basic/TargetInfo.h"
35#include "clang/CodeGen/CGFunctionInfo.h"
36#include "clang/CodeGen/SwiftCallingConv.h"
37#include "clang/CodeGenUtils/CallUtils.h"
38#include "llvm/ABI/FunctionInfo.h"
39#include "llvm/ABI/IRTypeMapper.h"
40#include "llvm/ABI/TargetInfo.h"
41#include "llvm/ABI/Types.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Analysis/ValueTracking.h"
45#include "llvm/IR/Assumptions.h"
46#include "llvm/IR/AttributeMask.h"
47#include "llvm/IR/Attributes.h"
48#include "llvm/IR/CallingConv.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugInfoMetadata.h"
51#include "llvm/IR/InlineAsm.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/Type.h"
55#include "llvm/Transforms/Utils/Local.h"
56#include <optional>
57using namespace clang;
58using namespace CodeGen;
59
60/***/
61
62unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
63 switch (CC) {
64 case CC_C:
65 // On SPIR/SPIR-V, CC_C is the AST-level default calling convention, but
66 // it still needs to lower to spir_func so IR consumers can rely on the
67 // calling convention to distinguish device functions.
68 if (Target.getTriple().isSPIROrSPIRV())
69 return llvm::CallingConv::SPIR_FUNC;
70 return llvm::CallingConv::C;
71 case CC_X86StdCall:
72 return llvm::CallingConv::X86_StdCall;
73 case CC_X86FastCall:
74 return llvm::CallingConv::X86_FastCall;
75 case CC_X86RegCall:
76 return llvm::CallingConv::X86_RegCall;
77 case CC_X86ThisCall:
78 return llvm::CallingConv::X86_ThisCall;
79 case CC_Win64:
80 return llvm::CallingConv::Win64;
81 case CC_X86_64SysV:
82 return llvm::CallingConv::X86_64_SysV;
83 case CC_AAPCS:
84 return llvm::CallingConv::ARM_AAPCS;
85 case CC_AAPCS_VFP:
86 return llvm::CallingConv::ARM_AAPCS_VFP;
87 case CC_IntelOclBicc:
88 return llvm::CallingConv::Intel_OCL_BI;
89 // TODO: Add support for __pascal to LLVM.
90 case CC_X86Pascal:
91 return llvm::CallingConv::C;
92 // TODO: Add support for __vectorcall to LLVM.
93 case CC_X86VectorCall:
94 return llvm::CallingConv::X86_VectorCall;
95 case CC_AArch64VectorCall:
96 return llvm::CallingConv::AArch64_VectorCall;
97 case CC_AArch64SVEPCS:
98 return llvm::CallingConv::AArch64_SVE_VectorCall;
99 case CC_DeviceKernel:
100 return CGM.getTargetCodeGenInfo().getDeviceKernelCallingConv();
101 case CC_PreserveMost:
102 return llvm::CallingConv::PreserveMost;
103 case CC_PreserveAll:
104 return llvm::CallingConv::PreserveAll;
105 case CC_Swift:
106 return llvm::CallingConv::Swift;
107 case CC_SwiftAsync:
108 return llvm::CallingConv::SwiftTail;
109 case CC_M68kRTD:
110 return llvm::CallingConv::M68k_RTD;
111 case CC_PreserveNone:
112 return llvm::CallingConv::PreserveNone;
113 // clang-format off
114 case CC_RISCVVectorCall: return llvm::CallingConv::RISCV_VectorCall;
115 // clang-format on
116#define CC_VLS_CASE(ABI_VLEN) \
117 case CC_RISCVVLSCall_##ABI_VLEN: \
118 return llvm::CallingConv::RISCV_VLSCall_##ABI_VLEN;
119 CC_VLS_CASE(32)
120 CC_VLS_CASE(64)
121 CC_VLS_CASE(128)
122 CC_VLS_CASE(256)
123 CC_VLS_CASE(512)
124 CC_VLS_CASE(1024)
125 CC_VLS_CASE(2048)
126 CC_VLS_CASE(4096)
127 CC_VLS_CASE(8192)
128 CC_VLS_CASE(16384)
129 CC_VLS_CASE(32768)
130 CC_VLS_CASE(65536)
131#undef CC_VLS_CASE
132 }
133 llvm_unreachable("unhandled calling convention");
134}
135
136/// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
137/// qualification. Either or both of RD and MD may be null. A null RD indicates
138/// that there is no meaningful 'this' type, and a null MD can occur when
139/// calling a method pointer.
140CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
141 const CXXMethodDecl *MD) {
142 CanQualType RecTy;
143 if (RD)
144 RecTy = Context.getCanonicalTagType(TD: RD);
145 else
146 RecTy = Context.VoidTy;
147
148 if (MD)
149 RecTy = CanQualType::CreateUnsafe(Other: Context.getAddrSpaceQualType(
150 T: RecTy, AddressSpace: MD->getMethodQualifiers().getAddressSpace()));
151 return Context.getPointerType(T: RecTy);
152}
153
154/// Returns the "extra-canonicalized" return type, which discards
155/// qualifiers on the return type. Codegen doesn't care about them,
156/// and it makes ABI code a little easier to be able to assume that
157/// all parameter and return types are top-level unqualified.
158static CanQualType GetReturnType(QualType RetTy) {
159 return RetTy->getCanonicalTypeUnqualified();
160}
161
162/// Arrange the argument and result information for a value of the given
163/// unprototyped freestanding function type.
164const CGFunctionInfo &
165CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
166 // When translating an unprototyped function type, always use a
167 // variadic type.
168 return arrangeLLVMFunctionInfo(returnType: FTNP->getReturnType().getUnqualifiedType(),
169 opts: FnInfoOpts::None, argTypes: {}, info: FTNP->getExtInfo(), paramInfos: {},
170 args: RequiredArgs(0), /*ABIInfoFD=*/nullptr);
171}
172
173static void addExtParameterInfosForCall(
174 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
175 const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs) {
176 assert(proto->hasExtParameterInfos());
177 assert(paramInfos.size() <= prefixArgs);
178 assert(proto->getNumParams() + prefixArgs <= totalArgs);
179
180 paramInfos.reserve(N: totalArgs);
181
182 // Add default infos for any prefix args that don't already have infos.
183 paramInfos.resize(N: prefixArgs);
184
185 // Add infos for the prototype.
186 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
187 paramInfos.push_back(Elt: ParamInfo);
188 // pass_object_size params have no parameter info.
189 if (ParamInfo.hasPassObjectSize())
190 paramInfos.emplace_back();
191 }
192
193 assert(paramInfos.size() <= totalArgs &&
194 "Did we forget to insert pass_object_size args?");
195 // Add default infos for the variadic and/or suffix arguments.
196 paramInfos.resize(N: totalArgs);
197}
198
199/// Adds the formal parameters in FPT to the given prefix. If any parameter in
200/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
201static void appendParameterTypes(
202 const CodeGenTypes &CGT, SmallVectorImpl<CanQualType> &prefix,
203 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
204 CanQual<FunctionProtoType> FPT) {
205 // Fast path: don't touch param info if we don't need to.
206 if (!FPT->hasExtParameterInfos()) {
207 assert(paramInfos.empty() &&
208 "We have paramInfos, but the prototype doesn't?");
209 prefix.append(in_start: FPT->param_type_begin(), in_end: FPT->param_type_end());
210 return;
211 }
212
213 unsigned PrefixSize = prefix.size();
214 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
215 // parameters; the only thing that can change this is the presence of
216 // pass_object_size. So, we preallocate for the common case.
217 prefix.reserve(N: prefix.size() + FPT->getNumParams());
218
219 auto ExtInfos = FPT->getExtParameterInfos();
220 assert(ExtInfos.size() == FPT->getNumParams());
221 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
222 prefix.push_back(Elt: FPT->getParamType(i: I));
223 if (ExtInfos[I].hasPassObjectSize())
224 prefix.push_back(Elt: CGT.getContext().getCanonicalSizeType());
225 }
226
227 addExtParameterInfosForCall(paramInfos, proto: FPT.getTypePtr(), prefixArgs: PrefixSize,
228 totalArgs: prefix.size());
229}
230
231using ExtParameterInfoList =
232 SmallVector<FunctionProtoType::ExtParameterInfo, 16>;
233
234/// Arrange the LLVM function layout for a value of the given function
235/// type, on top of any implicit parameters already stored.
236static const CGFunctionInfo &
237arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
238 SmallVectorImpl<CanQualType> &prefix,
239 CanQual<FunctionProtoType> FTP) {
240 ExtParameterInfoList paramInfos;
241 RequiredArgs Required = RequiredArgs::forPrototypePlus(prototype: FTP, additional: prefix.size());
242 appendParameterTypes(CGT, prefix, paramInfos, FPT: FTP);
243 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
244
245 FnInfoOpts opts =
246 instanceMethod ? FnInfoOpts::IsInstanceMethod : FnInfoOpts::None;
247 return CGT.arrangeLLVMFunctionInfo(returnType: resultType, opts, argTypes: prefix,
248 info: FTP->getExtInfo(), paramInfos, args: Required,
249 /*ABIInfoFD=*/nullptr);
250}
251
252using CanQualTypeList = SmallVector<CanQualType, 16>;
253
254/// Arrange the argument and result information for a value of the
255/// given freestanding function type.
256const CGFunctionInfo &
257CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
258 CanQualTypeList argTypes;
259 return ::arrangeLLVMFunctionInfo(CGT&: *this, /*instanceMethod=*/false, prefix&: argTypes,
260 FTP);
261}
262
263static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
264 bool IsTargetDefaultMSABI) {
265 // Set the appropriate calling convention for the Function.
266 if (D->hasAttr<StdCallAttr>())
267 return CC_X86StdCall;
268
269 if (D->hasAttr<FastCallAttr>())
270 return CC_X86FastCall;
271
272 if (D->hasAttr<RegCallAttr>())
273 return CC_X86RegCall;
274
275 if (D->hasAttr<ThisCallAttr>())
276 return CC_X86ThisCall;
277
278 if (D->hasAttr<VectorCallAttr>())
279 return CC_X86VectorCall;
280
281 if (D->hasAttr<PascalAttr>())
282 return CC_X86Pascal;
283
284 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
285 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
286
287 if (D->hasAttr<AArch64VectorPcsAttr>())
288 return CC_AArch64VectorCall;
289
290 if (D->hasAttr<AArch64SVEPcsAttr>())
291 return CC_AArch64SVEPCS;
292
293 if (D->hasAttr<DeviceKernelAttr>())
294 return CC_DeviceKernel;
295
296 if (D->hasAttr<IntelOclBiccAttr>())
297 return CC_IntelOclBicc;
298
299 if (D->hasAttr<MSABIAttr>())
300 return IsTargetDefaultMSABI ? CC_C : CC_Win64;
301
302 if (D->hasAttr<SysVABIAttr>())
303 return IsTargetDefaultMSABI ? CC_X86_64SysV : CC_C;
304
305 if (D->hasAttr<PreserveMostAttr>())
306 return CC_PreserveMost;
307
308 if (D->hasAttr<PreserveAllAttr>())
309 return CC_PreserveAll;
310
311 if (D->hasAttr<M68kRTDAttr>())
312 return CC_M68kRTD;
313
314 if (D->hasAttr<PreserveNoneAttr>())
315 return CC_PreserveNone;
316
317 if (D->hasAttr<RISCVVectorCCAttr>())
318 return CC_RISCVVectorCall;
319
320 if (RISCVVLSCCAttr *PCS = D->getAttr<RISCVVLSCCAttr>()) {
321 switch (PCS->getVectorWidth()) {
322 default:
323 llvm_unreachable("Invalid RISC-V VLS ABI VLEN");
324#define CC_VLS_CASE(ABI_VLEN) \
325 case ABI_VLEN: \
326 return CC_RISCVVLSCall_##ABI_VLEN;
327 CC_VLS_CASE(32)
328 CC_VLS_CASE(64)
329 CC_VLS_CASE(128)
330 CC_VLS_CASE(256)
331 CC_VLS_CASE(512)
332 CC_VLS_CASE(1024)
333 CC_VLS_CASE(2048)
334 CC_VLS_CASE(4096)
335 CC_VLS_CASE(8192)
336 CC_VLS_CASE(16384)
337 CC_VLS_CASE(32768)
338 CC_VLS_CASE(65536)
339#undef CC_VLS_CASE
340 }
341 }
342
343 return CC_C;
344}
345
346/// Arrange the argument and result information for a call to an
347/// unknown C++ non-static member function of the given abstract type.
348/// (A null RD means we don't have any meaningful "this" argument type,
349/// so fall back to a generic pointer type).
350/// The member function must be an ordinary function, i.e. not a
351/// constructor or destructor.
352const CGFunctionInfo &
353CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
354 const FunctionProtoType *FTP,
355 const CXXMethodDecl *MD) {
356 CanQualTypeList argTypes;
357
358 // Add the 'this' pointer.
359 argTypes.push_back(Elt: DeriveThisType(RD, MD));
360 auto CanonicalFTP =
361 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>();
362 ExtParameterInfoList paramInfos;
363 RequiredArgs required = RequiredArgs::forPrototypePlus(
364 prototype: CanonicalFTP.getTypePtr(), additional: argTypes.size());
365 appendParameterTypes(CGT: *this, prefix&: argTypes, paramInfos, FPT: CanonicalFTP);
366 return arrangeLLVMFunctionInfo(
367 returnType: CanonicalFTP->getReturnType().getUnqualifiedType(),
368 opts: FnInfoOpts::IsInstanceMethod, argTypes, info: CanonicalFTP->getExtInfo(),
369 paramInfos, args: required, ABIInfoFD: MD);
370}
371
372/// Set calling convention for CUDA/HIP kernel.
373static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
374 const FunctionDecl *FD) {
375 if (FD->hasAttr<CUDAGlobalAttr>()) {
376 const FunctionType *FT = FTy->getAs<FunctionType>();
377 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
378 FTy = FT->getCanonicalTypeUnqualified();
379 }
380}
381
382/// Arrange the argument and result information for a declaration or
383/// definition of the given C++ non-static member function. The
384/// member function must be an ordinary function, i.e. not a
385/// constructor or destructor.
386const CGFunctionInfo &
387CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
388 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
389 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
390
391 CanQualType FT = CodeGenUtils::getFormalType(MD).getAs<Type>();
392 setCUDAKernelCallingConvention(FTy&: FT, CGM, FD: MD);
393 auto prototype = FT.getAs<FunctionProtoType>();
394
395 if (MD->isImplicitObjectMemberFunction()) {
396 // The abstract case is perfectly fine.
397 const CXXRecordDecl *ThisType =
398 getCXXABI().getThisArgumentTypeForMethod(GD: MD);
399 return arrangeCXXMethodType(RD: ThisType, FTP: prototype.getTypePtr(), MD);
400 }
401
402 CanQualTypeList argTypes;
403 ExtParameterInfoList paramInfos;
404 appendParameterTypes(CGT: *this, prefix&: argTypes, paramInfos, FPT: prototype);
405 return arrangeLLVMFunctionInfo(
406 returnType: prototype->getReturnType().getUnqualifiedType(), opts: FnInfoOpts::None,
407 argTypes, info: prototype->getExtInfo(), paramInfos,
408 args: RequiredArgs::forPrototypePlus(prototype: prototype.getTypePtr(), additional: 0), ABIInfoFD: MD);
409}
410
411bool CodeGenTypes::inheritingCtorHasParams(
412 const InheritedConstructor &Inherited, CXXCtorType Type) {
413 // Parameters are unnecessary if we're constructing a base class subobject
414 // and the inherited constructor lives in a virtual base.
415 return Type == Ctor_Complete ||
416 !Inherited.getShadowDecl()->constructsVirtualBase() ||
417 !Target.getCXXABI().hasConstructorVariants();
418}
419
420const CGFunctionInfo &
421CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
422 auto *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
423
424 CanQualTypeList argTypes;
425 ExtParameterInfoList paramInfos;
426
427 const CXXRecordDecl *ThisType = getCXXABI().getThisArgumentTypeForMethod(GD);
428 argTypes.push_back(Elt: DeriveThisType(RD: ThisType, MD));
429
430 bool PassParams = true;
431
432 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
433 // A base class inheriting constructor doesn't get forwarded arguments
434 // needed to construct a virtual base (or base class thereof).
435 if (auto Inherited = CD->getInheritedConstructor())
436 PassParams = inheritingCtorHasParams(Inherited, Type: GD.getCtorType());
437 }
438
439 CanQual<FunctionProtoType> FTP = CodeGenUtils::getFormalType(MD);
440
441 // Add the formal parameters.
442 if (PassParams)
443 appendParameterTypes(CGT: *this, prefix&: argTypes, paramInfos, FPT: FTP);
444
445 CGCXXABI::AddedStructorArgCounts AddedArgs =
446 getCXXABI().buildStructorSignature(GD, ArgTys&: argTypes);
447 if (!paramInfos.empty()) {
448 // Note: prefix implies after the first param.
449 if (AddedArgs.Prefix)
450 paramInfos.insert(I: paramInfos.begin() + 1, NumToInsert: AddedArgs.Prefix,
451 Elt: FunctionProtoType::ExtParameterInfo{});
452 if (AddedArgs.Suffix)
453 paramInfos.append(NumInputs: AddedArgs.Suffix,
454 Elt: FunctionProtoType::ExtParameterInfo{});
455 }
456
457 RequiredArgs required =
458 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
459 : RequiredArgs::All);
460
461 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
462 CanQualType resultType = getCXXABI().HasThisReturn(GD) ? argTypes.front()
463 : getCXXABI().hasMostDerivedReturn(GD)
464 ? CGM.getContext().VoidPtrTy
465 : Context.VoidTy;
466 return arrangeLLVMFunctionInfo(returnType: resultType, opts: FnInfoOpts::IsInstanceMethod,
467 argTypes, info: extInfo, paramInfos, args: required, ABIInfoFD: MD);
468}
469
470static CanQualTypeList getArgTypesForCall(ASTContext &ctx,
471 const CallArgList &args) {
472 CanQualTypeList argTypes;
473 for (auto &arg : args)
474 argTypes.push_back(Elt: ctx.getCanonicalParamType(T: arg.Ty));
475 return argTypes;
476}
477
478static CanQualTypeList getArgTypesForDeclaration(ASTContext &ctx,
479 const FunctionArgList &args) {
480 CanQualTypeList argTypes;
481 for (auto &arg : args)
482 argTypes.push_back(Elt: ctx.getCanonicalParamType(T: arg->getType()));
483 return argTypes;
484}
485
486static ExtParameterInfoList
487getExtParameterInfosForCall(const FunctionProtoType *proto, unsigned prefixArgs,
488 unsigned totalArgs) {
489 ExtParameterInfoList result;
490 if (proto->hasExtParameterInfos()) {
491 addExtParameterInfosForCall(paramInfos&: result, proto, prefixArgs, totalArgs);
492 }
493 return result;
494}
495
496/// Arrange a call to a C++ method, passing the given arguments.
497///
498/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
499/// parameter.
500/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
501/// args.
502/// PassProtoArgs indicates whether `args` has args for the parameters in the
503/// given CXXConstructorDecl.
504const CGFunctionInfo &CodeGenTypes::arrangeCXXConstructorCall(
505 const CallArgList &args, const CXXConstructorDecl *D, CXXCtorType CtorKind,
506 unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs,
507 const FunctionDecl *ABIInfoFD, bool PassProtoArgs) {
508 CanQualTypeList ArgTypes;
509 for (const auto &Arg : args)
510 ArgTypes.push_back(Elt: Context.getCanonicalParamType(T: Arg.Ty));
511
512 // +1 for implicit this, which should always be args[0].
513 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
514
515 CanQual<FunctionProtoType> FPT = CodeGenUtils::getFormalType(MD: D);
516 RequiredArgs Required = PassProtoArgs
517 ? RequiredArgs::forPrototypePlus(
518 prototype: FPT, additional: TotalPrefixArgs + ExtraSuffixArgs)
519 : RequiredArgs::All;
520
521 GlobalDecl GD(D, CtorKind);
522 CanQualType ResultType = getCXXABI().HasThisReturn(GD) ? ArgTypes.front()
523 : getCXXABI().hasMostDerivedReturn(GD)
524 ? CGM.getContext().VoidPtrTy
525 : Context.VoidTy;
526
527 FunctionType::ExtInfo Info = FPT->getExtInfo();
528 ExtParameterInfoList ParamInfos;
529 // If the prototype args are elided, we should only have ABI-specific args,
530 // which never have param info.
531 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
532 // ABI-specific suffix arguments are treated the same as variadic arguments.
533 addExtParameterInfosForCall(paramInfos&: ParamInfos, proto: FPT.getTypePtr(), prefixArgs: TotalPrefixArgs,
534 totalArgs: ArgTypes.size());
535 }
536
537 return arrangeLLVMFunctionInfo(returnType: ResultType, opts: FnInfoOpts::IsInstanceMethod,
538 argTypes: ArgTypes, info: Info, paramInfos: ParamInfos, args: Required,
539 ABIInfoFD);
540}
541
542/// Arrange the argument and result information for the declaration or
543/// definition of the given function.
544const CGFunctionInfo &
545CodeGenTypes::arrangeFunctionDeclaration(const GlobalDecl GD) {
546 const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl());
547 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
548 if (MD->isImplicitObjectMemberFunction())
549 return arrangeCXXMethodDeclaration(MD);
550
551 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
552
553 assert(isa<FunctionType>(FTy));
554 setCUDAKernelCallingConvention(FTy, CGM, FD);
555
556 if (DeviceKernelAttr::isOpenCLSpelling(A: FD->getAttr<DeviceKernelAttr>()) &&
557 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
558 const FunctionType *FT = FTy->getAs<FunctionType>();
559 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
560 FTy = FT->getCanonicalTypeUnqualified();
561 }
562
563 // When declaring a function without a prototype, always use a
564 // non-variadic type.
565 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
566 return arrangeLLVMFunctionInfo(returnType: noProto->getReturnType(), opts: FnInfoOpts::None,
567 argTypes: {}, info: noProto->getExtInfo(), paramInfos: {},
568 args: RequiredArgs::All, ABIInfoFD: FD);
569 }
570
571 CanQual<FunctionProtoType> FTP = FTy.castAs<FunctionProtoType>();
572 CanQualTypeList argTypes;
573 ExtParameterInfoList paramInfos;
574 appendParameterTypes(CGT: *this, prefix&: argTypes, paramInfos, FPT: FTP);
575 return arrangeLLVMFunctionInfo(returnType: FTP->getReturnType().getUnqualifiedType(),
576 opts: FnInfoOpts::None, argTypes, info: FTP->getExtInfo(),
577 paramInfos,
578 args: RequiredArgs::forPrototypePlus(prototype: FTP, additional: 0), ABIInfoFD: FD);
579}
580
581/// Arrange the argument and result information for the declaration or
582/// definition of an Objective-C method.
583const CGFunctionInfo &
584CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
585 // It happens that this is the same as a call with no optional
586 // arguments, except also using the formal 'self' type.
587 return arrangeObjCMessageSendSignature(MD, receiverType: MD->getSelfDecl()->getType());
588}
589
590/// Arrange the argument and result information for the function type
591/// through which to perform a send to the given Objective-C method,
592/// using the given receiver type. The receiver type is not always
593/// the 'self' type of the method or even an Objective-C pointer type.
594/// This is *not* the right method for actually performing such a
595/// message send, due to the possibility of optional arguments.
596const CGFunctionInfo &
597CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
598 QualType receiverType) {
599 CanQualTypeList argTys;
600 ExtParameterInfoList extParamInfos(MD->isDirectMethod() ? 1 : 2);
601 argTys.push_back(Elt: Context.getCanonicalParamType(T: receiverType));
602 if (!MD->isDirectMethod())
603 argTys.push_back(Elt: Context.getCanonicalParamType(T: Context.getObjCSelType()));
604 for (const auto *I : MD->parameters()) {
605 argTys.push_back(Elt: Context.getCanonicalParamType(T: I->getType()));
606 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
607 NoEscape: I->hasAttr<NoEscapeAttr>());
608 extParamInfos.push_back(Elt: extParamInfo);
609 }
610
611 FunctionType::ExtInfo einfo;
612 bool IsTargetDefaultMSABI =
613 getContext().getTargetInfo().getTriple().isOSWindows() ||
614 getContext().getTargetInfo().getTriple().isUEFI();
615 einfo = einfo.withCallingConv(
616 cc: getCallingConventionForDecl(D: MD, IsTargetDefaultMSABI));
617
618 if (getContext().getLangOpts().ObjCAutoRefCount &&
619 MD->hasAttr<NSReturnsRetainedAttr>())
620 einfo = einfo.withProducesResult(producesResult: true);
621
622 RequiredArgs required =
623 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
624
625 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: MD->getReturnType()),
626 opts: FnInfoOpts::None, argTypes: argTys, info: einfo, paramInfos: extParamInfos,
627 args: required, /*ABIInfoFD=*/nullptr);
628}
629
630const CGFunctionInfo &
631CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
632 const CallArgList &args) {
633 CanQualTypeList argTypes = getArgTypesForCall(ctx&: Context, args);
634 FunctionType::ExtInfo einfo;
635
636 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: returnType), opts: FnInfoOpts::None,
637 argTypes, info: einfo, paramInfos: {}, args: RequiredArgs::All,
638 ABIInfoFD: nullptr);
639}
640
641const CGFunctionInfo &CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
642 // FIXME: Do we need to handle ObjCMethodDecl?
643 if (isa<CXXConstructorDecl>(Val: GD.getDecl()) ||
644 isa<CXXDestructorDecl>(Val: GD.getDecl()))
645 return arrangeCXXStructorDeclaration(GD);
646
647 return arrangeFunctionDeclaration(GD);
648}
649
650/// Arrange a thunk that takes 'this' as the first parameter followed by
651/// varargs. Return a void pointer, regardless of the actual return type.
652/// The body of the thunk will end in a musttail call to a function of the
653/// correct type, and the caller will bitcast the function to the correct
654/// prototype.
655const CGFunctionInfo &
656CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
657 assert(MD->isVirtual() && "only methods have thunks");
658 CanQual<FunctionProtoType> FTP = CodeGenUtils::getFormalType(MD);
659 CanQualType ArgTys[] = {DeriveThisType(RD: MD->getParent(), MD)};
660 return arrangeLLVMFunctionInfo(returnType: Context.VoidTy, opts: FnInfoOpts::None, argTypes: ArgTys,
661 info: FTP->getExtInfo(), paramInfos: {}, args: RequiredArgs(1), ABIInfoFD: MD);
662}
663
664const CGFunctionInfo &
665CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
666 CXXCtorType CT) {
667 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
668
669 CanQual<FunctionProtoType> FTP = CodeGenUtils::getFormalType(MD: CD);
670 SmallVector<CanQualType, 2> ArgTys;
671 const CXXRecordDecl *RD = CD->getParent();
672 ArgTys.push_back(Elt: DeriveThisType(RD, MD: CD));
673 if (CT == Ctor_CopyingClosure)
674 ArgTys.push_back(Elt: *FTP->param_type_begin());
675 if (RD->getNumVBases() > 0)
676 ArgTys.push_back(Elt: Context.IntTy);
677 CallingConv CC = Context.getDefaultCallingConvention(
678 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
679 return arrangeLLVMFunctionInfo(returnType: Context.VoidTy, opts: FnInfoOpts::IsInstanceMethod,
680 argTypes: ArgTys, info: FunctionType::ExtInfo(CC), paramInfos: {},
681 args: RequiredArgs::All, /*ABIInfoFD=*/nullptr);
682}
683
684/// Arrange a call as unto a free function, except possibly with an
685/// additional number of formal parameters considered required.
686static const CGFunctionInfo &
687arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, CodeGenModule &CGM,
688 const CallArgList &args, const FunctionType *fnType,
689 unsigned numExtraRequiredArgs, bool chainCall,
690 const FunctionDecl *ABIInfoFD) {
691 assert(args.size() >= numExtraRequiredArgs);
692
693 ExtParameterInfoList paramInfos;
694
695 // In most cases, there are no optional arguments.
696 RequiredArgs required = RequiredArgs::All;
697
698 // If we have a variadic prototype, the required arguments are the
699 // extra prefix plus the arguments in the prototype.
700 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(Val: fnType)) {
701 if (proto->isVariadic())
702 required = RequiredArgs::forPrototypePlus(prototype: proto, additional: numExtraRequiredArgs);
703
704 if (proto->hasExtParameterInfos())
705 addExtParameterInfosForCall(paramInfos, proto, prefixArgs: numExtraRequiredArgs,
706 totalArgs: args.size());
707
708 // If we don't have a prototype at all, but we're supposed to
709 // explicitly use the variadic convention for unprototyped calls,
710 // treat all of the arguments as required but preserve the nominal
711 // possibility of variadics.
712 } else if (CGM.getTargetCodeGenInfo().isNoProtoCallVariadic(
713 args, fnType: cast<FunctionNoProtoType>(Val: fnType))) {
714 required = RequiredArgs(args.size());
715 }
716
717 CanQualTypeList argTypes;
718 for (const auto &arg : args)
719 argTypes.push_back(Elt: CGT.getContext().getCanonicalParamType(T: arg.Ty));
720 FnInfoOpts opts = chainCall ? FnInfoOpts::IsChainCall : FnInfoOpts::None;
721 return CGT.arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: fnType->getReturnType()),
722 opts, argTypes, info: fnType->getExtInfo(),
723 paramInfos, args: required, ABIInfoFD);
724}
725
726/// Figure out the rules for calling a function with the given formal
727/// type using the given arguments. The arguments are necessary
728/// because the function might be unprototyped, in which case it's
729/// target-dependent in crazy ways.
730const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionCall(
731 const CallArgList &args, const FunctionType *fnType, bool chainCall,
732 const FunctionDecl *ABIInfoFD) {
733 return arrangeFreeFunctionLikeCall(CGT&: *this, CGM, args, fnType,
734 numExtraRequiredArgs: chainCall ? 1 : 0, chainCall, ABIInfoFD);
735}
736
737/// A block function is essentially a free function with an
738/// extra implicit argument.
739const CGFunctionInfo &
740CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
741 const FunctionType *fnType) {
742 // FIXME: Pass the enclosing function's ABI information so block calls use
743 // the caller's target features.
744 return arrangeFreeFunctionLikeCall(CGT&: *this, CGM, args, fnType, numExtraRequiredArgs: 1,
745 /*chainCall=*/false, ABIInfoFD: nullptr);
746}
747
748const CGFunctionInfo &
749CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
750 const FunctionArgList &params) {
751 ExtParameterInfoList paramInfos =
752 getExtParameterInfosForCall(proto, prefixArgs: 1, totalArgs: params.size());
753 CanQualTypeList argTypes = getArgTypesForDeclaration(ctx&: Context, args: params);
754
755 // FIXME: Use the block's target features when arranging its invoke function.
756 return arrangeLLVMFunctionInfo(
757 returnType: GetReturnType(RetTy: proto->getReturnType()), opts: FnInfoOpts::None, argTypes,
758 info: proto->getExtInfo(), paramInfos, args: RequiredArgs::forPrototypePlus(prototype: proto, additional: 1),
759 /*ABIInfoFD=*/nullptr);
760}
761
762const CGFunctionInfo &
763CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
764 const CallArgList &args) {
765 CanQualTypeList argTypes;
766 for (const auto &Arg : args)
767 argTypes.push_back(Elt: Context.getCanonicalParamType(T: Arg.Ty));
768 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: resultType), opts: FnInfoOpts::None,
769 argTypes, info: FunctionType::ExtInfo(),
770 /*paramInfos=*/{}, args: RequiredArgs::All, ABIInfoFD: nullptr);
771}
772
773const CGFunctionInfo &
774CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
775 const FunctionArgList &args) {
776 CanQualTypeList argTypes = getArgTypesForDeclaration(ctx&: Context, args);
777
778 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: resultType), opts: FnInfoOpts::None,
779 argTypes, info: FunctionType::ExtInfo(), paramInfos: {},
780 args: RequiredArgs::All, /*ABIInfoFD=*/nullptr);
781}
782
783const CGFunctionInfo &CodeGenTypes::arrangeBuiltinFunctionDeclaration(
784 CanQualType resultType, ArrayRef<CanQualType> argTypes) {
785 return arrangeLLVMFunctionInfo(returnType: resultType, opts: FnInfoOpts::None, argTypes,
786 info: FunctionType::ExtInfo(), paramInfos: {}, args: RequiredArgs::All,
787 /*ABIInfoFD=*/nullptr);
788}
789
790const CGFunctionInfo &CodeGenTypes::arrangeDeviceKernelCallerDeclaration(
791 QualType resultType, const FunctionArgList &args) {
792 CanQualTypeList argTypes = getArgTypesForDeclaration(ctx&: Context, args);
793
794 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: resultType), opts: FnInfoOpts::None,
795 argTypes,
796 info: FunctionType::ExtInfo(CC_DeviceKernel),
797 /*paramInfos=*/{}, args: RequiredArgs::All,
798 /*ABIInfoFD=*/nullptr);
799}
800
801/// Arrange a call to a C++ method, passing the given arguments.
802///
803/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
804/// does not count `this`.
805const CGFunctionInfo &CodeGenTypes::arrangeCXXMethodCall(
806 const CallArgList &args, const FunctionProtoType *proto,
807 RequiredArgs required, unsigned numPrefixArgs,
808 const FunctionDecl *ABIInfoFD) {
809 assert(numPrefixArgs + 1 <= args.size() &&
810 "Emitting a call with less args than the required prefix?");
811 // Add one to account for `this`. It's a bit awkward here, but we don't count
812 // `this` in similar places elsewhere.
813 ExtParameterInfoList paramInfos =
814 getExtParameterInfosForCall(proto, prefixArgs: numPrefixArgs + 1, totalArgs: args.size());
815
816 CanQualTypeList argTypes = getArgTypesForCall(ctx&: Context, args);
817
818 FunctionType::ExtInfo info = proto->getExtInfo();
819 return arrangeLLVMFunctionInfo(returnType: GetReturnType(RetTy: proto->getReturnType()),
820 opts: FnInfoOpts::IsInstanceMethod, argTypes, info,
821 paramInfos, args: required, ABIInfoFD);
822}
823
824const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
825 return arrangeLLVMFunctionInfo(returnType: getContext().VoidTy, opts: FnInfoOpts::None, argTypes: {},
826 info: FunctionType::ExtInfo(), paramInfos: {}, args: RequiredArgs::All,
827 /*ABIInfoFD=*/nullptr);
828}
829
830const CGFunctionInfo &CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
831 const CallArgList &args,
832 const FunctionDecl *ABIInfoFD) {
833 assert(signature.arg_size() <= args.size());
834 unsigned X86ABIAVXLevel =
835 CGM.getABIInfo().getX86ABIAVXLevel(ABIInfoFD, signature.getExtInfo());
836 if (signature.arg_size() == args.size() &&
837 signature.getX86ABIAVXLevel() == X86ABIAVXLevel)
838 return signature;
839
840 ExtParameterInfoList paramInfos;
841 auto sigParamInfos = signature.getExtParameterInfos();
842 if (!sigParamInfos.empty()) {
843 paramInfos.append(in_start: sigParamInfos.begin(), in_end: sigParamInfos.end());
844 paramInfos.resize(N: args.size());
845 }
846
847 CanQualTypeList argTypes = getArgTypesForCall(ctx&: Context, args);
848
849 assert(signature.getRequiredArgs().allowsOptionalArgs());
850 FnInfoOpts opts = FnInfoOpts::None;
851 if (signature.isInstanceMethod())
852 opts |= FnInfoOpts::IsInstanceMethod;
853 if (signature.isChainCall())
854 opts |= FnInfoOpts::IsChainCall;
855 if (signature.isDelegateCall())
856 opts |= FnInfoOpts::IsDelegateCall;
857
858 const CGFunctionInfo *newFI = findOrInsertCGFunctionInfo(
859 isInstanceMethod: signature.isInstanceMethod(), isChainCall: signature.isChainCall(),
860 isDelegateCall: signature.isDelegateCall(), X86ABIAVXLevel, info: signature.getExtInfo(),
861 paramInfos, required: signature.getRequiredArgs(), resultType: signature.getReturnType(),
862 argTypes);
863 return *newFI;
864}
865
866namespace clang {
867namespace CodeGen {
868void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
869} // namespace CodeGen
870} // namespace clang
871
872#ifndef NDEBUG
873static const char *abiKindToString(ABIArgInfo::Kind K) {
874 switch (K) {
875 case ABIArgInfo::Direct:
876 return "Direct";
877 case ABIArgInfo::Extend:
878 return "Extend";
879 case ABIArgInfo::Indirect:
880 return "Indirect";
881 case ABIArgInfo::IndirectAliased:
882 return "IndirectAliased";
883 case ABIArgInfo::Ignore:
884 return "Ignore";
885 case ABIArgInfo::Expand:
886 return "Expand";
887 case ABIArgInfo::CoerceAndExpand:
888 return "CoerceAndExpand";
889 case ABIArgInfo::TargetSpecific:
890 return "TargetSpecific";
891 case ABIArgInfo::InAlloca:
892 return "InAlloca";
893 }
894 llvm_unreachable("Unknown kind");
895}
896#endif
897
898void CodeGenModule::computeABIInfoUsingLib(CGFunctionInfo &FI) {
899 SmallVector<const llvm::abi::Type *> MappedArgTypes;
900 MappedArgTypes.reserve(N: FI.arg_size());
901 for (const auto &Arg : FI.arguments())
902 MappedArgTypes.push_back(Elt: AbiMapper->convertType(QT: Arg.type));
903
904 RequiredArgs Required = FI.getRequiredArgs();
905 llvm::abi::RequiredArgs AbiRequired = llvm::abi::RequiredArgs::All;
906 if (Required.allowsOptionalArgs())
907 AbiRequired = llvm::abi::RequiredArgs(Required.getNumRequiredArgs());
908
909 auto AbiFI = llvm::abi::FunctionInfo::create(
910 CC: FI.getCallingConvention(), ReturnType: AbiMapper->convertType(QT: FI.getReturnType()),
911 ArgTypes: MappedArgTypes, Required: AbiRequired);
912
913 getLLVMABITargetInfo(TB&: AbiMapper->getTypeBuilder()).computeInfo(FI&: *AbiFI);
914
915#ifndef NDEBUG
916 // With assertions enabled, also compute info using Clang ABI logic,
917 // so we can ensure the results are consistent.
918 getABIInfo().computeInfo(FI);
919
920 auto ConvertABIArgInfo = [&](ABIArgInfo &Target,
921 const llvm::abi::ArgInfo &AbiInfo, QualType Type,
922 int ArgNo) {
923 auto Check = [&](bool Cond, llvm::function_ref<void()> MessageFn) {
924 if (Cond)
925 return;
926 if (ArgNo == -1)
927 llvm::dbgs() << "For return value of type ";
928 else
929 llvm::dbgs() << "For argument " << ArgNo << " of type ";
930 llvm::dbgs() << Type << ": ";
931 MessageFn();
932 llvm::dbgs() << "\n";
933 abort();
934 };
935 auto CheckSimple = [&](auto TargetVal, auto ResVal, StringRef What) {
936 Check(TargetVal == ResVal, [&]() {
937 llvm::dbgs() << What << " mismatch (expected: " << TargetVal
938 << ", given: " << ResVal << ")";
939 });
940 };
941
942 ABIArgInfo Res = convertABIArgInfo(AbiInfo, Type);
943 Check(Target.getKind() == Res.getKind(), [&]() {
944 llvm::dbgs() << "Kind mismatch (expected: "
945 << abiKindToString(Target.getKind())
946 << ", given: " << abiKindToString(Res.getKind()) << ")";
947 });
948
949 if (Res.canHaveCoerceToType()) {
950 // Normalize nullptr types.
951 llvm::Type *TargetType = Target.getCoerceToType();
952 llvm::Type *ResType = Res.getCoerceToType();
953 if (!TargetType)
954 TargetType = getTypes().ConvertType(Type);
955 if (!ResType)
956 ResType = getTypes().ConvertType(Type);
957
958 Check(TargetType == ResType, [&]() {
959 llvm::dbgs() << "CoerceToType mismatch (expected: " << *TargetType
960 << ", given: " << *ResType << ")";
961 });
962 }
963
964 switch (Res.getKind()) {
965 case ABIArgInfo::Extend:
966 CheckSimple(Target.isSignExt(), Res.isSignExt(), "SignExt");
967 CheckSimple(Target.isZeroExt(), Res.isZeroExt(), "ZeroExt");
968 [[fallthrough]];
969 case ABIArgInfo::Direct:
970 CheckSimple(Target.getDirectAlign(), Res.getDirectAlign(), "DirectAlign");
971 CheckSimple(Target.getDirectOffset(), Res.getDirectOffset(),
972 "DirectOffset");
973 // Extend falls through to here, and only Direct carries the flag.
974 if (Res.isDirect())
975 CheckSimple(Target.getCanBeFlattened(), Res.getCanBeFlattened(),
976 "CanBeFlattened");
977 break;
978 case ABIArgInfo::Indirect:
979 CheckSimple(Target.getIndirectByVal(), Res.getIndirectByVal(),
980 "IndirectByVal");
981 [[fallthrough]];
982 case ABIArgInfo::IndirectAliased:
983 CheckSimple(Target.getIndirectAddrSpace(), Res.getIndirectAddrSpace(),
984 "IndirectAddrSpace");
985 CheckSimple(Target.getIndirectRealign(), Res.getIndirectRealign(),
986 "IndirectRealign");
987 Check(Target.getIndirectAlign() == Res.getIndirectAlign(), [&]() {
988 llvm::dbgs() << "IndirectAlign mismatch (expected: "
989 << Target.getIndirectAlign().getQuantity()
990 << ", given: " << Res.getIndirectAlign().getQuantity()
991 << ")";
992 });
993 break;
994 case ABIArgInfo::CoerceAndExpand:
995 Check(Target.getUnpaddedCoerceAndExpandType() ==
996 Res.getUnpaddedCoerceAndExpandType(),
997 [&]() {
998 llvm::dbgs() << "UnpaddedCoerceAndExpandType mismatch (expected: "
999 << *Target.getUnpaddedCoerceAndExpandType()
1000 << ", given: "
1001 << *Res.getUnpaddedCoerceAndExpandType() << ")";
1002 });
1003 break;
1004 default:
1005 break;
1006 }
1007
1008 Target = Res;
1009 };
1010#else
1011 auto ConvertABIArgInfo =
1012 [&](ABIArgInfo &Target, const llvm::abi::ArgInfo &AbiInfo, QualType Type,
1013 int ArgNo) { Target = convertABIArgInfo(AbiInfo, Type); };
1014#endif
1015
1016 ConvertABIArgInfo(FI.getReturnInfo(), AbiFI->getReturnInfo(),
1017 FI.getReturnType(), -1);
1018
1019 int ArgNo = 0;
1020 for (auto [CGArg, AbiArg] :
1021 llvm::zip_equal(t: FI.arguments(), u: AbiFI->arguments()))
1022 ConvertABIArgInfo(CGArg.info, AbiArg.Info, CGArg.type, ArgNo++);
1023}
1024
1025ABIArgInfo CodeGenModule::convertABIArgInfo(const llvm::abi::ArgInfo &AbiInfo,
1026 QualType Type) {
1027 switch (AbiInfo.getKind()) {
1028 case llvm::abi::ArgInfo::Direct: {
1029 llvm::Type *CoercedType = nullptr;
1030 if (AbiInfo.getCoerceToType())
1031 CoercedType = AbiReverseMapper->convertType(ABIType: AbiInfo.getCoerceToType());
1032 if (!CoercedType)
1033 CoercedType = getTypes().ConvertType(T: Type);
1034 unsigned DirectAlign = 0;
1035 if (llvm::MaybeAlign Align = AbiInfo.getDirectAlign())
1036 DirectAlign = Align->value();
1037 // TODO: Move Padding into the ABIArgInfo struct when we add support for
1038 // targets that need a different setting than we have here.
1039 return ABIArgInfo::getDirect(T: CoercedType, Offset: AbiInfo.getDirectOffset(),
1040 /*Padding=*/nullptr,
1041 CanBeFlattened: AbiInfo.getCanBeFlattened(), Align: DirectAlign);
1042 }
1043 case llvm::abi::ArgInfo::Extend: {
1044 llvm::Type *CoercedType = nullptr;
1045 if (AbiInfo.getCoerceToType())
1046 CoercedType = AbiReverseMapper->convertType(ABIType: AbiInfo.getCoerceToType());
1047 if (!CoercedType)
1048 CoercedType = getTypes().ConvertType(T: Type);
1049 // A transparent union is passed as its first field, so the extend keys off
1050 // that field's integral type, matching the classifier's
1051 // useFirstFieldIfTransparentUnion. Passing the union type to
1052 // ABIArgInfo::getSignExtend would trip its integral-type assert.
1053 QualType ExtendType = useFirstFieldIfTransparentUnion(Ty: Type);
1054 if (AbiInfo.isSignExt())
1055 return ABIArgInfo::getSignExtend(Ty: ExtendType, T: CoercedType);
1056 if (AbiInfo.isZeroExt())
1057 return ABIArgInfo::getZeroExtend(Ty: ExtendType, T: CoercedType);
1058 return ABIArgInfo::getExtend(Ty: ExtendType, T: CoercedType);
1059 }
1060 case llvm::abi::ArgInfo::Indirect: {
1061 CharUnits Alignment =
1062 CharUnits::fromQuantity(Quantity: AbiInfo.getIndirectAlign().value());
1063 return ABIArgInfo::getIndirect(Alignment, AddrSpace: AbiInfo.getIndirectAddrSpace(),
1064 ByVal: AbiInfo.getIndirectByVal(),
1065 Realign: AbiInfo.getIndirectRealign());
1066 }
1067 case llvm::abi::ArgInfo::IndirectAliased: {
1068 // Aliased indirect carries an address space but never byval.
1069 CharUnits Alignment =
1070 CharUnits::fromQuantity(Quantity: AbiInfo.getIndirectAlign().value());
1071 return ABIArgInfo::getIndirectAliased(Alignment,
1072 AddrSpace: AbiInfo.getIndirectAddrSpace(),
1073 Realign: AbiInfo.getIndirectRealign());
1074 }
1075 case llvm::abi::ArgInfo::Ignore:
1076 return ABIArgInfo::getIgnore();
1077 case llvm::abi::ArgInfo::CoerceAndExpand: {
1078 llvm::StructType *CoercedType = llvm::cast<llvm::StructType>(
1079 Val: AbiReverseMapper->convertType(ABIType: AbiInfo.getCoerceToType()));
1080 llvm::Type *UnpaddedType =
1081 AbiReverseMapper->convertType(ABIType: AbiInfo.getUnpaddedCoerceAndExpandType());
1082 return ABIArgInfo::getCoerceAndExpand(coerceToType: CoercedType, unpaddedCoerceToType: UnpaddedType);
1083 }
1084 }
1085 llvm_unreachable("Unexpected llvm::abi::ArgInfo kind");
1086}
1087
1088/// Arrange the argument and result information for an abstract value
1089/// of a given function type. This is the method which all of the
1090/// above functions ultimately defer to.
1091const CGFunctionInfo &CodeGenTypes::arrangeLLVMFunctionInfo(
1092 CanQualType resultType, FnInfoOpts opts, ArrayRef<CanQualType> argTypes,
1093 FunctionType::ExtInfo info,
1094 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
1095 RequiredArgs required, const FunctionDecl *ABIInfoFD) {
1096 assert(llvm::all_of(argTypes,
1097 [](CanQualType T) { return T.isCanonicalAsParam(); }));
1098
1099 // Lookup or create unique function info.
1100 llvm::FoldingSetNodeID ID;
1101 bool isInstanceMethod =
1102 (opts & FnInfoOpts::IsInstanceMethod) == FnInfoOpts::IsInstanceMethod;
1103 bool isChainCall =
1104 (opts & FnInfoOpts::IsChainCall) == FnInfoOpts::IsChainCall;
1105 bool isDelegateCall =
1106 (opts & FnInfoOpts::IsDelegateCall) == FnInfoOpts::IsDelegateCall;
1107 unsigned X86ABIAVXLevel = CGM.getABIInfo().getX86ABIAVXLevel(ABIInfoFD, info);
1108
1109 const CGFunctionInfo *newFI = findOrInsertCGFunctionInfo(
1110 isInstanceMethod, isChainCall, isDelegateCall, X86ABIAVXLevel, info,
1111 paramInfos, required, resultType, argTypes);
1112 return *newFI;
1113}
1114
1115CGFunctionInfo *CodeGenTypes::findOrInsertCGFunctionInfo(
1116 bool isInstanceMethod, bool isChainCall, bool isDelegateCall,
1117 unsigned X86ABIAVXLevel, const FunctionType::ExtInfo &info,
1118 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
1119 RequiredArgs required, CanQualType resultType,
1120 ArrayRef<CanQualType> argTypes) {
1121 llvm::FoldingSetNodeID ID;
1122 CGFunctionInfo::Profile(ID, InstanceMethod: isInstanceMethod, ChainCall: isChainCall, IsDelegateCall: isDelegateCall,
1123 X86ABIAVXLevel, info, paramInfos, required,
1124 resultType, argTypes);
1125
1126 llvm::FoldingSetInsertToken InsertToken;
1127 CGFunctionInfo *FI = FunctionInfos.lookup(ID, Token&: InsertToken);
1128 if (FI)
1129 return FI;
1130
1131 unsigned CC = ClangCallConvToLLVMCallConv(CC: info.getCC());
1132
1133 // Construct the function info. We co-allocate the ArgInfos.
1134 FI = CGFunctionInfo::create(llvmCC: CC, instanceMethod: isInstanceMethod, chainCall: isChainCall, delegateCall: isDelegateCall,
1135 X86ABIAVXLevel, extInfo: info, paramInfos, resultType,
1136 argTypes, required);
1137 FunctionInfos.insert(N: FI, Token: InsertToken);
1138
1139 bool inserted = FunctionsBeingProcessed.insert(Ptr: FI).second;
1140 (void)inserted;
1141 assert(inserted && "Recursively being processed?");
1142
1143 // Compute ABI information.
1144 if (info.getCC() == CC_DeviceKernel &&
1145 (CC == llvm::CallingConv::SPIR_KERNEL || CC == llvm::CallingConv::C)) {
1146 // Force target independent argument handling for the host visible
1147 // kernel functions.
1148 //
1149 // For CPU targets, this currently only works for OpenCL.
1150 assert(CC != llvm::CallingConv::C || getContext().getLangOpts().OpenCL);
1151 computeSPIRKernelABIInfo(CGM, FI&: *FI);
1152 } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
1153 swiftcall::computeABIInfo(CGM, FI&: *FI);
1154 } else if (CGM.shouldUseLLVMABILowering(CallingConv: CC)) {
1155 CGM.computeABIInfoUsingLib(FI&: *FI);
1156 } else {
1157 CGM.getABIInfo().computeInfo(FI&: *FI);
1158 }
1159
1160 // Loop over all of the computed argument and return value info. If any of
1161 // them are direct or extend without a specified coerce type, specify the
1162 // default now.
1163 ABIArgInfo &retInfo = FI->getReturnInfo();
1164 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
1165 retInfo.setCoerceToType(ConvertType(T: FI->getReturnType()));
1166
1167 for (auto &I : FI->arguments())
1168 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
1169 I.info.setCoerceToType(ConvertType(T: I.type));
1170
1171 bool erased = FunctionsBeingProcessed.erase(Ptr: FI);
1172 (void)erased;
1173 assert(erased && "Not in set?");
1174
1175 return FI;
1176}
1177
1178CGFunctionInfo *CGFunctionInfo::create(
1179 unsigned llvmCC, bool instanceMethod, bool chainCall, bool delegateCall,
1180 unsigned X86ABIAVXLevel, const FunctionType::ExtInfo &info,
1181 ArrayRef<ExtParameterInfo> paramInfos, CanQualType resultType,
1182 ArrayRef<CanQualType> argTypes, RequiredArgs required) {
1183 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
1184 assert(!required.allowsOptionalArgs() ||
1185 required.getNumRequiredArgs() <= argTypes.size());
1186
1187 void *buffer = operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
1188 Counts: argTypes.size() + 1, Counts: paramInfos.size()));
1189
1190 CGFunctionInfo *FI = new (buffer) CGFunctionInfo();
1191 FI->CallingConvention = llvmCC;
1192 FI->EffectiveCallingConvention = llvmCC;
1193 FI->ASTCallingConvention = info.getCC();
1194 FI->InstanceMethod = instanceMethod;
1195 FI->ChainCall = chainCall;
1196 FI->DelegateCall = delegateCall;
1197 FI->CmseNSCall = info.getCmseNSCall();
1198 FI->NoReturn = info.getNoReturn();
1199 FI->ReturnsRetained = info.getProducesResult();
1200 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
1201 FI->NoCfCheck = info.getNoCfCheck();
1202 FI->Required = required;
1203 FI->HasRegParm = info.getHasRegParm();
1204 FI->RegParm = info.getRegParm();
1205 FI->X86ABIAVXLevel = X86ABIAVXLevel;
1206 FI->ArgStruct = nullptr;
1207 FI->ArgStructAlign = 0;
1208 FI->NumArgs = argTypes.size();
1209 FI->HasExtParameterInfos = !paramInfos.empty();
1210 FI->getArgsBuffer()[0].type = resultType;
1211 FI->MaxVectorWidth = 0;
1212 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
1213 FI->getArgsBuffer()[i + 1].type = argTypes[i];
1214 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
1215 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
1216 return FI;
1217}
1218
1219/***/
1220
1221namespace {
1222// ABIArgInfo::Expand implementation.
1223
1224// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
1225struct TypeExpansion {
1226 enum TypeExpansionKind {
1227 // Elements of constant arrays are expanded recursively.
1228 TEK_ConstantArray,
1229 // Record fields are expanded recursively (but if record is a union, only
1230 // the field with the largest size is expanded).
1231 TEK_Record,
1232 // For complex types, real and imaginary parts are expanded recursively.
1233 TEK_Complex,
1234 // All other types are not expandable.
1235 TEK_None
1236 };
1237
1238 const TypeExpansionKind Kind;
1239
1240 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
1241 virtual ~TypeExpansion() {}
1242};
1243
1244struct ConstantArrayExpansion : TypeExpansion {
1245 QualType EltTy;
1246 uint64_t NumElts;
1247
1248 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
1249 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
1250 static bool classof(const TypeExpansion *TE) {
1251 return TE->Kind == TEK_ConstantArray;
1252 }
1253};
1254
1255struct RecordExpansion : TypeExpansion {
1256 SmallVector<const CXXBaseSpecifier *, 1> Bases;
1257
1258 SmallVector<const FieldDecl *, 1> Fields;
1259
1260 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
1261 SmallVector<const FieldDecl *, 1> &&Fields)
1262 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
1263 Fields(std::move(Fields)) {}
1264 static bool classof(const TypeExpansion *TE) {
1265 return TE->Kind == TEK_Record;
1266 }
1267};
1268
1269struct ComplexExpansion : TypeExpansion {
1270 QualType EltTy;
1271
1272 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
1273 static bool classof(const TypeExpansion *TE) {
1274 return TE->Kind == TEK_Complex;
1275 }
1276};
1277
1278struct NoExpansion : TypeExpansion {
1279 NoExpansion() : TypeExpansion(TEK_None) {}
1280 static bool classof(const TypeExpansion *TE) { return TE->Kind == TEK_None; }
1281};
1282} // namespace
1283
1284static std::unique_ptr<TypeExpansion>
1285getTypeExpansion(QualType Ty, const ASTContext &Context) {
1286 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T: Ty)) {
1287 return std::make_unique<ConstantArrayExpansion>(args: AT->getElementType(),
1288 args: AT->getZExtSize());
1289 }
1290 if (const auto *RD = Ty->getAsRecordDecl()) {
1291 SmallVector<const CXXBaseSpecifier *, 1> Bases;
1292 SmallVector<const FieldDecl *, 1> Fields;
1293 assert(!RD->hasFlexibleArrayMember() &&
1294 "Cannot expand structure with flexible array.");
1295 if (RD->isUnion()) {
1296 // Unions can be here only in degenerative cases - all the fields are same
1297 // after flattening. Thus we have to use the "largest" field.
1298 const FieldDecl *LargestFD = nullptr;
1299 CharUnits UnionSize = CharUnits::Zero();
1300
1301 for (const auto *FD : RD->fields()) {
1302 if (FD->isZeroLengthBitField())
1303 continue;
1304 assert(!FD->isBitField() &&
1305 "Cannot expand structure with bit-field members.");
1306 CharUnits FieldSize = Context.getTypeSizeInChars(T: FD->getType());
1307 if (UnionSize < FieldSize) {
1308 UnionSize = FieldSize;
1309 LargestFD = FD;
1310 }
1311 }
1312 if (LargestFD)
1313 Fields.push_back(Elt: LargestFD);
1314 } else {
1315 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1316 assert(!CXXRD->isDynamicClass() &&
1317 "cannot expand vtable pointers in dynamic classes");
1318 llvm::append_range(C&: Bases, R: llvm::make_pointer_range(Range: CXXRD->bases()));
1319 }
1320
1321 for (const auto *FD : RD->fields()) {
1322 if (FD->isZeroLengthBitField())
1323 continue;
1324 assert(!FD->isBitField() &&
1325 "Cannot expand structure with bit-field members.");
1326 Fields.push_back(Elt: FD);
1327 }
1328 }
1329 return std::make_unique<RecordExpansion>(args: std::move(Bases),
1330 args: std::move(Fields));
1331 }
1332 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1333 return std::make_unique<ComplexExpansion>(args: CT->getElementType());
1334 }
1335 return std::make_unique<NoExpansion>();
1336}
1337
1338static int getExpansionSize(QualType Ty, const ASTContext &Context) {
1339 auto Exp = getTypeExpansion(Ty, Context);
1340 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Val: Exp.get())) {
1341 return CAExp->NumElts * getExpansionSize(Ty: CAExp->EltTy, Context);
1342 }
1343 if (auto RExp = dyn_cast<RecordExpansion>(Val: Exp.get())) {
1344 int Res = 0;
1345 for (auto BS : RExp->Bases)
1346 Res += getExpansionSize(Ty: BS->getType(), Context);
1347 for (auto FD : RExp->Fields)
1348 Res += getExpansionSize(Ty: FD->getType(), Context);
1349 return Res;
1350 }
1351 if (isa<ComplexExpansion>(Val: Exp.get()))
1352 return 2;
1353 assert(isa<NoExpansion>(Exp.get()));
1354 return 1;
1355}
1356
1357void CodeGenTypes::getExpandedTypes(
1358 QualType Ty, SmallVectorImpl<llvm::Type *>::iterator &TI) {
1359 auto Exp = getTypeExpansion(Ty, Context);
1360 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Val: Exp.get())) {
1361 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
1362 getExpandedTypes(Ty: CAExp->EltTy, TI);
1363 }
1364 } else if (auto RExp = dyn_cast<RecordExpansion>(Val: Exp.get())) {
1365 for (auto BS : RExp->Bases)
1366 getExpandedTypes(Ty: BS->getType(), TI);
1367 for (auto FD : RExp->Fields)
1368 getExpandedTypes(Ty: FD->getType(), TI);
1369 } else if (auto CExp = dyn_cast<ComplexExpansion>(Val: Exp.get())) {
1370 llvm::Type *EltTy = ConvertType(T: CExp->EltTy);
1371 *TI++ = EltTy;
1372 *TI++ = EltTy;
1373 } else {
1374 assert(isa<NoExpansion>(Exp.get()));
1375 *TI++ = ConvertType(T: Ty);
1376 }
1377}
1378
1379static void forConstantArrayExpansion(CodeGenFunction &CGF,
1380 ConstantArrayExpansion *CAE,
1381 Address BaseAddr,
1382 llvm::function_ref<void(Address)> Fn) {
1383 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1384 Address EltAddr = CGF.Builder.CreateConstGEP2_32(Addr: BaseAddr, Idx0: 0, Idx1: i);
1385 Fn(EltAddr);
1386 }
1387}
1388
1389void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1390 llvm::Function::arg_iterator &AI) {
1391 assert(LV.isSimple() &&
1392 "Unexpected non-simple lvalue during struct expansion.");
1393
1394 auto Exp = getTypeExpansion(Ty, Context: getContext());
1395 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Val: Exp.get())) {
1396 forConstantArrayExpansion(
1397 CGF&: *this, CAE: CAExp, BaseAddr: LV.getAddress(), Fn: [&](Address EltAddr) {
1398 LValue LV = MakeAddrLValue(Addr: EltAddr, T: CAExp->EltTy);
1399 ExpandTypeFromArgs(Ty: CAExp->EltTy, LV, AI);
1400 });
1401 } else if (auto RExp = dyn_cast<RecordExpansion>(Val: Exp.get())) {
1402 Address This = LV.getAddress();
1403 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1404 // Perform a single step derived-to-base conversion.
1405 Address Base =
1406 GetAddressOfBaseClass(Value: This, Derived: Ty->getAsCXXRecordDecl(), PathBegin: &BS, PathEnd: &BS + 1,
1407 /*NullCheckValue=*/false, Loc: SourceLocation());
1408 LValue SubLV = MakeAddrLValue(Addr: Base, T: BS->getType());
1409
1410 // Recurse onto bases.
1411 ExpandTypeFromArgs(Ty: BS->getType(), LV: SubLV, AI);
1412 }
1413 for (auto FD : RExp->Fields) {
1414 // FIXME: What are the right qualifiers here?
1415 LValue SubLV = EmitLValueForFieldInitialization(Base: LV, Field: FD);
1416 ExpandTypeFromArgs(Ty: FD->getType(), LV: SubLV, AI);
1417 }
1418 } else if (isa<ComplexExpansion>(Val: Exp.get())) {
1419 auto realValue = &*AI++;
1420 auto imagValue = &*AI++;
1421 EmitStoreOfComplex(V: ComplexPairTy(realValue, imagValue), dest: LV, /*init*/ isInit: true);
1422 } else {
1423 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1424 // primitive store.
1425 assert(isa<NoExpansion>(Exp.get()));
1426 llvm::Value *Arg = &*AI++;
1427 if (LV.isBitField()) {
1428 EmitStoreThroughLValue(Src: RValue::get(V: Arg), Dst: LV);
1429 } else {
1430 // TODO: currently there are some places are inconsistent in what LLVM
1431 // pointer type they use (see D118744). Once clang uses opaque pointers
1432 // all LLVM pointer types will be the same and we can remove this check.
1433 if (Arg->getType()->isPointerTy()) {
1434 Address Addr = LV.getAddress();
1435 Arg = Builder.CreateBitCast(V: Arg, DestTy: Addr.getElementType());
1436 }
1437 EmitStoreOfScalar(value: Arg, lvalue: LV);
1438 }
1439 }
1440}
1441
1442void CodeGenFunction::ExpandTypeToArgs(
1443 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1444 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1445 auto Exp = getTypeExpansion(Ty, Context: getContext());
1446 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Val: Exp.get())) {
1447 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1448 : Arg.getKnownRValue().getAggregateAddress();
1449 forConstantArrayExpansion(CGF&: *this, CAE: CAExp, BaseAddr: Addr, Fn: [&](Address EltAddr) {
1450 CallArg EltArg =
1451 CallArg(convertTempToRValue(addr: EltAddr, type: CAExp->EltTy, Loc: SourceLocation()),
1452 CAExp->EltTy);
1453 ExpandTypeToArgs(Ty: CAExp->EltTy, Arg: EltArg, IRFuncTy, IRCallArgs,
1454 IRCallArgPos);
1455 });
1456 } else if (auto RExp = dyn_cast<RecordExpansion>(Val: Exp.get())) {
1457 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
1458 : Arg.getKnownRValue().getAggregateAddress();
1459 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1460 // Perform a single step derived-to-base conversion.
1461 Address Base =
1462 GetAddressOfBaseClass(Value: This, Derived: Ty->getAsCXXRecordDecl(), PathBegin: &BS, PathEnd: &BS + 1,
1463 /*NullCheckValue=*/false, Loc: SourceLocation());
1464 CallArg BaseArg = CallArg(RValue::getAggregate(addr: Base), BS->getType());
1465
1466 // Recurse onto bases.
1467 ExpandTypeToArgs(Ty: BS->getType(), Arg: BaseArg, IRFuncTy, IRCallArgs,
1468 IRCallArgPos);
1469 }
1470
1471 LValue LV = MakeAddrLValue(Addr: This, T: Ty);
1472 for (auto FD : RExp->Fields) {
1473 CallArg FldArg =
1474 CallArg(EmitRValueForField(LV, FD, Loc: SourceLocation()), FD->getType());
1475 ExpandTypeToArgs(Ty: FD->getType(), Arg: FldArg, IRFuncTy, IRCallArgs,
1476 IRCallArgPos);
1477 }
1478 } else if (isa<ComplexExpansion>(Val: Exp.get())) {
1479 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1480 IRCallArgs[IRCallArgPos++] = CV.first;
1481 IRCallArgs[IRCallArgPos++] = CV.second;
1482 } else {
1483 assert(isa<NoExpansion>(Exp.get()));
1484 auto RV = Arg.getKnownRValue();
1485 assert(RV.isScalar() &&
1486 "Unexpected non-scalar rvalue during struct expansion.");
1487
1488 // Insert a bitcast as needed.
1489 llvm::Value *V = RV.getScalarVal();
1490 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1491 V->getType() != IRFuncTy->getParamType(i: IRCallArgPos))
1492 V = Builder.CreateBitCast(V, DestTy: IRFuncTy->getParamType(i: IRCallArgPos));
1493
1494 IRCallArgs[IRCallArgPos++] = V;
1495 }
1496}
1497
1498/// Create a temporary allocation for the purposes of coercion.
1499static RawAddress CreateTempAllocaForCoercion(CodeGenFunction &CGF,
1500 llvm::Type *Ty,
1501 CharUnits MinAlign,
1502 const Twine &Name = "tmp") {
1503 // Don't use an alignment that's worse than what LLVM would prefer.
1504 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(Ty);
1505 CharUnits Align = std::max(a: MinAlign, b: CharUnits::fromQuantity(Quantity: PrefAlign));
1506
1507 return CGF.CreateTempAlloca(Ty, align: Align, Name: Name + ".coerce");
1508}
1509
1510/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1511/// accessing some number of bytes out of it, try to gep into the struct to get
1512/// at its inner goodness. Dive as deep as possible without entering an element
1513/// with an in-memory size smaller than DstSize.
1514static Address EnterStructPointerForCoercedAccess(Address SrcPtr,
1515 llvm::StructType *SrcSTy,
1516 uint64_t DstSize,
1517 CodeGenFunction &CGF) {
1518 // We can't dive into a zero-element struct.
1519 if (SrcSTy->getNumElements() == 0)
1520 return SrcPtr;
1521
1522 llvm::Type *FirstElt = SrcSTy->getElementType(N: 0);
1523
1524 // If the first elt is at least as large as what we're looking for, or if the
1525 // first element is the same size as the whole struct, we can enter it. The
1526 // comparison must be made on the store size and not the alloca size. Using
1527 // the alloca size may overstate the size of the load.
1528 uint64_t FirstEltSize = CGF.CGM.getDataLayout().getTypeStoreSize(Ty: FirstElt);
1529 if (FirstEltSize < DstSize &&
1530 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(Ty: SrcSTy))
1531 return SrcPtr;
1532
1533 // GEP into the first element.
1534 SrcPtr = CGF.Builder.CreateStructGEP(Addr: SrcPtr, Index: 0, Name: "coerce.dive");
1535
1536 // If the first element is a struct, recurse.
1537 llvm::Type *SrcTy = SrcPtr.getElementType();
1538 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(Val: SrcTy))
1539 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1540
1541 return SrcPtr;
1542}
1543
1544/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1545/// are either integers or pointers. This does a truncation of the value if it
1546/// is too large or a zero extension if it is too small.
1547///
1548/// This behaves as if the value were coerced through memory, so on big-endian
1549/// targets the high bits are preserved in a truncation, while little-endian
1550/// targets preserve the low bits.
1551static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, llvm::Type *Ty,
1552 CodeGenFunction &CGF) {
1553 if (Val->getType() == Ty)
1554 return Val;
1555
1556 if (isa<llvm::PointerType>(Val: Val->getType())) {
1557 // If this is Pointer->Pointer avoid conversion to and from int.
1558 if (isa<llvm::PointerType>(Val: Ty))
1559 return CGF.Builder.CreateBitCast(V: Val, DestTy: Ty, Name: "coerce.val");
1560
1561 // Convert the pointer to an integer so we can play with its width.
1562 Val = CGF.Builder.CreatePtrToInt(V: Val, DestTy: CGF.IntPtrTy, Name: "coerce.val.pi");
1563 }
1564
1565 llvm::Type *DestIntTy = Ty;
1566 if (isa<llvm::PointerType>(Val: DestIntTy))
1567 DestIntTy = CGF.IntPtrTy;
1568
1569 if (Val->getType() != DestIntTy) {
1570 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1571 if (DL.isBigEndian()) {
1572 // Preserve the high bits on big-endian targets.
1573 // That is what memory coercion does.
1574 uint64_t SrcSize = DL.getTypeSizeInBits(Ty: Val->getType());
1575 uint64_t DstSize = DL.getTypeSizeInBits(Ty: DestIntTy);
1576
1577 if (SrcSize > DstSize) {
1578 Val = CGF.Builder.CreateLShr(LHS: Val, RHS: SrcSize - DstSize, Name: "coerce.highbits");
1579 Val = CGF.Builder.CreateTrunc(V: Val, DestTy: DestIntTy, Name: "coerce.val.ii");
1580 } else {
1581 Val = CGF.Builder.CreateZExt(V: Val, DestTy: DestIntTy, Name: "coerce.val.ii");
1582 Val = CGF.Builder.CreateShl(LHS: Val, RHS: DstSize - SrcSize, Name: "coerce.highbits");
1583 }
1584 } else {
1585 // Little-endian targets preserve the low bits. No shifts required.
1586 Val = CGF.Builder.CreateIntCast(V: Val, DestTy: DestIntTy, isSigned: false, Name: "coerce.val.ii");
1587 }
1588 }
1589
1590 if (isa<llvm::PointerType>(Val: Ty))
1591 Val = CGF.Builder.CreateIntToPtr(V: Val, DestTy: Ty, Name: "coerce.val.ip");
1592 return Val;
1593}
1594
1595static llvm::Value *CreatePFPCoercedLoad(Address Src, QualType SrcFETy,
1596 llvm::Type *Ty, CodeGenFunction &CGF) {
1597 std::vector<PFPField> PFPFields = CGF.getContext().findPFPFields(Ty: SrcFETy);
1598 if (PFPFields.empty())
1599 return nullptr;
1600
1601 auto LoadCoercedField = [&](CharUnits Offset,
1602 llvm::Type *FieldType) -> llvm::Value * {
1603 // Check whether the field at Offset is a PFP field. This function is called
1604 // in ascending order of offset, and PFPFields is sorted by offset. This
1605 // means that we only need to check the first element (and remove it from
1606 // PFPFields if matching).
1607 if (!PFPFields.empty() && PFPFields[0].Offset == Offset) {
1608 auto FieldAddr = CGF.EmitAddressOfPFPField(RecordPtr: Src, Field: PFPFields[0]);
1609 llvm::Value *FieldVal = CGF.Builder.CreateLoad(Addr: FieldAddr);
1610 if (isa<llvm::IntegerType>(Val: FieldType))
1611 FieldVal = CGF.Builder.CreatePtrToInt(V: FieldVal, DestTy: FieldType);
1612 PFPFields.erase(position: PFPFields.begin());
1613 return FieldVal;
1614 }
1615 auto FieldAddr =
1616 CGF.Builder
1617 .CreateConstInBoundsByteGEP(Addr: Src.withElementType(ElemTy: CGF.Int8Ty), Offset)
1618 .withElementType(ElemTy: FieldType);
1619 return CGF.Builder.CreateLoad(Addr: FieldAddr);
1620 };
1621
1622 // The types handled by this function are the only ones that may be generated
1623 // by AArch64ABIInfo::classify{Argument,Return}Type for struct types with
1624 // pointers. PFP is only supported on AArch64.
1625 if (isa<llvm::IntegerType>(Val: Ty) || isa<llvm::PointerType>(Val: Ty)) {
1626 auto Addr = CGF.EmitAddressOfPFPField(RecordPtr: Src, Field: PFPFields[0]);
1627 llvm::Value *Val = CGF.Builder.CreateLoad(Addr);
1628 if (isa<llvm::IntegerType>(Val: Ty))
1629 Val = CGF.Builder.CreatePtrToInt(V: Val, DestTy: Ty);
1630 return Val;
1631 }
1632 auto *AT = cast<llvm::ArrayType>(Val: Ty);
1633 auto *ET = AT->getElementType();
1634 CharUnits WordSize = CGF.getContext().toCharUnitsFromBits(
1635 BitSize: CGF.CGM.getDataLayout().getTypeSizeInBits(Ty: ET));
1636 CharUnits Offset = CharUnits::Zero();
1637 llvm::Value *Val = llvm::PoisonValue::get(T: AT);
1638 for (unsigned Idx = 0; Idx != AT->getNumElements(); ++Idx, Offset += WordSize)
1639 Val = CGF.Builder.CreateInsertValue(Agg: Val, Val: LoadCoercedField(Offset, ET), Idxs: Idx);
1640 return Val;
1641}
1642
1643/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1644/// a pointer to an object of type \arg Ty, known to be aligned to
1645/// \arg SrcAlign bytes.
1646///
1647/// This safely handles the case when the src type is smaller than the
1648/// destination type; in this situation the values of bits which not
1649/// present in the src are undefined.
1650static llvm::Value *CreateCoercedLoad(Address Src, QualType SrcFETy,
1651 llvm::Type *Ty, CodeGenFunction &CGF) {
1652 llvm::Type *SrcTy = Src.getElementType();
1653
1654 // If SrcTy and Ty are the same, just do a load.
1655 if (SrcTy == Ty)
1656 return CGF.Builder.CreateLoad(Addr: Src);
1657
1658 if (llvm::Value *V = CreatePFPCoercedLoad(Src, SrcFETy, Ty, CGF))
1659 return V;
1660
1661 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1662
1663 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(Val: SrcTy)) {
1664 Src = EnterStructPointerForCoercedAccess(SrcPtr: Src, SrcSTy,
1665 DstSize: DstSize.getFixedValue(), CGF);
1666 SrcTy = Src.getElementType();
1667 }
1668
1669 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty: SrcTy);
1670
1671 // If the source and destination are integer or pointer types, just do an
1672 // extension or truncation to the desired type.
1673 if ((isa<llvm::IntegerType>(Val: Ty) || isa<llvm::PointerType>(Val: Ty)) &&
1674 (isa<llvm::IntegerType>(Val: SrcTy) || isa<llvm::PointerType>(Val: SrcTy))) {
1675 llvm::Value *Load = CGF.Builder.CreateLoad(Addr: Src);
1676 return CoerceIntOrPtrToIntOrPtr(Val: Load, Ty, CGF);
1677 }
1678
1679 // If load is legal, just bitcast the src pointer.
1680 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1681 SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1682 // Generally SrcSize is never greater than DstSize, since this means we are
1683 // losing bits. However, this can happen in cases where the structure has
1684 // additional padding, for example due to a user specified alignment.
1685 //
1686 // FIXME: Assert that we aren't truncating non-padding bits when have access
1687 // to that information.
1688 Src = Src.withElementType(ElemTy: Ty);
1689 return CGF.Builder.CreateLoad(Addr: Src);
1690 }
1691
1692 // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1693 // the types match, use the llvm.vector.insert intrinsic to perform the
1694 // conversion.
1695 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Val: Ty)) {
1696 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) {
1697 // If we are casting a fixed i8 vector to a scalable i1 predicate
1698 // vector, use a vector insert and bitcast the result.
1699 if (ScalableDstTy->getElementType()->isIntegerTy(BitWidth: 1) &&
1700 FixedSrcTy->getElementType()->isIntegerTy(BitWidth: 8)) {
1701 ScalableDstTy = llvm::ScalableVectorType::get(
1702 ElementType: FixedSrcTy->getElementType(),
1703 MinNumElts: llvm::divideCeil(
1704 Numerator: ScalableDstTy->getElementCount().getKnownMinValue(), Denominator: 8));
1705 }
1706 if (ScalableDstTy->getElementType() == FixedSrcTy->getElementType()) {
1707 auto *Load = CGF.Builder.CreateLoad(Addr: Src);
1708 auto *PoisonVec = llvm::PoisonValue::get(T: ScalableDstTy);
1709 llvm::Value *Result = CGF.Builder.CreateInsertVector(
1710 DstType: ScalableDstTy, SrcVec: PoisonVec, SubVec: Load, Idx: uint64_t(0), Name: "cast.scalable");
1711 ScalableDstTy = cast<llvm::ScalableVectorType>(
1712 Val: llvm::VectorType::getWithSizeAndScalar(SizeTy: ScalableDstTy, EltTy: Ty));
1713 if (Result->getType() != ScalableDstTy)
1714 Result = CGF.Builder.CreateBitCast(V: Result, DestTy: ScalableDstTy);
1715 if (Result->getType() != Ty)
1716 Result = CGF.Builder.CreateExtractVector(DstType: Ty, SrcVec: Result, Idx: uint64_t(0));
1717 return Result;
1718 }
1719 }
1720 }
1721
1722 // Otherwise do coercion through memory. This is stupid, but simple.
1723 RawAddress Tmp =
1724 CreateTempAllocaForCoercion(CGF, Ty, MinAlign: Src.getAlignment(), Name: Src.getName());
1725 CGF.Builder.CreateMemCpy(
1726 Dst: Tmp.getPointer(), DstAlign: Tmp.getAlignment().getAsAlign(),
1727 Src: Src.emitRawPointer(CGF), SrcAlign: Src.getAlignment().getAsAlign(),
1728 Size: llvm::ConstantInt::get(Ty: CGF.IntPtrTy, V: SrcSize.getKnownMinValue()));
1729 return CGF.Builder.CreateLoad(Addr: Tmp);
1730}
1731
1732static bool CreatePFPCoercedStore(llvm::Value *Src, QualType SrcFETy,
1733 Address Dst, CodeGenFunction &CGF) {
1734 std::vector<PFPField> PFPFields = CGF.getContext().findPFPFields(Ty: SrcFETy);
1735 if (PFPFields.empty())
1736 return false;
1737
1738 llvm::Type *SrcTy = Src->getType();
1739 auto StoreCoercedField = [&](CharUnits Offset, llvm::Value *FieldVal) {
1740 if (!PFPFields.empty() && PFPFields[0].Offset == Offset) {
1741 auto FieldAddr = CGF.EmitAddressOfPFPField(RecordPtr: Dst, Field: PFPFields[0]);
1742 if (isa<llvm::IntegerType>(Val: FieldVal->getType()))
1743 FieldVal = CGF.Builder.CreateIntToPtr(V: FieldVal, DestTy: CGF.VoidPtrTy);
1744 CGF.Builder.CreateStore(Val: FieldVal, Addr: FieldAddr);
1745 PFPFields.erase(position: PFPFields.begin());
1746 } else {
1747 auto FieldAddr = CGF.Builder
1748 .CreateConstInBoundsByteGEP(
1749 Addr: Dst.withElementType(ElemTy: CGF.Int8Ty), Offset)
1750 .withElementType(ElemTy: FieldVal->getType());
1751 CGF.Builder.CreateStore(Val: FieldVal, Addr: FieldAddr);
1752 }
1753 };
1754
1755 // The types handled by this function are the only ones that may be generated
1756 // by AArch64ABIInfo::classify{Argument,Return}Type for struct types with
1757 // pointers. PFP is only supported on AArch64.
1758 if (isa<llvm::IntegerType>(Val: SrcTy) || isa<llvm::PointerType>(Val: SrcTy)) {
1759 if (isa<llvm::IntegerType>(Val: SrcTy))
1760 Src = CGF.Builder.CreateIntToPtr(V: Src, DestTy: CGF.VoidPtrTy);
1761 auto Addr = CGF.EmitAddressOfPFPField(RecordPtr: Dst, Field: PFPFields[0]);
1762 CGF.Builder.CreateStore(Val: Src, Addr);
1763 } else {
1764 auto *AT = cast<llvm::ArrayType>(Val: SrcTy);
1765 auto *ET = AT->getElementType();
1766 CharUnits WordSize = CGF.getContext().toCharUnitsFromBits(
1767 BitSize: CGF.CGM.getDataLayout().getTypeSizeInBits(Ty: ET));
1768 CharUnits Offset = CharUnits::Zero();
1769 for (unsigned i = 0; i != AT->getNumElements(); ++i, Offset += WordSize)
1770 StoreCoercedField(Offset, CGF.Builder.CreateExtractValue(Agg: Src, Idxs: i));
1771 }
1772 return true;
1773}
1774
1775void CodeGenFunction::CreateCoercedStore(llvm::Value *Src, QualType SrcFETy,
1776 Address Dst, llvm::TypeSize DstSize,
1777 bool DstIsVolatile) {
1778 if (!DstSize)
1779 return;
1780
1781 llvm::Type *SrcTy = Src->getType();
1782 llvm::TypeSize SrcSize = CGM.getDataLayout().getTypeAllocSize(Ty: SrcTy);
1783
1784 // GEP into structs to try to make types match.
1785 // FIXME: This isn't really that useful with opaque types, but it impacts a
1786 // lot of regression tests.
1787 if (SrcTy != Dst.getElementType()) {
1788 if (llvm::StructType *DstSTy =
1789 dyn_cast<llvm::StructType>(Val: Dst.getElementType())) {
1790 assert(!SrcSize.isScalable());
1791 Dst = EnterStructPointerForCoercedAccess(SrcPtr: Dst, SrcSTy: DstSTy,
1792 DstSize: SrcSize.getFixedValue(), CGF&: *this);
1793 }
1794 }
1795
1796 if (CreatePFPCoercedStore(Src, SrcFETy, Dst, CGF&: *this))
1797 return;
1798
1799 if (SrcSize.isScalable() || SrcSize <= DstSize) {
1800 if (SrcTy->isIntegerTy() && Dst.getElementType()->isPointerTy() &&
1801 SrcSize == CGM.getDataLayout().getTypeAllocSize(Ty: Dst.getElementType())) {
1802 // If the value is supposed to be a pointer, convert it before storing it.
1803 Src = CoerceIntOrPtrToIntOrPtr(Val: Src, Ty: Dst.getElementType(), CGF&: *this);
1804 auto *I = Builder.CreateStore(Val: Src, Addr: Dst, IsVolatile: DstIsVolatile);
1805 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Src);
1806 } else if (llvm::StructType *STy =
1807 dyn_cast<llvm::StructType>(Val: Src->getType())) {
1808 // Prefer scalar stores to first-class aggregate stores.
1809 Dst = Dst.withElementType(ElemTy: SrcTy);
1810 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1811 Address EltPtr = Builder.CreateStructGEP(Addr: Dst, Index: i);
1812 llvm::Value *Elt = Builder.CreateExtractValue(Agg: Src, Idxs: i);
1813 auto *I = Builder.CreateStore(Val: Elt, Addr: EltPtr, IsVolatile: DstIsVolatile);
1814 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Elt);
1815 }
1816 } else {
1817 auto *I =
1818 Builder.CreateStore(Val: Src, Addr: Dst.withElementType(ElemTy: SrcTy), IsVolatile: DstIsVolatile);
1819 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Src);
1820 }
1821 } else if (SrcTy->isIntegerTy()) {
1822 // If the source is a simple integer, coerce it directly.
1823 llvm::Type *DstIntTy = Builder.getIntNTy(N: DstSize.getFixedValue() * 8);
1824 Src = CoerceIntOrPtrToIntOrPtr(Val: Src, Ty: DstIntTy, CGF&: *this);
1825 auto *I =
1826 Builder.CreateStore(Val: Src, Addr: Dst.withElementType(ElemTy: DstIntTy), IsVolatile: DstIsVolatile);
1827 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Src);
1828 } else {
1829 // Otherwise do coercion through memory. This is stupid, but
1830 // simple.
1831
1832 // Generally SrcSize is never greater than DstSize, since this means we are
1833 // losing bits. However, this can happen in cases where the structure has
1834 // additional padding, for example due to a user specified alignment.
1835 //
1836 // FIXME: Assert that we aren't truncating non-padding bits when have access
1837 // to that information.
1838 RawAddress Tmp =
1839 CreateTempAllocaForCoercion(CGF&: *this, Ty: SrcTy, MinAlign: Dst.getAlignment());
1840 Builder.CreateStore(Val: Src, Addr: Tmp);
1841 auto *I = Builder.CreateMemCpy(
1842 Dst: Dst.emitRawPointer(CGF&: *this), DstAlign: Dst.getAlignment().getAsAlign(),
1843 Src: Tmp.getPointer(), SrcAlign: Tmp.getAlignment().getAsAlign(),
1844 Size: Builder.CreateTypeSize(Ty: IntPtrTy, Size: DstSize));
1845 addInstToCurrentSourceAtom(KeyInstruction: I, Backup: Src);
1846 }
1847}
1848
1849static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1850 const ABIArgInfo &info) {
1851 if (unsigned offset = info.getDirectOffset()) {
1852 addr = addr.withElementType(ElemTy: CGF.Int8Ty);
1853 addr = CGF.Builder.CreateConstInBoundsByteGEP(
1854 Addr: addr, Offset: CharUnits::fromQuantity(Quantity: offset));
1855 addr = addr.withElementType(ElemTy: info.getCoerceToType());
1856 }
1857 return addr;
1858}
1859
1860static std::pair<llvm::Value *, bool>
1861CoerceScalableToFixed(CodeGenFunction &CGF, llvm::FixedVectorType *ToTy,
1862 llvm::ScalableVectorType *FromTy, llvm::Value *V,
1863 StringRef Name = "") {
1864 // If we are casting a scalable i1 predicate vector to a fixed i8
1865 // vector, first bitcast the source.
1866 if (FromTy->getElementType()->isIntegerTy(BitWidth: 1) &&
1867 ToTy->getElementType() == CGF.Builder.getInt8Ty()) {
1868 if (!FromTy->getElementCount().isKnownMultipleOf(RHS: 8)) {
1869 FromTy = llvm::ScalableVectorType::get(
1870 ElementType: FromTy->getElementType(),
1871 MinNumElts: llvm::alignTo<8>(Value: FromTy->getElementCount().getKnownMinValue()));
1872 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: FromTy);
1873 V = CGF.Builder.CreateInsertVector(DstType: FromTy, SrcVec: ZeroVec, SubVec: V, Idx: uint64_t(0));
1874 }
1875 FromTy = llvm::ScalableVectorType::get(
1876 ElementType: ToTy->getElementType(),
1877 MinNumElts: FromTy->getElementCount().getKnownMinValue() / 8);
1878 V = CGF.Builder.CreateBitCast(V, DestTy: FromTy);
1879 }
1880 if (FromTy->getElementType() == ToTy->getElementType()) {
1881 V->setName(Name + ".coerce");
1882 V = CGF.Builder.CreateExtractVector(DstType: ToTy, SrcVec: V, Idx: uint64_t(0), Name: "cast.fixed");
1883 return {V, true};
1884 }
1885 return {V, false};
1886}
1887
1888namespace {
1889
1890/// Encapsulates information about the way function arguments from
1891/// CGFunctionInfo should be passed to actual LLVM IR function.
1892class ClangToLLVMArgMapping {
1893 static const unsigned InvalidIndex = ~0U;
1894 unsigned InallocaArgNo;
1895 unsigned SRetArgNo;
1896 unsigned TotalIRArgs;
1897
1898 /// Arguments of LLVM IR function corresponding to single Clang argument.
1899 struct IRArgs {
1900 unsigned PaddingArgIndex;
1901 // Argument is expanded to IR arguments at positions
1902 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1903 unsigned FirstArgIndex;
1904 unsigned NumberOfArgs;
1905
1906 IRArgs()
1907 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1908 NumberOfArgs(0) {}
1909 };
1910
1911 SmallVector<IRArgs, 8> ArgInfo;
1912
1913public:
1914 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1915 bool OnlyRequiredArgs = false)
1916 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1917 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1918 construct(Context, FI, OnlyRequiredArgs);
1919 }
1920
1921 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1922 unsigned getInallocaArgNo() const {
1923 assert(hasInallocaArg());
1924 return InallocaArgNo;
1925 }
1926
1927 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1928 unsigned getSRetArgNo() const {
1929 assert(hasSRetArg());
1930 return SRetArgNo;
1931 }
1932
1933 unsigned totalIRArgs() const { return TotalIRArgs; }
1934
1935 bool hasPaddingArg(unsigned ArgNo) const {
1936 assert(ArgNo < ArgInfo.size());
1937 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1938 }
1939 unsigned getPaddingArgNo(unsigned ArgNo) const {
1940 assert(hasPaddingArg(ArgNo));
1941 return ArgInfo[ArgNo].PaddingArgIndex;
1942 }
1943
1944 /// Returns index of first IR argument corresponding to ArgNo, and their
1945 /// quantity.
1946 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1947 assert(ArgNo < ArgInfo.size());
1948 return std::make_pair(x: ArgInfo[ArgNo].FirstArgIndex,
1949 y: ArgInfo[ArgNo].NumberOfArgs);
1950 }
1951
1952private:
1953 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1954 bool OnlyRequiredArgs);
1955};
1956
1957void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1958 const CGFunctionInfo &FI,
1959 bool OnlyRequiredArgs) {
1960 unsigned IRArgNo = 0;
1961 bool SwapThisWithSRet = false;
1962 const ABIArgInfo &RetAI = FI.getReturnInfo();
1963
1964 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1965 SwapThisWithSRet = RetAI.isSRetAfterThis();
1966 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1967 }
1968
1969 unsigned ArgNo = 0;
1970 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1971 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1972 ++I, ++ArgNo) {
1973 assert(I != FI.arg_end());
1974 QualType ArgType = I->type;
1975 const ABIArgInfo &AI = I->info;
1976 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1977 auto &IRArgs = ArgInfo[ArgNo];
1978
1979 if (AI.getPaddingType())
1980 IRArgs.PaddingArgIndex = IRArgNo++;
1981
1982 switch (AI.getKind()) {
1983 case ABIArgInfo::TargetSpecific:
1984 case ABIArgInfo::Extend:
1985 case ABIArgInfo::Direct: {
1986 // FIXME: handle sseregparm someday...
1987 llvm::StructType *STy = dyn_cast<llvm::StructType>(Val: AI.getCoerceToType());
1988 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1989 IRArgs.NumberOfArgs = STy->getNumElements();
1990 } else {
1991 IRArgs.NumberOfArgs = 1;
1992 }
1993 break;
1994 }
1995 case ABIArgInfo::Indirect:
1996 case ABIArgInfo::IndirectAliased:
1997 IRArgs.NumberOfArgs = 1;
1998 break;
1999 case ABIArgInfo::Ignore:
2000 case ABIArgInfo::InAlloca:
2001 // ignore and inalloca doesn't have matching LLVM parameters.
2002 IRArgs.NumberOfArgs = 0;
2003 break;
2004 case ABIArgInfo::CoerceAndExpand:
2005 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
2006 break;
2007 case ABIArgInfo::Expand:
2008 IRArgs.NumberOfArgs = getExpansionSize(Ty: ArgType, Context);
2009 break;
2010 }
2011
2012 if (IRArgs.NumberOfArgs > 0) {
2013 IRArgs.FirstArgIndex = IRArgNo;
2014 IRArgNo += IRArgs.NumberOfArgs;
2015 }
2016
2017 // Skip over the sret parameter when it comes second. We already handled it
2018 // above.
2019 if (IRArgNo == 1 && SwapThisWithSRet)
2020 IRArgNo++;
2021 }
2022 assert(ArgNo == ArgInfo.size());
2023
2024 if (FI.usesInAlloca())
2025 InallocaArgNo = IRArgNo++;
2026
2027 TotalIRArgs = IRArgNo;
2028}
2029} // namespace
2030
2031/***/
2032
2033bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
2034 const auto &RI = FI.getReturnInfo();
2035 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
2036}
2037
2038bool CodeGenModule::ReturnTypeHasInReg(const CGFunctionInfo &FI) {
2039 const auto &RI = FI.getReturnInfo();
2040 return RI.getInReg();
2041}
2042
2043bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
2044 return ReturnTypeUsesSRet(FI) &&
2045 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
2046}
2047
2048bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
2049 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
2050 switch (BT->getKind()) {
2051 default:
2052 return false;
2053 case BuiltinType::Float:
2054 return getTarget().useObjCFPRetForRealType(T: FloatModeKind::Float);
2055 case BuiltinType::Double:
2056 return getTarget().useObjCFPRetForRealType(T: FloatModeKind::Double);
2057 case BuiltinType::LongDouble:
2058 return getTarget().useObjCFPRetForRealType(T: FloatModeKind::LongDouble);
2059 }
2060 }
2061
2062 return false;
2063}
2064
2065bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
2066 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
2067 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
2068 if (BT->getKind() == BuiltinType::LongDouble)
2069 return getTarget().useObjCFP2RetForComplexLongDouble();
2070 }
2071 }
2072
2073 return false;
2074}
2075
2076llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
2077 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
2078 return GetFunctionType(Info: FI);
2079}
2080
2081llvm::FunctionType *CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
2082
2083 bool Inserted = FunctionsBeingProcessed.insert(Ptr: &FI).second;
2084 (void)Inserted;
2085 assert(Inserted && "Recursively being processed?");
2086
2087 llvm::Type *resultType = nullptr;
2088 const ABIArgInfo &retAI = FI.getReturnInfo();
2089 switch (retAI.getKind()) {
2090 case ABIArgInfo::Expand:
2091 case ABIArgInfo::IndirectAliased:
2092 llvm_unreachable("Invalid ABI kind for return argument");
2093
2094 case ABIArgInfo::TargetSpecific:
2095 case ABIArgInfo::Extend:
2096 case ABIArgInfo::Direct:
2097 resultType = retAI.getCoerceToType();
2098 break;
2099
2100 case ABIArgInfo::InAlloca:
2101 if (retAI.getInAllocaSRet()) {
2102 // sret things on win32 aren't void, they return the sret pointer.
2103 QualType ret = FI.getReturnType();
2104 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(T: ret);
2105 resultType = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: addressSpace);
2106 } else {
2107 resultType = llvm::Type::getVoidTy(C&: getLLVMContext());
2108 }
2109 break;
2110
2111 case ABIArgInfo::Indirect:
2112 case ABIArgInfo::Ignore:
2113 resultType = llvm::Type::getVoidTy(C&: getLLVMContext());
2114 break;
2115
2116 case ABIArgInfo::CoerceAndExpand:
2117 resultType = retAI.getUnpaddedCoerceAndExpandType();
2118 break;
2119 }
2120
2121 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
2122 SmallVector<llvm::Type *, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
2123
2124 // Add type for sret argument.
2125 if (IRFunctionArgs.hasSRetArg()) {
2126 ArgTypes[IRFunctionArgs.getSRetArgNo()] = llvm::PointerType::get(
2127 C&: getLLVMContext(), AddressSpace: FI.getReturnInfo().getIndirectAddrSpace());
2128 }
2129
2130 // Add type for inalloca argument.
2131 if (IRFunctionArgs.hasInallocaArg())
2132 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
2133 llvm::PointerType::getUnqual(C&: getLLVMContext());
2134
2135 // Add in all of the required arguments.
2136 unsigned ArgNo = 0;
2137 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
2138 ie = it + FI.getNumRequiredArgs();
2139 for (; it != ie; ++it, ++ArgNo) {
2140 const ABIArgInfo &ArgInfo = it->info;
2141
2142 // Insert a padding type to ensure proper alignment.
2143 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2144 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2145 ArgInfo.getPaddingType();
2146
2147 unsigned FirstIRArg, NumIRArgs;
2148 std::tie(args&: FirstIRArg, args&: NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2149
2150 switch (ArgInfo.getKind()) {
2151 case ABIArgInfo::Ignore:
2152 case ABIArgInfo::InAlloca:
2153 assert(NumIRArgs == 0);
2154 break;
2155
2156 case ABIArgInfo::Indirect:
2157 assert(NumIRArgs == 1);
2158 // indirect arguments are always on the stack, which is alloca addr space.
2159 ArgTypes[FirstIRArg] = llvm::PointerType::get(
2160 C&: getLLVMContext(), AddressSpace: CGM.getDataLayout().getAllocaAddrSpace());
2161 break;
2162 case ABIArgInfo::IndirectAliased:
2163 assert(NumIRArgs == 1);
2164 ArgTypes[FirstIRArg] = llvm::PointerType::get(
2165 C&: getLLVMContext(), AddressSpace: ArgInfo.getIndirectAddrSpace());
2166 break;
2167 case ABIArgInfo::TargetSpecific:
2168 case ABIArgInfo::Extend:
2169 case ABIArgInfo::Direct: {
2170 // Fast-isel and the optimizer generally like scalar values better than
2171 // FCAs, so we flatten them if this is safe to do for this argument.
2172 llvm::Type *argType = ArgInfo.getCoerceToType();
2173 llvm::StructType *st = dyn_cast<llvm::StructType>(Val: argType);
2174 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
2175 assert(NumIRArgs == st->getNumElements());
2176 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
2177 ArgTypes[FirstIRArg + i] = st->getElementType(N: i);
2178 } else {
2179 assert(NumIRArgs == 1);
2180 ArgTypes[FirstIRArg] = argType;
2181 }
2182 break;
2183 }
2184
2185 case ABIArgInfo::CoerceAndExpand: {
2186 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
2187 for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
2188 *ArgTypesIter++ = EltTy;
2189 }
2190 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
2191 break;
2192 }
2193
2194 case ABIArgInfo::Expand:
2195 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
2196 getExpandedTypes(Ty: it->type, TI&: ArgTypesIter);
2197 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
2198 break;
2199 }
2200 }
2201
2202 bool Erased = FunctionsBeingProcessed.erase(Ptr: &FI);
2203 (void)Erased;
2204 assert(Erased && "Not in set?");
2205
2206 return llvm::FunctionType::get(Result: resultType, Params: ArgTypes, isVarArg: FI.isVariadic());
2207}
2208
2209llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
2210 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
2211 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2212
2213 if (!isFuncTypeConvertible(FT: FPT))
2214 return llvm::StructType::get(Context&: getLLVMContext());
2215
2216 return GetFunctionType(GD);
2217}
2218
2219static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
2220 llvm::AttrBuilder &FuncAttrs,
2221 const FunctionProtoType *FPT) {
2222 if (!FPT)
2223 return;
2224
2225 if (!isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
2226 FPT->isNothrow())
2227 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2228
2229 unsigned SMEBits = FPT->getAArch64SMEAttributes();
2230 if (SMEBits & FunctionType::SME_PStateSMEnabledMask)
2231 FuncAttrs.addAttribute(A: "aarch64_pstate_sm_enabled");
2232 if (SMEBits & FunctionType::SME_PStateSMCompatibleMask)
2233 FuncAttrs.addAttribute(A: "aarch64_pstate_sm_compatible");
2234 if (SMEBits & FunctionType::SME_AgnosticZAStateMask)
2235 FuncAttrs.addAttribute(A: "aarch64_za_state_agnostic");
2236
2237 // ZA
2238 if (FunctionType::getArmZAState(AttrBits: SMEBits) == FunctionType::ARM_Preserves)
2239 FuncAttrs.addAttribute(A: "aarch64_preserves_za");
2240 if (FunctionType::getArmZAState(AttrBits: SMEBits) == FunctionType::ARM_In)
2241 FuncAttrs.addAttribute(A: "aarch64_in_za");
2242 if (FunctionType::getArmZAState(AttrBits: SMEBits) == FunctionType::ARM_Out)
2243 FuncAttrs.addAttribute(A: "aarch64_out_za");
2244 if (FunctionType::getArmZAState(AttrBits: SMEBits) == FunctionType::ARM_InOut)
2245 FuncAttrs.addAttribute(A: "aarch64_inout_za");
2246
2247 // ZT0
2248 if (FunctionType::getArmZT0State(AttrBits: SMEBits) == FunctionType::ARM_Preserves)
2249 FuncAttrs.addAttribute(A: "aarch64_preserves_zt0");
2250 if (FunctionType::getArmZT0State(AttrBits: SMEBits) == FunctionType::ARM_In)
2251 FuncAttrs.addAttribute(A: "aarch64_in_zt0");
2252 if (FunctionType::getArmZT0State(AttrBits: SMEBits) == FunctionType::ARM_Out)
2253 FuncAttrs.addAttribute(A: "aarch64_out_zt0");
2254 if (FunctionType::getArmZT0State(AttrBits: SMEBits) == FunctionType::ARM_InOut)
2255 FuncAttrs.addAttribute(A: "aarch64_inout_zt0");
2256}
2257
2258static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
2259 const Decl *Callee) {
2260 if (!Callee)
2261 return;
2262
2263 SmallVector<StringRef, 4> Attrs;
2264
2265 for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
2266 AA->getAssumption().split(A&: Attrs, Separator: ",");
2267
2268 if (!Attrs.empty())
2269 FuncAttrs.addAttribute(A: llvm::AssumptionAttrKey,
2270 V: llvm::join(Begin: Attrs.begin(), End: Attrs.end(), Separator: ","));
2271}
2272
2273bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
2274 QualType ReturnType) const {
2275 // We can't just discard the return value for a record type with a
2276 // complex destructor or a non-trivially copyable type.
2277 if (const RecordType *RT =
2278 ReturnType.getCanonicalType()->getAsCanonical<RecordType>()) {
2279 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl()))
2280 return ClassDecl->hasTrivialDestructor();
2281 }
2282 return ReturnType.isTriviallyCopyableType(Context);
2283}
2284
2285static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy,
2286 const Decl *TargetDecl) {
2287 // As-is msan can not tolerate noundef mismatch between caller and
2288 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
2289 // into C++. Such mismatches lead to confusing false reports. To avoid
2290 // expensive workaround on msan we enforce initialization event in uncommon
2291 // cases where it's allowed.
2292 if (Module.getLangOpts().Sanitize.has(K: SanitizerKind::Memory))
2293 return true;
2294 // C++ explicitly makes returning undefined values UB. C's rule only applies
2295 // to used values, so we never mark them noundef for now.
2296 if (!Module.getLangOpts().CPlusPlus)
2297 return false;
2298 if (TargetDecl) {
2299 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: TargetDecl)) {
2300 if (FDecl->isExternC())
2301 return false;
2302 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(Val: TargetDecl)) {
2303 // Function pointer.
2304 if (VDecl->isExternC())
2305 return false;
2306 }
2307 }
2308
2309 // We don't want to be too aggressive with the return checking, unless
2310 // it's explicit in the code opts or we're using an appropriate sanitizer.
2311 // Try to respect what the programmer intended.
2312 return Module.getCodeGenOpts().StrictReturn ||
2313 !Module.MayDropFunctionReturn(Context: Module.getContext(), ReturnType: RetTy) ||
2314 Module.getLangOpts().Sanitize.has(K: SanitizerKind::Return);
2315}
2316
2317/// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
2318/// requested denormal behavior, accounting for the overriding behavior of the
2319/// -f32 case.
2320static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
2321 llvm::DenormalMode FP32DenormalMode,
2322 llvm::AttrBuilder &FuncAttrs) {
2323 llvm::DenormalFPEnv FPEnv(FPDenormalMode, FP32DenormalMode);
2324 if (FPEnv != llvm::DenormalFPEnv::getDefault())
2325 FuncAttrs.addDenormalFPEnvAttr(Mode: FPEnv);
2326}
2327
2328/// Add default attributes to a function, which have merge semantics under
2329/// -mlink-builtin-bitcode and should not simply overwrite any existing
2330/// attributes in the linked library.
2331static void
2332addMergableDefaultFunctionAttributes(const CodeGenOptions &CodeGenOpts,
2333 llvm::AttrBuilder &FuncAttrs) {
2334 addDenormalModeAttrs(FPDenormalMode: CodeGenOpts.FPDenormalMode, FP32DenormalMode: CodeGenOpts.FP32DenormalMode,
2335 FuncAttrs);
2336}
2337
2338static void getTrivialDefaultFunctionAttributes(
2339 StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
2340 const LangOptions &LangOpts, bool AttrOnCallSite,
2341 llvm::AttrBuilder &FuncAttrs) {
2342 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
2343 if (!HasOptnone) {
2344 if (CodeGenOpts.OptimizeSize)
2345 FuncAttrs.addAttribute(Val: llvm::Attribute::OptimizeForSize);
2346 if (CodeGenOpts.OptimizeSize == 2)
2347 FuncAttrs.addAttribute(Val: llvm::Attribute::MinSize);
2348 }
2349
2350 if (CodeGenOpts.DisableRedZone)
2351 FuncAttrs.addAttribute(Val: llvm::Attribute::NoRedZone);
2352 if (CodeGenOpts.IndirectTlsSegRefs)
2353 FuncAttrs.addAttribute(A: "indirect-tls-seg-refs");
2354 if (CodeGenOpts.NoImplicitFloat)
2355 FuncAttrs.addAttribute(Val: llvm::Attribute::NoImplicitFloat);
2356
2357 if (AttrOnCallSite) {
2358 // Attributes that should go on the call site only.
2359 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
2360 // the -fno-builtin-foo list.
2361 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
2362 FuncAttrs.addAttribute(Val: llvm::Attribute::NoBuiltin);
2363 if (!CodeGenOpts.TrapFuncName.empty())
2364 FuncAttrs.addAttribute(A: "trap-func-name", V: CodeGenOpts.TrapFuncName);
2365 } else {
2366 switch (CodeGenOpts.getFramePointer()) {
2367 case CodeGenOptions::FramePointerKind::None:
2368 // This is the default behavior.
2369 break;
2370 case CodeGenOptions::FramePointerKind::Reserved:
2371 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
2372 case CodeGenOptions::FramePointerKind::NonLeaf:
2373 case CodeGenOptions::FramePointerKind::All:
2374 FuncAttrs.addAttribute(A: "frame-pointer",
2375 V: CodeGenOptions::getFramePointerKindName(
2376 Kind: CodeGenOpts.getFramePointer()));
2377 }
2378
2379 if (CodeGenOpts.LessPreciseFPMAD)
2380 FuncAttrs.addAttribute(A: "less-precise-fpmad", V: "true");
2381
2382 if (CodeGenOpts.NullPointerIsValid)
2383 FuncAttrs.addAttribute(Val: llvm::Attribute::NullPointerIsValid);
2384
2385 if (LangOpts.getDefaultExceptionMode() == LangOptions::FPE_Ignore)
2386 FuncAttrs.addAttribute(A: "no-trapping-math", V: "true");
2387
2388 // TODO: Are these all needed?
2389 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
2390 if (CodeGenOpts.SoftFloat)
2391 FuncAttrs.addAttribute(A: "use-soft-float", V: "true");
2392 FuncAttrs.addAttribute(A: "stack-protector-buffer-size",
2393 V: llvm::utostr(X: CodeGenOpts.SSPBufferSize));
2394 if (LangOpts.NoSignedZero)
2395 FuncAttrs.addAttribute(A: "no-signed-zeros-fp-math", V: "true");
2396
2397 // TODO: Reciprocal estimate codegen options should apply to instructions?
2398 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
2399 if (!Recips.empty())
2400 FuncAttrs.addAttribute(A: "reciprocal-estimates", V: llvm::join(R: Recips, Separator: ","));
2401
2402 if (!CodeGenOpts.PreferVectorWidth.empty() &&
2403 CodeGenOpts.PreferVectorWidth != "none")
2404 FuncAttrs.addAttribute(A: "prefer-vector-width",
2405 V: CodeGenOpts.PreferVectorWidth);
2406
2407 if (CodeGenOpts.StackRealignment)
2408 FuncAttrs.addAttribute(A: "stackrealign");
2409 if (CodeGenOpts.Backchain)
2410 FuncAttrs.addAttribute(A: "backchain");
2411 if (CodeGenOpts.EnableSegmentedStacks)
2412 FuncAttrs.addAttribute(A: "split-stack");
2413
2414 if (CodeGenOpts.SpeculativeLoadHardening)
2415 FuncAttrs.addAttribute(Val: llvm::Attribute::SpeculativeLoadHardening);
2416
2417 // Add zero-call-used-regs attribute.
2418 switch (CodeGenOpts.getZeroCallUsedRegs()) {
2419 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
2420 FuncAttrs.removeAttribute(A: "zero-call-used-regs");
2421 break;
2422 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
2423 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "used-gpr-arg");
2424 break;
2425 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
2426 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "used-gpr");
2427 break;
2428 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
2429 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "used-arg");
2430 break;
2431 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
2432 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "used");
2433 break;
2434 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
2435 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "all-gpr-arg");
2436 break;
2437 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2438 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "all-gpr");
2439 break;
2440 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2441 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "all-arg");
2442 break;
2443 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2444 FuncAttrs.addAttribute(A: "zero-call-used-regs", V: "all");
2445 break;
2446 }
2447 }
2448
2449 if (LangOpts.assumeFunctionsAreConvergent()) {
2450 // Conservatively, mark all functions and calls in CUDA and OpenCL as
2451 // convergent (meaning, they may call an intrinsically convergent op, such
2452 // as __syncthreads() / barrier(), and so can't have certain optimizations
2453 // applied around them). LLVM will remove this attribute where it safely
2454 // can.
2455 FuncAttrs.addAttribute(Val: llvm::Attribute::Convergent);
2456 }
2457
2458 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2459 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2460 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2461 LangOpts.SYCLIsDevice) {
2462 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2463 }
2464
2465 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2466 FuncAttrs.addAttribute(A: "save-reg-params");
2467
2468 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2469 StringRef Var, Value;
2470 std::tie(args&: Var, args&: Value) = Attr.split(Separator: '=');
2471 FuncAttrs.addAttribute(A: Var, V: Value);
2472 }
2473
2474 if (!AttrOnCallSite) {
2475 TargetInfo::BranchProtectionInfo BPI(LangOpts);
2476 TargetCodeGenInfo::initBranchProtectionFnAttributes(BPI, FuncAttrs);
2477 }
2478}
2479
2480/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2481/// \FuncAttr
2482/// * features from \F are always kept
2483/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2484/// from \F
2485static void
2486overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr,
2487 const llvm::Function &F,
2488 const TargetOptions &TargetOpts) {
2489 auto FFeatures = F.getFnAttribute(Kind: "target-features");
2490
2491 llvm::StringSet<> MergedNames;
2492 SmallVector<StringRef> MergedFeatures;
2493 MergedFeatures.reserve(N: TargetOpts.Features.size());
2494
2495 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2496 for (StringRef Feature : FeatureRange) {
2497 if (Feature.empty())
2498 continue;
2499 assert(Feature[0] == '+' || Feature[0] == '-');
2500 StringRef Name = Feature.drop_front(N: 1);
2501 bool Merged = !MergedNames.insert(key: Name).second;
2502 if (!Merged)
2503 MergedFeatures.push_back(Elt: Feature);
2504 }
2505 };
2506
2507 if (FFeatures.isValid())
2508 AddUnmergedFeatures(llvm::split(Str: FFeatures.getValueAsString(), Separator: ','));
2509 AddUnmergedFeatures(TargetOpts.Features);
2510
2511 if (!MergedFeatures.empty()) {
2512 llvm::sort(C&: MergedFeatures);
2513 FuncAttr.addAttribute(A: "target-features", V: llvm::join(R&: MergedFeatures, Separator: ","));
2514 }
2515}
2516
2517void CodeGen::mergeDefaultFunctionDefinitionAttributes(
2518 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2519 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2520 bool WillInternalize) {
2521
2522 llvm::AttrBuilder FuncAttrs(F.getContext());
2523 // Here we only extract the options that are relevant compared to the version
2524 // from GetCPUAndFeaturesAttributes.
2525 if (!TargetOpts.CPU.empty())
2526 FuncAttrs.addAttribute(A: "target-cpu", V: TargetOpts.CPU);
2527 if (!TargetOpts.TuneCPU.empty())
2528 FuncAttrs.addAttribute(A: "tune-cpu", V: TargetOpts.TuneCPU);
2529
2530 ::getTrivialDefaultFunctionAttributes(Name: F.getName(), HasOptnone: F.hasOptNone(),
2531 CodeGenOpts, LangOpts,
2532 /*AttrOnCallSite=*/false, FuncAttrs);
2533
2534 if (!WillInternalize && F.isInterposable()) {
2535 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2536 // setting for weak functions that won't be internalized. The user has no
2537 // real control for how builtin bitcode is linked, so we shouldn't assume
2538 // later copies will use a consistent mode.
2539 F.addFnAttrs(Attrs: FuncAttrs);
2540 return;
2541 }
2542
2543 llvm::AttributeMask AttrsToRemove;
2544
2545 llvm::DenormalFPEnv OptsFPEnv(CodeGenOpts.FPDenormalMode,
2546 CodeGenOpts.FP32DenormalMode);
2547 llvm::DenormalFPEnv MergedFPEnv =
2548 OptsFPEnv.mergeCalleeMode(Callee: F.getDenormalFPEnv());
2549
2550 if (MergedFPEnv == llvm::DenormalFPEnv::getDefault()) {
2551 AttrsToRemove.addAttribute(Val: llvm::Attribute::DenormalFPEnv);
2552 } else {
2553 // Overwrite existing attribute
2554 FuncAttrs.addDenormalFPEnvAttr(Mode: MergedFPEnv);
2555 }
2556
2557 F.removeFnAttrs(Attrs: AttrsToRemove);
2558
2559 overrideFunctionFeaturesWithTargetFeatures(FuncAttr&: FuncAttrs, F, TargetOpts);
2560
2561 F.addFnAttrs(Attrs: FuncAttrs);
2562}
2563
2564void CodeGenModule::getTrivialDefaultFunctionAttributes(
2565 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2566 llvm::AttrBuilder &FuncAttrs) {
2567 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, CodeGenOpts: getCodeGenOpts(),
2568 LangOpts: getLangOpts(), AttrOnCallSite,
2569 FuncAttrs);
2570}
2571
2572void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2573 bool HasOptnone,
2574 bool AttrOnCallSite,
2575 llvm::AttrBuilder &FuncAttrs) {
2576 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2577 FuncAttrs);
2578
2579 if (!AttrOnCallSite)
2580 TargetCodeGenInfo::initPointerAuthFnAttributes(Opts: CodeGenOpts.PointerAuth,
2581 FuncAttrs);
2582
2583 // If we're just getting the default, get the default values for mergeable
2584 // attributes.
2585 if (!AttrOnCallSite)
2586 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2587}
2588
2589void CodeGenModule::addDefaultFunctionDefinitionAttributes(
2590 llvm::AttrBuilder &attrs) {
2591 getDefaultFunctionAttributes(/*function name*/ Name: "", /*optnone*/ HasOptnone: false,
2592 /*for call*/ AttrOnCallSite: false, FuncAttrs&: attrs);
2593 GetCPUAndFeaturesAttributes(GD: GlobalDecl(), AttrBuilder&: attrs);
2594}
2595
2596static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2597 const LangOptions &LangOpts,
2598 const NoBuiltinAttr *NBA = nullptr) {
2599 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2600 SmallString<32> AttributeName;
2601 AttributeName += "no-builtin-";
2602 AttributeName += BuiltinName;
2603 FuncAttrs.addAttribute(A: AttributeName);
2604 };
2605
2606 // First, handle the language options passed through -fno-builtin.
2607 if (LangOpts.NoBuiltin) {
2608 // -fno-builtin disables them all.
2609 FuncAttrs.addAttribute(A: "no-builtins");
2610 return;
2611 }
2612
2613 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2614 llvm::for_each(Range: LangOpts.NoBuiltinFuncs, F: AddNoBuiltinAttr);
2615
2616 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2617 // the source.
2618 if (!NBA)
2619 return;
2620
2621 // If there is a wildcard in the builtin names specified through the
2622 // attribute, disable them all.
2623 if (llvm::is_contained(Range: NBA->builtinNames(), Element: "*")) {
2624 FuncAttrs.addAttribute(A: "no-builtins");
2625 return;
2626 }
2627
2628 // And last, add the rest of the builtin names.
2629 llvm::for_each(Range: NBA->builtinNames(), F: AddNoBuiltinAttr);
2630}
2631
2632static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
2633 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2634 bool CheckCoerce = true) {
2635 llvm::Type *Ty = Types.ConvertTypeForMem(T: QTy);
2636 if (AI.getKind() == ABIArgInfo::Indirect ||
2637 AI.getKind() == ABIArgInfo::IndirectAliased)
2638 return true;
2639 if (AI.getKind() == ABIArgInfo::Extend && !AI.isNoExt())
2640 return true;
2641 if (!DL.typeSizeEqualsStoreSize(Ty))
2642 // TODO: This will result in a modest amount of values not marked noundef
2643 // when they could be. We care about values that *invisibly* contain undef
2644 // bits from the perspective of LLVM IR.
2645 return false;
2646 if (CheckCoerce && AI.canHaveCoerceToType()) {
2647 llvm::Type *CoerceTy = AI.getCoerceToType();
2648 if (llvm::TypeSize::isKnownGT(LHS: DL.getTypeSizeInBits(Ty: CoerceTy),
2649 RHS: DL.getTypeSizeInBits(Ty)))
2650 // If we're coercing to a type with a greater size than the canonical one,
2651 // we're introducing new undef bits.
2652 // Coercing to a type of smaller or equal size is ok, as we know that
2653 // there's no internal padding (typeSizeEqualsStoreSize).
2654 return false;
2655 }
2656 if (QTy->isBitIntType())
2657 return true;
2658 if (QTy->isReferenceType())
2659 return true;
2660 if (QTy->isNullPtrType())
2661 return false;
2662 if (QTy->isMemberPointerType())
2663 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2664 // now, never mark them.
2665 return false;
2666 if (QTy->isScalarType()) {
2667 if (const ComplexType *Complex = dyn_cast<ComplexType>(Val&: QTy))
2668 return DetermineNoUndef(QTy: Complex->getElementType(), Types, DL, AI, CheckCoerce: false);
2669 return true;
2670 }
2671 if (const VectorType *Vector = dyn_cast<VectorType>(Val&: QTy))
2672 return DetermineNoUndef(QTy: Vector->getElementType(), Types, DL, AI, CheckCoerce: false);
2673 if (const MatrixType *Matrix = dyn_cast<MatrixType>(Val&: QTy))
2674 return DetermineNoUndef(QTy: Matrix->getElementType(), Types, DL, AI, CheckCoerce: false);
2675 if (const ArrayType *Array = dyn_cast<ArrayType>(Val&: QTy))
2676 return DetermineNoUndef(QTy: Array->getElementType(), Types, DL, AI, CheckCoerce: false);
2677
2678 // TODO: Some structs may be `noundef`, in specific situations.
2679 return false;
2680}
2681
2682/// Check if the argument of a function has maybe_undef attribute.
2683static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2684 unsigned NumRequiredArgs, unsigned ArgNo) {
2685 const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl);
2686 if (!FD)
2687 return false;
2688
2689 // Assume variadic arguments do not have maybe_undef attribute.
2690 if (ArgNo >= NumRequiredArgs)
2691 return false;
2692
2693 // Check if argument has maybe_undef attribute.
2694 if (ArgNo < FD->getNumParams()) {
2695 const ParmVarDecl *Param = FD->getParamDecl(i: ArgNo);
2696 if (Param && Param->hasAttr<MaybeUndefAttr>())
2697 return true;
2698 }
2699
2700 return false;
2701}
2702
2703/// Test if it's legal to apply nofpclass for the given parameter type and it's
2704/// lowered IR type.
2705static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2706 bool IsReturn) {
2707 // Should only apply to FP types in the source, not ABI promoted.
2708 if (!ParamType->hasFloatingRepresentation())
2709 return false;
2710
2711 // The promoted-to IR type also needs to support nofpclass.
2712 llvm::Type *IRTy = AI.getCoerceToType();
2713 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty: IRTy))
2714 return true;
2715
2716 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Val: IRTy)) {
2717 return !IsReturn && AI.getCanBeFlattened() &&
2718 llvm::all_of(Range: ST->elements(),
2719 P: llvm::AttributeFuncs::isNoFPClassCompatibleType);
2720 }
2721
2722 return false;
2723}
2724
2725void CodeGenModule::AdjustMemoryAttribute(StringRef Name,
2726 CGCalleeInfo CalleeInfo,
2727 llvm::AttributeList &Attrs) {
2728 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2729 Attrs = Attrs.removeFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::Memory);
2730 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2731 Context&: getLLVMContext(), ME: llvm::MemoryEffects::writeOnly());
2732 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Attr: MemoryAttr);
2733 }
2734}
2735
2736/// Construct the IR attribute list of a function or call.
2737///
2738/// When adding an attribute, please consider where it should be handled:
2739///
2740/// - getDefaultFunctionAttributes is for attributes that are essentially
2741/// part of the global target configuration (but perhaps can be
2742/// overridden on a per-function basis). Adding attributes there
2743/// will cause them to also be set in frontends that build on Clang's
2744/// target-configuration logic, as well as for code defined in library
2745/// modules such as CUDA's libdevice.
2746///
2747/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2748/// and adds declaration-specific, convention-specific, and
2749/// frontend-specific logic. The last is of particular importance:
2750/// attributes that restrict how the frontend generates code must be
2751/// added here rather than getDefaultFunctionAttributes.
2752///
2753void CodeGenModule::ConstructAttributeList(StringRef Name,
2754 const CGFunctionInfo &FI,
2755 CGCalleeInfo CalleeInfo,
2756 llvm::AttributeList &AttrList,
2757 unsigned &CallingConv,
2758 bool AttrOnCallSite, bool IsThunk) {
2759 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2760 llvm::AttrBuilder RetAttrs(getLLVMContext());
2761
2762 // Collect function IR attributes from the CC lowering.
2763 // We'll collect the paramete and result attributes later.
2764 CallingConv = FI.getEffectiveCallingConvention();
2765 if (FI.isNoReturn())
2766 FuncAttrs.addAttribute(Val: llvm::Attribute::NoReturn);
2767 if (FI.isCmseNSCall())
2768 FuncAttrs.addAttribute(A: "cmse_nonsecure_call");
2769
2770 // Collect function IR attributes from the callee prototype if we have one.
2771 AddAttributesFromFunctionProtoType(Ctx&: getContext(), FuncAttrs,
2772 FPT: CalleeInfo.getCalleeFunctionProtoType());
2773 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2774
2775 // Attach assumption attributes to the declaration. If this is a call
2776 // site, attach assumptions from the caller to the call as well.
2777 AddAttributesFromOMPAssumes(FuncAttrs, Callee: TargetDecl);
2778
2779 bool HasOptnone = false;
2780 // The NoBuiltinAttr attached to the target FunctionDecl.
2781 const NoBuiltinAttr *NBA = nullptr;
2782
2783 // Some ABIs may result in additional accesses to arguments that may
2784 // otherwise not be present.
2785 std::optional<llvm::Attribute::AttrKind> MemAttrForPtrArgs;
2786 bool AddedPotentialArgAccess = false;
2787 auto AddPotentialArgAccess = [&]() {
2788 AddedPotentialArgAccess = true;
2789 llvm::Attribute A = FuncAttrs.getAttribute(Kind: llvm::Attribute::Memory);
2790 if (A.isValid())
2791 FuncAttrs.addMemoryAttr(ME: A.getMemoryEffects() |
2792 llvm::MemoryEffects::argMemOnly());
2793 };
2794
2795 // Collect function IR attributes based on declaration-specific
2796 // information.
2797 // FIXME: handle sseregparm someday...
2798 if (TargetDecl) {
2799 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2800 FuncAttrs.addAttribute(Val: llvm::Attribute::ReturnsTwice);
2801 if (TargetDecl->hasAttr<NoThrowAttr>())
2802 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2803 if (TargetDecl->hasAttr<NoReturnAttr>())
2804 FuncAttrs.addAttribute(Val: llvm::Attribute::NoReturn);
2805 if (TargetDecl->hasAttr<ColdAttr>())
2806 FuncAttrs.addAttribute(Val: llvm::Attribute::Cold);
2807 if (TargetDecl->hasAttr<HotAttr>())
2808 FuncAttrs.addAttribute(Val: llvm::Attribute::Hot);
2809 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2810 FuncAttrs.addAttribute(Val: llvm::Attribute::NoDuplicate);
2811 if (TargetDecl->hasAttr<ConvergentAttr>())
2812 FuncAttrs.addAttribute(Val: llvm::Attribute::Convergent);
2813
2814 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(Val: TargetDecl)) {
2815 AddAttributesFromFunctionProtoType(
2816 Ctx&: getContext(), FuncAttrs, FPT: Fn->getType()->getAs<FunctionProtoType>());
2817 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2818 // A sane operator new returns a non-aliasing pointer.
2819 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2820 Fn->getDeclName().isAnyOperatorNew())
2821 RetAttrs.addAttribute(Val: llvm::Attribute::NoAlias);
2822 }
2823 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Fn);
2824 const bool IsVirtualCall = MD && MD->isVirtual();
2825 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2826 // virtual function. These attributes are not inherited by overloads.
2827 if (!(AttrOnCallSite && IsVirtualCall)) {
2828 if (Fn->isNoReturn())
2829 FuncAttrs.addAttribute(Val: llvm::Attribute::NoReturn);
2830 NBA = Fn->getAttr<NoBuiltinAttr>();
2831 }
2832 }
2833
2834 if (isa<FunctionDecl>(Val: TargetDecl) || isa<VarDecl>(Val: TargetDecl)) {
2835 // Only place nomerge attribute on call sites, never functions. This
2836 // allows it to work on indirect virtual function calls.
2837 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2838 FuncAttrs.addAttribute(Val: llvm::Attribute::NoMerge);
2839 }
2840
2841 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2842 if (TargetDecl->hasAttr<ConstAttr>()) {
2843 FuncAttrs.addMemoryAttr(ME: llvm::MemoryEffects::none());
2844 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2845 // gcc specifies that 'const' functions have greater restrictions than
2846 // 'pure' functions, so they also cannot have infinite loops.
2847 FuncAttrs.addAttribute(Val: llvm::Attribute::WillReturn);
2848 MemAttrForPtrArgs = llvm::Attribute::ReadNone;
2849 } else if (TargetDecl->hasAttr<PureAttr>()) {
2850 FuncAttrs.addMemoryAttr(ME: llvm::MemoryEffects::readOnly());
2851 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2852 // gcc specifies that 'pure' functions cannot have infinite loops.
2853 FuncAttrs.addAttribute(Val: llvm::Attribute::WillReturn);
2854 MemAttrForPtrArgs = llvm::Attribute::ReadOnly;
2855 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2856 FuncAttrs.addMemoryAttr(ME: llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2857 FuncAttrs.addAttribute(Val: llvm::Attribute::NoUnwind);
2858 }
2859 if (const auto *RA = TargetDecl->getAttr<RestrictAttr>();
2860 RA && RA->getDeallocator() == nullptr)
2861 RetAttrs.addAttribute(Val: llvm::Attribute::NoAlias);
2862 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2863 !CodeGenOpts.NullPointerIsValid)
2864 RetAttrs.addAttribute(Val: llvm::Attribute::NonNull);
2865 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2866 FuncAttrs.addAttribute(A: "no_caller_saved_registers");
2867 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2868 FuncAttrs.addAttribute(Val: llvm::Attribute::NoCfCheck);
2869 if (TargetDecl->hasAttr<LeafAttr>())
2870 FuncAttrs.addAttribute(Val: llvm::Attribute::NoCallback);
2871 if (TargetDecl->hasAttr<BPFFastCallAttr>())
2872 FuncAttrs.addAttribute(A: "bpf_fastcall");
2873
2874 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2875 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2876 std::optional<unsigned> NumElemsParam;
2877 if (AllocSize->getNumElemsParam().isValid())
2878 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2879 FuncAttrs.addAllocSizeAttr(ElemSizeArg: AllocSize->getElemSizeParam().getLLVMIndex(),
2880 NumElemsArg: NumElemsParam);
2881 }
2882
2883 // OpenCL v2.0 Work groups may be whether uniform or not.
2884 // '-cl-uniform-work-group-size' compile option gets a hint
2885 // to the compiler that the global work-size be a multiple of
2886 // the work-group size specified to clEnqueueNDRangeKernel
2887 // (i.e. work groups are uniform).
2888 if (getLangOpts().OffloadUniformBlock)
2889 FuncAttrs.addAttribute(A: "uniform-work-group-size");
2890
2891 if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2892 FuncAttrs.addAttribute(A: "aarch64_pstate_sm_body");
2893
2894 if (auto *ModularFormat = TargetDecl->getAttr<ModularFormatAttr>()) {
2895 FormatAttr *Format = TargetDecl->getAttr<FormatAttr>();
2896 StringRef Type = Format->getType()->getName();
2897 std::string FormatIdx = std::to_string(val: Format->getFormatIdx());
2898 std::string FirstArg = std::to_string(val: Format->getFirstArg());
2899 SmallVector<StringRef> Args = {
2900 Type, FormatIdx, FirstArg,
2901 ModularFormat->getModularImplFn()->getName(),
2902 ModularFormat->getImplName()};
2903 llvm::append_range(C&: Args, R: ModularFormat->aspects());
2904 FuncAttrs.addAttribute(A: "modular-format", V: llvm::join(R&: Args, Separator: ","));
2905 }
2906 }
2907
2908 // Attach "no-builtins" attributes to:
2909 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2910 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2911 // The attributes can come from:
2912 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2913 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2914 addNoBuiltinAttributes(FuncAttrs, LangOpts: getLangOpts(), NBA);
2915
2916 // Collect function IR attributes based on global settiings.
2917 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2918
2919 // Override some default IR attributes based on declaration-specific
2920 // information.
2921 if (TargetDecl) {
2922 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2923 FuncAttrs.removeAttribute(Val: llvm::Attribute::SpeculativeLoadHardening);
2924 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2925 FuncAttrs.addAttribute(Val: llvm::Attribute::SpeculativeLoadHardening);
2926 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2927 FuncAttrs.removeAttribute(A: "split-stack");
2928 if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2929 // A function "__attribute__((...))" overrides the command-line flag.
2930 auto Kind =
2931 TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2932 FuncAttrs.removeAttribute(A: "zero-call-used-regs");
2933 FuncAttrs.addAttribute(
2934 A: "zero-call-used-regs",
2935 V: ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Val: Kind));
2936 }
2937
2938 // Add NonLazyBind attribute to function declarations when -fno-plt
2939 // is used.
2940 // FIXME: what if we just haven't processed the function definition
2941 // yet, or if it's an external definition like C99 inline?
2942 if (CodeGenOpts.NoPLT) {
2943 if (auto *Fn = dyn_cast<FunctionDecl>(Val: TargetDecl)) {
2944 if (!Fn->isDefined() && !AttrOnCallSite) {
2945 FuncAttrs.addAttribute(Val: llvm::Attribute::NonLazyBind);
2946 }
2947 }
2948 }
2949 // Remove 'convergent' if requested.
2950 if (TargetDecl->hasAttr<NoConvergentAttr>())
2951 FuncAttrs.removeAttribute(Val: llvm::Attribute::Convergent);
2952 }
2953
2954 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2955 // functions with -funique-internal-linkage-names.
2956 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2957 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl)) {
2958 if (!FD->isExternallyVisible())
2959 FuncAttrs.addAttribute(A: "sample-profile-suffix-elision-policy",
2960 V: "selected");
2961 }
2962 }
2963
2964 // Collect non-call-site function IR attributes from declaration-specific
2965 // information.
2966 if (!AttrOnCallSite) {
2967 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2968 FuncAttrs.addAttribute(A: "cmse_nonsecure_entry");
2969
2970 // Whether tail calls are enabled.
2971 auto shouldDisableTailCalls = [&] {
2972 // Should this be honored in getDefaultFunctionAttributes?
2973 if (CodeGenOpts.DisableTailCalls)
2974 return true;
2975
2976 if (!TargetDecl)
2977 return false;
2978
2979 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2980 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2981 return true;
2982
2983 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2984 if (const auto *BD = dyn_cast<BlockDecl>(Val: TargetDecl))
2985 if (!BD->doesNotEscape())
2986 return true;
2987 }
2988
2989 return false;
2990 };
2991 if (shouldDisableTailCalls())
2992 FuncAttrs.addAttribute(A: "disable-tail-calls", V: "true");
2993
2994 // These functions require the returns_twice attribute for correct codegen,
2995 // but the attribute may not be added if -fno-builtin is specified. We
2996 // explicitly add that attribute here.
2997 static const llvm::StringSet<> ReturnsTwiceFn{
2998 "_setjmpex", "setjmp", "_setjmp", "vfork",
2999 "sigsetjmp", "__sigsetjmp", "savectx", "getcontext"};
3000 if (ReturnsTwiceFn.contains(key: Name))
3001 FuncAttrs.addAttribute(Val: llvm::Attribute::ReturnsTwice);
3002
3003 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
3004 // handles these separately to set them based on the global defaults.
3005 GetCPUAndFeaturesAttributes(GD: CalleeInfo.getCalleeDecl(), AttrBuilder&: FuncAttrs);
3006
3007 // Windows hotpatching support
3008 if (!MSHotPatchFunctions.empty()) {
3009 bool IsHotPatched = llvm::binary_search(Range&: MSHotPatchFunctions, Value&: Name);
3010 if (IsHotPatched)
3011 FuncAttrs.addAttribute(A: "marked_for_windows_hot_patching");
3012 }
3013 }
3014
3015 // Mark functions that are replaceable by the loader.
3016 if (CodeGenOpts.isLoaderReplaceableFunctionName(FuncName: Name))
3017 FuncAttrs.addAttribute(A: "loader-replaceable");
3018
3019 // Collect attributes from arguments and return values.
3020 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
3021
3022 QualType RetTy = FI.getReturnType();
3023 const ABIArgInfo &RetAI = FI.getReturnInfo();
3024 const llvm::DataLayout &DL = getDataLayout();
3025
3026 // Determine if the return type could be partially undef
3027 if (CodeGenOpts.EnableNoundefAttrs &&
3028 HasStrictReturn(Module: *this, RetTy, TargetDecl)) {
3029 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
3030 DetermineNoUndef(QTy: RetTy, Types&: getTypes(), DL, AI: RetAI))
3031 RetAttrs.addAttribute(Val: llvm::Attribute::NoUndef);
3032 }
3033
3034 switch (RetAI.getKind()) {
3035 case ABIArgInfo::Extend:
3036 if (RetAI.isSignExt())
3037 RetAttrs.addAttribute(Val: llvm::Attribute::SExt);
3038 else if (RetAI.isZeroExt())
3039 RetAttrs.addAttribute(Val: llvm::Attribute::ZExt);
3040 else
3041 RetAttrs.addAttribute(Val: llvm::Attribute::NoExt);
3042 [[fallthrough]];
3043 case ABIArgInfo::TargetSpecific:
3044 case ABIArgInfo::Direct:
3045 if (RetAI.getInReg())
3046 RetAttrs.addAttribute(Val: llvm::Attribute::InReg);
3047
3048 if (canApplyNoFPClass(AI: RetAI, ParamType: RetTy, IsReturn: true))
3049 RetAttrs.addNoFPClassAttr(
3050 NoFPClassMask: CodeGenUtils::getNoFPClassTestMask(LangOpts: getLangOpts()));
3051
3052 break;
3053 case ABIArgInfo::Ignore:
3054 break;
3055
3056 case ABIArgInfo::InAlloca:
3057 case ABIArgInfo::Indirect: {
3058 // inalloca and sret disable readnone and readonly
3059 AddPotentialArgAccess();
3060 break;
3061 }
3062
3063 case ABIArgInfo::CoerceAndExpand:
3064 break;
3065
3066 case ABIArgInfo::Expand:
3067 case ABIArgInfo::IndirectAliased:
3068 llvm_unreachable("Invalid ABI kind for return argument");
3069 }
3070
3071 if (!IsThunk) {
3072 // FIXME: fix this properly, https://reviews.llvm.org/D100388
3073 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
3074 QualType PTy = RefTy->getPointeeType();
3075 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
3076 RetAttrs.addDereferenceableAttr(
3077 Bytes: getMinimumObjectSize(Ty: PTy).getQuantity());
3078 if (getTypes().getTargetAddressSpace(T: PTy) == 0 &&
3079 !CodeGenOpts.NullPointerIsValid)
3080 RetAttrs.addAttribute(Val: llvm::Attribute::NonNull);
3081 if (PTy->isObjectType()) {
3082 llvm::Align Alignment =
3083 getNaturalPointeeTypeAlignment(T: RetTy).getAsAlign();
3084 RetAttrs.addAlignmentAttr(Align: Alignment);
3085 }
3086 }
3087 }
3088
3089 bool hasUsedSRet = false;
3090 SmallVector<llvm::AttrBuilder, 4> ArgAttrs;
3091 for (unsigned I = 0; I < IRFunctionArgs.totalIRArgs(); ++I)
3092 ArgAttrs.emplace_back(Args&: getLLVMContext());
3093
3094 // Attach attributes to sret.
3095 if (IRFunctionArgs.hasSRetArg()) {
3096 llvm::AttrBuilder &SRETAttrs = ArgAttrs[IRFunctionArgs.getSRetArgNo()];
3097 SRETAttrs.addStructRetAttr(Ty: getTypes().ConvertTypeForMem(T: RetTy));
3098 SRETAttrs.addAttribute(Val: llvm::Attribute::Writable);
3099 SRETAttrs.addAttribute(Val: llvm::Attribute::DeadOnUnwind);
3100 hasUsedSRet = true;
3101 if (RetAI.getInReg())
3102 SRETAttrs.addAttribute(Val: llvm::Attribute::InReg);
3103 SRETAttrs.addAlignmentAttr(Align: RetAI.getIndirectAlign().getQuantity());
3104 }
3105
3106 // Attach attributes to inalloca argument.
3107 if (IRFunctionArgs.hasInallocaArg()) {
3108 ArgAttrs[IRFunctionArgs.getInallocaArgNo()].addInAllocaAttr(
3109 Ty: FI.getArgStruct());
3110 }
3111
3112 // Apply `nonnull`, `dereferenceable(N)` and `align N` to the `this` argument,
3113 // unless this is a thunk function. Add dead_on_return to the `this` argument
3114 // in base class destructors to aid in DSE.
3115 // FIXME: fix this properly, https://reviews.llvm.org/D100388
3116 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
3117 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
3118 auto IRArgs = IRFunctionArgs.getIRArgs(ArgNo: 0);
3119
3120 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
3121
3122 llvm::AttrBuilder &Attrs = ArgAttrs[IRArgs.first];
3123
3124 QualType ThisTy = FI.arg_begin()->type.getTypePtr()->getPointeeType();
3125 int64_t ThisSz = getMinimumObjectSize(Ty: ThisTy).getQuantity();
3126
3127 if (!CodeGenOpts.NullPointerIsValid &&
3128 getTypes().getTargetAddressSpace(T: FI.arg_begin()->type) == 0) {
3129 Attrs.addAttribute(Val: llvm::Attribute::NonNull);
3130 Attrs.addDereferenceableAttr(Bytes: ThisSz);
3131 } else {
3132 // FIXME dereferenceable should be correct here, regardless of
3133 // NullPointerIsValid. However, dereferenceable currently does not always
3134 // respect NullPointerIsValid and may imply nonnull and break the program.
3135 // See https://reviews.llvm.org/D66618 for discussions.
3136 Attrs.addDereferenceableOrNullAttr(Bytes: ThisSz);
3137 }
3138
3139 llvm::Align Alignment =
3140 getNaturalTypeAlignment(T: ThisTy, /*BaseInfo=*/nullptr,
3141 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
3142 .getAsAlign();
3143 Attrs.addAlignmentAttr(Align: Alignment);
3144
3145 const auto *DD = dyn_cast_if_present<CXXDestructorDecl>(
3146 Val: CalleeInfo.getCalleeDecl().getDecl());
3147 // Do not annotate vector deleting destructors with dead_on_return as the
3148 // this pointer in that case points to an array which we cannot
3149 // statically know the size of. Also do not mark deleting destructors
3150 // dead_on_return as then we might delete stores inside of a user-defined
3151 // operator delete implementation if it gets inlined, which would be
3152 // incorrect as the object's lifetime has already ended and the operator
3153 // delete implementation is allowed to manipulate the underlying storage.
3154 if (DD &&
3155 CalleeInfo.getCalleeDecl().getDtorType() !=
3156 CXXDtorType::Dtor_VectorDeleting &&
3157 CalleeInfo.getCalleeDecl().getDtorType() !=
3158 CXXDtorType::Dtor_Deleting &&
3159 CodeGenOpts.StrictLifetimes) {
3160 const CXXRecordDecl *ClassDecl =
3161 dyn_cast<CXXRecordDecl>(Val: DD->getDeclContext());
3162 // We cannot add dead_on_return if we have virtual base classes because
3163 // they will generally still be live after the base object destructor.
3164 if (ClassDecl->getNumVBases() == 0)
3165 Attrs.addDeadOnReturnAttr(Info: llvm::DeadOnReturnInfo(
3166 Context.getASTRecordLayout(D: ClassDecl).getDataSize().getQuantity()));
3167 }
3168 }
3169
3170 unsigned ArgNo = 0;
3171 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), E = FI.arg_end();
3172 I != E; ++I, ++ArgNo) {
3173 QualType ParamType = I->type;
3174 const ABIArgInfo &AI = I->info;
3175 llvm::AttrBuilder Attrs(getLLVMContext());
3176
3177 // Add attribute for padding argument, if necessary.
3178 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
3179 if (AI.getPaddingInReg()) {
3180 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)].addAttribute(
3181 Val: llvm::Attribute::InReg);
3182 }
3183 }
3184
3185 // Decide whether the argument we're handling could be partially undef
3186 if (CodeGenOpts.EnableNoundefAttrs &&
3187 DetermineNoUndef(QTy: ParamType, Types&: getTypes(), DL, AI)) {
3188 Attrs.addAttribute(Val: llvm::Attribute::NoUndef);
3189 }
3190
3191 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
3192 // have the corresponding parameter variable. It doesn't make
3193 // sense to do it here because parameters are so messed up.
3194 switch (AI.getKind()) {
3195 case ABIArgInfo::Extend:
3196 if (AI.isSignExt())
3197 Attrs.addAttribute(Val: llvm::Attribute::SExt);
3198 else if (AI.isZeroExt())
3199 Attrs.addAttribute(Val: llvm::Attribute::ZExt);
3200 else
3201 Attrs.addAttribute(Val: llvm::Attribute::NoExt);
3202 [[fallthrough]];
3203 case ABIArgInfo::TargetSpecific:
3204 case ABIArgInfo::Direct:
3205 if (ArgNo == 0 && FI.isChainCall())
3206 Attrs.addAttribute(Val: llvm::Attribute::Nest);
3207 else if (AI.getInReg())
3208 Attrs.addAttribute(Val: llvm::Attribute::InReg);
3209 Attrs.addStackAlignmentAttr(Align: llvm::MaybeAlign(AI.getDirectAlign()));
3210
3211 if (canApplyNoFPClass(AI, ParamType, IsReturn: false))
3212 Attrs.addNoFPClassAttr(
3213 NoFPClassMask: CodeGenUtils::getNoFPClassTestMask(LangOpts: getLangOpts()));
3214 break;
3215 case ABIArgInfo::Indirect: {
3216 assert(!ParamType->isIncompleteType() &&
3217 "Pass-by-value parameter has incomplete definition?");
3218
3219 if (AI.getInReg())
3220 Attrs.addAttribute(Val: llvm::Attribute::InReg);
3221
3222 // HLSL out and inout parameters must not be marked with ByVal or
3223 // DeadOnReturn attributes because stores to these parameters by the
3224 // callee are visible to the caller.
3225 if (auto ParamABI = FI.getExtParameterInfo(argIndex: ArgNo).getABI();
3226 ParamABI != ParameterABI::HLSLOut &&
3227 ParamABI != ParameterABI::HLSLInOut) {
3228
3229 // Depending on the ABI, this may be either a byval or a dead_on_return
3230 // argument.
3231 if (AI.getIndirectByVal()) {
3232 Attrs.addByValAttr(Ty: getTypes().ConvertTypeForMem(T: ParamType));
3233 } else {
3234 // Add dead_on_return when the object's lifetime ends in the callee.
3235 // This includes trivially-destructible objects, as well as objects
3236 // whose destruction / clean-up is carried out within the callee
3237 // (e.g., Obj-C ARC-managed structs, MSVC callee-destroyed objects).
3238 if (!ParamType.isDestructedType() || !ParamType->isRecordType() ||
3239 ParamType->castAsRecordDecl()->isParamDestroyedInCallee())
3240 Attrs.addDeadOnReturnAttr(Info: llvm::DeadOnReturnInfo());
3241 }
3242 }
3243
3244 auto *Decl = ParamType->getAsRecordDecl();
3245 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
3246 Decl->getArgPassingRestrictions() ==
3247 RecordArgPassingKind::CanPassInRegs)
3248 // When calling the function, the pointer passed in will be the only
3249 // reference to the underlying object. Mark it accordingly.
3250 Attrs.addAttribute(Val: llvm::Attribute::NoAlias);
3251
3252 // TODO: We could add the byref attribute if not byval, but it would
3253 // require updating many testcases.
3254
3255 CharUnits Align = AI.getIndirectAlign();
3256
3257 // In a byval argument, it is important that the required
3258 // alignment of the type is honored, as LLVM might be creating a
3259 // *new* stack object, and needs to know what alignment to give
3260 // it. (Sometimes it can deduce a sensible alignment on its own,
3261 // but not if clang decides it must emit a packed struct, or the
3262 // user specifies increased alignment requirements.)
3263 //
3264 // This is different from indirect *not* byval, where an aligned copy is
3265 // already created by the caller, and the align attribute is purely
3266 // informative. However, this can still be useful information for
3267 // optimizations, such as giving us one necessary condition for checking
3268 // if a load to this pointer can be speculatively executed.
3269 assert(!Align.isZero());
3270 Attrs.addAlignmentAttr(Align: Align.getQuantity());
3271
3272 // The `nofree` and `dereferenceable` attributes can already be inferred
3273 // for `byval` arguments. We'll need to provide additional hints
3274 // otherwise.
3275 if (!AI.getIndirectByVal()) {
3276 // Both 6.9.1 of the C standard and [basic.stc.auto] of the C++ standard
3277 // require parameters to have automatic storage duration. Therefore, the
3278 // underlying object of this pointer will not be freed during the
3279 // function's execution.
3280 Attrs.addAttribute(Val: llvm::Attribute::NoFreeObj);
3281 Attrs.addDereferenceableAttr(
3282 Bytes: Context.getTypeSizeInChars(T: ParamType).getQuantity());
3283 }
3284
3285 // byval disables readnone and readonly.
3286 AddPotentialArgAccess();
3287 break;
3288 }
3289 case ABIArgInfo::IndirectAliased: {
3290 CharUnits Align = AI.getIndirectAlign();
3291 Attrs.addByRefAttr(Ty: getTypes().ConvertTypeForMem(T: ParamType));
3292 Attrs.addAlignmentAttr(Align: Align.getQuantity());
3293 break;
3294 }
3295 case ABIArgInfo::Ignore:
3296 case ABIArgInfo::Expand:
3297 case ABIArgInfo::CoerceAndExpand:
3298 break;
3299
3300 case ABIArgInfo::InAlloca:
3301 // inalloca disables readnone and readonly.
3302 AddPotentialArgAccess();
3303 continue;
3304 }
3305
3306 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
3307 QualType PTy = RefTy->getPointeeType();
3308 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
3309 Attrs.addDereferenceableAttr(Bytes: getMinimumObjectSize(Ty: PTy).getQuantity());
3310 if (getTypes().getTargetAddressSpace(T: PTy) == 0 &&
3311 !CodeGenOpts.NullPointerIsValid)
3312 Attrs.addAttribute(Val: llvm::Attribute::NonNull);
3313 if (PTy->isObjectType()) {
3314 llvm::Align Alignment =
3315 getNaturalPointeeTypeAlignment(T: ParamType).getAsAlign();
3316 Attrs.addAlignmentAttr(Align: Alignment);
3317 }
3318 }
3319
3320 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
3321 // > For arguments to a __kernel function declared to be a pointer to a
3322 // > data type, the OpenCL compiler can assume that the pointee is always
3323 // > appropriately aligned as required by the data type.
3324 if (TargetDecl &&
3325 DeviceKernelAttr::isOpenCLSpelling(
3326 A: TargetDecl->getAttr<DeviceKernelAttr>()) &&
3327 ParamType->isPointerType()) {
3328 QualType PTy = ParamType->getPointeeType();
3329 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
3330 llvm::Align Alignment =
3331 getNaturalPointeeTypeAlignment(T: ParamType).getAsAlign();
3332 Attrs.addAlignmentAttr(Align: Alignment);
3333 }
3334 }
3335
3336 switch (FI.getExtParameterInfo(argIndex: ArgNo).getABI()) {
3337 case ParameterABI::HLSLOut:
3338 case ParameterABI::HLSLInOut:
3339 Attrs.addAttribute(Val: llvm::Attribute::NoAlias);
3340 break;
3341 case ParameterABI::Ordinary:
3342 break;
3343
3344 case ParameterABI::SwiftIndirectResult: {
3345 // Add 'sret' if we haven't already used it for something, but
3346 // only if the result is void.
3347 if (!hasUsedSRet && RetTy->isVoidType()) {
3348 Attrs.addStructRetAttr(Ty: getTypes().ConvertTypeForMem(T: ParamType));
3349 hasUsedSRet = true;
3350 }
3351
3352 // Add 'noalias' in either case.
3353 Attrs.addAttribute(Val: llvm::Attribute::NoAlias);
3354
3355 // Add 'dereferenceable' and 'alignment'.
3356 auto PTy = ParamType->getPointeeType();
3357 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
3358 auto info = getContext().getTypeInfoInChars(T: PTy);
3359 Attrs.addDereferenceableAttr(Bytes: info.Width.getQuantity());
3360 Attrs.addAlignmentAttr(Align: info.Align.getAsAlign());
3361 }
3362 break;
3363 }
3364
3365 case ParameterABI::SwiftErrorResult:
3366 Attrs.addAttribute(Val: llvm::Attribute::SwiftError);
3367 break;
3368
3369 case ParameterABI::SwiftContext:
3370 Attrs.addAttribute(Val: llvm::Attribute::SwiftSelf);
3371 break;
3372
3373 case ParameterABI::SwiftAsyncContext:
3374 Attrs.addAttribute(Val: llvm::Attribute::SwiftAsync);
3375 break;
3376 }
3377
3378 if (FI.getExtParameterInfo(argIndex: ArgNo).isNoEscape())
3379 Attrs.addCapturesAttr(
3380 CI: llvm::CaptureInfo(llvm::CaptureComponents::Address));
3381
3382 if (Attrs.hasAttributes()) {
3383 unsigned FirstIRArg, NumIRArgs;
3384 std::tie(args&: FirstIRArg, args&: NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3385 for (unsigned i = 0; i < NumIRArgs; i++)
3386 ArgAttrs[FirstIRArg + i].merge(B: Attrs);
3387 }
3388 }
3389 assert(ArgNo == FI.arg_size());
3390
3391 // We can't see all potential arguments in a varargs declaration; treat them
3392 // as if they can access memory.
3393 if (!AttrOnCallSite && FI.isVariadic())
3394 AddPotentialArgAccess();
3395
3396 ArgNo = 0;
3397 if (AddedPotentialArgAccess && MemAttrForPtrArgs) {
3398 llvm::FunctionType *FunctionType = getTypes().GetFunctionType(FI);
3399 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
3400 E = FI.arg_end();
3401 I != E; ++I, ++ArgNo) {
3402 if (I->info.isDirect() || I->info.isExpand() ||
3403 I->info.isCoerceAndExpand()) {
3404 unsigned FirstIRArg, NumIRArgs;
3405 std::tie(args&: FirstIRArg, args&: NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3406 for (unsigned i = FirstIRArg; i < FirstIRArg + NumIRArgs; ++i) {
3407 // The index may be out-of-bounds if the callee is a varargs
3408 // function.
3409 //
3410 // FIXME: We can compute the types of varargs arguments without going
3411 // through the function type, but the relevant code isn't exposed
3412 // in a way that can be called from here.
3413 if (i < FunctionType->getNumParams() &&
3414 FunctionType->getParamType(i)->isPointerTy()) {
3415 ArgAttrs[i].addAttribute(Val: *MemAttrForPtrArgs);
3416 }
3417 }
3418 }
3419 }
3420 }
3421
3422 SmallVector<llvm::AttributeSet, 4> ArgAttrSets;
3423 for (const llvm::AttrBuilder &Attrs : ArgAttrs)
3424 ArgAttrSets.push_back(Elt: llvm::AttributeSet::get(C&: getLLVMContext(), B: Attrs));
3425
3426 AttrList = llvm::AttributeList::get(
3427 C&: getLLVMContext(), FnAttrs: llvm::AttributeSet::get(C&: getLLVMContext(), B: FuncAttrs),
3428 RetAttrs: llvm::AttributeSet::get(C&: getLLVMContext(), B: RetAttrs), ArgAttrs: ArgAttrSets);
3429}
3430
3431/// An argument came in as a promoted argument; demote it back to its
3432/// declared type.
3433static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
3434 const VarDecl *var,
3435 llvm::Value *value) {
3436 llvm::Type *varType = CGF.ConvertType(T: var->getType());
3437
3438 // This can happen with promotions that actually don't change the
3439 // underlying type, like the enum promotions.
3440 if (value->getType() == varType)
3441 return value;
3442
3443 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) &&
3444 "unexpected promotion type");
3445
3446 if (isa<llvm::IntegerType>(Val: varType))
3447 return CGF.Builder.CreateTrunc(V: value, DestTy: varType, Name: "arg.unpromote");
3448
3449 return CGF.Builder.CreateFPCast(V: value, DestTy: varType, Name: "arg.unpromote");
3450}
3451
3452/// Returns the attribute (either parameter attribute, or function
3453/// attribute), which declares argument ArgNo to be non-null.
3454static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
3455 QualType ArgType, unsigned ArgNo) {
3456 // FIXME: __attribute__((nonnull)) can also be applied to:
3457 // - references to pointers, where the pointee is known to be
3458 // nonnull (apparently a Clang extension)
3459 // - transparent unions containing pointers
3460 // In the former case, LLVM IR cannot represent the constraint. In
3461 // the latter case, we have no guarantee that the transparent union
3462 // is in fact passed as a pointer.
3463 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
3464 return nullptr;
3465 // First, check attribute on parameter itself.
3466 if (PVD) {
3467 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
3468 return ParmNNAttr;
3469 }
3470 // Check function attributes.
3471 if (!FD)
3472 return nullptr;
3473 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
3474 if (NNAttr->isNonNull(IdxAST: ArgNo))
3475 return NNAttr;
3476 }
3477 return nullptr;
3478}
3479
3480namespace {
3481struct CopyBackSwiftError final : EHScopeStack::Cleanup {
3482 Address Temp;
3483 Address Arg;
3484 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
3485 void Emit(CodeGenFunction &CGF, Flags flags) override {
3486 llvm::Value *errorValue = CGF.Builder.CreateLoad(Addr: Temp);
3487 CGF.Builder.CreateStore(Val: errorValue, Addr: Arg);
3488 }
3489};
3490} // namespace
3491
3492void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
3493 llvm::Function *Fn,
3494 const FunctionArgList &Args) {
3495 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
3496 // Naked functions don't have prologues.
3497 return;
3498
3499 // If this is an implicit-return-zero function, go ahead and
3500 // initialize the return value. TODO: it might be nice to have
3501 // a more general mechanism for this that didn't require synthesized
3502 // return statements.
3503 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl)) {
3504 if (FD->hasImplicitReturnZero()) {
3505 QualType RetTy = FD->getReturnType().getUnqualifiedType();
3506 llvm::Type *LLVMTy = CGM.getTypes().ConvertType(T: RetTy);
3507 llvm::Constant *Zero = llvm::Constant::getNullValue(Ty: LLVMTy);
3508 Builder.CreateStore(Val: Zero, Addr: ReturnValue);
3509 }
3510 }
3511
3512 // FIXME: We no longer need the types from FunctionArgList; lift up and
3513 // simplify.
3514
3515 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
3516 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
3517
3518 // If we're using inalloca, all the memory arguments are GEPs off of the last
3519 // parameter, which is a pointer to the complete memory area.
3520 Address ArgStruct = Address::invalid();
3521 if (IRFunctionArgs.hasInallocaArg())
3522 ArgStruct = Address(Fn->getArg(i: IRFunctionArgs.getInallocaArgNo()),
3523 FI.getArgStruct(), FI.getArgStructAlignment());
3524
3525 // Name the struct return parameter.
3526 if (IRFunctionArgs.hasSRetArg()) {
3527 auto AI = Fn->getArg(i: IRFunctionArgs.getSRetArgNo());
3528 AI->setName("agg.result");
3529 AI->addAttr(Kind: llvm::Attribute::NoAlias);
3530 }
3531
3532 // Track if we received the parameter as a pointer (indirect, byval, or
3533 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
3534 // into a local alloca for us.
3535 SmallVector<ParamValue, 16> ArgVals;
3536 ArgVals.reserve(N: Args.size());
3537
3538 // Create a pointer value for every parameter declaration. This usually
3539 // entails copying one or more LLVM IR arguments into an alloca. Don't push
3540 // any cleanups or do anything that might unwind. We do that separately, so
3541 // we can push the cleanups in the correct order for the ABI.
3542 assert(FI.arg_size() == Args.size() &&
3543 "Mismatch between function signature & arguments.");
3544 unsigned ArgNo = 0;
3545 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
3546 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e;
3547 ++i, ++info_it, ++ArgNo) {
3548 const VarDecl *Arg = *i;
3549 const ABIArgInfo &ArgI = info_it->info;
3550
3551 bool isPromoted =
3552 isa<ParmVarDecl>(Val: Arg) && cast<ParmVarDecl>(Val: Arg)->isKNRPromoted();
3553 // We are converting from ABIArgInfo type to VarDecl type directly, unless
3554 // the parameter is promoted. In this case we convert to
3555 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3556 QualType Ty = isPromoted ? info_it->type : Arg->getType();
3557 assert(hasScalarEvaluationKind(Ty) ==
3558 hasScalarEvaluationKind(Arg->getType()));
3559
3560 unsigned FirstIRArg, NumIRArgs;
3561 std::tie(args&: FirstIRArg, args&: NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3562
3563 switch (ArgI.getKind()) {
3564 case ABIArgInfo::InAlloca: {
3565 assert(NumIRArgs == 0);
3566 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3567 Address V =
3568 Builder.CreateStructGEP(Addr: ArgStruct, Index: FieldIndex, Name: Arg->getName());
3569 if (ArgI.getInAllocaIndirect())
3570 V = Address(Builder.CreateLoad(Addr: V), ConvertTypeForMem(T: Ty),
3571 getContext().getTypeAlignInChars(T: Ty));
3572 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: V));
3573 break;
3574 }
3575
3576 case ABIArgInfo::Indirect:
3577 case ABIArgInfo::IndirectAliased: {
3578 assert(NumIRArgs == 1);
3579 Address ParamAddr = makeNaturalAddressForPointer(
3580 Ptr: Fn->getArg(i: FirstIRArg), T: Ty, Alignment: ArgI.getIndirectAlign(), ForPointeeType: false, BaseInfo: nullptr,
3581 TBAAInfo: nullptr, IsKnownNonNull: KnownNonNull);
3582
3583 if (!hasScalarEvaluationKind(T: Ty)) {
3584 // Aggregates and complex variables are accessed by reference. All we
3585 // need to do is realign the value, if requested. Also, if the address
3586 // may be aliased, copy it to ensure that the parameter variable is
3587 // mutable and has a unique adress, as C requires.
3588 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3589 RawAddress AlignedTemp = CreateMemTempWithoutCast(T: Ty, Name: "coerce");
3590
3591 // Copy from the incoming argument pointer to the temporary with the
3592 // appropriate alignment.
3593 //
3594 // FIXME: We should have a common utility for generating an aggregate
3595 // copy.
3596 CharUnits Size = getContext().getTypeSizeInChars(T: Ty);
3597 Builder.CreateMemCpy(
3598 Dst: AlignedTemp.getPointer(), DstAlign: AlignedTemp.getAlignment().getAsAlign(),
3599 Src: ParamAddr.emitRawPointer(CGF&: *this),
3600 SrcAlign: ParamAddr.getAlignment().getAsAlign(),
3601 Size: llvm::ConstantInt::get(Ty: IntPtrTy, V: Size.getQuantity()));
3602 ParamAddr = AlignedTemp;
3603 }
3604 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: ParamAddr));
3605 } else {
3606 // Load scalar value from indirect argument.
3607 llvm::Value *V =
3608 EmitLoadOfScalar(Addr: ParamAddr, Volatile: false, Ty, Loc: Arg->getBeginLoc());
3609
3610 if (isPromoted)
3611 V = emitArgumentDemotion(CGF&: *this, var: Arg, value: V);
3612 ArgVals.push_back(Elt: ParamValue::forDirect(value: V));
3613 }
3614 break;
3615 }
3616
3617 case ABIArgInfo::Extend:
3618 case ABIArgInfo::Direct: {
3619 auto AI = Fn->getArg(i: FirstIRArg);
3620 llvm::Type *LTy = ConvertType(T: Arg->getType());
3621
3622 // Prepare parameter attributes. So far, only attributes for pointer
3623 // parameters are prepared. See
3624 // http://llvm.org/docs/LangRef.html#paramattrs.
3625 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3626 ArgI.getCoerceToType()->isPointerTy()) {
3627 assert(NumIRArgs == 1);
3628
3629 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: Arg)) {
3630 // Set `nonnull` attribute if any.
3631 if (getNonNullAttr(FD: CurCodeDecl, PVD, ArgType: PVD->getType(),
3632 ArgNo: PVD->getFunctionScopeIndex()) &&
3633 !CGM.getCodeGenOpts().NullPointerIsValid)
3634 AI->addAttr(Kind: llvm::Attribute::NonNull);
3635
3636 QualType OTy = PVD->getOriginalType();
3637 if (const auto *ArrTy = getContext().getAsConstantArrayType(T: OTy)) {
3638 // A C99 array parameter declaration with the static keyword also
3639 // indicates dereferenceability, and if the size is constant we can
3640 // use the dereferenceable attribute (which requires the size in
3641 // bytes).
3642 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3643 QualType ETy = ArrTy->getElementType();
3644 llvm::Align Alignment =
3645 CGM.getNaturalTypeAlignment(T: ETy).getAsAlign();
3646 AI->addAttrs(B&: llvm::AttrBuilder(getLLVMContext())
3647 .addAlignmentAttr(Align: Alignment));
3648 uint64_t ArrSize = ArrTy->getZExtSize();
3649 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3650 ArrSize) {
3651 llvm::AttrBuilder Attrs(getLLVMContext());
3652 Attrs.addDereferenceableAttr(
3653 Bytes: getContext().getTypeSizeInChars(T: ETy).getQuantity() *
3654 ArrSize);
3655 AI->addAttrs(B&: Attrs);
3656 } else if (getContext().getTargetInfo().getNullPointerValue(
3657 AddrSpace: ETy.getAddressSpace()) == 0 &&
3658 !CGM.getCodeGenOpts().NullPointerIsValid) {
3659 AI->addAttr(Kind: llvm::Attribute::NonNull);
3660 }
3661 }
3662 } else if (const auto *ArrTy =
3663 getContext().getAsVariableArrayType(T: OTy)) {
3664 // For C99 VLAs with the static keyword, we don't know the size so
3665 // we can't use the dereferenceable attribute, but in addrspace(0)
3666 // we know that it must be nonnull.
3667 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3668 QualType ETy = ArrTy->getElementType();
3669 llvm::Align Alignment =
3670 CGM.getNaturalTypeAlignment(T: ETy).getAsAlign();
3671 AI->addAttrs(B&: llvm::AttrBuilder(getLLVMContext())
3672 .addAlignmentAttr(Align: Alignment));
3673 if (!getTypes().getTargetAddressSpace(T: ETy) &&
3674 !CGM.getCodeGenOpts().NullPointerIsValid)
3675 AI->addAttr(Kind: llvm::Attribute::NonNull);
3676 }
3677 }
3678
3679 // Set `align` attribute if any.
3680 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3681 if (!AVAttr)
3682 if (const auto *TOTy = OTy->getAs<TypedefType>())
3683 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3684 if (AVAttr && !SanOpts.has(K: SanitizerKind::Alignment)) {
3685 // If alignment-assumption sanitizer is enabled, we do *not* add
3686 // alignment attribute here, but emit normal alignment assumption,
3687 // so the UBSAN check could function.
3688 llvm::ConstantInt *AlignmentCI =
3689 cast<llvm::ConstantInt>(Val: EmitScalarExpr(E: AVAttr->getAlignment()));
3690 uint64_t AlignmentInt =
3691 AlignmentCI->getLimitedValue(Limit: llvm::Value::MaximumAlignment);
3692 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3693 AI->removeAttr(Kind: llvm::Attribute::AttrKind::Alignment);
3694 AI->addAttrs(B&: llvm::AttrBuilder(getLLVMContext())
3695 .addAlignmentAttr(Align: llvm::Align(AlignmentInt)));
3696 }
3697 }
3698 }
3699
3700 // Set 'noalias' if an argument type has the `restrict` qualifier.
3701 if (Arg->getType().isRestrictQualified())
3702 AI->addAttr(Kind: llvm::Attribute::NoAlias);
3703 }
3704
3705 // Prepare the argument value. If we have the trivial case, handle it
3706 // with no muss and fuss.
3707 if (!isa<llvm::StructType>(Val: ArgI.getCoerceToType()) &&
3708 ArgI.getCoerceToType() == ConvertType(T: Ty) &&
3709 ArgI.getDirectOffset() == 0) {
3710 assert(NumIRArgs == 1);
3711
3712 // LLVM expects swifterror parameters to be used in very restricted
3713 // ways. Copy the value into a less-restricted temporary.
3714 llvm::Value *V = AI;
3715 if (FI.getExtParameterInfo(argIndex: ArgNo).getABI() ==
3716 ParameterABI::SwiftErrorResult) {
3717 QualType pointeeTy = Ty->getPointeeType();
3718 assert(pointeeTy->isPointerType());
3719 RawAddress temp = CreateMemTempWithoutCast(
3720 T: pointeeTy, Align: getPointerAlign(), Name: "swifterror.temp");
3721 Address arg = makeNaturalAddressForPointer(
3722 Ptr: V, T: pointeeTy, Alignment: getContext().getTypeAlignInChars(T: pointeeTy));
3723 llvm::Value *incomingErrorValue = Builder.CreateLoad(Addr: arg);
3724 Builder.CreateStore(Val: incomingErrorValue, Addr: temp);
3725 V = temp.getPointer();
3726
3727 // Push a cleanup to copy the value back at the end of the function.
3728 // The convention does not guarantee that the value will be written
3729 // back if the function exits with an unwind exception.
3730 EHStack.pushCleanup<CopyBackSwiftError>(Kind: NormalCleanup, A: temp, A: arg);
3731 }
3732
3733 // Ensure the argument is the correct type.
3734 if (V->getType() != ArgI.getCoerceToType())
3735 V = Builder.CreateBitCast(V, DestTy: ArgI.getCoerceToType());
3736
3737 if (isPromoted)
3738 V = emitArgumentDemotion(CGF&: *this, var: Arg, value: V);
3739
3740 // Because of merging of function types from multiple decls it is
3741 // possible for the type of an argument to not match the corresponding
3742 // type in the function type. Since we are codegening the callee
3743 // in here, add a cast to the argument type.
3744 llvm::Type *LTy = ConvertType(T: Arg->getType());
3745 if (V->getType() != LTy)
3746 V = Builder.CreateBitCast(V, DestTy: LTy);
3747
3748 ArgVals.push_back(Elt: ParamValue::forDirect(value: V));
3749 break;
3750 }
3751
3752 // VLST arguments are coerced to VLATs at the function boundary for
3753 // ABI consistency. If this is a VLST that was coerced to
3754 // a VLAT at the function boundary and the types match up, use
3755 // llvm.vector.extract to convert back to the original VLST.
3756 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(Val: ConvertType(T: Ty))) {
3757 llvm::Value *ArgVal = Fn->getArg(i: FirstIRArg);
3758 if (auto *VecTyFrom =
3759 dyn_cast<llvm::ScalableVectorType>(Val: ArgVal->getType())) {
3760 auto [Coerced, Extracted] = CoerceScalableToFixed(
3761 CGF&: *this, ToTy: VecTyTo, FromTy: VecTyFrom, V: ArgVal, Name: Arg->getName());
3762 if (Extracted) {
3763 assert(NumIRArgs == 1);
3764 ArgVals.push_back(Elt: ParamValue::forDirect(value: Coerced));
3765 break;
3766 }
3767 }
3768 }
3769
3770 llvm::StructType *STy =
3771 dyn_cast<llvm::StructType>(Val: ArgI.getCoerceToType());
3772 Address Alloca = CreateMemTempWithoutCast(
3773 T: Ty, Align: getContext().getDeclAlign(D: Arg), Name: Arg->getName());
3774
3775 // Pointer to store into.
3776 Address Ptr = emitAddressAtOffset(CGF&: *this, addr: Alloca, info: ArgI);
3777
3778 // Fast-isel and the optimizer generally like scalar values better than
3779 // FCAs, so we flatten them if this is safe to do for this argument.
3780 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3781 STy->getNumElements() > 1) {
3782 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(Ty: STy);
3783 llvm::TypeSize PtrElementSize =
3784 CGM.getDataLayout().getTypeAllocSize(Ty: Ptr.getElementType());
3785 if (StructSize.isScalable()) {
3786 assert(STy->containsHomogeneousScalableVectorTypes() &&
3787 "ABI only supports structure with homogeneous scalable vector "
3788 "type");
3789 assert(StructSize == PtrElementSize &&
3790 "Only allow non-fractional movement of structure with"
3791 "homogeneous scalable vector type");
3792 assert(STy->getNumElements() == NumIRArgs);
3793
3794 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(T: STy);
3795 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3796 auto *AI = Fn->getArg(i: FirstIRArg + i);
3797 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3798 LoadedStructValue =
3799 Builder.CreateInsertValue(Agg: LoadedStructValue, Val: AI, Idxs: i);
3800 }
3801
3802 Builder.CreateStore(Val: LoadedStructValue, Addr: Ptr);
3803 } else {
3804 uint64_t SrcSize = StructSize.getFixedValue();
3805 uint64_t DstSize = PtrElementSize.getFixedValue();
3806
3807 Address AddrToStoreInto = Address::invalid();
3808 if (SrcSize <= DstSize) {
3809 AddrToStoreInto = Ptr.withElementType(ElemTy: STy);
3810 } else {
3811 AddrToStoreInto =
3812 CreateTempAlloca(Ty: STy, align: Alloca.getAlignment(), Name: "coerce");
3813 }
3814
3815 assert(STy->getNumElements() == NumIRArgs);
3816 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3817 auto AI = Fn->getArg(i: FirstIRArg + i);
3818 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3819 Address EltPtr = Builder.CreateStructGEP(Addr: AddrToStoreInto, Index: i);
3820 Builder.CreateStore(Val: AI, Addr: EltPtr);
3821 }
3822
3823 if (SrcSize > DstSize) {
3824 Builder.CreateMemCpy(Dest: Ptr, Src: AddrToStoreInto, Size: DstSize);
3825 }
3826
3827 // Structures with PFP fields require a coerced store to add any
3828 // pointer signatures.
3829 if (getContext().hasPFPFields(Ty)) {
3830 llvm::Value *Struct = Builder.CreateLoad(Addr: Ptr);
3831 CreatePFPCoercedStore(Src: Struct, SrcFETy: Ty, Dst: Ptr, CGF&: *this);
3832 }
3833 }
3834 } else {
3835 // Simple case, just do a coerced store of the argument into the alloca.
3836 assert(NumIRArgs == 1);
3837 auto AI = Fn->getArg(i: FirstIRArg);
3838 AI->setName(Arg->getName() + ".coerce");
3839 CreateCoercedStore(
3840 Src: AI, SrcFETy: Ty, Dst: Ptr,
3841 DstSize: llvm::TypeSize::getFixed(
3842 ExactSize: getContext().getTypeSizeInChars(T: Ty).getQuantity() -
3843 ArgI.getDirectOffset()),
3844 /*DstIsVolatile=*/false);
3845 }
3846
3847 // Match to what EmitParmDecl is expecting for this type.
3848 if (CodeGenFunction::hasScalarEvaluationKind(T: Ty)) {
3849 llvm::Value *V =
3850 EmitLoadOfScalar(Addr: Alloca, Volatile: false, Ty, Loc: Arg->getBeginLoc());
3851 if (isPromoted)
3852 V = emitArgumentDemotion(CGF&: *this, var: Arg, value: V);
3853 ArgVals.push_back(Elt: ParamValue::forDirect(value: V));
3854 } else {
3855 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: Alloca));
3856 }
3857 break;
3858 }
3859
3860 case ABIArgInfo::CoerceAndExpand: {
3861 // Reconstruct into a temporary.
3862 Address alloca =
3863 CreateMemTempWithoutCast(T: Ty, Align: getContext().getDeclAlign(D: Arg));
3864 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: alloca));
3865
3866 auto coercionType = ArgI.getCoerceAndExpandType();
3867 auto unpaddedCoercionType = ArgI.getUnpaddedCoerceAndExpandType();
3868 auto *unpaddedStruct = dyn_cast<llvm::StructType>(Val: unpaddedCoercionType);
3869
3870 alloca = alloca.withElementType(ElemTy: coercionType);
3871
3872 unsigned argIndex = FirstIRArg;
3873 unsigned unpaddedIndex = 0;
3874 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3875 llvm::Type *eltType = coercionType->getElementType(N: i);
3876 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
3877 continue;
3878
3879 auto eltAddr = Builder.CreateStructGEP(Addr: alloca, Index: i);
3880 llvm::Value *elt = Fn->getArg(i: argIndex++);
3881
3882 auto paramType = unpaddedStruct
3883 ? unpaddedStruct->getElementType(N: unpaddedIndex++)
3884 : unpaddedCoercionType;
3885
3886 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(Val: eltType)) {
3887 if (auto *VecTyFrom = dyn_cast<llvm::ScalableVectorType>(Val: paramType)) {
3888 bool Extracted;
3889 std::tie(args&: elt, args&: Extracted) = CoerceScalableToFixed(
3890 CGF&: *this, ToTy: VecTyTo, FromTy: VecTyFrom, V: elt, Name: elt->getName());
3891 assert(Extracted && "Unexpected scalable to fixed vector coercion");
3892 }
3893 }
3894 Builder.CreateStore(Val: elt, Addr: eltAddr);
3895 }
3896 assert(argIndex == FirstIRArg + NumIRArgs);
3897 break;
3898 }
3899
3900 case ABIArgInfo::Expand: {
3901 // If this structure was expanded into multiple arguments then
3902 // we need to create a temporary and reconstruct it from the
3903 // arguments.
3904 Address Alloca =
3905 CreateMemTempWithoutCast(T: Ty, Align: getContext().getDeclAlign(D: Arg));
3906 LValue LV = MakeAddrLValue(Addr: Alloca, T: Ty);
3907 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: Alloca));
3908
3909 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3910 ExpandTypeFromArgs(Ty, LV, AI&: FnArgIter);
3911 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3912 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3913 auto AI = Fn->getArg(i: FirstIRArg + i);
3914 AI->setName(Arg->getName() + "." + Twine(i));
3915 }
3916 break;
3917 }
3918
3919 case ABIArgInfo::TargetSpecific: {
3920 auto *AI = Fn->getArg(i: FirstIRArg);
3921 AI->setName(Arg->getName() + ".target_coerce");
3922 Address Alloca = CreateMemTempWithoutCast(
3923 T: Ty, Align: getContext().getDeclAlign(D: Arg), Name: Arg->getName());
3924 Address Ptr = emitAddressAtOffset(CGF&: *this, addr: Alloca, info: ArgI);
3925 CGM.getABIInfo().createCoercedStore(Val: AI, DstAddr: Ptr, AI: ArgI, DestIsVolatile: false, CGF&: *this);
3926 if (CodeGenFunction::hasScalarEvaluationKind(T: Ty)) {
3927 llvm::Value *V =
3928 EmitLoadOfScalar(Addr: Alloca, Volatile: false, Ty, Loc: Arg->getBeginLoc());
3929 if (isPromoted) {
3930 V = emitArgumentDemotion(CGF&: *this, var: Arg, value: V);
3931 }
3932 ArgVals.push_back(Elt: ParamValue::forDirect(value: V));
3933 } else {
3934 ArgVals.push_back(Elt: ParamValue::forIndirect(addr: Alloca));
3935 }
3936 break;
3937 }
3938 case ABIArgInfo::Ignore:
3939 assert(NumIRArgs == 0);
3940 // Initialize the local variable appropriately.
3941 if (!hasScalarEvaluationKind(T: Ty)) {
3942 ArgVals.push_back(
3943 Elt: ParamValue::forIndirect(addr: CreateMemTempWithoutCast(T: Ty)));
3944 } else {
3945 llvm::Value *U = llvm::UndefValue::get(T: ConvertType(T: Arg->getType()));
3946 ArgVals.push_back(Elt: ParamValue::forDirect(value: U));
3947 }
3948 break;
3949 }
3950 }
3951
3952 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3953 for (int I = Args.size() - 1; I >= 0; --I)
3954 EmitParmDecl(D: *Args[I], Arg: ArgVals[I], ArgNo: I + 1);
3955 } else {
3956 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3957 EmitParmDecl(D: *Args[I], Arg: ArgVals[I], ArgNo: I + 1);
3958 }
3959}
3960
3961static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3962 while (insn->use_empty()) {
3963 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(Val: insn);
3964 if (!bitcast)
3965 return;
3966
3967 // This is "safe" because we would have used a ConstantExpr otherwise.
3968 insn = cast<llvm::Instruction>(Val: bitcast->getOperand(i_nocapture: 0));
3969 bitcast->eraseFromParent();
3970 }
3971}
3972
3973/// Try to emit a fused autorelease of a return result.
3974static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
3975 llvm::Value *result) {
3976 // We must be immediately followed the cast.
3977 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3978 if (BB->empty())
3979 return nullptr;
3980 if (&BB->back() != result)
3981 return nullptr;
3982
3983 llvm::Type *resultType = result->getType();
3984
3985 // result is in a BasicBlock and is therefore an Instruction.
3986 llvm::Instruction *generator = cast<llvm::Instruction>(Val: result);
3987
3988 SmallVector<llvm::Instruction *, 4> InstsToKill;
3989
3990 // Look for:
3991 // %generator = bitcast %type1* %generator2 to %type2*
3992 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(Val: generator)) {
3993 // We would have emitted this as a constant if the operand weren't
3994 // an Instruction.
3995 generator = cast<llvm::Instruction>(Val: bitcast->getOperand(i_nocapture: 0));
3996
3997 // Require the generator to be immediately followed by the cast.
3998 if (generator->getNextNode() != bitcast)
3999 return nullptr;
4000
4001 InstsToKill.push_back(Elt: bitcast);
4002 }
4003
4004 // Look for:
4005 // %generator = call i8* @objc_retain(i8* %originalResult)
4006 // or
4007 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
4008 llvm::CallInst *call = dyn_cast<llvm::CallInst>(Val: generator);
4009 if (!call)
4010 return nullptr;
4011
4012 bool doRetainAutorelease;
4013
4014 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
4015 doRetainAutorelease = true;
4016 } else if (call->getCalledOperand() ==
4017 CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
4018 doRetainAutorelease = false;
4019
4020 // If we emitted an assembly marker for this call (and the
4021 // ARCEntrypoints field should have been set if so), go looking
4022 // for that call. If we can't find it, we can't do this
4023 // optimization. But it should always be the immediately previous
4024 // instruction, unless we needed bitcasts around the call.
4025 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
4026 llvm::Instruction *prev = call->getPrevNode();
4027 assert(prev);
4028 if (isa<llvm::BitCastInst>(Val: prev)) {
4029 prev = prev->getPrevNode();
4030 assert(prev);
4031 }
4032 assert(isa<llvm::CallInst>(prev));
4033 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
4034 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
4035 InstsToKill.push_back(Elt: prev);
4036 }
4037 } else {
4038 return nullptr;
4039 }
4040
4041 result = call->getArgOperand(i: 0);
4042 InstsToKill.push_back(Elt: call);
4043
4044 // Keep killing bitcasts, for sanity. Note that we no longer care
4045 // about precise ordering as long as there's exactly one use.
4046 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(Val: result)) {
4047 if (!bitcast->hasOneUse())
4048 break;
4049 InstsToKill.push_back(Elt: bitcast);
4050 result = bitcast->getOperand(i_nocapture: 0);
4051 }
4052
4053 // Delete all the unnecessary instructions, from latest to earliest.
4054 for (auto *I : InstsToKill)
4055 I->eraseFromParent();
4056
4057 // Do the fused retain/autorelease if we were asked to.
4058 if (doRetainAutorelease)
4059 result = CGF.EmitARCRetainAutoreleaseReturnValue(value: result);
4060
4061 // Cast back to the result type.
4062 return CGF.Builder.CreateBitCast(V: result, DestTy: resultType);
4063}
4064
4065/// If this is a +1 of the value of an immutable 'self', remove it.
4066static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
4067 llvm::Value *result) {
4068 // This is only applicable to a method with an immutable 'self'.
4069 const ObjCMethodDecl *method =
4070 dyn_cast_or_null<ObjCMethodDecl>(Val: CGF.CurCodeDecl);
4071 if (!method)
4072 return nullptr;
4073 const VarDecl *self = method->getSelfDecl();
4074 if (!self->getType().isConstQualified())
4075 return nullptr;
4076
4077 // Look for a retain call. Note: stripPointerCasts looks through returned arg
4078 // functions, which would cause us to miss the retain.
4079 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(Val: result);
4080 if (!retainCall || retainCall->getCalledOperand() !=
4081 CGF.CGM.getObjCEntrypoints().objc_retain)
4082 return nullptr;
4083
4084 // Look for an ordinary load of 'self'.
4085 llvm::Value *retainedValue = retainCall->getArgOperand(i: 0);
4086 llvm::LoadInst *load =
4087 dyn_cast<llvm::LoadInst>(Val: retainedValue->stripPointerCasts());
4088 if (!load || load->isAtomic() || load->isVolatile() ||
4089 load->getPointerOperand() != CGF.GetAddrOfLocalVar(VD: self).getBasePointer())
4090 return nullptr;
4091
4092 // Okay! Burn it all down. This relies for correctness on the
4093 // assumption that the retain is emitted as part of the return and
4094 // that thereafter everything is used "linearly".
4095 llvm::Type *resultType = result->getType();
4096 eraseUnusedBitCasts(insn: cast<llvm::Instruction>(Val: result));
4097 assert(retainCall->use_empty());
4098 retainCall->eraseFromParent();
4099 eraseUnusedBitCasts(insn: cast<llvm::Instruction>(Val: retainedValue));
4100
4101 return CGF.Builder.CreateBitCast(V: load, DestTy: resultType);
4102}
4103
4104/// Emit an ARC autorelease of the result of a function.
4105///
4106/// \return the value to actually return from the function
4107static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
4108 llvm::Value *result) {
4109 // If we're returning 'self', kill the initial retain. This is a
4110 // heuristic attempt to "encourage correctness" in the really unfortunate
4111 // case where we have a return of self during a dealloc and we desperately
4112 // need to avoid the possible autorelease.
4113 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
4114 return self;
4115
4116 // At -O0, try to emit a fused retain/autorelease.
4117 if (CGF.shouldUseFusedARCCalls())
4118 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
4119 return fused;
4120
4121 return CGF.EmitARCAutoreleaseReturnValue(value: result);
4122}
4123
4124/// Heuristically search for a dominating store to the return-value slot.
4125static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
4126 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
4127
4128 // Check if a User is a store which pointerOperand is the ReturnValue.
4129 // We are looking for stores to the ReturnValue, not for stores of the
4130 // ReturnValue to some other location.
4131 auto GetStoreIfValid = [&CGF,
4132 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
4133 auto *SI = dyn_cast<llvm::StoreInst>(Val: U);
4134 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
4135 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
4136 return nullptr;
4137 // These aren't actually possible for non-coerced returns, and we
4138 // only care about non-coerced returns on this code path.
4139 // All memory instructions inside __try block are volatile.
4140 assert(!SI->isAtomic() &&
4141 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
4142 return SI;
4143 };
4144 // If there are multiple uses of the return-value slot, just check
4145 // for something immediately preceding the IP. Sometimes this can
4146 // happen with how we generate implicit-returns; it can also happen
4147 // with noreturn cleanups.
4148 if (!ReturnValuePtr->hasOneUse()) {
4149 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
4150 if (IP->empty())
4151 return nullptr;
4152
4153 // Look at directly preceding instruction, skipping bitcasts, lifetime
4154 // markers, and fake uses and their operands.
4155 const llvm::Instruction *LoadIntoFakeUse = nullptr;
4156 for (llvm::Instruction &I : llvm::reverse(C&: *IP)) {
4157 // Ignore instructions that are just loads for fake uses; the load should
4158 // immediately precede the fake use, so we only need to remember the
4159 // operand for the last fake use seen.
4160 if (LoadIntoFakeUse == &I)
4161 continue;
4162 if (isa<llvm::BitCastInst>(Val: &I))
4163 continue;
4164 if (auto *II = dyn_cast<llvm::IntrinsicInst>(Val: &I)) {
4165 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
4166 continue;
4167
4168 if (II->getIntrinsicID() == llvm::Intrinsic::fake_use) {
4169 LoadIntoFakeUse = dyn_cast<llvm::Instruction>(Val: II->getArgOperand(i: 0));
4170 continue;
4171 }
4172 }
4173 return GetStoreIfValid(&I);
4174 }
4175 return nullptr;
4176 }
4177
4178 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
4179 if (!store)
4180 return nullptr;
4181
4182 // Now do a first-and-dirty dominance check: just walk up the
4183 // single-predecessors chain from the current insertion point.
4184 llvm::BasicBlock *StoreBB = store->getParent();
4185 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
4186 llvm::SmallPtrSet<llvm::BasicBlock *, 4> SeenBBs;
4187 while (IP != StoreBB) {
4188 if (!SeenBBs.insert(Ptr: IP).second || !(IP = IP->getSinglePredecessor()))
4189 return nullptr;
4190 }
4191
4192 // Okay, the store's basic block dominates the insertion point; we
4193 // can do our thing.
4194 return store;
4195}
4196
4197// Helper functions for EmitCMSEClearRecord
4198
4199// Set the bits corresponding to a field having width `BitWidth` and located at
4200// offset `BitOffset` (from the least significant bit) within a storage unit of
4201// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
4202// Use little-endian layout, i.e.`Bits[0]` is the LSB.
4203static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
4204 int BitWidth, int CharWidth) {
4205 assert(CharWidth <= 64);
4206 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
4207
4208 int Pos = 0;
4209 if (BitOffset >= CharWidth) {
4210 Pos += BitOffset / CharWidth;
4211 BitOffset = BitOffset % CharWidth;
4212 }
4213
4214 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
4215 if (BitOffset + BitWidth >= CharWidth) {
4216 Bits[Pos++] |= (Used << BitOffset) & Used;
4217 BitWidth -= CharWidth - BitOffset;
4218 BitOffset = 0;
4219 }
4220
4221 while (BitWidth >= CharWidth) {
4222 Bits[Pos++] = Used;
4223 BitWidth -= CharWidth;
4224 }
4225
4226 if (BitWidth > 0)
4227 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
4228}
4229
4230// Set the bits corresponding to a field having width `BitWidth` and located at
4231// offset `BitOffset` (from the least significant bit) within a storage unit of
4232// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
4233// `Bits` corresponds to one target byte. Use target endian layout.
4234static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
4235 int StorageSize, int BitOffset, int BitWidth,
4236 int CharWidth, bool BigEndian) {
4237
4238 SmallVector<uint64_t, 8> TmpBits(StorageSize);
4239 setBitRange(Bits&: TmpBits, BitOffset, BitWidth, CharWidth);
4240
4241 if (BigEndian)
4242 std::reverse(first: TmpBits.begin(), last: TmpBits.end());
4243
4244 for (uint64_t V : TmpBits)
4245 Bits[StorageOffset++] |= V;
4246}
4247
4248static void setUsedBits(CodeGenModule &, QualType, int,
4249 SmallVectorImpl<uint64_t> &);
4250
4251// Set the bits in `Bits`, which correspond to the value representations of
4252// the actual members of the record type `RTy`. Note that this function does
4253// not handle base classes, virtual tables, etc, since they cannot happen in
4254// CMSE function arguments or return. The bit mask corresponds to the target
4255// memory layout, i.e. it's endian dependent.
4256static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
4257 SmallVectorImpl<uint64_t> &Bits) {
4258 ASTContext &Context = CGM.getContext();
4259 int CharWidth = Context.getCharWidth();
4260 const RecordDecl *RD = RTy->getDecl()->getDefinition();
4261 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(D: RD);
4262 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
4263
4264 int Idx = 0;
4265 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
4266 const FieldDecl *F = *I;
4267
4268 if (F->isUnnamedBitField() || F->isZeroLengthBitField() ||
4269 F->getType()->isIncompleteArrayType())
4270 continue;
4271
4272 if (F->isBitField()) {
4273 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(FD: F);
4274 setBitRange(Bits, StorageOffset: Offset + BFI.StorageOffset.getQuantity(),
4275 StorageSize: BFI.StorageSize / CharWidth, BitOffset: BFI.Offset, BitWidth: BFI.Size, CharWidth,
4276 BigEndian: CGM.getDataLayout().isBigEndian());
4277 continue;
4278 }
4279
4280 setUsedBits(CGM, F->getType(),
4281 Offset + ASTLayout.getFieldOffset(FieldNo: Idx) / CharWidth, Bits);
4282 }
4283}
4284
4285// Set the bits in `Bits`, which correspond to the value representations of
4286// the elements of an array type `ATy`.
4287static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
4288 int Offset, SmallVectorImpl<uint64_t> &Bits) {
4289 const ASTContext &Context = CGM.getContext();
4290
4291 QualType ETy = Context.getBaseElementType(VAT: ATy);
4292 int Size = Context.getTypeSizeInChars(T: ETy).getQuantity();
4293 SmallVector<uint64_t, 4> TmpBits(Size);
4294 setUsedBits(CGM, ETy, 0, TmpBits);
4295
4296 for (int I = 0, N = Context.getConstantArrayElementCount(CA: ATy); I < N; ++I) {
4297 auto Src = TmpBits.begin();
4298 auto Dst = Bits.begin() + Offset + I * Size;
4299 for (int J = 0; J < Size; ++J)
4300 *Dst++ |= *Src++;
4301 }
4302}
4303
4304// Set the bits in `Bits`, which correspond to the value representations of
4305// the type `QTy`.
4306static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
4307 SmallVectorImpl<uint64_t> &Bits) {
4308 if (const auto *RTy = QTy->getAsCanonical<RecordType>())
4309 return setUsedBits(CGM, RTy, Offset, Bits);
4310
4311 ASTContext &Context = CGM.getContext();
4312 if (const auto *ATy = Context.getAsConstantArrayType(T: QTy))
4313 return setUsedBits(CGM, ATy, Offset, Bits);
4314
4315 int Size = Context.getTypeSizeInChars(T: QTy).getQuantity();
4316 if (Size <= 0)
4317 return;
4318
4319 std::fill_n(first: Bits.begin() + Offset, n: Size,
4320 value: (uint64_t(1) << Context.getCharWidth()) - 1);
4321}
4322
4323static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
4324 int Pos, int Size, int CharWidth,
4325 bool BigEndian) {
4326 assert(Size > 0);
4327 uint64_t Mask = 0;
4328 if (BigEndian) {
4329 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
4330 ++P)
4331 Mask = (Mask << CharWidth) | *P;
4332 } else {
4333 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
4334 do
4335 Mask = (Mask << CharWidth) | *--P;
4336 while (P != End);
4337 }
4338 return Mask;
4339}
4340
4341// Emit code to clear the bits in a record, which aren't a part of any user
4342// declared member, when the record is a function return.
4343llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
4344 llvm::IntegerType *ITy,
4345 QualType QTy) {
4346 assert(Src->getType() == ITy);
4347 assert(ITy->getScalarSizeInBits() <= 64);
4348
4349 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
4350 int Size = DataLayout.getTypeStoreSize(Ty: ITy);
4351 SmallVector<uint64_t, 4> Bits(Size);
4352 setUsedBits(CGM, RTy: QTy->castAsCanonical<RecordType>(), Offset: 0, Bits);
4353
4354 int CharWidth = CGM.getContext().getCharWidth();
4355 uint64_t Mask =
4356 buildMultiCharMask(Bits, Pos: 0, Size, CharWidth, BigEndian: DataLayout.isBigEndian());
4357
4358 return Builder.CreateAnd(LHS: Src, RHS: Mask, Name: "cmse.clear");
4359}
4360
4361// Emit code to clear the bits in a record, which aren't a part of any user
4362// declared member, when the record is a function argument.
4363llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
4364 llvm::ArrayType *ATy,
4365 QualType QTy) {
4366 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
4367 int Size = DataLayout.getTypeStoreSize(Ty: ATy);
4368 SmallVector<uint64_t, 16> Bits(Size);
4369 setUsedBits(CGM, RTy: QTy->castAsCanonical<RecordType>(), Offset: 0, Bits);
4370
4371 // Clear each element of the LLVM array.
4372 int CharWidth = CGM.getContext().getCharWidth();
4373 int CharsPerElt =
4374 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
4375 int MaskIndex = 0;
4376 llvm::Value *R = llvm::PoisonValue::get(T: ATy);
4377 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
4378 uint64_t Mask = buildMultiCharMask(Bits, Pos: MaskIndex, Size: CharsPerElt, CharWidth,
4379 BigEndian: DataLayout.isBigEndian());
4380 MaskIndex += CharsPerElt;
4381 llvm::Value *T0 = Builder.CreateExtractValue(Agg: Src, Idxs: I);
4382 llvm::Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Mask, Name: "cmse.clear");
4383 R = Builder.CreateInsertValue(Agg: R, Val: T1, Idxs: I);
4384 }
4385
4386 return R;
4387}
4388
4389void CodeGenFunction::EmitFunctionEpilog(
4390 const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc,
4391 uint64_t RetKeyInstructionsSourceAtom) {
4392 if (FI.isNoReturn()) {
4393 // Noreturn functions don't return.
4394 EmitUnreachable(Loc: EndLoc);
4395 return;
4396 }
4397
4398 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
4399 // Naked functions don't have epilogues.
4400 Builder.CreateUnreachable();
4401 return;
4402 }
4403
4404 // Functions with no result always return void.
4405 if (!ReturnValue.isValid()) {
4406 auto *I = Builder.CreateRetVoid();
4407 if (RetKeyInstructionsSourceAtom)
4408 addInstToSpecificSourceAtom(KeyInstruction: I, Backup: nullptr, Atom: RetKeyInstructionsSourceAtom);
4409 else
4410 addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr);
4411 return;
4412 }
4413
4414 llvm::DebugLoc RetDbgLoc;
4415 llvm::Value *RV = nullptr;
4416 QualType RetTy = FI.getReturnType();
4417 const ABIArgInfo &RetAI = FI.getReturnInfo();
4418
4419 switch (RetAI.getKind()) {
4420 case ABIArgInfo::InAlloca:
4421 // Aggregates get evaluated directly into the destination. Sometimes we
4422 // need to return the sret value in a register, though.
4423 assert(hasAggregateEvaluationKind(RetTy));
4424 if (RetAI.getInAllocaSRet()) {
4425 llvm::Function::arg_iterator EI = CurFn->arg_end();
4426 --EI;
4427 llvm::Value *ArgStruct = &*EI;
4428 llvm::Value *SRet = Builder.CreateStructGEP(
4429 Ty: FI.getArgStruct(), Ptr: ArgStruct, Idx: RetAI.getInAllocaFieldIndex());
4430 llvm::Type *Ty =
4431 cast<llvm::GetElementPtrInst>(Val: SRet)->getResultElementType();
4432 RV = Builder.CreateAlignedLoad(Ty, Addr: SRet, Align: getPointerAlign(), Name: "sret");
4433 }
4434 break;
4435
4436 case ABIArgInfo::Indirect: {
4437 auto AI = CurFn->arg_begin();
4438 if (RetAI.isSRetAfterThis())
4439 ++AI;
4440 switch (getEvaluationKind(T: RetTy)) {
4441 case TEK_Complex: {
4442 ComplexPairTy RT =
4443 EmitLoadOfComplex(src: MakeAddrLValue(Addr: ReturnValue, T: RetTy), loc: EndLoc);
4444 EmitStoreOfComplex(V: RT, dest: MakeNaturalAlignAddrLValue(V: &*AI, T: RetTy),
4445 /*isInit*/ true);
4446 break;
4447 }
4448 case TEK_Aggregate:
4449 // Do nothing; aggregates get evaluated directly into the destination.
4450 break;
4451 case TEK_Scalar: {
4452 LValueBaseInfo BaseInfo;
4453 TBAAAccessInfo TBAAInfo;
4454 CharUnits Alignment =
4455 CGM.getNaturalTypeAlignment(T: RetTy, BaseInfo: &BaseInfo, TBAAInfo: &TBAAInfo);
4456 Address ArgAddr(&*AI, ConvertType(T: RetTy), Alignment);
4457 LValue ArgVal =
4458 LValue::MakeAddr(Addr: ArgAddr, type: RetTy, Context&: getContext(), BaseInfo, TBAAInfo);
4459 EmitStoreOfScalar(
4460 value: EmitLoadOfScalar(lvalue: MakeAddrLValue(Addr: ReturnValue, T: RetTy), Loc: EndLoc), lvalue: ArgVal,
4461 /*isInit*/ true);
4462 break;
4463 }
4464 }
4465 break;
4466 }
4467
4468 case ABIArgInfo::Extend:
4469 case ABIArgInfo::Direct:
4470 if (RetAI.getCoerceToType() == ConvertType(T: RetTy) &&
4471 RetAI.getDirectOffset() == 0) {
4472 // The internal return value temp always will have pointer-to-return-type
4473 // type, just do a load.
4474
4475 // If there is a dominating store to ReturnValue, we can elide
4476 // the load, zap the store, and usually zap the alloca.
4477 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(CGF&: *this)) {
4478 // Reuse the debug location from the store unless there is
4479 // cleanup code to be emitted between the store and return
4480 // instruction.
4481 if (EmitRetDbgLoc && !AutoreleaseResult)
4482 RetDbgLoc = SI->getDebugLoc();
4483 // Get the stored value and nuke the now-dead store.
4484 RV = SI->getValueOperand();
4485 SI->eraseFromParent();
4486
4487 // Otherwise, we have to do a simple load.
4488 } else {
4489 RV = Builder.CreateLoad(Addr: ReturnValue);
4490 }
4491 } else {
4492 // If the value is offset in memory, apply the offset now.
4493 Address V = emitAddressAtOffset(CGF&: *this, addr: ReturnValue, info: RetAI);
4494
4495 RV = CreateCoercedLoad(Src: V, SrcFETy: RetTy, Ty: RetAI.getCoerceToType(), CGF&: *this);
4496 }
4497
4498 // In ARC, end functions that return a retainable type with a call
4499 // to objc_autoreleaseReturnValue.
4500 if (AutoreleaseResult) {
4501#ifndef NDEBUG
4502 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
4503 // been stripped of the typedefs, so we cannot use RetTy here. Get the
4504 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
4505 // CurCodeDecl or BlockInfo.
4506 QualType RT;
4507
4508 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
4509 RT = FD->getReturnType();
4510 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
4511 RT = MD->getReturnType();
4512 else if (isa<BlockDecl>(CurCodeDecl))
4513 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
4514 else
4515 llvm_unreachable("Unexpected function/method type");
4516
4517 assert(getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() &&
4518 RT->isObjCRetainableType());
4519#endif
4520 RV = emitAutoreleaseOfResult(CGF&: *this, result: RV);
4521 }
4522
4523 break;
4524
4525 case ABIArgInfo::Ignore:
4526 break;
4527
4528 case ABIArgInfo::CoerceAndExpand: {
4529 auto coercionType = RetAI.getCoerceAndExpandType();
4530 auto unpaddedCoercionType = RetAI.getUnpaddedCoerceAndExpandType();
4531 auto *unpaddedStruct = dyn_cast<llvm::StructType>(Val: unpaddedCoercionType);
4532
4533 // Load all of the coerced elements out into results.
4534 llvm::SmallVector<llvm::Value *, 4> results;
4535 Address addr = ReturnValue.withElementType(ElemTy: coercionType);
4536 unsigned unpaddedIndex = 0;
4537 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4538 auto coercedEltType = coercionType->getElementType(N: i);
4539 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType: coercedEltType))
4540 continue;
4541
4542 auto eltAddr = Builder.CreateStructGEP(Addr: addr, Index: i);
4543 llvm::Value *elt = CreateCoercedLoad(
4544 Src: eltAddr, SrcFETy: RetTy,
4545 Ty: unpaddedStruct ? unpaddedStruct->getElementType(N: unpaddedIndex++)
4546 : unpaddedCoercionType,
4547 CGF&: *this);
4548 results.push_back(Elt: elt);
4549 }
4550
4551 // If we have one result, it's the single direct result type.
4552 if (results.size() == 1) {
4553 RV = results[0];
4554
4555 // Otherwise, we need to make a first-class aggregate.
4556 } else {
4557 // Construct a return type that lacks padding elements.
4558 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
4559
4560 RV = llvm::PoisonValue::get(T: returnType);
4561 for (unsigned i = 0, e = results.size(); i != e; ++i) {
4562 RV = Builder.CreateInsertValue(Agg: RV, Val: results[i], Idxs: i);
4563 }
4564 }
4565 break;
4566 }
4567 case ABIArgInfo::TargetSpecific: {
4568 Address V = emitAddressAtOffset(CGF&: *this, addr: ReturnValue, info: RetAI);
4569 RV = CGM.getABIInfo().createCoercedLoad(SrcAddr: V, AI: RetAI, CGF&: *this);
4570 break;
4571 }
4572 case ABIArgInfo::Expand:
4573 case ABIArgInfo::IndirectAliased:
4574 llvm_unreachable("Invalid ABI kind for return argument");
4575 }
4576
4577 llvm::Instruction *Ret;
4578 if (RV) {
4579 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
4580 // For certain return types, clear padding bits, as they may reveal
4581 // sensitive information.
4582 // Small struct/union types are passed as integers.
4583 auto *ITy = dyn_cast<llvm::IntegerType>(Val: RV->getType());
4584 if (ITy != nullptr && isa<RecordType>(Val: RetTy.getCanonicalType()))
4585 RV = EmitCMSEClearRecord(Src: RV, ITy, QTy: RetTy);
4586 }
4587 EmitReturnValueCheck(RV);
4588 Ret = Builder.CreateRet(V: RV);
4589 } else {
4590 Ret = Builder.CreateRetVoid();
4591 }
4592
4593 if (RetDbgLoc)
4594 Ret->setDebugLoc(std::move(RetDbgLoc));
4595
4596 llvm::Value *Backup = RV ? Ret->getOperand(i: 0) : nullptr;
4597 if (RetKeyInstructionsSourceAtom)
4598 addInstToSpecificSourceAtom(KeyInstruction: Ret, Backup, Atom: RetKeyInstructionsSourceAtom);
4599 else
4600 addInstToNewSourceAtom(KeyInstruction: Ret, Backup);
4601}
4602
4603void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
4604 // A current decl may not be available when emitting vtable thunks.
4605 if (!CurCodeDecl)
4606 return;
4607
4608 // If the return block isn't reachable, neither is this check, so don't emit
4609 // it.
4610 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
4611 return;
4612
4613 ReturnsNonNullAttr *RetNNAttr = nullptr;
4614 if (SanOpts.has(K: SanitizerKind::ReturnsNonnullAttribute))
4615 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4616
4617 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4618 return;
4619
4620 // Prefer the returns_nonnull attribute if it's present.
4621 SourceLocation AttrLoc;
4622 SanitizerKind::SanitizerOrdinal CheckKind;
4623 SanitizerHandler Handler;
4624 if (RetNNAttr) {
4625 assert(!requiresReturnValueNullabilityCheck() &&
4626 "Cannot check nullability and the nonnull attribute");
4627 AttrLoc = RetNNAttr->getLocation();
4628 CheckKind = SanitizerKind::SO_ReturnsNonnullAttribute;
4629 Handler = SanitizerHandler::NonnullReturn;
4630 } else {
4631 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: CurCodeDecl))
4632 if (auto *TSI = DD->getTypeSourceInfo())
4633 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4634 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4635 CheckKind = SanitizerKind::SO_NullabilityReturn;
4636 Handler = SanitizerHandler::NullabilityReturn;
4637 }
4638
4639 SanitizerDebugLocation SanScope(this, {CheckKind}, Handler);
4640
4641 // Make sure the "return" source location is valid. If we're checking a
4642 // nullability annotation, make sure the preconditions for the check are met.
4643 llvm::BasicBlock *Check = createBasicBlock(name: "nullcheck");
4644 llvm::BasicBlock *NoCheck = createBasicBlock(name: "no.nullcheck");
4645 llvm::Value *SLocPtr = Builder.CreateLoad(Addr: ReturnLocation, Name: "return.sloc.load");
4646 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(Arg: SLocPtr);
4647 if (requiresReturnValueNullabilityCheck())
4648 CanNullCheck =
4649 Builder.CreateAnd(LHS: CanNullCheck, RHS: RetValNullabilityPrecondition);
4650 Builder.CreateCondBr(Cond: CanNullCheck, True: Check, False: NoCheck);
4651 EmitBlock(BB: Check);
4652
4653 // Now do the null check.
4654 llvm::Value *Cond = Builder.CreateIsNotNull(Arg: RV);
4655 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc: AttrLoc)};
4656 llvm::Value *DynamicData[] = {SLocPtr};
4657 EmitCheck(Checked: std::make_pair(x&: Cond, y&: CheckKind), Check: Handler, StaticArgs: StaticData, DynamicArgs: DynamicData);
4658
4659 EmitBlock(BB: NoCheck);
4660
4661#ifndef NDEBUG
4662 // The return location should not be used after the check has been emitted.
4663 ReturnLocation = Address::invalid();
4664#endif
4665}
4666
4667static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
4668 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4669 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4670}
4671
4672static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
4673 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4674 // placeholders.
4675 llvm::Type *IRTy = CGF.ConvertTypeForMem(T: Ty);
4676 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(C&: CGF.getLLVMContext());
4677 llvm::Value *Placeholder = llvm::PoisonValue::get(T: IRPtrTy);
4678
4679 // FIXME: When we generate this IR in one pass, we shouldn't need
4680 // this win32-specific alignment hack.
4681 CharUnits Align = CharUnits::fromQuantity(Quantity: 4);
4682 Placeholder = CGF.Builder.CreateAlignedLoad(Ty: IRPtrTy, Addr: Placeholder, Align);
4683
4684 return AggValueSlot::forAddr(
4685 addr: Address(Placeholder, IRTy, Align), quals: Ty.getQualifiers(),
4686 isDestructed: AggValueSlot::IsNotDestructed, needsGC: AggValueSlot::DoesNotNeedGCBarriers,
4687 isAliased: AggValueSlot::IsNotAliased, mayOverlap: AggValueSlot::DoesNotOverlap);
4688}
4689
4690void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
4691 const VarDecl *param,
4692 SourceLocation loc) {
4693 // StartFunction converted the ABI-lowered parameter(s) into a
4694 // local alloca. We need to turn that into an r-value suitable
4695 // for EmitCall.
4696 Address local = GetAddrOfLocalVar(VD: param);
4697
4698 QualType type = param->getType();
4699
4700 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4701 // but the argument needs to be the original pointer.
4702 if (type->isReferenceType()) {
4703 args.add(rvalue: RValue::get(V: Builder.CreateLoad(Addr: local)), type);
4704
4705 // In ARC, move out of consumed arguments so that the release cleanup
4706 // entered by StartFunction doesn't cause an over-release. This isn't
4707 // optimal -O0 code generation, but it should get cleaned up when
4708 // optimization is enabled. This also assumes that delegate calls are
4709 // performed exactly once for a set of arguments, but that should be safe.
4710 } else if (getLangOpts().ObjCAutoRefCount &&
4711 param->hasAttr<NSConsumedAttr>() && type->isObjCRetainableType()) {
4712 llvm::Value *ptr = Builder.CreateLoad(Addr: local);
4713 auto null =
4714 llvm::ConstantPointerNull::get(T: cast<llvm::PointerType>(Val: ptr->getType()));
4715 Builder.CreateStore(Val: null, Addr: local);
4716 args.add(rvalue: RValue::get(V: ptr), type);
4717
4718 // For the most part, we just need to load the alloca, except that
4719 // aggregate r-values are actually pointers to temporaries.
4720 } else {
4721 args.add(rvalue: convertTempToRValue(addr: local, type, Loc: loc), type);
4722 }
4723
4724 // Deactivate the cleanup for the callee-destructed param that was pushed.
4725 if (type->isRecordType() && !CurFuncIsThunk &&
4726 type->castAsRecordDecl()->isParamDestroyedInCallee() &&
4727 param->needsDestruction(Ctx: getContext())) {
4728 EHScopeStack::stable_iterator cleanup =
4729 CalleeDestructedParamCleanups.lookup(Val: cast<ParmVarDecl>(Val: param));
4730 assert(cleanup.isValid() &&
4731 "cleanup for callee-destructed param not recorded");
4732 // This unreachable is a temporary marker which will be removed later.
4733 llvm::Instruction *isActive = Builder.CreateUnreachable();
4734 args.addArgCleanupDeactivation(Cleanup: cleanup, IsActiveIP: isActive);
4735 }
4736}
4737
4738static bool isProvablyNull(llvm::Value *addr) {
4739 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(Val: addr);
4740}
4741
4742static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF) {
4743 return llvm::isKnownNonZero(V: Addr.getBasePointer(), Q: CGF.CGM.getDataLayout());
4744}
4745
4746/// Emit the actual writing-back of a writeback.
4747static void emitWriteback(CodeGenFunction &CGF,
4748 const CallArgList::Writeback &writeback) {
4749 const LValue &srcLV = writeback.Source;
4750 Address srcAddr = srcLV.getAddress();
4751 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4752 "shouldn't have writeback for provably null argument");
4753
4754 if (writeback.WritebackExpr) {
4755 CGF.EmitIgnoredExpr(E: writeback.WritebackExpr);
4756 CGF.EmitLifetimeEnd(Addr: writeback.Temporary.getBasePointer());
4757 return;
4758 }
4759
4760 llvm::BasicBlock *contBB = nullptr;
4761
4762 // If the argument wasn't provably non-null, we need to null check
4763 // before doing the store.
4764 bool provablyNonNull = isProvablyNonNull(Addr: srcAddr, CGF);
4765
4766 if (!provablyNonNull) {
4767 llvm::BasicBlock *writebackBB = CGF.createBasicBlock(name: "icr.writeback");
4768 contBB = CGF.createBasicBlock(name: "icr.done");
4769
4770 llvm::Value *isNull = CGF.Builder.CreateIsNull(Addr: srcAddr, Name: "icr.isnull");
4771 CGF.Builder.CreateCondBr(Cond: isNull, True: contBB, False: writebackBB);
4772 CGF.EmitBlock(BB: writebackBB);
4773 }
4774
4775 // Load the value to writeback.
4776 llvm::Value *value = CGF.Builder.CreateLoad(Addr: writeback.Temporary);
4777
4778 // Cast it back, in case we're writing an id to a Foo* or something.
4779 value = CGF.Builder.CreateBitCast(V: value, DestTy: srcAddr.getElementType(),
4780 Name: "icr.writeback-cast");
4781
4782 // Perform the writeback.
4783
4784 // If we have a "to use" value, it's something we need to emit a use
4785 // of. This has to be carefully threaded in: if it's done after the
4786 // release it's potentially undefined behavior (and the optimizer
4787 // will ignore it), and if it happens before the retain then the
4788 // optimizer could move the release there.
4789 if (writeback.ToUse) {
4790 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4791
4792 // Retain the new value. No need to block-copy here: the block's
4793 // being passed up the stack.
4794 value = CGF.EmitARCRetainNonBlock(value);
4795
4796 // Emit the intrinsic use here.
4797 CGF.EmitARCIntrinsicUse(values: writeback.ToUse);
4798
4799 // Load the old value (primitively).
4800 llvm::Value *oldValue = CGF.EmitLoadOfScalar(lvalue: srcLV, Loc: SourceLocation());
4801
4802 // Put the new value in place (primitively).
4803 CGF.EmitStoreOfScalar(value, lvalue: srcLV, /*init*/ isInit: false);
4804
4805 // Release the old value.
4806 CGF.EmitARCRelease(value: oldValue, precise: srcLV.isARCPreciseLifetime());
4807
4808 // Otherwise, we can just do a normal lvalue store.
4809 } else {
4810 CGF.EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: srcLV);
4811 }
4812
4813 // Jump to the continuation block.
4814 if (!provablyNonNull)
4815 CGF.EmitBlock(BB: contBB);
4816}
4817
4818static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
4819 const CallArgList &CallArgs) {
4820 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
4821 CallArgs.getCleanupsToDeactivate();
4822 // Iterate in reverse to increase the likelihood of popping the cleanup.
4823 for (const auto &I : llvm::reverse(C&: Cleanups)) {
4824 CGF.DeactivateCleanupBlock(Cleanup: I.Cleanup, DominatingIP: I.IsActiveIP);
4825 I.IsActiveIP->eraseFromParent();
4826 }
4827}
4828
4829static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4830 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(Val: E->IgnoreParens()))
4831 if (uop->getOpcode() == UO_AddrOf)
4832 return uop->getSubExpr();
4833 return nullptr;
4834}
4835
4836/// Emit an argument that's being passed call-by-writeback. That is,
4837/// we are passing the address of an __autoreleased temporary; it
4838/// might be copy-initialized with the current value of the given
4839/// address, but it will definitely be copied out of after the call.
4840static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
4841 const ObjCIndirectCopyRestoreExpr *CRE) {
4842 LValue srcLV;
4843
4844 // Make an optimistic effort to emit the address as an l-value.
4845 // This can fail if the argument expression is more complicated.
4846 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(E: CRE->getSubExpr())) {
4847 srcLV = CGF.EmitLValue(E: lvExpr);
4848
4849 // Otherwise, just emit it as a scalar.
4850 } else {
4851 Address srcAddr = CGF.EmitPointerWithAlignment(Addr: CRE->getSubExpr());
4852
4853 QualType srcAddrType =
4854 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
4855 srcLV = CGF.MakeAddrLValue(Addr: srcAddr, T: srcAddrType);
4856 }
4857 Address srcAddr = srcLV.getAddress();
4858
4859 // The dest and src types don't necessarily match in LLVM terms
4860 // because of the crazy ObjC compatibility rules.
4861
4862 llvm::PointerType *destType =
4863 cast<llvm::PointerType>(Val: CGF.ConvertType(T: CRE->getType()));
4864 llvm::Type *destElemType =
4865 CGF.ConvertTypeForMem(T: CRE->getType()->getPointeeType());
4866
4867 // If the address is a constant null, just pass the appropriate null.
4868 if (isProvablyNull(addr: srcAddr.getBasePointer())) {
4869 args.add(rvalue: RValue::get(V: llvm::ConstantPointerNull::get(T: destType)),
4870 type: CRE->getType());
4871 return;
4872 }
4873
4874 // Create the temporary.
4875 Address temp =
4876 CGF.CreateTempAlloca(Ty: destElemType, align: CGF.getPointerAlign(), Name: "icr.temp");
4877 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4878 // and that cleanup will be conditional if we can't prove that the l-value
4879 // isn't null, so we need to register a dominating point so that the cleanups
4880 // system will make valid IR.
4881 CodeGenFunction::ConditionalEvaluation condEval(CGF);
4882
4883 // Zero-initialize it if we're not doing a copy-initialization.
4884 bool shouldCopy = CRE->shouldCopy();
4885 if (!shouldCopy) {
4886 llvm::Value *null =
4887 llvm::ConstantPointerNull::get(T: cast<llvm::PointerType>(Val: destElemType));
4888 CGF.Builder.CreateStore(Val: null, Addr: temp);
4889 }
4890
4891 llvm::BasicBlock *contBB = nullptr;
4892 llvm::BasicBlock *originBB = nullptr;
4893
4894 // If the address is *not* known to be non-null, we need to switch.
4895 llvm::Value *finalArgument;
4896
4897 bool provablyNonNull = isProvablyNonNull(Addr: srcAddr, CGF);
4898
4899 if (provablyNonNull) {
4900 finalArgument = temp.emitRawPointer(CGF);
4901 } else {
4902 llvm::Value *isNull = CGF.Builder.CreateIsNull(Addr: srcAddr, Name: "icr.isnull");
4903
4904 finalArgument = CGF.Builder.CreateSelect(
4905 C: isNull, True: llvm::ConstantPointerNull::get(T: destType),
4906 False: temp.emitRawPointer(CGF), Name: "icr.argument");
4907
4908 // If we need to copy, then the load has to be conditional, which
4909 // means we need control flow.
4910 if (shouldCopy) {
4911 originBB = CGF.Builder.GetInsertBlock();
4912 contBB = CGF.createBasicBlock(name: "icr.cont");
4913 llvm::BasicBlock *copyBB = CGF.createBasicBlock(name: "icr.copy");
4914 CGF.Builder.CreateCondBr(Cond: isNull, True: contBB, False: copyBB);
4915 CGF.EmitBlock(BB: copyBB);
4916 condEval.begin(CGF);
4917 }
4918 }
4919
4920 llvm::Value *valueToUse = nullptr;
4921
4922 // Perform a copy if necessary.
4923 if (shouldCopy) {
4924 RValue srcRV = CGF.EmitLoadOfLValue(V: srcLV, Loc: SourceLocation());
4925 assert(srcRV.isScalar());
4926
4927 llvm::Value *src = srcRV.getScalarVal();
4928 src = CGF.Builder.CreateBitCast(V: src, DestTy: destElemType, Name: "icr.cast");
4929
4930 // Use an ordinary store, not a store-to-lvalue.
4931 CGF.Builder.CreateStore(Val: src, Addr: temp);
4932
4933 // If optimization is enabled, and the value was held in a
4934 // __strong variable, we need to tell the optimizer that this
4935 // value has to stay alive until we're doing the store back.
4936 // This is because the temporary is effectively unretained,
4937 // and so otherwise we can violate the high-level semantics.
4938 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4939 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
4940 valueToUse = src;
4941 }
4942 }
4943
4944 // Finish the control flow if we needed it.
4945 if (shouldCopy && !provablyNonNull) {
4946 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4947 CGF.EmitBlock(BB: contBB);
4948
4949 // Make a phi for the value to intrinsically use.
4950 if (valueToUse) {
4951 llvm::PHINode *phiToUse =
4952 CGF.Builder.CreatePHI(Ty: valueToUse->getType(), NumReservedValues: 2, Name: "icr.to-use");
4953 phiToUse->addIncoming(V: valueToUse, BB: copyBB);
4954 phiToUse->addIncoming(V: llvm::PoisonValue::get(T: valueToUse->getType()),
4955 BB: originBB);
4956 valueToUse = phiToUse;
4957 }
4958
4959 condEval.end(CGF);
4960 }
4961
4962 args.addWriteback(srcLV, temporary: temp, toUse: valueToUse);
4963 args.add(rvalue: RValue::get(V: finalArgument), type: CRE->getType());
4964}
4965
4966void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
4967 assert(!StackBase);
4968
4969 // Save the stack.
4970 StackBase = CGF.Builder.CreateStackSave(Name: "inalloca.save");
4971}
4972
4973void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
4974 if (StackBase) {
4975 // Restore the stack after the call.
4976 CGF.Builder.CreateStackRestore(Ptr: StackBase);
4977 }
4978}
4979
4980void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
4981 SourceLocation ArgLoc,
4982 AbstractCallee AC, unsigned ParmNum) {
4983 if (!AC.getDecl() || !(SanOpts.has(K: SanitizerKind::NonnullAttribute) ||
4984 SanOpts.has(K: SanitizerKind::NullabilityArg)))
4985 return;
4986
4987 // The param decl may be missing in a variadic function.
4988 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(I: ParmNum) : nullptr;
4989 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4990
4991 // Prefer the nonnull attribute if it's present.
4992 const NonNullAttr *NNAttr = nullptr;
4993 if (SanOpts.has(K: SanitizerKind::NonnullAttribute))
4994 NNAttr = getNonNullAttr(FD: AC.getDecl(), PVD, ArgType, ArgNo);
4995
4996 bool CanCheckNullability = false;
4997 if (SanOpts.has(K: SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4998 !PVD->getType()->isRecordType()) {
4999 auto Nullability = PVD->getType()->getNullability();
5000 CanCheckNullability = Nullability &&
5001 *Nullability == NullabilityKind::NonNull &&
5002 PVD->getTypeSourceInfo();
5003 }
5004
5005 if (!NNAttr && !CanCheckNullability)
5006 return;
5007
5008 SourceLocation AttrLoc;
5009 SanitizerKind::SanitizerOrdinal CheckKind;
5010 SanitizerHandler Handler;
5011 if (NNAttr) {
5012 AttrLoc = NNAttr->getLocation();
5013 CheckKind = SanitizerKind::SO_NonnullAttribute;
5014 Handler = SanitizerHandler::NonnullArg;
5015 } else {
5016 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
5017 CheckKind = SanitizerKind::SO_NullabilityArg;
5018 Handler = SanitizerHandler::NullabilityArg;
5019 }
5020
5021 SanitizerDebugLocation SanScope(this, {CheckKind}, Handler);
5022 llvm::Value *Cond = EmitNonNullRValueCheck(RV, T: ArgType);
5023 llvm::Constant *StaticData[] = {
5024 EmitCheckSourceLocation(Loc: ArgLoc),
5025 EmitCheckSourceLocation(Loc: AttrLoc),
5026 llvm::ConstantInt::get(Ty: Int32Ty, V: ArgNo + 1),
5027 };
5028 EmitCheck(Checked: std::make_pair(x&: Cond, y&: CheckKind), Check: Handler, StaticArgs: StaticData, DynamicArgs: {});
5029}
5030
5031void CodeGenFunction::EmitNonNullArgCheck(Address Addr, QualType ArgType,
5032 SourceLocation ArgLoc,
5033 AbstractCallee AC, unsigned ParmNum) {
5034 if (!AC.getDecl() || !(SanOpts.has(K: SanitizerKind::NonnullAttribute) ||
5035 SanOpts.has(K: SanitizerKind::NullabilityArg)))
5036 return;
5037
5038 EmitNonNullArgCheck(RV: RValue::get(Addr, CGF&: *this), ArgType, ArgLoc, AC, ParmNum);
5039}
5040
5041// Check if the call is going to use the inalloca convention. This needs to
5042// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
5043// later, so we can't check it directly.
5044static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
5045 ArrayRef<QualType> ArgTypes) {
5046 // The Swift calling conventions don't go through the target-specific
5047 // argument classification, they never use inalloca.
5048 // TODO: Consider limiting inalloca use to only calling conventions supported
5049 // by MSVC.
5050 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
5051 return false;
5052 if (!CGM.getTarget().getCXXABI().isMicrosoft())
5053 return false;
5054 return llvm::any_of(Range&: ArgTypes, P: [&](QualType Ty) {
5055 return isInAllocaArgument(ABI&: CGM.getCXXABI(), type: Ty);
5056 });
5057}
5058
5059#ifndef NDEBUG
5060// Determine whether the given argument is an Objective-C method
5061// that may have type parameters in its signature.
5062static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
5063 const DeclContext *dc = method->getDeclContext();
5064 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
5065 return classDecl->getTypeParamListAsWritten();
5066 }
5067
5068 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
5069 return catDecl->getTypeParamList();
5070 }
5071
5072 return false;
5073}
5074#endif
5075
5076/// EmitCallArgs - Emit call arguments for a function.
5077void CodeGenFunction::EmitCallArgs(
5078 CallArgList &Args, PrototypeWrapper Prototype,
5079 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
5080 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
5081 SmallVector<QualType, 16> ArgTypes;
5082
5083 assert((ParamsToSkip == 0 || Prototype.P) &&
5084 "Can't skip parameters if type info is not provided");
5085
5086 // This variable only captures *explicitly* written conventions, not those
5087 // applied by default via command line flags or target defaults, such as
5088 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
5089 // require knowing if this is a C++ instance method or being able to see
5090 // unprototyped FunctionTypes.
5091 CallingConv ExplicitCC = CC_C;
5092
5093 // First, if a prototype was provided, use those argument types.
5094 bool IsVariadic = false;
5095 if (Prototype.P) {
5096 const auto *MD = dyn_cast<const ObjCMethodDecl *>(Val&: Prototype.P);
5097 if (MD) {
5098 IsVariadic = MD->isVariadic();
5099 ExplicitCC = getCallingConventionForDecl(
5100 D: MD, IsTargetDefaultMSABI: CGM.getTarget().getTriple().isOSWindows());
5101 ArgTypes.assign(in_start: MD->param_type_begin() + ParamsToSkip,
5102 in_end: MD->param_type_end());
5103 } else {
5104 const auto *FPT = cast<const FunctionProtoType *>(Val&: Prototype.P);
5105 IsVariadic = FPT->isVariadic();
5106 ExplicitCC = FPT->getExtInfo().getCC();
5107 ArgTypes.assign(in_start: FPT->param_type_begin() + ParamsToSkip,
5108 in_end: FPT->param_type_end());
5109 }
5110
5111#ifndef NDEBUG
5112 // Check that the prototyped types match the argument expression types.
5113 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
5114 CallExpr::const_arg_iterator Arg = ArgRange.begin();
5115 for (QualType Ty : ArgTypes) {
5116 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
5117 QualType ParamTy = Ty.getNonReferenceType();
5118 QualType ArgTy = (*Arg)->getType();
5119 if (const auto *OBT = ParamTy->getAs<OverflowBehaviorType>())
5120 ParamTy = OBT->getUnderlyingType();
5121 if (const auto *OBT = ArgTy->getAs<OverflowBehaviorType>())
5122 ArgTy = OBT->getUnderlyingType();
5123 assert((isGenericMethod || Ty->isVariablyModifiedType() ||
5124 ParamTy->isObjCRetainableType() ||
5125 getContext().getCanonicalType(ParamTy).getTypePtr() ==
5126 getContext().getCanonicalType(ArgTy).getTypePtr()) &&
5127 "type mismatch in call argument!");
5128 ++Arg;
5129 }
5130
5131 // Either we've emitted all the call args, or we have a call to variadic
5132 // function.
5133 assert((Arg == ArgRange.end() || IsVariadic) &&
5134 "Extra arguments in non-variadic function!");
5135#endif
5136 }
5137
5138 // If we still have any arguments, emit them using the type of the argument.
5139 for (auto *A : llvm::drop_begin(RangeOrContainer&: ArgRange, N: ArgTypes.size()))
5140 ArgTypes.push_back(Elt: IsVariadic ? getVarArgType(Arg: A) : A->getType());
5141 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
5142
5143 // We must evaluate arguments from right to left in the MS C++ ABI,
5144 // because arguments are destroyed left to right in the callee. As a special
5145 // case, there are certain language constructs that require left-to-right
5146 // evaluation, and in those cases we consider the evaluation order requirement
5147 // to trump the "destruction order is reverse construction order" guarantee.
5148 bool LeftToRight =
5149 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
5150 ? Order == EvaluationOrder::ForceLeftToRight
5151 : Order != EvaluationOrder::ForceRightToLeft;
5152
5153 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
5154 RValue EmittedArg) {
5155 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
5156 return;
5157 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
5158 if (PS == nullptr)
5159 return;
5160
5161 const auto &Context = getContext();
5162 auto SizeTy = Context.getSizeType();
5163 auto T = Builder.getIntNTy(N: Context.getTypeSize(T: SizeTy));
5164 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
5165 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(
5166 E: Arg, Type: PS->getType(), ResType: T, EmittedE: EmittedArg.getScalarVal(), IsDynamic: PS->isDynamic());
5167 Args.add(rvalue: RValue::get(V), type: SizeTy);
5168 // If we're emitting args in reverse, be sure to do so with
5169 // pass_object_size, as well.
5170 if (!LeftToRight)
5171 std::swap(a&: Args.back(), b&: *(&Args.back() - 1));
5172 };
5173
5174 // Insert a stack save if we're going to need any inalloca args.
5175 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
5176 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
5177 "inalloca only supported on x86");
5178 Args.allocateArgumentMemory(CGF&: *this);
5179 }
5180
5181 // Evaluate each argument in the appropriate order.
5182 size_t CallArgsStart = Args.size();
5183 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
5184 unsigned Idx = LeftToRight ? I : E - I - 1;
5185 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
5186 unsigned InitialArgSize = Args.size();
5187 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
5188 // the argument and parameter match or the objc method is parameterized.
5189 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
5190 getContext().hasSameUnqualifiedType((*Arg)->getType(),
5191 ArgTypes[Idx]) ||
5192 (isa<ObjCMethodDecl>(AC.getDecl()) &&
5193 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
5194 "Argument and parameter types don't match");
5195 EmitCallArg(args&: Args, E: *Arg, ArgType: ArgTypes[Idx]);
5196 // In particular, we depend on it being the last arg in Args, and the
5197 // objectsize bits depend on there only being one arg if !LeftToRight.
5198 assert(InitialArgSize + 1 == Args.size() &&
5199 "The code below depends on only adding one arg per EmitCallArg");
5200 (void)InitialArgSize;
5201 // Since pointer argument are never emitted as LValue, it is safe to emit
5202 // non-null argument check for r-value only.
5203 if (!Args.back().hasLValue()) {
5204 RValue RVArg = Args.back().getKnownRValue();
5205 EmitNonNullArgCheck(RV: RVArg, ArgType: ArgTypes[Idx], ArgLoc: (*Arg)->getExprLoc(), AC,
5206 ParmNum: ParamsToSkip + Idx);
5207 // @llvm.objectsize should never have side-effects and shouldn't need
5208 // destruction/cleanups, so we can safely "emit" it after its arg,
5209 // regardless of right-to-leftness
5210 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
5211 }
5212 }
5213
5214 if (!LeftToRight) {
5215 // Un-reverse the arguments we just evaluated so they match up with the LLVM
5216 // IR function.
5217 std::reverse(first: Args.begin() + CallArgsStart, last: Args.end());
5218
5219 // Reverse the writebacks to match the MSVC ABI.
5220 Args.reverseWritebacks();
5221 }
5222}
5223
5224namespace {
5225
5226struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
5227 DestroyUnpassedArg(Address Addr, QualType Ty) : Addr(Addr), Ty(Ty) {}
5228
5229 Address Addr;
5230 QualType Ty;
5231
5232 void Emit(CodeGenFunction &CGF, Flags flags) override {
5233 QualType::DestructionKind DtorKind = Ty.isDestructedType();
5234 if (DtorKind == QualType::DK_cxx_destructor) {
5235 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
5236 assert(!Dtor->isTrivial());
5237 CGF.EmitCXXDestructorCall(D: Dtor, Type: Dtor_Complete, /*for vbase*/ ForVirtualBase: false,
5238 /*Delegating=*/false, This: Addr, ThisTy: Ty);
5239 } else {
5240 CGF.callCStructDestructor(Dst: CGF.MakeAddrLValue(Addr, T: Ty));
5241 }
5242 }
5243};
5244
5245} // end anonymous namespace
5246
5247RValue CallArg::getRValue(CodeGenFunction &CGF) const {
5248 if (!HasLV)
5249 return RV;
5250 LValue Copy = CGF.MakeAddrLValue(Addr: CGF.CreateMemTempWithoutCast(T: Ty), T: Ty);
5251 CGF.EmitAggregateCopy(Dest: Copy, Src: LV, EltTy: Ty, MayOverlap: AggValueSlot::DoesNotOverlap,
5252 isVolatile: LV.isVolatile());
5253 IsUsed = true;
5254 return RValue::getAggregate(addr: Copy.getAddress());
5255}
5256
5257void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
5258 LValue Dst = CGF.MakeAddrLValue(Addr, T: Ty);
5259 if (!HasLV && RV.isScalar())
5260 CGF.EmitStoreOfScalar(value: RV.getScalarVal(), lvalue: Dst, /*isInit=*/true);
5261 else if (!HasLV && RV.isComplex())
5262 CGF.EmitStoreOfComplex(V: RV.getComplexVal(), dest: Dst, /*init=*/isInit: true);
5263 else {
5264 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
5265 LValue SrcLV = CGF.MakeAddrLValue(Addr, T: Ty);
5266 // We assume that call args are never copied into subobjects.
5267 CGF.EmitAggregateCopy(Dest: Dst, Src: SrcLV, EltTy: Ty, MayOverlap: AggValueSlot::DoesNotOverlap,
5268 isVolatile: HasLV ? LV.isVolatileQualified()
5269 : RV.isVolatileQualified());
5270 }
5271 IsUsed = true;
5272}
5273
5274void CodeGenFunction::EmitWritebacks(const CallArgList &args) {
5275 for (const auto &I : args.writebacks())
5276 emitWriteback(CGF&: *this, writeback: I);
5277}
5278
5279void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
5280 QualType type) {
5281 std::optional<DisableDebugLocationUpdates> Dis;
5282 if (isa<CXXDefaultArgExpr>(Val: E))
5283 Dis.emplace(args&: *this);
5284 if (const ObjCIndirectCopyRestoreExpr *CRE =
5285 dyn_cast<ObjCIndirectCopyRestoreExpr>(Val: E)) {
5286 assert(getLangOpts().ObjCAutoRefCount);
5287 return emitWritebackArg(CGF&: *this, args, CRE);
5288 }
5289
5290 // Add writeback for HLSLOutParamExpr.
5291 // Needs to be before the assert below because HLSLOutArgExpr is an LValue
5292 // and is not a reference.
5293 if (const HLSLOutArgExpr *OE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
5294 EmitHLSLOutArgExpr(E: OE, Args&: args, Ty: type);
5295 return;
5296 }
5297
5298 assert(type->isReferenceType() == E->isGLValue() &&
5299 "reference binding to unmaterialized r-value!");
5300
5301 if (E->isGLValue()) {
5302 assert(E->getObjectKind() == OK_Ordinary);
5303 return args.add(rvalue: EmitReferenceBindingToExpr(E), type);
5304 }
5305
5306 bool HasAggregateEvalKind = hasAggregateEvaluationKind(T: type);
5307
5308 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
5309 // However, we still have to push an EH-only cleanup in case we unwind before
5310 // we make it to the call.
5311 if (type->isRecordType() &&
5312 type->castAsRecordDecl()->isParamDestroyedInCallee()) {
5313 // If we're using inalloca, use the argument memory. Otherwise, use a
5314 // temporary.
5315 AggValueSlot Slot = args.isUsingInAlloca()
5316 ? createPlaceholderSlot(CGF&: *this, Ty: type)
5317 : CreateAggTemp(T: type, Name: "agg.tmp");
5318
5319 bool DestroyedInCallee = true, NeedsCleanup = true;
5320 if (const auto *RD = type->getAsCXXRecordDecl())
5321 DestroyedInCallee = RD->hasNonTrivialDestructor();
5322 else
5323 NeedsCleanup = type.isDestructedType();
5324
5325 if (DestroyedInCallee)
5326 Slot.setExternallyDestructed();
5327
5328 EmitAggExpr(E, AS: Slot);
5329 RValue RV = Slot.asRValue();
5330 args.add(rvalue: RV, type);
5331
5332 if (DestroyedInCallee && NeedsCleanup) {
5333 // Create a no-op GEP between the placeholder and the cleanup so we can
5334 // RAUW it successfully. It also serves as a marker of the first
5335 // instruction where the cleanup is active.
5336 pushFullExprCleanup<DestroyUnpassedArg>(kind: NormalAndEHCleanup,
5337 A: Slot.getAddress(), A: type);
5338 // This unreachable is a temporary marker which will be removed later.
5339 llvm::Instruction *IsActive =
5340 Builder.CreateFlagLoad(Addr: llvm::Constant::getNullValue(Ty: Int8PtrTy));
5341 args.addArgCleanupDeactivation(Cleanup: EHStack.stable_begin(), IsActiveIP: IsActive);
5342 }
5343 return;
5344 }
5345
5346 if (HasAggregateEvalKind) {
5347 auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E);
5348 if (ICE && ICE->getCastKind() == CK_LValueToRValue &&
5349 ICE->getSubExpr()->getType().getAddressSpace() !=
5350 LangAS::hlsl_constant &&
5351 !type->isArrayParameterType() && !type.isNonTrivialToPrimitiveCopy()) {
5352 LValue L = EmitLValue(E: cast<CastExpr>(Val: E)->getSubExpr());
5353 assert(L.isSimple());
5354 args.addUncopiedAggregate(LV: L, type);
5355 return;
5356 }
5357 }
5358
5359 args.add(rvalue: EmitAnyExprToTemp(E), type);
5360}
5361
5362QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
5363 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
5364 // implicitly widens null pointer constants that are arguments to varargs
5365 // functions to pointer-sized ints.
5366 if (!getTarget().getTriple().isOSWindows())
5367 return Arg->getType();
5368
5369 if (Arg->getType()->isIntegerType() &&
5370 getContext().getTypeSize(T: Arg->getType()) <
5371 getContext().getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) &&
5372 Arg->isNullPointerConstant(Ctx&: getContext(),
5373 NPC: Expr::NPC_ValueDependentIsNotNull)) {
5374 return getContext().getIntPtrType();
5375 }
5376
5377 return Arg->getType();
5378}
5379
5380// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5381// optimizer it can aggressively ignore unwind edges.
5382void CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
5383 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
5384 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
5385 Inst->setMetadata(Kind: "clang.arc.no_objc_arc_exceptions",
5386 Node: CGM.getNoObjCARCExceptionsMetadata());
5387}
5388
5389/// Emits a call to the given no-arguments nounwind runtime function.
5390llvm::CallInst *
5391CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
5392 const llvm::Twine &name) {
5393 return EmitNounwindRuntimeCall(callee, args: ArrayRef<llvm::Value *>(), name);
5394}
5395
5396/// Emits a call to the given nounwind runtime function.
5397llvm::CallInst *
5398CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
5399 ArrayRef<Address> args,
5400 const llvm::Twine &name) {
5401 SmallVector<llvm::Value *, 3> values;
5402 for (auto arg : args)
5403 values.push_back(Elt: arg.emitRawPointer(CGF&: *this));
5404 return EmitNounwindRuntimeCall(callee, args: values, name);
5405}
5406
5407llvm::CallInst *
5408CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
5409 ArrayRef<llvm::Value *> args,
5410 const llvm::Twine &name) {
5411 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
5412 call->setDoesNotThrow();
5413 return call;
5414}
5415
5416/// Emits a simple call (never an invoke) to the given no-arguments
5417/// runtime function.
5418llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
5419 const llvm::Twine &name) {
5420 return EmitRuntimeCall(callee, args: {}, name);
5421}
5422
5423// Calls which may throw must have operand bundles indicating which funclet
5424// they are nested within.
5425SmallVector<llvm::OperandBundleDef, 1>
5426CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
5427 // There is no need for a funclet operand bundle if we aren't inside a
5428 // funclet.
5429 if (!CurrentFuncletPad)
5430 return (SmallVector<llvm::OperandBundleDef, 1>());
5431
5432 // Skip intrinsics which cannot throw (as long as they don't lower into
5433 // regular function calls in the course of IR transformations).
5434 if (auto *CalleeFn = dyn_cast<llvm::Function>(Val: Callee->stripPointerCasts())) {
5435 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
5436 auto IID = CalleeFn->getIntrinsicID();
5437 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
5438 return (SmallVector<llvm::OperandBundleDef, 1>());
5439 }
5440 }
5441
5442 SmallVector<llvm::OperandBundleDef, 1> BundleList;
5443 BundleList.emplace_back(Args: "funclet", Args&: CurrentFuncletPad);
5444 return BundleList;
5445}
5446
5447/// Emits a simple call (never an invoke) to the given runtime function.
5448llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
5449 ArrayRef<llvm::Value *> args,
5450 const llvm::Twine &name) {
5451 llvm::CallInst *call = Builder.CreateCall(
5452 Callee: callee, Args: args, OpBundles: getBundlesForFunclet(Callee: callee.getCallee()), Name: name);
5453 call->setCallingConv(getRuntimeCC());
5454
5455 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
5456 return cast<llvm::CallInst>(Val: addConvergenceControlToken(Input: call));
5457 return call;
5458}
5459
5460llvm::CallInst *CodeGenFunction::EmitIntrinsicCall(llvm::Intrinsic::ID ID,
5461 const llvm::Twine &Name) {
5462 return EmitIntrinsicCall(ID, Args: {}, RetTy: {}, Name);
5463}
5464
5465llvm::CallInst *CodeGenFunction::EmitIntrinsicCall(llvm::Intrinsic::ID ID,
5466 ArrayRef<llvm::Value *> Args,
5467 const llvm::Twine &Name) {
5468 return EmitIntrinsicCall(ID, Types: {}, Args, Name);
5469}
5470
5471llvm::CallInst *CodeGenFunction::EmitIntrinsicCall(llvm::Intrinsic::ID ID,
5472 ArrayRef<llvm::Type *> Types,
5473 ArrayRef<llvm::Value *> Args,
5474 const llvm::Twine &Name) {
5475 llvm::Function *F =
5476 llvm::Intrinsic::getOrInsertDeclaration(M: &CGM.getModule(), id: ID, OverloadTys: Types);
5477 llvm::CallInst *Call =
5478 Builder.CreateCall(Callee: F, Args, OpBundles: getBundlesForFunclet(Callee: F), Name);
5479 if (CGM.shouldEmitConvergenceTokens() && Call->isConvergent())
5480 return cast<llvm::CallInst>(Val: addConvergenceControlToken(Input: Call));
5481 return Call;
5482}
5483
5484llvm::CallInst *CodeGenFunction::EmitIntrinsicCall(llvm::Intrinsic::ID ID,
5485 ArrayRef<llvm::Value *> Args,
5486 llvm::Type *RetTy,
5487 const llvm::Twine &Name) {
5488 SmallVector<llvm::Type *> ArgTys;
5489 ArgTys.reserve(N: Args.size());
5490 for (llvm::Value *Arg : Args)
5491 ArgTys.push_back(Elt: Arg->getType());
5492 llvm::Function *F = llvm::Intrinsic::getOrInsertDeclaration(
5493 M: &CGM.getModule(), IID: ID, RetTy, ArgTys);
5494 llvm::CallInst *Call =
5495 Builder.CreateCall(Callee: F, Args, OpBundles: getBundlesForFunclet(Callee: F), Name);
5496 if (CGM.shouldEmitConvergenceTokens() && Call->isConvergent())
5497 return cast<llvm::CallInst>(Val: addConvergenceControlToken(Input: Call));
5498 return Call;
5499}
5500
5501/// Emits a call or invoke to the given noreturn runtime function.
5502void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
5503 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
5504 SmallVector<llvm::OperandBundleDef, 1> BundleList =
5505 getBundlesForFunclet(Callee: callee.getCallee());
5506
5507 if (getInvokeDest()) {
5508 llvm::InvokeInst *invoke = Builder.CreateInvoke(
5509 Callee: callee, NormalDest: getUnreachableBlock(), UnwindDest: getInvokeDest(), Args: args, OpBundles: BundleList);
5510 invoke->setDoesNotReturn();
5511 invoke->setCallingConv(getRuntimeCC());
5512 } else {
5513 llvm::CallInst *call = Builder.CreateCall(Callee: callee, Args: args, OpBundles: BundleList);
5514 call->setDoesNotReturn();
5515 call->setCallingConv(getRuntimeCC());
5516 Builder.CreateUnreachable();
5517 }
5518}
5519
5520/// Emits a call or invoke instruction to the given nullary runtime function.
5521llvm::CallBase *
5522CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
5523 const Twine &name) {
5524 return EmitRuntimeCallOrInvoke(callee, args: {}, name);
5525}
5526
5527/// Emits a call or invoke instruction to the given runtime function.
5528llvm::CallBase *
5529CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
5530 ArrayRef<llvm::Value *> args,
5531 const Twine &name) {
5532 llvm::CallBase *call = EmitCallOrInvoke(Callee: callee, Args: args, Name: name);
5533 call->setCallingConv(getRuntimeCC());
5534 return call;
5535}
5536
5537/// Emits a call or invoke instruction to the given function, depending
5538/// on the current state of the EH stack.
5539llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
5540 ArrayRef<llvm::Value *> Args,
5541 const Twine &Name) {
5542 llvm::BasicBlock *InvokeDest = getInvokeDest();
5543 SmallVector<llvm::OperandBundleDef, 1> BundleList =
5544 getBundlesForFunclet(Callee: Callee.getCallee());
5545
5546 llvm::CallBase *Inst;
5547 if (!InvokeDest)
5548 Inst = Builder.CreateCall(Callee, Args, OpBundles: BundleList, Name);
5549 else {
5550 llvm::BasicBlock *ContBB = createBasicBlock(name: "invoke.cont");
5551 Inst = Builder.CreateInvoke(Callee, NormalDest: ContBB, UnwindDest: InvokeDest, Args, OpBundles: BundleList,
5552 Name);
5553 EmitBlock(BB: ContBB);
5554 }
5555
5556 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5557 // optimizer it can aggressively ignore unwind edges.
5558 if (CGM.getLangOpts().ObjCAutoRefCount)
5559 AddObjCARCExceptionMetadata(Inst);
5560
5561 return Inst;
5562}
5563
5564void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
5565 llvm::Value *New) {
5566 DeferredReplacements.push_back(
5567 Elt: std::make_pair(x: llvm::WeakTrackingVH(Old), y&: New));
5568}
5569
5570namespace {
5571
5572/// Specify given \p NewAlign as the alignment of return value attribute. If
5573/// such attribute already exists, re-set it to the maximal one of two options.
5574[[nodiscard]] llvm::AttributeList
5575maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
5576 const llvm::AttributeList &Attrs,
5577 llvm::Align NewAlign) {
5578 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
5579 if (CurAlign >= NewAlign)
5580 return Attrs;
5581 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Context&: Ctx, Alignment: NewAlign);
5582 return Attrs.removeRetAttribute(C&: Ctx, Kind: llvm::Attribute::AttrKind::Alignment)
5583 .addRetAttribute(C&: Ctx, Attr: AlignAttr);
5584}
5585
5586template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
5587protected:
5588 CodeGenFunction &CGF;
5589
5590 /// We do nothing if this is, or becomes, nullptr.
5591 const AlignedAttrTy *AA = nullptr;
5592
5593 llvm::Value *Alignment = nullptr; // May or may not be a constant.
5594 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
5595
5596 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5597 : CGF(CGF_) {
5598 if (!FuncDecl)
5599 return;
5600 AA = FuncDecl->getAttr<AlignedAttrTy>();
5601 }
5602
5603public:
5604 /// If we can, materialize the alignment as an attribute on return value.
5605 [[nodiscard]] llvm::AttributeList
5606 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
5607 if (!AA || OffsetCI || CGF.SanOpts.has(K: SanitizerKind::Alignment))
5608 return Attrs;
5609 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Val: Alignment);
5610 if (!AlignmentCI)
5611 return Attrs;
5612 // We may legitimately have non-power-of-2 alignment here.
5613 // If so, this is UB land, emit it via `@llvm.assume` instead.
5614 if (!AlignmentCI->getValue().isPowerOf2())
5615 return Attrs;
5616 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
5617 Ctx&: CGF.getLLVMContext(), Attrs,
5618 NewAlign: llvm::Align(
5619 AlignmentCI->getLimitedValue(Limit: llvm::Value::MaximumAlignment)));
5620 AA = nullptr; // We're done. Disallow doing anything else.
5621 return NewAttrs;
5622 }
5623
5624 /// Emit alignment assumption.
5625 /// This is a general fallback that we take if either there is an offset,
5626 /// or the alignment is variable or we are sanitizing for alignment.
5627 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
5628 if (!AA)
5629 return;
5630 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
5631 AA->getLocation(), Alignment, OffsetCI);
5632 AA = nullptr; // We're done. Disallow doing anything else.
5633 }
5634};
5635
5636/// Helper data structure to emit `AssumeAlignedAttr`.
5637class AssumeAlignedAttrEmitter final
5638 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
5639public:
5640 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5641 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5642 if (!AA)
5643 return;
5644 // It is guaranteed that the alignment/offset are constants.
5645 Alignment = cast<llvm::ConstantInt>(Val: CGF.EmitScalarExpr(E: AA->getAlignment()));
5646 if (Expr *Offset = AA->getOffset()) {
5647 OffsetCI = cast<llvm::ConstantInt>(Val: CGF.EmitScalarExpr(E: Offset));
5648 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
5649 OffsetCI = nullptr;
5650 }
5651 }
5652};
5653
5654/// Helper data structure to emit `AllocAlignAttr`.
5655class AllocAlignAttrEmitter final
5656 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5657public:
5658 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5659 const CallArgList &CallArgs)
5660 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5661 if (!AA)
5662 return;
5663 // Alignment may or may not be a constant, and that is okay.
5664 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5665 .getRValue(CGF)
5666 .getScalarVal();
5667 }
5668};
5669
5670} // namespace
5671
5672static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5673 if (auto *VT = dyn_cast<llvm::VectorType>(Val: Ty))
5674 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5675 if (auto *AT = dyn_cast<llvm::ArrayType>(Val: Ty))
5676 return getMaxVectorWidth(Ty: AT->getElementType());
5677
5678 unsigned MaxVectorWidth = 0;
5679 if (auto *ST = dyn_cast<llvm::StructType>(Val: Ty))
5680 for (auto *I : ST->elements())
5681 MaxVectorWidth = std::max(a: MaxVectorWidth, b: getMaxVectorWidth(Ty: I));
5682 return MaxVectorWidth;
5683}
5684
5685RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
5686 const CGCallee &Callee,
5687 ReturnValueSlot ReturnValue,
5688 const CallArgList &CallArgs,
5689 llvm::CallBase **callOrInvoke, bool IsMustTail,
5690 SourceLocation Loc,
5691 bool IsVirtualFunctionPointerThunk) {
5692 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5693
5694 assert(Callee.isOrdinary() || Callee.isVirtual());
5695
5696 // Handle struct-return functions by passing a pointer to the
5697 // location that we would like to return into.
5698 QualType RetTy = CallInfo.getReturnType();
5699 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5700
5701 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(FI: CallInfo);
5702
5703 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5704 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl)) {
5705 // We can only guarantee that a function is called from the correct
5706 // context/function based on the appropriate target attributes,
5707 // so only check in the case where we have both always_inline and target
5708 // since otherwise we could be making a conditional call after a check for
5709 // the proper cpu features (and it won't cause code generation issues due to
5710 // function based code generation).
5711 if ((TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5712 (TargetDecl->hasAttr<TargetAttr>() ||
5713 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>()))) ||
5714 (CurFuncDecl && CurFuncDecl->hasAttr<FlattenAttr>() &&
5715 (CurFuncDecl->hasAttr<TargetAttr>() ||
5716 TargetDecl->hasAttr<TargetAttr>())))
5717 checkTargetFeatures(Loc, TargetDecl: FD);
5718 }
5719
5720 // Some architectures (such as x86-64) have the ABI changed based on
5721 // attribute-target/features. Give them a chance to diagnose.
5722 const FunctionDecl *CallerDecl = dyn_cast_or_null<FunctionDecl>(Val: CurCodeDecl);
5723 const FunctionDecl *CalleeDecl = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl);
5724 CGM.getTargetCodeGenInfo().checkFunctionCallABI(CGM, CallLoc: Loc, Caller: CallerDecl,
5725 Callee: CalleeDecl, Args: CallArgs, ReturnType: RetTy);
5726
5727 // 1. Set up the arguments.
5728
5729 // If we're using inalloca, insert the allocation after the stack save.
5730 // FIXME: Do this earlier rather than hacking it in here!
5731 RawAddress ArgMemory = RawAddress::invalid();
5732 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5733 const llvm::DataLayout &DL = CGM.getDataLayout();
5734 llvm::Instruction *IP = CallArgs.getStackBase();
5735 llvm::AllocaInst *AI;
5736 if (IP) {
5737 IP = IP->getNextNode();
5738 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), "argmem",
5739 IP->getIterator());
5740 } else {
5741 AI = CreateTempAlloca(Ty: ArgStruct, Name: "argmem");
5742 }
5743 auto Align = CallInfo.getArgStructAlignment();
5744 AI->setAlignment(Align.getAsAlign());
5745 AI->setUsedWithInAlloca(true);
5746 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5747 ArgMemory = RawAddress(AI, ArgStruct, Align);
5748 }
5749
5750 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5751 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5752
5753 // If the call returns a temporary with struct return, create a temporary
5754 // alloca to hold the result, unless one is given to us.
5755 Address SRetPtr = Address::invalid();
5756 // Original alloca for lifetime markers
5757 Address SRetAlloca = Address::invalid();
5758 bool NeedSRetLifetimeEnd = false;
5759 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5760 // For virtual function pointer thunks and musttail calls, we must always
5761 // forward an incoming SRet pointer to the callee, because a local alloca
5762 // would be de-allocated before the call. These cases both guarantee that
5763 // there will be an incoming SRet argument of the correct type.
5764 if ((IsVirtualFunctionPointerThunk || IsMustTail) && RetAI.isIndirect()) {
5765 SRetPtr = makeNaturalAddressForPointer(Ptr: CurFn->arg_begin() +
5766 IRFunctionArgs.getSRetArgNo(),
5767 T: RetTy, Alignment: CharUnits::fromQuantity(Quantity: 1));
5768 } else if (!ReturnValue.isNull()) {
5769 SRetPtr = ReturnValue.getAddress();
5770 } else {
5771 SRetPtr = CreateMemTempWithoutCast(T: RetTy, Name: "tmp");
5772 if (HaveInsertPoint() && ReturnValue.isUnused()) {
5773 NeedSRetLifetimeEnd = EmitLifetimeStart(Addr: SRetPtr.getBasePointer());
5774 if (NeedSRetLifetimeEnd)
5775 SRetAlloca = SRetPtr;
5776 }
5777 }
5778 if (IRFunctionArgs.hasSRetArg()) {
5779 // A mismatch between the allocated return value's AS and the target's
5780 // chosen IndirectAS can happen e.g. when passing the this pointer through
5781 // a chain involving stores to / loads from the DefaultAS; we address this
5782 // here, symmetrically with the handling we have for normal pointer args.
5783 if (SRetPtr.getAddressSpace() != RetAI.getIndirectAddrSpace()) {
5784 llvm::Value *V = SRetPtr.getBasePointer();
5785 llvm::Type *Ty = llvm::PointerType::get(C&: getLLVMContext(),
5786 AddressSpace: RetAI.getIndirectAddrSpace());
5787
5788 SRetPtr = SRetPtr.withPointer(NewPointer: performAddrSpaceCast(Src: V, DestTy: Ty),
5789 IsKnownNonNull: SRetPtr.isKnownNonNull());
5790 }
5791 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5792 getAsNaturalPointerTo(Addr: SRetPtr, PointeeType: RetTy);
5793 } else if (RetAI.isInAlloca()) {
5794 Address Addr =
5795 Builder.CreateStructGEP(Addr: ArgMemory, Index: RetAI.getInAllocaFieldIndex());
5796 Builder.CreateStore(Val: getAsNaturalPointerTo(Addr: SRetPtr, PointeeType: RetTy), Addr);
5797 }
5798 }
5799
5800 RawAddress swiftErrorTemp = RawAddress::invalid();
5801 Address swiftErrorArg = Address::invalid();
5802
5803 // When passing arguments using temporary allocas, we need to add the
5804 // appropriate lifetime markers. This vector keeps track of all the lifetime
5805 // markers that need to be ended right after the call.
5806 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5807
5808 // Translate all of the arguments as necessary to match the IR lowering.
5809 assert(CallInfo.arg_size() == CallArgs.size() &&
5810 "Mismatch between function signature & arguments.");
5811 unsigned ArgNo = 0;
5812 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5813 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5814 I != E; ++I, ++info_it, ++ArgNo) {
5815 const ABIArgInfo &ArgInfo = info_it->info;
5816
5817 // Insert a padding argument to ensure proper alignment.
5818 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5819 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5820 llvm::UndefValue::get(T: ArgInfo.getPaddingType());
5821
5822 unsigned FirstIRArg, NumIRArgs;
5823 std::tie(args&: FirstIRArg, args&: NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5824
5825 bool ArgHasMaybeUndefAttr =
5826 IsArgumentMaybeUndef(TargetDecl, NumRequiredArgs: CallInfo.getNumRequiredArgs(), ArgNo);
5827
5828 switch (ArgInfo.getKind()) {
5829 case ABIArgInfo::InAlloca: {
5830 assert(NumIRArgs == 0);
5831 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5832 if (I->isAggregate()) {
5833 RawAddress Addr = I->hasLValue()
5834 ? I->getKnownLValue().getAddress()
5835 : I->getKnownRValue().getAggregateAddress();
5836 llvm::Instruction *Placeholder =
5837 cast<llvm::Instruction>(Val: Addr.getPointer());
5838
5839 if (!ArgInfo.getInAllocaIndirect()) {
5840 // Replace the placeholder with the appropriate argument slot GEP.
5841 CGBuilderTy::InsertPoint IP = Builder.saveIP();
5842 Builder.SetInsertPoint(Placeholder);
5843 Addr = Builder.CreateStructGEP(Addr: ArgMemory,
5844 Index: ArgInfo.getInAllocaFieldIndex());
5845 Builder.restoreIP(IP);
5846 } else {
5847 // For indirect things such as overaligned structs, replace the
5848 // placeholder with a regular aggregate temporary alloca. Store the
5849 // address of this alloca into the struct.
5850 Addr =
5851 CreateMemTempWithoutCast(T: info_it->type, Name: "inalloca.indirect.tmp");
5852 Address ArgSlot = Builder.CreateStructGEP(
5853 Addr: ArgMemory, Index: ArgInfo.getInAllocaFieldIndex());
5854 Builder.CreateStore(Val: Addr.getPointer(), Addr: ArgSlot);
5855 }
5856 deferPlaceholderReplacement(Old: Placeholder, New: Addr.getPointer());
5857 } else if (ArgInfo.getInAllocaIndirect()) {
5858 // Make a temporary alloca and store the address of it into the argument
5859 // struct.
5860 RawAddress Addr = CreateMemTempWithoutCast(
5861 T: I->Ty, Align: getContext().getTypeAlignInChars(T: I->Ty),
5862 Name: "indirect-arg-temp");
5863 I->copyInto(CGF&: *this, Addr);
5864 Address ArgSlot =
5865 Builder.CreateStructGEP(Addr: ArgMemory, Index: ArgInfo.getInAllocaFieldIndex());
5866 Builder.CreateStore(Val: Addr.getPointer(), Addr: ArgSlot);
5867 } else {
5868 // Store the RValue into the argument struct.
5869 Address Addr =
5870 Builder.CreateStructGEP(Addr: ArgMemory, Index: ArgInfo.getInAllocaFieldIndex());
5871 Addr = Addr.withElementType(ElemTy: ConvertTypeForMem(T: I->Ty));
5872 I->copyInto(CGF&: *this, Addr);
5873 }
5874 break;
5875 }
5876
5877 case ABIArgInfo::Indirect:
5878 case ABIArgInfo::IndirectAliased: {
5879 assert(NumIRArgs == 1);
5880 if (I->isAggregate()) {
5881 // We want to avoid creating an unnecessary temporary+copy here;
5882 // however, we need one in three cases:
5883 // 1. If the argument is not byval, and we are required to copy the
5884 // source. (This case doesn't occur on any common architecture.)
5885 // 2. If the argument is byval, RV is not sufficiently aligned, and
5886 // we cannot force it to be sufficiently aligned.
5887 // 3. If the argument is byval, but RV is not located in default
5888 // or alloca address space.
5889 Address Addr = I->hasLValue()
5890 ? I->getKnownLValue().getAddress()
5891 : I->getKnownRValue().getAggregateAddress();
5892 CharUnits Align = ArgInfo.getIndirectAlign();
5893 const llvm::DataLayout *TD = &CGM.getDataLayout();
5894
5895 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5896 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5897 TD->getAllocaAddrSpace()) &&
5898 "indirect argument must be in alloca address space");
5899
5900 bool NeedCopy = false;
5901 if (Addr.getAlignment() < Align &&
5902 llvm::getOrEnforceKnownAlignment(V: Addr.emitRawPointer(CGF&: *this),
5903 PrefAlign: Align.getAsAlign(),
5904 DL: *TD) < Align.getAsAlign()) {
5905 NeedCopy = true;
5906 } else if (I->hasLValue()) {
5907 auto LV = I->getKnownLValue();
5908
5909 bool isByValOrRef =
5910 ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5911
5912 if (!isByValOrRef ||
5913 (LV.getAlignment() < getContext().getTypeAlignInChars(T: I->Ty))) {
5914 NeedCopy = true;
5915 }
5916
5917 if (isByValOrRef && Addr.getType()->getAddressSpace() !=
5918 ArgInfo.getIndirectAddrSpace()) {
5919 NeedCopy = true;
5920 }
5921 }
5922
5923 if (!NeedCopy) {
5924 // Skip the extra memcpy call.
5925 llvm::Value *V = getAsNaturalPointerTo(Addr, PointeeType: I->Ty);
5926 auto *T = llvm::PointerType::get(C&: CGM.getLLVMContext(),
5927 AddressSpace: ArgInfo.getIndirectAddrSpace());
5928
5929 // FIXME: This should not depend on the language address spaces, and
5930 // only the contextual values. If the address space mismatches, see if
5931 // we can look through a cast to a compatible address space value,
5932 // otherwise emit a copy.
5933 llvm::Value *Val = performAddrSpaceCast(Src: V, DestTy: T);
5934 if (ArgHasMaybeUndefAttr)
5935 Val = Builder.CreateFreeze(V: Val);
5936 IRCallArgs[FirstIRArg] = Val;
5937 break;
5938 }
5939 } else if (I->getType()->isArrayParameterType()) {
5940 // Don't produce a temporary for ArrayParameterType arguments.
5941 // ArrayParameterType arguments are only created from
5942 // HLSL_ArrayRValue casts and HLSLOutArgExpr expressions, both
5943 // of which create temporaries already. This allows us to just use the
5944 // scalar for the decayed array pointer as the argument directly.
5945 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5946 break;
5947 }
5948
5949 // For non-aggregate args and aggregate args meeting conditions above
5950 // we need to create an aligned temporary, and copy to it.
5951 RawAddress AI = CreateMemTempWithoutCast(
5952 T: I->Ty, Align: ArgInfo.getIndirectAlign(), Name: "byval-temp");
5953 llvm::Value *Val = getAsNaturalPointerTo(Addr: AI, PointeeType: I->Ty);
5954 if (ArgHasMaybeUndefAttr)
5955 Val = Builder.CreateFreeze(V: Val);
5956 IRCallArgs[FirstIRArg] = Val;
5957
5958 // Emit lifetime markers for the temporary alloca and add cleanup code to
5959 // emit the end lifetime marker after the call.
5960 if (EmitLifetimeStart(Addr: AI.getPointer()))
5961 CallLifetimeEndAfterCall.emplace_back(Args&: AI);
5962
5963 // Generate the copy.
5964 I->copyInto(CGF&: *this, Addr: AI);
5965 break;
5966 }
5967
5968 case ABIArgInfo::Ignore:
5969 assert(NumIRArgs == 0);
5970 break;
5971
5972 case ABIArgInfo::Extend:
5973 case ABIArgInfo::Direct: {
5974 if (!isa<llvm::StructType>(Val: ArgInfo.getCoerceToType()) &&
5975 ArgInfo.getCoerceToType() == ConvertType(T: info_it->type) &&
5976 ArgInfo.getDirectOffset() == 0) {
5977 assert(NumIRArgs == 1);
5978 llvm::Value *V;
5979 if (!I->isAggregate())
5980 V = I->getKnownRValue().getScalarVal();
5981 else
5982 V = Builder.CreateLoad(
5983 Addr: I->hasLValue() ? I->getKnownLValue().getAddress()
5984 : I->getKnownRValue().getAggregateAddress());
5985
5986 // Implement swifterror by copying into a new swifterror argument.
5987 // We'll write back in the normal path out of the call.
5988 if (CallInfo.getExtParameterInfo(argIndex: ArgNo).getABI() ==
5989 ParameterABI::SwiftErrorResult) {
5990 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5991
5992 QualType pointeeTy = I->Ty->getPointeeType();
5993 swiftErrorArg = makeNaturalAddressForPointer(
5994 Ptr: V, T: pointeeTy, Alignment: getContext().getTypeAlignInChars(T: pointeeTy));
5995
5996 swiftErrorTemp = CreateMemTempWithoutCast(
5997 T: pointeeTy, Align: getPointerAlign(), Name: "swifterror.temp");
5998 V = swiftErrorTemp.getPointer();
5999 cast<llvm::AllocaInst>(Val: V)->setSwiftError(true);
6000
6001 llvm::Value *errorValue = Builder.CreateLoad(Addr: swiftErrorArg);
6002 Builder.CreateStore(Val: errorValue, Addr: swiftErrorTemp);
6003 }
6004
6005 // We might have to widen integers, but we should never truncate.
6006 if (ArgInfo.getCoerceToType() != V->getType() &&
6007 V->getType()->isIntegerTy())
6008 V = Builder.CreateZExt(V, DestTy: ArgInfo.getCoerceToType());
6009
6010 // The only plausible mismatch here would be for pointer address spaces.
6011 // We assume that the target has a reasonable mapping for the DefaultAS
6012 // (it can be casted to from incoming specific ASes), and insert an AS
6013 // cast to address the mismatch.
6014 if (FirstIRArg < IRFuncTy->getNumParams() &&
6015 V->getType() != IRFuncTy->getParamType(i: FirstIRArg)) {
6016 assert(V->getType()->isPointerTy() && "Only pointers can mismatch!");
6017 V = performAddrSpaceCast(Src: V, DestTy: IRFuncTy->getParamType(i: FirstIRArg));
6018 }
6019
6020 if (ArgHasMaybeUndefAttr)
6021 V = Builder.CreateFreeze(V);
6022 IRCallArgs[FirstIRArg] = V;
6023 break;
6024 }
6025
6026 llvm::StructType *STy =
6027 dyn_cast<llvm::StructType>(Val: ArgInfo.getCoerceToType());
6028
6029 // FIXME: Avoid the conversion through memory if possible.
6030 Address Src = Address::invalid();
6031 if (!I->isAggregate()) {
6032 Src = CreateMemTempWithoutCast(T: I->Ty, Name: "coerce");
6033 I->copyInto(CGF&: *this, Addr: Src);
6034 } else {
6035 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
6036 : I->getKnownRValue().getAggregateAddress();
6037 }
6038
6039 // If the value is offset in memory, apply the offset now.
6040 Src = emitAddressAtOffset(CGF&: *this, addr: Src, info: ArgInfo);
6041
6042 // Fast-isel and the optimizer generally like scalar values better than
6043 // FCAs, so we flatten them if this is safe to do for this argument.
6044 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
6045 llvm::Type *SrcTy = Src.getElementType();
6046 llvm::TypeSize SrcTypeSize =
6047 CGM.getDataLayout().getTypeAllocSize(Ty: SrcTy);
6048 llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(Ty: STy);
6049 if (SrcTypeSize.isScalable()) {
6050 assert(STy->containsHomogeneousScalableVectorTypes() &&
6051 "ABI only supports structure with homogeneous scalable vector "
6052 "type");
6053 assert(SrcTypeSize == DstTypeSize &&
6054 "Only allow non-fractional movement of structure with "
6055 "homogeneous scalable vector type");
6056 assert(NumIRArgs == STy->getNumElements());
6057
6058 llvm::Value *StoredStructValue =
6059 Builder.CreateLoad(Addr: Src, Name: Src.getName() + ".tuple");
6060 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6061 llvm::Value *Extract = Builder.CreateExtractValue(
6062 Agg: StoredStructValue, Idxs: i, Name: Src.getName() + ".extract" + Twine(i));
6063 IRCallArgs[FirstIRArg + i] = Extract;
6064 }
6065 } else {
6066 uint64_t SrcSize = SrcTypeSize.getFixedValue();
6067 uint64_t DstSize = DstTypeSize.getFixedValue();
6068 bool HasPFPFields = getContext().hasPFPFields(Ty: I->Ty);
6069
6070 // If the source type is smaller than the destination type of the
6071 // coerce-to logic, copy the source value into a temp alloca the size
6072 // of the destination type to allow loading all of it. The bits past
6073 // the source value are left undef.
6074 if (HasPFPFields || SrcSize < DstSize) {
6075 Address TempAlloca = CreateTempAlloca(Ty: STy, align: Src.getAlignment(),
6076 Name: Src.getName() + ".coerce");
6077 if (HasPFPFields) {
6078 // Structures with PFP fields require a coerced load to remove any
6079 // pointer signatures.
6080 Builder.CreateStore(
6081 Val: CreatePFPCoercedLoad(Src, SrcFETy: I->Ty, Ty: ArgInfo.getCoerceToType(),
6082 CGF&: *this),
6083 Addr: TempAlloca);
6084 } else
6085 Builder.CreateMemCpy(Dest: TempAlloca, Src, Size: SrcSize);
6086 Src = TempAlloca;
6087 } else {
6088 Src = Src.withElementType(ElemTy: STy);
6089 }
6090
6091 assert(NumIRArgs == STy->getNumElements());
6092 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6093 Address EltPtr = Builder.CreateStructGEP(Addr: Src, Index: i);
6094 llvm::Value *LI = Builder.CreateLoad(Addr: EltPtr);
6095 if (ArgHasMaybeUndefAttr)
6096 LI = Builder.CreateFreeze(V: LI);
6097 IRCallArgs[FirstIRArg + i] = LI;
6098 }
6099 }
6100 } else {
6101 // In the simple case, just pass the coerced loaded value.
6102 assert(NumIRArgs == 1);
6103 llvm::Value *Load =
6104 CreateCoercedLoad(Src, SrcFETy: I->Ty, Ty: ArgInfo.getCoerceToType(), CGF&: *this);
6105
6106 if (CallInfo.isCmseNSCall()) {
6107 // For certain parameter types, clear padding bits, as they may reveal
6108 // sensitive information.
6109 // Small struct/union types are passed as integer arrays.
6110 auto *ATy = dyn_cast<llvm::ArrayType>(Val: Load->getType());
6111 if (ATy != nullptr && isa<RecordType>(Val: I->Ty.getCanonicalType()))
6112 Load = EmitCMSEClearRecord(Src: Load, ATy, QTy: I->Ty);
6113 }
6114
6115 if (ArgHasMaybeUndefAttr)
6116 Load = Builder.CreateFreeze(V: Load);
6117 IRCallArgs[FirstIRArg] = Load;
6118 }
6119
6120 break;
6121 }
6122
6123 case ABIArgInfo::CoerceAndExpand: {
6124 auto coercionType = ArgInfo.getCoerceAndExpandType();
6125 auto layout = CGM.getDataLayout().getStructLayout(Ty: coercionType);
6126 auto unpaddedCoercionType = ArgInfo.getUnpaddedCoerceAndExpandType();
6127 auto *unpaddedStruct = dyn_cast<llvm::StructType>(Val: unpaddedCoercionType);
6128
6129 Address addr = Address::invalid();
6130 RawAddress AllocaAddr = RawAddress::invalid();
6131 bool NeedLifetimeEnd = false;
6132 if (I->isAggregate()) {
6133 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
6134 : I->getKnownRValue().getAggregateAddress();
6135
6136 } else {
6137 RValue RV = I->getKnownRValue();
6138 assert(RV.isScalar()); // complex should always just be direct
6139
6140 llvm::Type *scalarType = RV.getScalarVal()->getType();
6141 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(Ty: scalarType);
6142
6143 // Materialize to a temporary.
6144 addr = CreateTempAlloca(Ty: RV.getScalarVal()->getType(),
6145 align: CharUnits::fromQuantity(Quantity: std::max(
6146 a: layout->getAlignment(), b: scalarAlign)),
6147 Name: "tmp",
6148 /*ArraySize=*/nullptr, Alloca: &AllocaAddr);
6149 NeedLifetimeEnd = EmitLifetimeStart(Addr: AllocaAddr.getPointer());
6150
6151 Builder.CreateStore(Val: RV.getScalarVal(), Addr: addr);
6152 }
6153
6154 addr = addr.withElementType(ElemTy: coercionType);
6155
6156 unsigned IRArgPos = FirstIRArg;
6157 unsigned unpaddedIndex = 0;
6158 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
6159 llvm::Type *eltType = coercionType->getElementType(N: i);
6160 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
6161 continue;
6162 Address eltAddr = Builder.CreateStructGEP(Addr: addr, Index: i);
6163 llvm::Value *elt = CreateCoercedLoad(
6164 Src: eltAddr, SrcFETy: I->Ty,
6165 Ty: unpaddedStruct ? unpaddedStruct->getElementType(N: unpaddedIndex++)
6166 : unpaddedCoercionType,
6167 CGF&: *this);
6168 if (ArgHasMaybeUndefAttr)
6169 elt = Builder.CreateFreeze(V: elt);
6170 IRCallArgs[IRArgPos++] = elt;
6171 }
6172 assert(IRArgPos == FirstIRArg + NumIRArgs);
6173
6174 if (NeedLifetimeEnd)
6175 EmitLifetimeEnd(Addr: AllocaAddr.getPointer());
6176 break;
6177 }
6178
6179 case ABIArgInfo::Expand: {
6180 unsigned IRArgPos = FirstIRArg;
6181 ExpandTypeToArgs(Ty: I->Ty, Arg: *I, IRFuncTy, IRCallArgs, IRCallArgPos&: IRArgPos);
6182 assert(IRArgPos == FirstIRArg + NumIRArgs);
6183 break;
6184 }
6185
6186 case ABIArgInfo::TargetSpecific: {
6187 Address Src = Address::invalid();
6188 if (!I->isAggregate()) {
6189 Src = CreateMemTempWithoutCast(T: I->Ty, Name: "target_coerce");
6190 I->copyInto(CGF&: *this, Addr: Src);
6191 } else {
6192 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
6193 : I->getKnownRValue().getAggregateAddress();
6194 }
6195
6196 // If the value is offset in memory, apply the offset now.
6197 Src = emitAddressAtOffset(CGF&: *this, addr: Src, info: ArgInfo);
6198 llvm::Value *Load =
6199 CGM.getABIInfo().createCoercedLoad(SrcAddr: Src, AI: ArgInfo, CGF&: *this);
6200 IRCallArgs[FirstIRArg] = Load;
6201 break;
6202 }
6203 }
6204 }
6205
6206 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(CGF&: *this);
6207 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
6208
6209 // If we're using inalloca, set up that argument.
6210 if (ArgMemory.isValid()) {
6211 llvm::Value *Arg = ArgMemory.getPointer();
6212 assert(IRFunctionArgs.hasInallocaArg());
6213 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
6214 }
6215
6216 // 2. Prepare the function pointer.
6217
6218 // If the callee is a bitcast of a non-variadic function to have a
6219 // variadic function pointer type, check to see if we can remove the
6220 // bitcast. This comes up with unprototyped functions.
6221 //
6222 // This makes the IR nicer, but more importantly it ensures that we
6223 // can inline the function at -O0 if it is marked always_inline.
6224 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
6225 llvm::Value *Ptr) -> llvm::Function * {
6226 if (!CalleeFT->isVarArg())
6227 return nullptr;
6228
6229 // Get underlying value if it's a bitcast
6230 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Val: Ptr)) {
6231 if (CE->getOpcode() == llvm::Instruction::BitCast)
6232 Ptr = CE->getOperand(i_nocapture: 0);
6233 }
6234
6235 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Val: Ptr);
6236 if (!OrigFn)
6237 return nullptr;
6238
6239 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
6240
6241 // If the original type is variadic, or if any of the component types
6242 // disagree, we cannot remove the cast.
6243 if (OrigFT->isVarArg() ||
6244 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
6245 OrigFT->getReturnType() != CalleeFT->getReturnType())
6246 return nullptr;
6247
6248 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
6249 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
6250 return nullptr;
6251
6252 return OrigFn;
6253 };
6254
6255 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
6256 CalleePtr = OrigFn;
6257 IRFuncTy = OrigFn->getFunctionType();
6258 }
6259
6260 // 3. Perform the actual call.
6261
6262 // Deactivate any cleanups that we're supposed to do immediately before
6263 // the call.
6264 if (!CallArgs.getCleanupsToDeactivate().empty())
6265 deactivateArgCleanupsBeforeCall(CGF&: *this, CallArgs);
6266
6267 // Update the largest vector width if any arguments have vector types.
6268 for (unsigned i = 0; i < IRCallArgs.size(); ++i)
6269 LargestVectorWidth = std::max(a: LargestVectorWidth,
6270 b: getMaxVectorWidth(Ty: IRCallArgs[i]->getType()));
6271
6272 // Compute the calling convention and attributes.
6273 unsigned CallingConv;
6274 llvm::AttributeList Attrs;
6275 CGM.ConstructAttributeList(Name: CalleePtr->getName(), FI: CallInfo,
6276 CalleeInfo: Callee.getAbstractInfo(), AttrList&: Attrs, CallingConv,
6277 /*AttrOnCallSite=*/true,
6278 /*IsThunk=*/false);
6279
6280 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
6281 getTarget().getTriple().isWindowsArm64EC()) {
6282 CGM.Error(loc: Loc, error: "__vectorcall calling convention is not currently "
6283 "supported");
6284 }
6285
6286 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurFuncDecl)) {
6287 if (FD->hasAttr<StrictFPAttr>())
6288 // All calls within a strictfp function are marked strictfp
6289 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::StrictFP);
6290
6291 // If -ffast-math is enabled and the function is guarded by an
6292 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
6293 // library call instead of the intrinsic.
6294 if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
6295 CGM.AdjustMemoryAttribute(Name: CalleePtr->getName(), CalleeInfo: Callee.getAbstractInfo(),
6296 Attrs);
6297 }
6298 // Add call-site nomerge attribute if exists.
6299 if (InNoMergeAttributedStmt)
6300 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::NoMerge);
6301
6302 // Add call-site noinline attribute if exists.
6303 if (InNoInlineAttributedStmt)
6304 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::NoInline);
6305
6306 // Add call-site always_inline attribute if exists.
6307 // Note: This corresponds to the [[clang::always_inline]] statement attribute.
6308 if (InAlwaysInlineAttributedStmt &&
6309 !CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
6310 Caller: CallerDecl, Callee: CalleeDecl))
6311 Attrs =
6312 Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::AlwaysInline);
6313
6314 // Remove call-site convergent attribute if requested.
6315 if (InNoConvergentAttributedStmt)
6316 Attrs =
6317 Attrs.removeFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::Convergent);
6318
6319 // Apply some call-site-specific attributes.
6320 // TODO: work this into building the attribute set.
6321
6322 // Apply always_inline to all calls within flatten functions.
6323 // FIXME: should this really take priority over __try, below?
6324 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
6325 !InNoInlineAttributedStmt &&
6326 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>()) &&
6327 !CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
6328 Caller: CallerDecl, Callee: CalleeDecl)) {
6329 Attrs =
6330 Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::AlwaysInline);
6331 }
6332
6333 // Disable inlining inside SEH __try blocks.
6334 if (isSEHTryScope()) {
6335 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::NoInline);
6336 }
6337
6338 // Decide whether to use a call or an invoke.
6339 bool CannotThrow;
6340 if (currentFunctionUsesSEHTry()) {
6341 // SEH cares about asynchronous exceptions, so everything can "throw."
6342 CannotThrow = false;
6343 } else if (isCleanupPadScope() &&
6344 getEHPersonality(CGF&: *this).isMSVCXXPersonality()) {
6345 // The MSVC++ personality will implicitly terminate the program if an
6346 // exception is thrown during a cleanup outside of a try/catch.
6347 // We don't need to model anything in IR to get this behavior.
6348 CannotThrow = true;
6349 } else {
6350 // Otherwise, nounwind call sites will never throw.
6351 CannotThrow = Attrs.hasFnAttr(Kind: llvm::Attribute::NoUnwind);
6352
6353 if (auto *FPtr = dyn_cast<llvm::Function>(Val: CalleePtr))
6354 if (FPtr->hasFnAttribute(Kind: llvm::Attribute::NoUnwind))
6355 CannotThrow = true;
6356 }
6357
6358 // If we made a temporary, be sure to clean up after ourselves. Note that we
6359 // can't depend on being inside of an ExprWithCleanups, so we need to manually
6360 // pop this cleanup later on. Being eager about this is OK, since this
6361 // temporary is 'invisible' outside of the callee.
6362 // Use the original alloca pointer (before any addrspacecast) for the
6363 // lifetime end marker, since lifetime intrinsics must reference the alloca
6364 // address space.
6365 if (NeedSRetLifetimeEnd)
6366 pushFullExprCleanup<CallLifetimeEnd>(kind: NormalEHLifetimeMarker, A: SRetAlloca);
6367
6368 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
6369
6370 SmallVector<llvm::OperandBundleDef, 1> BundleList =
6371 getBundlesForFunclet(Callee: CalleePtr);
6372
6373 if (SanOpts.has(K: SanitizerKind::KCFI) &&
6374 !isa_and_nonnull<FunctionDecl>(Val: TargetDecl))
6375 EmitKCFIOperandBundle(Callee: ConcreteCallee, Bundles&: BundleList);
6376
6377 // Add the pointer-authentication bundle.
6378 EmitPointerAuthOperandBundle(Info: ConcreteCallee.getPointerAuthInfo(), Bundles&: BundleList);
6379
6380 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: CurFuncDecl))
6381 if (FD->hasAttr<StrictFPAttr>())
6382 // All calls within a strictfp function are marked strictfp
6383 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: llvm::Attribute::StrictFP);
6384
6385 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
6386 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
6387
6388 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
6389 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
6390
6391 // Emit the actual call/invoke instruction.
6392 llvm::CallBase *CI;
6393 if (!InvokeDest) {
6394 CI = Builder.CreateCall(FTy: IRFuncTy, Callee: CalleePtr, Args: IRCallArgs, OpBundles: BundleList);
6395 } else {
6396 llvm::BasicBlock *Cont = createBasicBlock(name: "invoke.cont");
6397 CI = Builder.CreateInvoke(Ty: IRFuncTy, Callee: CalleePtr, NormalDest: Cont, UnwindDest: InvokeDest, Args: IRCallArgs,
6398 OpBundles: BundleList);
6399 EmitBlock(BB: Cont);
6400 }
6401 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
6402 CI->getCalledFunction()->getName().starts_with(Prefix: "_Z4sqrt")) {
6403 SetSqrtFPAccuracy(CI);
6404 }
6405 if (callOrInvoke) {
6406 *callOrInvoke = CI;
6407 if (CGM.getCodeGenOpts().CallGraphSection) {
6408 QualType CST;
6409 if (TargetDecl && TargetDecl->getFunctionType())
6410 CST = QualType(TargetDecl->getFunctionType(), 0);
6411 else if (const auto *FPT =
6412 Callee.getAbstractInfo().getCalleeFunctionProtoType())
6413 CST = QualType(FPT, 0);
6414 else if (const auto *FT =
6415 Callee.getAbstractInfo().getCalleeFunctionType())
6416 CST = QualType(FT, 0);
6417 else
6418 llvm_unreachable(
6419 "Cannot find the callee type to generate callee_type metadata.");
6420
6421 // Set type identifier metadata of indirect calls for call graph section.
6422 if (!CST.isNull()) {
6423 if (!CST->isFunctionProtoType()) {
6424 // Reconstruct a prototype for unprototyped callees from the argument
6425 // types passed at the call site (after default argument promotion).
6426 //
6427 // Basic Rationale & K&R-Style Definitions:
6428 // The argument types in CallArgs have already undergone C default
6429 // argument promotion (e.g., char/short -> int, float -> double).
6430 // Furthermore, for a K&R-style
6431 // definition (e.g., void foo(x) short x; { ... }), canonical C ABI
6432 // semantics expect the promoted type (int) at the call boundary
6433 // and implicitly cast down to the declared type (short) inside the
6434 // function. Therefore, signature computation at K&R definition
6435 // sites must also apply default argument promotion (yielding
6436 // void(int), not void(short)) so definition and call sites match.
6437 //
6438 // Signature Strictness & Normalization:
6439 // Since type identifier matching relies on exact hash equality, any
6440 // tolerance for C compatibility rules must be done by normalizing
6441 // types before hashing.
6442 // - Standard C allows certain exceptions for unprototyped calls (and
6443 // variadic va_arg), such as differences in signedness (e.g.,
6444 // passing an int to an unsigned int parameter) or
6445 // interchangeability of enum types with their underlying integer
6446 // types.
6447 // - Existing CFI normalization (e.g.,
6448 // -fsanitize-cfi-icall-experimental-normalize-integers) normalizes
6449 // types by bit-width and signedness (e.g., int vs long on LP64,
6450 // which C does not treat as compatible), but does not normalize
6451 // away signedness or enum mismatches.
6452 // - In the future, whether to normalize away signedness, enums, or
6453 // integer bit-widths depends on whether call graph analysis should
6454 // err on the side of inclusion (admitting any C-valid call) or
6455 // strictness (like CFI). Any normalization applied here at the call
6456 // site must remain strictly matched with definition-site
6457 // type signature computation.
6458 if (const auto *FNPT = CST->getAs<FunctionNoProtoType>()) {
6459 SmallVector<QualType, 8> ParamTypes;
6460 // CallArgs already contains default-promoted argument types for
6461 // unprototyped calls.
6462 for (const CallArg &Arg : CallArgs)
6463 ParamTypes.push_back(Elt: Arg.getType());
6464 CST = CGM.ReconstructCallGraphPrototype(FNPT, ParamTypes);
6465 }
6466
6467 llvm::Metadata *MD =
6468 CGM.CreateMetadataIdentifierForCallGraphType(T: CST);
6469 StringRef TypeStr;
6470 if (auto *MDS = dyn_cast_or_null<llvm::MDString>(Val: MD))
6471 TypeStr = MDS->getString();
6472
6473 CGM.getDiags().Report(Loc, DiagID: diag::warn_cgs_no_proto) << CST << TypeStr;
6474 }
6475 CGM.createCalleeTypeMetadataForIcall(QT: CST, CB: *callOrInvoke);
6476 }
6477 }
6478 }
6479
6480 // If this is within a function that has the guard(nocf) attribute and is an
6481 // indirect call, add the "guard_nocf" attribute to this call to indicate that
6482 // Control Flow Guard checks should not be added, even if the call is inlined.
6483 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: CurFuncDecl)) {
6484 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
6485 if (A->getGuard() == CFGuardAttr::GuardArg::nocf &&
6486 !CI->getCalledFunction())
6487 Attrs = Attrs.addFnAttribute(C&: getLLVMContext(), Kind: "guard_nocf");
6488 }
6489 }
6490
6491 // Apply the attributes and calling convention.
6492 CI->setAttributes(Attrs);
6493 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
6494
6495 // Apply various metadata.
6496
6497 if (!CI->getType()->isVoidTy())
6498 CI->setName("call");
6499
6500 if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
6501 CI = addConvergenceControlToken(Input: CI);
6502
6503 // Update largest vector width from the return type.
6504 LargestVectorWidth =
6505 std::max(a: LargestVectorWidth, b: getMaxVectorWidth(Ty: CI->getType()));
6506
6507 // Insert instrumentation or attach profile metadata at indirect call sites.
6508 // For more details, see the comment before the definition of
6509 // IPVK_IndirectCallTarget in InstrProfData.inc.
6510 if (!CI->getCalledFunction())
6511 PGO->valueProfile(Builder, ValueKind: llvm::IPVK_IndirectCallTarget, ValueSite: CI, ValuePtr: CalleePtr);
6512
6513 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
6514 // optimizer it can aggressively ignore unwind edges.
6515 if (CGM.getLangOpts().ObjCAutoRefCount)
6516 AddObjCARCExceptionMetadata(Inst: CI);
6517
6518 // Set tail call kind if necessary.
6519 bool IsPPC = getTarget().getTriple().isPPC();
6520 bool IsMIPS = getTarget().getTriple().isMIPS();
6521 bool HasMips16 = false;
6522 if (IsMIPS) {
6523 const TargetOptions &TargetOpts = getTarget().getTargetOpts();
6524 HasMips16 = TargetOpts.FeatureMap.lookup(Key: "mips16");
6525 if (!HasMips16)
6526 HasMips16 = llvm::is_contained(Range: TargetOpts.Features, Element: "+mips16");
6527 }
6528 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(Val: CI)) {
6529 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
6530 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
6531 else if (IsMustTail) {
6532 if (IsPPC) {
6533 if (getTarget().getTriple().isOSAIX())
6534 CGM.getDiags().Report(Loc, DiagID: diag::err_aix_musttail_unsupported);
6535 else if (!getTarget().hasFeature(Feature: "pcrelative-memops")) {
6536 if (getTarget().hasFeature(Feature: "longcall"))
6537 CGM.getDiags().Report(Loc, DiagID: diag::err_ppc_impossible_musttail) << 0;
6538 else if (Call->isIndirectCall())
6539 CGM.getDiags().Report(Loc, DiagID: diag::err_ppc_impossible_musttail) << 1;
6540 else if (isa_and_nonnull<FunctionDecl>(Val: TargetDecl)) {
6541 if (!cast<FunctionDecl>(Val: TargetDecl)->isDefined())
6542 // The undefined callee may be a forward declaration. Without
6543 // knowning all symbols in the module, we won't know the symbol is
6544 // defined or not. Collect all these symbols for later diagnosing.
6545 CGM.addUndefinedGlobalForTailCall(
6546 Global: {cast<FunctionDecl>(Val: TargetDecl), Loc});
6547 else {
6548 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(
6549 GD: GlobalDecl(cast<FunctionDecl>(Val: TargetDecl)));
6550 if (llvm::GlobalValue::isWeakForLinker(Linkage) ||
6551 llvm::GlobalValue::isDiscardableIfUnused(Linkage))
6552 CGM.getDiags().Report(Loc, DiagID: diag::err_ppc_impossible_musttail)
6553 << 2;
6554 }
6555 }
6556 }
6557 }
6558 if (IsMIPS) {
6559 if (HasMips16)
6560 CGM.getDiags().Report(Loc, DiagID: diag::err_mips_impossible_musttail) << 0;
6561 else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
6562 CGM.addUndefinedGlobalForTailCall(Global: {FD, Loc});
6563 }
6564 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
6565 }
6566 }
6567
6568 // Add metadata for calls to MSAllocator functions
6569 if (getDebugInfo() && TargetDecl && TargetDecl->hasAttr<MSAllocatorAttr>())
6570 getDebugInfo()->addHeapAllocSiteMetadata(CallSite: CI, AllocatedTy: RetTy->getPointeeType(), Loc);
6571
6572 // Add srcloc metadata for [[gnu::error/warning]] diagnostics. When
6573 // ShowInliningChain is enabled, also track inline/static calls for the
6574 // heuristic fallback when debug info is not available. This heuristic is
6575 // conservative and best-effort since static or inline-annotated functions
6576 // are still not guaranteed to be inlined.
6577 if (TargetDecl) {
6578 bool NeedSrcLoc = TargetDecl->hasAttr<ErrorAttr>();
6579 if (!NeedSrcLoc && CGM.getCodeGenOpts().ShowInliningChain) {
6580 if (const auto *FD = dyn_cast<FunctionDecl>(Val: TargetDecl))
6581 NeedSrcLoc = FD->isInlined() || FD->hasAttr<AlwaysInlineAttr>() ||
6582 FD->getStorageClass() == SC_Static ||
6583 FD->isInAnonymousNamespace();
6584 }
6585 if (NeedSrcLoc) {
6586 auto *Line = llvm::ConstantInt::get(Ty: Int64Ty, V: Loc.getRawEncoding());
6587 auto *MD = llvm::ConstantAsMetadata::get(C: Line);
6588 CI->setMetadata(Kind: "srcloc", Node: llvm::MDNode::get(Context&: getLLVMContext(), MDs: {MD}));
6589 }
6590 }
6591
6592 // 4. Finish the call.
6593
6594 // If the call doesn't return, finish the basic block and clear the
6595 // insertion point; this allows the rest of IRGen to discard
6596 // unreachable code.
6597 if (CI->doesNotReturn()) {
6598 if (NeedSRetLifetimeEnd)
6599 PopCleanupBlock();
6600
6601 // Strip away the noreturn attribute to better diagnose unreachable UB.
6602 if (SanOpts.has(K: SanitizerKind::Unreachable)) {
6603 // Also remove from function since CallBase::hasFnAttr additionally checks
6604 // attributes of the called function.
6605 if (auto *F = CI->getCalledFunction())
6606 F->removeFnAttr(Kind: llvm::Attribute::NoReturn);
6607 CI->removeFnAttr(Kind: llvm::Attribute::NoReturn);
6608
6609 // Avoid incompatibility with ASan which relies on the `noreturn`
6610 // attribute to insert handler calls.
6611 if (SanOpts.hasOneOf(K: SanitizerKind::Address |
6612 SanitizerKind::KernelAddress)) {
6613 SanitizerScope SanScope(this);
6614 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
6615 Builder.SetInsertPoint(CI);
6616 auto *FnType = llvm::FunctionType::get(Result: CGM.VoidTy, /*isVarArg=*/false);
6617 llvm::FunctionCallee Fn =
6618 CGM.CreateRuntimeFunction(Ty: FnType, Name: "__asan_handle_no_return");
6619 EmitNounwindRuntimeCall(callee: Fn);
6620 }
6621 }
6622
6623 EmitUnreachable(Loc);
6624 Builder.ClearInsertionPoint();
6625
6626 // FIXME: For now, emit a dummy basic block because expr emitters in
6627 // generally are not ready to handle emitting expressions at unreachable
6628 // points.
6629 EnsureInsertPoint();
6630
6631 // Return a reasonable RValue.
6632 return GetUndefRValue(Ty: RetTy);
6633 }
6634
6635 // If this is a musttail call, return immediately. We do not branch to the
6636 // epilogue in this case.
6637 if (IsMustTail) {
6638 for (auto it = EHStack.find(sp: CurrentCleanupScopeDepth); it != EHStack.end();
6639 ++it) {
6640 // A noexcept caller pushes an EHTerminateScope to call std::terminate()
6641 // if an exception escapes. A musttail call replaces the caller's frame,
6642 // removing this handler. This is safe if the callee is also nounwind:
6643 // the callee's own noexcept handler prevents any exception from reaching
6644 // where the caller's handler would have been.
6645 if (isa<EHTerminateScope>(Val: &*it)) {
6646 if (CI->doesNotThrow())
6647 continue;
6648 CGM.getDiags().Report(Loc: MustTailCall->getBeginLoc(),
6649 DiagID: diag::err_musttail_noexcept_mismatch);
6650 break;
6651 }
6652 if (auto *Cleanup = dyn_cast<EHCleanupScope>(Val: &*it)) {
6653 // Fake uses can be safely emitted immediately prior to the tail call,
6654 // so we choose to emit them just before the call here.
6655 if (Cleanup->isFakeUse()) {
6656 CGBuilderTy::InsertPointGuard IPG(Builder);
6657 Builder.SetInsertPoint(CI);
6658 Cleanup->getCleanup()->Emit(CGF&: *this, flags: EHScopeStack::Cleanup::Flags());
6659 continue;
6660 }
6661 if (Cleanup->isRedundantBeforeReturn())
6662 continue;
6663 }
6664 CGM.ErrorUnsupported(S: MustTailCall, Type: "tail call skipping over cleanups");
6665 }
6666 if (CI->getType()->isVoidTy())
6667 Builder.CreateRetVoid();
6668 else
6669 Builder.CreateRet(V: CI);
6670 Builder.ClearInsertionPoint();
6671 EnsureInsertPoint();
6672 return GetUndefRValue(Ty: RetTy);
6673 }
6674
6675 // Perform the swifterror writeback.
6676 if (swiftErrorTemp.isValid()) {
6677 llvm::Value *errorResult = Builder.CreateLoad(Addr: swiftErrorTemp);
6678 Builder.CreateStore(Val: errorResult, Addr: swiftErrorArg);
6679 }
6680
6681 // Emit any call-associated writebacks immediately. Arguably this
6682 // should happen after any return-value munging.
6683 if (CallArgs.hasWritebacks())
6684 EmitWritebacks(args: CallArgs);
6685
6686 // The stack cleanup for inalloca arguments has to run out of the normal
6687 // lexical order, so deactivate it and run it manually here.
6688 CallArgs.freeArgumentMemory(CGF&: *this);
6689
6690 // Extract the return value.
6691 RValue Ret;
6692
6693 // If the current function is a virtual function pointer thunk, avoid copying
6694 // the return value of the musttail call to a temporary.
6695 if (IsVirtualFunctionPointerThunk) {
6696 Ret = RValue::get(V: CI);
6697 } else {
6698 Ret = [&] {
6699 switch (RetAI.getKind()) {
6700 case ABIArgInfo::CoerceAndExpand: {
6701 auto coercionType = RetAI.getCoerceAndExpandType();
6702
6703 Address addr = SRetPtr.withElementType(ElemTy: coercionType);
6704
6705 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
6706 bool requiresExtract = isa<llvm::StructType>(Val: CI->getType());
6707
6708 unsigned unpaddedIndex = 0;
6709 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
6710 llvm::Type *eltType = coercionType->getElementType(N: i);
6711 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
6712 continue;
6713 Address eltAddr = Builder.CreateStructGEP(Addr: addr, Index: i);
6714 llvm::Value *elt = CI;
6715 if (requiresExtract)
6716 elt = Builder.CreateExtractValue(Agg: elt, Idxs: unpaddedIndex++);
6717 else
6718 assert(unpaddedIndex == 0);
6719 Builder.CreateStore(Val: elt, Addr: eltAddr);
6720 }
6721 [[fallthrough]];
6722 }
6723
6724 case ABIArgInfo::InAlloca:
6725 case ABIArgInfo::Indirect: {
6726 RValue ret = convertTempToRValue(addr: SRetPtr, type: RetTy, Loc: SourceLocation());
6727 if (NeedSRetLifetimeEnd)
6728 PopCleanupBlock();
6729 return ret;
6730 }
6731
6732 case ABIArgInfo::Ignore:
6733 // If we are ignoring an argument that had a result, make sure to
6734 // construct the appropriate return value for our caller.
6735 return GetUndefRValue(Ty: RetTy);
6736
6737 case ABIArgInfo::Extend:
6738 case ABIArgInfo::Direct: {
6739 llvm::Type *RetIRTy = ConvertType(T: RetTy);
6740 if (RetAI.getCoerceToType() == RetIRTy &&
6741 RetAI.getDirectOffset() == 0) {
6742 switch (getEvaluationKind(T: RetTy)) {
6743 case TEK_Complex: {
6744 llvm::Value *Real = Builder.CreateExtractValue(Agg: CI, Idxs: 0);
6745 llvm::Value *Imag = Builder.CreateExtractValue(Agg: CI, Idxs: 1);
6746 return RValue::getComplex(C: std::make_pair(x&: Real, y&: Imag));
6747 }
6748 case TEK_Aggregate:
6749 break;
6750 case TEK_Scalar: {
6751 // If the argument doesn't match, perform a bitcast to coerce it.
6752 // This can happen due to trivial type mismatches.
6753 llvm::Value *V = CI;
6754 if (V->getType() != RetIRTy)
6755 V = Builder.CreateBitCast(V, DestTy: RetIRTy);
6756 return RValue::get(V);
6757 }
6758 }
6759 }
6760
6761 // If coercing a fixed vector from a scalable vector for ABI
6762 // compatibility, and the types match, use the llvm.vector.extract
6763 // intrinsic to perform the conversion.
6764 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(Val: RetIRTy)) {
6765 llvm::Value *V = CI;
6766 if (auto *ScalableSrcTy =
6767 dyn_cast<llvm::ScalableVectorType>(Val: V->getType())) {
6768 if (FixedDstTy->getElementType() ==
6769 ScalableSrcTy->getElementType()) {
6770 V = Builder.CreateExtractVector(DstType: FixedDstTy, SrcVec: V, Idx: uint64_t(0),
6771 Name: "cast.fixed");
6772 return RValue::get(V);
6773 }
6774 }
6775 }
6776
6777 Address DestPtr = ReturnValue.getValue();
6778 bool DestIsVolatile = ReturnValue.isVolatile();
6779 uint64_t DestSize =
6780 getContext().getTypeInfoDataSizeInChars(T: RetTy).Width.getQuantity();
6781
6782 if (!DestPtr.isValid()) {
6783 DestPtr = CreateMemTempWithoutCast(T: RetTy, Name: "coerce");
6784 DestIsVolatile = false;
6785 DestSize = getContext().getTypeSizeInChars(T: RetTy).getQuantity();
6786 }
6787
6788 // An empty record can overlap other data (if declared with
6789 // no_unique_address); omit the store for such types - as there is no
6790 // actual data to store.
6791 if (!isEmptyRecord(Context&: getContext(), T: RetTy, AllowArrays: true)) {
6792 // If the value is offset in memory, apply the offset now.
6793 Address StorePtr = emitAddressAtOffset(CGF&: *this, addr: DestPtr, info: RetAI);
6794 CreateCoercedStore(
6795 Src: CI, SrcFETy: RetTy, Dst: StorePtr,
6796 DstSize: llvm::TypeSize::getFixed(ExactSize: DestSize - RetAI.getDirectOffset()),
6797 DstIsVolatile: DestIsVolatile);
6798 }
6799
6800 return convertTempToRValue(addr: DestPtr, type: RetTy, Loc: SourceLocation());
6801 }
6802
6803 case ABIArgInfo::TargetSpecific: {
6804 Address DestPtr = ReturnValue.getValue();
6805 Address StorePtr = emitAddressAtOffset(CGF&: *this, addr: DestPtr, info: RetAI);
6806 bool DestIsVolatile = ReturnValue.isVolatile();
6807 if (!DestPtr.isValid()) {
6808 DestPtr = CreateMemTempWithoutCast(T: RetTy, Name: "target_coerce");
6809 DestIsVolatile = false;
6810 }
6811 CGM.getABIInfo().createCoercedStore(Val: CI, DstAddr: StorePtr, AI: RetAI, DestIsVolatile,
6812 CGF&: *this);
6813 return convertTempToRValue(addr: DestPtr, type: RetTy, Loc: SourceLocation());
6814 }
6815
6816 case ABIArgInfo::Expand:
6817 case ABIArgInfo::IndirectAliased:
6818 llvm_unreachable("Invalid ABI kind for return argument");
6819 }
6820
6821 llvm_unreachable("Unhandled ABIArgInfo::Kind");
6822 }();
6823 }
6824
6825 // Emit the assume_aligned check on the return value.
6826 if (Ret.isScalar() && TargetDecl) {
6827 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6828 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6829 }
6830
6831 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6832 // we can't use the full cleanup mechanism.
6833 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6834 LifetimeEnd.Emit(CGF&: *this, /*Flags=*/flags: {});
6835
6836 if (!ReturnValue.isExternallyDestructed() &&
6837 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
6838 pushDestroy(dtorKind: QualType::DK_nontrivial_c_struct, addr: Ret.getAggregateAddress(),
6839 type: RetTy);
6840
6841 // Generate function declaration DISuprogram in order to be used
6842 // in debug info about call sites.
6843 if (CGDebugInfo *DI = getDebugInfo()) {
6844 // Ensure call site info would actually be emitted before collecting
6845 // further callee info.
6846 if (CalleeDecl && !CalleeDecl->hasAttr<NoDebugAttr>() &&
6847 DI->getCallSiteRelatedAttrs() != llvm::DINode::FlagZero) {
6848 CodeGenFunction CalleeCGF(CGM);
6849 const GlobalDecl &CalleeGlobalDecl =
6850 Callee.getAbstractInfo().getCalleeDecl();
6851 CalleeCGF.CurGD = CalleeGlobalDecl;
6852 FunctionArgList Args;
6853 QualType ResTy = CalleeCGF.BuildFunctionArgList(GD: CalleeGlobalDecl, Args);
6854 DI->EmitFuncDeclForCallSite(
6855 CallOrInvoke: CI, CalleeType: DI->getFunctionType(FD: CalleeDecl, RetTy: ResTy, Args), CalleeGlobalDecl);
6856 }
6857 // Generate call site target information.
6858 DI->addCallTargetIfVirtual(FD: CalleeDecl, CI);
6859 }
6860
6861 return Ret;
6862}
6863
6864CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
6865 if (isVirtual()) {
6866 const CallExpr *CE = getVirtualCallExpr();
6867 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
6868 CGF, GD: getVirtualMethodDecl(), This: getThisAddress(), Ty: getVirtualFunctionType(),
6869 Loc: CE ? CE->getBeginLoc() : SourceLocation());
6870 }
6871
6872 return *this;
6873}
6874
6875/* VarArg handling */
6876
6877RValue CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr,
6878 AggValueSlot Slot) {
6879 VAListAddr = VE->isMicrosoftABI()
6880 ? EmitMSVAListRef(E: VE->getSubExpr())
6881 : (VE->isZOSABI() ? EmitZOSVAListRef(E: VE->getSubExpr())
6882 : EmitVAListRef(E: VE->getSubExpr()));
6883 QualType Ty = VE->getType();
6884 if (Ty->isVariablyModifiedType())
6885 EmitVariablyModifiedType(Ty);
6886 if (VE->isMicrosoftABI())
6887 return CGM.getABIInfo().EmitMSVAArg(CGF&: *this, VAListAddr, Ty, Slot);
6888 if (VE->isZOSABI())
6889 return CGM.getABIInfo().EmitZOSVAArg(CGF&: *this, VAListAddr, Ty, Slot);
6890 return CGM.getABIInfo().EmitVAArg(CGF&: *this, VAListAddr, Ty, Slot);
6891}
6892
6893DisableDebugLocationUpdates::DisableDebugLocationUpdates(CodeGenFunction &CGF)
6894 : CGF(CGF) {
6895 CGF.disableDebugInfo();
6896}
6897
6898DisableDebugLocationUpdates::~DisableDebugLocationUpdates() {
6899 CGF.enableDebugInfo();
6900}
6901