1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
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
7 //===----------------------------------------------------------------------===//
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
12 //===----------------------------------------------------------------------===//
16 #include "ABIInfoImpl.h"
19 #include "CGCleanup.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenModule.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/Basic/CodeGenOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/CodeGen/CGFunctionInfo.h"
31 #include "clang/CodeGen/SwiftCallingConv.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Assumptions.h"
35 #include "llvm/IR/AttributeMask.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/InlineAsm.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/Transforms/Utils/Local.h"
45 using namespace clang
;
46 using namespace CodeGen
;
50 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC
) {
52 default: return llvm::CallingConv::C
;
53 case CC_X86StdCall
: return llvm::CallingConv::X86_StdCall
;
54 case CC_X86FastCall
: return llvm::CallingConv::X86_FastCall
;
55 case CC_X86RegCall
: return llvm::CallingConv::X86_RegCall
;
56 case CC_X86ThisCall
: return llvm::CallingConv::X86_ThisCall
;
57 case CC_Win64
: return llvm::CallingConv::Win64
;
58 case CC_X86_64SysV
: return llvm::CallingConv::X86_64_SysV
;
59 case CC_AAPCS
: return llvm::CallingConv::ARM_AAPCS
;
60 case CC_AAPCS_VFP
: return llvm::CallingConv::ARM_AAPCS_VFP
;
61 case CC_IntelOclBicc
: return llvm::CallingConv::Intel_OCL_BI
;
62 // TODO: Add support for __pascal to LLVM.
63 case CC_X86Pascal
: return llvm::CallingConv::C
;
64 // TODO: Add support for __vectorcall to LLVM.
65 case CC_X86VectorCall
: return llvm::CallingConv::X86_VectorCall
;
66 case CC_AArch64VectorCall
: return llvm::CallingConv::AArch64_VectorCall
;
67 case CC_AArch64SVEPCS
: return llvm::CallingConv::AArch64_SVE_VectorCall
;
68 case CC_AMDGPUKernelCall
: return llvm::CallingConv::AMDGPU_KERNEL
;
69 case CC_SpirFunction
: return llvm::CallingConv::SPIR_FUNC
;
70 case CC_OpenCLKernel
: return CGM
.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
71 case CC_PreserveMost
: return llvm::CallingConv::PreserveMost
;
72 case CC_PreserveAll
: return llvm::CallingConv::PreserveAll
;
73 case CC_Swift
: return llvm::CallingConv::Swift
;
74 case CC_SwiftAsync
: return llvm::CallingConv::SwiftTail
;
75 case CC_M68kRTD
: return llvm::CallingConv::M68k_RTD
;
76 case CC_PreserveNone
: return llvm::CallingConv::PreserveNone
;
78 case CC_RISCVVectorCall
: return llvm::CallingConv::RISCV_VectorCall
;
83 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
84 /// qualification. Either or both of RD and MD may be null. A null RD indicates
85 /// that there is no meaningful 'this' type, and a null MD can occur when
86 /// calling a method pointer.
87 CanQualType
CodeGenTypes::DeriveThisType(const CXXRecordDecl
*RD
,
88 const CXXMethodDecl
*MD
) {
91 RecTy
= Context
.getTagDeclType(RD
)->getCanonicalTypeInternal();
93 RecTy
= Context
.VoidTy
;
96 RecTy
= Context
.getAddrSpaceQualType(RecTy
, MD
->getMethodQualifiers().getAddressSpace());
97 return Context
.getPointerType(CanQualType::CreateUnsafe(RecTy
));
100 /// Returns the canonical formal type of the given C++ method.
101 static CanQual
<FunctionProtoType
> GetFormalType(const CXXMethodDecl
*MD
) {
102 return MD
->getType()->getCanonicalTypeUnqualified()
103 .getAs
<FunctionProtoType
>();
106 /// Returns the "extra-canonicalized" return type, which discards
107 /// qualifiers on the return type. Codegen doesn't care about them,
108 /// and it makes ABI code a little easier to be able to assume that
109 /// all parameter and return types are top-level unqualified.
110 static CanQualType
GetReturnType(QualType RetTy
) {
111 return RetTy
->getCanonicalTypeUnqualified().getUnqualifiedType();
114 /// Arrange the argument and result information for a value of the given
115 /// unprototyped freestanding function type.
116 const CGFunctionInfo
&
117 CodeGenTypes::arrangeFreeFunctionType(CanQual
<FunctionNoProtoType
> FTNP
) {
118 // When translating an unprototyped function type, always use a
120 return arrangeLLVMFunctionInfo(FTNP
->getReturnType().getUnqualifiedType(),
121 FnInfoOpts::None
, std::nullopt
,
122 FTNP
->getExtInfo(), {}, RequiredArgs(0));
125 static void addExtParameterInfosForCall(
126 llvm::SmallVectorImpl
<FunctionProtoType::ExtParameterInfo
> ¶mInfos
,
127 const FunctionProtoType
*proto
,
129 unsigned totalArgs
) {
130 assert(proto
->hasExtParameterInfos());
131 assert(paramInfos
.size() <= prefixArgs
);
132 assert(proto
->getNumParams() + prefixArgs
<= totalArgs
);
134 paramInfos
.reserve(totalArgs
);
136 // Add default infos for any prefix args that don't already have infos.
137 paramInfos
.resize(prefixArgs
);
139 // Add infos for the prototype.
140 for (const auto &ParamInfo
: proto
->getExtParameterInfos()) {
141 paramInfos
.push_back(ParamInfo
);
142 // pass_object_size params have no parameter info.
143 if (ParamInfo
.hasPassObjectSize())
144 paramInfos
.emplace_back();
147 assert(paramInfos
.size() <= totalArgs
&&
148 "Did we forget to insert pass_object_size args?");
149 // Add default infos for the variadic and/or suffix arguments.
150 paramInfos
.resize(totalArgs
);
153 /// Adds the formal parameters in FPT to the given prefix. If any parameter in
154 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
155 static void appendParameterTypes(const CodeGenTypes
&CGT
,
156 SmallVectorImpl
<CanQualType
> &prefix
,
157 SmallVectorImpl
<FunctionProtoType::ExtParameterInfo
> ¶mInfos
,
158 CanQual
<FunctionProtoType
> FPT
) {
159 // Fast path: don't touch param info if we don't need to.
160 if (!FPT
->hasExtParameterInfos()) {
161 assert(paramInfos
.empty() &&
162 "We have paramInfos, but the prototype doesn't?");
163 prefix
.append(FPT
->param_type_begin(), FPT
->param_type_end());
167 unsigned PrefixSize
= prefix
.size();
168 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
169 // parameters; the only thing that can change this is the presence of
170 // pass_object_size. So, we preallocate for the common case.
171 prefix
.reserve(prefix
.size() + FPT
->getNumParams());
173 auto ExtInfos
= FPT
->getExtParameterInfos();
174 assert(ExtInfos
.size() == FPT
->getNumParams());
175 for (unsigned I
= 0, E
= FPT
->getNumParams(); I
!= E
; ++I
) {
176 prefix
.push_back(FPT
->getParamType(I
));
177 if (ExtInfos
[I
].hasPassObjectSize())
178 prefix
.push_back(CGT
.getContext().getSizeType());
181 addExtParameterInfosForCall(paramInfos
, FPT
.getTypePtr(), PrefixSize
,
185 /// Arrange the LLVM function layout for a value of the given function
186 /// type, on top of any implicit parameters already stored.
187 static const CGFunctionInfo
&
188 arrangeLLVMFunctionInfo(CodeGenTypes
&CGT
, bool instanceMethod
,
189 SmallVectorImpl
<CanQualType
> &prefix
,
190 CanQual
<FunctionProtoType
> FTP
) {
191 SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> paramInfos
;
192 RequiredArgs Required
= RequiredArgs::forPrototypePlus(FTP
, prefix
.size());
194 appendParameterTypes(CGT
, prefix
, paramInfos
, FTP
);
195 CanQualType resultType
= FTP
->getReturnType().getUnqualifiedType();
198 instanceMethod
? FnInfoOpts::IsInstanceMethod
: FnInfoOpts::None
;
199 return CGT
.arrangeLLVMFunctionInfo(resultType
, opts
, prefix
,
200 FTP
->getExtInfo(), paramInfos
, Required
);
203 /// Arrange the argument and result information for a value of the
204 /// given freestanding function type.
205 const CGFunctionInfo
&
206 CodeGenTypes::arrangeFreeFunctionType(CanQual
<FunctionProtoType
> FTP
) {
207 SmallVector
<CanQualType
, 16> argTypes
;
208 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes
,
212 static CallingConv
getCallingConventionForDecl(const ObjCMethodDecl
*D
,
214 // Set the appropriate calling convention for the Function.
215 if (D
->hasAttr
<StdCallAttr
>())
216 return CC_X86StdCall
;
218 if (D
->hasAttr
<FastCallAttr
>())
219 return CC_X86FastCall
;
221 if (D
->hasAttr
<RegCallAttr
>())
222 return CC_X86RegCall
;
224 if (D
->hasAttr
<ThisCallAttr
>())
225 return CC_X86ThisCall
;
227 if (D
->hasAttr
<VectorCallAttr
>())
228 return CC_X86VectorCall
;
230 if (D
->hasAttr
<PascalAttr
>())
233 if (PcsAttr
*PCS
= D
->getAttr
<PcsAttr
>())
234 return (PCS
->getPCS() == PcsAttr::AAPCS
? CC_AAPCS
: CC_AAPCS_VFP
);
236 if (D
->hasAttr
<AArch64VectorPcsAttr
>())
237 return CC_AArch64VectorCall
;
239 if (D
->hasAttr
<AArch64SVEPcsAttr
>())
240 return CC_AArch64SVEPCS
;
242 if (D
->hasAttr
<AMDGPUKernelCallAttr
>())
243 return CC_AMDGPUKernelCall
;
245 if (D
->hasAttr
<IntelOclBiccAttr
>())
246 return CC_IntelOclBicc
;
248 if (D
->hasAttr
<MSABIAttr
>())
249 return IsWindows
? CC_C
: CC_Win64
;
251 if (D
->hasAttr
<SysVABIAttr
>())
252 return IsWindows
? CC_X86_64SysV
: CC_C
;
254 if (D
->hasAttr
<PreserveMostAttr
>())
255 return CC_PreserveMost
;
257 if (D
->hasAttr
<PreserveAllAttr
>())
258 return CC_PreserveAll
;
260 if (D
->hasAttr
<M68kRTDAttr
>())
263 if (D
->hasAttr
<PreserveNoneAttr
>())
264 return CC_PreserveNone
;
266 if (D
->hasAttr
<RISCVVectorCCAttr
>())
267 return CC_RISCVVectorCall
;
272 /// Arrange the argument and result information for a call to an
273 /// unknown C++ non-static member function of the given abstract type.
274 /// (A null RD means we don't have any meaningful "this" argument type,
275 /// so fall back to a generic pointer type).
276 /// The member function must be an ordinary function, i.e. not a
277 /// constructor or destructor.
278 const CGFunctionInfo
&
279 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl
*RD
,
280 const FunctionProtoType
*FTP
,
281 const CXXMethodDecl
*MD
) {
282 SmallVector
<CanQualType
, 16> argTypes
;
284 // Add the 'this' pointer.
285 argTypes
.push_back(DeriveThisType(RD
, MD
));
287 return ::arrangeLLVMFunctionInfo(
288 *this, /*instanceMethod=*/true, argTypes
,
289 FTP
->getCanonicalTypeUnqualified().getAs
<FunctionProtoType
>());
292 /// Set calling convention for CUDA/HIP kernel.
293 static void setCUDAKernelCallingConvention(CanQualType
&FTy
, CodeGenModule
&CGM
,
294 const FunctionDecl
*FD
) {
295 if (FD
->hasAttr
<CUDAGlobalAttr
>()) {
296 const FunctionType
*FT
= FTy
->getAs
<FunctionType
>();
297 CGM
.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT
);
298 FTy
= FT
->getCanonicalTypeUnqualified();
302 /// Arrange the argument and result information for a declaration or
303 /// definition of the given C++ non-static member function. The
304 /// member function must be an ordinary function, i.e. not a
305 /// constructor or destructor.
306 const CGFunctionInfo
&
307 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl
*MD
) {
308 assert(!isa
<CXXConstructorDecl
>(MD
) && "wrong method for constructors!");
309 assert(!isa
<CXXDestructorDecl
>(MD
) && "wrong method for destructors!");
311 CanQualType FT
= GetFormalType(MD
).getAs
<Type
>();
312 setCUDAKernelCallingConvention(FT
, CGM
, MD
);
313 auto prototype
= FT
.getAs
<FunctionProtoType
>();
315 if (MD
->isImplicitObjectMemberFunction()) {
316 // The abstract case is perfectly fine.
317 const CXXRecordDecl
*ThisType
= TheCXXABI
.getThisArgumentTypeForMethod(MD
);
318 return arrangeCXXMethodType(ThisType
, prototype
.getTypePtr(), MD
);
321 return arrangeFreeFunctionType(prototype
);
324 bool CodeGenTypes::inheritingCtorHasParams(
325 const InheritedConstructor
&Inherited
, CXXCtorType Type
) {
326 // Parameters are unnecessary if we're constructing a base class subobject
327 // and the inherited constructor lives in a virtual base.
328 return Type
== Ctor_Complete
||
329 !Inherited
.getShadowDecl()->constructsVirtualBase() ||
330 !Target
.getCXXABI().hasConstructorVariants();
333 const CGFunctionInfo
&
334 CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD
) {
335 auto *MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
337 SmallVector
<CanQualType
, 16> argTypes
;
338 SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> paramInfos
;
340 const CXXRecordDecl
*ThisType
= TheCXXABI
.getThisArgumentTypeForMethod(GD
);
341 argTypes
.push_back(DeriveThisType(ThisType
, MD
));
343 bool PassParams
= true;
345 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
346 // A base class inheriting constructor doesn't get forwarded arguments
347 // needed to construct a virtual base (or base class thereof).
348 if (auto Inherited
= CD
->getInheritedConstructor())
349 PassParams
= inheritingCtorHasParams(Inherited
, GD
.getCtorType());
352 CanQual
<FunctionProtoType
> FTP
= GetFormalType(MD
);
354 // Add the formal parameters.
356 appendParameterTypes(*this, argTypes
, paramInfos
, FTP
);
358 CGCXXABI::AddedStructorArgCounts AddedArgs
=
359 TheCXXABI
.buildStructorSignature(GD
, argTypes
);
360 if (!paramInfos
.empty()) {
361 // Note: prefix implies after the first param.
362 if (AddedArgs
.Prefix
)
363 paramInfos
.insert(paramInfos
.begin() + 1, AddedArgs
.Prefix
,
364 FunctionProtoType::ExtParameterInfo
{});
365 if (AddedArgs
.Suffix
)
366 paramInfos
.append(AddedArgs
.Suffix
,
367 FunctionProtoType::ExtParameterInfo
{});
370 RequiredArgs required
=
371 (PassParams
&& MD
->isVariadic() ? RequiredArgs(argTypes
.size())
372 : RequiredArgs::All
);
374 FunctionType::ExtInfo extInfo
= FTP
->getExtInfo();
375 CanQualType resultType
= TheCXXABI
.HasThisReturn(GD
)
377 : TheCXXABI
.hasMostDerivedReturn(GD
)
378 ? CGM
.getContext().VoidPtrTy
380 return arrangeLLVMFunctionInfo(resultType
, FnInfoOpts::IsInstanceMethod
,
381 argTypes
, extInfo
, paramInfos
, required
);
384 static SmallVector
<CanQualType
, 16>
385 getArgTypesForCall(ASTContext
&ctx
, const CallArgList
&args
) {
386 SmallVector
<CanQualType
, 16> argTypes
;
387 for (auto &arg
: args
)
388 argTypes
.push_back(ctx
.getCanonicalParamType(arg
.Ty
));
392 static SmallVector
<CanQualType
, 16>
393 getArgTypesForDeclaration(ASTContext
&ctx
, const FunctionArgList
&args
) {
394 SmallVector
<CanQualType
, 16> argTypes
;
395 for (auto &arg
: args
)
396 argTypes
.push_back(ctx
.getCanonicalParamType(arg
->getType()));
400 static llvm::SmallVector
<FunctionProtoType::ExtParameterInfo
, 16>
401 getExtParameterInfosForCall(const FunctionProtoType
*proto
,
402 unsigned prefixArgs
, unsigned totalArgs
) {
403 llvm::SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> result
;
404 if (proto
->hasExtParameterInfos()) {
405 addExtParameterInfosForCall(result
, proto
, prefixArgs
, totalArgs
);
410 /// Arrange a call to a C++ method, passing the given arguments.
412 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
414 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
416 /// PassProtoArgs indicates whether `args` has args for the parameters in the
417 /// given CXXConstructorDecl.
418 const CGFunctionInfo
&
419 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList
&args
,
420 const CXXConstructorDecl
*D
,
421 CXXCtorType CtorKind
,
422 unsigned ExtraPrefixArgs
,
423 unsigned ExtraSuffixArgs
,
424 bool PassProtoArgs
) {
426 SmallVector
<CanQualType
, 16> ArgTypes
;
427 for (const auto &Arg
: args
)
428 ArgTypes
.push_back(Context
.getCanonicalParamType(Arg
.Ty
));
430 // +1 for implicit this, which should always be args[0].
431 unsigned TotalPrefixArgs
= 1 + ExtraPrefixArgs
;
433 CanQual
<FunctionProtoType
> FPT
= GetFormalType(D
);
434 RequiredArgs Required
= PassProtoArgs
435 ? RequiredArgs::forPrototypePlus(
436 FPT
, TotalPrefixArgs
+ ExtraSuffixArgs
)
439 GlobalDecl
GD(D
, CtorKind
);
440 CanQualType ResultType
= TheCXXABI
.HasThisReturn(GD
)
442 : TheCXXABI
.hasMostDerivedReturn(GD
)
443 ? CGM
.getContext().VoidPtrTy
446 FunctionType::ExtInfo Info
= FPT
->getExtInfo();
447 llvm::SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> ParamInfos
;
448 // If the prototype args are elided, we should only have ABI-specific args,
449 // which never have param info.
450 if (PassProtoArgs
&& FPT
->hasExtParameterInfos()) {
451 // ABI-specific suffix arguments are treated the same as variadic arguments.
452 addExtParameterInfosForCall(ParamInfos
, FPT
.getTypePtr(), TotalPrefixArgs
,
456 return arrangeLLVMFunctionInfo(ResultType
, FnInfoOpts::IsInstanceMethod
,
457 ArgTypes
, Info
, ParamInfos
, Required
);
460 /// Arrange the argument and result information for the declaration or
461 /// definition of the given function.
462 const CGFunctionInfo
&
463 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl
*FD
) {
464 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
))
465 if (MD
->isImplicitObjectMemberFunction())
466 return arrangeCXXMethodDeclaration(MD
);
468 CanQualType FTy
= FD
->getType()->getCanonicalTypeUnqualified();
470 assert(isa
<FunctionType
>(FTy
));
471 setCUDAKernelCallingConvention(FTy
, CGM
, FD
);
473 // When declaring a function without a prototype, always use a
474 // non-variadic type.
475 if (CanQual
<FunctionNoProtoType
> noProto
= FTy
.getAs
<FunctionNoProtoType
>()) {
476 return arrangeLLVMFunctionInfo(noProto
->getReturnType(), FnInfoOpts::None
,
477 std::nullopt
, noProto
->getExtInfo(), {},
481 return arrangeFreeFunctionType(FTy
.castAs
<FunctionProtoType
>());
484 /// Arrange the argument and result information for the declaration or
485 /// definition of an Objective-C method.
486 const CGFunctionInfo
&
487 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl
*MD
) {
488 // It happens that this is the same as a call with no optional
489 // arguments, except also using the formal 'self' type.
490 return arrangeObjCMessageSendSignature(MD
, MD
->getSelfDecl()->getType());
493 /// Arrange the argument and result information for the function type
494 /// through which to perform a send to the given Objective-C method,
495 /// using the given receiver type. The receiver type is not always
496 /// the 'self' type of the method or even an Objective-C pointer type.
497 /// This is *not* the right method for actually performing such a
498 /// message send, due to the possibility of optional arguments.
499 const CGFunctionInfo
&
500 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl
*MD
,
501 QualType receiverType
) {
502 SmallVector
<CanQualType
, 16> argTys
;
503 SmallVector
<FunctionProtoType::ExtParameterInfo
, 4> extParamInfos(
504 MD
->isDirectMethod() ? 1 : 2);
505 argTys
.push_back(Context
.getCanonicalParamType(receiverType
));
506 if (!MD
->isDirectMethod())
507 argTys
.push_back(Context
.getCanonicalParamType(Context
.getObjCSelType()));
509 for (const auto *I
: MD
->parameters()) {
510 argTys
.push_back(Context
.getCanonicalParamType(I
->getType()));
511 auto extParamInfo
= FunctionProtoType::ExtParameterInfo().withIsNoEscape(
512 I
->hasAttr
<NoEscapeAttr
>());
513 extParamInfos
.push_back(extParamInfo
);
516 FunctionType::ExtInfo einfo
;
517 bool IsWindows
= getContext().getTargetInfo().getTriple().isOSWindows();
518 einfo
= einfo
.withCallingConv(getCallingConventionForDecl(MD
, IsWindows
));
520 if (getContext().getLangOpts().ObjCAutoRefCount
&&
521 MD
->hasAttr
<NSReturnsRetainedAttr
>())
522 einfo
= einfo
.withProducesResult(true);
524 RequiredArgs required
=
525 (MD
->isVariadic() ? RequiredArgs(argTys
.size()) : RequiredArgs::All
);
527 return arrangeLLVMFunctionInfo(GetReturnType(MD
->getReturnType()),
528 FnInfoOpts::None
, argTys
, einfo
, extParamInfos
,
532 const CGFunctionInfo
&
533 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType
,
534 const CallArgList
&args
) {
535 auto argTypes
= getArgTypesForCall(Context
, args
);
536 FunctionType::ExtInfo einfo
;
538 return arrangeLLVMFunctionInfo(GetReturnType(returnType
), FnInfoOpts::None
,
539 argTypes
, einfo
, {}, RequiredArgs::All
);
542 const CGFunctionInfo
&
543 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD
) {
544 // FIXME: Do we need to handle ObjCMethodDecl?
545 const FunctionDecl
*FD
= cast
<FunctionDecl
>(GD
.getDecl());
547 if (isa
<CXXConstructorDecl
>(GD
.getDecl()) ||
548 isa
<CXXDestructorDecl
>(GD
.getDecl()))
549 return arrangeCXXStructorDeclaration(GD
);
551 return arrangeFunctionDeclaration(FD
);
554 /// Arrange a thunk that takes 'this' as the first parameter followed by
555 /// varargs. Return a void pointer, regardless of the actual return type.
556 /// The body of the thunk will end in a musttail call to a function of the
557 /// correct type, and the caller will bitcast the function to the correct
559 const CGFunctionInfo
&
560 CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl
*MD
) {
561 assert(MD
->isVirtual() && "only methods have thunks");
562 CanQual
<FunctionProtoType
> FTP
= GetFormalType(MD
);
563 CanQualType ArgTys
[] = {DeriveThisType(MD
->getParent(), MD
)};
564 return arrangeLLVMFunctionInfo(Context
.VoidTy
, FnInfoOpts::None
, ArgTys
,
565 FTP
->getExtInfo(), {}, RequiredArgs(1));
568 const CGFunctionInfo
&
569 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl
*CD
,
571 assert(CT
== Ctor_CopyingClosure
|| CT
== Ctor_DefaultClosure
);
573 CanQual
<FunctionProtoType
> FTP
= GetFormalType(CD
);
574 SmallVector
<CanQualType
, 2> ArgTys
;
575 const CXXRecordDecl
*RD
= CD
->getParent();
576 ArgTys
.push_back(DeriveThisType(RD
, CD
));
577 if (CT
== Ctor_CopyingClosure
)
578 ArgTys
.push_back(*FTP
->param_type_begin());
579 if (RD
->getNumVBases() > 0)
580 ArgTys
.push_back(Context
.IntTy
);
581 CallingConv CC
= Context
.getDefaultCallingConvention(
582 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
583 return arrangeLLVMFunctionInfo(Context
.VoidTy
, FnInfoOpts::IsInstanceMethod
,
584 ArgTys
, FunctionType::ExtInfo(CC
), {},
588 /// Arrange a call as unto a free function, except possibly with an
589 /// additional number of formal parameters considered required.
590 static const CGFunctionInfo
&
591 arrangeFreeFunctionLikeCall(CodeGenTypes
&CGT
,
593 const CallArgList
&args
,
594 const FunctionType
*fnType
,
595 unsigned numExtraRequiredArgs
,
597 assert(args
.size() >= numExtraRequiredArgs
);
599 llvm::SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> paramInfos
;
601 // In most cases, there are no optional arguments.
602 RequiredArgs required
= RequiredArgs::All
;
604 // If we have a variadic prototype, the required arguments are the
605 // extra prefix plus the arguments in the prototype.
606 if (const FunctionProtoType
*proto
= dyn_cast
<FunctionProtoType
>(fnType
)) {
607 if (proto
->isVariadic())
608 required
= RequiredArgs::forPrototypePlus(proto
, numExtraRequiredArgs
);
610 if (proto
->hasExtParameterInfos())
611 addExtParameterInfosForCall(paramInfos
, proto
, numExtraRequiredArgs
,
614 // If we don't have a prototype at all, but we're supposed to
615 // explicitly use the variadic convention for unprototyped calls,
616 // treat all of the arguments as required but preserve the nominal
617 // possibility of variadics.
618 } else if (CGM
.getTargetCodeGenInfo()
619 .isNoProtoCallVariadic(args
,
620 cast
<FunctionNoProtoType
>(fnType
))) {
621 required
= RequiredArgs(args
.size());
625 SmallVector
<CanQualType
, 16> argTypes
;
626 for (const auto &arg
: args
)
627 argTypes
.push_back(CGT
.getContext().getCanonicalParamType(arg
.Ty
));
628 FnInfoOpts opts
= chainCall
? FnInfoOpts::IsChainCall
: FnInfoOpts::None
;
629 return CGT
.arrangeLLVMFunctionInfo(GetReturnType(fnType
->getReturnType()),
630 opts
, argTypes
, fnType
->getExtInfo(),
631 paramInfos
, required
);
634 /// Figure out the rules for calling a function with the given formal
635 /// type using the given arguments. The arguments are necessary
636 /// because the function might be unprototyped, in which case it's
637 /// target-dependent in crazy ways.
638 const CGFunctionInfo
&
639 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList
&args
,
640 const FunctionType
*fnType
,
642 return arrangeFreeFunctionLikeCall(*this, CGM
, args
, fnType
,
643 chainCall
? 1 : 0, chainCall
);
646 /// A block function is essentially a free function with an
647 /// extra implicit argument.
648 const CGFunctionInfo
&
649 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList
&args
,
650 const FunctionType
*fnType
) {
651 return arrangeFreeFunctionLikeCall(*this, CGM
, args
, fnType
, 1,
652 /*chainCall=*/false);
655 const CGFunctionInfo
&
656 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType
*proto
,
657 const FunctionArgList
¶ms
) {
658 auto paramInfos
= getExtParameterInfosForCall(proto
, 1, params
.size());
659 auto argTypes
= getArgTypesForDeclaration(Context
, params
);
661 return arrangeLLVMFunctionInfo(GetReturnType(proto
->getReturnType()),
662 FnInfoOpts::None
, argTypes
,
663 proto
->getExtInfo(), paramInfos
,
664 RequiredArgs::forPrototypePlus(proto
, 1));
667 const CGFunctionInfo
&
668 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType
,
669 const CallArgList
&args
) {
671 SmallVector
<CanQualType
, 16> argTypes
;
672 for (const auto &Arg
: args
)
673 argTypes
.push_back(Context
.getCanonicalParamType(Arg
.Ty
));
674 return arrangeLLVMFunctionInfo(GetReturnType(resultType
), FnInfoOpts::None
,
675 argTypes
, FunctionType::ExtInfo(),
676 /*paramInfos=*/{}, RequiredArgs::All
);
679 const CGFunctionInfo
&
680 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType
,
681 const FunctionArgList
&args
) {
682 auto argTypes
= getArgTypesForDeclaration(Context
, args
);
684 return arrangeLLVMFunctionInfo(GetReturnType(resultType
), FnInfoOpts::None
,
685 argTypes
, FunctionType::ExtInfo(), {},
689 const CGFunctionInfo
&
690 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType
,
691 ArrayRef
<CanQualType
> argTypes
) {
692 return arrangeLLVMFunctionInfo(resultType
, FnInfoOpts::None
, argTypes
,
693 FunctionType::ExtInfo(), {},
697 /// Arrange a call to a C++ method, passing the given arguments.
699 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
700 /// does not count `this`.
701 const CGFunctionInfo
&
702 CodeGenTypes::arrangeCXXMethodCall(const CallArgList
&args
,
703 const FunctionProtoType
*proto
,
704 RequiredArgs required
,
705 unsigned numPrefixArgs
) {
706 assert(numPrefixArgs
+ 1 <= args
.size() &&
707 "Emitting a call with less args than the required prefix?");
708 // Add one to account for `this`. It's a bit awkward here, but we don't count
709 // `this` in similar places elsewhere.
711 getExtParameterInfosForCall(proto
, numPrefixArgs
+ 1, args
.size());
714 auto argTypes
= getArgTypesForCall(Context
, args
);
716 FunctionType::ExtInfo info
= proto
->getExtInfo();
717 return arrangeLLVMFunctionInfo(GetReturnType(proto
->getReturnType()),
718 FnInfoOpts::IsInstanceMethod
, argTypes
, info
,
719 paramInfos
, required
);
722 const CGFunctionInfo
&CodeGenTypes::arrangeNullaryFunction() {
723 return arrangeLLVMFunctionInfo(getContext().VoidTy
, FnInfoOpts::None
,
724 std::nullopt
, FunctionType::ExtInfo(), {},
728 const CGFunctionInfo
&
729 CodeGenTypes::arrangeCall(const CGFunctionInfo
&signature
,
730 const CallArgList
&args
) {
731 assert(signature
.arg_size() <= args
.size());
732 if (signature
.arg_size() == args
.size())
735 SmallVector
<FunctionProtoType::ExtParameterInfo
, 16> paramInfos
;
736 auto sigParamInfos
= signature
.getExtParameterInfos();
737 if (!sigParamInfos
.empty()) {
738 paramInfos
.append(sigParamInfos
.begin(), sigParamInfos
.end());
739 paramInfos
.resize(args
.size());
742 auto argTypes
= getArgTypesForCall(Context
, args
);
744 assert(signature
.getRequiredArgs().allowsOptionalArgs());
745 FnInfoOpts opts
= FnInfoOpts::None
;
746 if (signature
.isInstanceMethod())
747 opts
|= FnInfoOpts::IsInstanceMethod
;
748 if (signature
.isChainCall())
749 opts
|= FnInfoOpts::IsChainCall
;
750 if (signature
.isDelegateCall())
751 opts
|= FnInfoOpts::IsDelegateCall
;
752 return arrangeLLVMFunctionInfo(signature
.getReturnType(), opts
, argTypes
,
753 signature
.getExtInfo(), paramInfos
,
754 signature
.getRequiredArgs());
759 void computeSPIRKernelABIInfo(CodeGenModule
&CGM
, CGFunctionInfo
&FI
);
763 /// Arrange the argument and result information for an abstract value
764 /// of a given function type. This is the method which all of the
765 /// above functions ultimately defer to.
766 const CGFunctionInfo
&CodeGenTypes::arrangeLLVMFunctionInfo(
767 CanQualType resultType
, FnInfoOpts opts
, ArrayRef
<CanQualType
> argTypes
,
768 FunctionType::ExtInfo info
,
769 ArrayRef
<FunctionProtoType::ExtParameterInfo
> paramInfos
,
770 RequiredArgs required
) {
771 assert(llvm::all_of(argTypes
,
772 [](CanQualType T
) { return T
.isCanonicalAsParam(); }));
774 // Lookup or create unique function info.
775 llvm::FoldingSetNodeID ID
;
776 bool isInstanceMethod
=
777 (opts
& FnInfoOpts::IsInstanceMethod
) == FnInfoOpts::IsInstanceMethod
;
779 (opts
& FnInfoOpts::IsChainCall
) == FnInfoOpts::IsChainCall
;
780 bool isDelegateCall
=
781 (opts
& FnInfoOpts::IsDelegateCall
) == FnInfoOpts::IsDelegateCall
;
782 CGFunctionInfo::Profile(ID
, isInstanceMethod
, isChainCall
, isDelegateCall
,
783 info
, paramInfos
, required
, resultType
, argTypes
);
785 void *insertPos
= nullptr;
786 CGFunctionInfo
*FI
= FunctionInfos
.FindNodeOrInsertPos(ID
, insertPos
);
790 unsigned CC
= ClangCallConvToLLVMCallConv(info
.getCC());
792 // Construct the function info. We co-allocate the ArgInfos.
793 FI
= CGFunctionInfo::create(CC
, isInstanceMethod
, isChainCall
, isDelegateCall
,
794 info
, paramInfos
, resultType
, argTypes
, required
);
795 FunctionInfos
.InsertNode(FI
, insertPos
);
797 bool inserted
= FunctionsBeingProcessed
.insert(FI
).second
;
799 assert(inserted
&& "Recursively being processed?");
801 // Compute ABI information.
802 if (CC
== llvm::CallingConv::SPIR_KERNEL
) {
803 // Force target independent argument handling for the host visible
805 computeSPIRKernelABIInfo(CGM
, *FI
);
806 } else if (info
.getCC() == CC_Swift
|| info
.getCC() == CC_SwiftAsync
) {
807 swiftcall::computeABIInfo(CGM
, *FI
);
809 getABIInfo().computeInfo(*FI
);
812 // Loop over all of the computed argument and return value info. If any of
813 // them are direct or extend without a specified coerce type, specify the
815 ABIArgInfo
&retInfo
= FI
->getReturnInfo();
816 if (retInfo
.canHaveCoerceToType() && retInfo
.getCoerceToType() == nullptr)
817 retInfo
.setCoerceToType(ConvertType(FI
->getReturnType()));
819 for (auto &I
: FI
->arguments())
820 if (I
.info
.canHaveCoerceToType() && I
.info
.getCoerceToType() == nullptr)
821 I
.info
.setCoerceToType(ConvertType(I
.type
));
823 bool erased
= FunctionsBeingProcessed
.erase(FI
); (void)erased
;
824 assert(erased
&& "Not in set?");
829 CGFunctionInfo
*CGFunctionInfo::create(unsigned llvmCC
, bool instanceMethod
,
830 bool chainCall
, bool delegateCall
,
831 const FunctionType::ExtInfo
&info
,
832 ArrayRef
<ExtParameterInfo
> paramInfos
,
833 CanQualType resultType
,
834 ArrayRef
<CanQualType
> argTypes
,
835 RequiredArgs required
) {
836 assert(paramInfos
.empty() || paramInfos
.size() == argTypes
.size());
837 assert(!required
.allowsOptionalArgs() ||
838 required
.getNumRequiredArgs() <= argTypes
.size());
841 operator new(totalSizeToAlloc
<ArgInfo
, ExtParameterInfo
>(
842 argTypes
.size() + 1, paramInfos
.size()));
844 CGFunctionInfo
*FI
= new(buffer
) CGFunctionInfo();
845 FI
->CallingConvention
= llvmCC
;
846 FI
->EffectiveCallingConvention
= llvmCC
;
847 FI
->ASTCallingConvention
= info
.getCC();
848 FI
->InstanceMethod
= instanceMethod
;
849 FI
->ChainCall
= chainCall
;
850 FI
->DelegateCall
= delegateCall
;
851 FI
->CmseNSCall
= info
.getCmseNSCall();
852 FI
->NoReturn
= info
.getNoReturn();
853 FI
->ReturnsRetained
= info
.getProducesResult();
854 FI
->NoCallerSavedRegs
= info
.getNoCallerSavedRegs();
855 FI
->NoCfCheck
= info
.getNoCfCheck();
856 FI
->Required
= required
;
857 FI
->HasRegParm
= info
.getHasRegParm();
858 FI
->RegParm
= info
.getRegParm();
859 FI
->ArgStruct
= nullptr;
860 FI
->ArgStructAlign
= 0;
861 FI
->NumArgs
= argTypes
.size();
862 FI
->HasExtParameterInfos
= !paramInfos
.empty();
863 FI
->getArgsBuffer()[0].type
= resultType
;
864 FI
->MaxVectorWidth
= 0;
865 for (unsigned i
= 0, e
= argTypes
.size(); i
!= e
; ++i
)
866 FI
->getArgsBuffer()[i
+ 1].type
= argTypes
[i
];
867 for (unsigned i
= 0, e
= paramInfos
.size(); i
!= e
; ++i
)
868 FI
->getExtParameterInfosBuffer()[i
] = paramInfos
[i
];
875 // ABIArgInfo::Expand implementation.
877 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
878 struct TypeExpansion
{
879 enum TypeExpansionKind
{
880 // Elements of constant arrays are expanded recursively.
882 // Record fields are expanded recursively (but if record is a union, only
883 // the field with the largest size is expanded).
885 // For complex types, real and imaginary parts are expanded recursively.
887 // All other types are not expandable.
891 const TypeExpansionKind Kind
;
893 TypeExpansion(TypeExpansionKind K
) : Kind(K
) {}
894 virtual ~TypeExpansion() {}
897 struct ConstantArrayExpansion
: TypeExpansion
{
901 ConstantArrayExpansion(QualType EltTy
, uint64_t NumElts
)
902 : TypeExpansion(TEK_ConstantArray
), EltTy(EltTy
), NumElts(NumElts
) {}
903 static bool classof(const TypeExpansion
*TE
) {
904 return TE
->Kind
== TEK_ConstantArray
;
908 struct RecordExpansion
: TypeExpansion
{
909 SmallVector
<const CXXBaseSpecifier
*, 1> Bases
;
911 SmallVector
<const FieldDecl
*, 1> Fields
;
913 RecordExpansion(SmallVector
<const CXXBaseSpecifier
*, 1> &&Bases
,
914 SmallVector
<const FieldDecl
*, 1> &&Fields
)
915 : TypeExpansion(TEK_Record
), Bases(std::move(Bases
)),
916 Fields(std::move(Fields
)) {}
917 static bool classof(const TypeExpansion
*TE
) {
918 return TE
->Kind
== TEK_Record
;
922 struct ComplexExpansion
: TypeExpansion
{
925 ComplexExpansion(QualType EltTy
) : TypeExpansion(TEK_Complex
), EltTy(EltTy
) {}
926 static bool classof(const TypeExpansion
*TE
) {
927 return TE
->Kind
== TEK_Complex
;
931 struct NoExpansion
: TypeExpansion
{
932 NoExpansion() : TypeExpansion(TEK_None
) {}
933 static bool classof(const TypeExpansion
*TE
) {
934 return TE
->Kind
== TEK_None
;
939 static std::unique_ptr
<TypeExpansion
>
940 getTypeExpansion(QualType Ty
, const ASTContext
&Context
) {
941 if (const ConstantArrayType
*AT
= Context
.getAsConstantArrayType(Ty
)) {
942 return std::make_unique
<ConstantArrayExpansion
>(AT
->getElementType(),
945 if (const RecordType
*RT
= Ty
->getAs
<RecordType
>()) {
946 SmallVector
<const CXXBaseSpecifier
*, 1> Bases
;
947 SmallVector
<const FieldDecl
*, 1> Fields
;
948 const RecordDecl
*RD
= RT
->getDecl();
949 assert(!RD
->hasFlexibleArrayMember() &&
950 "Cannot expand structure with flexible array.");
952 // Unions can be here only in degenerative cases - all the fields are same
953 // after flattening. Thus we have to use the "largest" field.
954 const FieldDecl
*LargestFD
= nullptr;
955 CharUnits UnionSize
= CharUnits::Zero();
957 for (const auto *FD
: RD
->fields()) {
958 if (FD
->isZeroLengthBitField(Context
))
960 assert(!FD
->isBitField() &&
961 "Cannot expand structure with bit-field members.");
962 CharUnits FieldSize
= Context
.getTypeSizeInChars(FD
->getType());
963 if (UnionSize
< FieldSize
) {
964 UnionSize
= FieldSize
;
969 Fields
.push_back(LargestFD
);
971 if (const auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
972 assert(!CXXRD
->isDynamicClass() &&
973 "cannot expand vtable pointers in dynamic classes");
974 llvm::append_range(Bases
, llvm::make_pointer_range(CXXRD
->bases()));
977 for (const auto *FD
: RD
->fields()) {
978 if (FD
->isZeroLengthBitField(Context
))
980 assert(!FD
->isBitField() &&
981 "Cannot expand structure with bit-field members.");
982 Fields
.push_back(FD
);
985 return std::make_unique
<RecordExpansion
>(std::move(Bases
),
988 if (const ComplexType
*CT
= Ty
->getAs
<ComplexType
>()) {
989 return std::make_unique
<ComplexExpansion
>(CT
->getElementType());
991 return std::make_unique
<NoExpansion
>();
994 static int getExpansionSize(QualType Ty
, const ASTContext
&Context
) {
995 auto Exp
= getTypeExpansion(Ty
, Context
);
996 if (auto CAExp
= dyn_cast
<ConstantArrayExpansion
>(Exp
.get())) {
997 return CAExp
->NumElts
* getExpansionSize(CAExp
->EltTy
, Context
);
999 if (auto RExp
= dyn_cast
<RecordExpansion
>(Exp
.get())) {
1001 for (auto BS
: RExp
->Bases
)
1002 Res
+= getExpansionSize(BS
->getType(), Context
);
1003 for (auto FD
: RExp
->Fields
)
1004 Res
+= getExpansionSize(FD
->getType(), Context
);
1007 if (isa
<ComplexExpansion
>(Exp
.get()))
1009 assert(isa
<NoExpansion
>(Exp
.get()));
1014 CodeGenTypes::getExpandedTypes(QualType Ty
,
1015 SmallVectorImpl
<llvm::Type
*>::iterator
&TI
) {
1016 auto Exp
= getTypeExpansion(Ty
, Context
);
1017 if (auto CAExp
= dyn_cast
<ConstantArrayExpansion
>(Exp
.get())) {
1018 for (int i
= 0, n
= CAExp
->NumElts
; i
< n
; i
++) {
1019 getExpandedTypes(CAExp
->EltTy
, TI
);
1021 } else if (auto RExp
= dyn_cast
<RecordExpansion
>(Exp
.get())) {
1022 for (auto BS
: RExp
->Bases
)
1023 getExpandedTypes(BS
->getType(), TI
);
1024 for (auto FD
: RExp
->Fields
)
1025 getExpandedTypes(FD
->getType(), TI
);
1026 } else if (auto CExp
= dyn_cast
<ComplexExpansion
>(Exp
.get())) {
1027 llvm::Type
*EltTy
= ConvertType(CExp
->EltTy
);
1031 assert(isa
<NoExpansion
>(Exp
.get()));
1032 *TI
++ = ConvertType(Ty
);
1036 static void forConstantArrayExpansion(CodeGenFunction
&CGF
,
1037 ConstantArrayExpansion
*CAE
,
1039 llvm::function_ref
<void(Address
)> Fn
) {
1040 for (int i
= 0, n
= CAE
->NumElts
; i
< n
; i
++) {
1041 Address EltAddr
= CGF
.Builder
.CreateConstGEP2_32(BaseAddr
, 0, i
);
1046 void CodeGenFunction::ExpandTypeFromArgs(QualType Ty
, LValue LV
,
1047 llvm::Function::arg_iterator
&AI
) {
1048 assert(LV
.isSimple() &&
1049 "Unexpected non-simple lvalue during struct expansion.");
1051 auto Exp
= getTypeExpansion(Ty
, getContext());
1052 if (auto CAExp
= dyn_cast
<ConstantArrayExpansion
>(Exp
.get())) {
1053 forConstantArrayExpansion(
1054 *this, CAExp
, LV
.getAddress(), [&](Address EltAddr
) {
1055 LValue LV
= MakeAddrLValue(EltAddr
, CAExp
->EltTy
);
1056 ExpandTypeFromArgs(CAExp
->EltTy
, LV
, AI
);
1058 } else if (auto RExp
= dyn_cast
<RecordExpansion
>(Exp
.get())) {
1059 Address This
= LV
.getAddress();
1060 for (const CXXBaseSpecifier
*BS
: RExp
->Bases
) {
1061 // Perform a single step derived-to-base conversion.
1063 GetAddressOfBaseClass(This
, Ty
->getAsCXXRecordDecl(), &BS
, &BS
+ 1,
1064 /*NullCheckValue=*/false, SourceLocation());
1065 LValue SubLV
= MakeAddrLValue(Base
, BS
->getType());
1067 // Recurse onto bases.
1068 ExpandTypeFromArgs(BS
->getType(), SubLV
, AI
);
1070 for (auto FD
: RExp
->Fields
) {
1071 // FIXME: What are the right qualifiers here?
1072 LValue SubLV
= EmitLValueForFieldInitialization(LV
, FD
);
1073 ExpandTypeFromArgs(FD
->getType(), SubLV
, AI
);
1075 } else if (isa
<ComplexExpansion
>(Exp
.get())) {
1076 auto realValue
= &*AI
++;
1077 auto imagValue
= &*AI
++;
1078 EmitStoreOfComplex(ComplexPairTy(realValue
, imagValue
), LV
, /*init*/ true);
1080 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1082 assert(isa
<NoExpansion
>(Exp
.get()));
1083 llvm::Value
*Arg
= &*AI
++;
1084 if (LV
.isBitField()) {
1085 EmitStoreThroughLValue(RValue::get(Arg
), LV
);
1087 // TODO: currently there are some places are inconsistent in what LLVM
1088 // pointer type they use (see D118744). Once clang uses opaque pointers
1089 // all LLVM pointer types will be the same and we can remove this check.
1090 if (Arg
->getType()->isPointerTy()) {
1091 Address Addr
= LV
.getAddress();
1092 Arg
= Builder
.CreateBitCast(Arg
, Addr
.getElementType());
1094 EmitStoreOfScalar(Arg
, LV
);
1099 void CodeGenFunction::ExpandTypeToArgs(
1100 QualType Ty
, CallArg Arg
, llvm::FunctionType
*IRFuncTy
,
1101 SmallVectorImpl
<llvm::Value
*> &IRCallArgs
, unsigned &IRCallArgPos
) {
1102 auto Exp
= getTypeExpansion(Ty
, getContext());
1103 if (auto CAExp
= dyn_cast
<ConstantArrayExpansion
>(Exp
.get())) {
1104 Address Addr
= Arg
.hasLValue() ? Arg
.getKnownLValue().getAddress()
1105 : Arg
.getKnownRValue().getAggregateAddress();
1106 forConstantArrayExpansion(
1107 *this, CAExp
, Addr
, [&](Address EltAddr
) {
1108 CallArg EltArg
= CallArg(
1109 convertTempToRValue(EltAddr
, CAExp
->EltTy
, SourceLocation()),
1111 ExpandTypeToArgs(CAExp
->EltTy
, EltArg
, IRFuncTy
, IRCallArgs
,
1114 } else if (auto RExp
= dyn_cast
<RecordExpansion
>(Exp
.get())) {
1115 Address This
= Arg
.hasLValue() ? Arg
.getKnownLValue().getAddress()
1116 : Arg
.getKnownRValue().getAggregateAddress();
1117 for (const CXXBaseSpecifier
*BS
: RExp
->Bases
) {
1118 // Perform a single step derived-to-base conversion.
1120 GetAddressOfBaseClass(This
, Ty
->getAsCXXRecordDecl(), &BS
, &BS
+ 1,
1121 /*NullCheckValue=*/false, SourceLocation());
1122 CallArg BaseArg
= CallArg(RValue::getAggregate(Base
), BS
->getType());
1124 // Recurse onto bases.
1125 ExpandTypeToArgs(BS
->getType(), BaseArg
, IRFuncTy
, IRCallArgs
,
1129 LValue LV
= MakeAddrLValue(This
, Ty
);
1130 for (auto FD
: RExp
->Fields
) {
1132 CallArg(EmitRValueForField(LV
, FD
, SourceLocation()), FD
->getType());
1133 ExpandTypeToArgs(FD
->getType(), FldArg
, IRFuncTy
, IRCallArgs
,
1136 } else if (isa
<ComplexExpansion
>(Exp
.get())) {
1137 ComplexPairTy CV
= Arg
.getKnownRValue().getComplexVal();
1138 IRCallArgs
[IRCallArgPos
++] = CV
.first
;
1139 IRCallArgs
[IRCallArgPos
++] = CV
.second
;
1141 assert(isa
<NoExpansion
>(Exp
.get()));
1142 auto RV
= Arg
.getKnownRValue();
1143 assert(RV
.isScalar() &&
1144 "Unexpected non-scalar rvalue during struct expansion.");
1146 // Insert a bitcast as needed.
1147 llvm::Value
*V
= RV
.getScalarVal();
1148 if (IRCallArgPos
< IRFuncTy
->getNumParams() &&
1149 V
->getType() != IRFuncTy
->getParamType(IRCallArgPos
))
1150 V
= Builder
.CreateBitCast(V
, IRFuncTy
->getParamType(IRCallArgPos
));
1152 IRCallArgs
[IRCallArgPos
++] = V
;
1156 /// Create a temporary allocation for the purposes of coercion.
1157 static RawAddress
CreateTempAllocaForCoercion(CodeGenFunction
&CGF
,
1160 const Twine
&Name
= "tmp") {
1161 // Don't use an alignment that's worse than what LLVM would prefer.
1162 auto PrefAlign
= CGF
.CGM
.getDataLayout().getPrefTypeAlign(Ty
);
1163 CharUnits Align
= std::max(MinAlign
, CharUnits::fromQuantity(PrefAlign
));
1165 return CGF
.CreateTempAlloca(Ty
, Align
, Name
+ ".coerce");
1168 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1169 /// accessing some number of bytes out of it, try to gep into the struct to get
1170 /// at its inner goodness. Dive as deep as possible without entering an element
1171 /// with an in-memory size smaller than DstSize.
1173 EnterStructPointerForCoercedAccess(Address SrcPtr
,
1174 llvm::StructType
*SrcSTy
,
1175 uint64_t DstSize
, CodeGenFunction
&CGF
) {
1176 // We can't dive into a zero-element struct.
1177 if (SrcSTy
->getNumElements() == 0) return SrcPtr
;
1179 llvm::Type
*FirstElt
= SrcSTy
->getElementType(0);
1181 // If the first elt is at least as large as what we're looking for, or if the
1182 // first element is the same size as the whole struct, we can enter it. The
1183 // comparison must be made on the store size and not the alloca size. Using
1184 // the alloca size may overstate the size of the load.
1185 uint64_t FirstEltSize
=
1186 CGF
.CGM
.getDataLayout().getTypeStoreSize(FirstElt
);
1187 if (FirstEltSize
< DstSize
&&
1188 FirstEltSize
< CGF
.CGM
.getDataLayout().getTypeStoreSize(SrcSTy
))
1191 // GEP into the first element.
1192 SrcPtr
= CGF
.Builder
.CreateStructGEP(SrcPtr
, 0, "coerce.dive");
1194 // If the first element is a struct, recurse.
1195 llvm::Type
*SrcTy
= SrcPtr
.getElementType();
1196 if (llvm::StructType
*SrcSTy
= dyn_cast
<llvm::StructType
>(SrcTy
))
1197 return EnterStructPointerForCoercedAccess(SrcPtr
, SrcSTy
, DstSize
, CGF
);
1202 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1203 /// are either integers or pointers. This does a truncation of the value if it
1204 /// is too large or a zero extension if it is too small.
1206 /// This behaves as if the value were coerced through memory, so on big-endian
1207 /// targets the high bits are preserved in a truncation, while little-endian
1208 /// targets preserve the low bits.
1209 static llvm::Value
*CoerceIntOrPtrToIntOrPtr(llvm::Value
*Val
,
1211 CodeGenFunction
&CGF
) {
1212 if (Val
->getType() == Ty
)
1215 if (isa
<llvm::PointerType
>(Val
->getType())) {
1216 // If this is Pointer->Pointer avoid conversion to and from int.
1217 if (isa
<llvm::PointerType
>(Ty
))
1218 return CGF
.Builder
.CreateBitCast(Val
, Ty
, "coerce.val");
1220 // Convert the pointer to an integer so we can play with its width.
1221 Val
= CGF
.Builder
.CreatePtrToInt(Val
, CGF
.IntPtrTy
, "coerce.val.pi");
1224 llvm::Type
*DestIntTy
= Ty
;
1225 if (isa
<llvm::PointerType
>(DestIntTy
))
1226 DestIntTy
= CGF
.IntPtrTy
;
1228 if (Val
->getType() != DestIntTy
) {
1229 const llvm::DataLayout
&DL
= CGF
.CGM
.getDataLayout();
1230 if (DL
.isBigEndian()) {
1231 // Preserve the high bits on big-endian targets.
1232 // That is what memory coercion does.
1233 uint64_t SrcSize
= DL
.getTypeSizeInBits(Val
->getType());
1234 uint64_t DstSize
= DL
.getTypeSizeInBits(DestIntTy
);
1236 if (SrcSize
> DstSize
) {
1237 Val
= CGF
.Builder
.CreateLShr(Val
, SrcSize
- DstSize
, "coerce.highbits");
1238 Val
= CGF
.Builder
.CreateTrunc(Val
, DestIntTy
, "coerce.val.ii");
1240 Val
= CGF
.Builder
.CreateZExt(Val
, DestIntTy
, "coerce.val.ii");
1241 Val
= CGF
.Builder
.CreateShl(Val
, DstSize
- SrcSize
, "coerce.highbits");
1244 // Little-endian targets preserve the low bits. No shifts required.
1245 Val
= CGF
.Builder
.CreateIntCast(Val
, DestIntTy
, false, "coerce.val.ii");
1249 if (isa
<llvm::PointerType
>(Ty
))
1250 Val
= CGF
.Builder
.CreateIntToPtr(Val
, Ty
, "coerce.val.ip");
1256 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1257 /// a pointer to an object of type \arg Ty, known to be aligned to
1258 /// \arg SrcAlign bytes.
1260 /// This safely handles the case when the src type is smaller than the
1261 /// destination type; in this situation the values of bits which not
1262 /// present in the src are undefined.
1263 static llvm::Value
*CreateCoercedLoad(Address Src
, llvm::Type
*Ty
,
1264 CodeGenFunction
&CGF
) {
1265 llvm::Type
*SrcTy
= Src
.getElementType();
1267 // If SrcTy and Ty are the same, just do a load.
1269 return CGF
.Builder
.CreateLoad(Src
);
1271 llvm::TypeSize DstSize
= CGF
.CGM
.getDataLayout().getTypeAllocSize(Ty
);
1273 if (llvm::StructType
*SrcSTy
= dyn_cast
<llvm::StructType
>(SrcTy
)) {
1274 Src
= EnterStructPointerForCoercedAccess(Src
, SrcSTy
,
1275 DstSize
.getFixedValue(), CGF
);
1276 SrcTy
= Src
.getElementType();
1279 llvm::TypeSize SrcSize
= CGF
.CGM
.getDataLayout().getTypeAllocSize(SrcTy
);
1281 // If the source and destination are integer or pointer types, just do an
1282 // extension or truncation to the desired type.
1283 if ((isa
<llvm::IntegerType
>(Ty
) || isa
<llvm::PointerType
>(Ty
)) &&
1284 (isa
<llvm::IntegerType
>(SrcTy
) || isa
<llvm::PointerType
>(SrcTy
))) {
1285 llvm::Value
*Load
= CGF
.Builder
.CreateLoad(Src
);
1286 return CoerceIntOrPtrToIntOrPtr(Load
, Ty
, CGF
);
1289 // If load is legal, just bitcast the src pointer.
1290 if (!SrcSize
.isScalable() && !DstSize
.isScalable() &&
1291 SrcSize
.getFixedValue() >= DstSize
.getFixedValue()) {
1292 // Generally SrcSize is never greater than DstSize, since this means we are
1293 // losing bits. However, this can happen in cases where the structure has
1294 // additional padding, for example due to a user specified alignment.
1296 // FIXME: Assert that we aren't truncating non-padding bits when have access
1297 // to that information.
1298 Src
= Src
.withElementType(Ty
);
1299 return CGF
.Builder
.CreateLoad(Src
);
1302 // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1303 // the types match, use the llvm.vector.insert intrinsic to perform the
1305 if (auto *ScalableDstTy
= dyn_cast
<llvm::ScalableVectorType
>(Ty
)) {
1306 if (auto *FixedSrcTy
= dyn_cast
<llvm::FixedVectorType
>(SrcTy
)) {
1307 // If we are casting a fixed i8 vector to a scalable i1 predicate
1308 // vector, use a vector insert and bitcast the result.
1309 if (ScalableDstTy
->getElementType()->isIntegerTy(1) &&
1310 ScalableDstTy
->getElementCount().isKnownMultipleOf(8) &&
1311 FixedSrcTy
->getElementType()->isIntegerTy(8)) {
1312 ScalableDstTy
= llvm::ScalableVectorType::get(
1313 FixedSrcTy
->getElementType(),
1314 ScalableDstTy
->getElementCount().getKnownMinValue() / 8);
1316 if (ScalableDstTy
->getElementType() == FixedSrcTy
->getElementType()) {
1317 auto *Load
= CGF
.Builder
.CreateLoad(Src
);
1318 auto *UndefVec
= llvm::UndefValue::get(ScalableDstTy
);
1319 auto *Zero
= llvm::Constant::getNullValue(CGF
.CGM
.Int64Ty
);
1320 llvm::Value
*Result
= CGF
.Builder
.CreateInsertVector(
1321 ScalableDstTy
, UndefVec
, Load
, Zero
, "cast.scalable");
1322 if (ScalableDstTy
!= Ty
)
1323 Result
= CGF
.Builder
.CreateBitCast(Result
, Ty
);
1329 // Otherwise do coercion through memory. This is stupid, but simple.
1331 CreateTempAllocaForCoercion(CGF
, Ty
, Src
.getAlignment(), Src
.getName());
1332 CGF
.Builder
.CreateMemCpy(
1333 Tmp
.getPointer(), Tmp
.getAlignment().getAsAlign(),
1334 Src
.emitRawPointer(CGF
), Src
.getAlignment().getAsAlign(),
1335 llvm::ConstantInt::get(CGF
.IntPtrTy
, SrcSize
.getKnownMinValue()));
1336 return CGF
.Builder
.CreateLoad(Tmp
);
1339 void CodeGenFunction::CreateCoercedStore(llvm::Value
*Src
, Address Dst
,
1340 llvm::TypeSize DstSize
,
1341 bool DstIsVolatile
) {
1345 llvm::Type
*SrcTy
= Src
->getType();
1346 llvm::TypeSize SrcSize
= CGM
.getDataLayout().getTypeAllocSize(SrcTy
);
1348 // GEP into structs to try to make types match.
1349 // FIXME: This isn't really that useful with opaque types, but it impacts a
1350 // lot of regression tests.
1351 if (SrcTy
!= Dst
.getElementType()) {
1352 if (llvm::StructType
*DstSTy
=
1353 dyn_cast
<llvm::StructType
>(Dst
.getElementType())) {
1354 assert(!SrcSize
.isScalable());
1355 Dst
= EnterStructPointerForCoercedAccess(Dst
, DstSTy
,
1356 SrcSize
.getFixedValue(), *this);
1360 if (SrcSize
.isScalable() || SrcSize
<= DstSize
) {
1361 if (SrcTy
->isIntegerTy() && Dst
.getElementType()->isPointerTy() &&
1362 SrcSize
== CGM
.getDataLayout().getTypeAllocSize(Dst
.getElementType())) {
1363 // If the value is supposed to be a pointer, convert it before storing it.
1364 Src
= CoerceIntOrPtrToIntOrPtr(Src
, Dst
.getElementType(), *this);
1365 Builder
.CreateStore(Src
, Dst
, DstIsVolatile
);
1366 } else if (llvm::StructType
*STy
=
1367 dyn_cast
<llvm::StructType
>(Src
->getType())) {
1368 // Prefer scalar stores to first-class aggregate stores.
1369 Dst
= Dst
.withElementType(SrcTy
);
1370 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
) {
1371 Address EltPtr
= Builder
.CreateStructGEP(Dst
, i
);
1372 llvm::Value
*Elt
= Builder
.CreateExtractValue(Src
, i
);
1373 Builder
.CreateStore(Elt
, EltPtr
, DstIsVolatile
);
1376 Builder
.CreateStore(Src
, Dst
.withElementType(SrcTy
), DstIsVolatile
);
1378 } else if (SrcTy
->isIntegerTy()) {
1379 // If the source is a simple integer, coerce it directly.
1380 llvm::Type
*DstIntTy
= Builder
.getIntNTy(DstSize
.getFixedValue() * 8);
1381 Src
= CoerceIntOrPtrToIntOrPtr(Src
, DstIntTy
, *this);
1382 Builder
.CreateStore(Src
, Dst
.withElementType(DstIntTy
), DstIsVolatile
);
1384 // Otherwise do coercion through memory. This is stupid, but
1387 // Generally SrcSize is never greater than DstSize, since this means we are
1388 // losing bits. However, this can happen in cases where the structure has
1389 // additional padding, for example due to a user specified alignment.
1391 // FIXME: Assert that we aren't truncating non-padding bits when have access
1392 // to that information.
1394 CreateTempAllocaForCoercion(*this, SrcTy
, Dst
.getAlignment());
1395 Builder
.CreateStore(Src
, Tmp
);
1396 Builder
.CreateMemCpy(Dst
.emitRawPointer(*this),
1397 Dst
.getAlignment().getAsAlign(), Tmp
.getPointer(),
1398 Tmp
.getAlignment().getAsAlign(),
1399 Builder
.CreateTypeSize(IntPtrTy
, DstSize
));
1403 static Address
emitAddressAtOffset(CodeGenFunction
&CGF
, Address addr
,
1404 const ABIArgInfo
&info
) {
1405 if (unsigned offset
= info
.getDirectOffset()) {
1406 addr
= addr
.withElementType(CGF
.Int8Ty
);
1407 addr
= CGF
.Builder
.CreateConstInBoundsByteGEP(addr
,
1408 CharUnits::fromQuantity(offset
));
1409 addr
= addr
.withElementType(info
.getCoerceToType());
1416 /// Encapsulates information about the way function arguments from
1417 /// CGFunctionInfo should be passed to actual LLVM IR function.
1418 class ClangToLLVMArgMapping
{
1419 static const unsigned InvalidIndex
= ~0U;
1420 unsigned InallocaArgNo
;
1422 unsigned TotalIRArgs
;
1424 /// Arguments of LLVM IR function corresponding to single Clang argument.
1426 unsigned PaddingArgIndex
;
1427 // Argument is expanded to IR arguments at positions
1428 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1429 unsigned FirstArgIndex
;
1430 unsigned NumberOfArgs
;
1433 : PaddingArgIndex(InvalidIndex
), FirstArgIndex(InvalidIndex
),
1437 SmallVector
<IRArgs
, 8> ArgInfo
;
1440 ClangToLLVMArgMapping(const ASTContext
&Context
, const CGFunctionInfo
&FI
,
1441 bool OnlyRequiredArgs
= false)
1442 : InallocaArgNo(InvalidIndex
), SRetArgNo(InvalidIndex
), TotalIRArgs(0),
1443 ArgInfo(OnlyRequiredArgs
? FI
.getNumRequiredArgs() : FI
.arg_size()) {
1444 construct(Context
, FI
, OnlyRequiredArgs
);
1447 bool hasInallocaArg() const { return InallocaArgNo
!= InvalidIndex
; }
1448 unsigned getInallocaArgNo() const {
1449 assert(hasInallocaArg());
1450 return InallocaArgNo
;
1453 bool hasSRetArg() const { return SRetArgNo
!= InvalidIndex
; }
1454 unsigned getSRetArgNo() const {
1455 assert(hasSRetArg());
1459 unsigned totalIRArgs() const { return TotalIRArgs
; }
1461 bool hasPaddingArg(unsigned ArgNo
) const {
1462 assert(ArgNo
< ArgInfo
.size());
1463 return ArgInfo
[ArgNo
].PaddingArgIndex
!= InvalidIndex
;
1465 unsigned getPaddingArgNo(unsigned ArgNo
) const {
1466 assert(hasPaddingArg(ArgNo
));
1467 return ArgInfo
[ArgNo
].PaddingArgIndex
;
1470 /// Returns index of first IR argument corresponding to ArgNo, and their
1472 std::pair
<unsigned, unsigned> getIRArgs(unsigned ArgNo
) const {
1473 assert(ArgNo
< ArgInfo
.size());
1474 return std::make_pair(ArgInfo
[ArgNo
].FirstArgIndex
,
1475 ArgInfo
[ArgNo
].NumberOfArgs
);
1479 void construct(const ASTContext
&Context
, const CGFunctionInfo
&FI
,
1480 bool OnlyRequiredArgs
);
1483 void ClangToLLVMArgMapping::construct(const ASTContext
&Context
,
1484 const CGFunctionInfo
&FI
,
1485 bool OnlyRequiredArgs
) {
1486 unsigned IRArgNo
= 0;
1487 bool SwapThisWithSRet
= false;
1488 const ABIArgInfo
&RetAI
= FI
.getReturnInfo();
1490 if (RetAI
.getKind() == ABIArgInfo::Indirect
) {
1491 SwapThisWithSRet
= RetAI
.isSRetAfterThis();
1492 SRetArgNo
= SwapThisWithSRet
? 1 : IRArgNo
++;
1496 unsigned NumArgs
= OnlyRequiredArgs
? FI
.getNumRequiredArgs() : FI
.arg_size();
1497 for (CGFunctionInfo::const_arg_iterator I
= FI
.arg_begin(); ArgNo
< NumArgs
;
1499 assert(I
!= FI
.arg_end());
1500 QualType ArgType
= I
->type
;
1501 const ABIArgInfo
&AI
= I
->info
;
1502 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1503 auto &IRArgs
= ArgInfo
[ArgNo
];
1505 if (AI
.getPaddingType())
1506 IRArgs
.PaddingArgIndex
= IRArgNo
++;
1508 switch (AI
.getKind()) {
1509 case ABIArgInfo::Extend
:
1510 case ABIArgInfo::Direct
: {
1511 // FIXME: handle sseregparm someday...
1512 llvm::StructType
*STy
= dyn_cast
<llvm::StructType
>(AI
.getCoerceToType());
1513 if (AI
.isDirect() && AI
.getCanBeFlattened() && STy
) {
1514 IRArgs
.NumberOfArgs
= STy
->getNumElements();
1516 IRArgs
.NumberOfArgs
= 1;
1520 case ABIArgInfo::Indirect
:
1521 case ABIArgInfo::IndirectAliased
:
1522 IRArgs
.NumberOfArgs
= 1;
1524 case ABIArgInfo::Ignore
:
1525 case ABIArgInfo::InAlloca
:
1526 // ignore and inalloca doesn't have matching LLVM parameters.
1527 IRArgs
.NumberOfArgs
= 0;
1529 case ABIArgInfo::CoerceAndExpand
:
1530 IRArgs
.NumberOfArgs
= AI
.getCoerceAndExpandTypeSequence().size();
1532 case ABIArgInfo::Expand
:
1533 IRArgs
.NumberOfArgs
= getExpansionSize(ArgType
, Context
);
1537 if (IRArgs
.NumberOfArgs
> 0) {
1538 IRArgs
.FirstArgIndex
= IRArgNo
;
1539 IRArgNo
+= IRArgs
.NumberOfArgs
;
1542 // Skip over the sret parameter when it comes second. We already handled it
1544 if (IRArgNo
== 1 && SwapThisWithSRet
)
1547 assert(ArgNo
== ArgInfo
.size());
1549 if (FI
.usesInAlloca())
1550 InallocaArgNo
= IRArgNo
++;
1552 TotalIRArgs
= IRArgNo
;
1558 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo
&FI
) {
1559 const auto &RI
= FI
.getReturnInfo();
1560 return RI
.isIndirect() || (RI
.isInAlloca() && RI
.getInAllocaSRet());
1563 bool CodeGenModule::ReturnTypeHasInReg(const CGFunctionInfo
&FI
) {
1564 const auto &RI
= FI
.getReturnInfo();
1565 return RI
.getInReg();
1568 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo
&FI
) {
1569 return ReturnTypeUsesSRet(FI
) &&
1570 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1573 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType
) {
1574 if (const BuiltinType
*BT
= ResultType
->getAs
<BuiltinType
>()) {
1575 switch (BT
->getKind()) {
1578 case BuiltinType::Float
:
1579 return getTarget().useObjCFPRetForRealType(FloatModeKind::Float
);
1580 case BuiltinType::Double
:
1581 return getTarget().useObjCFPRetForRealType(FloatModeKind::Double
);
1582 case BuiltinType::LongDouble
:
1583 return getTarget().useObjCFPRetForRealType(FloatModeKind::LongDouble
);
1590 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType
) {
1591 if (const ComplexType
*CT
= ResultType
->getAs
<ComplexType
>()) {
1592 if (const BuiltinType
*BT
= CT
->getElementType()->getAs
<BuiltinType
>()) {
1593 if (BT
->getKind() == BuiltinType::LongDouble
)
1594 return getTarget().useObjCFP2RetForComplexLongDouble();
1601 llvm::FunctionType
*CodeGenTypes::GetFunctionType(GlobalDecl GD
) {
1602 const CGFunctionInfo
&FI
= arrangeGlobalDeclaration(GD
);
1603 return GetFunctionType(FI
);
1606 llvm::FunctionType
*
1607 CodeGenTypes::GetFunctionType(const CGFunctionInfo
&FI
) {
1609 bool Inserted
= FunctionsBeingProcessed
.insert(&FI
).second
;
1611 assert(Inserted
&& "Recursively being processed?");
1613 llvm::Type
*resultType
= nullptr;
1614 const ABIArgInfo
&retAI
= FI
.getReturnInfo();
1615 switch (retAI
.getKind()) {
1616 case ABIArgInfo::Expand
:
1617 case ABIArgInfo::IndirectAliased
:
1618 llvm_unreachable("Invalid ABI kind for return argument");
1620 case ABIArgInfo::Extend
:
1621 case ABIArgInfo::Direct
:
1622 resultType
= retAI
.getCoerceToType();
1625 case ABIArgInfo::InAlloca
:
1626 if (retAI
.getInAllocaSRet()) {
1627 // sret things on win32 aren't void, they return the sret pointer.
1628 QualType ret
= FI
.getReturnType();
1629 unsigned addressSpace
= CGM
.getTypes().getTargetAddressSpace(ret
);
1630 resultType
= llvm::PointerType::get(getLLVMContext(), addressSpace
);
1632 resultType
= llvm::Type::getVoidTy(getLLVMContext());
1636 case ABIArgInfo::Indirect
:
1637 case ABIArgInfo::Ignore
:
1638 resultType
= llvm::Type::getVoidTy(getLLVMContext());
1641 case ABIArgInfo::CoerceAndExpand
:
1642 resultType
= retAI
.getUnpaddedCoerceAndExpandType();
1646 ClangToLLVMArgMapping
IRFunctionArgs(getContext(), FI
, true);
1647 SmallVector
<llvm::Type
*, 8> ArgTypes(IRFunctionArgs
.totalIRArgs());
1649 // Add type for sret argument.
1650 if (IRFunctionArgs
.hasSRetArg()) {
1651 QualType Ret
= FI
.getReturnType();
1652 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(Ret
);
1653 ArgTypes
[IRFunctionArgs
.getSRetArgNo()] =
1654 llvm::PointerType::get(getLLVMContext(), AddressSpace
);
1657 // Add type for inalloca argument.
1658 if (IRFunctionArgs
.hasInallocaArg())
1659 ArgTypes
[IRFunctionArgs
.getInallocaArgNo()] =
1660 llvm::PointerType::getUnqual(getLLVMContext());
1662 // Add in all of the required arguments.
1664 CGFunctionInfo::const_arg_iterator it
= FI
.arg_begin(),
1665 ie
= it
+ FI
.getNumRequiredArgs();
1666 for (; it
!= ie
; ++it
, ++ArgNo
) {
1667 const ABIArgInfo
&ArgInfo
= it
->info
;
1669 // Insert a padding type to ensure proper alignment.
1670 if (IRFunctionArgs
.hasPaddingArg(ArgNo
))
1671 ArgTypes
[IRFunctionArgs
.getPaddingArgNo(ArgNo
)] =
1672 ArgInfo
.getPaddingType();
1674 unsigned FirstIRArg
, NumIRArgs
;
1675 std::tie(FirstIRArg
, NumIRArgs
) = IRFunctionArgs
.getIRArgs(ArgNo
);
1677 switch (ArgInfo
.getKind()) {
1678 case ABIArgInfo::Ignore
:
1679 case ABIArgInfo::InAlloca
:
1680 assert(NumIRArgs
== 0);
1683 case ABIArgInfo::Indirect
:
1684 assert(NumIRArgs
== 1);
1685 // indirect arguments are always on the stack, which is alloca addr space.
1686 ArgTypes
[FirstIRArg
] = llvm::PointerType::get(
1687 getLLVMContext(), CGM
.getDataLayout().getAllocaAddrSpace());
1689 case ABIArgInfo::IndirectAliased
:
1690 assert(NumIRArgs
== 1);
1691 ArgTypes
[FirstIRArg
] = llvm::PointerType::get(
1692 getLLVMContext(), ArgInfo
.getIndirectAddrSpace());
1694 case ABIArgInfo::Extend
:
1695 case ABIArgInfo::Direct
: {
1696 // Fast-isel and the optimizer generally like scalar values better than
1697 // FCAs, so we flatten them if this is safe to do for this argument.
1698 llvm::Type
*argType
= ArgInfo
.getCoerceToType();
1699 llvm::StructType
*st
= dyn_cast
<llvm::StructType
>(argType
);
1700 if (st
&& ArgInfo
.isDirect() && ArgInfo
.getCanBeFlattened()) {
1701 assert(NumIRArgs
== st
->getNumElements());
1702 for (unsigned i
= 0, e
= st
->getNumElements(); i
!= e
; ++i
)
1703 ArgTypes
[FirstIRArg
+ i
] = st
->getElementType(i
);
1705 assert(NumIRArgs
== 1);
1706 ArgTypes
[FirstIRArg
] = argType
;
1711 case ABIArgInfo::CoerceAndExpand
: {
1712 auto ArgTypesIter
= ArgTypes
.begin() + FirstIRArg
;
1713 for (auto *EltTy
: ArgInfo
.getCoerceAndExpandTypeSequence()) {
1714 *ArgTypesIter
++ = EltTy
;
1716 assert(ArgTypesIter
== ArgTypes
.begin() + FirstIRArg
+ NumIRArgs
);
1720 case ABIArgInfo::Expand
:
1721 auto ArgTypesIter
= ArgTypes
.begin() + FirstIRArg
;
1722 getExpandedTypes(it
->type
, ArgTypesIter
);
1723 assert(ArgTypesIter
== ArgTypes
.begin() + FirstIRArg
+ NumIRArgs
);
1728 bool Erased
= FunctionsBeingProcessed
.erase(&FI
); (void)Erased
;
1729 assert(Erased
&& "Not in set?");
1731 return llvm::FunctionType::get(resultType
, ArgTypes
, FI
.isVariadic());
1734 llvm::Type
*CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD
) {
1735 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
1736 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
1738 if (!isFuncTypeConvertible(FPT
))
1739 return llvm::StructType::get(getLLVMContext());
1741 return GetFunctionType(GD
);
1744 static void AddAttributesFromFunctionProtoType(ASTContext
&Ctx
,
1745 llvm::AttrBuilder
&FuncAttrs
,
1746 const FunctionProtoType
*FPT
) {
1750 if (!isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()) &&
1752 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
1754 unsigned SMEBits
= FPT
->getAArch64SMEAttributes();
1755 if (SMEBits
& FunctionType::SME_PStateSMEnabledMask
)
1756 FuncAttrs
.addAttribute("aarch64_pstate_sm_enabled");
1757 if (SMEBits
& FunctionType::SME_PStateSMCompatibleMask
)
1758 FuncAttrs
.addAttribute("aarch64_pstate_sm_compatible");
1761 if (FunctionType::getArmZAState(SMEBits
) == FunctionType::ARM_Preserves
)
1762 FuncAttrs
.addAttribute("aarch64_preserves_za");
1763 if (FunctionType::getArmZAState(SMEBits
) == FunctionType::ARM_In
)
1764 FuncAttrs
.addAttribute("aarch64_in_za");
1765 if (FunctionType::getArmZAState(SMEBits
) == FunctionType::ARM_Out
)
1766 FuncAttrs
.addAttribute("aarch64_out_za");
1767 if (FunctionType::getArmZAState(SMEBits
) == FunctionType::ARM_InOut
)
1768 FuncAttrs
.addAttribute("aarch64_inout_za");
1771 if (FunctionType::getArmZT0State(SMEBits
) == FunctionType::ARM_Preserves
)
1772 FuncAttrs
.addAttribute("aarch64_preserves_zt0");
1773 if (FunctionType::getArmZT0State(SMEBits
) == FunctionType::ARM_In
)
1774 FuncAttrs
.addAttribute("aarch64_in_zt0");
1775 if (FunctionType::getArmZT0State(SMEBits
) == FunctionType::ARM_Out
)
1776 FuncAttrs
.addAttribute("aarch64_out_zt0");
1777 if (FunctionType::getArmZT0State(SMEBits
) == FunctionType::ARM_InOut
)
1778 FuncAttrs
.addAttribute("aarch64_inout_zt0");
1781 static void AddAttributesFromOMPAssumes(llvm::AttrBuilder
&FuncAttrs
,
1782 const Decl
*Callee
) {
1786 SmallVector
<StringRef
, 4> Attrs
;
1788 for (const OMPAssumeAttr
*AA
: Callee
->specific_attrs
<OMPAssumeAttr
>())
1789 AA
->getAssumption().split(Attrs
, ",");
1792 FuncAttrs
.addAttribute(llvm::AssumptionAttrKey
,
1793 llvm::join(Attrs
.begin(), Attrs
.end(), ","));
1796 bool CodeGenModule::MayDropFunctionReturn(const ASTContext
&Context
,
1797 QualType ReturnType
) const {
1798 // We can't just discard the return value for a record type with a
1799 // complex destructor or a non-trivially copyable type.
1800 if (const RecordType
*RT
=
1801 ReturnType
.getCanonicalType()->getAs
<RecordType
>()) {
1802 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl()))
1803 return ClassDecl
->hasTrivialDestructor();
1805 return ReturnType
.isTriviallyCopyableType(Context
);
1808 static bool HasStrictReturn(const CodeGenModule
&Module
, QualType RetTy
,
1809 const Decl
*TargetDecl
) {
1810 // As-is msan can not tolerate noundef mismatch between caller and
1811 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1812 // into C++. Such mismatches lead to confusing false reports. To avoid
1813 // expensive workaround on msan we enforce initialization event in uncommon
1814 // cases where it's allowed.
1815 if (Module
.getLangOpts().Sanitize
.has(SanitizerKind::Memory
))
1817 // C++ explicitly makes returning undefined values UB. C's rule only applies
1818 // to used values, so we never mark them noundef for now.
1819 if (!Module
.getLangOpts().CPlusPlus
)
1822 if (const FunctionDecl
*FDecl
= dyn_cast
<FunctionDecl
>(TargetDecl
)) {
1823 if (FDecl
->isExternC())
1825 } else if (const VarDecl
*VDecl
= dyn_cast
<VarDecl
>(TargetDecl
)) {
1826 // Function pointer.
1827 if (VDecl
->isExternC())
1832 // We don't want to be too aggressive with the return checking, unless
1833 // it's explicit in the code opts or we're using an appropriate sanitizer.
1834 // Try to respect what the programmer intended.
1835 return Module
.getCodeGenOpts().StrictReturn
||
1836 !Module
.MayDropFunctionReturn(Module
.getContext(), RetTy
) ||
1837 Module
.getLangOpts().Sanitize
.has(SanitizerKind::Return
);
1840 /// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1841 /// requested denormal behavior, accounting for the overriding behavior of the
1843 static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode
,
1844 llvm::DenormalMode FP32DenormalMode
,
1845 llvm::AttrBuilder
&FuncAttrs
) {
1846 if (FPDenormalMode
!= llvm::DenormalMode::getDefault())
1847 FuncAttrs
.addAttribute("denormal-fp-math", FPDenormalMode
.str());
1849 if (FP32DenormalMode
!= FPDenormalMode
&& FP32DenormalMode
.isValid())
1850 FuncAttrs
.addAttribute("denormal-fp-math-f32", FP32DenormalMode
.str());
1853 /// Add default attributes to a function, which have merge semantics under
1854 /// -mlink-builtin-bitcode and should not simply overwrite any existing
1855 /// attributes in the linked library.
1857 addMergableDefaultFunctionAttributes(const CodeGenOptions
&CodeGenOpts
,
1858 llvm::AttrBuilder
&FuncAttrs
) {
1859 addDenormalModeAttrs(CodeGenOpts
.FPDenormalMode
, CodeGenOpts
.FP32DenormalMode
,
1863 static void getTrivialDefaultFunctionAttributes(
1864 StringRef Name
, bool HasOptnone
, const CodeGenOptions
&CodeGenOpts
,
1865 const LangOptions
&LangOpts
, bool AttrOnCallSite
,
1866 llvm::AttrBuilder
&FuncAttrs
) {
1867 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1869 if (CodeGenOpts
.OptimizeSize
)
1870 FuncAttrs
.addAttribute(llvm::Attribute::OptimizeForSize
);
1871 if (CodeGenOpts
.OptimizeSize
== 2)
1872 FuncAttrs
.addAttribute(llvm::Attribute::MinSize
);
1875 if (CodeGenOpts
.DisableRedZone
)
1876 FuncAttrs
.addAttribute(llvm::Attribute::NoRedZone
);
1877 if (CodeGenOpts
.IndirectTlsSegRefs
)
1878 FuncAttrs
.addAttribute("indirect-tls-seg-refs");
1879 if (CodeGenOpts
.NoImplicitFloat
)
1880 FuncAttrs
.addAttribute(llvm::Attribute::NoImplicitFloat
);
1882 if (AttrOnCallSite
) {
1883 // Attributes that should go on the call site only.
1884 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1885 // the -fno-builtin-foo list.
1886 if (!CodeGenOpts
.SimplifyLibCalls
|| LangOpts
.isNoBuiltinFunc(Name
))
1887 FuncAttrs
.addAttribute(llvm::Attribute::NoBuiltin
);
1888 if (!CodeGenOpts
.TrapFuncName
.empty())
1889 FuncAttrs
.addAttribute("trap-func-name", CodeGenOpts
.TrapFuncName
);
1891 switch (CodeGenOpts
.getFramePointer()) {
1892 case CodeGenOptions::FramePointerKind::None
:
1893 // This is the default behavior.
1895 case CodeGenOptions::FramePointerKind::Reserved
:
1896 case CodeGenOptions::FramePointerKind::NonLeaf
:
1897 case CodeGenOptions::FramePointerKind::All
:
1898 FuncAttrs
.addAttribute("frame-pointer",
1899 CodeGenOptions::getFramePointerKindName(
1900 CodeGenOpts
.getFramePointer()));
1903 if (CodeGenOpts
.LessPreciseFPMAD
)
1904 FuncAttrs
.addAttribute("less-precise-fpmad", "true");
1906 if (CodeGenOpts
.NullPointerIsValid
)
1907 FuncAttrs
.addAttribute(llvm::Attribute::NullPointerIsValid
);
1909 if (LangOpts
.getDefaultExceptionMode() == LangOptions::FPE_Ignore
)
1910 FuncAttrs
.addAttribute("no-trapping-math", "true");
1912 // TODO: Are these all needed?
1913 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1914 if (LangOpts
.NoHonorInfs
)
1915 FuncAttrs
.addAttribute("no-infs-fp-math", "true");
1916 if (LangOpts
.NoHonorNaNs
)
1917 FuncAttrs
.addAttribute("no-nans-fp-math", "true");
1918 if (LangOpts
.ApproxFunc
)
1919 FuncAttrs
.addAttribute("approx-func-fp-math", "true");
1920 if (LangOpts
.AllowFPReassoc
&& LangOpts
.AllowRecip
&&
1921 LangOpts
.NoSignedZero
&& LangOpts
.ApproxFunc
&&
1922 (LangOpts
.getDefaultFPContractMode() ==
1923 LangOptions::FPModeKind::FPM_Fast
||
1924 LangOpts
.getDefaultFPContractMode() ==
1925 LangOptions::FPModeKind::FPM_FastHonorPragmas
))
1926 FuncAttrs
.addAttribute("unsafe-fp-math", "true");
1927 if (CodeGenOpts
.SoftFloat
)
1928 FuncAttrs
.addAttribute("use-soft-float", "true");
1929 FuncAttrs
.addAttribute("stack-protector-buffer-size",
1930 llvm::utostr(CodeGenOpts
.SSPBufferSize
));
1931 if (LangOpts
.NoSignedZero
)
1932 FuncAttrs
.addAttribute("no-signed-zeros-fp-math", "true");
1934 // TODO: Reciprocal estimate codegen options should apply to instructions?
1935 const std::vector
<std::string
> &Recips
= CodeGenOpts
.Reciprocals
;
1936 if (!Recips
.empty())
1937 FuncAttrs
.addAttribute("reciprocal-estimates",
1938 llvm::join(Recips
, ","));
1940 if (!CodeGenOpts
.PreferVectorWidth
.empty() &&
1941 CodeGenOpts
.PreferVectorWidth
!= "none")
1942 FuncAttrs
.addAttribute("prefer-vector-width",
1943 CodeGenOpts
.PreferVectorWidth
);
1945 if (CodeGenOpts
.StackRealignment
)
1946 FuncAttrs
.addAttribute("stackrealign");
1947 if (CodeGenOpts
.Backchain
)
1948 FuncAttrs
.addAttribute("backchain");
1949 if (CodeGenOpts
.EnableSegmentedStacks
)
1950 FuncAttrs
.addAttribute("split-stack");
1952 if (CodeGenOpts
.SpeculativeLoadHardening
)
1953 FuncAttrs
.addAttribute(llvm::Attribute::SpeculativeLoadHardening
);
1955 // Add zero-call-used-regs attribute.
1956 switch (CodeGenOpts
.getZeroCallUsedRegs()) {
1957 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip
:
1958 FuncAttrs
.removeAttribute("zero-call-used-regs");
1960 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg
:
1961 FuncAttrs
.addAttribute("zero-call-used-regs", "used-gpr-arg");
1963 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR
:
1964 FuncAttrs
.addAttribute("zero-call-used-regs", "used-gpr");
1966 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg
:
1967 FuncAttrs
.addAttribute("zero-call-used-regs", "used-arg");
1969 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used
:
1970 FuncAttrs
.addAttribute("zero-call-used-regs", "used");
1972 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg
:
1973 FuncAttrs
.addAttribute("zero-call-used-regs", "all-gpr-arg");
1975 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR
:
1976 FuncAttrs
.addAttribute("zero-call-used-regs", "all-gpr");
1978 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg
:
1979 FuncAttrs
.addAttribute("zero-call-used-regs", "all-arg");
1981 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All
:
1982 FuncAttrs
.addAttribute("zero-call-used-regs", "all");
1987 if (LangOpts
.assumeFunctionsAreConvergent()) {
1988 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1989 // convergent (meaning, they may call an intrinsically convergent op, such
1990 // as __syncthreads() / barrier(), and so can't have certain optimizations
1991 // applied around them). LLVM will remove this attribute where it safely
1993 FuncAttrs
.addAttribute(llvm::Attribute::Convergent
);
1996 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
1997 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
1998 if ((LangOpts
.CUDA
&& LangOpts
.CUDAIsDevice
) || LangOpts
.OpenCL
||
1999 LangOpts
.SYCLIsDevice
) {
2000 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
2003 for (StringRef Attr
: CodeGenOpts
.DefaultFunctionAttrs
) {
2004 StringRef Var
, Value
;
2005 std::tie(Var
, Value
) = Attr
.split('=');
2006 FuncAttrs
.addAttribute(Var
, Value
);
2009 TargetInfo::BranchProtectionInfo
BPI(LangOpts
);
2010 TargetCodeGenInfo::initBranchProtectionFnAttributes(BPI
, FuncAttrs
);
2013 /// Merges `target-features` from \TargetOpts and \F, and sets the result in
2015 /// * features from \F are always kept
2016 /// * a feature from \TargetOpts is kept if itself and its opposite are absent
2019 overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder
&FuncAttr
,
2020 const llvm::Function
&F
,
2021 const TargetOptions
&TargetOpts
) {
2022 auto FFeatures
= F
.getFnAttribute("target-features");
2024 llvm::StringSet
<> MergedNames
;
2025 SmallVector
<StringRef
> MergedFeatures
;
2026 MergedFeatures
.reserve(TargetOpts
.Features
.size());
2028 auto AddUnmergedFeatures
= [&](auto &&FeatureRange
) {
2029 for (StringRef Feature
: FeatureRange
) {
2030 if (Feature
.empty())
2032 assert(Feature
[0] == '+' || Feature
[0] == '-');
2033 StringRef Name
= Feature
.drop_front(1);
2034 bool Merged
= !MergedNames
.insert(Name
).second
;
2036 MergedFeatures
.push_back(Feature
);
2040 if (FFeatures
.isValid())
2041 AddUnmergedFeatures(llvm::split(FFeatures
.getValueAsString(), ','));
2042 AddUnmergedFeatures(TargetOpts
.Features
);
2044 if (!MergedFeatures
.empty()) {
2045 llvm::sort(MergedFeatures
);
2046 FuncAttr
.addAttribute("target-features", llvm::join(MergedFeatures
, ","));
2050 void CodeGen::mergeDefaultFunctionDefinitionAttributes(
2051 llvm::Function
&F
, const CodeGenOptions
&CodeGenOpts
,
2052 const LangOptions
&LangOpts
, const TargetOptions
&TargetOpts
,
2053 bool WillInternalize
) {
2055 llvm::AttrBuilder
FuncAttrs(F
.getContext());
2056 // Here we only extract the options that are relevant compared to the version
2057 // from GetCPUAndFeaturesAttributes.
2058 if (!TargetOpts
.CPU
.empty())
2059 FuncAttrs
.addAttribute("target-cpu", TargetOpts
.CPU
);
2060 if (!TargetOpts
.TuneCPU
.empty())
2061 FuncAttrs
.addAttribute("tune-cpu", TargetOpts
.TuneCPU
);
2063 ::getTrivialDefaultFunctionAttributes(F
.getName(), F
.hasOptNone(),
2064 CodeGenOpts
, LangOpts
,
2065 /*AttrOnCallSite=*/false, FuncAttrs
);
2067 if (!WillInternalize
&& F
.isInterposable()) {
2068 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2069 // setting for weak functions that won't be internalized. The user has no
2070 // real control for how builtin bitcode is linked, so we shouldn't assume
2071 // later copies will use a consistent mode.
2072 F
.addFnAttrs(FuncAttrs
);
2076 llvm::AttributeMask AttrsToRemove
;
2078 llvm::DenormalMode DenormModeToMerge
= F
.getDenormalModeRaw();
2079 llvm::DenormalMode DenormModeToMergeF32
= F
.getDenormalModeF32Raw();
2080 llvm::DenormalMode Merged
=
2081 CodeGenOpts
.FPDenormalMode
.mergeCalleeMode(DenormModeToMerge
);
2082 llvm::DenormalMode MergedF32
= CodeGenOpts
.FP32DenormalMode
;
2084 if (DenormModeToMergeF32
.isValid()) {
2086 CodeGenOpts
.FP32DenormalMode
.mergeCalleeMode(DenormModeToMergeF32
);
2089 if (Merged
== llvm::DenormalMode::getDefault()) {
2090 AttrsToRemove
.addAttribute("denormal-fp-math");
2091 } else if (Merged
!= DenormModeToMerge
) {
2092 // Overwrite existing attribute
2093 FuncAttrs
.addAttribute("denormal-fp-math",
2094 CodeGenOpts
.FPDenormalMode
.str());
2097 if (MergedF32
== llvm::DenormalMode::getDefault()) {
2098 AttrsToRemove
.addAttribute("denormal-fp-math-f32");
2099 } else if (MergedF32
!= DenormModeToMergeF32
) {
2100 // Overwrite existing attribute
2101 FuncAttrs
.addAttribute("denormal-fp-math-f32",
2102 CodeGenOpts
.FP32DenormalMode
.str());
2105 F
.removeFnAttrs(AttrsToRemove
);
2106 addDenormalModeAttrs(Merged
, MergedF32
, FuncAttrs
);
2108 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs
, F
, TargetOpts
);
2110 F
.addFnAttrs(FuncAttrs
);
2113 void CodeGenModule::getTrivialDefaultFunctionAttributes(
2114 StringRef Name
, bool HasOptnone
, bool AttrOnCallSite
,
2115 llvm::AttrBuilder
&FuncAttrs
) {
2116 ::getTrivialDefaultFunctionAttributes(Name
, HasOptnone
, getCodeGenOpts(),
2117 getLangOpts(), AttrOnCallSite
,
2121 void CodeGenModule::getDefaultFunctionAttributes(StringRef Name
,
2123 bool AttrOnCallSite
,
2124 llvm::AttrBuilder
&FuncAttrs
) {
2125 getTrivialDefaultFunctionAttributes(Name
, HasOptnone
, AttrOnCallSite
,
2127 // If we're just getting the default, get the default values for mergeable
2129 if (!AttrOnCallSite
)
2130 addMergableDefaultFunctionAttributes(CodeGenOpts
, FuncAttrs
);
2133 void CodeGenModule::addDefaultFunctionDefinitionAttributes(
2134 llvm::AttrBuilder
&attrs
) {
2135 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2136 /*for call*/ false, attrs
);
2137 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs
);
2140 static void addNoBuiltinAttributes(llvm::AttrBuilder
&FuncAttrs
,
2141 const LangOptions
&LangOpts
,
2142 const NoBuiltinAttr
*NBA
= nullptr) {
2143 auto AddNoBuiltinAttr
= [&FuncAttrs
](StringRef BuiltinName
) {
2144 SmallString
<32> AttributeName
;
2145 AttributeName
+= "no-builtin-";
2146 AttributeName
+= BuiltinName
;
2147 FuncAttrs
.addAttribute(AttributeName
);
2150 // First, handle the language options passed through -fno-builtin.
2151 if (LangOpts
.NoBuiltin
) {
2152 // -fno-builtin disables them all.
2153 FuncAttrs
.addAttribute("no-builtins");
2157 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2158 llvm::for_each(LangOpts
.NoBuiltinFuncs
, AddNoBuiltinAttr
);
2160 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2165 // If there is a wildcard in the builtin names specified through the
2166 // attribute, disable them all.
2167 if (llvm::is_contained(NBA
->builtinNames(), "*")) {
2168 FuncAttrs
.addAttribute("no-builtins");
2172 // And last, add the rest of the builtin names.
2173 llvm::for_each(NBA
->builtinNames(), AddNoBuiltinAttr
);
2176 static bool DetermineNoUndef(QualType QTy
, CodeGenTypes
&Types
,
2177 const llvm::DataLayout
&DL
, const ABIArgInfo
&AI
,
2178 bool CheckCoerce
= true) {
2179 llvm::Type
*Ty
= Types
.ConvertTypeForMem(QTy
);
2180 if (AI
.getKind() == ABIArgInfo::Indirect
||
2181 AI
.getKind() == ABIArgInfo::IndirectAliased
)
2183 if (AI
.getKind() == ABIArgInfo::Extend
)
2185 if (!DL
.typeSizeEqualsStoreSize(Ty
))
2186 // TODO: This will result in a modest amount of values not marked noundef
2187 // when they could be. We care about values that *invisibly* contain undef
2188 // bits from the perspective of LLVM IR.
2190 if (CheckCoerce
&& AI
.canHaveCoerceToType()) {
2191 llvm::Type
*CoerceTy
= AI
.getCoerceToType();
2192 if (llvm::TypeSize::isKnownGT(DL
.getTypeSizeInBits(CoerceTy
),
2193 DL
.getTypeSizeInBits(Ty
)))
2194 // If we're coercing to a type with a greater size than the canonical one,
2195 // we're introducing new undef bits.
2196 // Coercing to a type of smaller or equal size is ok, as we know that
2197 // there's no internal padding (typeSizeEqualsStoreSize).
2200 if (QTy
->isBitIntType())
2202 if (QTy
->isReferenceType())
2204 if (QTy
->isNullPtrType())
2206 if (QTy
->isMemberPointerType())
2207 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2208 // now, never mark them.
2210 if (QTy
->isScalarType()) {
2211 if (const ComplexType
*Complex
= dyn_cast
<ComplexType
>(QTy
))
2212 return DetermineNoUndef(Complex
->getElementType(), Types
, DL
, AI
, false);
2215 if (const VectorType
*Vector
= dyn_cast
<VectorType
>(QTy
))
2216 return DetermineNoUndef(Vector
->getElementType(), Types
, DL
, AI
, false);
2217 if (const MatrixType
*Matrix
= dyn_cast
<MatrixType
>(QTy
))
2218 return DetermineNoUndef(Matrix
->getElementType(), Types
, DL
, AI
, false);
2219 if (const ArrayType
*Array
= dyn_cast
<ArrayType
>(QTy
))
2220 return DetermineNoUndef(Array
->getElementType(), Types
, DL
, AI
, false);
2222 // TODO: Some structs may be `noundef`, in specific situations.
2226 /// Check if the argument of a function has maybe_undef attribute.
2227 static bool IsArgumentMaybeUndef(const Decl
*TargetDecl
,
2228 unsigned NumRequiredArgs
, unsigned ArgNo
) {
2229 const auto *FD
= dyn_cast_or_null
<FunctionDecl
>(TargetDecl
);
2233 // Assume variadic arguments do not have maybe_undef attribute.
2234 if (ArgNo
>= NumRequiredArgs
)
2237 // Check if argument has maybe_undef attribute.
2238 if (ArgNo
< FD
->getNumParams()) {
2239 const ParmVarDecl
*Param
= FD
->getParamDecl(ArgNo
);
2240 if (Param
&& Param
->hasAttr
<MaybeUndefAttr
>())
2247 /// Test if it's legal to apply nofpclass for the given parameter type and it's
2248 /// lowered IR type.
2249 static bool canApplyNoFPClass(const ABIArgInfo
&AI
, QualType ParamType
,
2251 // Should only apply to FP types in the source, not ABI promoted.
2252 if (!ParamType
->hasFloatingRepresentation())
2255 // The promoted-to IR type also needs to support nofpclass.
2256 llvm::Type
*IRTy
= AI
.getCoerceToType();
2257 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy
))
2260 if (llvm::StructType
*ST
= dyn_cast
<llvm::StructType
>(IRTy
)) {
2261 return !IsReturn
&& AI
.getCanBeFlattened() &&
2262 llvm::all_of(ST
->elements(), [](llvm::Type
*Ty
) {
2263 return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty
);
2270 /// Return the nofpclass mask that can be applied to floating-point parameters.
2271 static llvm::FPClassTest
getNoFPClassTestMask(const LangOptions
&LangOpts
) {
2272 llvm::FPClassTest Mask
= llvm::fcNone
;
2273 if (LangOpts
.NoHonorInfs
)
2274 Mask
|= llvm::fcInf
;
2275 if (LangOpts
.NoHonorNaNs
)
2276 Mask
|= llvm::fcNan
;
2280 void CodeGenModule::AdjustMemoryAttribute(StringRef Name
,
2281 CGCalleeInfo CalleeInfo
,
2282 llvm::AttributeList
&Attrs
) {
2283 if (Attrs
.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef
) {
2284 Attrs
= Attrs
.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory
);
2285 llvm::Attribute MemoryAttr
= llvm::Attribute::getWithMemoryEffects(
2286 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2287 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), MemoryAttr
);
2291 /// Construct the IR attribute list of a function or call.
2293 /// When adding an attribute, please consider where it should be handled:
2295 /// - getDefaultFunctionAttributes is for attributes that are essentially
2296 /// part of the global target configuration (but perhaps can be
2297 /// overridden on a per-function basis). Adding attributes there
2298 /// will cause them to also be set in frontends that build on Clang's
2299 /// target-configuration logic, as well as for code defined in library
2300 /// modules such as CUDA's libdevice.
2302 /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2303 /// and adds declaration-specific, convention-specific, and
2304 /// frontend-specific logic. The last is of particular importance:
2305 /// attributes that restrict how the frontend generates code must be
2306 /// added here rather than getDefaultFunctionAttributes.
2308 void CodeGenModule::ConstructAttributeList(StringRef Name
,
2309 const CGFunctionInfo
&FI
,
2310 CGCalleeInfo CalleeInfo
,
2311 llvm::AttributeList
&AttrList
,
2312 unsigned &CallingConv
,
2313 bool AttrOnCallSite
, bool IsThunk
) {
2314 llvm::AttrBuilder
FuncAttrs(getLLVMContext());
2315 llvm::AttrBuilder
RetAttrs(getLLVMContext());
2317 // Collect function IR attributes from the CC lowering.
2318 // We'll collect the paramete and result attributes later.
2319 CallingConv
= FI
.getEffectiveCallingConvention();
2320 if (FI
.isNoReturn())
2321 FuncAttrs
.addAttribute(llvm::Attribute::NoReturn
);
2322 if (FI
.isCmseNSCall())
2323 FuncAttrs
.addAttribute("cmse_nonsecure_call");
2325 // Collect function IR attributes from the callee prototype if we have one.
2326 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs
,
2327 CalleeInfo
.getCalleeFunctionProtoType());
2329 const Decl
*TargetDecl
= CalleeInfo
.getCalleeDecl().getDecl();
2331 // Attach assumption attributes to the declaration. If this is a call
2332 // site, attach assumptions from the caller to the call as well.
2333 AddAttributesFromOMPAssumes(FuncAttrs
, TargetDecl
);
2335 bool HasOptnone
= false;
2336 // The NoBuiltinAttr attached to the target FunctionDecl.
2337 const NoBuiltinAttr
*NBA
= nullptr;
2339 // Some ABIs may result in additional accesses to arguments that may
2340 // otherwise not be present.
2341 auto AddPotentialArgAccess
= [&]() {
2342 llvm::Attribute A
= FuncAttrs
.getAttribute(llvm::Attribute::Memory
);
2344 FuncAttrs
.addMemoryAttr(A
.getMemoryEffects() |
2345 llvm::MemoryEffects::argMemOnly());
2348 // Collect function IR attributes based on declaration-specific
2350 // FIXME: handle sseregparm someday...
2352 if (TargetDecl
->hasAttr
<ReturnsTwiceAttr
>())
2353 FuncAttrs
.addAttribute(llvm::Attribute::ReturnsTwice
);
2354 if (TargetDecl
->hasAttr
<NoThrowAttr
>())
2355 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
2356 if (TargetDecl
->hasAttr
<NoReturnAttr
>())
2357 FuncAttrs
.addAttribute(llvm::Attribute::NoReturn
);
2358 if (TargetDecl
->hasAttr
<ColdAttr
>())
2359 FuncAttrs
.addAttribute(llvm::Attribute::Cold
);
2360 if (TargetDecl
->hasAttr
<HotAttr
>())
2361 FuncAttrs
.addAttribute(llvm::Attribute::Hot
);
2362 if (TargetDecl
->hasAttr
<NoDuplicateAttr
>())
2363 FuncAttrs
.addAttribute(llvm::Attribute::NoDuplicate
);
2364 if (TargetDecl
->hasAttr
<ConvergentAttr
>())
2365 FuncAttrs
.addAttribute(llvm::Attribute::Convergent
);
2367 if (const FunctionDecl
*Fn
= dyn_cast
<FunctionDecl
>(TargetDecl
)) {
2368 AddAttributesFromFunctionProtoType(
2369 getContext(), FuncAttrs
, Fn
->getType()->getAs
<FunctionProtoType
>());
2370 if (AttrOnCallSite
&& Fn
->isReplaceableGlobalAllocationFunction()) {
2371 // A sane operator new returns a non-aliasing pointer.
2372 auto Kind
= Fn
->getDeclName().getCXXOverloadedOperator();
2373 if (getCodeGenOpts().AssumeSaneOperatorNew
&&
2374 (Kind
== OO_New
|| Kind
== OO_Array_New
))
2375 RetAttrs
.addAttribute(llvm::Attribute::NoAlias
);
2377 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Fn
);
2378 const bool IsVirtualCall
= MD
&& MD
->isVirtual();
2379 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2380 // virtual function. These attributes are not inherited by overloads.
2381 if (!(AttrOnCallSite
&& IsVirtualCall
)) {
2382 if (Fn
->isNoReturn())
2383 FuncAttrs
.addAttribute(llvm::Attribute::NoReturn
);
2384 NBA
= Fn
->getAttr
<NoBuiltinAttr
>();
2388 if (isa
<FunctionDecl
>(TargetDecl
) || isa
<VarDecl
>(TargetDecl
)) {
2389 // Only place nomerge attribute on call sites, never functions. This
2390 // allows it to work on indirect virtual function calls.
2391 if (AttrOnCallSite
&& TargetDecl
->hasAttr
<NoMergeAttr
>())
2392 FuncAttrs
.addAttribute(llvm::Attribute::NoMerge
);
2395 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2396 if (TargetDecl
->hasAttr
<ConstAttr
>()) {
2397 FuncAttrs
.addMemoryAttr(llvm::MemoryEffects::none());
2398 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
2399 // gcc specifies that 'const' functions have greater restrictions than
2400 // 'pure' functions, so they also cannot have infinite loops.
2401 FuncAttrs
.addAttribute(llvm::Attribute::WillReturn
);
2402 } else if (TargetDecl
->hasAttr
<PureAttr
>()) {
2403 FuncAttrs
.addMemoryAttr(llvm::MemoryEffects::readOnly());
2404 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
2405 // gcc specifies that 'pure' functions cannot have infinite loops.
2406 FuncAttrs
.addAttribute(llvm::Attribute::WillReturn
);
2407 } else if (TargetDecl
->hasAttr
<NoAliasAttr
>()) {
2408 FuncAttrs
.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2409 FuncAttrs
.addAttribute(llvm::Attribute::NoUnwind
);
2411 if (TargetDecl
->hasAttr
<RestrictAttr
>())
2412 RetAttrs
.addAttribute(llvm::Attribute::NoAlias
);
2413 if (TargetDecl
->hasAttr
<ReturnsNonNullAttr
>() &&
2414 !CodeGenOpts
.NullPointerIsValid
)
2415 RetAttrs
.addAttribute(llvm::Attribute::NonNull
);
2416 if (TargetDecl
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>())
2417 FuncAttrs
.addAttribute("no_caller_saved_registers");
2418 if (TargetDecl
->hasAttr
<AnyX86NoCfCheckAttr
>())
2419 FuncAttrs
.addAttribute(llvm::Attribute::NoCfCheck
);
2420 if (TargetDecl
->hasAttr
<LeafAttr
>())
2421 FuncAttrs
.addAttribute(llvm::Attribute::NoCallback
);
2423 HasOptnone
= TargetDecl
->hasAttr
<OptimizeNoneAttr
>();
2424 if (auto *AllocSize
= TargetDecl
->getAttr
<AllocSizeAttr
>()) {
2425 std::optional
<unsigned> NumElemsParam
;
2426 if (AllocSize
->getNumElemsParam().isValid())
2427 NumElemsParam
= AllocSize
->getNumElemsParam().getLLVMIndex();
2428 FuncAttrs
.addAllocSizeAttr(AllocSize
->getElemSizeParam().getLLVMIndex(),
2432 if (TargetDecl
->hasAttr
<OpenCLKernelAttr
>()) {
2433 if (getLangOpts().OpenCLVersion
<= 120) {
2434 // OpenCL v1.2 Work groups are always uniform
2435 FuncAttrs
.addAttribute("uniform-work-group-size", "true");
2437 // OpenCL v2.0 Work groups may be whether uniform or not.
2438 // '-cl-uniform-work-group-size' compile option gets a hint
2439 // to the compiler that the global work-size be a multiple of
2440 // the work-group size specified to clEnqueueNDRangeKernel
2441 // (i.e. work groups are uniform).
2442 FuncAttrs
.addAttribute(
2443 "uniform-work-group-size",
2444 llvm::toStringRef(getLangOpts().OffloadUniformBlock
));
2448 if (TargetDecl
->hasAttr
<CUDAGlobalAttr
>() &&
2449 getLangOpts().OffloadUniformBlock
)
2450 FuncAttrs
.addAttribute("uniform-work-group-size", "true");
2452 if (TargetDecl
->hasAttr
<ArmLocallyStreamingAttr
>())
2453 FuncAttrs
.addAttribute("aarch64_pstate_sm_body");
2456 // Attach "no-builtins" attributes to:
2457 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2458 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2459 // The attributes can come from:
2460 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2461 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2462 addNoBuiltinAttributes(FuncAttrs
, getLangOpts(), NBA
);
2464 // Collect function IR attributes based on global settiings.
2465 getDefaultFunctionAttributes(Name
, HasOptnone
, AttrOnCallSite
, FuncAttrs
);
2467 // Override some default IR attributes based on declaration-specific
2470 if (TargetDecl
->hasAttr
<NoSpeculativeLoadHardeningAttr
>())
2471 FuncAttrs
.removeAttribute(llvm::Attribute::SpeculativeLoadHardening
);
2472 if (TargetDecl
->hasAttr
<SpeculativeLoadHardeningAttr
>())
2473 FuncAttrs
.addAttribute(llvm::Attribute::SpeculativeLoadHardening
);
2474 if (TargetDecl
->hasAttr
<NoSplitStackAttr
>())
2475 FuncAttrs
.removeAttribute("split-stack");
2476 if (TargetDecl
->hasAttr
<ZeroCallUsedRegsAttr
>()) {
2477 // A function "__attribute__((...))" overrides the command-line flag.
2479 TargetDecl
->getAttr
<ZeroCallUsedRegsAttr
>()->getZeroCallUsedRegs();
2480 FuncAttrs
.removeAttribute("zero-call-used-regs");
2481 FuncAttrs
.addAttribute(
2482 "zero-call-used-regs",
2483 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind
));
2486 // Add NonLazyBind attribute to function declarations when -fno-plt
2488 // FIXME: what if we just haven't processed the function definition
2489 // yet, or if it's an external definition like C99 inline?
2490 if (CodeGenOpts
.NoPLT
) {
2491 if (auto *Fn
= dyn_cast
<FunctionDecl
>(TargetDecl
)) {
2492 if (!Fn
->isDefined() && !AttrOnCallSite
) {
2493 FuncAttrs
.addAttribute(llvm::Attribute::NonLazyBind
);
2499 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2500 // functions with -funique-internal-linkage-names.
2501 if (TargetDecl
&& CodeGenOpts
.UniqueInternalLinkageNames
) {
2502 if (const auto *FD
= dyn_cast_or_null
<FunctionDecl
>(TargetDecl
)) {
2503 if (!FD
->isExternallyVisible())
2504 FuncAttrs
.addAttribute("sample-profile-suffix-elision-policy",
2509 // Collect non-call-site function IR attributes from declaration-specific
2511 if (!AttrOnCallSite
) {
2512 if (TargetDecl
&& TargetDecl
->hasAttr
<CmseNSEntryAttr
>())
2513 FuncAttrs
.addAttribute("cmse_nonsecure_entry");
2515 // Whether tail calls are enabled.
2516 auto shouldDisableTailCalls
= [&] {
2517 // Should this be honored in getDefaultFunctionAttributes?
2518 if (CodeGenOpts
.DisableTailCalls
)
2524 if (TargetDecl
->hasAttr
<DisableTailCallsAttr
>() ||
2525 TargetDecl
->hasAttr
<AnyX86InterruptAttr
>())
2528 if (CodeGenOpts
.NoEscapingBlockTailCalls
) {
2529 if (const auto *BD
= dyn_cast
<BlockDecl
>(TargetDecl
))
2530 if (!BD
->doesNotEscape())
2536 if (shouldDisableTailCalls())
2537 FuncAttrs
.addAttribute("disable-tail-calls", "true");
2539 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2540 // handles these separately to set them based on the global defaults.
2541 GetCPUAndFeaturesAttributes(CalleeInfo
.getCalleeDecl(), FuncAttrs
);
2544 // Collect attributes from arguments and return values.
2545 ClangToLLVMArgMapping
IRFunctionArgs(getContext(), FI
);
2547 QualType RetTy
= FI
.getReturnType();
2548 const ABIArgInfo
&RetAI
= FI
.getReturnInfo();
2549 const llvm::DataLayout
&DL
= getDataLayout();
2551 // Determine if the return type could be partially undef
2552 if (CodeGenOpts
.EnableNoundefAttrs
&&
2553 HasStrictReturn(*this, RetTy
, TargetDecl
)) {
2554 if (!RetTy
->isVoidType() && RetAI
.getKind() != ABIArgInfo::Indirect
&&
2555 DetermineNoUndef(RetTy
, getTypes(), DL
, RetAI
))
2556 RetAttrs
.addAttribute(llvm::Attribute::NoUndef
);
2559 switch (RetAI
.getKind()) {
2560 case ABIArgInfo::Extend
:
2561 if (RetAI
.isSignExt())
2562 RetAttrs
.addAttribute(llvm::Attribute::SExt
);
2564 RetAttrs
.addAttribute(llvm::Attribute::ZExt
);
2566 case ABIArgInfo::Direct
:
2567 if (RetAI
.getInReg())
2568 RetAttrs
.addAttribute(llvm::Attribute::InReg
);
2570 if (canApplyNoFPClass(RetAI
, RetTy
, true))
2571 RetAttrs
.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2574 case ABIArgInfo::Ignore
:
2577 case ABIArgInfo::InAlloca
:
2578 case ABIArgInfo::Indirect
: {
2579 // inalloca and sret disable readnone and readonly
2580 AddPotentialArgAccess();
2584 case ABIArgInfo::CoerceAndExpand
:
2587 case ABIArgInfo::Expand
:
2588 case ABIArgInfo::IndirectAliased
:
2589 llvm_unreachable("Invalid ABI kind for return argument");
2593 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2594 if (const auto *RefTy
= RetTy
->getAs
<ReferenceType
>()) {
2595 QualType PTy
= RefTy
->getPointeeType();
2596 if (!PTy
->isIncompleteType() && PTy
->isConstantSizeType())
2597 RetAttrs
.addDereferenceableAttr(
2598 getMinimumObjectSize(PTy
).getQuantity());
2599 if (getTypes().getTargetAddressSpace(PTy
) == 0 &&
2600 !CodeGenOpts
.NullPointerIsValid
)
2601 RetAttrs
.addAttribute(llvm::Attribute::NonNull
);
2602 if (PTy
->isObjectType()) {
2603 llvm::Align Alignment
=
2604 getNaturalPointeeTypeAlignment(RetTy
).getAsAlign();
2605 RetAttrs
.addAlignmentAttr(Alignment
);
2610 bool hasUsedSRet
= false;
2611 SmallVector
<llvm::AttributeSet
, 4> ArgAttrs(IRFunctionArgs
.totalIRArgs());
2613 // Attach attributes to sret.
2614 if (IRFunctionArgs
.hasSRetArg()) {
2615 llvm::AttrBuilder
SRETAttrs(getLLVMContext());
2616 SRETAttrs
.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy
));
2617 SRETAttrs
.addAttribute(llvm::Attribute::Writable
);
2618 SRETAttrs
.addAttribute(llvm::Attribute::DeadOnUnwind
);
2620 if (RetAI
.getInReg())
2621 SRETAttrs
.addAttribute(llvm::Attribute::InReg
);
2622 SRETAttrs
.addAlignmentAttr(RetAI
.getIndirectAlign().getQuantity());
2623 ArgAttrs
[IRFunctionArgs
.getSRetArgNo()] =
2624 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs
);
2627 // Attach attributes to inalloca argument.
2628 if (IRFunctionArgs
.hasInallocaArg()) {
2629 llvm::AttrBuilder
Attrs(getLLVMContext());
2630 Attrs
.addInAllocaAttr(FI
.getArgStruct());
2631 ArgAttrs
[IRFunctionArgs
.getInallocaArgNo()] =
2632 llvm::AttributeSet::get(getLLVMContext(), Attrs
);
2635 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2636 // unless this is a thunk function.
2637 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2638 if (FI
.isInstanceMethod() && !IRFunctionArgs
.hasInallocaArg() &&
2639 !FI
.arg_begin()->type
->isVoidPointerType() && !IsThunk
) {
2640 auto IRArgs
= IRFunctionArgs
.getIRArgs(0);
2642 assert(IRArgs
.second
== 1 && "Expected only a single `this` pointer.");
2644 llvm::AttrBuilder
Attrs(getLLVMContext());
2647 FI
.arg_begin()->type
.getTypePtr()->getPointeeType();
2649 if (!CodeGenOpts
.NullPointerIsValid
&&
2650 getTypes().getTargetAddressSpace(FI
.arg_begin()->type
) == 0) {
2651 Attrs
.addAttribute(llvm::Attribute::NonNull
);
2652 Attrs
.addDereferenceableAttr(getMinimumObjectSize(ThisTy
).getQuantity());
2654 // FIXME dereferenceable should be correct here, regardless of
2655 // NullPointerIsValid. However, dereferenceable currently does not always
2656 // respect NullPointerIsValid and may imply nonnull and break the program.
2657 // See https://reviews.llvm.org/D66618 for discussions.
2658 Attrs
.addDereferenceableOrNullAttr(
2659 getMinimumObjectSize(
2660 FI
.arg_begin()->type
.castAs
<PointerType
>()->getPointeeType())
2664 llvm::Align Alignment
=
2665 getNaturalTypeAlignment(ThisTy
, /*BaseInfo=*/nullptr,
2666 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2668 Attrs
.addAlignmentAttr(Alignment
);
2670 ArgAttrs
[IRArgs
.first
] = llvm::AttributeSet::get(getLLVMContext(), Attrs
);
2674 for (CGFunctionInfo::const_arg_iterator I
= FI
.arg_begin(),
2676 I
!= E
; ++I
, ++ArgNo
) {
2677 QualType ParamType
= I
->type
;
2678 const ABIArgInfo
&AI
= I
->info
;
2679 llvm::AttrBuilder
Attrs(getLLVMContext());
2681 // Add attribute for padding argument, if necessary.
2682 if (IRFunctionArgs
.hasPaddingArg(ArgNo
)) {
2683 if (AI
.getPaddingInReg()) {
2684 ArgAttrs
[IRFunctionArgs
.getPaddingArgNo(ArgNo
)] =
2685 llvm::AttributeSet::get(
2687 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg
));
2691 // Decide whether the argument we're handling could be partially undef
2692 if (CodeGenOpts
.EnableNoundefAttrs
&&
2693 DetermineNoUndef(ParamType
, getTypes(), DL
, AI
)) {
2694 Attrs
.addAttribute(llvm::Attribute::NoUndef
);
2697 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2698 // have the corresponding parameter variable. It doesn't make
2699 // sense to do it here because parameters are so messed up.
2700 switch (AI
.getKind()) {
2701 case ABIArgInfo::Extend
:
2703 Attrs
.addAttribute(llvm::Attribute::SExt
);
2705 Attrs
.addAttribute(llvm::Attribute::ZExt
);
2707 case ABIArgInfo::Direct
:
2708 if (ArgNo
== 0 && FI
.isChainCall())
2709 Attrs
.addAttribute(llvm::Attribute::Nest
);
2710 else if (AI
.getInReg())
2711 Attrs
.addAttribute(llvm::Attribute::InReg
);
2712 Attrs
.addStackAlignmentAttr(llvm::MaybeAlign(AI
.getDirectAlign()));
2714 if (canApplyNoFPClass(AI
, ParamType
, false))
2715 Attrs
.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2717 case ABIArgInfo::Indirect
: {
2719 Attrs
.addAttribute(llvm::Attribute::InReg
);
2721 if (AI
.getIndirectByVal())
2722 Attrs
.addByValAttr(getTypes().ConvertTypeForMem(ParamType
));
2724 auto *Decl
= ParamType
->getAsRecordDecl();
2725 if (CodeGenOpts
.PassByValueIsNoAlias
&& Decl
&&
2726 Decl
->getArgPassingRestrictions() ==
2727 RecordArgPassingKind::CanPassInRegs
)
2728 // When calling the function, the pointer passed in will be the only
2729 // reference to the underlying object. Mark it accordingly.
2730 Attrs
.addAttribute(llvm::Attribute::NoAlias
);
2732 // TODO: We could add the byref attribute if not byval, but it would
2733 // require updating many testcases.
2735 CharUnits Align
= AI
.getIndirectAlign();
2737 // In a byval argument, it is important that the required
2738 // alignment of the type is honored, as LLVM might be creating a
2739 // *new* stack object, and needs to know what alignment to give
2740 // it. (Sometimes it can deduce a sensible alignment on its own,
2741 // but not if clang decides it must emit a packed struct, or the
2742 // user specifies increased alignment requirements.)
2744 // This is different from indirect *not* byval, where the object
2745 // exists already, and the align attribute is purely
2747 assert(!Align
.isZero());
2749 // For now, only add this when we have a byval argument.
2750 // TODO: be less lazy about updating test cases.
2751 if (AI
.getIndirectByVal())
2752 Attrs
.addAlignmentAttr(Align
.getQuantity());
2754 // byval disables readnone and readonly.
2755 AddPotentialArgAccess();
2758 case ABIArgInfo::IndirectAliased
: {
2759 CharUnits Align
= AI
.getIndirectAlign();
2760 Attrs
.addByRefAttr(getTypes().ConvertTypeForMem(ParamType
));
2761 Attrs
.addAlignmentAttr(Align
.getQuantity());
2764 case ABIArgInfo::Ignore
:
2765 case ABIArgInfo::Expand
:
2766 case ABIArgInfo::CoerceAndExpand
:
2769 case ABIArgInfo::InAlloca
:
2770 // inalloca disables readnone and readonly.
2771 AddPotentialArgAccess();
2775 if (const auto *RefTy
= ParamType
->getAs
<ReferenceType
>()) {
2776 QualType PTy
= RefTy
->getPointeeType();
2777 if (!PTy
->isIncompleteType() && PTy
->isConstantSizeType())
2778 Attrs
.addDereferenceableAttr(
2779 getMinimumObjectSize(PTy
).getQuantity());
2780 if (getTypes().getTargetAddressSpace(PTy
) == 0 &&
2781 !CodeGenOpts
.NullPointerIsValid
)
2782 Attrs
.addAttribute(llvm::Attribute::NonNull
);
2783 if (PTy
->isObjectType()) {
2784 llvm::Align Alignment
=
2785 getNaturalPointeeTypeAlignment(ParamType
).getAsAlign();
2786 Attrs
.addAlignmentAttr(Alignment
);
2790 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2791 // > For arguments to a __kernel function declared to be a pointer to a
2792 // > data type, the OpenCL compiler can assume that the pointee is always
2793 // > appropriately aligned as required by the data type.
2794 if (TargetDecl
&& TargetDecl
->hasAttr
<OpenCLKernelAttr
>() &&
2795 ParamType
->isPointerType()) {
2796 QualType PTy
= ParamType
->getPointeeType();
2797 if (!PTy
->isIncompleteType() && PTy
->isConstantSizeType()) {
2798 llvm::Align Alignment
=
2799 getNaturalPointeeTypeAlignment(ParamType
).getAsAlign();
2800 Attrs
.addAlignmentAttr(Alignment
);
2804 switch (FI
.getExtParameterInfo(ArgNo
).getABI()) {
2805 case ParameterABI::Ordinary
:
2808 case ParameterABI::SwiftIndirectResult
: {
2809 // Add 'sret' if we haven't already used it for something, but
2810 // only if the result is void.
2811 if (!hasUsedSRet
&& RetTy
->isVoidType()) {
2812 Attrs
.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType
));
2816 // Add 'noalias' in either case.
2817 Attrs
.addAttribute(llvm::Attribute::NoAlias
);
2819 // Add 'dereferenceable' and 'alignment'.
2820 auto PTy
= ParamType
->getPointeeType();
2821 if (!PTy
->isIncompleteType() && PTy
->isConstantSizeType()) {
2822 auto info
= getContext().getTypeInfoInChars(PTy
);
2823 Attrs
.addDereferenceableAttr(info
.Width
.getQuantity());
2824 Attrs
.addAlignmentAttr(info
.Align
.getAsAlign());
2829 case ParameterABI::SwiftErrorResult
:
2830 Attrs
.addAttribute(llvm::Attribute::SwiftError
);
2833 case ParameterABI::SwiftContext
:
2834 Attrs
.addAttribute(llvm::Attribute::SwiftSelf
);
2837 case ParameterABI::SwiftAsyncContext
:
2838 Attrs
.addAttribute(llvm::Attribute::SwiftAsync
);
2842 if (FI
.getExtParameterInfo(ArgNo
).isNoEscape())
2843 Attrs
.addAttribute(llvm::Attribute::NoCapture
);
2845 if (Attrs
.hasAttributes()) {
2846 unsigned FirstIRArg
, NumIRArgs
;
2847 std::tie(FirstIRArg
, NumIRArgs
) = IRFunctionArgs
.getIRArgs(ArgNo
);
2848 for (unsigned i
= 0; i
< NumIRArgs
; i
++)
2849 ArgAttrs
[FirstIRArg
+ i
] = ArgAttrs
[FirstIRArg
+ i
].addAttributes(
2850 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs
));
2853 assert(ArgNo
== FI
.arg_size());
2855 AttrList
= llvm::AttributeList::get(
2856 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs
),
2857 llvm::AttributeSet::get(getLLVMContext(), RetAttrs
), ArgAttrs
);
2860 /// An argument came in as a promoted argument; demote it back to its
2862 static llvm::Value
*emitArgumentDemotion(CodeGenFunction
&CGF
,
2864 llvm::Value
*value
) {
2865 llvm::Type
*varType
= CGF
.ConvertType(var
->getType());
2867 // This can happen with promotions that actually don't change the
2868 // underlying type, like the enum promotions.
2869 if (value
->getType() == varType
) return value
;
2871 assert((varType
->isIntegerTy() || varType
->isFloatingPointTy())
2872 && "unexpected promotion type");
2874 if (isa
<llvm::IntegerType
>(varType
))
2875 return CGF
.Builder
.CreateTrunc(value
, varType
, "arg.unpromote");
2877 return CGF
.Builder
.CreateFPCast(value
, varType
, "arg.unpromote");
2880 /// Returns the attribute (either parameter attribute, or function
2881 /// attribute), which declares argument ArgNo to be non-null.
2882 static const NonNullAttr
*getNonNullAttr(const Decl
*FD
, const ParmVarDecl
*PVD
,
2883 QualType ArgType
, unsigned ArgNo
) {
2884 // FIXME: __attribute__((nonnull)) can also be applied to:
2885 // - references to pointers, where the pointee is known to be
2886 // nonnull (apparently a Clang extension)
2887 // - transparent unions containing pointers
2888 // In the former case, LLVM IR cannot represent the constraint. In
2889 // the latter case, we have no guarantee that the transparent union
2890 // is in fact passed as a pointer.
2891 if (!ArgType
->isAnyPointerType() && !ArgType
->isBlockPointerType())
2893 // First, check attribute on parameter itself.
2895 if (auto ParmNNAttr
= PVD
->getAttr
<NonNullAttr
>())
2898 // Check function attributes.
2901 for (const auto *NNAttr
: FD
->specific_attrs
<NonNullAttr
>()) {
2902 if (NNAttr
->isNonNull(ArgNo
))
2909 struct CopyBackSwiftError final
: EHScopeStack::Cleanup
{
2912 CopyBackSwiftError(Address temp
, Address arg
) : Temp(temp
), Arg(arg
) {}
2913 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2914 llvm::Value
*errorValue
= CGF
.Builder
.CreateLoad(Temp
);
2915 CGF
.Builder
.CreateStore(errorValue
, Arg
);
2920 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo
&FI
,
2922 const FunctionArgList
&Args
) {
2923 if (CurCodeDecl
&& CurCodeDecl
->hasAttr
<NakedAttr
>())
2924 // Naked functions don't have prologues.
2927 // If this is an implicit-return-zero function, go ahead and
2928 // initialize the return value. TODO: it might be nice to have
2929 // a more general mechanism for this that didn't require synthesized
2930 // return statements.
2931 if (const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(CurCodeDecl
)) {
2932 if (FD
->hasImplicitReturnZero()) {
2933 QualType RetTy
= FD
->getReturnType().getUnqualifiedType();
2934 llvm::Type
* LLVMTy
= CGM
.getTypes().ConvertType(RetTy
);
2935 llvm::Constant
* Zero
= llvm::Constant::getNullValue(LLVMTy
);
2936 Builder
.CreateStore(Zero
, ReturnValue
);
2940 // FIXME: We no longer need the types from FunctionArgList; lift up and
2943 ClangToLLVMArgMapping
IRFunctionArgs(CGM
.getContext(), FI
);
2944 assert(Fn
->arg_size() == IRFunctionArgs
.totalIRArgs());
2946 // If we're using inalloca, all the memory arguments are GEPs off of the last
2947 // parameter, which is a pointer to the complete memory area.
2948 Address ArgStruct
= Address::invalid();
2949 if (IRFunctionArgs
.hasInallocaArg())
2950 ArgStruct
= Address(Fn
->getArg(IRFunctionArgs
.getInallocaArgNo()),
2951 FI
.getArgStruct(), FI
.getArgStructAlignment());
2953 // Name the struct return parameter.
2954 if (IRFunctionArgs
.hasSRetArg()) {
2955 auto AI
= Fn
->getArg(IRFunctionArgs
.getSRetArgNo());
2956 AI
->setName("agg.result");
2957 AI
->addAttr(llvm::Attribute::NoAlias
);
2960 // Track if we received the parameter as a pointer (indirect, byval, or
2961 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2962 // into a local alloca for us.
2963 SmallVector
<ParamValue
, 16> ArgVals
;
2964 ArgVals
.reserve(Args
.size());
2966 // Create a pointer value for every parameter declaration. This usually
2967 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2968 // any cleanups or do anything that might unwind. We do that separately, so
2969 // we can push the cleanups in the correct order for the ABI.
2970 assert(FI
.arg_size() == Args
.size() &&
2971 "Mismatch between function signature & arguments.");
2973 CGFunctionInfo::const_arg_iterator info_it
= FI
.arg_begin();
2974 for (FunctionArgList::const_iterator i
= Args
.begin(), e
= Args
.end();
2975 i
!= e
; ++i
, ++info_it
, ++ArgNo
) {
2976 const VarDecl
*Arg
= *i
;
2977 const ABIArgInfo
&ArgI
= info_it
->info
;
2980 isa
<ParmVarDecl
>(Arg
) && cast
<ParmVarDecl
>(Arg
)->isKNRPromoted();
2981 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2982 // the parameter is promoted. In this case we convert to
2983 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2984 QualType Ty
= isPromoted
? info_it
->type
: Arg
->getType();
2985 assert(hasScalarEvaluationKind(Ty
) ==
2986 hasScalarEvaluationKind(Arg
->getType()));
2988 unsigned FirstIRArg
, NumIRArgs
;
2989 std::tie(FirstIRArg
, NumIRArgs
) = IRFunctionArgs
.getIRArgs(ArgNo
);
2991 switch (ArgI
.getKind()) {
2992 case ABIArgInfo::InAlloca
: {
2993 assert(NumIRArgs
== 0);
2994 auto FieldIndex
= ArgI
.getInAllocaFieldIndex();
2996 Builder
.CreateStructGEP(ArgStruct
, FieldIndex
, Arg
->getName());
2997 if (ArgI
.getInAllocaIndirect())
2998 V
= Address(Builder
.CreateLoad(V
), ConvertTypeForMem(Ty
),
2999 getContext().getTypeAlignInChars(Ty
));
3000 ArgVals
.push_back(ParamValue::forIndirect(V
));
3004 case ABIArgInfo::Indirect
:
3005 case ABIArgInfo::IndirectAliased
: {
3006 assert(NumIRArgs
== 1);
3007 Address ParamAddr
= makeNaturalAddressForPointer(
3008 Fn
->getArg(FirstIRArg
), Ty
, ArgI
.getIndirectAlign(), false, nullptr,
3009 nullptr, KnownNonNull
);
3011 if (!hasScalarEvaluationKind(Ty
)) {
3012 // Aggregates and complex variables are accessed by reference. All we
3013 // need to do is realign the value, if requested. Also, if the address
3014 // may be aliased, copy it to ensure that the parameter variable is
3015 // mutable and has a unique adress, as C requires.
3016 if (ArgI
.getIndirectRealign() || ArgI
.isIndirectAliased()) {
3017 RawAddress AlignedTemp
= CreateMemTemp(Ty
, "coerce");
3019 // Copy from the incoming argument pointer to the temporary with the
3020 // appropriate alignment.
3022 // FIXME: We should have a common utility for generating an aggregate
3024 CharUnits Size
= getContext().getTypeSizeInChars(Ty
);
3025 Builder
.CreateMemCpy(
3026 AlignedTemp
.getPointer(), AlignedTemp
.getAlignment().getAsAlign(),
3027 ParamAddr
.emitRawPointer(*this),
3028 ParamAddr
.getAlignment().getAsAlign(),
3029 llvm::ConstantInt::get(IntPtrTy
, Size
.getQuantity()));
3030 ParamAddr
= AlignedTemp
;
3032 ArgVals
.push_back(ParamValue::forIndirect(ParamAddr
));
3034 // Load scalar value from indirect argument.
3036 EmitLoadOfScalar(ParamAddr
, false, Ty
, Arg
->getBeginLoc());
3039 V
= emitArgumentDemotion(*this, Arg
, V
);
3040 ArgVals
.push_back(ParamValue::forDirect(V
));
3045 case ABIArgInfo::Extend
:
3046 case ABIArgInfo::Direct
: {
3047 auto AI
= Fn
->getArg(FirstIRArg
);
3048 llvm::Type
*LTy
= ConvertType(Arg
->getType());
3050 // Prepare parameter attributes. So far, only attributes for pointer
3051 // parameters are prepared. See
3052 // http://llvm.org/docs/LangRef.html#paramattrs.
3053 if (ArgI
.getDirectOffset() == 0 && LTy
->isPointerTy() &&
3054 ArgI
.getCoerceToType()->isPointerTy()) {
3055 assert(NumIRArgs
== 1);
3057 if (const ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(Arg
)) {
3058 // Set `nonnull` attribute if any.
3059 if (getNonNullAttr(CurCodeDecl
, PVD
, PVD
->getType(),
3060 PVD
->getFunctionScopeIndex()) &&
3061 !CGM
.getCodeGenOpts().NullPointerIsValid
)
3062 AI
->addAttr(llvm::Attribute::NonNull
);
3064 QualType OTy
= PVD
->getOriginalType();
3065 if (const auto *ArrTy
=
3066 getContext().getAsConstantArrayType(OTy
)) {
3067 // A C99 array parameter declaration with the static keyword also
3068 // indicates dereferenceability, and if the size is constant we can
3069 // use the dereferenceable attribute (which requires the size in
3071 if (ArrTy
->getSizeModifier() == ArraySizeModifier::Static
) {
3072 QualType ETy
= ArrTy
->getElementType();
3073 llvm::Align Alignment
=
3074 CGM
.getNaturalTypeAlignment(ETy
).getAsAlign();
3075 AI
->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment
));
3076 uint64_t ArrSize
= ArrTy
->getZExtSize();
3077 if (!ETy
->isIncompleteType() && ETy
->isConstantSizeType() &&
3079 llvm::AttrBuilder
Attrs(getLLVMContext());
3080 Attrs
.addDereferenceableAttr(
3081 getContext().getTypeSizeInChars(ETy
).getQuantity() *
3083 AI
->addAttrs(Attrs
);
3084 } else if (getContext().getTargetInfo().getNullPointerValue(
3085 ETy
.getAddressSpace()) == 0 &&
3086 !CGM
.getCodeGenOpts().NullPointerIsValid
) {
3087 AI
->addAttr(llvm::Attribute::NonNull
);
3090 } else if (const auto *ArrTy
=
3091 getContext().getAsVariableArrayType(OTy
)) {
3092 // For C99 VLAs with the static keyword, we don't know the size so
3093 // we can't use the dereferenceable attribute, but in addrspace(0)
3094 // we know that it must be nonnull.
3095 if (ArrTy
->getSizeModifier() == ArraySizeModifier::Static
) {
3096 QualType ETy
= ArrTy
->getElementType();
3097 llvm::Align Alignment
=
3098 CGM
.getNaturalTypeAlignment(ETy
).getAsAlign();
3099 AI
->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment
));
3100 if (!getTypes().getTargetAddressSpace(ETy
) &&
3101 !CGM
.getCodeGenOpts().NullPointerIsValid
)
3102 AI
->addAttr(llvm::Attribute::NonNull
);
3106 // Set `align` attribute if any.
3107 const auto *AVAttr
= PVD
->getAttr
<AlignValueAttr
>();
3109 if (const auto *TOTy
= OTy
->getAs
<TypedefType
>())
3110 AVAttr
= TOTy
->getDecl()->getAttr
<AlignValueAttr
>();
3111 if (AVAttr
&& !SanOpts
.has(SanitizerKind::Alignment
)) {
3112 // If alignment-assumption sanitizer is enabled, we do *not* add
3113 // alignment attribute here, but emit normal alignment assumption,
3114 // so the UBSAN check could function.
3115 llvm::ConstantInt
*AlignmentCI
=
3116 cast
<llvm::ConstantInt
>(EmitScalarExpr(AVAttr
->getAlignment()));
3117 uint64_t AlignmentInt
=
3118 AlignmentCI
->getLimitedValue(llvm::Value::MaximumAlignment
);
3119 if (AI
->getParamAlign().valueOrOne() < AlignmentInt
) {
3120 AI
->removeAttr(llvm::Attribute::AttrKind::Alignment
);
3121 AI
->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3122 llvm::Align(AlignmentInt
)));
3127 // Set 'noalias' if an argument type has the `restrict` qualifier.
3128 if (Arg
->getType().isRestrictQualified())
3129 AI
->addAttr(llvm::Attribute::NoAlias
);
3132 // Prepare the argument value. If we have the trivial case, handle it
3133 // with no muss and fuss.
3134 if (!isa
<llvm::StructType
>(ArgI
.getCoerceToType()) &&
3135 ArgI
.getCoerceToType() == ConvertType(Ty
) &&
3136 ArgI
.getDirectOffset() == 0) {
3137 assert(NumIRArgs
== 1);
3139 // LLVM expects swifterror parameters to be used in very restricted
3140 // ways. Copy the value into a less-restricted temporary.
3141 llvm::Value
*V
= AI
;
3142 if (FI
.getExtParameterInfo(ArgNo
).getABI()
3143 == ParameterABI::SwiftErrorResult
) {
3144 QualType pointeeTy
= Ty
->getPointeeType();
3145 assert(pointeeTy
->isPointerType());
3147 CreateMemTemp(pointeeTy
, getPointerAlign(), "swifterror.temp");
3148 Address arg
= makeNaturalAddressForPointer(
3149 V
, pointeeTy
, getContext().getTypeAlignInChars(pointeeTy
));
3150 llvm::Value
*incomingErrorValue
= Builder
.CreateLoad(arg
);
3151 Builder
.CreateStore(incomingErrorValue
, temp
);
3152 V
= temp
.getPointer();
3154 // Push a cleanup to copy the value back at the end of the function.
3155 // The convention does not guarantee that the value will be written
3156 // back if the function exits with an unwind exception.
3157 EHStack
.pushCleanup
<CopyBackSwiftError
>(NormalCleanup
, temp
, arg
);
3160 // Ensure the argument is the correct type.
3161 if (V
->getType() != ArgI
.getCoerceToType())
3162 V
= Builder
.CreateBitCast(V
, ArgI
.getCoerceToType());
3165 V
= emitArgumentDemotion(*this, Arg
, V
);
3167 // Because of merging of function types from multiple decls it is
3168 // possible for the type of an argument to not match the corresponding
3169 // type in the function type. Since we are codegening the callee
3170 // in here, add a cast to the argument type.
3171 llvm::Type
*LTy
= ConvertType(Arg
->getType());
3172 if (V
->getType() != LTy
)
3173 V
= Builder
.CreateBitCast(V
, LTy
);
3175 ArgVals
.push_back(ParamValue::forDirect(V
));
3179 // VLST arguments are coerced to VLATs at the function boundary for
3180 // ABI consistency. If this is a VLST that was coerced to
3181 // a VLAT at the function boundary and the types match up, use
3182 // llvm.vector.extract to convert back to the original VLST.
3183 if (auto *VecTyTo
= dyn_cast
<llvm::FixedVectorType
>(ConvertType(Ty
))) {
3184 llvm::Value
*Coerced
= Fn
->getArg(FirstIRArg
);
3185 if (auto *VecTyFrom
=
3186 dyn_cast
<llvm::ScalableVectorType
>(Coerced
->getType())) {
3187 // If we are casting a scalable i1 predicate vector to a fixed i8
3188 // vector, bitcast the source and use a vector extract.
3189 if (VecTyFrom
->getElementType()->isIntegerTy(1) &&
3190 VecTyFrom
->getElementCount().isKnownMultipleOf(8) &&
3191 VecTyTo
->getElementType() == Builder
.getInt8Ty()) {
3192 VecTyFrom
= llvm::ScalableVectorType::get(
3193 VecTyTo
->getElementType(),
3194 VecTyFrom
->getElementCount().getKnownMinValue() / 8);
3195 Coerced
= Builder
.CreateBitCast(Coerced
, VecTyFrom
);
3197 if (VecTyFrom
->getElementType() == VecTyTo
->getElementType()) {
3198 llvm::Value
*Zero
= llvm::Constant::getNullValue(CGM
.Int64Ty
);
3200 assert(NumIRArgs
== 1);
3201 Coerced
->setName(Arg
->getName() + ".coerce");
3202 ArgVals
.push_back(ParamValue::forDirect(Builder
.CreateExtractVector(
3203 VecTyTo
, Coerced
, Zero
, "cast.fixed")));
3209 llvm::StructType
*STy
=
3210 dyn_cast
<llvm::StructType
>(ArgI
.getCoerceToType());
3211 if (ArgI
.isDirect() && !ArgI
.getCanBeFlattened() && STy
&&
3212 STy
->getNumElements() > 1) {
3213 [[maybe_unused
]] llvm::TypeSize StructSize
=
3214 CGM
.getDataLayout().getTypeAllocSize(STy
);
3215 [[maybe_unused
]] llvm::TypeSize PtrElementSize
=
3216 CGM
.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty
));
3217 if (STy
->containsHomogeneousScalableVectorTypes()) {
3218 assert(StructSize
== PtrElementSize
&&
3219 "Only allow non-fractional movement of structure with"
3220 "homogeneous scalable vector type");
3222 ArgVals
.push_back(ParamValue::forDirect(AI
));
3227 Address Alloca
= CreateMemTemp(Ty
, getContext().getDeclAlign(Arg
),
3230 // Pointer to store into.
3231 Address Ptr
= emitAddressAtOffset(*this, Alloca
, ArgI
);
3233 // Fast-isel and the optimizer generally like scalar values better than
3234 // FCAs, so we flatten them if this is safe to do for this argument.
3235 if (ArgI
.isDirect() && ArgI
.getCanBeFlattened() && STy
&&
3236 STy
->getNumElements() > 1) {
3237 llvm::TypeSize StructSize
= CGM
.getDataLayout().getTypeAllocSize(STy
);
3238 llvm::TypeSize PtrElementSize
=
3239 CGM
.getDataLayout().getTypeAllocSize(Ptr
.getElementType());
3240 if (StructSize
.isScalable()) {
3241 assert(STy
->containsHomogeneousScalableVectorTypes() &&
3242 "ABI only supports structure with homogeneous scalable vector "
3244 assert(StructSize
== PtrElementSize
&&
3245 "Only allow non-fractional movement of structure with"
3246 "homogeneous scalable vector type");
3247 assert(STy
->getNumElements() == NumIRArgs
);
3249 llvm::Value
*LoadedStructValue
= llvm::PoisonValue::get(STy
);
3250 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
) {
3251 auto *AI
= Fn
->getArg(FirstIRArg
+ i
);
3252 AI
->setName(Arg
->getName() + ".coerce" + Twine(i
));
3254 Builder
.CreateInsertValue(LoadedStructValue
, AI
, i
);
3257 Builder
.CreateStore(LoadedStructValue
, Ptr
);
3259 uint64_t SrcSize
= StructSize
.getFixedValue();
3260 uint64_t DstSize
= PtrElementSize
.getFixedValue();
3262 Address AddrToStoreInto
= Address::invalid();
3263 if (SrcSize
<= DstSize
) {
3264 AddrToStoreInto
= Ptr
.withElementType(STy
);
3267 CreateTempAlloca(STy
, Alloca
.getAlignment(), "coerce");
3270 assert(STy
->getNumElements() == NumIRArgs
);
3271 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
) {
3272 auto AI
= Fn
->getArg(FirstIRArg
+ i
);
3273 AI
->setName(Arg
->getName() + ".coerce" + Twine(i
));
3274 Address EltPtr
= Builder
.CreateStructGEP(AddrToStoreInto
, i
);
3275 Builder
.CreateStore(AI
, EltPtr
);
3278 if (SrcSize
> DstSize
) {
3279 Builder
.CreateMemCpy(Ptr
, AddrToStoreInto
, DstSize
);
3283 // Simple case, just do a coerced store of the argument into the alloca.
3284 assert(NumIRArgs
== 1);
3285 auto AI
= Fn
->getArg(FirstIRArg
);
3286 AI
->setName(Arg
->getName() + ".coerce");
3289 llvm::TypeSize::getFixed(
3290 getContext().getTypeSizeInChars(Ty
).getQuantity() -
3291 ArgI
.getDirectOffset()),
3292 /*DstIsVolatile=*/false);
3295 // Match to what EmitParmDecl is expecting for this type.
3296 if (CodeGenFunction::hasScalarEvaluationKind(Ty
)) {
3298 EmitLoadOfScalar(Alloca
, false, Ty
, Arg
->getBeginLoc());
3300 V
= emitArgumentDemotion(*this, Arg
, V
);
3301 ArgVals
.push_back(ParamValue::forDirect(V
));
3303 ArgVals
.push_back(ParamValue::forIndirect(Alloca
));
3308 case ABIArgInfo::CoerceAndExpand
: {
3309 // Reconstruct into a temporary.
3310 Address alloca
= CreateMemTemp(Ty
, getContext().getDeclAlign(Arg
));
3311 ArgVals
.push_back(ParamValue::forIndirect(alloca
));
3313 auto coercionType
= ArgI
.getCoerceAndExpandType();
3314 alloca
= alloca
.withElementType(coercionType
);
3316 unsigned argIndex
= FirstIRArg
;
3317 for (unsigned i
= 0, e
= coercionType
->getNumElements(); i
!= e
; ++i
) {
3318 llvm::Type
*eltType
= coercionType
->getElementType(i
);
3319 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType
))
3322 auto eltAddr
= Builder
.CreateStructGEP(alloca
, i
);
3323 auto elt
= Fn
->getArg(argIndex
++);
3324 Builder
.CreateStore(elt
, eltAddr
);
3326 assert(argIndex
== FirstIRArg
+ NumIRArgs
);
3330 case ABIArgInfo::Expand
: {
3331 // If this structure was expanded into multiple arguments then
3332 // we need to create a temporary and reconstruct it from the
3334 Address Alloca
= CreateMemTemp(Ty
, getContext().getDeclAlign(Arg
));
3335 LValue LV
= MakeAddrLValue(Alloca
, Ty
);
3336 ArgVals
.push_back(ParamValue::forIndirect(Alloca
));
3338 auto FnArgIter
= Fn
->arg_begin() + FirstIRArg
;
3339 ExpandTypeFromArgs(Ty
, LV
, FnArgIter
);
3340 assert(FnArgIter
== Fn
->arg_begin() + FirstIRArg
+ NumIRArgs
);
3341 for (unsigned i
= 0, e
= NumIRArgs
; i
!= e
; ++i
) {
3342 auto AI
= Fn
->getArg(FirstIRArg
+ i
);
3343 AI
->setName(Arg
->getName() + "." + Twine(i
));
3348 case ABIArgInfo::Ignore
:
3349 assert(NumIRArgs
== 0);
3350 // Initialize the local variable appropriately.
3351 if (!hasScalarEvaluationKind(Ty
)) {
3352 ArgVals
.push_back(ParamValue::forIndirect(CreateMemTemp(Ty
)));
3354 llvm::Value
*U
= llvm::UndefValue::get(ConvertType(Arg
->getType()));
3355 ArgVals
.push_back(ParamValue::forDirect(U
));
3361 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3362 for (int I
= Args
.size() - 1; I
>= 0; --I
)
3363 EmitParmDecl(*Args
[I
], ArgVals
[I
], I
+ 1);
3365 for (unsigned I
= 0, E
= Args
.size(); I
!= E
; ++I
)
3366 EmitParmDecl(*Args
[I
], ArgVals
[I
], I
+ 1);
3370 static void eraseUnusedBitCasts(llvm::Instruction
*insn
) {
3371 while (insn
->use_empty()) {
3372 llvm::BitCastInst
*bitcast
= dyn_cast
<llvm::BitCastInst
>(insn
);
3373 if (!bitcast
) return;
3375 // This is "safe" because we would have used a ConstantExpr otherwise.
3376 insn
= cast
<llvm::Instruction
>(bitcast
->getOperand(0));
3377 bitcast
->eraseFromParent();
3381 /// Try to emit a fused autorelease of a return result.
3382 static llvm::Value
*tryEmitFusedAutoreleaseOfResult(CodeGenFunction
&CGF
,
3383 llvm::Value
*result
) {
3384 // We must be immediately followed the cast.
3385 llvm::BasicBlock
*BB
= CGF
.Builder
.GetInsertBlock();
3386 if (BB
->empty()) return nullptr;
3387 if (&BB
->back() != result
) return nullptr;
3389 llvm::Type
*resultType
= result
->getType();
3391 // result is in a BasicBlock and is therefore an Instruction.
3392 llvm::Instruction
*generator
= cast
<llvm::Instruction
>(result
);
3394 SmallVector
<llvm::Instruction
*, 4> InstsToKill
;
3397 // %generator = bitcast %type1* %generator2 to %type2*
3398 while (llvm::BitCastInst
*bitcast
= dyn_cast
<llvm::BitCastInst
>(generator
)) {
3399 // We would have emitted this as a constant if the operand weren't
3401 generator
= cast
<llvm::Instruction
>(bitcast
->getOperand(0));
3403 // Require the generator to be immediately followed by the cast.
3404 if (generator
->getNextNode() != bitcast
)
3407 InstsToKill
.push_back(bitcast
);
3411 // %generator = call i8* @objc_retain(i8* %originalResult)
3413 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3414 llvm::CallInst
*call
= dyn_cast
<llvm::CallInst
>(generator
);
3415 if (!call
) return nullptr;
3417 bool doRetainAutorelease
;
3419 if (call
->getCalledOperand() == CGF
.CGM
.getObjCEntrypoints().objc_retain
) {
3420 doRetainAutorelease
= true;
3421 } else if (call
->getCalledOperand() ==
3422 CGF
.CGM
.getObjCEntrypoints().objc_retainAutoreleasedReturnValue
) {
3423 doRetainAutorelease
= false;
3425 // If we emitted an assembly marker for this call (and the
3426 // ARCEntrypoints field should have been set if so), go looking
3427 // for that call. If we can't find it, we can't do this
3428 // optimization. But it should always be the immediately previous
3429 // instruction, unless we needed bitcasts around the call.
3430 if (CGF
.CGM
.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) {
3431 llvm::Instruction
*prev
= call
->getPrevNode();
3433 if (isa
<llvm::BitCastInst
>(prev
)) {
3434 prev
= prev
->getPrevNode();
3437 assert(isa
<llvm::CallInst
>(prev
));
3438 assert(cast
<llvm::CallInst
>(prev
)->getCalledOperand() ==
3439 CGF
.CGM
.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
);
3440 InstsToKill
.push_back(prev
);
3446 result
= call
->getArgOperand(0);
3447 InstsToKill
.push_back(call
);
3449 // Keep killing bitcasts, for sanity. Note that we no longer care
3450 // about precise ordering as long as there's exactly one use.
3451 while (llvm::BitCastInst
*bitcast
= dyn_cast
<llvm::BitCastInst
>(result
)) {
3452 if (!bitcast
->hasOneUse()) break;
3453 InstsToKill
.push_back(bitcast
);
3454 result
= bitcast
->getOperand(0);
3457 // Delete all the unnecessary instructions, from latest to earliest.
3458 for (auto *I
: InstsToKill
)
3459 I
->eraseFromParent();
3461 // Do the fused retain/autorelease if we were asked to.
3462 if (doRetainAutorelease
)
3463 result
= CGF
.EmitARCRetainAutoreleaseReturnValue(result
);
3465 // Cast back to the result type.
3466 return CGF
.Builder
.CreateBitCast(result
, resultType
);
3469 /// If this is a +1 of the value of an immutable 'self', remove it.
3470 static llvm::Value
*tryRemoveRetainOfSelf(CodeGenFunction
&CGF
,
3471 llvm::Value
*result
) {
3472 // This is only applicable to a method with an immutable 'self'.
3473 const ObjCMethodDecl
*method
=
3474 dyn_cast_or_null
<ObjCMethodDecl
>(CGF
.CurCodeDecl
);
3475 if (!method
) return nullptr;
3476 const VarDecl
*self
= method
->getSelfDecl();
3477 if (!self
->getType().isConstQualified()) return nullptr;
3479 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3480 // functions, which would cause us to miss the retain.
3481 llvm::CallInst
*retainCall
= dyn_cast
<llvm::CallInst
>(result
);
3482 if (!retainCall
|| retainCall
->getCalledOperand() !=
3483 CGF
.CGM
.getObjCEntrypoints().objc_retain
)
3486 // Look for an ordinary load of 'self'.
3487 llvm::Value
*retainedValue
= retainCall
->getArgOperand(0);
3488 llvm::LoadInst
*load
=
3489 dyn_cast
<llvm::LoadInst
>(retainedValue
->stripPointerCasts());
3490 if (!load
|| load
->isAtomic() || load
->isVolatile() ||
3491 load
->getPointerOperand() != CGF
.GetAddrOfLocalVar(self
).getBasePointer())
3494 // Okay! Burn it all down. This relies for correctness on the
3495 // assumption that the retain is emitted as part of the return and
3496 // that thereafter everything is used "linearly".
3497 llvm::Type
*resultType
= result
->getType();
3498 eraseUnusedBitCasts(cast
<llvm::Instruction
>(result
));
3499 assert(retainCall
->use_empty());
3500 retainCall
->eraseFromParent();
3501 eraseUnusedBitCasts(cast
<llvm::Instruction
>(retainedValue
));
3503 return CGF
.Builder
.CreateBitCast(load
, resultType
);
3506 /// Emit an ARC autorelease of the result of a function.
3508 /// \return the value to actually return from the function
3509 static llvm::Value
*emitAutoreleaseOfResult(CodeGenFunction
&CGF
,
3510 llvm::Value
*result
) {
3511 // If we're returning 'self', kill the initial retain. This is a
3512 // heuristic attempt to "encourage correctness" in the really unfortunate
3513 // case where we have a return of self during a dealloc and we desperately
3514 // need to avoid the possible autorelease.
3515 if (llvm::Value
*self
= tryRemoveRetainOfSelf(CGF
, result
))
3518 // At -O0, try to emit a fused retain/autorelease.
3519 if (CGF
.shouldUseFusedARCCalls())
3520 if (llvm::Value
*fused
= tryEmitFusedAutoreleaseOfResult(CGF
, result
))
3523 return CGF
.EmitARCAutoreleaseReturnValue(result
);
3526 /// Heuristically search for a dominating store to the return-value slot.
3527 static llvm::StoreInst
*findDominatingStoreToReturnValue(CodeGenFunction
&CGF
) {
3528 llvm::Value
*ReturnValuePtr
= CGF
.ReturnValue
.getBasePointer();
3530 // Check if a User is a store which pointerOperand is the ReturnValue.
3531 // We are looking for stores to the ReturnValue, not for stores of the
3532 // ReturnValue to some other location.
3533 auto GetStoreIfValid
= [&CGF
,
3534 ReturnValuePtr
](llvm::User
*U
) -> llvm::StoreInst
* {
3535 auto *SI
= dyn_cast
<llvm::StoreInst
>(U
);
3536 if (!SI
|| SI
->getPointerOperand() != ReturnValuePtr
||
3537 SI
->getValueOperand()->getType() != CGF
.ReturnValue
.getElementType())
3539 // These aren't actually possible for non-coerced returns, and we
3540 // only care about non-coerced returns on this code path.
3541 // All memory instructions inside __try block are volatile.
3542 assert(!SI
->isAtomic() &&
3543 (!SI
->isVolatile() || CGF
.currentFunctionUsesSEHTry()));
3546 // If there are multiple uses of the return-value slot, just check
3547 // for something immediately preceding the IP. Sometimes this can
3548 // happen with how we generate implicit-returns; it can also happen
3549 // with noreturn cleanups.
3550 if (!ReturnValuePtr
->hasOneUse()) {
3551 llvm::BasicBlock
*IP
= CGF
.Builder
.GetInsertBlock();
3552 if (IP
->empty()) return nullptr;
3554 // Look at directly preceding instruction, skipping bitcasts and lifetime
3556 for (llvm::Instruction
&I
: make_range(IP
->rbegin(), IP
->rend())) {
3557 if (isa
<llvm::BitCastInst
>(&I
))
3559 if (auto *II
= dyn_cast
<llvm::IntrinsicInst
>(&I
))
3560 if (II
->getIntrinsicID() == llvm::Intrinsic::lifetime_end
)
3563 return GetStoreIfValid(&I
);
3568 llvm::StoreInst
*store
= GetStoreIfValid(ReturnValuePtr
->user_back());
3569 if (!store
) return nullptr;
3571 // Now do a first-and-dirty dominance check: just walk up the
3572 // single-predecessors chain from the current insertion point.
3573 llvm::BasicBlock
*StoreBB
= store
->getParent();
3574 llvm::BasicBlock
*IP
= CGF
.Builder
.GetInsertBlock();
3575 llvm::SmallPtrSet
<llvm::BasicBlock
*, 4> SeenBBs
;
3576 while (IP
!= StoreBB
) {
3577 if (!SeenBBs
.insert(IP
).second
|| !(IP
= IP
->getSinglePredecessor()))
3581 // Okay, the store's basic block dominates the insertion point; we
3582 // can do our thing.
3586 // Helper functions for EmitCMSEClearRecord
3588 // Set the bits corresponding to a field having width `BitWidth` and located at
3589 // offset `BitOffset` (from the least significant bit) within a storage unit of
3590 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3591 // Use little-endian layout, i.e.`Bits[0]` is the LSB.
3592 static void setBitRange(SmallVectorImpl
<uint64_t> &Bits
, int BitOffset
,
3593 int BitWidth
, int CharWidth
) {
3594 assert(CharWidth
<= 64);
3595 assert(static_cast<unsigned>(BitWidth
) <= Bits
.size() * CharWidth
);
3598 if (BitOffset
>= CharWidth
) {
3599 Pos
+= BitOffset
/ CharWidth
;
3600 BitOffset
= BitOffset
% CharWidth
;
3603 const uint64_t Used
= (uint64_t(1) << CharWidth
) - 1;
3604 if (BitOffset
+ BitWidth
>= CharWidth
) {
3605 Bits
[Pos
++] |= (Used
<< BitOffset
) & Used
;
3606 BitWidth
-= CharWidth
- BitOffset
;
3610 while (BitWidth
>= CharWidth
) {
3612 BitWidth
-= CharWidth
;
3616 Bits
[Pos
++] |= (Used
>> (CharWidth
- BitWidth
)) << BitOffset
;
3619 // Set the bits corresponding to a field having width `BitWidth` and located at
3620 // offset `BitOffset` (from the least significant bit) within a storage unit of
3621 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3622 // `Bits` corresponds to one target byte. Use target endian layout.
3623 static void setBitRange(SmallVectorImpl
<uint64_t> &Bits
, int StorageOffset
,
3624 int StorageSize
, int BitOffset
, int BitWidth
,
3625 int CharWidth
, bool BigEndian
) {
3627 SmallVector
<uint64_t, 8> TmpBits(StorageSize
);
3628 setBitRange(TmpBits
, BitOffset
, BitWidth
, CharWidth
);
3631 std::reverse(TmpBits
.begin(), TmpBits
.end());
3633 for (uint64_t V
: TmpBits
)
3634 Bits
[StorageOffset
++] |= V
;
3637 static void setUsedBits(CodeGenModule
&, QualType
, int,
3638 SmallVectorImpl
<uint64_t> &);
3640 // Set the bits in `Bits`, which correspond to the value representations of
3641 // the actual members of the record type `RTy`. Note that this function does
3642 // not handle base classes, virtual tables, etc, since they cannot happen in
3643 // CMSE function arguments or return. The bit mask corresponds to the target
3644 // memory layout, i.e. it's endian dependent.
3645 static void setUsedBits(CodeGenModule
&CGM
, const RecordType
*RTy
, int Offset
,
3646 SmallVectorImpl
<uint64_t> &Bits
) {
3647 ASTContext
&Context
= CGM
.getContext();
3648 int CharWidth
= Context
.getCharWidth();
3649 const RecordDecl
*RD
= RTy
->getDecl()->getDefinition();
3650 const ASTRecordLayout
&ASTLayout
= Context
.getASTRecordLayout(RD
);
3651 const CGRecordLayout
&Layout
= CGM
.getTypes().getCGRecordLayout(RD
);
3654 for (auto I
= RD
->field_begin(), E
= RD
->field_end(); I
!= E
; ++I
, ++Idx
) {
3655 const FieldDecl
*F
= *I
;
3657 if (F
->isUnnamedBitField() || F
->isZeroLengthBitField(Context
) ||
3658 F
->getType()->isIncompleteArrayType())
3661 if (F
->isBitField()) {
3662 const CGBitFieldInfo
&BFI
= Layout
.getBitFieldInfo(F
);
3663 setBitRange(Bits
, Offset
+ BFI
.StorageOffset
.getQuantity(),
3664 BFI
.StorageSize
/ CharWidth
, BFI
.Offset
,
3665 BFI
.Size
, CharWidth
,
3666 CGM
.getDataLayout().isBigEndian());
3670 setUsedBits(CGM
, F
->getType(),
3671 Offset
+ ASTLayout
.getFieldOffset(Idx
) / CharWidth
, Bits
);
3675 // Set the bits in `Bits`, which correspond to the value representations of
3676 // the elements of an array type `ATy`.
3677 static void setUsedBits(CodeGenModule
&CGM
, const ConstantArrayType
*ATy
,
3678 int Offset
, SmallVectorImpl
<uint64_t> &Bits
) {
3679 const ASTContext
&Context
= CGM
.getContext();
3681 QualType ETy
= Context
.getBaseElementType(ATy
);
3682 int Size
= Context
.getTypeSizeInChars(ETy
).getQuantity();
3683 SmallVector
<uint64_t, 4> TmpBits(Size
);
3684 setUsedBits(CGM
, ETy
, 0, TmpBits
);
3686 for (int I
= 0, N
= Context
.getConstantArrayElementCount(ATy
); I
< N
; ++I
) {
3687 auto Src
= TmpBits
.begin();
3688 auto Dst
= Bits
.begin() + Offset
+ I
* Size
;
3689 for (int J
= 0; J
< Size
; ++J
)
3694 // Set the bits in `Bits`, which correspond to the value representations of
3696 static void setUsedBits(CodeGenModule
&CGM
, QualType QTy
, int Offset
,
3697 SmallVectorImpl
<uint64_t> &Bits
) {
3698 if (const auto *RTy
= QTy
->getAs
<RecordType
>())
3699 return setUsedBits(CGM
, RTy
, Offset
, Bits
);
3701 ASTContext
&Context
= CGM
.getContext();
3702 if (const auto *ATy
= Context
.getAsConstantArrayType(QTy
))
3703 return setUsedBits(CGM
, ATy
, Offset
, Bits
);
3705 int Size
= Context
.getTypeSizeInChars(QTy
).getQuantity();
3709 std::fill_n(Bits
.begin() + Offset
, Size
,
3710 (uint64_t(1) << Context
.getCharWidth()) - 1);
3713 static uint64_t buildMultiCharMask(const SmallVectorImpl
<uint64_t> &Bits
,
3714 int Pos
, int Size
, int CharWidth
,
3719 for (auto P
= Bits
.begin() + Pos
, E
= Bits
.begin() + Pos
+ Size
; P
!= E
;
3721 Mask
= (Mask
<< CharWidth
) | *P
;
3723 auto P
= Bits
.begin() + Pos
+ Size
, End
= Bits
.begin() + Pos
;
3725 Mask
= (Mask
<< CharWidth
) | *--P
;
3731 // Emit code to clear the bits in a record, which aren't a part of any user
3732 // declared member, when the record is a function return.
3733 llvm::Value
*CodeGenFunction::EmitCMSEClearRecord(llvm::Value
*Src
,
3734 llvm::IntegerType
*ITy
,
3736 assert(Src
->getType() == ITy
);
3737 assert(ITy
->getScalarSizeInBits() <= 64);
3739 const llvm::DataLayout
&DataLayout
= CGM
.getDataLayout();
3740 int Size
= DataLayout
.getTypeStoreSize(ITy
);
3741 SmallVector
<uint64_t, 4> Bits(Size
);
3742 setUsedBits(CGM
, QTy
->castAs
<RecordType
>(), 0, Bits
);
3744 int CharWidth
= CGM
.getContext().getCharWidth();
3746 buildMultiCharMask(Bits
, 0, Size
, CharWidth
, DataLayout
.isBigEndian());
3748 return Builder
.CreateAnd(Src
, Mask
, "cmse.clear");
3751 // Emit code to clear the bits in a record, which aren't a part of any user
3752 // declared member, when the record is a function argument.
3753 llvm::Value
*CodeGenFunction::EmitCMSEClearRecord(llvm::Value
*Src
,
3754 llvm::ArrayType
*ATy
,
3756 const llvm::DataLayout
&DataLayout
= CGM
.getDataLayout();
3757 int Size
= DataLayout
.getTypeStoreSize(ATy
);
3758 SmallVector
<uint64_t, 16> Bits(Size
);
3759 setUsedBits(CGM
, QTy
->castAs
<RecordType
>(), 0, Bits
);
3761 // Clear each element of the LLVM array.
3762 int CharWidth
= CGM
.getContext().getCharWidth();
3764 ATy
->getArrayElementType()->getScalarSizeInBits() / CharWidth
;
3766 llvm::Value
*R
= llvm::PoisonValue::get(ATy
);
3767 for (int I
= 0, N
= ATy
->getArrayNumElements(); I
!= N
; ++I
) {
3768 uint64_t Mask
= buildMultiCharMask(Bits
, MaskIndex
, CharsPerElt
, CharWidth
,
3769 DataLayout
.isBigEndian());
3770 MaskIndex
+= CharsPerElt
;
3771 llvm::Value
*T0
= Builder
.CreateExtractValue(Src
, I
);
3772 llvm::Value
*T1
= Builder
.CreateAnd(T0
, Mask
, "cmse.clear");
3773 R
= Builder
.CreateInsertValue(R
, T1
, I
);
3779 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo
&FI
,
3781 SourceLocation EndLoc
) {
3782 if (FI
.isNoReturn()) {
3783 // Noreturn functions don't return.
3784 EmitUnreachable(EndLoc
);
3788 if (CurCodeDecl
&& CurCodeDecl
->hasAttr
<NakedAttr
>()) {
3789 // Naked functions don't have epilogues.
3790 Builder
.CreateUnreachable();
3794 // Functions with no result always return void.
3795 if (!ReturnValue
.isValid()) {
3796 Builder
.CreateRetVoid();
3800 llvm::DebugLoc RetDbgLoc
;
3801 llvm::Value
*RV
= nullptr;
3802 QualType RetTy
= FI
.getReturnType();
3803 const ABIArgInfo
&RetAI
= FI
.getReturnInfo();
3805 switch (RetAI
.getKind()) {
3806 case ABIArgInfo::InAlloca
:
3807 // Aggregates get evaluated directly into the destination. Sometimes we
3808 // need to return the sret value in a register, though.
3809 assert(hasAggregateEvaluationKind(RetTy
));
3810 if (RetAI
.getInAllocaSRet()) {
3811 llvm::Function::arg_iterator EI
= CurFn
->arg_end();
3813 llvm::Value
*ArgStruct
= &*EI
;
3814 llvm::Value
*SRet
= Builder
.CreateStructGEP(
3815 FI
.getArgStruct(), ArgStruct
, RetAI
.getInAllocaFieldIndex());
3817 cast
<llvm::GetElementPtrInst
>(SRet
)->getResultElementType();
3818 RV
= Builder
.CreateAlignedLoad(Ty
, SRet
, getPointerAlign(), "sret");
3822 case ABIArgInfo::Indirect
: {
3823 auto AI
= CurFn
->arg_begin();
3824 if (RetAI
.isSRetAfterThis())
3826 switch (getEvaluationKind(RetTy
)) {
3829 EmitLoadOfComplex(MakeAddrLValue(ReturnValue
, RetTy
), EndLoc
);
3830 EmitStoreOfComplex(RT
, MakeNaturalAlignAddrLValue(&*AI
, RetTy
),
3835 // Do nothing; aggregates get evaluated directly into the destination.
3838 LValueBaseInfo BaseInfo
;
3839 TBAAAccessInfo TBAAInfo
;
3840 CharUnits Alignment
=
3841 CGM
.getNaturalTypeAlignment(RetTy
, &BaseInfo
, &TBAAInfo
);
3842 Address
ArgAddr(&*AI
, ConvertType(RetTy
), Alignment
);
3844 LValue::MakeAddr(ArgAddr
, RetTy
, getContext(), BaseInfo
, TBAAInfo
);
3846 EmitLoadOfScalar(MakeAddrLValue(ReturnValue
, RetTy
), EndLoc
), ArgVal
,
3854 case ABIArgInfo::Extend
:
3855 case ABIArgInfo::Direct
:
3856 if (RetAI
.getCoerceToType() == ConvertType(RetTy
) &&
3857 RetAI
.getDirectOffset() == 0) {
3858 // The internal return value temp always will have pointer-to-return-type
3859 // type, just do a load.
3861 // If there is a dominating store to ReturnValue, we can elide
3862 // the load, zap the store, and usually zap the alloca.
3863 if (llvm::StoreInst
*SI
=
3864 findDominatingStoreToReturnValue(*this)) {
3865 // Reuse the debug location from the store unless there is
3866 // cleanup code to be emitted between the store and return
3868 if (EmitRetDbgLoc
&& !AutoreleaseResult
)
3869 RetDbgLoc
= SI
->getDebugLoc();
3870 // Get the stored value and nuke the now-dead store.
3871 RV
= SI
->getValueOperand();
3872 SI
->eraseFromParent();
3874 // Otherwise, we have to do a simple load.
3876 RV
= Builder
.CreateLoad(ReturnValue
);
3879 // If the value is offset in memory, apply the offset now.
3880 Address V
= emitAddressAtOffset(*this, ReturnValue
, RetAI
);
3882 RV
= CreateCoercedLoad(V
, RetAI
.getCoerceToType(), *this);
3885 // In ARC, end functions that return a retainable type with a call
3886 // to objc_autoreleaseReturnValue.
3887 if (AutoreleaseResult
) {
3889 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3890 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3891 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3892 // CurCodeDecl or BlockInfo.
3895 if (auto *FD
= dyn_cast
<FunctionDecl
>(CurCodeDecl
))
3896 RT
= FD
->getReturnType();
3897 else if (auto *MD
= dyn_cast
<ObjCMethodDecl
>(CurCodeDecl
))
3898 RT
= MD
->getReturnType();
3899 else if (isa
<BlockDecl
>(CurCodeDecl
))
3900 RT
= BlockInfo
->BlockExpression
->getFunctionType()->getReturnType();
3902 llvm_unreachable("Unexpected function/method type");
3904 assert(getLangOpts().ObjCAutoRefCount
&&
3905 !FI
.isReturnsRetained() &&
3906 RT
->isObjCRetainableType());
3908 RV
= emitAutoreleaseOfResult(*this, RV
);
3913 case ABIArgInfo::Ignore
:
3916 case ABIArgInfo::CoerceAndExpand
: {
3917 auto coercionType
= RetAI
.getCoerceAndExpandType();
3919 // Load all of the coerced elements out into results.
3920 llvm::SmallVector
<llvm::Value
*, 4> results
;
3921 Address addr
= ReturnValue
.withElementType(coercionType
);
3922 for (unsigned i
= 0, e
= coercionType
->getNumElements(); i
!= e
; ++i
) {
3923 auto coercedEltType
= coercionType
->getElementType(i
);
3924 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType
))
3927 auto eltAddr
= Builder
.CreateStructGEP(addr
, i
);
3928 auto elt
= Builder
.CreateLoad(eltAddr
);
3929 results
.push_back(elt
);
3932 // If we have one result, it's the single direct result type.
3933 if (results
.size() == 1) {
3936 // Otherwise, we need to make a first-class aggregate.
3938 // Construct a return type that lacks padding elements.
3939 llvm::Type
*returnType
= RetAI
.getUnpaddedCoerceAndExpandType();
3941 RV
= llvm::PoisonValue::get(returnType
);
3942 for (unsigned i
= 0, e
= results
.size(); i
!= e
; ++i
) {
3943 RV
= Builder
.CreateInsertValue(RV
, results
[i
], i
);
3948 case ABIArgInfo::Expand
:
3949 case ABIArgInfo::IndirectAliased
:
3950 llvm_unreachable("Invalid ABI kind for return argument");
3953 llvm::Instruction
*Ret
;
3955 if (CurFuncDecl
&& CurFuncDecl
->hasAttr
<CmseNSEntryAttr
>()) {
3956 // For certain return types, clear padding bits, as they may reveal
3957 // sensitive information.
3958 // Small struct/union types are passed as integers.
3959 auto *ITy
= dyn_cast
<llvm::IntegerType
>(RV
->getType());
3960 if (ITy
!= nullptr && isa
<RecordType
>(RetTy
.getCanonicalType()))
3961 RV
= EmitCMSEClearRecord(RV
, ITy
, RetTy
);
3963 EmitReturnValueCheck(RV
);
3964 Ret
= Builder
.CreateRet(RV
);
3966 Ret
= Builder
.CreateRetVoid();
3970 Ret
->setDebugLoc(std::move(RetDbgLoc
));
3973 void CodeGenFunction::EmitReturnValueCheck(llvm::Value
*RV
) {
3974 // A current decl may not be available when emitting vtable thunks.
3978 // If the return block isn't reachable, neither is this check, so don't emit
3980 if (ReturnBlock
.isValid() && ReturnBlock
.getBlock()->use_empty())
3983 ReturnsNonNullAttr
*RetNNAttr
= nullptr;
3984 if (SanOpts
.has(SanitizerKind::ReturnsNonnullAttribute
))
3985 RetNNAttr
= CurCodeDecl
->getAttr
<ReturnsNonNullAttr
>();
3987 if (!RetNNAttr
&& !requiresReturnValueNullabilityCheck())
3990 // Prefer the returns_nonnull attribute if it's present.
3991 SourceLocation AttrLoc
;
3992 SanitizerMask CheckKind
;
3993 SanitizerHandler Handler
;
3995 assert(!requiresReturnValueNullabilityCheck() &&
3996 "Cannot check nullability and the nonnull attribute");
3997 AttrLoc
= RetNNAttr
->getLocation();
3998 CheckKind
= SanitizerKind::ReturnsNonnullAttribute
;
3999 Handler
= SanitizerHandler::NonnullReturn
;
4001 if (auto *DD
= dyn_cast
<DeclaratorDecl
>(CurCodeDecl
))
4002 if (auto *TSI
= DD
->getTypeSourceInfo())
4003 if (auto FTL
= TSI
->getTypeLoc().getAsAdjusted
<FunctionTypeLoc
>())
4004 AttrLoc
= FTL
.getReturnLoc().findNullabilityLoc();
4005 CheckKind
= SanitizerKind::NullabilityReturn
;
4006 Handler
= SanitizerHandler::NullabilityReturn
;
4009 SanitizerScope
SanScope(this);
4011 // Make sure the "return" source location is valid. If we're checking a
4012 // nullability annotation, make sure the preconditions for the check are met.
4013 llvm::BasicBlock
*Check
= createBasicBlock("nullcheck");
4014 llvm::BasicBlock
*NoCheck
= createBasicBlock("no.nullcheck");
4015 llvm::Value
*SLocPtr
= Builder
.CreateLoad(ReturnLocation
, "return.sloc.load");
4016 llvm::Value
*CanNullCheck
= Builder
.CreateIsNotNull(SLocPtr
);
4017 if (requiresReturnValueNullabilityCheck())
4019 Builder
.CreateAnd(CanNullCheck
, RetValNullabilityPrecondition
);
4020 Builder
.CreateCondBr(CanNullCheck
, Check
, NoCheck
);
4023 // Now do the null check.
4024 llvm::Value
*Cond
= Builder
.CreateIsNotNull(RV
);
4025 llvm::Constant
*StaticData
[] = {EmitCheckSourceLocation(AttrLoc
)};
4026 llvm::Value
*DynamicData
[] = {SLocPtr
};
4027 EmitCheck(std::make_pair(Cond
, CheckKind
), Handler
, StaticData
, DynamicData
);
4032 // The return location should not be used after the check has been emitted.
4033 ReturnLocation
= Address::invalid();
4037 static bool isInAllocaArgument(CGCXXABI
&ABI
, QualType type
) {
4038 const CXXRecordDecl
*RD
= type
->getAsCXXRecordDecl();
4039 return RD
&& ABI
.getRecordArgABI(RD
) == CGCXXABI::RAA_DirectInMemory
;
4042 static AggValueSlot
createPlaceholderSlot(CodeGenFunction
&CGF
,
4044 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4046 llvm::Type
*IRTy
= CGF
.ConvertTypeForMem(Ty
);
4047 llvm::Type
*IRPtrTy
= llvm::PointerType::getUnqual(CGF
.getLLVMContext());
4048 llvm::Value
*Placeholder
= llvm::PoisonValue::get(IRPtrTy
);
4050 // FIXME: When we generate this IR in one pass, we shouldn't need
4051 // this win32-specific alignment hack.
4052 CharUnits Align
= CharUnits::fromQuantity(4);
4053 Placeholder
= CGF
.Builder
.CreateAlignedLoad(IRPtrTy
, Placeholder
, Align
);
4055 return AggValueSlot::forAddr(Address(Placeholder
, IRTy
, Align
),
4057 AggValueSlot::IsNotDestructed
,
4058 AggValueSlot::DoesNotNeedGCBarriers
,
4059 AggValueSlot::IsNotAliased
,
4060 AggValueSlot::DoesNotOverlap
);
4063 void CodeGenFunction::EmitDelegateCallArg(CallArgList
&args
,
4064 const VarDecl
*param
,
4065 SourceLocation loc
) {
4066 // StartFunction converted the ABI-lowered parameter(s) into a
4067 // local alloca. We need to turn that into an r-value suitable
4069 Address local
= GetAddrOfLocalVar(param
);
4071 QualType type
= param
->getType();
4073 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4074 // but the argument needs to be the original pointer.
4075 if (type
->isReferenceType()) {
4076 args
.add(RValue::get(Builder
.CreateLoad(local
)), type
);
4078 // In ARC, move out of consumed arguments so that the release cleanup
4079 // entered by StartFunction doesn't cause an over-release. This isn't
4080 // optimal -O0 code generation, but it should get cleaned up when
4081 // optimization is enabled. This also assumes that delegate calls are
4082 // performed exactly once for a set of arguments, but that should be safe.
4083 } else if (getLangOpts().ObjCAutoRefCount
&&
4084 param
->hasAttr
<NSConsumedAttr
>() &&
4085 type
->isObjCRetainableType()) {
4086 llvm::Value
*ptr
= Builder
.CreateLoad(local
);
4088 llvm::ConstantPointerNull::get(cast
<llvm::PointerType
>(ptr
->getType()));
4089 Builder
.CreateStore(null
, local
);
4090 args
.add(RValue::get(ptr
), type
);
4092 // For the most part, we just need to load the alloca, except that
4093 // aggregate r-values are actually pointers to temporaries.
4095 args
.add(convertTempToRValue(local
, type
, loc
), type
);
4098 // Deactivate the cleanup for the callee-destructed param that was pushed.
4099 if (type
->isRecordType() && !CurFuncIsThunk
&&
4100 type
->castAs
<RecordType
>()->getDecl()->isParamDestroyedInCallee() &&
4101 param
->needsDestruction(getContext())) {
4102 EHScopeStack::stable_iterator cleanup
=
4103 CalleeDestructedParamCleanups
.lookup(cast
<ParmVarDecl
>(param
));
4104 assert(cleanup
.isValid() &&
4105 "cleanup for callee-destructed param not recorded");
4106 // This unreachable is a temporary marker which will be removed later.
4107 llvm::Instruction
*isActive
= Builder
.CreateUnreachable();
4108 args
.addArgCleanupDeactivation(cleanup
, isActive
);
4112 static bool isProvablyNull(llvm::Value
*addr
) {
4113 return llvm::isa_and_nonnull
<llvm::ConstantPointerNull
>(addr
);
4116 static bool isProvablyNonNull(Address Addr
, CodeGenFunction
&CGF
) {
4117 return llvm::isKnownNonZero(Addr
.getBasePointer(), CGF
.CGM
.getDataLayout());
4120 /// Emit the actual writing-back of a writeback.
4121 static void emitWriteback(CodeGenFunction
&CGF
,
4122 const CallArgList::Writeback
&writeback
) {
4123 const LValue
&srcLV
= writeback
.Source
;
4124 Address srcAddr
= srcLV
.getAddress();
4125 assert(!isProvablyNull(srcAddr
.getBasePointer()) &&
4126 "shouldn't have writeback for provably null argument");
4128 llvm::BasicBlock
*contBB
= nullptr;
4130 // If the argument wasn't provably non-null, we need to null check
4131 // before doing the store.
4132 bool provablyNonNull
= isProvablyNonNull(srcAddr
, CGF
);
4134 if (!provablyNonNull
) {
4135 llvm::BasicBlock
*writebackBB
= CGF
.createBasicBlock("icr.writeback");
4136 contBB
= CGF
.createBasicBlock("icr.done");
4138 llvm::Value
*isNull
= CGF
.Builder
.CreateIsNull(srcAddr
, "icr.isnull");
4139 CGF
.Builder
.CreateCondBr(isNull
, contBB
, writebackBB
);
4140 CGF
.EmitBlock(writebackBB
);
4143 // Load the value to writeback.
4144 llvm::Value
*value
= CGF
.Builder
.CreateLoad(writeback
.Temporary
);
4146 // Cast it back, in case we're writing an id to a Foo* or something.
4147 value
= CGF
.Builder
.CreateBitCast(value
, srcAddr
.getElementType(),
4148 "icr.writeback-cast");
4150 // Perform the writeback.
4152 // If we have a "to use" value, it's something we need to emit a use
4153 // of. This has to be carefully threaded in: if it's done after the
4154 // release it's potentially undefined behavior (and the optimizer
4155 // will ignore it), and if it happens before the retain then the
4156 // optimizer could move the release there.
4157 if (writeback
.ToUse
) {
4158 assert(srcLV
.getObjCLifetime() == Qualifiers::OCL_Strong
);
4160 // Retain the new value. No need to block-copy here: the block's
4161 // being passed up the stack.
4162 value
= CGF
.EmitARCRetainNonBlock(value
);
4164 // Emit the intrinsic use here.
4165 CGF
.EmitARCIntrinsicUse(writeback
.ToUse
);
4167 // Load the old value (primitively).
4168 llvm::Value
*oldValue
= CGF
.EmitLoadOfScalar(srcLV
, SourceLocation());
4170 // Put the new value in place (primitively).
4171 CGF
.EmitStoreOfScalar(value
, srcLV
, /*init*/ false);
4173 // Release the old value.
4174 CGF
.EmitARCRelease(oldValue
, srcLV
.isARCPreciseLifetime());
4176 // Otherwise, we can just do a normal lvalue store.
4178 CGF
.EmitStoreThroughLValue(RValue::get(value
), srcLV
);
4181 // Jump to the continuation block.
4182 if (!provablyNonNull
)
4183 CGF
.EmitBlock(contBB
);
4186 static void emitWritebacks(CodeGenFunction
&CGF
,
4187 const CallArgList
&args
) {
4188 for (const auto &I
: args
.writebacks())
4189 emitWriteback(CGF
, I
);
4192 static void deactivateArgCleanupsBeforeCall(CodeGenFunction
&CGF
,
4193 const CallArgList
&CallArgs
) {
4194 ArrayRef
<CallArgList::CallArgCleanup
> Cleanups
=
4195 CallArgs
.getCleanupsToDeactivate();
4196 // Iterate in reverse to increase the likelihood of popping the cleanup.
4197 for (const auto &I
: llvm::reverse(Cleanups
)) {
4198 CGF
.DeactivateCleanupBlock(I
.Cleanup
, I
.IsActiveIP
);
4199 I
.IsActiveIP
->eraseFromParent();
4203 static const Expr
*maybeGetUnaryAddrOfOperand(const Expr
*E
) {
4204 if (const UnaryOperator
*uop
= dyn_cast
<UnaryOperator
>(E
->IgnoreParens()))
4205 if (uop
->getOpcode() == UO_AddrOf
)
4206 return uop
->getSubExpr();
4210 /// Emit an argument that's being passed call-by-writeback. That is,
4211 /// we are passing the address of an __autoreleased temporary; it
4212 /// might be copy-initialized with the current value of the given
4213 /// address, but it will definitely be copied out of after the call.
4214 static void emitWritebackArg(CodeGenFunction
&CGF
, CallArgList
&args
,
4215 const ObjCIndirectCopyRestoreExpr
*CRE
) {
4218 // Make an optimistic effort to emit the address as an l-value.
4219 // This can fail if the argument expression is more complicated.
4220 if (const Expr
*lvExpr
= maybeGetUnaryAddrOfOperand(CRE
->getSubExpr())) {
4221 srcLV
= CGF
.EmitLValue(lvExpr
);
4223 // Otherwise, just emit it as a scalar.
4225 Address srcAddr
= CGF
.EmitPointerWithAlignment(CRE
->getSubExpr());
4227 QualType srcAddrType
=
4228 CRE
->getSubExpr()->getType()->castAs
<PointerType
>()->getPointeeType();
4229 srcLV
= CGF
.MakeAddrLValue(srcAddr
, srcAddrType
);
4231 Address srcAddr
= srcLV
.getAddress();
4233 // The dest and src types don't necessarily match in LLVM terms
4234 // because of the crazy ObjC compatibility rules.
4236 llvm::PointerType
*destType
=
4237 cast
<llvm::PointerType
>(CGF
.ConvertType(CRE
->getType()));
4238 llvm::Type
*destElemType
=
4239 CGF
.ConvertTypeForMem(CRE
->getType()->getPointeeType());
4241 // If the address is a constant null, just pass the appropriate null.
4242 if (isProvablyNull(srcAddr
.getBasePointer())) {
4243 args
.add(RValue::get(llvm::ConstantPointerNull::get(destType
)),
4248 // Create the temporary.
4250 CGF
.CreateTempAlloca(destElemType
, CGF
.getPointerAlign(), "icr.temp");
4251 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4252 // and that cleanup will be conditional if we can't prove that the l-value
4253 // isn't null, so we need to register a dominating point so that the cleanups
4254 // system will make valid IR.
4255 CodeGenFunction::ConditionalEvaluation
condEval(CGF
);
4257 // Zero-initialize it if we're not doing a copy-initialization.
4258 bool shouldCopy
= CRE
->shouldCopy();
4261 llvm::ConstantPointerNull::get(cast
<llvm::PointerType
>(destElemType
));
4262 CGF
.Builder
.CreateStore(null
, temp
);
4265 llvm::BasicBlock
*contBB
= nullptr;
4266 llvm::BasicBlock
*originBB
= nullptr;
4268 // If the address is *not* known to be non-null, we need to switch.
4269 llvm::Value
*finalArgument
;
4271 bool provablyNonNull
= isProvablyNonNull(srcAddr
, CGF
);
4273 if (provablyNonNull
) {
4274 finalArgument
= temp
.emitRawPointer(CGF
);
4276 llvm::Value
*isNull
= CGF
.Builder
.CreateIsNull(srcAddr
, "icr.isnull");
4278 finalArgument
= CGF
.Builder
.CreateSelect(
4279 isNull
, llvm::ConstantPointerNull::get(destType
),
4280 temp
.emitRawPointer(CGF
), "icr.argument");
4282 // If we need to copy, then the load has to be conditional, which
4283 // means we need control flow.
4285 originBB
= CGF
.Builder
.GetInsertBlock();
4286 contBB
= CGF
.createBasicBlock("icr.cont");
4287 llvm::BasicBlock
*copyBB
= CGF
.createBasicBlock("icr.copy");
4288 CGF
.Builder
.CreateCondBr(isNull
, contBB
, copyBB
);
4289 CGF
.EmitBlock(copyBB
);
4290 condEval
.begin(CGF
);
4294 llvm::Value
*valueToUse
= nullptr;
4296 // Perform a copy if necessary.
4298 RValue srcRV
= CGF
.EmitLoadOfLValue(srcLV
, SourceLocation());
4299 assert(srcRV
.isScalar());
4301 llvm::Value
*src
= srcRV
.getScalarVal();
4302 src
= CGF
.Builder
.CreateBitCast(src
, destElemType
, "icr.cast");
4304 // Use an ordinary store, not a store-to-lvalue.
4305 CGF
.Builder
.CreateStore(src
, temp
);
4307 // If optimization is enabled, and the value was held in a
4308 // __strong variable, we need to tell the optimizer that this
4309 // value has to stay alive until we're doing the store back.
4310 // This is because the temporary is effectively unretained,
4311 // and so otherwise we can violate the high-level semantics.
4312 if (CGF
.CGM
.getCodeGenOpts().OptimizationLevel
!= 0 &&
4313 srcLV
.getObjCLifetime() == Qualifiers::OCL_Strong
) {
4318 // Finish the control flow if we needed it.
4319 if (shouldCopy
&& !provablyNonNull
) {
4320 llvm::BasicBlock
*copyBB
= CGF
.Builder
.GetInsertBlock();
4321 CGF
.EmitBlock(contBB
);
4323 // Make a phi for the value to intrinsically use.
4325 llvm::PHINode
*phiToUse
= CGF
.Builder
.CreatePHI(valueToUse
->getType(), 2,
4327 phiToUse
->addIncoming(valueToUse
, copyBB
);
4328 phiToUse
->addIncoming(llvm::UndefValue::get(valueToUse
->getType()),
4330 valueToUse
= phiToUse
;
4336 args
.addWriteback(srcLV
, temp
, valueToUse
);
4337 args
.add(RValue::get(finalArgument
), CRE
->getType());
4340 void CallArgList::allocateArgumentMemory(CodeGenFunction
&CGF
) {
4344 StackBase
= CGF
.Builder
.CreateStackSave("inalloca.save");
4347 void CallArgList::freeArgumentMemory(CodeGenFunction
&CGF
) const {
4349 // Restore the stack after the call.
4350 CGF
.Builder
.CreateStackRestore(StackBase
);
4354 void CodeGenFunction::EmitNonNullArgCheck(RValue RV
, QualType ArgType
,
4355 SourceLocation ArgLoc
,
4358 if (!AC
.getDecl() || !(SanOpts
.has(SanitizerKind::NonnullAttribute
) ||
4359 SanOpts
.has(SanitizerKind::NullabilityArg
)))
4362 // The param decl may be missing in a variadic function.
4363 auto PVD
= ParmNum
< AC
.getNumParams() ? AC
.getParamDecl(ParmNum
) : nullptr;
4364 unsigned ArgNo
= PVD
? PVD
->getFunctionScopeIndex() : ParmNum
;
4366 // Prefer the nonnull attribute if it's present.
4367 const NonNullAttr
*NNAttr
= nullptr;
4368 if (SanOpts
.has(SanitizerKind::NonnullAttribute
))
4369 NNAttr
= getNonNullAttr(AC
.getDecl(), PVD
, ArgType
, ArgNo
);
4371 bool CanCheckNullability
= false;
4372 if (SanOpts
.has(SanitizerKind::NullabilityArg
) && !NNAttr
&& PVD
&&
4373 !PVD
->getType()->isRecordType()) {
4374 auto Nullability
= PVD
->getType()->getNullability();
4375 CanCheckNullability
= Nullability
&&
4376 *Nullability
== NullabilityKind::NonNull
&&
4377 PVD
->getTypeSourceInfo();
4380 if (!NNAttr
&& !CanCheckNullability
)
4383 SourceLocation AttrLoc
;
4384 SanitizerMask CheckKind
;
4385 SanitizerHandler Handler
;
4387 AttrLoc
= NNAttr
->getLocation();
4388 CheckKind
= SanitizerKind::NonnullAttribute
;
4389 Handler
= SanitizerHandler::NonnullArg
;
4391 AttrLoc
= PVD
->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4392 CheckKind
= SanitizerKind::NullabilityArg
;
4393 Handler
= SanitizerHandler::NullabilityArg
;
4396 SanitizerScope
SanScope(this);
4397 llvm::Value
*Cond
= EmitNonNullRValueCheck(RV
, ArgType
);
4398 llvm::Constant
*StaticData
[] = {
4399 EmitCheckSourceLocation(ArgLoc
), EmitCheckSourceLocation(AttrLoc
),
4400 llvm::ConstantInt::get(Int32Ty
, ArgNo
+ 1),
4402 EmitCheck(std::make_pair(Cond
, CheckKind
), Handler
, StaticData
, std::nullopt
);
4405 void CodeGenFunction::EmitNonNullArgCheck(Address Addr
, QualType ArgType
,
4406 SourceLocation ArgLoc
,
4407 AbstractCallee AC
, unsigned ParmNum
) {
4408 if (!AC
.getDecl() || !(SanOpts
.has(SanitizerKind::NonnullAttribute
) ||
4409 SanOpts
.has(SanitizerKind::NullabilityArg
)))
4412 EmitNonNullArgCheck(RValue::get(Addr
, *this), ArgType
, ArgLoc
, AC
, ParmNum
);
4415 // Check if the call is going to use the inalloca convention. This needs to
4416 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4417 // later, so we can't check it directly.
4418 static bool hasInAllocaArgs(CodeGenModule
&CGM
, CallingConv ExplicitCC
,
4419 ArrayRef
<QualType
> ArgTypes
) {
4420 // The Swift calling conventions don't go through the target-specific
4421 // argument classification, they never use inalloca.
4422 // TODO: Consider limiting inalloca use to only calling conventions supported
4424 if (ExplicitCC
== CC_Swift
|| ExplicitCC
== CC_SwiftAsync
)
4426 if (!CGM
.getTarget().getCXXABI().isMicrosoft())
4428 return llvm::any_of(ArgTypes
, [&](QualType Ty
) {
4429 return isInAllocaArgument(CGM
.getCXXABI(), Ty
);
4434 // Determine whether the given argument is an Objective-C method
4435 // that may have type parameters in its signature.
4436 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl
*method
) {
4437 const DeclContext
*dc
= method
->getDeclContext();
4438 if (const ObjCInterfaceDecl
*classDecl
= dyn_cast
<ObjCInterfaceDecl
>(dc
)) {
4439 return classDecl
->getTypeParamListAsWritten();
4442 if (const ObjCCategoryDecl
*catDecl
= dyn_cast
<ObjCCategoryDecl
>(dc
)) {
4443 return catDecl
->getTypeParamList();
4450 /// EmitCallArgs - Emit call arguments for a function.
4451 void CodeGenFunction::EmitCallArgs(
4452 CallArgList
&Args
, PrototypeWrapper Prototype
,
4453 llvm::iterator_range
<CallExpr::const_arg_iterator
> ArgRange
,
4454 AbstractCallee AC
, unsigned ParamsToSkip
, EvaluationOrder Order
) {
4455 SmallVector
<QualType
, 16> ArgTypes
;
4457 assert((ParamsToSkip
== 0 || Prototype
.P
) &&
4458 "Can't skip parameters if type info is not provided");
4460 // This variable only captures *explicitly* written conventions, not those
4461 // applied by default via command line flags or target defaults, such as
4462 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4463 // require knowing if this is a C++ instance method or being able to see
4464 // unprototyped FunctionTypes.
4465 CallingConv ExplicitCC
= CC_C
;
4467 // First, if a prototype was provided, use those argument types.
4468 bool IsVariadic
= false;
4470 const auto *MD
= Prototype
.P
.dyn_cast
<const ObjCMethodDecl
*>();
4472 IsVariadic
= MD
->isVariadic();
4473 ExplicitCC
= getCallingConventionForDecl(
4474 MD
, CGM
.getTarget().getTriple().isOSWindows());
4475 ArgTypes
.assign(MD
->param_type_begin() + ParamsToSkip
,
4476 MD
->param_type_end());
4478 const auto *FPT
= Prototype
.P
.get
<const FunctionProtoType
*>();
4479 IsVariadic
= FPT
->isVariadic();
4480 ExplicitCC
= FPT
->getExtInfo().getCC();
4481 ArgTypes
.assign(FPT
->param_type_begin() + ParamsToSkip
,
4482 FPT
->param_type_end());
4486 // Check that the prototyped types match the argument expression types.
4487 bool isGenericMethod
= MD
&& isObjCMethodWithTypeParams(MD
);
4488 CallExpr::const_arg_iterator Arg
= ArgRange
.begin();
4489 for (QualType Ty
: ArgTypes
) {
4490 assert(Arg
!= ArgRange
.end() && "Running over edge of argument list!");
4492 (isGenericMethod
|| Ty
->isVariablyModifiedType() ||
4493 Ty
.getNonReferenceType()->isObjCRetainableType() ||
4495 .getCanonicalType(Ty
.getNonReferenceType())
4497 getContext().getCanonicalType((*Arg
)->getType()).getTypePtr()) &&
4498 "type mismatch in call argument!");
4502 // Either we've emitted all the call args, or we have a call to variadic
4504 assert((Arg
== ArgRange
.end() || IsVariadic
) &&
4505 "Extra arguments in non-variadic function!");
4509 // If we still have any arguments, emit them using the type of the argument.
4510 for (auto *A
: llvm::drop_begin(ArgRange
, ArgTypes
.size()))
4511 ArgTypes
.push_back(IsVariadic
? getVarArgType(A
) : A
->getType());
4512 assert((int)ArgTypes
.size() == (ArgRange
.end() - ArgRange
.begin()));
4514 // We must evaluate arguments from right to left in the MS C++ ABI,
4515 // because arguments are destroyed left to right in the callee. As a special
4516 // case, there are certain language constructs that require left-to-right
4517 // evaluation, and in those cases we consider the evaluation order requirement
4518 // to trump the "destruction order is reverse construction order" guarantee.
4520 CGM
.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4521 ? Order
== EvaluationOrder::ForceLeftToRight
4522 : Order
!= EvaluationOrder::ForceRightToLeft
;
4524 auto MaybeEmitImplicitObjectSize
= [&](unsigned I
, const Expr
*Arg
,
4525 RValue EmittedArg
) {
4526 if (!AC
.hasFunctionDecl() || I
>= AC
.getNumParams())
4528 auto *PS
= AC
.getParamDecl(I
)->getAttr
<PassObjectSizeAttr
>();
4532 const auto &Context
= getContext();
4533 auto SizeTy
= Context
.getSizeType();
4534 auto T
= Builder
.getIntNTy(Context
.getTypeSize(SizeTy
));
4535 assert(EmittedArg
.getScalarVal() && "We emitted nothing for the arg?");
4536 llvm::Value
*V
= evaluateOrEmitBuiltinObjectSize(Arg
, PS
->getType(), T
,
4537 EmittedArg
.getScalarVal(),
4539 Args
.add(RValue::get(V
), SizeTy
);
4540 // If we're emitting args in reverse, be sure to do so with
4541 // pass_object_size, as well.
4543 std::swap(Args
.back(), *(&Args
.back() - 1));
4546 // Insert a stack save if we're going to need any inalloca args.
4547 if (hasInAllocaArgs(CGM
, ExplicitCC
, ArgTypes
)) {
4548 assert(getTarget().getTriple().getArch() == llvm::Triple::x86
&&
4549 "inalloca only supported on x86");
4550 Args
.allocateArgumentMemory(*this);
4553 // Evaluate each argument in the appropriate order.
4554 size_t CallArgsStart
= Args
.size();
4555 for (unsigned I
= 0, E
= ArgTypes
.size(); I
!= E
; ++I
) {
4556 unsigned Idx
= LeftToRight
? I
: E
- I
- 1;
4557 CallExpr::const_arg_iterator Arg
= ArgRange
.begin() + Idx
;
4558 unsigned InitialArgSize
= Args
.size();
4559 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4560 // the argument and parameter match or the objc method is parameterized.
4561 assert((!isa
<ObjCIndirectCopyRestoreExpr
>(*Arg
) ||
4562 getContext().hasSameUnqualifiedType((*Arg
)->getType(),
4564 (isa
<ObjCMethodDecl
>(AC
.getDecl()) &&
4565 isObjCMethodWithTypeParams(cast
<ObjCMethodDecl
>(AC
.getDecl())))) &&
4566 "Argument and parameter types don't match");
4567 EmitCallArg(Args
, *Arg
, ArgTypes
[Idx
]);
4568 // In particular, we depend on it being the last arg in Args, and the
4569 // objectsize bits depend on there only being one arg if !LeftToRight.
4570 assert(InitialArgSize
+ 1 == Args
.size() &&
4571 "The code below depends on only adding one arg per EmitCallArg");
4572 (void)InitialArgSize
;
4573 // Since pointer argument are never emitted as LValue, it is safe to emit
4574 // non-null argument check for r-value only.
4575 if (!Args
.back().hasLValue()) {
4576 RValue RVArg
= Args
.back().getKnownRValue();
4577 EmitNonNullArgCheck(RVArg
, ArgTypes
[Idx
], (*Arg
)->getExprLoc(), AC
,
4578 ParamsToSkip
+ Idx
);
4579 // @llvm.objectsize should never have side-effects and shouldn't need
4580 // destruction/cleanups, so we can safely "emit" it after its arg,
4581 // regardless of right-to-leftness
4582 MaybeEmitImplicitObjectSize(Idx
, *Arg
, RVArg
);
4587 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4589 std::reverse(Args
.begin() + CallArgsStart
, Args
.end());
4595 struct DestroyUnpassedArg final
: EHScopeStack::Cleanup
{
4596 DestroyUnpassedArg(Address Addr
, QualType Ty
)
4597 : Addr(Addr
), Ty(Ty
) {}
4602 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
4603 QualType::DestructionKind DtorKind
= Ty
.isDestructedType();
4604 if (DtorKind
== QualType::DK_cxx_destructor
) {
4605 const CXXDestructorDecl
*Dtor
= Ty
->getAsCXXRecordDecl()->getDestructor();
4606 assert(!Dtor
->isTrivial());
4607 CGF
.EmitCXXDestructorCall(Dtor
, Dtor_Complete
, /*for vbase*/ false,
4608 /*Delegating=*/false, Addr
, Ty
);
4610 CGF
.callCStructDestructor(CGF
.MakeAddrLValue(Addr
, Ty
));
4615 struct DisableDebugLocationUpdates
{
4616 CodeGenFunction
&CGF
;
4617 bool disabledDebugInfo
;
4618 DisableDebugLocationUpdates(CodeGenFunction
&CGF
, const Expr
*E
) : CGF(CGF
) {
4619 if ((disabledDebugInfo
= isa
<CXXDefaultArgExpr
>(E
) && CGF
.getDebugInfo()))
4620 CGF
.disableDebugInfo();
4622 ~DisableDebugLocationUpdates() {
4623 if (disabledDebugInfo
)
4624 CGF
.enableDebugInfo();
4628 } // end anonymous namespace
4630 RValue
CallArg::getRValue(CodeGenFunction
&CGF
) const {
4633 LValue Copy
= CGF
.MakeAddrLValue(CGF
.CreateMemTemp(Ty
), Ty
);
4634 CGF
.EmitAggregateCopy(Copy
, LV
, Ty
, AggValueSlot::DoesNotOverlap
,
4637 return RValue::getAggregate(Copy
.getAddress());
4640 void CallArg::copyInto(CodeGenFunction
&CGF
, Address Addr
) const {
4641 LValue Dst
= CGF
.MakeAddrLValue(Addr
, Ty
);
4642 if (!HasLV
&& RV
.isScalar())
4643 CGF
.EmitStoreOfScalar(RV
.getScalarVal(), Dst
, /*isInit=*/true);
4644 else if (!HasLV
&& RV
.isComplex())
4645 CGF
.EmitStoreOfComplex(RV
.getComplexVal(), Dst
, /*init=*/true);
4647 auto Addr
= HasLV
? LV
.getAddress() : RV
.getAggregateAddress();
4648 LValue SrcLV
= CGF
.MakeAddrLValue(Addr
, Ty
);
4649 // We assume that call args are never copied into subobjects.
4650 CGF
.EmitAggregateCopy(Dst
, SrcLV
, Ty
, AggValueSlot::DoesNotOverlap
,
4651 HasLV
? LV
.isVolatileQualified()
4652 : RV
.isVolatileQualified());
4657 void CodeGenFunction::EmitCallArg(CallArgList
&args
, const Expr
*E
,
4659 DisableDebugLocationUpdates
Dis(*this, E
);
4660 if (const ObjCIndirectCopyRestoreExpr
*CRE
4661 = dyn_cast
<ObjCIndirectCopyRestoreExpr
>(E
)) {
4662 assert(getLangOpts().ObjCAutoRefCount
);
4663 return emitWritebackArg(*this, args
, CRE
);
4666 assert(type
->isReferenceType() == E
->isGLValue() &&
4667 "reference binding to unmaterialized r-value!");
4669 if (E
->isGLValue()) {
4670 assert(E
->getObjectKind() == OK_Ordinary
);
4671 return args
.add(EmitReferenceBindingToExpr(E
), type
);
4674 bool HasAggregateEvalKind
= hasAggregateEvaluationKind(type
);
4676 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4677 // However, we still have to push an EH-only cleanup in case we unwind before
4678 // we make it to the call.
4679 if (type
->isRecordType() &&
4680 type
->castAs
<RecordType
>()->getDecl()->isParamDestroyedInCallee()) {
4681 // If we're using inalloca, use the argument memory. Otherwise, use a
4683 AggValueSlot Slot
= args
.isUsingInAlloca()
4684 ? createPlaceholderSlot(*this, type
) : CreateAggTemp(type
, "agg.tmp");
4686 bool DestroyedInCallee
= true, NeedsCleanup
= true;
4687 if (const auto *RD
= type
->getAsCXXRecordDecl())
4688 DestroyedInCallee
= RD
->hasNonTrivialDestructor();
4690 NeedsCleanup
= type
.isDestructedType();
4692 if (DestroyedInCallee
)
4693 Slot
.setExternallyDestructed();
4695 EmitAggExpr(E
, Slot
);
4696 RValue RV
= Slot
.asRValue();
4699 if (DestroyedInCallee
&& NeedsCleanup
) {
4700 // Create a no-op GEP between the placeholder and the cleanup so we can
4701 // RAUW it successfully. It also serves as a marker of the first
4702 // instruction where the cleanup is active.
4703 pushFullExprCleanup
<DestroyUnpassedArg
>(NormalAndEHCleanup
,
4704 Slot
.getAddress(), type
);
4705 // This unreachable is a temporary marker which will be removed later.
4706 llvm::Instruction
*IsActive
=
4707 Builder
.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy
));
4708 args
.addArgCleanupDeactivation(EHStack
.stable_begin(), IsActive
);
4713 if (HasAggregateEvalKind
&& isa
<ImplicitCastExpr
>(E
) &&
4714 cast
<CastExpr
>(E
)->getCastKind() == CK_LValueToRValue
&&
4715 !type
->isArrayParameterType()) {
4716 LValue L
= EmitLValue(cast
<CastExpr
>(E
)->getSubExpr());
4717 assert(L
.isSimple());
4718 args
.addUncopiedAggregate(L
, type
);
4722 args
.add(EmitAnyExprToTemp(E
), type
);
4725 QualType
CodeGenFunction::getVarArgType(const Expr
*Arg
) {
4726 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4727 // implicitly widens null pointer constants that are arguments to varargs
4728 // functions to pointer-sized ints.
4729 if (!getTarget().getTriple().isOSWindows())
4730 return Arg
->getType();
4732 if (Arg
->getType()->isIntegerType() &&
4733 getContext().getTypeSize(Arg
->getType()) <
4734 getContext().getTargetInfo().getPointerWidth(LangAS::Default
) &&
4735 Arg
->isNullPointerConstant(getContext(),
4736 Expr::NPC_ValueDependentIsNotNull
)) {
4737 return getContext().getIntPtrType();
4740 return Arg
->getType();
4743 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4744 // optimizer it can aggressively ignore unwind edges.
4746 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction
*Inst
) {
4747 if (CGM
.getCodeGenOpts().OptimizationLevel
!= 0 &&
4748 !CGM
.getCodeGenOpts().ObjCAutoRefCountExceptions
)
4749 Inst
->setMetadata("clang.arc.no_objc_arc_exceptions",
4750 CGM
.getNoObjCARCExceptionsMetadata());
4753 /// Emits a call to the given no-arguments nounwind runtime function.
4755 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee
,
4756 const llvm::Twine
&name
) {
4757 return EmitNounwindRuntimeCall(callee
, ArrayRef
<llvm::Value
*>(), name
);
4760 /// Emits a call to the given nounwind runtime function.
4762 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee
,
4763 ArrayRef
<Address
> args
,
4764 const llvm::Twine
&name
) {
4765 SmallVector
<llvm::Value
*, 3> values
;
4766 for (auto arg
: args
)
4767 values
.push_back(arg
.emitRawPointer(*this));
4768 return EmitNounwindRuntimeCall(callee
, values
, name
);
4772 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee
,
4773 ArrayRef
<llvm::Value
*> args
,
4774 const llvm::Twine
&name
) {
4775 llvm::CallInst
*call
= EmitRuntimeCall(callee
, args
, name
);
4776 call
->setDoesNotThrow();
4780 /// Emits a simple call (never an invoke) to the given no-arguments
4781 /// runtime function.
4782 llvm::CallInst
*CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee
,
4783 const llvm::Twine
&name
) {
4784 return EmitRuntimeCall(callee
, std::nullopt
, name
);
4787 // Calls which may throw must have operand bundles indicating which funclet
4788 // they are nested within.
4789 SmallVector
<llvm::OperandBundleDef
, 1>
4790 CodeGenFunction::getBundlesForFunclet(llvm::Value
*Callee
) {
4791 // There is no need for a funclet operand bundle if we aren't inside a
4793 if (!CurrentFuncletPad
)
4794 return (SmallVector
<llvm::OperandBundleDef
, 1>());
4796 // Skip intrinsics which cannot throw (as long as they don't lower into
4797 // regular function calls in the course of IR transformations).
4798 if (auto *CalleeFn
= dyn_cast
<llvm::Function
>(Callee
->stripPointerCasts())) {
4799 if (CalleeFn
->isIntrinsic() && CalleeFn
->doesNotThrow()) {
4800 auto IID
= CalleeFn
->getIntrinsicID();
4801 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID
))
4802 return (SmallVector
<llvm::OperandBundleDef
, 1>());
4806 SmallVector
<llvm::OperandBundleDef
, 1> BundleList
;
4807 BundleList
.emplace_back("funclet", CurrentFuncletPad
);
4811 /// Emits a simple call (never an invoke) to the given runtime function.
4812 llvm::CallInst
*CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee
,
4813 ArrayRef
<llvm::Value
*> args
,
4814 const llvm::Twine
&name
) {
4815 llvm::CallInst
*call
= Builder
.CreateCall(
4816 callee
, args
, getBundlesForFunclet(callee
.getCallee()), name
);
4817 call
->setCallingConv(getRuntimeCC());
4819 if (CGM
.shouldEmitConvergenceTokens() && call
->isConvergent())
4820 return addControlledConvergenceToken(call
);
4824 /// Emits a call or invoke to the given noreturn runtime function.
4825 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4826 llvm::FunctionCallee callee
, ArrayRef
<llvm::Value
*> args
) {
4827 SmallVector
<llvm::OperandBundleDef
, 1> BundleList
=
4828 getBundlesForFunclet(callee
.getCallee());
4830 if (getInvokeDest()) {
4831 llvm::InvokeInst
*invoke
=
4832 Builder
.CreateInvoke(callee
,
4833 getUnreachableBlock(),
4837 invoke
->setDoesNotReturn();
4838 invoke
->setCallingConv(getRuntimeCC());
4840 llvm::CallInst
*call
= Builder
.CreateCall(callee
, args
, BundleList
);
4841 call
->setDoesNotReturn();
4842 call
->setCallingConv(getRuntimeCC());
4843 Builder
.CreateUnreachable();
4847 /// Emits a call or invoke instruction to the given nullary runtime function.
4849 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee
,
4850 const Twine
&name
) {
4851 return EmitRuntimeCallOrInvoke(callee
, std::nullopt
, name
);
4854 /// Emits a call or invoke instruction to the given runtime function.
4856 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee
,
4857 ArrayRef
<llvm::Value
*> args
,
4858 const Twine
&name
) {
4859 llvm::CallBase
*call
= EmitCallOrInvoke(callee
, args
, name
);
4860 call
->setCallingConv(getRuntimeCC());
4864 /// Emits a call or invoke instruction to the given function, depending
4865 /// on the current state of the EH stack.
4866 llvm::CallBase
*CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee
,
4867 ArrayRef
<llvm::Value
*> Args
,
4868 const Twine
&Name
) {
4869 llvm::BasicBlock
*InvokeDest
= getInvokeDest();
4870 SmallVector
<llvm::OperandBundleDef
, 1> BundleList
=
4871 getBundlesForFunclet(Callee
.getCallee());
4873 llvm::CallBase
*Inst
;
4875 Inst
= Builder
.CreateCall(Callee
, Args
, BundleList
, Name
);
4877 llvm::BasicBlock
*ContBB
= createBasicBlock("invoke.cont");
4878 Inst
= Builder
.CreateInvoke(Callee
, ContBB
, InvokeDest
, Args
, BundleList
,
4883 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4884 // optimizer it can aggressively ignore unwind edges.
4885 if (CGM
.getLangOpts().ObjCAutoRefCount
)
4886 AddObjCARCExceptionMetadata(Inst
);
4891 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction
*Old
,
4893 DeferredReplacements
.push_back(
4894 std::make_pair(llvm::WeakTrackingVH(Old
), New
));
4899 /// Specify given \p NewAlign as the alignment of return value attribute. If
4900 /// such attribute already exists, re-set it to the maximal one of two options.
4901 [[nodiscard
]] llvm::AttributeList
4902 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext
&Ctx
,
4903 const llvm::AttributeList
&Attrs
,
4904 llvm::Align NewAlign
) {
4905 llvm::Align CurAlign
= Attrs
.getRetAlignment().valueOrOne();
4906 if (CurAlign
>= NewAlign
)
4908 llvm::Attribute AlignAttr
= llvm::Attribute::getWithAlignment(Ctx
, NewAlign
);
4909 return Attrs
.removeRetAttribute(Ctx
, llvm::Attribute::AttrKind::Alignment
)
4910 .addRetAttribute(Ctx
, AlignAttr
);
4913 template <typename AlignedAttrTy
> class AbstractAssumeAlignedAttrEmitter
{
4915 CodeGenFunction
&CGF
;
4917 /// We do nothing if this is, or becomes, nullptr.
4918 const AlignedAttrTy
*AA
= nullptr;
4920 llvm::Value
*Alignment
= nullptr; // May or may not be a constant.
4921 llvm::ConstantInt
*OffsetCI
= nullptr; // Constant, hopefully zero.
4923 AbstractAssumeAlignedAttrEmitter(CodeGenFunction
&CGF_
, const Decl
*FuncDecl
)
4927 AA
= FuncDecl
->getAttr
<AlignedAttrTy
>();
4931 /// If we can, materialize the alignment as an attribute on return value.
4932 [[nodiscard
]] llvm::AttributeList
4933 TryEmitAsCallSiteAttribute(const llvm::AttributeList
&Attrs
) {
4934 if (!AA
|| OffsetCI
|| CGF
.SanOpts
.has(SanitizerKind::Alignment
))
4936 const auto *AlignmentCI
= dyn_cast
<llvm::ConstantInt
>(Alignment
);
4939 // We may legitimately have non-power-of-2 alignment here.
4940 // If so, this is UB land, emit it via `@llvm.assume` instead.
4941 if (!AlignmentCI
->getValue().isPowerOf2())
4943 llvm::AttributeList NewAttrs
= maybeRaiseRetAlignmentAttribute(
4944 CGF
.getLLVMContext(), Attrs
,
4946 AlignmentCI
->getLimitedValue(llvm::Value::MaximumAlignment
)));
4947 AA
= nullptr; // We're done. Disallow doing anything else.
4951 /// Emit alignment assumption.
4952 /// This is a general fallback that we take if either there is an offset,
4953 /// or the alignment is variable or we are sanitizing for alignment.
4954 void EmitAsAnAssumption(SourceLocation Loc
, QualType RetTy
, RValue
&Ret
) {
4957 CGF
.emitAlignmentAssumption(Ret
.getScalarVal(), RetTy
, Loc
,
4958 AA
->getLocation(), Alignment
, OffsetCI
);
4959 AA
= nullptr; // We're done. Disallow doing anything else.
4963 /// Helper data structure to emit `AssumeAlignedAttr`.
4964 class AssumeAlignedAttrEmitter final
4965 : public AbstractAssumeAlignedAttrEmitter
<AssumeAlignedAttr
> {
4967 AssumeAlignedAttrEmitter(CodeGenFunction
&CGF_
, const Decl
*FuncDecl
)
4968 : AbstractAssumeAlignedAttrEmitter(CGF_
, FuncDecl
) {
4971 // It is guaranteed that the alignment/offset are constants.
4972 Alignment
= cast
<llvm::ConstantInt
>(CGF
.EmitScalarExpr(AA
->getAlignment()));
4973 if (Expr
*Offset
= AA
->getOffset()) {
4974 OffsetCI
= cast
<llvm::ConstantInt
>(CGF
.EmitScalarExpr(Offset
));
4975 if (OffsetCI
->isNullValue()) // Canonicalize zero offset to no offset.
4981 /// Helper data structure to emit `AllocAlignAttr`.
4982 class AllocAlignAttrEmitter final
4983 : public AbstractAssumeAlignedAttrEmitter
<AllocAlignAttr
> {
4985 AllocAlignAttrEmitter(CodeGenFunction
&CGF_
, const Decl
*FuncDecl
,
4986 const CallArgList
&CallArgs
)
4987 : AbstractAssumeAlignedAttrEmitter(CGF_
, FuncDecl
) {
4990 // Alignment may or may not be a constant, and that is okay.
4991 Alignment
= CallArgs
[AA
->getParamIndex().getLLVMIndex()]
4999 static unsigned getMaxVectorWidth(const llvm::Type
*Ty
) {
5000 if (auto *VT
= dyn_cast
<llvm::VectorType
>(Ty
))
5001 return VT
->getPrimitiveSizeInBits().getKnownMinValue();
5002 if (auto *AT
= dyn_cast
<llvm::ArrayType
>(Ty
))
5003 return getMaxVectorWidth(AT
->getElementType());
5005 unsigned MaxVectorWidth
= 0;
5006 if (auto *ST
= dyn_cast
<llvm::StructType
>(Ty
))
5007 for (auto *I
: ST
->elements())
5008 MaxVectorWidth
= std::max(MaxVectorWidth
, getMaxVectorWidth(I
));
5009 return MaxVectorWidth
;
5012 RValue
CodeGenFunction::EmitCall(const CGFunctionInfo
&CallInfo
,
5013 const CGCallee
&Callee
,
5014 ReturnValueSlot ReturnValue
,
5015 const CallArgList
&CallArgs
,
5016 llvm::CallBase
**callOrInvoke
, bool IsMustTail
,
5018 bool IsVirtualFunctionPointerThunk
) {
5019 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5021 assert(Callee
.isOrdinary() || Callee
.isVirtual());
5023 // Handle struct-return functions by passing a pointer to the
5024 // location that we would like to return into.
5025 QualType RetTy
= CallInfo
.getReturnType();
5026 const ABIArgInfo
&RetAI
= CallInfo
.getReturnInfo();
5028 llvm::FunctionType
*IRFuncTy
= getTypes().GetFunctionType(CallInfo
);
5030 const Decl
*TargetDecl
= Callee
.getAbstractInfo().getCalleeDecl().getDecl();
5031 if (const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(TargetDecl
)) {
5032 // We can only guarantee that a function is called from the correct
5033 // context/function based on the appropriate target attributes,
5034 // so only check in the case where we have both always_inline and target
5035 // since otherwise we could be making a conditional call after a check for
5036 // the proper cpu features (and it won't cause code generation issues due to
5037 // function based code generation).
5038 if (TargetDecl
->hasAttr
<AlwaysInlineAttr
>() &&
5039 (TargetDecl
->hasAttr
<TargetAttr
>() ||
5040 (CurFuncDecl
&& CurFuncDecl
->hasAttr
<TargetAttr
>())))
5041 checkTargetFeatures(Loc
, FD
);
5044 // Some architectures (such as x86-64) have the ABI changed based on
5045 // attribute-target/features. Give them a chance to diagnose.
5046 CGM
.getTargetCodeGenInfo().checkFunctionCallABI(
5047 CGM
, Loc
, dyn_cast_or_null
<FunctionDecl
>(CurCodeDecl
),
5048 dyn_cast_or_null
<FunctionDecl
>(TargetDecl
), CallArgs
, RetTy
);
5050 // 1. Set up the arguments.
5052 // If we're using inalloca, insert the allocation after the stack save.
5053 // FIXME: Do this earlier rather than hacking it in here!
5054 RawAddress ArgMemory
= RawAddress::invalid();
5055 if (llvm::StructType
*ArgStruct
= CallInfo
.getArgStruct()) {
5056 const llvm::DataLayout
&DL
= CGM
.getDataLayout();
5057 llvm::Instruction
*IP
= CallArgs
.getStackBase();
5058 llvm::AllocaInst
*AI
;
5060 IP
= IP
->getNextNode();
5061 AI
= new llvm::AllocaInst(ArgStruct
, DL
.getAllocaAddrSpace(),
5064 AI
= CreateTempAlloca(ArgStruct
, "argmem");
5066 auto Align
= CallInfo
.getArgStructAlignment();
5067 AI
->setAlignment(Align
.getAsAlign());
5068 AI
->setUsedWithInAlloca(true);
5069 assert(AI
->isUsedWithInAlloca() && !AI
->isStaticAlloca());
5070 ArgMemory
= RawAddress(AI
, ArgStruct
, Align
);
5073 ClangToLLVMArgMapping
IRFunctionArgs(CGM
.getContext(), CallInfo
);
5074 SmallVector
<llvm::Value
*, 16> IRCallArgs(IRFunctionArgs
.totalIRArgs());
5076 // If the call returns a temporary with struct return, create a temporary
5077 // alloca to hold the result, unless one is given to us.
5078 Address SRetPtr
= Address::invalid();
5079 RawAddress SRetAlloca
= RawAddress::invalid();
5080 llvm::Value
*UnusedReturnSizePtr
= nullptr;
5081 if (RetAI
.isIndirect() || RetAI
.isInAlloca() || RetAI
.isCoerceAndExpand()) {
5082 if (IsVirtualFunctionPointerThunk
&& RetAI
.isIndirect()) {
5083 SRetPtr
= makeNaturalAddressForPointer(CurFn
->arg_begin() +
5084 IRFunctionArgs
.getSRetArgNo(),
5085 RetTy
, CharUnits::fromQuantity(1));
5086 } else if (!ReturnValue
.isNull()) {
5087 SRetPtr
= ReturnValue
.getAddress();
5089 SRetPtr
= CreateMemTemp(RetTy
, "tmp", &SRetAlloca
);
5090 if (HaveInsertPoint() && ReturnValue
.isUnused()) {
5091 llvm::TypeSize size
=
5092 CGM
.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy
));
5093 UnusedReturnSizePtr
= EmitLifetimeStart(size
, SRetAlloca
.getPointer());
5096 if (IRFunctionArgs
.hasSRetArg()) {
5097 IRCallArgs
[IRFunctionArgs
.getSRetArgNo()] =
5098 getAsNaturalPointerTo(SRetPtr
, RetTy
);
5099 } else if (RetAI
.isInAlloca()) {
5101 Builder
.CreateStructGEP(ArgMemory
, RetAI
.getInAllocaFieldIndex());
5102 Builder
.CreateStore(getAsNaturalPointerTo(SRetPtr
, RetTy
), Addr
);
5106 RawAddress swiftErrorTemp
= RawAddress::invalid();
5107 Address swiftErrorArg
= Address::invalid();
5109 // When passing arguments using temporary allocas, we need to add the
5110 // appropriate lifetime markers. This vector keeps track of all the lifetime
5111 // markers that need to be ended right after the call.
5112 SmallVector
<CallLifetimeEnd
, 2> CallLifetimeEndAfterCall
;
5114 // Translate all of the arguments as necessary to match the IR lowering.
5115 assert(CallInfo
.arg_size() == CallArgs
.size() &&
5116 "Mismatch between function signature & arguments.");
5118 CGFunctionInfo::const_arg_iterator info_it
= CallInfo
.arg_begin();
5119 for (CallArgList::const_iterator I
= CallArgs
.begin(), E
= CallArgs
.end();
5120 I
!= E
; ++I
, ++info_it
, ++ArgNo
) {
5121 const ABIArgInfo
&ArgInfo
= info_it
->info
;
5123 // Insert a padding argument to ensure proper alignment.
5124 if (IRFunctionArgs
.hasPaddingArg(ArgNo
))
5125 IRCallArgs
[IRFunctionArgs
.getPaddingArgNo(ArgNo
)] =
5126 llvm::UndefValue::get(ArgInfo
.getPaddingType());
5128 unsigned FirstIRArg
, NumIRArgs
;
5129 std::tie(FirstIRArg
, NumIRArgs
) = IRFunctionArgs
.getIRArgs(ArgNo
);
5131 bool ArgHasMaybeUndefAttr
=
5132 IsArgumentMaybeUndef(TargetDecl
, CallInfo
.getNumRequiredArgs(), ArgNo
);
5134 switch (ArgInfo
.getKind()) {
5135 case ABIArgInfo::InAlloca
: {
5136 assert(NumIRArgs
== 0);
5137 assert(getTarget().getTriple().getArch() == llvm::Triple::x86
);
5138 if (I
->isAggregate()) {
5139 RawAddress Addr
= I
->hasLValue()
5140 ? I
->getKnownLValue().getAddress()
5141 : I
->getKnownRValue().getAggregateAddress();
5142 llvm::Instruction
*Placeholder
=
5143 cast
<llvm::Instruction
>(Addr
.getPointer());
5145 if (!ArgInfo
.getInAllocaIndirect()) {
5146 // Replace the placeholder with the appropriate argument slot GEP.
5147 CGBuilderTy::InsertPoint IP
= Builder
.saveIP();
5148 Builder
.SetInsertPoint(Placeholder
);
5149 Addr
= Builder
.CreateStructGEP(ArgMemory
,
5150 ArgInfo
.getInAllocaFieldIndex());
5151 Builder
.restoreIP(IP
);
5153 // For indirect things such as overaligned structs, replace the
5154 // placeholder with a regular aggregate temporary alloca. Store the
5155 // address of this alloca into the struct.
5156 Addr
= CreateMemTemp(info_it
->type
, "inalloca.indirect.tmp");
5157 Address ArgSlot
= Builder
.CreateStructGEP(
5158 ArgMemory
, ArgInfo
.getInAllocaFieldIndex());
5159 Builder
.CreateStore(Addr
.getPointer(), ArgSlot
);
5161 deferPlaceholderReplacement(Placeholder
, Addr
.getPointer());
5162 } else if (ArgInfo
.getInAllocaIndirect()) {
5163 // Make a temporary alloca and store the address of it into the argument
5165 RawAddress Addr
= CreateMemTempWithoutCast(
5166 I
->Ty
, getContext().getTypeAlignInChars(I
->Ty
),
5167 "indirect-arg-temp");
5168 I
->copyInto(*this, Addr
);
5170 Builder
.CreateStructGEP(ArgMemory
, ArgInfo
.getInAllocaFieldIndex());
5171 Builder
.CreateStore(Addr
.getPointer(), ArgSlot
);
5173 // Store the RValue into the argument struct.
5175 Builder
.CreateStructGEP(ArgMemory
, ArgInfo
.getInAllocaFieldIndex());
5176 Addr
= Addr
.withElementType(ConvertTypeForMem(I
->Ty
));
5177 I
->copyInto(*this, Addr
);
5182 case ABIArgInfo::Indirect
:
5183 case ABIArgInfo::IndirectAliased
: {
5184 assert(NumIRArgs
== 1);
5185 if (I
->isAggregate()) {
5186 // We want to avoid creating an unnecessary temporary+copy here;
5187 // however, we need one in three cases:
5188 // 1. If the argument is not byval, and we are required to copy the
5189 // source. (This case doesn't occur on any common architecture.)
5190 // 2. If the argument is byval, RV is not sufficiently aligned, and
5191 // we cannot force it to be sufficiently aligned.
5192 // 3. If the argument is byval, but RV is not located in default
5193 // or alloca address space.
5194 Address Addr
= I
->hasLValue()
5195 ? I
->getKnownLValue().getAddress()
5196 : I
->getKnownRValue().getAggregateAddress();
5197 CharUnits Align
= ArgInfo
.getIndirectAlign();
5198 const llvm::DataLayout
*TD
= &CGM
.getDataLayout();
5200 assert((FirstIRArg
>= IRFuncTy
->getNumParams() ||
5201 IRFuncTy
->getParamType(FirstIRArg
)->getPointerAddressSpace() ==
5202 TD
->getAllocaAddrSpace()) &&
5203 "indirect argument must be in alloca address space");
5205 bool NeedCopy
= false;
5206 if (Addr
.getAlignment() < Align
&&
5207 llvm::getOrEnforceKnownAlignment(Addr
.emitRawPointer(*this),
5209 *TD
) < Align
.getAsAlign()) {
5211 } else if (I
->hasLValue()) {
5212 auto LV
= I
->getKnownLValue();
5213 auto AS
= LV
.getAddressSpace();
5216 ArgInfo
.isIndirectAliased() || ArgInfo
.getIndirectByVal();
5218 if (!isByValOrRef
||
5219 (LV
.getAlignment() < getContext().getTypeAlignInChars(I
->Ty
))) {
5222 if (!getLangOpts().OpenCL
) {
5223 if ((isByValOrRef
&&
5224 (AS
!= LangAS::Default
&&
5225 AS
!= CGM
.getASTAllocaAddressSpace()))) {
5229 // For OpenCL even if RV is located in default or alloca address space
5230 // we don't want to perform address space cast for it.
5231 else if ((isByValOrRef
&&
5232 Addr
.getType()->getAddressSpace() != IRFuncTy
->
5233 getParamType(FirstIRArg
)->getPointerAddressSpace())) {
5239 // Skip the extra memcpy call.
5240 llvm::Value
*V
= getAsNaturalPointerTo(Addr
, I
->Ty
);
5241 auto *T
= llvm::PointerType::get(
5242 CGM
.getLLVMContext(), CGM
.getDataLayout().getAllocaAddrSpace());
5244 llvm::Value
*Val
= getTargetHooks().performAddrSpaceCast(
5245 *this, V
, LangAS::Default
, CGM
.getASTAllocaAddressSpace(), T
,
5247 if (ArgHasMaybeUndefAttr
)
5248 Val
= Builder
.CreateFreeze(Val
);
5249 IRCallArgs
[FirstIRArg
] = Val
;
5254 // For non-aggregate args and aggregate args meeting conditions above
5255 // we need to create an aligned temporary, and copy to it.
5256 RawAddress AI
= CreateMemTempWithoutCast(
5257 I
->Ty
, ArgInfo
.getIndirectAlign(), "byval-temp");
5258 llvm::Value
*Val
= getAsNaturalPointerTo(AI
, I
->Ty
);
5259 if (ArgHasMaybeUndefAttr
)
5260 Val
= Builder
.CreateFreeze(Val
);
5261 IRCallArgs
[FirstIRArg
] = Val
;
5263 // Emit lifetime markers for the temporary alloca.
5264 llvm::TypeSize ByvalTempElementSize
=
5265 CGM
.getDataLayout().getTypeAllocSize(AI
.getElementType());
5266 llvm::Value
*LifetimeSize
=
5267 EmitLifetimeStart(ByvalTempElementSize
, AI
.getPointer());
5269 // Add cleanup code to emit the end lifetime marker after the call.
5270 if (LifetimeSize
) // In case we disabled lifetime markers.
5271 CallLifetimeEndAfterCall
.emplace_back(AI
, LifetimeSize
);
5273 // Generate the copy.
5274 I
->copyInto(*this, AI
);
5278 case ABIArgInfo::Ignore
:
5279 assert(NumIRArgs
== 0);
5282 case ABIArgInfo::Extend
:
5283 case ABIArgInfo::Direct
: {
5284 if (!isa
<llvm::StructType
>(ArgInfo
.getCoerceToType()) &&
5285 ArgInfo
.getCoerceToType() == ConvertType(info_it
->type
) &&
5286 ArgInfo
.getDirectOffset() == 0) {
5287 assert(NumIRArgs
== 1);
5289 if (!I
->isAggregate())
5290 V
= I
->getKnownRValue().getScalarVal();
5292 V
= Builder
.CreateLoad(
5293 I
->hasLValue() ? I
->getKnownLValue().getAddress()
5294 : I
->getKnownRValue().getAggregateAddress());
5296 // Implement swifterror by copying into a new swifterror argument.
5297 // We'll write back in the normal path out of the call.
5298 if (CallInfo
.getExtParameterInfo(ArgNo
).getABI()
5299 == ParameterABI::SwiftErrorResult
) {
5300 assert(!swiftErrorTemp
.isValid() && "multiple swifterror args");
5302 QualType pointeeTy
= I
->Ty
->getPointeeType();
5303 swiftErrorArg
= makeNaturalAddressForPointer(
5304 V
, pointeeTy
, getContext().getTypeAlignInChars(pointeeTy
));
5307 CreateMemTemp(pointeeTy
, getPointerAlign(), "swifterror.temp");
5308 V
= swiftErrorTemp
.getPointer();
5309 cast
<llvm::AllocaInst
>(V
)->setSwiftError(true);
5311 llvm::Value
*errorValue
= Builder
.CreateLoad(swiftErrorArg
);
5312 Builder
.CreateStore(errorValue
, swiftErrorTemp
);
5315 // We might have to widen integers, but we should never truncate.
5316 if (ArgInfo
.getCoerceToType() != V
->getType() &&
5317 V
->getType()->isIntegerTy())
5318 V
= Builder
.CreateZExt(V
, ArgInfo
.getCoerceToType());
5320 // If the argument doesn't match, perform a bitcast to coerce it. This
5321 // can happen due to trivial type mismatches.
5322 if (FirstIRArg
< IRFuncTy
->getNumParams() &&
5323 V
->getType() != IRFuncTy
->getParamType(FirstIRArg
))
5324 V
= Builder
.CreateBitCast(V
, IRFuncTy
->getParamType(FirstIRArg
));
5326 if (ArgHasMaybeUndefAttr
)
5327 V
= Builder
.CreateFreeze(V
);
5328 IRCallArgs
[FirstIRArg
] = V
;
5332 llvm::StructType
*STy
=
5333 dyn_cast
<llvm::StructType
>(ArgInfo
.getCoerceToType());
5334 if (STy
&& ArgInfo
.isDirect() && !ArgInfo
.getCanBeFlattened()) {
5335 llvm::Type
*SrcTy
= ConvertTypeForMem(I
->Ty
);
5336 [[maybe_unused
]] llvm::TypeSize SrcTypeSize
=
5337 CGM
.getDataLayout().getTypeAllocSize(SrcTy
);
5338 [[maybe_unused
]] llvm::TypeSize DstTypeSize
=
5339 CGM
.getDataLayout().getTypeAllocSize(STy
);
5340 if (STy
->containsHomogeneousScalableVectorTypes()) {
5341 assert(SrcTypeSize
== DstTypeSize
&&
5342 "Only allow non-fractional movement of structure with "
5343 "homogeneous scalable vector type");
5345 IRCallArgs
[FirstIRArg
] = I
->getKnownRValue().getScalarVal();
5350 // FIXME: Avoid the conversion through memory if possible.
5351 Address Src
= Address::invalid();
5352 if (!I
->isAggregate()) {
5353 Src
= CreateMemTemp(I
->Ty
, "coerce");
5354 I
->copyInto(*this, Src
);
5356 Src
= I
->hasLValue() ? I
->getKnownLValue().getAddress()
5357 : I
->getKnownRValue().getAggregateAddress();
5360 // If the value is offset in memory, apply the offset now.
5361 Src
= emitAddressAtOffset(*this, Src
, ArgInfo
);
5363 // Fast-isel and the optimizer generally like scalar values better than
5364 // FCAs, so we flatten them if this is safe to do for this argument.
5365 if (STy
&& ArgInfo
.isDirect() && ArgInfo
.getCanBeFlattened()) {
5366 llvm::Type
*SrcTy
= Src
.getElementType();
5367 llvm::TypeSize SrcTypeSize
=
5368 CGM
.getDataLayout().getTypeAllocSize(SrcTy
);
5369 llvm::TypeSize DstTypeSize
= CGM
.getDataLayout().getTypeAllocSize(STy
);
5370 if (SrcTypeSize
.isScalable()) {
5371 assert(STy
->containsHomogeneousScalableVectorTypes() &&
5372 "ABI only supports structure with homogeneous scalable vector "
5374 assert(SrcTypeSize
== DstTypeSize
&&
5375 "Only allow non-fractional movement of structure with "
5376 "homogeneous scalable vector type");
5377 assert(NumIRArgs
== STy
->getNumElements());
5379 llvm::Value
*StoredStructValue
=
5380 Builder
.CreateLoad(Src
, Src
.getName() + ".tuple");
5381 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
) {
5382 llvm::Value
*Extract
= Builder
.CreateExtractValue(
5383 StoredStructValue
, i
, Src
.getName() + ".extract" + Twine(i
));
5384 IRCallArgs
[FirstIRArg
+ i
] = Extract
;
5387 uint64_t SrcSize
= SrcTypeSize
.getFixedValue();
5388 uint64_t DstSize
= DstTypeSize
.getFixedValue();
5390 // If the source type is smaller than the destination type of the
5391 // coerce-to logic, copy the source value into a temp alloca the size
5392 // of the destination type to allow loading all of it. The bits past
5393 // the source value are left undef.
5394 if (SrcSize
< DstSize
) {
5395 Address TempAlloca
= CreateTempAlloca(STy
, Src
.getAlignment(),
5396 Src
.getName() + ".coerce");
5397 Builder
.CreateMemCpy(TempAlloca
, Src
, SrcSize
);
5400 Src
= Src
.withElementType(STy
);
5403 assert(NumIRArgs
== STy
->getNumElements());
5404 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
) {
5405 Address EltPtr
= Builder
.CreateStructGEP(Src
, i
);
5406 llvm::Value
*LI
= Builder
.CreateLoad(EltPtr
);
5407 if (ArgHasMaybeUndefAttr
)
5408 LI
= Builder
.CreateFreeze(LI
);
5409 IRCallArgs
[FirstIRArg
+ i
] = LI
;
5413 // In the simple case, just pass the coerced loaded value.
5414 assert(NumIRArgs
== 1);
5416 CreateCoercedLoad(Src
, ArgInfo
.getCoerceToType(), *this);
5418 if (CallInfo
.isCmseNSCall()) {
5419 // For certain parameter types, clear padding bits, as they may reveal
5420 // sensitive information.
5421 // Small struct/union types are passed as integer arrays.
5422 auto *ATy
= dyn_cast
<llvm::ArrayType
>(Load
->getType());
5423 if (ATy
!= nullptr && isa
<RecordType
>(I
->Ty
.getCanonicalType()))
5424 Load
= EmitCMSEClearRecord(Load
, ATy
, I
->Ty
);
5427 if (ArgHasMaybeUndefAttr
)
5428 Load
= Builder
.CreateFreeze(Load
);
5429 IRCallArgs
[FirstIRArg
] = Load
;
5435 case ABIArgInfo::CoerceAndExpand
: {
5436 auto coercionType
= ArgInfo
.getCoerceAndExpandType();
5437 auto layout
= CGM
.getDataLayout().getStructLayout(coercionType
);
5439 llvm::Value
*tempSize
= nullptr;
5440 Address addr
= Address::invalid();
5441 RawAddress AllocaAddr
= RawAddress::invalid();
5442 if (I
->isAggregate()) {
5443 addr
= I
->hasLValue() ? I
->getKnownLValue().getAddress()
5444 : I
->getKnownRValue().getAggregateAddress();
5447 RValue RV
= I
->getKnownRValue();
5448 assert(RV
.isScalar()); // complex should always just be direct
5450 llvm::Type
*scalarType
= RV
.getScalarVal()->getType();
5451 auto scalarSize
= CGM
.getDataLayout().getTypeAllocSize(scalarType
);
5452 auto scalarAlign
= CGM
.getDataLayout().getPrefTypeAlign(scalarType
);
5454 // Materialize to a temporary.
5455 addr
= CreateTempAlloca(
5456 RV
.getScalarVal()->getType(),
5457 CharUnits::fromQuantity(std::max(layout
->getAlignment(), scalarAlign
)),
5459 /*ArraySize=*/nullptr, &AllocaAddr
);
5460 tempSize
= EmitLifetimeStart(scalarSize
, AllocaAddr
.getPointer());
5462 Builder
.CreateStore(RV
.getScalarVal(), addr
);
5465 addr
= addr
.withElementType(coercionType
);
5467 unsigned IRArgPos
= FirstIRArg
;
5468 for (unsigned i
= 0, e
= coercionType
->getNumElements(); i
!= e
; ++i
) {
5469 llvm::Type
*eltType
= coercionType
->getElementType(i
);
5470 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType
)) continue;
5471 Address eltAddr
= Builder
.CreateStructGEP(addr
, i
);
5472 llvm::Value
*elt
= Builder
.CreateLoad(eltAddr
);
5473 if (ArgHasMaybeUndefAttr
)
5474 elt
= Builder
.CreateFreeze(elt
);
5475 IRCallArgs
[IRArgPos
++] = elt
;
5477 assert(IRArgPos
== FirstIRArg
+ NumIRArgs
);
5480 EmitLifetimeEnd(tempSize
, AllocaAddr
.getPointer());
5486 case ABIArgInfo::Expand
: {
5487 unsigned IRArgPos
= FirstIRArg
;
5488 ExpandTypeToArgs(I
->Ty
, *I
, IRFuncTy
, IRCallArgs
, IRArgPos
);
5489 assert(IRArgPos
== FirstIRArg
+ NumIRArgs
);
5495 const CGCallee
&ConcreteCallee
= Callee
.prepareConcreteCallee(*this);
5496 llvm::Value
*CalleePtr
= ConcreteCallee
.getFunctionPointer();
5498 // If we're using inalloca, set up that argument.
5499 if (ArgMemory
.isValid()) {
5500 llvm::Value
*Arg
= ArgMemory
.getPointer();
5501 assert(IRFunctionArgs
.hasInallocaArg());
5502 IRCallArgs
[IRFunctionArgs
.getInallocaArgNo()] = Arg
;
5505 // 2. Prepare the function pointer.
5507 // If the callee is a bitcast of a non-variadic function to have a
5508 // variadic function pointer type, check to see if we can remove the
5509 // bitcast. This comes up with unprototyped functions.
5511 // This makes the IR nicer, but more importantly it ensures that we
5512 // can inline the function at -O0 if it is marked always_inline.
5513 auto simplifyVariadicCallee
= [](llvm::FunctionType
*CalleeFT
,
5514 llvm::Value
*Ptr
) -> llvm::Function
* {
5515 if (!CalleeFT
->isVarArg())
5518 // Get underlying value if it's a bitcast
5519 if (llvm::ConstantExpr
*CE
= dyn_cast
<llvm::ConstantExpr
>(Ptr
)) {
5520 if (CE
->getOpcode() == llvm::Instruction::BitCast
)
5521 Ptr
= CE
->getOperand(0);
5524 llvm::Function
*OrigFn
= dyn_cast
<llvm::Function
>(Ptr
);
5528 llvm::FunctionType
*OrigFT
= OrigFn
->getFunctionType();
5530 // If the original type is variadic, or if any of the component types
5531 // disagree, we cannot remove the cast.
5532 if (OrigFT
->isVarArg() ||
5533 OrigFT
->getNumParams() != CalleeFT
->getNumParams() ||
5534 OrigFT
->getReturnType() != CalleeFT
->getReturnType())
5537 for (unsigned i
= 0, e
= OrigFT
->getNumParams(); i
!= e
; ++i
)
5538 if (OrigFT
->getParamType(i
) != CalleeFT
->getParamType(i
))
5544 if (llvm::Function
*OrigFn
= simplifyVariadicCallee(IRFuncTy
, CalleePtr
)) {
5546 IRFuncTy
= OrigFn
->getFunctionType();
5549 // 3. Perform the actual call.
5551 // Deactivate any cleanups that we're supposed to do immediately before
5553 if (!CallArgs
.getCleanupsToDeactivate().empty())
5554 deactivateArgCleanupsBeforeCall(*this, CallArgs
);
5556 // Assert that the arguments we computed match up. The IR verifier
5557 // will catch this, but this is a common enough source of problems
5558 // during IRGen changes that it's way better for debugging to catch
5559 // it ourselves here.
5561 assert(IRCallArgs
.size() == IRFuncTy
->getNumParams() || IRFuncTy
->isVarArg());
5562 for (unsigned i
= 0; i
< IRCallArgs
.size(); ++i
) {
5563 // Inalloca argument can have different type.
5564 if (IRFunctionArgs
.hasInallocaArg() &&
5565 i
== IRFunctionArgs
.getInallocaArgNo())
5567 if (i
< IRFuncTy
->getNumParams())
5568 assert(IRCallArgs
[i
]->getType() == IRFuncTy
->getParamType(i
));
5572 // Update the largest vector width if any arguments have vector types.
5573 for (unsigned i
= 0; i
< IRCallArgs
.size(); ++i
)
5574 LargestVectorWidth
= std::max(LargestVectorWidth
,
5575 getMaxVectorWidth(IRCallArgs
[i
]->getType()));
5577 // Compute the calling convention and attributes.
5578 unsigned CallingConv
;
5579 llvm::AttributeList Attrs
;
5580 CGM
.ConstructAttributeList(CalleePtr
->getName(), CallInfo
,
5581 Callee
.getAbstractInfo(), Attrs
, CallingConv
,
5582 /*AttrOnCallSite=*/true,
5585 if (CallingConv
== llvm::CallingConv::X86_VectorCall
&&
5586 getTarget().getTriple().isWindowsArm64EC()) {
5587 CGM
.Error(Loc
, "__vectorcall calling convention is not currently "
5591 if (const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(CurFuncDecl
)) {
5592 if (FD
->hasAttr
<StrictFPAttr
>())
5593 // All calls within a strictfp function are marked strictfp
5594 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP
);
5596 // If -ffast-math is enabled and the function is guarded by an
5597 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5598 // library call instead of the intrinsic.
5599 if (FD
->hasAttr
<OptimizeNoneAttr
>() && getLangOpts().FastMath
)
5600 CGM
.AdjustMemoryAttribute(CalleePtr
->getName(), Callee
.getAbstractInfo(),
5603 // Add call-site nomerge attribute if exists.
5604 if (InNoMergeAttributedStmt
)
5605 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge
);
5607 // Add call-site noinline attribute if exists.
5608 if (InNoInlineAttributedStmt
)
5609 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline
);
5611 // Add call-site always_inline attribute if exists.
5612 if (InAlwaysInlineAttributedStmt
)
5614 Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline
);
5616 // Apply some call-site-specific attributes.
5617 // TODO: work this into building the attribute set.
5619 // Apply always_inline to all calls within flatten functions.
5620 // FIXME: should this really take priority over __try, below?
5621 if (CurCodeDecl
&& CurCodeDecl
->hasAttr
<FlattenAttr
>() &&
5622 !InNoInlineAttributedStmt
&&
5623 !(TargetDecl
&& TargetDecl
->hasAttr
<NoInlineAttr
>())) {
5625 Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline
);
5628 // Disable inlining inside SEH __try blocks.
5629 if (isSEHTryScope()) {
5630 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline
);
5633 // Decide whether to use a call or an invoke.
5635 if (currentFunctionUsesSEHTry()) {
5636 // SEH cares about asynchronous exceptions, so everything can "throw."
5637 CannotThrow
= false;
5638 } else if (isCleanupPadScope() &&
5639 EHPersonality::get(*this).isMSVCXXPersonality()) {
5640 // The MSVC++ personality will implicitly terminate the program if an
5641 // exception is thrown during a cleanup outside of a try/catch.
5642 // We don't need to model anything in IR to get this behavior.
5645 // Otherwise, nounwind call sites will never throw.
5646 CannotThrow
= Attrs
.hasFnAttr(llvm::Attribute::NoUnwind
);
5648 if (auto *FPtr
= dyn_cast
<llvm::Function
>(CalleePtr
))
5649 if (FPtr
->hasFnAttribute(llvm::Attribute::NoUnwind
))
5653 // If we made a temporary, be sure to clean up after ourselves. Note that we
5654 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5655 // pop this cleanup later on. Being eager about this is OK, since this
5656 // temporary is 'invisible' outside of the callee.
5657 if (UnusedReturnSizePtr
)
5658 pushFullExprCleanup
<CallLifetimeEnd
>(NormalEHLifetimeMarker
, SRetAlloca
,
5659 UnusedReturnSizePtr
);
5661 llvm::BasicBlock
*InvokeDest
= CannotThrow
? nullptr : getInvokeDest();
5663 SmallVector
<llvm::OperandBundleDef
, 1> BundleList
=
5664 getBundlesForFunclet(CalleePtr
);
5666 if (SanOpts
.has(SanitizerKind::KCFI
) &&
5667 !isa_and_nonnull
<FunctionDecl
>(TargetDecl
))
5668 EmitKCFIOperandBundle(ConcreteCallee
, BundleList
);
5670 // Add the pointer-authentication bundle.
5671 EmitPointerAuthOperandBundle(ConcreteCallee
.getPointerAuthInfo(), BundleList
);
5673 if (const FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(CurFuncDecl
))
5674 if (FD
->hasAttr
<StrictFPAttr
>())
5675 // All calls within a strictfp function are marked strictfp
5676 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP
);
5678 AssumeAlignedAttrEmitter
AssumeAlignedAttrEmitter(*this, TargetDecl
);
5679 Attrs
= AssumeAlignedAttrEmitter
.TryEmitAsCallSiteAttribute(Attrs
);
5681 AllocAlignAttrEmitter
AllocAlignAttrEmitter(*this, TargetDecl
, CallArgs
);
5682 Attrs
= AllocAlignAttrEmitter
.TryEmitAsCallSiteAttribute(Attrs
);
5684 // Emit the actual call/invoke instruction.
5687 CI
= Builder
.CreateCall(IRFuncTy
, CalleePtr
, IRCallArgs
, BundleList
);
5689 llvm::BasicBlock
*Cont
= createBasicBlock("invoke.cont");
5690 CI
= Builder
.CreateInvoke(IRFuncTy
, CalleePtr
, Cont
, InvokeDest
, IRCallArgs
,
5694 if (CI
->getCalledFunction() && CI
->getCalledFunction()->hasName() &&
5695 CI
->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5696 SetSqrtFPAccuracy(CI
);
5701 // If this is within a function that has the guard(nocf) attribute and is an
5702 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5703 // Control Flow Guard checks should not be added, even if the call is inlined.
5704 if (const auto *FD
= dyn_cast_or_null
<FunctionDecl
>(CurFuncDecl
)) {
5705 if (const auto *A
= FD
->getAttr
<CFGuardAttr
>()) {
5706 if (A
->getGuard() == CFGuardAttr::GuardArg::nocf
&& !CI
->getCalledFunction())
5707 Attrs
= Attrs
.addFnAttribute(getLLVMContext(), "guard_nocf");
5711 // Apply the attributes and calling convention.
5712 CI
->setAttributes(Attrs
);
5713 CI
->setCallingConv(static_cast<llvm::CallingConv::ID
>(CallingConv
));
5715 // Apply various metadata.
5717 if (!CI
->getType()->isVoidTy())
5718 CI
->setName("call");
5720 if (CGM
.shouldEmitConvergenceTokens() && CI
->isConvergent())
5721 CI
= addControlledConvergenceToken(CI
);
5723 // Update largest vector width from the return type.
5724 LargestVectorWidth
=
5725 std::max(LargestVectorWidth
, getMaxVectorWidth(CI
->getType()));
5727 // Insert instrumentation or attach profile metadata at indirect call sites.
5728 // For more details, see the comment before the definition of
5729 // IPVK_IndirectCallTarget in InstrProfData.inc.
5730 if (!CI
->getCalledFunction())
5731 PGO
.valueProfile(Builder
, llvm::IPVK_IndirectCallTarget
,
5734 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5735 // optimizer it can aggressively ignore unwind edges.
5736 if (CGM
.getLangOpts().ObjCAutoRefCount
)
5737 AddObjCARCExceptionMetadata(CI
);
5739 // Set tail call kind if necessary.
5740 if (llvm::CallInst
*Call
= dyn_cast
<llvm::CallInst
>(CI
)) {
5741 if (TargetDecl
&& TargetDecl
->hasAttr
<NotTailCalledAttr
>())
5742 Call
->setTailCallKind(llvm::CallInst::TCK_NoTail
);
5743 else if (IsMustTail
) {
5744 if (getTarget().getTriple().isPPC()) {
5745 if (getTarget().getTriple().isOSAIX())
5746 CGM
.getDiags().Report(Loc
, diag::err_aix_musttail_unsupported
);
5747 else if (!getTarget().hasFeature("pcrelative-memops")) {
5748 if (getTarget().hasFeature("longcall"))
5749 CGM
.getDiags().Report(Loc
, diag::err_ppc_impossible_musttail
) << 0;
5750 else if (Call
->isIndirectCall())
5751 CGM
.getDiags().Report(Loc
, diag::err_ppc_impossible_musttail
) << 1;
5752 else if (isa_and_nonnull
<FunctionDecl
>(TargetDecl
)) {
5753 if (!cast
<FunctionDecl
>(TargetDecl
)->isDefined())
5754 // The undefined callee may be a forward declaration. Without
5755 // knowning all symbols in the module, we won't know the symbol is
5756 // defined or not. Collect all these symbols for later diagnosing.
5757 CGM
.addUndefinedGlobalForTailCall(
5758 {cast
<FunctionDecl
>(TargetDecl
), Loc
});
5760 llvm::GlobalValue::LinkageTypes Linkage
= CGM
.getFunctionLinkage(
5761 GlobalDecl(cast
<FunctionDecl
>(TargetDecl
)));
5762 if (llvm::GlobalValue::isWeakForLinker(Linkage
) ||
5763 llvm::GlobalValue::isDiscardableIfUnused(Linkage
))
5764 CGM
.getDiags().Report(Loc
, diag::err_ppc_impossible_musttail
)
5770 Call
->setTailCallKind(llvm::CallInst::TCK_MustTail
);
5774 // Add metadata for calls to MSAllocator functions
5775 if (getDebugInfo() && TargetDecl
&&
5776 TargetDecl
->hasAttr
<MSAllocatorAttr
>())
5777 getDebugInfo()->addHeapAllocSiteMetadata(CI
, RetTy
->getPointeeType(), Loc
);
5779 // Add metadata if calling an __attribute__((error(""))) or warning fn.
5780 if (TargetDecl
&& TargetDecl
->hasAttr
<ErrorAttr
>()) {
5781 llvm::ConstantInt
*Line
=
5782 llvm::ConstantInt::get(Int64Ty
, Loc
.getRawEncoding());
5783 llvm::ConstantAsMetadata
*MD
= llvm::ConstantAsMetadata::get(Line
);
5784 llvm::MDTuple
*MDT
= llvm::MDNode::get(getLLVMContext(), {MD
});
5785 CI
->setMetadata("srcloc", MDT
);
5788 // 4. Finish the call.
5790 // If the call doesn't return, finish the basic block and clear the
5791 // insertion point; this allows the rest of IRGen to discard
5792 // unreachable code.
5793 if (CI
->doesNotReturn()) {
5794 if (UnusedReturnSizePtr
)
5797 // Strip away the noreturn attribute to better diagnose unreachable UB.
5798 if (SanOpts
.has(SanitizerKind::Unreachable
)) {
5799 // Also remove from function since CallBase::hasFnAttr additionally checks
5800 // attributes of the called function.
5801 if (auto *F
= CI
->getCalledFunction())
5802 F
->removeFnAttr(llvm::Attribute::NoReturn
);
5803 CI
->removeFnAttr(llvm::Attribute::NoReturn
);
5805 // Avoid incompatibility with ASan which relies on the `noreturn`
5806 // attribute to insert handler calls.
5807 if (SanOpts
.hasOneOf(SanitizerKind::Address
|
5808 SanitizerKind::KernelAddress
)) {
5809 SanitizerScope
SanScope(this);
5810 llvm::IRBuilder
<>::InsertPointGuard
IPGuard(Builder
);
5811 Builder
.SetInsertPoint(CI
);
5812 auto *FnType
= llvm::FunctionType::get(CGM
.VoidTy
, /*isVarArg=*/false);
5813 llvm::FunctionCallee Fn
=
5814 CGM
.CreateRuntimeFunction(FnType
, "__asan_handle_no_return");
5815 EmitNounwindRuntimeCall(Fn
);
5819 EmitUnreachable(Loc
);
5820 Builder
.ClearInsertionPoint();
5822 // FIXME: For now, emit a dummy basic block because expr emitters in
5823 // generally are not ready to handle emitting expressions at unreachable
5825 EnsureInsertPoint();
5827 // Return a reasonable RValue.
5828 return GetUndefRValue(RetTy
);
5831 // If this is a musttail call, return immediately. We do not branch to the
5832 // epilogue in this case.
5834 for (auto it
= EHStack
.find(CurrentCleanupScopeDepth
); it
!= EHStack
.end();
5836 EHCleanupScope
*Cleanup
= dyn_cast
<EHCleanupScope
>(&*it
);
5837 if (!(Cleanup
&& Cleanup
->getCleanup()->isRedundantBeforeReturn()))
5838 CGM
.ErrorUnsupported(MustTailCall
, "tail call skipping over cleanups");
5840 if (CI
->getType()->isVoidTy())
5841 Builder
.CreateRetVoid();
5843 Builder
.CreateRet(CI
);
5844 Builder
.ClearInsertionPoint();
5845 EnsureInsertPoint();
5846 return GetUndefRValue(RetTy
);
5849 // Perform the swifterror writeback.
5850 if (swiftErrorTemp
.isValid()) {
5851 llvm::Value
*errorResult
= Builder
.CreateLoad(swiftErrorTemp
);
5852 Builder
.CreateStore(errorResult
, swiftErrorArg
);
5855 // Emit any call-associated writebacks immediately. Arguably this
5856 // should happen after any return-value munging.
5857 if (CallArgs
.hasWritebacks())
5858 emitWritebacks(*this, CallArgs
);
5860 // The stack cleanup for inalloca arguments has to run out of the normal
5861 // lexical order, so deactivate it and run it manually here.
5862 CallArgs
.freeArgumentMemory(*this);
5864 // Extract the return value.
5867 // If the current function is a virtual function pointer thunk, avoid copying
5868 // the return value of the musttail call to a temporary.
5869 if (IsVirtualFunctionPointerThunk
) {
5870 Ret
= RValue::get(CI
);
5873 switch (RetAI
.getKind()) {
5874 case ABIArgInfo::CoerceAndExpand
: {
5875 auto coercionType
= RetAI
.getCoerceAndExpandType();
5877 Address addr
= SRetPtr
.withElementType(coercionType
);
5879 assert(CI
->getType() == RetAI
.getUnpaddedCoerceAndExpandType());
5880 bool requiresExtract
= isa
<llvm::StructType
>(CI
->getType());
5882 unsigned unpaddedIndex
= 0;
5883 for (unsigned i
= 0, e
= coercionType
->getNumElements(); i
!= e
; ++i
) {
5884 llvm::Type
*eltType
= coercionType
->getElementType(i
);
5885 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType
))
5887 Address eltAddr
= Builder
.CreateStructGEP(addr
, i
);
5888 llvm::Value
*elt
= CI
;
5889 if (requiresExtract
)
5890 elt
= Builder
.CreateExtractValue(elt
, unpaddedIndex
++);
5892 assert(unpaddedIndex
== 0);
5893 Builder
.CreateStore(elt
, eltAddr
);
5898 case ABIArgInfo::InAlloca
:
5899 case ABIArgInfo::Indirect
: {
5900 RValue ret
= convertTempToRValue(SRetPtr
, RetTy
, SourceLocation());
5901 if (UnusedReturnSizePtr
)
5906 case ABIArgInfo::Ignore
:
5907 // If we are ignoring an argument that had a result, make sure to
5908 // construct the appropriate return value for our caller.
5909 return GetUndefRValue(RetTy
);
5911 case ABIArgInfo::Extend
:
5912 case ABIArgInfo::Direct
: {
5913 llvm::Type
*RetIRTy
= ConvertType(RetTy
);
5914 if (RetAI
.getCoerceToType() == RetIRTy
&&
5915 RetAI
.getDirectOffset() == 0) {
5916 switch (getEvaluationKind(RetTy
)) {
5918 llvm::Value
*Real
= Builder
.CreateExtractValue(CI
, 0);
5919 llvm::Value
*Imag
= Builder
.CreateExtractValue(CI
, 1);
5920 return RValue::getComplex(std::make_pair(Real
, Imag
));
5925 // If the argument doesn't match, perform a bitcast to coerce it.
5926 // This can happen due to trivial type mismatches.
5927 llvm::Value
*V
= CI
;
5928 if (V
->getType() != RetIRTy
)
5929 V
= Builder
.CreateBitCast(V
, RetIRTy
);
5930 return RValue::get(V
);
5935 // If coercing a fixed vector from a scalable vector for ABI
5936 // compatibility, and the types match, use the llvm.vector.extract
5937 // intrinsic to perform the conversion.
5938 if (auto *FixedDstTy
= dyn_cast
<llvm::FixedVectorType
>(RetIRTy
)) {
5939 llvm::Value
*V
= CI
;
5940 if (auto *ScalableSrcTy
=
5941 dyn_cast
<llvm::ScalableVectorType
>(V
->getType())) {
5942 if (FixedDstTy
->getElementType() ==
5943 ScalableSrcTy
->getElementType()) {
5944 llvm::Value
*Zero
= llvm::Constant::getNullValue(CGM
.Int64Ty
);
5945 V
= Builder
.CreateExtractVector(FixedDstTy
, V
, Zero
,
5947 return RValue::get(V
);
5952 Address DestPtr
= ReturnValue
.getValue();
5953 bool DestIsVolatile
= ReturnValue
.isVolatile();
5955 getContext().getTypeInfoDataSizeInChars(RetTy
).Width
.getQuantity();
5957 if (!DestPtr
.isValid()) {
5958 DestPtr
= CreateMemTemp(RetTy
, "coerce");
5959 DestIsVolatile
= false;
5960 DestSize
= getContext().getTypeSizeInChars(RetTy
).getQuantity();
5963 // An empty record can overlap other data (if declared with
5964 // no_unique_address); omit the store for such types - as there is no
5965 // actual data to store.
5966 if (!isEmptyRecord(getContext(), RetTy
, true)) {
5967 // If the value is offset in memory, apply the offset now.
5968 Address StorePtr
= emitAddressAtOffset(*this, DestPtr
, RetAI
);
5971 llvm::TypeSize::getFixed(DestSize
- RetAI
.getDirectOffset()),
5975 return convertTempToRValue(DestPtr
, RetTy
, SourceLocation());
5978 case ABIArgInfo::Expand
:
5979 case ABIArgInfo::IndirectAliased
:
5980 llvm_unreachable("Invalid ABI kind for return argument");
5983 llvm_unreachable("Unhandled ABIArgInfo::Kind");
5987 // Emit the assume_aligned check on the return value.
5988 if (Ret
.isScalar() && TargetDecl
) {
5989 AssumeAlignedAttrEmitter
.EmitAsAnAssumption(Loc
, RetTy
, Ret
);
5990 AllocAlignAttrEmitter
.EmitAsAnAssumption(Loc
, RetTy
, Ret
);
5993 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5994 // we can't use the full cleanup mechanism.
5995 for (CallLifetimeEnd
&LifetimeEnd
: CallLifetimeEndAfterCall
)
5996 LifetimeEnd
.Emit(*this, /*Flags=*/{});
5998 if (!ReturnValue
.isExternallyDestructed() &&
5999 RetTy
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
6000 pushDestroy(QualType::DK_nontrivial_c_struct
, Ret
.getAggregateAddress(),
6006 CGCallee
CGCallee::prepareConcreteCallee(CodeGenFunction
&CGF
) const {
6008 const CallExpr
*CE
= getVirtualCallExpr();
6009 return CGF
.CGM
.getCXXABI().getVirtualFunctionPointer(
6010 CGF
, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
6011 CE
? CE
->getBeginLoc() : SourceLocation());
6017 /* VarArg handling */
6019 RValue
CodeGenFunction::EmitVAArg(VAArgExpr
*VE
, Address
&VAListAddr
,
6020 AggValueSlot Slot
) {
6021 VAListAddr
= VE
->isMicrosoftABI() ? EmitMSVAListRef(VE
->getSubExpr())
6022 : EmitVAListRef(VE
->getSubExpr());
6023 QualType Ty
= VE
->getType();
6024 if (VE
->isMicrosoftABI())
6025 return CGM
.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr
, Ty
, Slot
);
6026 return CGM
.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr
, Ty
, Slot
);