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