Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGCall.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp
1//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCall.h"
15#include "ABIInfo.h"
16#include "CGBlocks.h"
17#include "CGCXXABI.h"
18#include "CGCleanup.h"
19#include "CGRecordLayout.h"
20#include "CodeGenFunction.h"
21#include "CodeGenModule.h"
22#include "TargetInfo.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/Basic/CodeGenOptions.h"
28#include "clang/Basic/TargetBuiltins.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/Attributes.h"
35#include "llvm/IR/CallingConv.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/Transforms/Utils/Local.h"
41using namespace clang;
42using namespace CodeGen;
43
44/***/
45
46unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
47 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
51 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
52 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
53 case CC_Win64: return llvm::CallingConv::Win64;
54 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
55 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
57 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
58 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
61 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
62 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
63 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
64 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
65 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
66 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
67 case CC_Swift: return llvm::CallingConv::Swift;
68 }
69}
70
71/// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
72/// qualification. Either or both of RD and MD may be null. A null RD indicates
73/// that there is no meaningful 'this' type, and a null MD can occur when
74/// calling a method pointer.
75CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
76 const CXXMethodDecl *MD) {
77 QualType RecTy;
78 if (RD)
79 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
80 else
81 RecTy = Context.VoidTy;
82
83 if (MD)
84 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
85 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
86}
87
88/// Returns the canonical formal type of the given C++ method.
89static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
90 return MD->getType()->getCanonicalTypeUnqualified()
91 .getAs<FunctionProtoType>();
92}
93
94/// Returns the "extra-canonicalized" return type, which discards
95/// qualifiers on the return type. Codegen doesn't care about them,
96/// and it makes ABI code a little easier to be able to assume that
97/// all parameter and return types are top-level unqualified.
98static CanQualType GetReturnType(QualType RetTy) {
99 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
100}
101
102/// Arrange the argument and result information for a value of the given
103/// unprototyped freestanding function type.
104const CGFunctionInfo &
105CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
106 // When translating an unprototyped function type, always use a
107 // variadic type.
108 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
109 /*instanceMethod=*/false,
110 /*chainCall=*/false, None,
111 FTNP->getExtInfo(), {}, RequiredArgs(0));
112}
113
114static void addExtParameterInfosForCall(
115 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
116 const FunctionProtoType *proto,
117 unsigned prefixArgs,
118 unsigned totalArgs) {
119 assert(proto->hasExtParameterInfos())((proto->hasExtParameterInfos()) ? static_cast<void>
(0) : __assert_fail ("proto->hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 119, __PRETTY_FUNCTION__))
;
120 assert(paramInfos.size() <= prefixArgs)((paramInfos.size() <= prefixArgs) ? static_cast<void>
(0) : __assert_fail ("paramInfos.size() <= prefixArgs", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 120, __PRETTY_FUNCTION__))
;
121 assert(proto->getNumParams() + prefixArgs <= totalArgs)((proto->getNumParams() + prefixArgs <= totalArgs) ? static_cast
<void> (0) : __assert_fail ("proto->getNumParams() + prefixArgs <= totalArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 121, __PRETTY_FUNCTION__))
;
122
123 paramInfos.reserve(totalArgs);
124
125 // Add default infos for any prefix args that don't already have infos.
126 paramInfos.resize(prefixArgs);
127
128 // Add infos for the prototype.
129 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
130 paramInfos.push_back(ParamInfo);
131 // pass_object_size params have no parameter info.
132 if (ParamInfo.hasPassObjectSize())
133 paramInfos.emplace_back();
134 }
135
136 assert(paramInfos.size() <= totalArgs &&((paramInfos.size() <= totalArgs && "Did we forget to insert pass_object_size args?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 137, __PRETTY_FUNCTION__))
137 "Did we forget to insert pass_object_size args?")((paramInfos.size() <= totalArgs && "Did we forget to insert pass_object_size args?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.size() <= totalArgs && \"Did we forget to insert pass_object_size args?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 137, __PRETTY_FUNCTION__))
;
138 // Add default infos for the variadic and/or suffix arguments.
139 paramInfos.resize(totalArgs);
140}
141
142/// Adds the formal parameters in FPT to the given prefix. If any parameter in
143/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
144static void appendParameterTypes(const CodeGenTypes &CGT,
145 SmallVectorImpl<CanQualType> &prefix,
146 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
147 CanQual<FunctionProtoType> FPT) {
148 // Fast path: don't touch param info if we don't need to.
149 if (!FPT->hasExtParameterInfos()) {
150 assert(paramInfos.empty() &&((paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 151, __PRETTY_FUNCTION__))
151 "We have paramInfos, but the prototype doesn't?")((paramInfos.empty() && "We have paramInfos, but the prototype doesn't?"
) ? static_cast<void> (0) : __assert_fail ("paramInfos.empty() && \"We have paramInfos, but the prototype doesn't?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 151, __PRETTY_FUNCTION__))
;
152 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
153 return;
154 }
155
156 unsigned PrefixSize = prefix.size();
157 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
158 // parameters; the only thing that can change this is the presence of
159 // pass_object_size. So, we preallocate for the common case.
160 prefix.reserve(prefix.size() + FPT->getNumParams());
161
162 auto ExtInfos = FPT->getExtParameterInfos();
163 assert(ExtInfos.size() == FPT->getNumParams())((ExtInfos.size() == FPT->getNumParams()) ? static_cast<
void> (0) : __assert_fail ("ExtInfos.size() == FPT->getNumParams()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 163, __PRETTY_FUNCTION__))
;
164 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
165 prefix.push_back(FPT->getParamType(I));
166 if (ExtInfos[I].hasPassObjectSize())
167 prefix.push_back(CGT.getContext().getSizeType());
168 }
169
170 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
171 prefix.size());
172}
173
174/// Arrange the LLVM function layout for a value of the given function
175/// type, on top of any implicit parameters already stored.
176static const CGFunctionInfo &
177arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
178 SmallVectorImpl<CanQualType> &prefix,
179 CanQual<FunctionProtoType> FTP) {
180 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
181 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
182 // FIXME: Kill copy.
183 appendParameterTypes(CGT, prefix, paramInfos, FTP);
184 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
185
186 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
187 /*chainCall=*/false, prefix,
188 FTP->getExtInfo(), paramInfos,
189 Required);
190}
191
192/// Arrange the argument and result information for a value of the
193/// given freestanding function type.
194const CGFunctionInfo &
195CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
196 SmallVector<CanQualType, 16> argTypes;
197 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
198 FTP);
199}
200
201static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
202 // Set the appropriate calling convention for the Function.
203 if (D->hasAttr<StdCallAttr>())
204 return CC_X86StdCall;
205
206 if (D->hasAttr<FastCallAttr>())
207 return CC_X86FastCall;
208
209 if (D->hasAttr<RegCallAttr>())
210 return CC_X86RegCall;
211
212 if (D->hasAttr<ThisCallAttr>())
213 return CC_X86ThisCall;
214
215 if (D->hasAttr<VectorCallAttr>())
216 return CC_X86VectorCall;
217
218 if (D->hasAttr<PascalAttr>())
219 return CC_X86Pascal;
220
221 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
222 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
223
224 if (D->hasAttr<AArch64VectorPcsAttr>())
225 return CC_AArch64VectorCall;
226
227 if (D->hasAttr<IntelOclBiccAttr>())
228 return CC_IntelOclBicc;
229
230 if (D->hasAttr<MSABIAttr>())
231 return IsWindows ? CC_C : CC_Win64;
232
233 if (D->hasAttr<SysVABIAttr>())
234 return IsWindows ? CC_X86_64SysV : CC_C;
235
236 if (D->hasAttr<PreserveMostAttr>())
237 return CC_PreserveMost;
238
239 if (D->hasAttr<PreserveAllAttr>())
240 return CC_PreserveAll;
241
242 return CC_C;
243}
244
245/// Arrange the argument and result information for a call to an
246/// unknown C++ non-static member function of the given abstract type.
247/// (A null RD means we don't have any meaningful "this" argument type,
248/// so fall back to a generic pointer type).
249/// The member function must be an ordinary function, i.e. not a
250/// constructor or destructor.
251const CGFunctionInfo &
252CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
253 const FunctionProtoType *FTP,
254 const CXXMethodDecl *MD) {
255 SmallVector<CanQualType, 16> argTypes;
256
257 // Add the 'this' pointer.
258 argTypes.push_back(DeriveThisType(RD, MD));
259
260 return ::arrangeLLVMFunctionInfo(
261 *this, true, argTypes,
262 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
263}
264
265/// Set calling convention for CUDA/HIP kernel.
266static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
267 const FunctionDecl *FD) {
268 if (FD->hasAttr<CUDAGlobalAttr>()) {
269 const FunctionType *FT = FTy->getAs<FunctionType>();
270 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
271 FTy = FT->getCanonicalTypeUnqualified();
272 }
273}
274
275/// Arrange the argument and result information for a declaration or
276/// definition of the given C++ non-static member function. The
277/// member function must be an ordinary function, i.e. not a
278/// constructor or destructor.
279const CGFunctionInfo &
280CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
281 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!")((!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(MD) && \"wrong method for constructors!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 281, __PRETTY_FUNCTION__))
;
282 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!")((!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXDestructorDecl>(MD) && \"wrong method for destructors!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 282, __PRETTY_FUNCTION__))
;
283
284 CanQualType FT = GetFormalType(MD).getAs<Type>();
285 setCUDAKernelCallingConvention(FT, CGM, MD);
286 auto prototype = FT.getAs<FunctionProtoType>();
287
288 if (MD->isInstance()) {
289 // The abstract case is perfectly fine.
290 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
291 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
292 }
293
294 return arrangeFreeFunctionType(prototype);
295}
296
297bool CodeGenTypes::inheritingCtorHasParams(
298 const InheritedConstructor &Inherited, CXXCtorType Type) {
299 // Parameters are unnecessary if we're constructing a base class subobject
300 // and the inherited constructor lives in a virtual base.
301 return Type == Ctor_Complete ||
302 !Inherited.getShadowDecl()->constructsVirtualBase() ||
303 !Target.getCXXABI().hasConstructorVariants();
304}
305
306const CGFunctionInfo &
307CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
308 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
309
310 SmallVector<CanQualType, 16> argTypes;
311 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
312 argTypes.push_back(DeriveThisType(MD->getParent(), MD));
313
314 bool PassParams = true;
315
316 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
317 // A base class inheriting constructor doesn't get forwarded arguments
318 // needed to construct a virtual base (or base class thereof).
319 if (auto Inherited = CD->getInheritedConstructor())
320 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
321 }
322
323 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
324
325 // Add the formal parameters.
326 if (PassParams)
327 appendParameterTypes(*this, argTypes, paramInfos, FTP);
328
329 CGCXXABI::AddedStructorArgCounts AddedArgs =
330 TheCXXABI.buildStructorSignature(GD, argTypes);
331 if (!paramInfos.empty()) {
332 // Note: prefix implies after the first param.
333 if (AddedArgs.Prefix)
334 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
335 FunctionProtoType::ExtParameterInfo{});
336 if (AddedArgs.Suffix)
337 paramInfos.append(AddedArgs.Suffix,
338 FunctionProtoType::ExtParameterInfo{});
339 }
340
341 RequiredArgs required =
342 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
343 : RequiredArgs::All);
344
345 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
346 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
347 ? argTypes.front()
348 : TheCXXABI.hasMostDerivedReturn(GD)
349 ? CGM.getContext().VoidPtrTy
350 : Context.VoidTy;
351 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
352 /*chainCall=*/false, argTypes, extInfo,
353 paramInfos, required);
354}
355
356static SmallVector<CanQualType, 16>
357getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
358 SmallVector<CanQualType, 16> argTypes;
359 for (auto &arg : args)
360 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
361 return argTypes;
362}
363
364static SmallVector<CanQualType, 16>
365getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
366 SmallVector<CanQualType, 16> argTypes;
367 for (auto &arg : args)
368 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
369 return argTypes;
370}
371
372static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
373getExtParameterInfosForCall(const FunctionProtoType *proto,
374 unsigned prefixArgs, unsigned totalArgs) {
375 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
376 if (proto->hasExtParameterInfos()) {
377 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
378 }
379 return result;
380}
381
382/// Arrange a call to a C++ method, passing the given arguments.
383///
384/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
385/// parameter.
386/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
387/// args.
388/// PassProtoArgs indicates whether `args` has args for the parameters in the
389/// given CXXConstructorDecl.
390const CGFunctionInfo &
391CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
392 const CXXConstructorDecl *D,
393 CXXCtorType CtorKind,
394 unsigned ExtraPrefixArgs,
395 unsigned ExtraSuffixArgs,
396 bool PassProtoArgs) {
397 // FIXME: Kill copy.
398 SmallVector<CanQualType, 16> ArgTypes;
399 for (const auto &Arg : args)
400 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
401
402 // +1 for implicit this, which should always be args[0].
403 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
404
405 CanQual<FunctionProtoType> FPT = GetFormalType(D);
406 RequiredArgs Required = PassProtoArgs
407 ? RequiredArgs::forPrototypePlus(
408 FPT, TotalPrefixArgs + ExtraSuffixArgs)
409 : RequiredArgs::All;
410
411 GlobalDecl GD(D, CtorKind);
412 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
413 ? ArgTypes.front()
414 : TheCXXABI.hasMostDerivedReturn(GD)
415 ? CGM.getContext().VoidPtrTy
416 : Context.VoidTy;
417
418 FunctionType::ExtInfo Info = FPT->getExtInfo();
419 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
420 // If the prototype args are elided, we should only have ABI-specific args,
421 // which never have param info.
422 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
423 // ABI-specific suffix arguments are treated the same as variadic arguments.
424 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
425 ArgTypes.size());
426 }
427 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
428 /*chainCall=*/false, ArgTypes, Info,
429 ParamInfos, Required);
430}
431
432/// Arrange the argument and result information for the declaration or
433/// definition of the given function.
434const CGFunctionInfo &
435CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
436 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
437 if (MD->isInstance())
438 return arrangeCXXMethodDeclaration(MD);
439
440 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
441
442 assert(isa<FunctionType>(FTy))((isa<FunctionType>(FTy)) ? static_cast<void> (0)
: __assert_fail ("isa<FunctionType>(FTy)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 442, __PRETTY_FUNCTION__))
;
443 setCUDAKernelCallingConvention(FTy, CGM, FD);
444
445 // When declaring a function without a prototype, always use a
446 // non-variadic type.
447 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
448 return arrangeLLVMFunctionInfo(
449 noProto->getReturnType(), /*instanceMethod=*/false,
450 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
451 }
452
453 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
454}
455
456/// Arrange the argument and result information for the declaration or
457/// definition of an Objective-C method.
458const CGFunctionInfo &
459CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
460 // It happens that this is the same as a call with no optional
461 // arguments, except also using the formal 'self' type.
462 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
463}
464
465/// Arrange the argument and result information for the function type
466/// through which to perform a send to the given Objective-C method,
467/// using the given receiver type. The receiver type is not always
468/// the 'self' type of the method or even an Objective-C pointer type.
469/// This is *not* the right method for actually performing such a
470/// message send, due to the possibility of optional arguments.
471const CGFunctionInfo &
472CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
473 QualType receiverType) {
474 SmallVector<CanQualType, 16> argTys;
475 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
476 argTys.push_back(Context.getCanonicalParamType(receiverType));
477 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
478 // FIXME: Kill copy?
479 for (const auto *I : MD->parameters()) {
480 argTys.push_back(Context.getCanonicalParamType(I->getType()));
481 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
482 I->hasAttr<NoEscapeAttr>());
483 extParamInfos.push_back(extParamInfo);
484 }
485
486 FunctionType::ExtInfo einfo;
487 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
488 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
489
490 if (getContext().getLangOpts().ObjCAutoRefCount &&
491 MD->hasAttr<NSReturnsRetainedAttr>())
492 einfo = einfo.withProducesResult(true);
493
494 RequiredArgs required =
495 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
496
497 return arrangeLLVMFunctionInfo(
498 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
499 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
500}
501
502const CGFunctionInfo &
503CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
504 const CallArgList &args) {
505 auto argTypes = getArgTypesForCall(Context, args);
506 FunctionType::ExtInfo einfo;
507
508 return arrangeLLVMFunctionInfo(
509 GetReturnType(returnType), /*instanceMethod=*/false,
510 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
511}
512
513const CGFunctionInfo &
514CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
515 // FIXME: Do we need to handle ObjCMethodDecl?
516 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
517
518 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
519 isa<CXXDestructorDecl>(GD.getDecl()))
520 return arrangeCXXStructorDeclaration(GD);
521
522 return arrangeFunctionDeclaration(FD);
523}
524
525/// Arrange a thunk that takes 'this' as the first parameter followed by
526/// varargs. Return a void pointer, regardless of the actual return type.
527/// The body of the thunk will end in a musttail call to a function of the
528/// correct type, and the caller will bitcast the function to the correct
529/// prototype.
530const CGFunctionInfo &
531CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
532 assert(MD->isVirtual() && "only methods have thunks")((MD->isVirtual() && "only methods have thunks") ?
static_cast<void> (0) : __assert_fail ("MD->isVirtual() && \"only methods have thunks\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 532, __PRETTY_FUNCTION__))
;
533 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
534 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
535 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
536 /*chainCall=*/false, ArgTys,
537 FTP->getExtInfo(), {}, RequiredArgs(1));
538}
539
540const CGFunctionInfo &
541CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
542 CXXCtorType CT) {
543 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure)((CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure) ? static_cast
<void> (0) : __assert_fail ("CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 543, __PRETTY_FUNCTION__))
;
544
545 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
546 SmallVector<CanQualType, 2> ArgTys;
547 const CXXRecordDecl *RD = CD->getParent();
548 ArgTys.push_back(DeriveThisType(RD, CD));
549 if (CT == Ctor_CopyingClosure)
550 ArgTys.push_back(*FTP->param_type_begin());
551 if (RD->getNumVBases() > 0)
552 ArgTys.push_back(Context.IntTy);
553 CallingConv CC = Context.getDefaultCallingConvention(
554 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
555 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
556 /*chainCall=*/false, ArgTys,
557 FunctionType::ExtInfo(CC), {},
558 RequiredArgs::All);
559}
560
561/// Arrange a call as unto a free function, except possibly with an
562/// additional number of formal parameters considered required.
563static const CGFunctionInfo &
564arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
565 CodeGenModule &CGM,
566 const CallArgList &args,
567 const FunctionType *fnType,
568 unsigned numExtraRequiredArgs,
569 bool chainCall) {
570 assert(args.size() >= numExtraRequiredArgs)((args.size() >= numExtraRequiredArgs) ? static_cast<void
> (0) : __assert_fail ("args.size() >= numExtraRequiredArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 570, __PRETTY_FUNCTION__))
;
571
572 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
573
574 // In most cases, there are no optional arguments.
575 RequiredArgs required = RequiredArgs::All;
576
577 // If we have a variadic prototype, the required arguments are the
578 // extra prefix plus the arguments in the prototype.
579 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
580 if (proto->isVariadic())
581 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
582
583 if (proto->hasExtParameterInfos())
584 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
585 args.size());
586
587 // If we don't have a prototype at all, but we're supposed to
588 // explicitly use the variadic convention for unprototyped calls,
589 // treat all of the arguments as required but preserve the nominal
590 // possibility of variadics.
591 } else if (CGM.getTargetCodeGenInfo()
592 .isNoProtoCallVariadic(args,
593 cast<FunctionNoProtoType>(fnType))) {
594 required = RequiredArgs(args.size());
595 }
596
597 // FIXME: Kill copy.
598 SmallVector<CanQualType, 16> argTypes;
599 for (const auto &arg : args)
600 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
601 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
602 /*instanceMethod=*/false, chainCall,
603 argTypes, fnType->getExtInfo(), paramInfos,
604 required);
605}
606
607/// Figure out the rules for calling a function with the given formal
608/// type using the given arguments. The arguments are necessary
609/// because the function might be unprototyped, in which case it's
610/// target-dependent in crazy ways.
611const CGFunctionInfo &
612CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
613 const FunctionType *fnType,
614 bool chainCall) {
615 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
616 chainCall ? 1 : 0, chainCall);
617}
618
619/// A block function is essentially a free function with an
620/// extra implicit argument.
621const CGFunctionInfo &
622CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
623 const FunctionType *fnType) {
624 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
625 /*chainCall=*/false);
626}
627
628const CGFunctionInfo &
629CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
630 const FunctionArgList &params) {
631 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
632 auto argTypes = getArgTypesForDeclaration(Context, params);
633
634 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
635 /*instanceMethod*/ false, /*chainCall*/ false,
636 argTypes, proto->getExtInfo(), paramInfos,
637 RequiredArgs::forPrototypePlus(proto, 1));
638}
639
640const CGFunctionInfo &
641CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
642 const CallArgList &args) {
643 // FIXME: Kill copy.
644 SmallVector<CanQualType, 16> argTypes;
645 for (const auto &Arg : args)
646 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
647 return arrangeLLVMFunctionInfo(
648 GetReturnType(resultType), /*instanceMethod=*/false,
649 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
650 /*paramInfos=*/ {}, RequiredArgs::All);
651}
652
653const CGFunctionInfo &
654CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
655 const FunctionArgList &args) {
656 auto argTypes = getArgTypesForDeclaration(Context, args);
657
658 return arrangeLLVMFunctionInfo(
659 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
660 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
661}
662
663const CGFunctionInfo &
664CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
665 ArrayRef<CanQualType> argTypes) {
666 return arrangeLLVMFunctionInfo(
667 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
668 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
669}
670
671/// Arrange a call to a C++ method, passing the given arguments.
672///
673/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
674/// does not count `this`.
675const CGFunctionInfo &
676CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
677 const FunctionProtoType *proto,
678 RequiredArgs required,
679 unsigned numPrefixArgs) {
680 assert(numPrefixArgs + 1 <= args.size() &&((numPrefixArgs + 1 <= args.size() && "Emitting a call with less args than the required prefix?"
) ? static_cast<void> (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 681, __PRETTY_FUNCTION__))
681 "Emitting a call with less args than the required prefix?")((numPrefixArgs + 1 <= args.size() && "Emitting a call with less args than the required prefix?"
) ? static_cast<void> (0) : __assert_fail ("numPrefixArgs + 1 <= args.size() && \"Emitting a call with less args than the required prefix?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 681, __PRETTY_FUNCTION__))
;
682 // Add one to account for `this`. It's a bit awkward here, but we don't count
683 // `this` in similar places elsewhere.
684 auto paramInfos =
685 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
686
687 // FIXME: Kill copy.
688 auto argTypes = getArgTypesForCall(Context, args);
689
690 FunctionType::ExtInfo info = proto->getExtInfo();
691 return arrangeLLVMFunctionInfo(
692 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
693 /*chainCall=*/false, argTypes, info, paramInfos, required);
694}
695
696const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
697 return arrangeLLVMFunctionInfo(
698 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
699 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
700}
701
702const CGFunctionInfo &
703CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
704 const CallArgList &args) {
705 assert(signature.arg_size() <= args.size())((signature.arg_size() <= args.size()) ? static_cast<void
> (0) : __assert_fail ("signature.arg_size() <= args.size()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 705, __PRETTY_FUNCTION__))
;
706 if (signature.arg_size() == args.size())
707 return signature;
708
709 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
710 auto sigParamInfos = signature.getExtParameterInfos();
711 if (!sigParamInfos.empty()) {
712 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
713 paramInfos.resize(args.size());
714 }
715
716 auto argTypes = getArgTypesForCall(Context, args);
717
718 assert(signature.getRequiredArgs().allowsOptionalArgs())((signature.getRequiredArgs().allowsOptionalArgs()) ? static_cast
<void> (0) : __assert_fail ("signature.getRequiredArgs().allowsOptionalArgs()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 718, __PRETTY_FUNCTION__))
;
719 return arrangeLLVMFunctionInfo(signature.getReturnType(),
720 signature.isInstanceMethod(),
721 signature.isChainCall(),
722 argTypes,
723 signature.getExtInfo(),
724 paramInfos,
725 signature.getRequiredArgs());
726}
727
728namespace clang {
729namespace CodeGen {
730void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
731}
732}
733
734/// Arrange the argument and result information for an abstract value
735/// of a given function type. This is the method which all of the
736/// above functions ultimately defer to.
737const CGFunctionInfo &
738CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
739 bool instanceMethod,
740 bool chainCall,
741 ArrayRef<CanQualType> argTypes,
742 FunctionType::ExtInfo info,
743 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
744 RequiredArgs required) {
745 assert(llvm::all_of(argTypes,((llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam
(); })) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 746, __PRETTY_FUNCTION__))
746 [](CanQualType T) { return T.isCanonicalAsParam(); }))((llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam
(); })) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(argTypes, [](CanQualType T) { return T.isCanonicalAsParam(); })"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 746, __PRETTY_FUNCTION__))
;
747
748 // Lookup or create unique function info.
749 llvm::FoldingSetNodeID ID;
750 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
751 required, resultType, argTypes);
752
753 void *insertPos = nullptr;
754 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
755 if (FI)
756 return *FI;
757
758 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
759
760 // Construct the function info. We co-allocate the ArgInfos.
761 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
762 paramInfos, resultType, argTypes, required);
763 FunctionInfos.InsertNode(FI, insertPos);
764
765 bool inserted = FunctionsBeingProcessed.insert(FI).second;
766 (void)inserted;
767 assert(inserted && "Recursively being processed?")((inserted && "Recursively being processed?") ? static_cast
<void> (0) : __assert_fail ("inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 767, __PRETTY_FUNCTION__))
;
768
769 // Compute ABI information.
770 if (CC == llvm::CallingConv::SPIR_KERNEL) {
771 // Force target independent argument handling for the host visible
772 // kernel functions.
773 computeSPIRKernelABIInfo(CGM, *FI);
774 } else if (info.getCC() == CC_Swift) {
775 swiftcall::computeABIInfo(CGM, *FI);
776 } else {
777 getABIInfo().computeInfo(*FI);
778 }
779
780 // Loop over all of the computed argument and return value info. If any of
781 // them are direct or extend without a specified coerce type, specify the
782 // default now.
783 ABIArgInfo &retInfo = FI->getReturnInfo();
784 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
785 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
786
787 for (auto &I : FI->arguments())
788 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
789 I.info.setCoerceToType(ConvertType(I.type));
790
791 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
792 assert(erased && "Not in set?")((erased && "Not in set?") ? static_cast<void> (
0) : __assert_fail ("erased && \"Not in set?\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 792, __PRETTY_FUNCTION__))
;
793
794 return *FI;
795}
796
797CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
798 bool instanceMethod,
799 bool chainCall,
800 const FunctionType::ExtInfo &info,
801 ArrayRef<ExtParameterInfo> paramInfos,
802 CanQualType resultType,
803 ArrayRef<CanQualType> argTypes,
804 RequiredArgs required) {
805 assert(paramInfos.empty() || paramInfos.size() == argTypes.size())((paramInfos.empty() || paramInfos.size() == argTypes.size())
? static_cast<void> (0) : __assert_fail ("paramInfos.empty() || paramInfos.size() == argTypes.size()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 805, __PRETTY_FUNCTION__))
;
806 assert(!required.allowsOptionalArgs() ||((!required.allowsOptionalArgs() || required.getNumRequiredArgs
() <= argTypes.size()) ? static_cast<void> (0) : __assert_fail
("!required.allowsOptionalArgs() || required.getNumRequiredArgs() <= argTypes.size()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 807, __PRETTY_FUNCTION__))
807 required.getNumRequiredArgs() <= argTypes.size())((!required.allowsOptionalArgs() || required.getNumRequiredArgs
() <= argTypes.size()) ? static_cast<void> (0) : __assert_fail
("!required.allowsOptionalArgs() || required.getNumRequiredArgs() <= argTypes.size()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 807, __PRETTY_FUNCTION__))
;
808
809 void *buffer =
810 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
811 argTypes.size() + 1, paramInfos.size()));
812
813 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
814 FI->CallingConvention = llvmCC;
815 FI->EffectiveCallingConvention = llvmCC;
816 FI->ASTCallingConvention = info.getCC();
817 FI->InstanceMethod = instanceMethod;
818 FI->ChainCall = chainCall;
819 FI->CmseNSCall = info.getCmseNSCall();
820 FI->NoReturn = info.getNoReturn();
821 FI->ReturnsRetained = info.getProducesResult();
822 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
823 FI->NoCfCheck = info.getNoCfCheck();
824 FI->Required = required;
825 FI->HasRegParm = info.getHasRegParm();
826 FI->RegParm = info.getRegParm();
827 FI->ArgStruct = nullptr;
828 FI->ArgStructAlign = 0;
829 FI->NumArgs = argTypes.size();
830 FI->HasExtParameterInfos = !paramInfos.empty();
831 FI->getArgsBuffer()[0].type = resultType;
832 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
833 FI->getArgsBuffer()[i + 1].type = argTypes[i];
834 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
835 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
836 return FI;
837}
838
839/***/
840
841namespace {
842// ABIArgInfo::Expand implementation.
843
844// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
845struct TypeExpansion {
846 enum TypeExpansionKind {
847 // Elements of constant arrays are expanded recursively.
848 TEK_ConstantArray,
849 // Record fields are expanded recursively (but if record is a union, only
850 // the field with the largest size is expanded).
851 TEK_Record,
852 // For complex types, real and imaginary parts are expanded recursively.
853 TEK_Complex,
854 // All other types are not expandable.
855 TEK_None
856 };
857
858 const TypeExpansionKind Kind;
859
860 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
861 virtual ~TypeExpansion() {}
862};
863
864struct ConstantArrayExpansion : TypeExpansion {
865 QualType EltTy;
866 uint64_t NumElts;
867
868 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
869 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
870 static bool classof(const TypeExpansion *TE) {
871 return TE->Kind == TEK_ConstantArray;
872 }
873};
874
875struct RecordExpansion : TypeExpansion {
876 SmallVector<const CXXBaseSpecifier *, 1> Bases;
877
878 SmallVector<const FieldDecl *, 1> Fields;
879
880 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
881 SmallVector<const FieldDecl *, 1> &&Fields)
882 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
883 Fields(std::move(Fields)) {}
884 static bool classof(const TypeExpansion *TE) {
885 return TE->Kind == TEK_Record;
886 }
887};
888
889struct ComplexExpansion : TypeExpansion {
890 QualType EltTy;
891
892 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
893 static bool classof(const TypeExpansion *TE) {
894 return TE->Kind == TEK_Complex;
895 }
896};
897
898struct NoExpansion : TypeExpansion {
899 NoExpansion() : TypeExpansion(TEK_None) {}
900 static bool classof(const TypeExpansion *TE) {
901 return TE->Kind == TEK_None;
902 }
903};
904} // namespace
905
906static std::unique_ptr<TypeExpansion>
907getTypeExpansion(QualType Ty, const ASTContext &Context) {
908 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
909 return std::make_unique<ConstantArrayExpansion>(
910 AT->getElementType(), AT->getSize().getZExtValue());
911 }
912 if (const RecordType *RT = Ty->getAs<RecordType>()) {
913 SmallVector<const CXXBaseSpecifier *, 1> Bases;
914 SmallVector<const FieldDecl *, 1> Fields;
915 const RecordDecl *RD = RT->getDecl();
916 assert(!RD->hasFlexibleArrayMember() &&((!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."
) ? static_cast<void> (0) : __assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 917, __PRETTY_FUNCTION__))
917 "Cannot expand structure with flexible array.")((!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."
) ? static_cast<void> (0) : __assert_fail ("!RD->hasFlexibleArrayMember() && \"Cannot expand structure with flexible array.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 917, __PRETTY_FUNCTION__))
;
918 if (RD->isUnion()) {
919 // Unions can be here only in degenerative cases - all the fields are same
920 // after flattening. Thus we have to use the "largest" field.
921 const FieldDecl *LargestFD = nullptr;
922 CharUnits UnionSize = CharUnits::Zero();
923
924 for (const auto *FD : RD->fields()) {
925 if (FD->isZeroLengthBitField(Context))
926 continue;
927 assert(!FD->isBitField() &&((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 928, __PRETTY_FUNCTION__))
928 "Cannot expand structure with bit-field members.")((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 928, __PRETTY_FUNCTION__))
;
929 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
930 if (UnionSize < FieldSize) {
931 UnionSize = FieldSize;
932 LargestFD = FD;
933 }
934 }
935 if (LargestFD)
936 Fields.push_back(LargestFD);
937 } else {
938 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
939 assert(!CXXRD->isDynamicClass() &&((!CXXRD->isDynamicClass() && "cannot expand vtable pointers in dynamic classes"
) ? static_cast<void> (0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 940, __PRETTY_FUNCTION__))
940 "cannot expand vtable pointers in dynamic classes")((!CXXRD->isDynamicClass() && "cannot expand vtable pointers in dynamic classes"
) ? static_cast<void> (0) : __assert_fail ("!CXXRD->isDynamicClass() && \"cannot expand vtable pointers in dynamic classes\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 940, __PRETTY_FUNCTION__))
;
941 for (const CXXBaseSpecifier &BS : CXXRD->bases())
942 Bases.push_back(&BS);
943 }
944
945 for (const auto *FD : RD->fields()) {
946 if (FD->isZeroLengthBitField(Context))
947 continue;
948 assert(!FD->isBitField() &&((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 949, __PRETTY_FUNCTION__))
949 "Cannot expand structure with bit-field members.")((!FD->isBitField() && "Cannot expand structure with bit-field members."
) ? static_cast<void> (0) : __assert_fail ("!FD->isBitField() && \"Cannot expand structure with bit-field members.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 949, __PRETTY_FUNCTION__))
;
950 Fields.push_back(FD);
951 }
952 }
953 return std::make_unique<RecordExpansion>(std::move(Bases),
954 std::move(Fields));
955 }
956 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
957 return std::make_unique<ComplexExpansion>(CT->getElementType());
958 }
959 return std::make_unique<NoExpansion>();
960}
961
962static int getExpansionSize(QualType Ty, const ASTContext &Context) {
963 auto Exp = getTypeExpansion(Ty, Context);
964 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
965 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
966 }
967 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
968 int Res = 0;
969 for (auto BS : RExp->Bases)
970 Res += getExpansionSize(BS->getType(), Context);
971 for (auto FD : RExp->Fields)
972 Res += getExpansionSize(FD->getType(), Context);
973 return Res;
974 }
975 if (isa<ComplexExpansion>(Exp.get()))
976 return 2;
977 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 977, __PRETTY_FUNCTION__))
;
978 return 1;
979}
980
981void
982CodeGenTypes::getExpandedTypes(QualType Ty,
983 SmallVectorImpl<llvm::Type *>::iterator &TI) {
984 auto Exp = getTypeExpansion(Ty, Context);
985 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
986 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
987 getExpandedTypes(CAExp->EltTy, TI);
988 }
989 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
990 for (auto BS : RExp->Bases)
991 getExpandedTypes(BS->getType(), TI);
992 for (auto FD : RExp->Fields)
993 getExpandedTypes(FD->getType(), TI);
994 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
995 llvm::Type *EltTy = ConvertType(CExp->EltTy);
996 *TI++ = EltTy;
997 *TI++ = EltTy;
998 } else {
999 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 999, __PRETTY_FUNCTION__))
;
1000 *TI++ = ConvertType(Ty);
1001 }
1002}
1003
1004static void forConstantArrayExpansion(CodeGenFunction &CGF,
1005 ConstantArrayExpansion *CAE,
1006 Address BaseAddr,
1007 llvm::function_ref<void(Address)> Fn) {
1008 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1009 CharUnits EltAlign =
1010 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1011
1012 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1013 llvm::Value *EltAddr =
1014 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
1015 Fn(Address(EltAddr, EltAlign));
1016 }
1017}
1018
1019void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1020 llvm::Function::arg_iterator &AI) {
1021 assert(LV.isSimple() &&((LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1022, __PRETTY_FUNCTION__))
1022 "Unexpected non-simple lvalue during struct expansion.")((LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("LV.isSimple() && \"Unexpected non-simple lvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1022, __PRETTY_FUNCTION__))
;
1023
1024 auto Exp = getTypeExpansion(Ty, getContext());
1025 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1026 forConstantArrayExpansion(
1027 *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
1028 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1029 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1030 });
1031 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1032 Address This = LV.getAddress(*this);
1033 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1034 // Perform a single step derived-to-base conversion.
1035 Address Base =
1036 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1037 /*NullCheckValue=*/false, SourceLocation());
1038 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1039
1040 // Recurse onto bases.
1041 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1042 }
1043 for (auto FD : RExp->Fields) {
1044 // FIXME: What are the right qualifiers here?
1045 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1046 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1047 }
1048 } else if (isa<ComplexExpansion>(Exp.get())) {
1049 auto realValue = &*AI++;
1050 auto imagValue = &*AI++;
1051 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1052 } else {
1053 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1054 // primitive store.
1055 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1055, __PRETTY_FUNCTION__))
;
1056 if (LV.isBitField())
1057 EmitStoreThroughLValue(RValue::get(&*AI++), LV);
1058 else
1059 EmitStoreOfScalar(&*AI++, LV);
1060 }
1061}
1062
1063void CodeGenFunction::ExpandTypeToArgs(
1064 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1065 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1066 auto Exp = getTypeExpansion(Ty, getContext());
1067 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1068 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1069 : Arg.getKnownRValue().getAggregateAddress();
1070 forConstantArrayExpansion(
1071 *this, CAExp, Addr, [&](Address EltAddr) {
1072 CallArg EltArg = CallArg(
1073 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1074 CAExp->EltTy);
1075 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1076 IRCallArgPos);
1077 });
1078 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1079 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1080 : Arg.getKnownRValue().getAggregateAddress();
1081 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1082 // Perform a single step derived-to-base conversion.
1083 Address Base =
1084 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1085 /*NullCheckValue=*/false, SourceLocation());
1086 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1087
1088 // Recurse onto bases.
1089 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1090 IRCallArgPos);
1091 }
1092
1093 LValue LV = MakeAddrLValue(This, Ty);
1094 for (auto FD : RExp->Fields) {
1095 CallArg FldArg =
1096 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1097 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1098 IRCallArgPos);
1099 }
1100 } else if (isa<ComplexExpansion>(Exp.get())) {
1101 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1102 IRCallArgs[IRCallArgPos++] = CV.first;
1103 IRCallArgs[IRCallArgPos++] = CV.second;
1104 } else {
1105 assert(isa<NoExpansion>(Exp.get()))((isa<NoExpansion>(Exp.get())) ? static_cast<void>
(0) : __assert_fail ("isa<NoExpansion>(Exp.get())", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106 auto RV = Arg.getKnownRValue();
1107 assert(RV.isScalar() &&((RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1108, __PRETTY_FUNCTION__))
1108 "Unexpected non-scalar rvalue during struct expansion.")((RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."
) ? static_cast<void> (0) : __assert_fail ("RV.isScalar() && \"Unexpected non-scalar rvalue during struct expansion.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1108, __PRETTY_FUNCTION__))
;
1109
1110 // Insert a bitcast as needed.
1111 llvm::Value *V = RV.getScalarVal();
1112 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1113 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1114 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1115
1116 IRCallArgs[IRCallArgPos++] = V;
1117 }
1118}
1119
1120/// Create a temporary allocation for the purposes of coercion.
1121static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1122 CharUnits MinAlign,
1123 const Twine &Name = "tmp") {
1124 // Don't use an alignment that's worse than what LLVM would prefer.
1125 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1126 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1127
1128 return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1129}
1130
1131/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1132/// accessing some number of bytes out of it, try to gep into the struct to get
1133/// at its inner goodness. Dive as deep as possible without entering an element
1134/// with an in-memory size smaller than DstSize.
1135static Address
1136EnterStructPointerForCoercedAccess(Address SrcPtr,
1137 llvm::StructType *SrcSTy,
1138 uint64_t DstSize, CodeGenFunction &CGF) {
1139 // We can't dive into a zero-element struct.
1140 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1141
1142 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1143
1144 // If the first elt is at least as large as what we're looking for, or if the
1145 // first element is the same size as the whole struct, we can enter it. The
1146 // comparison must be made on the store size and not the alloca size. Using
1147 // the alloca size may overstate the size of the load.
1148 uint64_t FirstEltSize =
1149 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1150 if (FirstEltSize < DstSize &&
1151 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1152 return SrcPtr;
1153
1154 // GEP into the first element.
1155 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1156
1157 // If the first element is a struct, recurse.
1158 llvm::Type *SrcTy = SrcPtr.getElementType();
1159 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1160 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1161
1162 return SrcPtr;
1163}
1164
1165/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1166/// are either integers or pointers. This does a truncation of the value if it
1167/// is too large or a zero extension if it is too small.
1168///
1169/// This behaves as if the value were coerced through memory, so on big-endian
1170/// targets the high bits are preserved in a truncation, while little-endian
1171/// targets preserve the low bits.
1172static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1173 llvm::Type *Ty,
1174 CodeGenFunction &CGF) {
1175 if (Val->getType() == Ty)
1176 return Val;
1177
1178 if (isa<llvm::PointerType>(Val->getType())) {
1179 // If this is Pointer->Pointer avoid conversion to and from int.
1180 if (isa<llvm::PointerType>(Ty))
1181 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1182
1183 // Convert the pointer to an integer so we can play with its width.
1184 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1185 }
1186
1187 llvm::Type *DestIntTy = Ty;
1188 if (isa<llvm::PointerType>(DestIntTy))
1189 DestIntTy = CGF.IntPtrTy;
1190
1191 if (Val->getType() != DestIntTy) {
1192 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1193 if (DL.isBigEndian()) {
1194 // Preserve the high bits on big-endian targets.
1195 // That is what memory coercion does.
1196 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1197 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1198
1199 if (SrcSize > DstSize) {
1200 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1201 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1202 } else {
1203 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1204 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1205 }
1206 } else {
1207 // Little-endian targets preserve the low bits. No shifts required.
1208 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1209 }
1210 }
1211
1212 if (isa<llvm::PointerType>(Ty))
1213 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1214 return Val;
1215}
1216
1217
1218
1219/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1220/// a pointer to an object of type \arg Ty, known to be aligned to
1221/// \arg SrcAlign bytes.
1222///
1223/// This safely handles the case when the src type is smaller than the
1224/// destination type; in this situation the values of bits which not
1225/// present in the src are undefined.
1226static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1227 CodeGenFunction &CGF) {
1228 llvm::Type *SrcTy = Src.getElementType();
1229
1230 // If SrcTy and Ty are the same, just do a load.
1231 if (SrcTy == Ty)
1232 return CGF.Builder.CreateLoad(Src);
1233
1234 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1235
1236 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1237 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1238 DstSize.getFixedSize(), CGF);
1239 SrcTy = Src.getElementType();
1240 }
1241
1242 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1243
1244 // If the source and destination are integer or pointer types, just do an
1245 // extension or truncation to the desired type.
1246 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1247 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1248 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1249 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1250 }
1251
1252 // If load is legal, just bitcast the src pointer.
1253 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1254 SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
1255 // Generally SrcSize is never greater than DstSize, since this means we are
1256 // losing bits. However, this can happen in cases where the structure has
1257 // additional padding, for example due to a user specified alignment.
1258 //
1259 // FIXME: Assert that we aren't truncating non-padding bits when have access
1260 // to that information.
1261 Src = CGF.Builder.CreateBitCast(Src,
1262 Ty->getPointerTo(Src.getAddressSpace()));
1263 return CGF.Builder.CreateLoad(Src);
1264 }
1265
1266 // Otherwise do coercion through memory. This is stupid, but simple.
1267 Address Tmp =
1268 CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1269 CGF.Builder.CreateMemCpy(
1270 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1271 Src.getAlignment().getAsAlign(),
1272 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
1273 return CGF.Builder.CreateLoad(Tmp);
1274}
1275
1276// Function to store a first-class aggregate into memory. We prefer to
1277// store the elements rather than the aggregate to be more friendly to
1278// fast-isel.
1279// FIXME: Do we need to recurse here?
1280void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1281 bool DestIsVolatile) {
1282 // Prefer scalar stores to first-class aggregate stores.
1283 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1284 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1285 Address EltPtr = Builder.CreateStructGEP(Dest, i);
1286 llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1287 Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1288 }
1289 } else {
1290 Builder.CreateStore(Val, Dest, DestIsVolatile);
1291 }
1292}
1293
1294/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1295/// where the source and destination may have different types. The
1296/// destination is known to be aligned to \arg DstAlign bytes.
1297///
1298/// This safely handles the case when the src type is larger than the
1299/// destination type; the upper bits of the src will be lost.
1300static void CreateCoercedStore(llvm::Value *Src,
1301 Address Dst,
1302 bool DstIsVolatile,
1303 CodeGenFunction &CGF) {
1304 llvm::Type *SrcTy = Src->getType();
1305 llvm::Type *DstTy = Dst.getElementType();
1306 if (SrcTy == DstTy) {
1307 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1308 return;
1309 }
1310
1311 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1312
1313 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1314 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1315 SrcSize.getFixedSize(), CGF);
1316 DstTy = Dst.getElementType();
1317 }
1318
1319 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1320 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1321 if (SrcPtrTy && DstPtrTy &&
1322 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1323 Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1324 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1325 return;
1326 }
1327
1328 // If the source and destination are integer or pointer types, just do an
1329 // extension or truncation to the desired type.
1330 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1331 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1332 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1333 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1334 return;
1335 }
1336
1337 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1338
1339 // If store is legal, just bitcast the src pointer.
1340 if (isa<llvm::ScalableVectorType>(SrcTy) ||
1341 isa<llvm::ScalableVectorType>(DstTy) ||
1342 SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
1343 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1344 CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1345 } else {
1346 // Otherwise do coercion through memory. This is stupid, but
1347 // simple.
1348
1349 // Generally SrcSize is never greater than DstSize, since this means we are
1350 // losing bits. However, this can happen in cases where the structure has
1351 // additional padding, for example due to a user specified alignment.
1352 //
1353 // FIXME: Assert that we aren't truncating non-padding bits when have access
1354 // to that information.
1355 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1356 CGF.Builder.CreateStore(Src, Tmp);
1357 CGF.Builder.CreateMemCpy(
1358 Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1359 Tmp.getAlignment().getAsAlign(),
1360 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
1361 }
1362}
1363
1364static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1365 const ABIArgInfo &info) {
1366 if (unsigned offset = info.getDirectOffset()) {
1367 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1368 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1369 CharUnits::fromQuantity(offset));
1370 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1371 }
1372 return addr;
1373}
1374
1375namespace {
1376
1377/// Encapsulates information about the way function arguments from
1378/// CGFunctionInfo should be passed to actual LLVM IR function.
1379class ClangToLLVMArgMapping {
1380 static const unsigned InvalidIndex = ~0U;
1381 unsigned InallocaArgNo;
1382 unsigned SRetArgNo;
1383 unsigned TotalIRArgs;
1384
1385 /// Arguments of LLVM IR function corresponding to single Clang argument.
1386 struct IRArgs {
1387 unsigned PaddingArgIndex;
1388 // Argument is expanded to IR arguments at positions
1389 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1390 unsigned FirstArgIndex;
1391 unsigned NumberOfArgs;
1392
1393 IRArgs()
1394 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1395 NumberOfArgs(0) {}
1396 };
1397
1398 SmallVector<IRArgs, 8> ArgInfo;
1399
1400public:
1401 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1402 bool OnlyRequiredArgs = false)
1403 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1404 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1405 construct(Context, FI, OnlyRequiredArgs);
1406 }
1407
1408 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1409 unsigned getInallocaArgNo() const {
1410 assert(hasInallocaArg())((hasInallocaArg()) ? static_cast<void> (0) : __assert_fail
("hasInallocaArg()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1410, __PRETTY_FUNCTION__))
;
1411 return InallocaArgNo;
1412 }
1413
1414 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1415 unsigned getSRetArgNo() const {
1416 assert(hasSRetArg())((hasSRetArg()) ? static_cast<void> (0) : __assert_fail
("hasSRetArg()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1416, __PRETTY_FUNCTION__))
;
1417 return SRetArgNo;
1418 }
1419
1420 unsigned totalIRArgs() const { return TotalIRArgs; }
1421
1422 bool hasPaddingArg(unsigned ArgNo) const {
1423 assert(ArgNo < ArgInfo.size())((ArgNo < ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1423, __PRETTY_FUNCTION__))
;
1424 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1425 }
1426 unsigned getPaddingArgNo(unsigned ArgNo) const {
1427 assert(hasPaddingArg(ArgNo))((hasPaddingArg(ArgNo)) ? static_cast<void> (0) : __assert_fail
("hasPaddingArg(ArgNo)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1427, __PRETTY_FUNCTION__))
;
1428 return ArgInfo[ArgNo].PaddingArgIndex;
1429 }
1430
1431 /// Returns index of first IR argument corresponding to ArgNo, and their
1432 /// quantity.
1433 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1434 assert(ArgNo < ArgInfo.size())((ArgNo < ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo < ArgInfo.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1434, __PRETTY_FUNCTION__))
;
1435 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1436 ArgInfo[ArgNo].NumberOfArgs);
1437 }
1438
1439private:
1440 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1441 bool OnlyRequiredArgs);
1442};
1443
1444void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1445 const CGFunctionInfo &FI,
1446 bool OnlyRequiredArgs) {
1447 unsigned IRArgNo = 0;
1448 bool SwapThisWithSRet = false;
1449 const ABIArgInfo &RetAI = FI.getReturnInfo();
1450
1451 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1452 SwapThisWithSRet = RetAI.isSRetAfterThis();
1453 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1454 }
1455
1456 unsigned ArgNo = 0;
1457 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1458 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1459 ++I, ++ArgNo) {
1460 assert(I != FI.arg_end())((I != FI.arg_end()) ? static_cast<void> (0) : __assert_fail
("I != FI.arg_end()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1460, __PRETTY_FUNCTION__))
;
1461 QualType ArgType = I->type;
1462 const ABIArgInfo &AI = I->info;
1463 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1464 auto &IRArgs = ArgInfo[ArgNo];
1465
1466 if (AI.getPaddingType())
1467 IRArgs.PaddingArgIndex = IRArgNo++;
1468
1469 switch (AI.getKind()) {
1470 case ABIArgInfo::Extend:
1471 case ABIArgInfo::Direct: {
1472 // FIXME: handle sseregparm someday...
1473 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1474 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1475 IRArgs.NumberOfArgs = STy->getNumElements();
1476 } else {
1477 IRArgs.NumberOfArgs = 1;
1478 }
1479 break;
1480 }
1481 case ABIArgInfo::Indirect:
1482 case ABIArgInfo::IndirectAliased:
1483 IRArgs.NumberOfArgs = 1;
1484 break;
1485 case ABIArgInfo::Ignore:
1486 case ABIArgInfo::InAlloca:
1487 // ignore and inalloca doesn't have matching LLVM parameters.
1488 IRArgs.NumberOfArgs = 0;
1489 break;
1490 case ABIArgInfo::CoerceAndExpand:
1491 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1492 break;
1493 case ABIArgInfo::Expand:
1494 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1495 break;
1496 }
1497
1498 if (IRArgs.NumberOfArgs > 0) {
1499 IRArgs.FirstArgIndex = IRArgNo;
1500 IRArgNo += IRArgs.NumberOfArgs;
1501 }
1502
1503 // Skip over the sret parameter when it comes second. We already handled it
1504 // above.
1505 if (IRArgNo == 1 && SwapThisWithSRet)
1506 IRArgNo++;
1507 }
1508 assert(ArgNo == ArgInfo.size())((ArgNo == ArgInfo.size()) ? static_cast<void> (0) : __assert_fail
("ArgNo == ArgInfo.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1508, __PRETTY_FUNCTION__))
;
1509
1510 if (FI.usesInAlloca())
1511 InallocaArgNo = IRArgNo++;
1512
1513 TotalIRArgs = IRArgNo;
1514}
1515} // namespace
1516
1517/***/
1518
1519bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1520 const auto &RI = FI.getReturnInfo();
1521 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1522}
1523
1524bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1525 return ReturnTypeUsesSRet(FI) &&
1526 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1527}
1528
1529bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1530 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1531 switch (BT->getKind()) {
1532 default:
1533 return false;
1534 case BuiltinType::Float:
1535 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1536 case BuiltinType::Double:
1537 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1538 case BuiltinType::LongDouble:
1539 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1540 }
1541 }
1542
1543 return false;
1544}
1545
1546bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1547 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1548 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1549 if (BT->getKind() == BuiltinType::LongDouble)
1550 return getTarget().useObjCFP2RetForComplexLongDouble();
1551 }
1552 }
1553
1554 return false;
1555}
1556
1557llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1558 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1559 return GetFunctionType(FI);
1560}
1561
1562llvm::FunctionType *
1563CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1564
1565 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1566 (void)Inserted;
1567 assert(Inserted && "Recursively being processed?")((Inserted && "Recursively being processed?") ? static_cast
<void> (0) : __assert_fail ("Inserted && \"Recursively being processed?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1567, __PRETTY_FUNCTION__))
;
1568
1569 llvm::Type *resultType = nullptr;
1570 const ABIArgInfo &retAI = FI.getReturnInfo();
1571 switch (retAI.getKind()) {
1572 case ABIArgInfo::Expand:
1573 case ABIArgInfo::IndirectAliased:
1574 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1574)
;
1575
1576 case ABIArgInfo::Extend:
1577 case ABIArgInfo::Direct:
1578 resultType = retAI.getCoerceToType();
1579 break;
1580
1581 case ABIArgInfo::InAlloca:
1582 if (retAI.getInAllocaSRet()) {
1583 // sret things on win32 aren't void, they return the sret pointer.
1584 QualType ret = FI.getReturnType();
1585 llvm::Type *ty = ConvertType(ret);
1586 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1587 resultType = llvm::PointerType::get(ty, addressSpace);
1588 } else {
1589 resultType = llvm::Type::getVoidTy(getLLVMContext());
1590 }
1591 break;
1592
1593 case ABIArgInfo::Indirect:
1594 case ABIArgInfo::Ignore:
1595 resultType = llvm::Type::getVoidTy(getLLVMContext());
1596 break;
1597
1598 case ABIArgInfo::CoerceAndExpand:
1599 resultType = retAI.getUnpaddedCoerceAndExpandType();
1600 break;
1601 }
1602
1603 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1604 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1605
1606 // Add type for sret argument.
1607 if (IRFunctionArgs.hasSRetArg()) {
1608 QualType Ret = FI.getReturnType();
1609 llvm::Type *Ty = ConvertType(Ret);
1610 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1611 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1612 llvm::PointerType::get(Ty, AddressSpace);
1613 }
1614
1615 // Add type for inalloca argument.
1616 if (IRFunctionArgs.hasInallocaArg()) {
1617 auto ArgStruct = FI.getArgStruct();
1618 assert(ArgStruct)((ArgStruct) ? static_cast<void> (0) : __assert_fail ("ArgStruct"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1618, __PRETTY_FUNCTION__))
;
1619 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1620 }
1621
1622 // Add in all of the required arguments.
1623 unsigned ArgNo = 0;
1624 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1625 ie = it + FI.getNumRequiredArgs();
1626 for (; it != ie; ++it, ++ArgNo) {
1627 const ABIArgInfo &ArgInfo = it->info;
1628
1629 // Insert a padding type to ensure proper alignment.
1630 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1631 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1632 ArgInfo.getPaddingType();
1633
1634 unsigned FirstIRArg, NumIRArgs;
1635 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1636
1637 switch (ArgInfo.getKind()) {
1638 case ABIArgInfo::Ignore:
1639 case ABIArgInfo::InAlloca:
1640 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 break;
1642
1643 case ABIArgInfo::Indirect: {
1644 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1644, __PRETTY_FUNCTION__))
;
1645 // indirect arguments are always on the stack, which is alloca addr space.
1646 llvm::Type *LTy = ConvertTypeForMem(it->type);
1647 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1648 CGM.getDataLayout().getAllocaAddrSpace());
1649 break;
1650 }
1651 case ABIArgInfo::IndirectAliased: {
1652 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1652, __PRETTY_FUNCTION__))
;
1653 llvm::Type *LTy = ConvertTypeForMem(it->type);
1654 ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1655 break;
1656 }
1657 case ABIArgInfo::Extend:
1658 case ABIArgInfo::Direct: {
1659 // Fast-isel and the optimizer generally like scalar values better than
1660 // FCAs, so we flatten them if this is safe to do for this argument.
1661 llvm::Type *argType = ArgInfo.getCoerceToType();
1662 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1663 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1664 assert(NumIRArgs == st->getNumElements())((NumIRArgs == st->getNumElements()) ? static_cast<void
> (0) : __assert_fail ("NumIRArgs == st->getNumElements()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1666 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1667 } else {
1668 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1668, __PRETTY_FUNCTION__))
;
1669 ArgTypes[FirstIRArg] = argType;
1670 }
1671 break;
1672 }
1673
1674 case ABIArgInfo::CoerceAndExpand: {
1675 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1676 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1677 *ArgTypesIter++ = EltTy;
1678 }
1679 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs)((ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs) ?
static_cast<void> (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1679, __PRETTY_FUNCTION__))
;
1680 break;
1681 }
1682
1683 case ABIArgInfo::Expand:
1684 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1685 getExpandedTypes(it->type, ArgTypesIter);
1686 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs)((ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs) ?
static_cast<void> (0) : __assert_fail ("ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1686, __PRETTY_FUNCTION__))
;
1687 break;
1688 }
1689 }
1690
1691 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1692 assert(Erased && "Not in set?")((Erased && "Not in set?") ? static_cast<void> (
0) : __assert_fail ("Erased && \"Not in set?\"", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 1692, __PRETTY_FUNCTION__))
;
1693
1694 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1695}
1696
1697llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1698 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1699 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1700
1701 if (!isFuncTypeConvertible(FPT))
1702 return llvm::StructType::get(getLLVMContext());
1703
1704 return GetFunctionType(GD);
1705}
1706
1707static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1708 llvm::AttrBuilder &FuncAttrs,
1709 const FunctionProtoType *FPT) {
1710 if (!FPT)
1711 return;
1712
1713 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1714 FPT->isNothrow())
1715 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1716}
1717
1718void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1719 bool HasOptnone,
1720 bool AttrOnCallSite,
1721 llvm::AttrBuilder &FuncAttrs) {
1722 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1723 if (!HasOptnone) {
1724 if (CodeGenOpts.OptimizeSize)
1725 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1726 if (CodeGenOpts.OptimizeSize == 2)
1727 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1728 }
1729
1730 if (CodeGenOpts.DisableRedZone)
1731 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1732 if (CodeGenOpts.IndirectTlsSegRefs)
1733 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1734 if (CodeGenOpts.NoImplicitFloat)
1735 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1736
1737 if (AttrOnCallSite) {
1738 // Attributes that should go on the call site only.
1739 if (!CodeGenOpts.SimplifyLibCalls ||
1740 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1741 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1742 if (!CodeGenOpts.TrapFuncName.empty())
1743 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1744 } else {
1745 StringRef FpKind;
1746 switch (CodeGenOpts.getFramePointer()) {
1747 case CodeGenOptions::FramePointerKind::None:
1748 FpKind = "none";
1749 break;
1750 case CodeGenOptions::FramePointerKind::NonLeaf:
1751 FpKind = "non-leaf";
1752 break;
1753 case CodeGenOptions::FramePointerKind::All:
1754 FpKind = "all";
1755 break;
1756 }
1757 FuncAttrs.addAttribute("frame-pointer", FpKind);
1758
1759 FuncAttrs.addAttribute("less-precise-fpmad",
1760 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1761
1762 if (CodeGenOpts.NullPointerIsValid)
1763 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1764
1765 if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1766 FuncAttrs.addAttribute("denormal-fp-math",
1767 CodeGenOpts.FPDenormalMode.str());
1768 if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1769 FuncAttrs.addAttribute(
1770 "denormal-fp-math-f32",
1771 CodeGenOpts.FP32DenormalMode.str());
1772 }
1773
1774 FuncAttrs.addAttribute("no-trapping-math",
1775 llvm::toStringRef(LangOpts.getFPExceptionMode() ==
1776 LangOptions::FPE_Ignore));
1777
1778 // Strict (compliant) code is the default, so only add this attribute to
1779 // indicate that we are trying to workaround a problem case.
1780 if (!CodeGenOpts.StrictFloatCastOverflow)
1781 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
1782
1783 // TODO: Are these all needed?
1784 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1785 FuncAttrs.addAttribute("no-infs-fp-math",
1786 llvm::toStringRef(LangOpts.NoHonorInfs));
1787 FuncAttrs.addAttribute("no-nans-fp-math",
1788 llvm::toStringRef(LangOpts.NoHonorNaNs));
1789 FuncAttrs.addAttribute("unsafe-fp-math",
1790 llvm::toStringRef(LangOpts.UnsafeFPMath));
1791 FuncAttrs.addAttribute("use-soft-float",
1792 llvm::toStringRef(CodeGenOpts.SoftFloat));
1793 FuncAttrs.addAttribute("stack-protector-buffer-size",
1794 llvm::utostr(CodeGenOpts.SSPBufferSize));
1795 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1796 llvm::toStringRef(LangOpts.NoSignedZero));
1797
1798 // TODO: Reciprocal estimate codegen options should apply to instructions?
1799 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1800 if (!Recips.empty())
1801 FuncAttrs.addAttribute("reciprocal-estimates",
1802 llvm::join(Recips, ","));
1803
1804 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1805 CodeGenOpts.PreferVectorWidth != "none")
1806 FuncAttrs.addAttribute("prefer-vector-width",
1807 CodeGenOpts.PreferVectorWidth);
1808
1809 if (CodeGenOpts.StackRealignment)
1810 FuncAttrs.addAttribute("stackrealign");
1811 if (CodeGenOpts.Backchain)
1812 FuncAttrs.addAttribute("backchain");
1813 if (CodeGenOpts.EnableSegmentedStacks)
1814 FuncAttrs.addAttribute("split-stack");
1815
1816 if (CodeGenOpts.SpeculativeLoadHardening)
1817 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1818 }
1819
1820 if (getLangOpts().assumeFunctionsAreConvergent()) {
1821 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1822 // convergent (meaning, they may call an intrinsically convergent op, such
1823 // as __syncthreads() / barrier(), and so can't have certain optimizations
1824 // applied around them). LLVM will remove this attribute where it safely
1825 // can.
1826 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1827 }
1828
1829 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1830 // Exceptions aren't supported in CUDA device code.
1831 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1832 }
1833
1834 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1835 StringRef Var, Value;
1836 std::tie(Var, Value) = Attr.split('=');
1837 FuncAttrs.addAttribute(Var, Value);
1838 }
1839}
1840
1841void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
1842 llvm::AttrBuilder FuncAttrs;
1843 getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
1844 /* AttrOnCallSite = */ false, FuncAttrs);
1845 // TODO: call GetCPUAndFeaturesAttributes?
1846 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1847}
1848
1849void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1850 llvm::AttrBuilder &attrs) {
1851 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
1852 /*for call*/ false, attrs);
1853 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
1854}
1855
1856static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
1857 const LangOptions &LangOpts,
1858 const NoBuiltinAttr *NBA = nullptr) {
1859 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
1860 SmallString<32> AttributeName;
1861 AttributeName += "no-builtin-";
1862 AttributeName += BuiltinName;
1863 FuncAttrs.addAttribute(AttributeName);
1864 };
1865
1866 // First, handle the language options passed through -fno-builtin.
1867 if (LangOpts.NoBuiltin) {
1868 // -fno-builtin disables them all.
1869 FuncAttrs.addAttribute("no-builtins");
1870 return;
1871 }
1872
1873 // Then, add attributes for builtins specified through -fno-builtin-<name>.
1874 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
1875
1876 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
1877 // the source.
1878 if (!NBA)
1879 return;
1880
1881 // If there is a wildcard in the builtin names specified through the
1882 // attribute, disable them all.
1883 if (llvm::is_contained(NBA->builtinNames(), "*")) {
1884 FuncAttrs.addAttribute("no-builtins");
1885 return;
1886 }
1887
1888 // And last, add the rest of the builtin names.
1889 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
1890}
1891
1892/// Construct the IR attribute list of a function or call.
1893///
1894/// When adding an attribute, please consider where it should be handled:
1895///
1896/// - getDefaultFunctionAttributes is for attributes that are essentially
1897/// part of the global target configuration (but perhaps can be
1898/// overridden on a per-function basis). Adding attributes there
1899/// will cause them to also be set in frontends that build on Clang's
1900/// target-configuration logic, as well as for code defined in library
1901/// modules such as CUDA's libdevice.
1902///
1903/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
1904/// and adds declaration-specific, convention-specific, and
1905/// frontend-specific logic. The last is of particular importance:
1906/// attributes that restrict how the frontend generates code must be
1907/// added here rather than getDefaultFunctionAttributes.
1908///
1909void CodeGenModule::ConstructAttributeList(
1910 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1911 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
1912 llvm::AttrBuilder FuncAttrs;
1913 llvm::AttrBuilder RetAttrs;
1914
1915 // Collect function IR attributes from the CC lowering.
1916 // We'll collect the paramete and result attributes later.
1917 CallingConv = FI.getEffectiveCallingConvention();
1918 if (FI.isNoReturn())
1919 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1920 if (FI.isCmseNSCall())
1921 FuncAttrs.addAttribute("cmse_nonsecure_call");
1922
1923 // Collect function IR attributes from the callee prototype if we have one.
1924 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1925 CalleeInfo.getCalleeFunctionProtoType());
1926
1927 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
1928
1929 bool HasOptnone = false;
1930 // The NoBuiltinAttr attached to the target FunctionDecl.
1931 const NoBuiltinAttr *NBA = nullptr;
1932
1933 // Collect function IR attributes based on declaration-specific
1934 // information.
1935 // FIXME: handle sseregparm someday...
1936 if (TargetDecl) {
1937 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
1938 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
1939 if (TargetDecl->hasAttr<NoThrowAttr>())
1940 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1941 if (TargetDecl->hasAttr<NoReturnAttr>())
1942 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1943 if (TargetDecl->hasAttr<ColdAttr>())
1944 FuncAttrs.addAttribute(llvm::Attribute::Cold);
1945 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1946 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
1947 if (TargetDecl->hasAttr<ConvergentAttr>())
1948 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1949
1950 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
1951 AddAttributesFromFunctionProtoType(
1952 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
1953 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
1954 // A sane operator new returns a non-aliasing pointer.
1955 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
1956 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1957 (Kind == OO_New || Kind == OO_Array_New))
1958 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1959 }
1960 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1961 const bool IsVirtualCall = MD && MD->isVirtual();
1962 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
1963 // virtual function. These attributes are not inherited by overloads.
1964 if (!(AttrOnCallSite && IsVirtualCall)) {
1965 if (Fn->isNoReturn())
1966 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1967 NBA = Fn->getAttr<NoBuiltinAttr>();
1968 }
1969 }
1970
1971 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
1972 if (TargetDecl->hasAttr<ConstAttr>()) {
1973 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1974 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1975 } else if (TargetDecl->hasAttr<PureAttr>()) {
1976 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1977 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1978 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1979 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1980 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1981 }
1982 if (TargetDecl->hasAttr<RestrictAttr>())
1983 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
1984 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
1985 !CodeGenOpts.NullPointerIsValid)
1986 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1987 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
1988 FuncAttrs.addAttribute("no_caller_saved_registers");
1989 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
1990 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
1991
1992 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
1993 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1994 Optional<unsigned> NumElemsParam;
1995 if (AllocSize->getNumElemsParam().isValid())
1996 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
1997 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
1998 NumElemsParam);
1999 }
2000
2001 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2002 if (getLangOpts().OpenCLVersion <= 120) {
2003 // OpenCL v1.2 Work groups are always uniform
2004 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2005 } else {
2006 // OpenCL v2.0 Work groups may be whether uniform or not.
2007 // '-cl-uniform-work-group-size' compile option gets a hint
2008 // to the compiler that the global work-size be a multiple of
2009 // the work-group size specified to clEnqueueNDRangeKernel
2010 // (i.e. work groups are uniform).
2011 FuncAttrs.addAttribute("uniform-work-group-size",
2012 llvm::toStringRef(CodeGenOpts.UniformWGSize));
2013 }
2014 }
2015 }
2016
2017 // Attach "no-builtins" attributes to:
2018 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2019 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2020 // The attributes can come from:
2021 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2022 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2023 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2024
2025 // Collect function IR attributes based on global settiings.
2026 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2027
2028 // Override some default IR attributes based on declaration-specific
2029 // information.
2030 if (TargetDecl) {
2031 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2032 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2033 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2034 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2035 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2036 FuncAttrs.removeAttribute("split-stack");
2037
2038 // Add NonLazyBind attribute to function declarations when -fno-plt
2039 // is used.
2040 // FIXME: what if we just haven't processed the function definition
2041 // yet, or if it's an external definition like C99 inline?
2042 if (CodeGenOpts.NoPLT) {
2043 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2044 if (!Fn->isDefined() && !AttrOnCallSite) {
2045 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2046 }
2047 }
2048 }
2049 }
2050
2051 // Collect non-call-site function IR attributes from declaration-specific
2052 // information.
2053 if (!AttrOnCallSite) {
2054 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2055 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2056
2057 // Whether tail calls are enabled.
2058 auto shouldDisableTailCalls = [&] {
2059 // Should this be honored in getDefaultFunctionAttributes?
2060 if (CodeGenOpts.DisableTailCalls)
2061 return true;
2062
2063 if (!TargetDecl)
2064 return false;
2065
2066 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2067 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2068 return true;
2069
2070 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2071 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2072 if (!BD->doesNotEscape())
2073 return true;
2074 }
2075
2076 return false;
2077 };
2078 FuncAttrs.addAttribute("disable-tail-calls",
2079 llvm::toStringRef(shouldDisableTailCalls()));
2080
2081 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2082 // handles these separately to set them based on the global defaults.
2083 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2084 }
2085
2086 // Collect attributes from arguments and return values.
2087 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2088
2089 QualType RetTy = FI.getReturnType();
2090 const ABIArgInfo &RetAI = FI.getReturnInfo();
2091 switch (RetAI.getKind()) {
2092 case ABIArgInfo::Extend:
2093 if (RetAI.isSignExt())
2094 RetAttrs.addAttribute(llvm::Attribute::SExt);
2095 else
2096 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2097 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2098 case ABIArgInfo::Direct:
2099 if (RetAI.getInReg())
2100 RetAttrs.addAttribute(llvm::Attribute::InReg);
2101 break;
2102 case ABIArgInfo::Ignore:
2103 break;
2104
2105 case ABIArgInfo::InAlloca:
2106 case ABIArgInfo::Indirect: {
2107 // inalloca and sret disable readnone and readonly
2108 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2109 .removeAttribute(llvm::Attribute::ReadNone);
2110 break;
2111 }
2112
2113 case ABIArgInfo::CoerceAndExpand:
2114 break;
2115
2116 case ABIArgInfo::Expand:
2117 case ABIArgInfo::IndirectAliased:
2118 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2118)
;
2119 }
2120
2121 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2122 QualType PTy = RefTy->getPointeeType();
2123 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2124 RetAttrs.addDereferenceableAttr(
2125 getMinimumObjectSize(PTy).getQuantity());
2126 if (getContext().getTargetAddressSpace(PTy) == 0 &&
2127 !CodeGenOpts.NullPointerIsValid)
2128 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2129 if (PTy->isObjectType()) {
2130 llvm::Align Alignment =
2131 getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2132 RetAttrs.addAlignmentAttr(Alignment);
2133 }
2134 }
2135
2136 bool hasUsedSRet = false;
2137 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2138
2139 // Attach attributes to sret.
2140 if (IRFunctionArgs.hasSRetArg()) {
2141 llvm::AttrBuilder SRETAttrs;
2142 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2143 hasUsedSRet = true;
2144 if (RetAI.getInReg())
2145 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2146 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2147 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2148 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2149 }
2150
2151 // Attach attributes to inalloca argument.
2152 if (IRFunctionArgs.hasInallocaArg()) {
2153 llvm::AttrBuilder Attrs;
2154 Attrs.addAttribute(llvm::Attribute::InAlloca);
2155 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2156 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2157 }
2158
2159 // Apply `nonnull` and `dereferencable(N)` to the `this` argument.
2160 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2161 !FI.arg_begin()->type->isVoidPointerType()) {
2162 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2163
2164 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.")((IRArgs.second == 1 && "Expected only a single `this` pointer."
) ? static_cast<void> (0) : __assert_fail ("IRArgs.second == 1 && \"Expected only a single `this` pointer.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2164, __PRETTY_FUNCTION__))
;
2165
2166 llvm::AttrBuilder Attrs;
2167
2168 if (!CodeGenOpts.NullPointerIsValid &&
2169 getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2170 Attrs.addAttribute(llvm::Attribute::NonNull);
2171 }
2172
2173 Attrs.addDereferenceableAttr(
2174 getMinimumObjectSize(
2175 FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2176 .getQuantity());
2177
2178 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2179 }
2180
2181 unsigned ArgNo = 0;
2182 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2183 E = FI.arg_end();
2184 I != E; ++I, ++ArgNo) {
2185 QualType ParamType = I->type;
2186 const ABIArgInfo &AI = I->info;
2187 llvm::AttrBuilder Attrs;
2188
2189 // Add attribute for padding argument, if necessary.
2190 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2191 if (AI.getPaddingInReg()) {
2192 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2193 llvm::AttributeSet::get(
2194 getLLVMContext(),
2195 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2196 }
2197 }
2198
2199 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2200 // have the corresponding parameter variable. It doesn't make
2201 // sense to do it here because parameters are so messed up.
2202 switch (AI.getKind()) {
2203 case ABIArgInfo::Extend:
2204 if (AI.isSignExt())
2205 Attrs.addAttribute(llvm::Attribute::SExt);
2206 else
2207 Attrs.addAttribute(llvm::Attribute::ZExt);
2208 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2209 case ABIArgInfo::Direct:
2210 if (ArgNo == 0 && FI.isChainCall())
2211 Attrs.addAttribute(llvm::Attribute::Nest);
2212 else if (AI.getInReg())
2213 Attrs.addAttribute(llvm::Attribute::InReg);
2214 break;
2215
2216 case ABIArgInfo::Indirect: {
2217 if (AI.getInReg())
2218 Attrs.addAttribute(llvm::Attribute::InReg);
2219
2220 if (AI.getIndirectByVal())
2221 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2222
2223 auto *Decl = ParamType->getAsRecordDecl();
2224 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2225 Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2226 // When calling the function, the pointer passed in will be the only
2227 // reference to the underlying object. Mark it accordingly.
2228 Attrs.addAttribute(llvm::Attribute::NoAlias);
2229
2230 // TODO: We could add the byref attribute if not byval, but it would
2231 // require updating many testcases.
2232
2233 CharUnits Align = AI.getIndirectAlign();
2234
2235 // In a byval argument, it is important that the required
2236 // alignment of the type is honored, as LLVM might be creating a
2237 // *new* stack object, and needs to know what alignment to give
2238 // it. (Sometimes it can deduce a sensible alignment on its own,
2239 // but not if clang decides it must emit a packed struct, or the
2240 // user specifies increased alignment requirements.)
2241 //
2242 // This is different from indirect *not* byval, where the object
2243 // exists already, and the align attribute is purely
2244 // informative.
2245 assert(!Align.isZero())((!Align.isZero()) ? static_cast<void> (0) : __assert_fail
("!Align.isZero()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2245, __PRETTY_FUNCTION__))
;
2246
2247 // For now, only add this when we have a byval argument.
2248 // TODO: be less lazy about updating test cases.
2249 if (AI.getIndirectByVal())
2250 Attrs.addAlignmentAttr(Align.getQuantity());
2251
2252 // byval disables readnone and readonly.
2253 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2254 .removeAttribute(llvm::Attribute::ReadNone);
2255
2256 break;
2257 }
2258 case ABIArgInfo::IndirectAliased: {
2259 CharUnits Align = AI.getIndirectAlign();
2260 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2261 Attrs.addAlignmentAttr(Align.getQuantity());
2262 break;
2263 }
2264 case ABIArgInfo::Ignore:
2265 case ABIArgInfo::Expand:
2266 case ABIArgInfo::CoerceAndExpand:
2267 break;
2268
2269 case ABIArgInfo::InAlloca:
2270 // inalloca disables readnone and readonly.
2271 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2272 .removeAttribute(llvm::Attribute::ReadNone);
2273 continue;
2274 }
2275
2276 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2277 QualType PTy = RefTy->getPointeeType();
2278 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2279 Attrs.addDereferenceableAttr(
2280 getMinimumObjectSize(PTy).getQuantity());
2281 if (getContext().getTargetAddressSpace(PTy) == 0 &&
2282 !CodeGenOpts.NullPointerIsValid)
2283 Attrs.addAttribute(llvm::Attribute::NonNull);
2284 if (PTy->isObjectType()) {
2285 llvm::Align Alignment =
2286 getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2287 Attrs.addAlignmentAttr(Alignment);
2288 }
2289 }
2290
2291 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2292 case ParameterABI::Ordinary:
2293 break;
2294
2295 case ParameterABI::SwiftIndirectResult: {
2296 // Add 'sret' if we haven't already used it for something, but
2297 // only if the result is void.
2298 if (!hasUsedSRet && RetTy->isVoidType()) {
2299 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2300 hasUsedSRet = true;
2301 }
2302
2303 // Add 'noalias' in either case.
2304 Attrs.addAttribute(llvm::Attribute::NoAlias);
2305
2306 // Add 'dereferenceable' and 'alignment'.
2307 auto PTy = ParamType->getPointeeType();
2308 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2309 auto info = getContext().getTypeInfoInChars(PTy);
2310 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2311 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2312 }
2313 break;
2314 }
2315
2316 case ParameterABI::SwiftErrorResult:
2317 Attrs.addAttribute(llvm::Attribute::SwiftError);
2318 break;
2319
2320 case ParameterABI::SwiftContext:
2321 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2322 break;
2323 }
2324
2325 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2326 Attrs.addAttribute(llvm::Attribute::NoCapture);
2327
2328 if (Attrs.hasAttributes()) {
2329 unsigned FirstIRArg, NumIRArgs;
2330 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2331 for (unsigned i = 0; i < NumIRArgs; i++)
2332 ArgAttrs[FirstIRArg + i] =
2333 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2334 }
2335 }
2336 assert(ArgNo == FI.arg_size())((ArgNo == FI.arg_size()) ? static_cast<void> (0) : __assert_fail
("ArgNo == FI.arg_size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2336, __PRETTY_FUNCTION__))
;
2337
2338 AttrList = llvm::AttributeList::get(
2339 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2340 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2341}
2342
2343/// An argument came in as a promoted argument; demote it back to its
2344/// declared type.
2345static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2346 const VarDecl *var,
2347 llvm::Value *value) {
2348 llvm::Type *varType = CGF.ConvertType(var->getType());
2349
2350 // This can happen with promotions that actually don't change the
2351 // underlying type, like the enum promotions.
2352 if (value->getType() == varType) return value;
2353
2354 assert((varType->isIntegerTy() || varType->isFloatingPointTy())(((varType->isIntegerTy() || varType->isFloatingPointTy
()) && "unexpected promotion type") ? static_cast<
void> (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2355, __PRETTY_FUNCTION__))
2355 && "unexpected promotion type")(((varType->isIntegerTy() || varType->isFloatingPointTy
()) && "unexpected promotion type") ? static_cast<
void> (0) : __assert_fail ("(varType->isIntegerTy() || varType->isFloatingPointTy()) && \"unexpected promotion type\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2355, __PRETTY_FUNCTION__))
;
2356
2357 if (isa<llvm::IntegerType>(varType))
2358 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2359
2360 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2361}
2362
2363/// Returns the attribute (either parameter attribute, or function
2364/// attribute), which declares argument ArgNo to be non-null.
2365static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2366 QualType ArgType, unsigned ArgNo) {
2367 // FIXME: __attribute__((nonnull)) can also be applied to:
2368 // - references to pointers, where the pointee is known to be
2369 // nonnull (apparently a Clang extension)
2370 // - transparent unions containing pointers
2371 // In the former case, LLVM IR cannot represent the constraint. In
2372 // the latter case, we have no guarantee that the transparent union
2373 // is in fact passed as a pointer.
2374 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2375 return nullptr;
2376 // First, check attribute on parameter itself.
2377 if (PVD) {
2378 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2379 return ParmNNAttr;
2380 }
2381 // Check function attributes.
2382 if (!FD)
2383 return nullptr;
2384 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2385 if (NNAttr->isNonNull(ArgNo))
2386 return NNAttr;
2387 }
2388 return nullptr;
2389}
2390
2391namespace {
2392 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2393 Address Temp;
2394 Address Arg;
2395 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2396 void Emit(CodeGenFunction &CGF, Flags flags) override {
2397 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2398 CGF.Builder.CreateStore(errorValue, Arg);
2399 }
2400 };
2401}
2402
2403void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2404 llvm::Function *Fn,
2405 const FunctionArgList &Args) {
2406 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2407 // Naked functions don't have prologues.
2408 return;
2409
2410 // If this is an implicit-return-zero function, go ahead and
2411 // initialize the return value. TODO: it might be nice to have
2412 // a more general mechanism for this that didn't require synthesized
2413 // return statements.
2414 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2415 if (FD->hasImplicitReturnZero()) {
2416 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2417 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2418 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2419 Builder.CreateStore(Zero, ReturnValue);
2420 }
2421 }
2422
2423 // FIXME: We no longer need the types from FunctionArgList; lift up and
2424 // simplify.
2425
2426 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2427 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs())((Fn->arg_size() == IRFunctionArgs.totalIRArgs()) ? static_cast
<void> (0) : __assert_fail ("Fn->arg_size() == IRFunctionArgs.totalIRArgs()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2427, __PRETTY_FUNCTION__))
;
2428
2429 // If we're using inalloca, all the memory arguments are GEPs off of the last
2430 // parameter, which is a pointer to the complete memory area.
2431 Address ArgStruct = Address::invalid();
2432 if (IRFunctionArgs.hasInallocaArg()) {
2433 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2434 FI.getArgStructAlignment());
2435
2436 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo())((ArgStruct.getType() == FI.getArgStruct()->getPointerTo()
) ? static_cast<void> (0) : __assert_fail ("ArgStruct.getType() == FI.getArgStruct()->getPointerTo()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2436, __PRETTY_FUNCTION__))
;
2437 }
2438
2439 // Name the struct return parameter.
2440 if (IRFunctionArgs.hasSRetArg()) {
2441 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2442 AI->setName("agg.result");
2443 AI->addAttr(llvm::Attribute::NoAlias);
2444 }
2445
2446 // Track if we received the parameter as a pointer (indirect, byval, or
2447 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2448 // into a local alloca for us.
2449 SmallVector<ParamValue, 16> ArgVals;
2450 ArgVals.reserve(Args.size());
2451
2452 // Create a pointer value for every parameter declaration. This usually
2453 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2454 // any cleanups or do anything that might unwind. We do that separately, so
2455 // we can push the cleanups in the correct order for the ABI.
2456 assert(FI.arg_size() == Args.size() &&((FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2457, __PRETTY_FUNCTION__))
2457 "Mismatch between function signature & arguments.")((FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("FI.arg_size() == Args.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2457, __PRETTY_FUNCTION__))
;
2458 unsigned ArgNo = 0;
2459 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2460 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2461 i != e; ++i, ++info_it, ++ArgNo) {
2462 const VarDecl *Arg = *i;
2463 const ABIArgInfo &ArgI = info_it->info;
2464
2465 bool isPromoted =
2466 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2467 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2468 // the parameter is promoted. In this case we convert to
2469 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2470 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2471 assert(hasScalarEvaluationKind(Ty) ==((hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->
getType())) ? static_cast<void> (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2472, __PRETTY_FUNCTION__))
2472 hasScalarEvaluationKind(Arg->getType()))((hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->
getType())) ? static_cast<void> (0) : __assert_fail ("hasScalarEvaluationKind(Ty) == hasScalarEvaluationKind(Arg->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2472, __PRETTY_FUNCTION__))
;
2473
2474 unsigned FirstIRArg, NumIRArgs;
2475 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2476
2477 switch (ArgI.getKind()) {
2478 case ABIArgInfo::InAlloca: {
2479 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2479, __PRETTY_FUNCTION__))
;
2480 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2481 Address V =
2482 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2483 if (ArgI.getInAllocaIndirect())
2484 V = Address(Builder.CreateLoad(V),
2485 getContext().getTypeAlignInChars(Ty));
2486 ArgVals.push_back(ParamValue::forIndirect(V));
2487 break;
2488 }
2489
2490 case ABIArgInfo::Indirect:
2491 case ABIArgInfo::IndirectAliased: {
2492 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2492, __PRETTY_FUNCTION__))
;
2493 Address ParamAddr =
2494 Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign());
2495
2496 if (!hasScalarEvaluationKind(Ty)) {
2497 // Aggregates and complex variables are accessed by reference. All we
2498 // need to do is realign the value, if requested. Also, if the address
2499 // may be aliased, copy it to ensure that the parameter variable is
2500 // mutable and has a unique adress, as C requires.
2501 Address V = ParamAddr;
2502 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
2503 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2504
2505 // Copy from the incoming argument pointer to the temporary with the
2506 // appropriate alignment.
2507 //
2508 // FIXME: We should have a common utility for generating an aggregate
2509 // copy.
2510 CharUnits Size = getContext().getTypeSizeInChars(Ty);
2511 Builder.CreateMemCpy(
2512 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2513 ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2514 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
2515 V = AlignedTemp;
2516 }
2517 ArgVals.push_back(ParamValue::forIndirect(V));
2518 } else {
2519 // Load scalar value from indirect argument.
2520 llvm::Value *V =
2521 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2522
2523 if (isPromoted)
2524 V = emitArgumentDemotion(*this, Arg, V);
2525 ArgVals.push_back(ParamValue::forDirect(V));
2526 }
2527 break;
2528 }
2529
2530 case ABIArgInfo::Extend:
2531 case ABIArgInfo::Direct: {
2532 auto AI = Fn->getArg(FirstIRArg);
2533 llvm::Type *LTy = ConvertType(Arg->getType());
2534
2535 // Prepare parameter attributes. So far, only attributes for pointer
2536 // parameters are prepared. See
2537 // http://llvm.org/docs/LangRef.html#paramattrs.
2538 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2539 ArgI.getCoerceToType()->isPointerTy()) {
2540 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2540, __PRETTY_FUNCTION__))
;
2541
2542 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2543 // Set `nonnull` attribute if any.
2544 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2545 PVD->getFunctionScopeIndex()) &&
2546 !CGM.getCodeGenOpts().NullPointerIsValid)
2547 AI->addAttr(llvm::Attribute::NonNull);
2548
2549 QualType OTy = PVD->getOriginalType();
2550 if (const auto *ArrTy =
2551 getContext().getAsConstantArrayType(OTy)) {
2552 // A C99 array parameter declaration with the static keyword also
2553 // indicates dereferenceability, and if the size is constant we can
2554 // use the dereferenceable attribute (which requires the size in
2555 // bytes).
2556 if (ArrTy->getSizeModifier() == ArrayType::Static) {
2557 QualType ETy = ArrTy->getElementType();
2558 llvm::Align Alignment =
2559 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2560 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2561 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2562 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2563 ArrSize) {
2564 llvm::AttrBuilder Attrs;
2565 Attrs.addDereferenceableAttr(
2566 getContext().getTypeSizeInChars(ETy).getQuantity() *
2567 ArrSize);
2568 AI->addAttrs(Attrs);
2569 } else if (getContext().getTargetInfo().getNullPointerValue(
2570 ETy.getAddressSpace()) == 0 &&
2571 !CGM.getCodeGenOpts().NullPointerIsValid) {
2572 AI->addAttr(llvm::Attribute::NonNull);
2573 }
2574 }
2575 } else if (const auto *ArrTy =
2576 getContext().getAsVariableArrayType(OTy)) {
2577 // For C99 VLAs with the static keyword, we don't know the size so
2578 // we can't use the dereferenceable attribute, but in addrspace(0)
2579 // we know that it must be nonnull.
2580 if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2581 QualType ETy = ArrTy->getElementType();
2582 llvm::Align Alignment =
2583 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2584 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2585 if (!getContext().getTargetAddressSpace(ETy) &&
2586 !CGM.getCodeGenOpts().NullPointerIsValid)
2587 AI->addAttr(llvm::Attribute::NonNull);
2588 }
2589 }
2590
2591 // Set `align` attribute if any.
2592 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2593 if (!AVAttr)
2594 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2595 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2596 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2597 // If alignment-assumption sanitizer is enabled, we do *not* add
2598 // alignment attribute here, but emit normal alignment assumption,
2599 // so the UBSAN check could function.
2600 llvm::ConstantInt *AlignmentCI =
2601 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2602 unsigned AlignmentInt =
2603 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2604 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2605 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2606 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(
2607 llvm::Align(AlignmentInt)));
2608 }
2609 }
2610 }
2611
2612 // Set 'noalias' if an argument type has the `restrict` qualifier.
2613 if (Arg->getType().isRestrictQualified())
2614 AI->addAttr(llvm::Attribute::NoAlias);
2615 }
2616
2617 // Prepare the argument value. If we have the trivial case, handle it
2618 // with no muss and fuss.
2619 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2620 ArgI.getCoerceToType() == ConvertType(Ty) &&
2621 ArgI.getDirectOffset() == 0) {
2622 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2622, __PRETTY_FUNCTION__))
;
2623
2624 // LLVM expects swifterror parameters to be used in very restricted
2625 // ways. Copy the value into a less-restricted temporary.
2626 llvm::Value *V = AI;
2627 if (FI.getExtParameterInfo(ArgNo).getABI()
2628 == ParameterABI::SwiftErrorResult) {
2629 QualType pointeeTy = Ty->getPointeeType();
2630 assert(pointeeTy->isPointerType())((pointeeTy->isPointerType()) ? static_cast<void> (0
) : __assert_fail ("pointeeTy->isPointerType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2630, __PRETTY_FUNCTION__))
;
2631 Address temp =
2632 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2633 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2634 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2635 Builder.CreateStore(incomingErrorValue, temp);
2636 V = temp.getPointer();
2637
2638 // Push a cleanup to copy the value back at the end of the function.
2639 // The convention does not guarantee that the value will be written
2640 // back if the function exits with an unwind exception.
2641 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2642 }
2643
2644 // Ensure the argument is the correct type.
2645 if (V->getType() != ArgI.getCoerceToType())
2646 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2647
2648 if (isPromoted)
2649 V = emitArgumentDemotion(*this, Arg, V);
2650
2651 // Because of merging of function types from multiple decls it is
2652 // possible for the type of an argument to not match the corresponding
2653 // type in the function type. Since we are codegening the callee
2654 // in here, add a cast to the argument type.
2655 llvm::Type *LTy = ConvertType(Arg->getType());
2656 if (V->getType() != LTy)
2657 V = Builder.CreateBitCast(V, LTy);
2658
2659 ArgVals.push_back(ParamValue::forDirect(V));
2660 break;
2661 }
2662
2663 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2664 Arg->getName());
2665
2666 // Pointer to store into.
2667 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2668
2669 // Fast-isel and the optimizer generally like scalar values better than
2670 // FCAs, so we flatten them if this is safe to do for this argument.
2671 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2672 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2673 STy->getNumElements() > 1) {
2674 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2675 llvm::Type *DstTy = Ptr.getElementType();
2676 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2677
2678 Address AddrToStoreInto = Address::invalid();
2679 if (SrcSize <= DstSize) {
2680 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
2681 } else {
2682 AddrToStoreInto =
2683 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2684 }
2685
2686 assert(STy->getNumElements() == NumIRArgs)((STy->getNumElements() == NumIRArgs) ? static_cast<void
> (0) : __assert_fail ("STy->getNumElements() == NumIRArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2686, __PRETTY_FUNCTION__))
;
2687 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2688 auto AI = Fn->getArg(FirstIRArg + i);
2689 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2690 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
2691 Builder.CreateStore(AI, EltPtr);
2692 }
2693
2694 if (SrcSize > DstSize) {
2695 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2696 }
2697
2698 } else {
2699 // Simple case, just do a coerced store of the argument into the alloca.
2700 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2700, __PRETTY_FUNCTION__))
;
2701 auto AI = Fn->getArg(FirstIRArg);
2702 AI->setName(Arg->getName() + ".coerce");
2703 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
2704 }
2705
2706 // Match to what EmitParmDecl is expecting for this type.
2707 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
2708 llvm::Value *V =
2709 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
2710 if (isPromoted)
2711 V = emitArgumentDemotion(*this, Arg, V);
2712 ArgVals.push_back(ParamValue::forDirect(V));
2713 } else {
2714 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2715 }
2716 break;
2717 }
2718
2719 case ABIArgInfo::CoerceAndExpand: {
2720 // Reconstruct into a temporary.
2721 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2722 ArgVals.push_back(ParamValue::forIndirect(alloca));
2723
2724 auto coercionType = ArgI.getCoerceAndExpandType();
2725 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2726
2727 unsigned argIndex = FirstIRArg;
2728 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2729 llvm::Type *eltType = coercionType->getElementType(i);
2730 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2731 continue;
2732
2733 auto eltAddr = Builder.CreateStructGEP(alloca, i);
2734 auto elt = Fn->getArg(argIndex++);
2735 Builder.CreateStore(elt, eltAddr);
2736 }
2737 assert(argIndex == FirstIRArg + NumIRArgs)((argIndex == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("argIndex == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2737, __PRETTY_FUNCTION__))
;
2738 break;
2739 }
2740
2741 case ABIArgInfo::Expand: {
2742 // If this structure was expanded into multiple arguments then
2743 // we need to create a temporary and reconstruct it from the
2744 // arguments.
2745 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2746 LValue LV = MakeAddrLValue(Alloca, Ty);
2747 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2748
2749 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
2750 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2751 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs)((FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs) ?
static_cast<void> (0) : __assert_fail ("FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2751, __PRETTY_FUNCTION__))
;
2752 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2753 auto AI = Fn->getArg(FirstIRArg + i);
2754 AI->setName(Arg->getName() + "." + Twine(i));
2755 }
2756 break;
2757 }
2758
2759 case ABIArgInfo::Ignore:
2760 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2760, __PRETTY_FUNCTION__))
;
2761 // Initialize the local variable appropriately.
2762 if (!hasScalarEvaluationKind(Ty)) {
2763 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
2764 } else {
2765 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2766 ArgVals.push_back(ParamValue::forDirect(U));
2767 }
2768 break;
2769 }
2770 }
2771
2772 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2773 for (int I = Args.size() - 1; I >= 0; --I)
2774 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2775 } else {
2776 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2777 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2778 }
2779}
2780
2781static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2782 while (insn->use_empty()) {
2783 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2784 if (!bitcast) return;
2785
2786 // This is "safe" because we would have used a ConstantExpr otherwise.
2787 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2788 bitcast->eraseFromParent();
2789 }
2790}
2791
2792/// Try to emit a fused autorelease of a return result.
2793static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2794 llvm::Value *result) {
2795 // We must be immediately followed the cast.
2796 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
2797 if (BB->empty()) return nullptr;
2798 if (&BB->back() != result) return nullptr;
2799
2800 llvm::Type *resultType = result->getType();
2801
2802 // result is in a BasicBlock and is therefore an Instruction.
2803 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2804
2805 SmallVector<llvm::Instruction *, 4> InstsToKill;
2806
2807 // Look for:
2808 // %generator = bitcast %type1* %generator2 to %type2*
2809 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2810 // We would have emitted this as a constant if the operand weren't
2811 // an Instruction.
2812 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2813
2814 // Require the generator to be immediately followed by the cast.
2815 if (generator->getNextNode() != bitcast)
2816 return nullptr;
2817
2818 InstsToKill.push_back(bitcast);
2819 }
2820
2821 // Look for:
2822 // %generator = call i8* @objc_retain(i8* %originalResult)
2823 // or
2824 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2825 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
2826 if (!call) return nullptr;
2827
2828 bool doRetainAutorelease;
2829
2830 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
2831 doRetainAutorelease = true;
2832 } else if (call->getCalledOperand() ==
2833 CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
2834 doRetainAutorelease = false;
2835
2836 // If we emitted an assembly marker for this call (and the
2837 // ARCEntrypoints field should have been set if so), go looking
2838 // for that call. If we can't find it, we can't do this
2839 // optimization. But it should always be the immediately previous
2840 // instruction, unless we needed bitcasts around the call.
2841 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
2842 llvm::Instruction *prev = call->getPrevNode();
2843 assert(prev)((prev) ? static_cast<void> (0) : __assert_fail ("prev"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2843, __PRETTY_FUNCTION__))
;
2844 if (isa<llvm::BitCastInst>(prev)) {
2845 prev = prev->getPrevNode();
2846 assert(prev)((prev) ? static_cast<void> (0) : __assert_fail ("prev"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2846, __PRETTY_FUNCTION__))
;
2847 }
2848 assert(isa<llvm::CallInst>(prev))((isa<llvm::CallInst>(prev)) ? static_cast<void> (
0) : __assert_fail ("isa<llvm::CallInst>(prev)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2848, __PRETTY_FUNCTION__))
;
2849 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==((cast<llvm::CallInst>(prev)->getCalledOperand() == CGF
.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? static_cast<void> (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledOperand() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2850, __PRETTY_FUNCTION__))
2850 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker)((cast<llvm::CallInst>(prev)->getCalledOperand() == CGF
.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker
) ? static_cast<void> (0) : __assert_fail ("cast<llvm::CallInst>(prev)->getCalledOperand() == CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2850, __PRETTY_FUNCTION__))
;
2851 InstsToKill.push_back(prev);
2852 }
2853 } else {
2854 return nullptr;
2855 }
2856
2857 result = call->getArgOperand(0);
2858 InstsToKill.push_back(call);
2859
2860 // Keep killing bitcasts, for sanity. Note that we no longer care
2861 // about precise ordering as long as there's exactly one use.
2862 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2863 if (!bitcast->hasOneUse()) break;
2864 InstsToKill.push_back(bitcast);
2865 result = bitcast->getOperand(0);
2866 }
2867
2868 // Delete all the unnecessary instructions, from latest to earliest.
2869 for (auto *I : InstsToKill)
2870 I->eraseFromParent();
2871
2872 // Do the fused retain/autorelease if we were asked to.
2873 if (doRetainAutorelease)
2874 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2875
2876 // Cast back to the result type.
2877 return CGF.Builder.CreateBitCast(result, resultType);
2878}
2879
2880/// If this is a +1 of the value of an immutable 'self', remove it.
2881static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2882 llvm::Value *result) {
2883 // This is only applicable to a method with an immutable 'self'.
2884 const ObjCMethodDecl *method =
2885 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
2886 if (!method) return nullptr;
2887 const VarDecl *self = method->getSelfDecl();
2888 if (!self->getType().isConstQualified()) return nullptr;
2889
2890 // Look for a retain call.
2891 llvm::CallInst *retainCall =
2892 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2893 if (!retainCall || retainCall->getCalledOperand() !=
2894 CGF.CGM.getObjCEntrypoints().objc_retain)
2895 return nullptr;
2896
2897 // Look for an ordinary load of 'self'.
2898 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2899 llvm::LoadInst *load =
2900 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2901 if (!load || load->isAtomic() || load->isVolatile() ||
2902 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
2903 return nullptr;
2904
2905 // Okay! Burn it all down. This relies for correctness on the
2906 // assumption that the retain is emitted as part of the return and
2907 // that thereafter everything is used "linearly".
2908 llvm::Type *resultType = result->getType();
2909 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2910 assert(retainCall->use_empty())((retainCall->use_empty()) ? static_cast<void> (0) :
__assert_fail ("retainCall->use_empty()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2910, __PRETTY_FUNCTION__))
;
2911 retainCall->eraseFromParent();
2912 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2913
2914 return CGF.Builder.CreateBitCast(load, resultType);
2915}
2916
2917/// Emit an ARC autorelease of the result of a function.
2918///
2919/// \return the value to actually return from the function
2920static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2921 llvm::Value *result) {
2922 // If we're returning 'self', kill the initial retain. This is a
2923 // heuristic attempt to "encourage correctness" in the really unfortunate
2924 // case where we have a return of self during a dealloc and we desperately
2925 // need to avoid the possible autorelease.
2926 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2927 return self;
2928
2929 // At -O0, try to emit a fused retain/autorelease.
2930 if (CGF.shouldUseFusedARCCalls())
2931 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2932 return fused;
2933
2934 return CGF.EmitARCAutoreleaseReturnValue(result);
2935}
2936
2937/// Heuristically search for a dominating store to the return-value slot.
2938static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2939 // Check if a User is a store which pointerOperand is the ReturnValue.
2940 // We are looking for stores to the ReturnValue, not for stores of the
2941 // ReturnValue to some other location.
2942 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2943 auto *SI = dyn_cast<llvm::StoreInst>(U);
2944 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2945 return nullptr;
2946 // These aren't actually possible for non-coerced returns, and we
2947 // only care about non-coerced returns on this code path.
2948 assert(!SI->isAtomic() && !SI->isVolatile())((!SI->isAtomic() && !SI->isVolatile()) ? static_cast
<void> (0) : __assert_fail ("!SI->isAtomic() && !SI->isVolatile()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 2948, __PRETTY_FUNCTION__))
;
2949 return SI;
2950 };
2951 // If there are multiple uses of the return-value slot, just check
2952 // for something immediately preceding the IP. Sometimes this can
2953 // happen with how we generate implicit-returns; it can also happen
2954 // with noreturn cleanups.
2955 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
2956 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2957 if (IP->empty()) return nullptr;
2958 llvm::Instruction *I = &IP->back();
2959
2960 // Skip lifetime markers
2961 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2962 IE = IP->rend();
2963 II != IE; ++II) {
2964 if (llvm::IntrinsicInst *Intrinsic =
2965 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2966 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2967 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2968 ++II;
2969 if (II == IE)
2970 break;
2971 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2972 continue;
2973 }
2974 }
2975 I = &*II;
2976 break;
2977 }
2978
2979 return GetStoreIfValid(I);
2980 }
2981
2982 llvm::StoreInst *store =
2983 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
2984 if (!store) return nullptr;
2985
2986 // Now do a first-and-dirty dominance check: just walk up the
2987 // single-predecessors chain from the current insertion point.
2988 llvm::BasicBlock *StoreBB = store->getParent();
2989 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2990 while (IP != StoreBB) {
2991 if (!(IP = IP->getSinglePredecessor()))
2992 return nullptr;
2993 }
2994
2995 // Okay, the store's basic block dominates the insertion point; we
2996 // can do our thing.
2997 return store;
2998}
2999
3000// Helper functions for EmitCMSEClearRecord
3001
3002// Set the bits corresponding to a field having width `BitWidth` and located at
3003// offset `BitOffset` (from the least significant bit) within a storage unit of
3004// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3005// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3006static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3007 int BitWidth, int CharWidth) {
3008 assert(CharWidth <= 64)((CharWidth <= 64) ? static_cast<void> (0) : __assert_fail
("CharWidth <= 64", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3008, __PRETTY_FUNCTION__))
;
3009 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth)((static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth
) ? static_cast<void> (0) : __assert_fail ("static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3009, __PRETTY_FUNCTION__))
;
3010
3011 int Pos = 0;
3012 if (BitOffset >= CharWidth) {
3013 Pos += BitOffset / CharWidth;
3014 BitOffset = BitOffset % CharWidth;
3015 }
3016
3017 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3018 if (BitOffset + BitWidth >= CharWidth) {
3019 Bits[Pos++] |= (Used << BitOffset) & Used;
3020 BitWidth -= CharWidth - BitOffset;
3021 BitOffset = 0;
3022 }
3023
3024 while (BitWidth >= CharWidth) {
3025 Bits[Pos++] = Used;
3026 BitWidth -= CharWidth;
3027 }
3028
3029 if (BitWidth > 0)
3030 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3031}
3032
3033// Set the bits corresponding to a field having width `BitWidth` and located at
3034// offset `BitOffset` (from the least significant bit) within a storage unit of
3035// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3036// `Bits` corresponds to one target byte. Use target endian layout.
3037static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3038 int StorageSize, int BitOffset, int BitWidth,
3039 int CharWidth, bool BigEndian) {
3040
3041 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3042 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3043
3044 if (BigEndian)
3045 std::reverse(TmpBits.begin(), TmpBits.end());
3046
3047 for (uint64_t V : TmpBits)
3048 Bits[StorageOffset++] |= V;
3049}
3050
3051static void setUsedBits(CodeGenModule &, QualType, int,
3052 SmallVectorImpl<uint64_t> &);
3053
3054// Set the bits in `Bits`, which correspond to the value representations of
3055// the actual members of the record type `RTy`. Note that this function does
3056// not handle base classes, virtual tables, etc, since they cannot happen in
3057// CMSE function arguments or return. The bit mask corresponds to the target
3058// memory layout, i.e. it's endian dependent.
3059static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3060 SmallVectorImpl<uint64_t> &Bits) {
3061 ASTContext &Context = CGM.getContext();
3062 int CharWidth = Context.getCharWidth();
3063 const RecordDecl *RD = RTy->getDecl()->getDefinition();
4
Called C++ object pointer is null
3064 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3065 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3066
3067 int Idx = 0;
3068 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3069 const FieldDecl *F = *I;
3070
3071 if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3072 F->getType()->isIncompleteArrayType())
3073 continue;
3074
3075 if (F->isBitField()) {
3076 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3077 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3078 BFI.StorageSize / CharWidth, BFI.Offset,
3079 BFI.Size, CharWidth,
3080 CGM.getDataLayout().isBigEndian());
3081 continue;
3082 }
3083
3084 setUsedBits(CGM, F->getType(),
3085 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3086 }
3087}
3088
3089// Set the bits in `Bits`, which correspond to the value representations of
3090// the elements of an array type `ATy`.
3091static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3092 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3093 const ASTContext &Context = CGM.getContext();
3094
3095 QualType ETy = Context.getBaseElementType(ATy);
3096 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3097 SmallVector<uint64_t, 4> TmpBits(Size);
3098 setUsedBits(CGM, ETy, 0, TmpBits);
3099
3100 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3101 auto Src = TmpBits.begin();
3102 auto Dst = Bits.begin() + Offset + I * Size;
3103 for (int J = 0; J < Size; ++J)
3104 *Dst++ |= *Src++;
3105 }
3106}
3107
3108// Set the bits in `Bits`, which correspond to the value representations of
3109// the type `QTy`.
3110static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3111 SmallVectorImpl<uint64_t> &Bits) {
3112 if (const auto *RTy = QTy->getAs<RecordType>())
3113 return setUsedBits(CGM, RTy, Offset, Bits);
3114
3115 ASTContext &Context = CGM.getContext();
3116 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3117 return setUsedBits(CGM, ATy, Offset, Bits);
3118
3119 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3120 if (Size <= 0)
3121 return;
3122
3123 std::fill_n(Bits.begin() + Offset, Size,
3124 (uint64_t(1) << Context.getCharWidth()) - 1);
3125}
3126
3127static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3128 int Pos, int Size, int CharWidth,
3129 bool BigEndian) {
3130 assert(Size > 0)((Size > 0) ? static_cast<void> (0) : __assert_fail (
"Size > 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3130, __PRETTY_FUNCTION__))
;
3131 uint64_t Mask = 0;
3132 if (BigEndian) {
3133 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3134 ++P)
3135 Mask = (Mask << CharWidth) | *P;
3136 } else {
3137 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3138 do
3139 Mask = (Mask << CharWidth) | *--P;
3140 while (P != End);
3141 }
3142 return Mask;
3143}
3144
3145// Emit code to clear the bits in a record, which aren't a part of any user
3146// declared member, when the record is a function return.
3147llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3148 llvm::IntegerType *ITy,
3149 QualType QTy) {
3150 assert(Src->getType() == ITy)((Src->getType() == ITy) ? static_cast<void> (0) : __assert_fail
("Src->getType() == ITy", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3150, __PRETTY_FUNCTION__))
;
3151 assert(ITy->getScalarSizeInBits() <= 64)((ITy->getScalarSizeInBits() <= 64) ? static_cast<void
> (0) : __assert_fail ("ITy->getScalarSizeInBits() <= 64"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3151, __PRETTY_FUNCTION__))
;
3152
3153 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3154 int Size = DataLayout.getTypeStoreSize(ITy);
3155 SmallVector<uint64_t, 4> Bits(Size);
3156 setUsedBits(CGM, QTy->getAs<RecordType>(), 0, Bits);
3157
3158 int CharWidth = CGM.getContext().getCharWidth();
3159 uint64_t Mask =
3160 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3161
3162 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3163}
3164
3165// Emit code to clear the bits in a record, which aren't a part of any user
3166// declared member, when the record is a function argument.
3167llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3168 llvm::ArrayType *ATy,
3169 QualType QTy) {
3170 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3171 int Size = DataLayout.getTypeStoreSize(ATy);
3172 SmallVector<uint64_t, 16> Bits(Size);
3173 setUsedBits(CGM, QTy->getAs<RecordType>(), 0, Bits);
1
Assuming the object is not a 'RecordType'
2
Passing null pointer value via 2nd parameter 'RTy'
3
Calling 'setUsedBits'
3174
3175 // Clear each element of the LLVM array.
3176 int CharWidth = CGM.getContext().getCharWidth();
3177 int CharsPerElt =
3178 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3179 int MaskIndex = 0;
3180 llvm::Value *R = llvm::UndefValue::get(ATy);
3181 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3182 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3183 DataLayout.isBigEndian());
3184 MaskIndex += CharsPerElt;
3185 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3186 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3187 R = Builder.CreateInsertValue(R, T1, I);
3188 }
3189
3190 return R;
3191}
3192
3193void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
3194 bool EmitRetDbgLoc,
3195 SourceLocation EndLoc) {
3196 if (FI.isNoReturn()) {
3197 // Noreturn functions don't return.
3198 EmitUnreachable(EndLoc);
3199 return;
3200 }
3201
3202 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3203 // Naked functions don't have epilogues.
3204 Builder.CreateUnreachable();
3205 return;
3206 }
3207
3208 // Functions with no result always return void.
3209 if (!ReturnValue.isValid()) {
3210 Builder.CreateRetVoid();
3211 return;
3212 }
3213
3214 llvm::DebugLoc RetDbgLoc;
3215 llvm::Value *RV = nullptr;
3216 QualType RetTy = FI.getReturnType();
3217 const ABIArgInfo &RetAI = FI.getReturnInfo();
3218
3219 switch (RetAI.getKind()) {
3220 case ABIArgInfo::InAlloca:
3221 // Aggregrates get evaluated directly into the destination. Sometimes we
3222 // need to return the sret value in a register, though.
3223 assert(hasAggregateEvaluationKind(RetTy))((hasAggregateEvaluationKind(RetTy)) ? static_cast<void>
(0) : __assert_fail ("hasAggregateEvaluationKind(RetTy)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3223, __PRETTY_FUNCTION__))
;
3224 if (RetAI.getInAllocaSRet()) {
3225 llvm::Function::arg_iterator EI = CurFn->arg_end();
3226 --EI;
3227 llvm::Value *ArgStruct = &*EI;
3228 llvm::Value *SRet = Builder.CreateStructGEP(
3229 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
3230 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
3231 }
3232 break;
3233
3234 case ABIArgInfo::Indirect: {
3235 auto AI = CurFn->arg_begin();
3236 if (RetAI.isSRetAfterThis())
3237 ++AI;
3238 switch (getEvaluationKind(RetTy)) {
3239 case TEK_Complex: {
3240 ComplexPairTy RT =
3241 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3242 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
3243 /*isInit*/ true);
3244 break;
3245 }
3246 case TEK_Aggregate:
3247 // Do nothing; aggregrates get evaluated directly into the destination.
3248 break;
3249 case TEK_Scalar:
3250 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
3251 MakeNaturalAlignAddrLValue(&*AI, RetTy),
3252 /*isInit*/ true);
3253 break;
3254 }
3255 break;
3256 }
3257
3258 case ABIArgInfo::Extend:
3259 case ABIArgInfo::Direct:
3260 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3261 RetAI.getDirectOffset() == 0) {
3262 // The internal return value temp always will have pointer-to-return-type
3263 // type, just do a load.
3264
3265 // If there is a dominating store to ReturnValue, we can elide
3266 // the load, zap the store, and usually zap the alloca.
3267 if (llvm::StoreInst *SI =
3268 findDominatingStoreToReturnValue(*this)) {
3269 // Reuse the debug location from the store unless there is
3270 // cleanup code to be emitted between the store and return
3271 // instruction.
3272 if (EmitRetDbgLoc && !AutoreleaseResult)
3273 RetDbgLoc = SI->getDebugLoc();
3274 // Get the stored value and nuke the now-dead store.
3275 RV = SI->getValueOperand();
3276 SI->eraseFromParent();
3277
3278 // Otherwise, we have to do a simple load.
3279 } else {
3280 RV = Builder.CreateLoad(ReturnValue);
3281 }
3282 } else {
3283 // If the value is offset in memory, apply the offset now.
3284 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3285
3286 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3287 }
3288
3289 // In ARC, end functions that return a retainable type with a call
3290 // to objc_autoreleaseReturnValue.
3291 if (AutoreleaseResult) {
3292#ifndef NDEBUG
3293 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3294 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3295 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3296 // CurCodeDecl or BlockInfo.
3297 QualType RT;
3298
3299 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3300 RT = FD->getReturnType();
3301 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3302 RT = MD->getReturnType();
3303 else if (isa<BlockDecl>(CurCodeDecl))
3304 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
3305 else
3306 llvm_unreachable("Unexpected function/method type")::llvm::llvm_unreachable_internal("Unexpected function/method type"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3306)
;
3307
3308 assert(getLangOpts().ObjCAutoRefCount &&((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3310, __PRETTY_FUNCTION__))
3309 !FI.isReturnsRetained() &&((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3310, __PRETTY_FUNCTION__))
3310 RT->isObjCRetainableType())((getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained
() && RT->isObjCRetainableType()) ? static_cast<
void> (0) : __assert_fail ("getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() && RT->isObjCRetainableType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3310, __PRETTY_FUNCTION__))
;
3311#endif
3312 RV = emitAutoreleaseOfResult(*this, RV);
3313 }
3314
3315 break;
3316
3317 case ABIArgInfo::Ignore:
3318 break;
3319
3320 case ABIArgInfo::CoerceAndExpand: {
3321 auto coercionType = RetAI.getCoerceAndExpandType();
3322
3323 // Load all of the coerced elements out into results.
3324 llvm::SmallVector<llvm::Value*, 4> results;
3325 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
3326 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3327 auto coercedEltType = coercionType->getElementType(i);
3328 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3329 continue;
3330
3331 auto eltAddr = Builder.CreateStructGEP(addr, i);
3332 auto elt = Builder.CreateLoad(eltAddr);
3333 results.push_back(elt);
3334 }
3335
3336 // If we have one result, it's the single direct result type.
3337 if (results.size() == 1) {
3338 RV = results[0];
3339
3340 // Otherwise, we need to make a first-class aggregate.
3341 } else {
3342 // Construct a return type that lacks padding elements.
3343 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3344
3345 RV = llvm::UndefValue::get(returnType);
3346 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3347 RV = Builder.CreateInsertValue(RV, results[i], i);
3348 }
3349 }
3350 break;
3351 }
3352 case ABIArgInfo::Expand:
3353 case ABIArgInfo::IndirectAliased:
3354 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3354)
;
3355 }
3356
3357 llvm::Instruction *Ret;
3358 if (RV) {
3359 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3360 // For certain return types, clear padding bits, as they may reveal
3361 // sensitive information.
3362 // Small struct/union types are passed as integers.
3363 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3364 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3365 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3366 }
3367 EmitReturnValueCheck(RV);
3368 Ret = Builder.CreateRet(RV);
3369 } else {
3370 Ret = Builder.CreateRetVoid();
3371 }
3372
3373 if (RetDbgLoc)
3374 Ret->setDebugLoc(std::move(RetDbgLoc));
3375}
3376
3377void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3378 // A current decl may not be available when emitting vtable thunks.
3379 if (!CurCodeDecl)
3380 return;
3381
3382 // If the return block isn't reachable, neither is this check, so don't emit
3383 // it.
3384 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3385 return;
3386
3387 ReturnsNonNullAttr *RetNNAttr = nullptr;
3388 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3389 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3390
3391 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3392 return;
3393
3394 // Prefer the returns_nonnull attribute if it's present.
3395 SourceLocation AttrLoc;
3396 SanitizerMask CheckKind;
3397 SanitizerHandler Handler;
3398 if (RetNNAttr) {
3399 assert(!requiresReturnValueNullabilityCheck() &&((!requiresReturnValueNullabilityCheck() && "Cannot check nullability and the nonnull attribute"
) ? static_cast<void> (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3400, __PRETTY_FUNCTION__))
3400 "Cannot check nullability and the nonnull attribute")((!requiresReturnValueNullabilityCheck() && "Cannot check nullability and the nonnull attribute"
) ? static_cast<void> (0) : __assert_fail ("!requiresReturnValueNullabilityCheck() && \"Cannot check nullability and the nonnull attribute\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3400, __PRETTY_FUNCTION__))
;
3401 AttrLoc = RetNNAttr->getLocation();
3402 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
3403 Handler = SanitizerHandler::NonnullReturn;
3404 } else {
3405 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3406 if (auto *TSI = DD->getTypeSourceInfo())
3407 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
3408 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3409 CheckKind = SanitizerKind::NullabilityReturn;
3410 Handler = SanitizerHandler::NullabilityReturn;
3411 }
3412
3413 SanitizerScope SanScope(this);
3414
3415 // Make sure the "return" source location is valid. If we're checking a
3416 // nullability annotation, make sure the preconditions for the check are met.
3417 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3418 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3419 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3420 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3421 if (requiresReturnValueNullabilityCheck())
3422 CanNullCheck =
3423 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3424 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3425 EmitBlock(Check);
3426
3427 // Now do the null check.
3428 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3429 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3430 llvm::Value *DynamicData[] = {SLocPtr};
3431 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3432
3433 EmitBlock(NoCheck);
3434
3435#ifndef NDEBUG
3436 // The return location should not be used after the check has been emitted.
3437 ReturnLocation = Address::invalid();
3438#endif
3439}
3440
3441static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3442 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3443 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3444}
3445
3446static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3447 QualType Ty) {
3448 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3449 // placeholders.
3450 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3451 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3452 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
3453
3454 // FIXME: When we generate this IR in one pass, we shouldn't need
3455 // this win32-specific alignment hack.
3456 CharUnits Align = CharUnits::fromQuantity(4);
3457 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3458
3459 return AggValueSlot::forAddr(Address(Placeholder, Align),
3460 Ty.getQualifiers(),
3461 AggValueSlot::IsNotDestructed,
3462 AggValueSlot::DoesNotNeedGCBarriers,
3463 AggValueSlot::IsNotAliased,
3464 AggValueSlot::DoesNotOverlap);
3465}
3466
3467void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3468 const VarDecl *param,
3469 SourceLocation loc) {
3470 // StartFunction converted the ABI-lowered parameter(s) into a
3471 // local alloca. We need to turn that into an r-value suitable
3472 // for EmitCall.
3473 Address local = GetAddrOfLocalVar(param);
3474
3475 QualType type = param->getType();
3476
3477 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3478 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3479 }
3480
3481 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3482 // but the argument needs to be the original pointer.
3483 if (type->isReferenceType()) {
3484 args.add(RValue::get(Builder.CreateLoad(local)), type);
3485
3486 // In ARC, move out of consumed arguments so that the release cleanup
3487 // entered by StartFunction doesn't cause an over-release. This isn't
3488 // optimal -O0 code generation, but it should get cleaned up when
3489 // optimization is enabled. This also assumes that delegate calls are
3490 // performed exactly once for a set of arguments, but that should be safe.
3491 } else if (getLangOpts().ObjCAutoRefCount &&
3492 param->hasAttr<NSConsumedAttr>() &&
3493 type->isObjCRetainableType()) {
3494 llvm::Value *ptr = Builder.CreateLoad(local);
3495 auto null =
3496 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3497 Builder.CreateStore(null, local);
3498 args.add(RValue::get(ptr), type);
3499
3500 // For the most part, we just need to load the alloca, except that
3501 // aggregate r-values are actually pointers to temporaries.
3502 } else {
3503 args.add(convertTempToRValue(local, type, loc), type);
3504 }
3505
3506 // Deactivate the cleanup for the callee-destructed param that was pushed.
3507 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk &&
3508 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3509 param->needsDestruction(getContext())) {
3510 EHScopeStack::stable_iterator cleanup =
3511 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3512 assert(cleanup.isValid() &&((cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? static_cast<void> (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3513, __PRETTY_FUNCTION__))
3513 "cleanup for callee-destructed param not recorded")((cleanup.isValid() && "cleanup for callee-destructed param not recorded"
) ? static_cast<void> (0) : __assert_fail ("cleanup.isValid() && \"cleanup for callee-destructed param not recorded\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3513, __PRETTY_FUNCTION__))
;
3514 // This unreachable is a temporary marker which will be removed later.
3515 llvm::Instruction *isActive = Builder.CreateUnreachable();
3516 args.addArgCleanupDeactivation(cleanup, isActive);
3517 }
3518}
3519
3520static bool isProvablyNull(llvm::Value *addr) {
3521 return isa<llvm::ConstantPointerNull>(addr);
3522}
3523
3524/// Emit the actual writing-back of a writeback.
3525static void emitWriteback(CodeGenFunction &CGF,
3526 const CallArgList::Writeback &writeback) {
3527 const LValue &srcLV = writeback.Source;
3528 Address srcAddr = srcLV.getAddress(CGF);
3529 assert(!isProvablyNull(srcAddr.getPointer()) &&((!isProvablyNull(srcAddr.getPointer()) && "shouldn't have writeback for provably null argument"
) ? static_cast<void> (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3530, __PRETTY_FUNCTION__))
3530 "shouldn't have writeback for provably null argument")((!isProvablyNull(srcAddr.getPointer()) && "shouldn't have writeback for provably null argument"
) ? static_cast<void> (0) : __assert_fail ("!isProvablyNull(srcAddr.getPointer()) && \"shouldn't have writeback for provably null argument\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3530, __PRETTY_FUNCTION__))
;
3531
3532 llvm::BasicBlock *contBB = nullptr;
3533
3534 // If the argument wasn't provably non-null, we need to null check
3535 // before doing the store.
3536 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3537 CGF.CGM.getDataLayout());
3538 if (!provablyNonNull) {
3539 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3540 contBB = CGF.createBasicBlock("icr.done");
3541
3542 llvm::Value *isNull =
3543 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3544 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3545 CGF.EmitBlock(writebackBB);
3546 }
3547
3548 // Load the value to writeback.
3549 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3550
3551 // Cast it back, in case we're writing an id to a Foo* or something.
3552 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3553 "icr.writeback-cast");
3554
3555 // Perform the writeback.
3556
3557 // If we have a "to use" value, it's something we need to emit a use
3558 // of. This has to be carefully threaded in: if it's done after the
3559 // release it's potentially undefined behavior (and the optimizer
3560 // will ignore it), and if it happens before the retain then the
3561 // optimizer could move the release there.
3562 if (writeback.ToUse) {
3563 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong)((srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) ? static_cast
<void> (0) : __assert_fail ("srcLV.getObjCLifetime() == Qualifiers::OCL_Strong"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3563, __PRETTY_FUNCTION__))
;
3564
3565 // Retain the new value. No need to block-copy here: the block's
3566 // being passed up the stack.
3567 value = CGF.EmitARCRetainNonBlock(value);
3568
3569 // Emit the intrinsic use here.
3570 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3571
3572 // Load the old value (primitively).
3573 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3574
3575 // Put the new value in place (primitively).
3576 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3577
3578 // Release the old value.
3579 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3580
3581 // Otherwise, we can just do a normal lvalue store.
3582 } else {
3583 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3584 }
3585
3586 // Jump to the continuation block.
3587 if (!provablyNonNull)
3588 CGF.EmitBlock(contBB);
3589}
3590
3591static void emitWritebacks(CodeGenFunction &CGF,
3592 const CallArgList &args) {
3593 for (const auto &I : args.writebacks())
3594 emitWriteback(CGF, I);
3595}
3596
3597static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3598 const CallArgList &CallArgs) {
3599 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3600 CallArgs.getCleanupsToDeactivate();
3601 // Iterate in reverse to increase the likelihood of popping the cleanup.
3602 for (const auto &I : llvm::reverse(Cleanups)) {
3603 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3604 I.IsActiveIP->eraseFromParent();
3605 }
3606}
3607
3608static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3609 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3610 if (uop->getOpcode() == UO_AddrOf)
3611 return uop->getSubExpr();
3612 return nullptr;
3613}
3614
3615/// Emit an argument that's being passed call-by-writeback. That is,
3616/// we are passing the address of an __autoreleased temporary; it
3617/// might be copy-initialized with the current value of the given
3618/// address, but it will definitely be copied out of after the call.
3619static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3620 const ObjCIndirectCopyRestoreExpr *CRE) {
3621 LValue srcLV;
3622
3623 // Make an optimistic effort to emit the address as an l-value.
3624 // This can fail if the argument expression is more complicated.
3625 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3626 srcLV = CGF.EmitLValue(lvExpr);
3627
3628 // Otherwise, just emit it as a scalar.
3629 } else {
3630 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3631
3632 QualType srcAddrType =
3633 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3634 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3635 }
3636 Address srcAddr = srcLV.getAddress(CGF);
3637
3638 // The dest and src types don't necessarily match in LLVM terms
3639 // because of the crazy ObjC compatibility rules.
3640
3641 llvm::PointerType *destType =
3642 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3643
3644 // If the address is a constant null, just pass the appropriate null.
3645 if (isProvablyNull(srcAddr.getPointer())) {
3646 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3647 CRE->getType());
3648 return;
3649 }
3650
3651 // Create the temporary.
3652 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3653 CGF.getPointerAlign(),
3654 "icr.temp");
3655 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3656 // and that cleanup will be conditional if we can't prove that the l-value
3657 // isn't null, so we need to register a dominating point so that the cleanups
3658 // system will make valid IR.
3659 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3660
3661 // Zero-initialize it if we're not doing a copy-initialization.
3662 bool shouldCopy = CRE->shouldCopy();
3663 if (!shouldCopy) {
3664 llvm::Value *null =
3665 llvm::ConstantPointerNull::get(
3666 cast<llvm::PointerType>(destType->getElementType()));
3667 CGF.Builder.CreateStore(null, temp);
3668 }
3669
3670 llvm::BasicBlock *contBB = nullptr;
3671 llvm::BasicBlock *originBB = nullptr;
3672
3673 // If the address is *not* known to be non-null, we need to switch.
3674 llvm::Value *finalArgument;
3675
3676 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3677 CGF.CGM.getDataLayout());
3678 if (provablyNonNull) {
3679 finalArgument = temp.getPointer();
3680 } else {
3681 llvm::Value *isNull =
3682 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3683
3684 finalArgument = CGF.Builder.CreateSelect(isNull,
3685 llvm::ConstantPointerNull::get(destType),
3686 temp.getPointer(), "icr.argument");
3687
3688 // If we need to copy, then the load has to be conditional, which
3689 // means we need control flow.
3690 if (shouldCopy) {
3691 originBB = CGF.Builder.GetInsertBlock();
3692 contBB = CGF.createBasicBlock("icr.cont");
3693 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3694 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3695 CGF.EmitBlock(copyBB);
3696 condEval.begin(CGF);
3697 }
3698 }
3699
3700 llvm::Value *valueToUse = nullptr;
3701
3702 // Perform a copy if necessary.
3703 if (shouldCopy) {
3704 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
3705 assert(srcRV.isScalar())((srcRV.isScalar()) ? static_cast<void> (0) : __assert_fail
("srcRV.isScalar()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3705, __PRETTY_FUNCTION__))
;
3706
3707 llvm::Value *src = srcRV.getScalarVal();
3708 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3709 "icr.cast");
3710
3711 // Use an ordinary store, not a store-to-lvalue.
3712 CGF.Builder.CreateStore(src, temp);
3713
3714 // If optimization is enabled, and the value was held in a
3715 // __strong variable, we need to tell the optimizer that this
3716 // value has to stay alive until we're doing the store back.
3717 // This is because the temporary is effectively unretained,
3718 // and so otherwise we can violate the high-level semantics.
3719 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3720 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3721 valueToUse = src;
3722 }
3723 }
3724
3725 // Finish the control flow if we needed it.
3726 if (shouldCopy && !provablyNonNull) {
3727 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
3728 CGF.EmitBlock(contBB);
3729
3730 // Make a phi for the value to intrinsically use.
3731 if (valueToUse) {
3732 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3733 "icr.to-use");
3734 phiToUse->addIncoming(valueToUse, copyBB);
3735 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3736 originBB);
3737 valueToUse = phiToUse;
3738 }
3739
3740 condEval.end(CGF);
3741 }
3742
3743 args.addWriteback(srcLV, temp, valueToUse);
3744 args.add(RValue::get(finalArgument), CRE->getType());
3745}
3746
3747void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3748 assert(!StackBase)((!StackBase) ? static_cast<void> (0) : __assert_fail (
"!StackBase", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3748, __PRETTY_FUNCTION__))
;
3749
3750 // Save the stack.
3751 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
3752 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
3753}
3754
3755void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3756 if (StackBase) {
3757 // Restore the stack after the call.
3758 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
3759 CGF.Builder.CreateCall(F, StackBase);
3760 }
3761}
3762
3763void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3764 SourceLocation ArgLoc,
3765 AbstractCallee AC,
3766 unsigned ParmNum) {
3767 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3768 SanOpts.has(SanitizerKind::NullabilityArg)))
3769 return;
3770
3771 // The param decl may be missing in a variadic function.
3772 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
3773 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3774
3775 // Prefer the nonnull attribute if it's present.
3776 const NonNullAttr *NNAttr = nullptr;
3777 if (SanOpts.has(SanitizerKind::NonnullAttribute))
3778 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
3779
3780 bool CanCheckNullability = false;
3781 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
3782 auto Nullability = PVD->getType()->getNullability(getContext());
3783 CanCheckNullability = Nullability &&
3784 *Nullability == NullabilityKind::NonNull &&
3785 PVD->getTypeSourceInfo();
3786 }
3787
3788 if (!NNAttr && !CanCheckNullability)
3789 return;
3790
3791 SourceLocation AttrLoc;
3792 SanitizerMask CheckKind;
3793 SanitizerHandler Handler;
3794 if (NNAttr) {
3795 AttrLoc = NNAttr->getLocation();
3796 CheckKind = SanitizerKind::NonnullAttribute;
3797 Handler = SanitizerHandler::NonnullArg;
3798 } else {
3799 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
3800 CheckKind = SanitizerKind::NullabilityArg;
3801 Handler = SanitizerHandler::NullabilityArg;
3802 }
3803
3804 SanitizerScope SanScope(this);
3805 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
3806 llvm::Constant *StaticData[] = {
3807 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
3808 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
3809 };
3810 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
3811}
3812
3813void CodeGenFunction::EmitCallArgs(
3814 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3815 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3816 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
3817 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()))(((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())
) ? static_cast<void> (0) : __assert_fail ("(int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3817, __PRETTY_FUNCTION__))
;
3818
3819 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3820 // because arguments are destroyed left to right in the callee. As a special
3821 // case, there are certain language constructs that require left-to-right
3822 // evaluation, and in those cases we consider the evaluation order requirement
3823 // to trump the "destruction order is reverse construction order" guarantee.
3824 bool LeftToRight =
3825 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3826 ? Order == EvaluationOrder::ForceLeftToRight
3827 : Order != EvaluationOrder::ForceRightToLeft;
3828
3829 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3830 RValue EmittedArg) {
3831 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
3832 return;
3833 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3834 if (PS == nullptr)
3835 return;
3836
3837 const auto &Context = getContext();
3838 auto SizeTy = Context.getSizeType();
3839 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3840 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?")((EmittedArg.getScalarVal() && "We emitted nothing for the arg?"
) ? static_cast<void> (0) : __assert_fail ("EmittedArg.getScalarVal() && \"We emitted nothing for the arg?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3840, __PRETTY_FUNCTION__))
;
3841 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3842 EmittedArg.getScalarVal(),
3843 PS->isDynamic());
3844 Args.add(RValue::get(V), SizeTy);
3845 // If we're emitting args in reverse, be sure to do so with
3846 // pass_object_size, as well.
3847 if (!LeftToRight)
3848 std::swap(Args.back(), *(&Args.back() - 1));
3849 };
3850
3851 // Insert a stack save if we're going to need any inalloca args.
3852 bool HasInAllocaArgs = false;
3853 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3854 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3855 I != E && !HasInAllocaArgs; ++I)
3856 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3857 if (HasInAllocaArgs) {
3858 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)((getTarget().getTriple().getArch() == llvm::Triple::x86) ? static_cast
<void> (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3858, __PRETTY_FUNCTION__))
;
3859 Args.allocateArgumentMemory(*this);
3860 }
3861 }
3862
3863 // Evaluate each argument in the appropriate order.
3864 size_t CallArgsStart = Args.size();
3865 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3866 unsigned Idx = LeftToRight ? I : E - I - 1;
3867 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
3868 unsigned InitialArgSize = Args.size();
3869 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
3870 // the argument and parameter match or the objc method is parameterized.
3871 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
3872 getContext().hasSameUnqualifiedType((*Arg)->getType(),(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
3873 ArgTypes[Idx]) ||(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
3874 (isa<ObjCMethodDecl>(AC.getDecl()) &&(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
3875 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
3876 "Argument and parameter types don't match")(((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext
().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]
) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams
(cast<ObjCMethodDecl>(AC.getDecl())))) && "Argument and parameter types don't match"
) ? static_cast<void> (0) : __assert_fail ("(!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || getContext().hasSameUnqualifiedType((*Arg)->getType(), ArgTypes[Idx]) || (isa<ObjCMethodDecl>(AC.getDecl()) && isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && \"Argument and parameter types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3876, __PRETTY_FUNCTION__))
;
3877 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
3878 // In particular, we depend on it being the last arg in Args, and the
3879 // objectsize bits depend on there only being one arg if !LeftToRight.
3880 assert(InitialArgSize + 1 == Args.size() &&((InitialArgSize + 1 == Args.size() && "The code below depends on only adding one arg per EmitCallArg"
) ? static_cast<void> (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3881, __PRETTY_FUNCTION__))
3881 "The code below depends on only adding one arg per EmitCallArg")((InitialArgSize + 1 == Args.size() && "The code below depends on only adding one arg per EmitCallArg"
) ? static_cast<void> (0) : __assert_fail ("InitialArgSize + 1 == Args.size() && \"The code below depends on only adding one arg per EmitCallArg\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3881, __PRETTY_FUNCTION__))
;
3882 (void)InitialArgSize;
3883 // Since pointer argument are never emitted as LValue, it is safe to emit
3884 // non-null argument check for r-value only.
3885 if (!Args.back().hasLValue()) {
3886 RValue RVArg = Args.back().getKnownRValue();
3887 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
3888 ParamsToSkip + Idx);
3889 // @llvm.objectsize should never have side-effects and shouldn't need
3890 // destruction/cleanups, so we can safely "emit" it after its arg,
3891 // regardless of right-to-leftness
3892 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
3893 }
3894 }
3895
3896 if (!LeftToRight) {
3897 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3898 // IR function.
3899 std::reverse(Args.begin() + CallArgsStart, Args.end());
3900 }
3901}
3902
3903namespace {
3904
3905struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
3906 DestroyUnpassedArg(Address Addr, QualType Ty)
3907 : Addr(Addr), Ty(Ty) {}
3908
3909 Address Addr;
3910 QualType Ty;
3911
3912 void Emit(CodeGenFunction &CGF, Flags flags) override {
3913 QualType::DestructionKind DtorKind = Ty.isDestructedType();
3914 if (DtorKind == QualType::DK_cxx_destructor) {
3915 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3916 assert(!Dtor->isTrivial())((!Dtor->isTrivial()) ? static_cast<void> (0) : __assert_fail
("!Dtor->isTrivial()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3916, __PRETTY_FUNCTION__))
;
3917 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3918 /*Delegating=*/false, Addr, Ty);
3919 } else {
3920 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
3921 }
3922 }
3923};
3924
3925struct DisableDebugLocationUpdates {
3926 CodeGenFunction &CGF;
3927 bool disabledDebugInfo;
3928 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3929 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3930 CGF.disableDebugInfo();
3931 }
3932 ~DisableDebugLocationUpdates() {
3933 if (disabledDebugInfo)
3934 CGF.enableDebugInfo();
3935 }
3936};
3937
3938} // end anonymous namespace
3939
3940RValue CallArg::getRValue(CodeGenFunction &CGF) const {
3941 if (!HasLV)
3942 return RV;
3943 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
3944 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
3945 LV.isVolatile());
3946 IsUsed = true;
3947 return RValue::getAggregate(Copy.getAddress(CGF));
3948}
3949
3950void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
3951 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
3952 if (!HasLV && RV.isScalar())
3953 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
3954 else if (!HasLV && RV.isComplex())
3955 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
3956 else {
3957 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
3958 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
3959 // We assume that call args are never copied into subobjects.
3960 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
3961 HasLV ? LV.isVolatileQualified()
3962 : RV.isVolatileQualified());
3963 }
3964 IsUsed = true;
3965}
3966
3967void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3968 QualType type) {
3969 DisableDebugLocationUpdates Dis(*this, E);
3970 if (const ObjCIndirectCopyRestoreExpr *CRE
3971 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
3972 assert(getLangOpts().ObjCAutoRefCount)((getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3972, __PRETTY_FUNCTION__))
;
3973 return emitWritebackArg(*this, args, CRE);
3974 }
3975
3976 assert(type->isReferenceType() == E->isGLValue() &&((type->isReferenceType() == E->isGLValue() && "reference binding to unmaterialized r-value!"
) ? static_cast<void> (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3977, __PRETTY_FUNCTION__))
3977 "reference binding to unmaterialized r-value!")((type->isReferenceType() == E->isGLValue() && "reference binding to unmaterialized r-value!"
) ? static_cast<void> (0) : __assert_fail ("type->isReferenceType() == E->isGLValue() && \"reference binding to unmaterialized r-value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3977, __PRETTY_FUNCTION__))
;
3978
3979 if (E->isGLValue()) {
3980 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 3980, __PRETTY_FUNCTION__))
;
3981 return args.add(EmitReferenceBindingToExpr(E), type);
3982 }
3983
3984 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3985
3986 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3987 // However, we still have to push an EH-only cleanup in case we unwind before
3988 // we make it to the call.
3989 if (HasAggregateEvalKind &&
3990 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
3991 // If we're using inalloca, use the argument memory. Otherwise, use a
3992 // temporary.
3993 AggValueSlot Slot;
3994 if (args.isUsingInAlloca())
3995 Slot = createPlaceholderSlot(*this, type);
3996 else
3997 Slot = CreateAggTemp(type, "agg.tmp");
3998
3999 bool DestroyedInCallee = true, NeedsEHCleanup = true;
4000 if (const auto *RD = type->getAsCXXRecordDecl())
4001 DestroyedInCallee = RD->hasNonTrivialDestructor();
4002 else
4003 NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
4004
4005 if (DestroyedInCallee)
4006 Slot.setExternallyDestructed();
4007
4008 EmitAggExpr(E, Slot);
4009 RValue RV = Slot.asRValue();
4010 args.add(RV, type);
4011
4012 if (DestroyedInCallee && NeedsEHCleanup) {
4013 // Create a no-op GEP between the placeholder and the cleanup so we can
4014 // RAUW it successfully. It also serves as a marker of the first
4015 // instruction where the cleanup is active.
4016 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
4017 type);
4018 // This unreachable is a temporary marker which will be removed later.
4019 llvm::Instruction *IsActive = Builder.CreateUnreachable();
4020 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
4021 }
4022 return;
4023 }
4024
4025 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4026 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
4027 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4028 assert(L.isSimple())((L.isSimple()) ? static_cast<void> (0) : __assert_fail
("L.isSimple()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4028, __PRETTY_FUNCTION__))
;
4029 args.addUncopiedAggregate(L, type);
4030 return;
4031 }
4032
4033 args.add(EmitAnyExprToTemp(E), type);
4034}
4035
4036QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4037 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4038 // implicitly widens null pointer constants that are arguments to varargs
4039 // functions to pointer-sized ints.
4040 if (!getTarget().getTriple().isOSWindows())
4041 return Arg->getType();
4042
4043 if (Arg->getType()->isIntegerType() &&
4044 getContext().getTypeSize(Arg->getType()) <
4045 getContext().getTargetInfo().getPointerWidth(0) &&
4046 Arg->isNullPointerConstant(getContext(),
4047 Expr::NPC_ValueDependentIsNotNull)) {
4048 return getContext().getIntPtrType();
4049 }
4050
4051 return Arg->getType();
4052}
4053
4054// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4055// optimizer it can aggressively ignore unwind edges.
4056void
4057CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4058 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4059 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4060 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4061 CGM.getNoObjCARCExceptionsMetadata());
4062}
4063
4064/// Emits a call to the given no-arguments nounwind runtime function.
4065llvm::CallInst *
4066CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4067 const llvm::Twine &name) {
4068 return EmitNounwindRuntimeCall(callee, None, name);
4069}
4070
4071/// Emits a call to the given nounwind runtime function.
4072llvm::CallInst *
4073CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4074 ArrayRef<llvm::Value *> args,
4075 const llvm::Twine &name) {
4076 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4077 call->setDoesNotThrow();
4078 return call;
4079}
4080
4081/// Emits a simple call (never an invoke) to the given no-arguments
4082/// runtime function.
4083llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4084 const llvm::Twine &name) {
4085 return EmitRuntimeCall(callee, None, name);
4086}
4087
4088// Calls which may throw must have operand bundles indicating which funclet
4089// they are nested within.
4090SmallVector<llvm::OperandBundleDef, 1>
4091CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4092 SmallVector<llvm::OperandBundleDef, 1> BundleList;
4093 // There is no need for a funclet operand bundle if we aren't inside a
4094 // funclet.
4095 if (!CurrentFuncletPad)
4096 return BundleList;
4097
4098 // Skip intrinsics which cannot throw.
4099 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
4100 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
4101 return BundleList;
4102
4103 BundleList.emplace_back("funclet", CurrentFuncletPad);
4104 return BundleList;
4105}
4106
4107/// Emits a simple call (never an invoke) to the given runtime function.
4108llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4109 ArrayRef<llvm::Value *> args,
4110 const llvm::Twine &name) {
4111 llvm::CallInst *call = Builder.CreateCall(
4112 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4113 call->setCallingConv(getRuntimeCC());
4114 return call;
4115}
4116
4117/// Emits a call or invoke to the given noreturn runtime function.
4118void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4119 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4120 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4121 getBundlesForFunclet(callee.getCallee());
4122
4123 if (getInvokeDest()) {
4124 llvm::InvokeInst *invoke =
4125 Builder.CreateInvoke(callee,
4126 getUnreachableBlock(),
4127 getInvokeDest(),
4128 args,
4129 BundleList);
4130 invoke->setDoesNotReturn();
4131 invoke->setCallingConv(getRuntimeCC());
4132 } else {
4133 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4134 call->setDoesNotReturn();
4135 call->setCallingConv(getRuntimeCC());
4136 Builder.CreateUnreachable();
4137 }
4138}
4139
4140/// Emits a call or invoke instruction to the given nullary runtime function.
4141llvm::CallBase *
4142CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4143 const Twine &name) {
4144 return EmitRuntimeCallOrInvoke(callee, None, name);
4145}
4146
4147/// Emits a call or invoke instruction to the given runtime function.
4148llvm::CallBase *
4149CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4150 ArrayRef<llvm::Value *> args,
4151 const Twine &name) {
4152 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4153 call->setCallingConv(getRuntimeCC());
4154 return call;
4155}
4156
4157/// Emits a call or invoke instruction to the given function, depending
4158/// on the current state of the EH stack.
4159llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4160 ArrayRef<llvm::Value *> Args,
4161 const Twine &Name) {
4162 llvm::BasicBlock *InvokeDest = getInvokeDest();
4163 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4164 getBundlesForFunclet(Callee.getCallee());
4165
4166 llvm::CallBase *Inst;
4167 if (!InvokeDest)
4168 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4169 else {
4170 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4171 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4172 Name);
4173 EmitBlock(ContBB);
4174 }
4175
4176 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4177 // optimizer it can aggressively ignore unwind edges.
4178 if (CGM.getLangOpts().ObjCAutoRefCount)
4179 AddObjCARCExceptionMetadata(Inst);
4180
4181 return Inst;
4182}
4183
4184void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4185 llvm::Value *New) {
4186 DeferredReplacements.push_back(std::make_pair(Old, New));
4187}
4188
4189namespace {
4190
4191/// Specify given \p NewAlign as the alignment of return value attribute. If
4192/// such attribute already exists, re-set it to the maximal one of two options.
4193LLVM_NODISCARD[[clang::warn_unused_result]] llvm::AttributeList
4194maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4195 const llvm::AttributeList &Attrs,
4196 llvm::Align NewAlign) {
4197 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4198 if (CurAlign >= NewAlign)
4199 return Attrs;
4200 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4201 return Attrs
4202 .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex,
4203 llvm::Attribute::AttrKind::Alignment)
4204 .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr);
4205}
4206
4207template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4208protected:
4209 CodeGenFunction &CGF;
4210
4211 /// We do nothing if this is, or becomes, nullptr.
4212 const AlignedAttrTy *AA = nullptr;
4213
4214 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4215 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4216
4217 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4218 : CGF(CGF_) {
4219 if (!FuncDecl)
4220 return;
4221 AA = FuncDecl->getAttr<AlignedAttrTy>();
4222 }
4223
4224public:
4225 /// If we can, materialize the alignment as an attribute on return value.
4226 LLVM_NODISCARD[[clang::warn_unused_result]] llvm::AttributeList
4227 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4228 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4229 return Attrs;
4230 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4231 if (!AlignmentCI)
4232 return Attrs;
4233 // We may legitimately have non-power-of-2 alignment here.
4234 // If so, this is UB land, emit it via `@llvm.assume` instead.
4235 if (!AlignmentCI->getValue().isPowerOf2())
4236 return Attrs;
4237 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4238 CGF.getLLVMContext(), Attrs,
4239 llvm::Align(
4240 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4241 AA = nullptr; // We're done. Disallow doing anything else.
4242 return NewAttrs;
4243 }
4244
4245 /// Emit alignment assumption.
4246 /// This is a general fallback that we take if either there is an offset,
4247 /// or the alignment is variable or we are sanitizing for alignment.
4248 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4249 if (!AA)
4250 return;
4251 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4252 AA->getLocation(), Alignment, OffsetCI);
4253 AA = nullptr; // We're done. Disallow doing anything else.
4254 }
4255};
4256
4257/// Helper data structure to emit `AssumeAlignedAttr`.
4258class AssumeAlignedAttrEmitter final
4259 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4260public:
4261 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4262 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4263 if (!AA)
4264 return;
4265 // It is guaranteed that the alignment/offset are constants.
4266 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4267 if (Expr *Offset = AA->getOffset()) {
4268 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4269 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4270 OffsetCI = nullptr;
4271 }
4272 }
4273};
4274
4275/// Helper data structure to emit `AllocAlignAttr`.
4276class AllocAlignAttrEmitter final
4277 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4278public:
4279 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4280 const CallArgList &CallArgs)
4281 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4282 if (!AA)
4283 return;
4284 // Alignment may or may not be a constant, and that is okay.
4285 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4286 .getRValue(CGF)
4287 .getScalarVal();
4288 }
4289};
4290
4291} // namespace
4292
4293RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
4294 const CGCallee &Callee,
4295 ReturnValueSlot ReturnValue,
4296 const CallArgList &CallArgs,
4297 llvm::CallBase **callOrInvoke,
4298 SourceLocation Loc) {
4299 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
4300
4301 assert(Callee.isOrdinary() || Callee.isVirtual())((Callee.isOrdinary() || Callee.isVirtual()) ? static_cast<
void> (0) : __assert_fail ("Callee.isOrdinary() || Callee.isVirtual()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4301, __PRETTY_FUNCTION__))
;
4302
4303 // Handle struct-return functions by passing a pointer to the
4304 // location that we would like to return into.
4305 QualType RetTy = CallInfo.getReturnType();
4306 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
4307
4308 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
4309
4310 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4311 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
4312 // We can only guarantee that a function is called from the correct
4313 // context/function based on the appropriate target attributes,
4314 // so only check in the case where we have both always_inline and target
4315 // since otherwise we could be making a conditional call after a check for
4316 // the proper cpu features (and it won't cause code generation issues due to
4317 // function based code generation).
4318 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4319 TargetDecl->hasAttr<TargetAttr>())
4320 checkTargetFeatures(Loc, FD);
4321
4322 // Some architectures (such as x86-64) have the ABI changed based on
4323 // attribute-target/features. Give them a chance to diagnose.
4324 CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4325 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4326 }
4327
4328#ifndef NDEBUG
4329 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
4330 // For an inalloca varargs function, we don't expect CallInfo to match the
4331 // function pointer's type, because the inalloca struct a will have extra
4332 // fields in it for the varargs parameters. Code later in this function
4333 // bitcasts the function pointer to the type derived from CallInfo.
4334 //
4335 // In other cases, we assert that the types match up (until pointers stop
4336 // having pointee types).
4337 llvm::Type *TypeFromVal;
4338 if (Callee.isVirtual())
4339 TypeFromVal = Callee.getVirtualFunctionType();
4340 else
4341 TypeFromVal =
4342 Callee.getFunctionPointer()->getType()->getPointerElementType();
4343 assert(IRFuncTy == TypeFromVal)((IRFuncTy == TypeFromVal) ? static_cast<void> (0) : __assert_fail
("IRFuncTy == TypeFromVal", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4343, __PRETTY_FUNCTION__))
;
4344 }
4345#endif
4346
4347 // 1. Set up the arguments.
4348
4349 // If we're using inalloca, insert the allocation after the stack save.
4350 // FIXME: Do this earlier rather than hacking it in here!
4351 Address ArgMemory = Address::invalid();
4352 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
4353 const llvm::DataLayout &DL = CGM.getDataLayout();
4354 llvm::Instruction *IP = CallArgs.getStackBase();
4355 llvm::AllocaInst *AI;
4356 if (IP) {
4357 IP = IP->getNextNode();
4358 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
4359 "argmem", IP);
4360 } else {
4361 AI = CreateTempAlloca(ArgStruct, "argmem");
4362 }
4363 auto Align = CallInfo.getArgStructAlignment();
4364 AI->setAlignment(Align.getAsAlign());
4365 AI->setUsedWithInAlloca(true);
4366 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca())((AI->isUsedWithInAlloca() && !AI->isStaticAlloca
()) ? static_cast<void> (0) : __assert_fail ("AI->isUsedWithInAlloca() && !AI->isStaticAlloca()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4366, __PRETTY_FUNCTION__))
;
4367 ArgMemory = Address(AI, Align);
4368 }
4369
4370 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
4371 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
4372
4373 // If the call returns a temporary with struct return, create a temporary
4374 // alloca to hold the result, unless one is given to us.
4375 Address SRetPtr = Address::invalid();
4376 Address SRetAlloca = Address::invalid();
4377 llvm::Value *UnusedReturnSizePtr = nullptr;
4378 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
4379 if (!ReturnValue.isNull()) {
4380 SRetPtr = ReturnValue.getValue();
4381 } else {
4382 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
4383 if (HaveInsertPoint() && ReturnValue.isUnused()) {
4384 uint64_t size =
4385 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
4386 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
4387 }
4388 }
4389 if (IRFunctionArgs.hasSRetArg()) {
4390 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
4391 } else if (RetAI.isInAlloca()) {
4392 Address Addr =
4393 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
4394 Builder.CreateStore(SRetPtr.getPointer(), Addr);
4395 }
4396 }
4397
4398 Address swiftErrorTemp = Address::invalid();
4399 Address swiftErrorArg = Address::invalid();
4400
4401 // When passing arguments using temporary allocas, we need to add the
4402 // appropriate lifetime markers. This vector keeps track of all the lifetime
4403 // markers that need to be ended right after the call.
4404 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
4405
4406 // Translate all of the arguments as necessary to match the IR lowering.
4407 assert(CallInfo.arg_size() == CallArgs.size() &&((CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4408, __PRETTY_FUNCTION__))
4408 "Mismatch between function signature & arguments.")((CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."
) ? static_cast<void> (0) : __assert_fail ("CallInfo.arg_size() == CallArgs.size() && \"Mismatch between function signature & arguments.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4408, __PRETTY_FUNCTION__))
;
4409 unsigned ArgNo = 0;
4410 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
4411 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
4412 I != E; ++I, ++info_it, ++ArgNo) {
4413 const ABIArgInfo &ArgInfo = info_it->info;
4414
4415 // Insert a padding argument to ensure proper alignment.
4416 if (IRFunctionArgs.hasPaddingArg(ArgNo))
4417 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
4418 llvm::UndefValue::get(ArgInfo.getPaddingType());
4419
4420 unsigned FirstIRArg, NumIRArgs;
4421 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
4422
4423 switch (ArgInfo.getKind()) {
4424 case ABIArgInfo::InAlloca: {
4425 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4425, __PRETTY_FUNCTION__))
;
4426 assert(getTarget().getTriple().getArch() == llvm::Triple::x86)((getTarget().getTriple().getArch() == llvm::Triple::x86) ? static_cast
<void> (0) : __assert_fail ("getTarget().getTriple().getArch() == llvm::Triple::x86"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4426, __PRETTY_FUNCTION__))
;
4427 if (I->isAggregate()) {
4428 Address Addr = I->hasLValue()
4429 ? I->getKnownLValue().getAddress(*this)
4430 : I->getKnownRValue().getAggregateAddress();
4431 llvm::Instruction *Placeholder =
4432 cast<llvm::Instruction>(Addr.getPointer());
4433
4434 if (!ArgInfo.getInAllocaIndirect()) {
4435 // Replace the placeholder with the appropriate argument slot GEP.
4436 CGBuilderTy::InsertPoint IP = Builder.saveIP();
4437 Builder.SetInsertPoint(Placeholder);
4438 Addr = Builder.CreateStructGEP(ArgMemory,
4439 ArgInfo.getInAllocaFieldIndex());
4440 Builder.restoreIP(IP);
4441 } else {
4442 // For indirect things such as overaligned structs, replace the
4443 // placeholder with a regular aggregate temporary alloca. Store the
4444 // address of this alloca into the struct.
4445 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4446 Address ArgSlot = Builder.CreateStructGEP(
4447 ArgMemory, ArgInfo.getInAllocaFieldIndex());
4448 Builder.CreateStore(Addr.getPointer(), ArgSlot);
4449 }
4450 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4451 } else if (ArgInfo.getInAllocaIndirect()) {
4452 // Make a temporary alloca and store the address of it into the argument
4453 // struct.
4454 Address Addr = CreateMemTempWithoutCast(
4455 I->Ty, getContext().getTypeAlignInChars(I->Ty),
4456 "indirect-arg-temp");
4457 I->copyInto(*this, Addr);
4458 Address ArgSlot =
4459 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4460 Builder.CreateStore(Addr.getPointer(), ArgSlot);
4461 } else {
4462 // Store the RValue into the argument struct.
4463 Address Addr =
4464 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4465 unsigned AS = Addr.getType()->getPointerAddressSpace();
4466 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
4467 // There are some cases where a trivial bitcast is not avoidable. The
4468 // definition of a type later in a translation unit may change it's type
4469 // from {}* to (%struct.foo*)*.
4470 if (Addr.getType() != MemType)
4471 Addr = Builder.CreateBitCast(Addr, MemType);
4472 I->copyInto(*this, Addr);
4473 }
4474 break;
4475 }
4476
4477 case ABIArgInfo::Indirect:
4478 case ABIArgInfo::IndirectAliased: {
4479 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4479, __PRETTY_FUNCTION__))
;
4480 if (!I->isAggregate()) {
4481 // Make a temporary alloca to pass the argument.
4482 Address Addr = CreateMemTempWithoutCast(
4483 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
4484 IRCallArgs[FirstIRArg] = Addr.getPointer();
4485
4486 I->copyInto(*this, Addr);
4487 } else {
4488 // We want to avoid creating an unnecessary temporary+copy here;
4489 // however, we need one in three cases:
4490 // 1. If the argument is not byval, and we are required to copy the
4491 // source. (This case doesn't occur on any common architecture.)
4492 // 2. If the argument is byval, RV is not sufficiently aligned, and
4493 // we cannot force it to be sufficiently aligned.
4494 // 3. If the argument is byval, but RV is not located in default
4495 // or alloca address space.
4496 Address Addr = I->hasLValue()
4497 ? I->getKnownLValue().getAddress(*this)
4498 : I->getKnownRValue().getAggregateAddress();
4499 llvm::Value *V = Addr.getPointer();
4500 CharUnits Align = ArgInfo.getIndirectAlign();
4501 const llvm::DataLayout *TD = &CGM.getDataLayout();
4502
4503 assert((FirstIRArg >= IRFuncTy->getNumParams() ||(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4506, __PRETTY_FUNCTION__))
4504 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4506, __PRETTY_FUNCTION__))
4505 TD->getAllocaAddrSpace()) &&(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4506, __PRETTY_FUNCTION__))
4506 "indirect argument must be in alloca address space")(((FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->
getParamType(FirstIRArg)->getPointerAddressSpace() == TD->
getAllocaAddrSpace()) && "indirect argument must be in alloca address space"
) ? static_cast<void> (0) : __assert_fail ("(FirstIRArg >= IRFuncTy->getNumParams() || IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == TD->getAllocaAddrSpace()) && \"indirect argument must be in alloca address space\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4506, __PRETTY_FUNCTION__))
;
4507
4508 bool NeedCopy = false;
4509
4510 if (Addr.getAlignment() < Align &&
4511 llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4512 Align.getAsAlign()) {
4513 NeedCopy = true;
4514 } else if (I->hasLValue()) {
4515 auto LV = I->getKnownLValue();
4516 auto AS = LV.getAddressSpace();
4517
4518 if (!ArgInfo.getIndirectByVal() ||
4519 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
4520 NeedCopy = true;
4521 }
4522 if (!getLangOpts().OpenCL) {
4523 if ((ArgInfo.getIndirectByVal() &&
4524 (AS != LangAS::Default &&
4525 AS != CGM.getASTAllocaAddressSpace()))) {
4526 NeedCopy = true;
4527 }
4528 }
4529 // For OpenCL even if RV is located in default or alloca address space
4530 // we don't want to perform address space cast for it.
4531 else if ((ArgInfo.getIndirectByVal() &&
4532 Addr.getType()->getAddressSpace() != IRFuncTy->
4533 getParamType(FirstIRArg)->getPointerAddressSpace())) {
4534 NeedCopy = true;
4535 }
4536 }
4537
4538 if (NeedCopy) {
4539 // Create an aligned temporary, and copy to it.
4540 Address AI = CreateMemTempWithoutCast(
4541 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
4542 IRCallArgs[FirstIRArg] = AI.getPointer();
4543
4544 // Emit lifetime markers for the temporary alloca.
4545 uint64_t ByvalTempElementSize =
4546 CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
4547 llvm::Value *LifetimeSize =
4548 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
4549
4550 // Add cleanup code to emit the end lifetime marker after the call.
4551 if (LifetimeSize) // In case we disabled lifetime markers.
4552 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
4553
4554 // Generate the copy.
4555 I->copyInto(*this, AI);
4556 } else {
4557 // Skip the extra memcpy call.
4558 auto *T = V->getType()->getPointerElementType()->getPointerTo(
4559 CGM.getDataLayout().getAllocaAddrSpace());
4560 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
4561 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
4562 true);
4563 }
4564 }
4565 break;
4566 }
4567
4568 case ABIArgInfo::Ignore:
4569 assert(NumIRArgs == 0)((NumIRArgs == 0) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4569, __PRETTY_FUNCTION__))
;
4570 break;
4571
4572 case ABIArgInfo::Extend:
4573 case ABIArgInfo::Direct: {
4574 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
4575 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
4576 ArgInfo.getDirectOffset() == 0) {
4577 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4577, __PRETTY_FUNCTION__))
;
4578 llvm::Value *V;
4579 if (!I->isAggregate())
4580 V = I->getKnownRValue().getScalarVal();
4581 else
4582 V = Builder.CreateLoad(
4583 I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4584 : I->getKnownRValue().getAggregateAddress());
4585
4586 // Implement swifterror by copying into a new swifterror argument.
4587 // We'll write back in the normal path out of the call.
4588 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
4589 == ParameterABI::SwiftErrorResult) {
4590 assert(!swiftErrorTemp.isValid() && "multiple swifterror args")((!swiftErrorTemp.isValid() && "multiple swifterror args"
) ? static_cast<void> (0) : __assert_fail ("!swiftErrorTemp.isValid() && \"multiple swifterror args\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4590, __PRETTY_FUNCTION__))
;
4591
4592 QualType pointeeTy = I->Ty->getPointeeType();
4593 swiftErrorArg =
4594 Address(V, getContext().getTypeAlignInChars(pointeeTy));
4595
4596 swiftErrorTemp =
4597 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4598 V = swiftErrorTemp.getPointer();
4599 cast<llvm::AllocaInst>(V)->setSwiftError(true);
4600
4601 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4602 Builder.CreateStore(errorValue, swiftErrorTemp);
4603 }
4604
4605 // We might have to widen integers, but we should never truncate.
4606 if (ArgInfo.getCoerceToType() != V->getType() &&
4607 V->getType()->isIntegerTy())
4608 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
4609
4610 // If the argument doesn't match, perform a bitcast to coerce it. This
4611 // can happen due to trivial type mismatches.
4612 if (FirstIRArg < IRFuncTy->getNumParams() &&
4613 V->getType() != IRFuncTy->getParamType(FirstIRArg))
4614 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
4615
4616 IRCallArgs[FirstIRArg] = V;
4617 break;
4618 }
4619
4620 // FIXME: Avoid the conversion through memory if possible.
4621 Address Src = Address::invalid();
4622 if (!I->isAggregate()) {
4623 Src = CreateMemTemp(I->Ty, "coerce");
4624 I->copyInto(*this, Src);
4625 } else {
4626 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4627 : I->getKnownRValue().getAggregateAddress();
4628 }
4629
4630 // If the value is offset in memory, apply the offset now.
4631 Src = emitAddressAtOffset(*this, Src, ArgInfo);
4632
4633 // Fast-isel and the optimizer generally like scalar values better than
4634 // FCAs, so we flatten them if this is safe to do for this argument.
4635 llvm::StructType *STy =
4636 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
4637 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
4638 llvm::Type *SrcTy = Src.getElementType();
4639 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4640 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
4641
4642 // If the source type is smaller than the destination type of the
4643 // coerce-to logic, copy the source value into a temp alloca the size
4644 // of the destination type to allow loading all of it. The bits past
4645 // the source value are left undef.
4646 if (SrcSize < DstSize) {
4647 Address TempAlloca
4648 = CreateTempAlloca(STy, Src.getAlignment(),
4649 Src.getName() + ".coerce");
4650 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
4651 Src = TempAlloca;
4652 } else {
4653 Src = Builder.CreateBitCast(Src,
4654 STy->getPointerTo(Src.getAddressSpace()));
4655 }
4656
4657 assert(NumIRArgs == STy->getNumElements())((NumIRArgs == STy->getNumElements()) ? static_cast<void
> (0) : __assert_fail ("NumIRArgs == STy->getNumElements()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4657, __PRETTY_FUNCTION__))
;
4658 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
4659 Address EltPtr = Builder.CreateStructGEP(Src, i);
4660 llvm::Value *LI = Builder.CreateLoad(EltPtr);
4661 IRCallArgs[FirstIRArg + i] = LI;
4662 }
4663 } else {
4664 // In the simple case, just pass the coerced loaded value.
4665 assert(NumIRArgs == 1)((NumIRArgs == 1) ? static_cast<void> (0) : __assert_fail
("NumIRArgs == 1", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4665, __PRETTY_FUNCTION__))
;
4666 llvm::Value *Load =
4667 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
4668
4669 if (CallInfo.isCmseNSCall()) {
4670 // For certain parameter types, clear padding bits, as they may reveal
4671 // sensitive information.
4672 // Small struct/union types are passed as integer arrays.
4673 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
4674 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
4675 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
4676 }
4677 IRCallArgs[FirstIRArg] = Load;
4678 }
4679
4680 break;
4681 }
4682
4683 case ABIArgInfo::CoerceAndExpand: {
4684 auto coercionType = ArgInfo.getCoerceAndExpandType();
4685 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4686
4687 llvm::Value *tempSize = nullptr;
4688 Address addr = Address::invalid();
4689 Address AllocaAddr = Address::invalid();
4690 if (I->isAggregate()) {
4691 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4692 : I->getKnownRValue().getAggregateAddress();
4693
4694 } else {
4695 RValue RV = I->getKnownRValue();
4696 assert(RV.isScalar())((RV.isScalar()) ? static_cast<void> (0) : __assert_fail
("RV.isScalar()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4696, __PRETTY_FUNCTION__))
; // complex should always just be direct
4697
4698 llvm::Type *scalarType = RV.getScalarVal()->getType();
4699 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
4700 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
4701
4702 // Materialize to a temporary.
4703 addr = CreateTempAlloca(
4704 RV.getScalarVal()->getType(),
4705 CharUnits::fromQuantity(std::max(
4706 (unsigned)layout->getAlignment().value(), scalarAlign)),
4707 "tmp",
4708 /*ArraySize=*/nullptr, &AllocaAddr);
4709 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
4710
4711 Builder.CreateStore(RV.getScalarVal(), addr);
4712 }
4713
4714 addr = Builder.CreateElementBitCast(addr, coercionType);
4715
4716 unsigned IRArgPos = FirstIRArg;
4717 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4718 llvm::Type *eltType = coercionType->getElementType(i);
4719 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4720 Address eltAddr = Builder.CreateStructGEP(addr, i);
4721 llvm::Value *elt = Builder.CreateLoad(eltAddr);
4722 IRCallArgs[IRArgPos++] = elt;
4723 }
4724 assert(IRArgPos == FirstIRArg + NumIRArgs)((IRArgPos == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4724, __PRETTY_FUNCTION__))
;
4725
4726 if (tempSize) {
4727 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
4728 }
4729
4730 break;
4731 }
4732
4733 case ABIArgInfo::Expand: {
4734 unsigned IRArgPos = FirstIRArg;
4735 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
4736 assert(IRArgPos == FirstIRArg + NumIRArgs)((IRArgPos == FirstIRArg + NumIRArgs) ? static_cast<void>
(0) : __assert_fail ("IRArgPos == FirstIRArg + NumIRArgs", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4736, __PRETTY_FUNCTION__))
;
4737 break;
4738 }
4739 }
4740 }
4741
4742 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
4743 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
4744
4745 // If we're using inalloca, set up that argument.
4746 if (ArgMemory.isValid()) {
4747 llvm::Value *Arg = ArgMemory.getPointer();
4748 if (CallInfo.isVariadic()) {
4749 // When passing non-POD arguments by value to variadic functions, we will
4750 // end up with a variadic prototype and an inalloca call site. In such
4751 // cases, we can't do any parameter mismatch checks. Give up and bitcast
4752 // the callee.
4753 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
4754 CalleePtr =
4755 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
4756 } else {
4757 llvm::Type *LastParamTy =
4758 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
4759 if (Arg->getType() != LastParamTy) {
4760#ifndef NDEBUG
4761 // Assert that these structs have equivalent element types.
4762 llvm::StructType *FullTy = CallInfo.getArgStruct();
4763 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
4764 cast<llvm::PointerType>(LastParamTy)->getElementType());
4765 assert(DeclaredTy->getNumElements() == FullTy->getNumElements())((DeclaredTy->getNumElements() == FullTy->getNumElements
()) ? static_cast<void> (0) : __assert_fail ("DeclaredTy->getNumElements() == FullTy->getNumElements()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4765, __PRETTY_FUNCTION__))
;
4766 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
4767 DE = DeclaredTy->element_end(),
4768 FI = FullTy->element_begin();
4769 DI != DE; ++DI, ++FI)
4770 assert(*DI == *FI)((*DI == *FI) ? static_cast<void> (0) : __assert_fail (
"*DI == *FI", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4770, __PRETTY_FUNCTION__))
;
4771#endif
4772 Arg = Builder.CreateBitCast(Arg, LastParamTy);
4773 }
4774 }
4775 assert(IRFunctionArgs.hasInallocaArg())((IRFunctionArgs.hasInallocaArg()) ? static_cast<void> (
0) : __assert_fail ("IRFunctionArgs.hasInallocaArg()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4775, __PRETTY_FUNCTION__))
;
4776 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
4777 }
4778
4779 // 2. Prepare the function pointer.
4780
4781 // If the callee is a bitcast of a non-variadic function to have a
4782 // variadic function pointer type, check to see if we can remove the
4783 // bitcast. This comes up with unprototyped functions.
4784 //
4785 // This makes the IR nicer, but more importantly it ensures that we
4786 // can inline the function at -O0 if it is marked always_inline.
4787 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
4788 llvm::Value *Ptr) -> llvm::Function * {
4789 if (!CalleeFT->isVarArg())
4790 return nullptr;
4791
4792 // Get underlying value if it's a bitcast
4793 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
4794 if (CE->getOpcode() == llvm::Instruction::BitCast)
4795 Ptr = CE->getOperand(0);
4796 }
4797
4798 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
4799 if (!OrigFn)
4800 return nullptr;
4801
4802 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
4803
4804 // If the original type is variadic, or if any of the component types
4805 // disagree, we cannot remove the cast.
4806 if (OrigFT->isVarArg() ||
4807 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4808 OrigFT->getReturnType() != CalleeFT->getReturnType())
4809 return nullptr;
4810
4811 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4812 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
4813 return nullptr;
4814
4815 return OrigFn;
4816 };
4817
4818 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
4819 CalleePtr = OrigFn;
4820 IRFuncTy = OrigFn->getFunctionType();
4821 }
4822
4823 // 3. Perform the actual call.
4824
4825 // Deactivate any cleanups that we're supposed to do immediately before
4826 // the call.
4827 if (!CallArgs.getCleanupsToDeactivate().empty())
4828 deactivateArgCleanupsBeforeCall(*this, CallArgs);
4829
4830 // Assert that the arguments we computed match up. The IR verifier
4831 // will catch this, but this is a common enough source of problems
4832 // during IRGen changes that it's way better for debugging to catch
4833 // it ourselves here.
4834#ifndef NDEBUG
4835 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg())((IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy
->isVarArg()) ? static_cast<void> (0) : __assert_fail
("IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4835, __PRETTY_FUNCTION__))
;
4836 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4837 // Inalloca argument can have different type.
4838 if (IRFunctionArgs.hasInallocaArg() &&
4839 i == IRFunctionArgs.getInallocaArgNo())
4840 continue;
4841 if (i < IRFuncTy->getNumParams())
4842 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i))((IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)
) ? static_cast<void> (0) : __assert_fail ("IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 4842, __PRETTY_FUNCTION__))
;
4843 }
4844#endif
4845
4846 // Update the largest vector width if any arguments have vector types.
4847 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4848 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
4849 LargestVectorWidth =
4850 std::max((uint64_t)LargestVectorWidth,
4851 VT->getPrimitiveSizeInBits().getKnownMinSize());
4852 }
4853
4854 // Compute the calling convention and attributes.
4855 unsigned CallingConv;
4856 llvm::AttributeList Attrs;
4857 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
4858 Callee.getAbstractInfo(), Attrs, CallingConv,
4859 /*AttrOnCallSite=*/true);
4860
4861 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
4862 if (FD->hasAttr<StrictFPAttr>())
4863 // All calls within a strictfp function are marked strictfp
4864 Attrs =
4865 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4866 llvm::Attribute::StrictFP);
4867
4868 // Add call-site nomerge attribute if exists.
4869 if (InNoMergeAttributedStmt)
4870 Attrs =
4871 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4872 llvm::Attribute::NoMerge);
4873
4874 // Apply some call-site-specific attributes.
4875 // TODO: work this into building the attribute set.
4876
4877 // Apply always_inline to all calls within flatten functions.
4878 // FIXME: should this really take priority over __try, below?
4879 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4880 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
4881 Attrs =
4882 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4883 llvm::Attribute::AlwaysInline);
4884 }
4885
4886 // Disable inlining inside SEH __try blocks.
4887 if (isSEHTryScope()) {
4888 Attrs =
4889 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4890 llvm::Attribute::NoInline);
4891 }
4892
4893 // Decide whether to use a call or an invoke.
4894 bool CannotThrow;
4895 if (currentFunctionUsesSEHTry()) {
4896 // SEH cares about asynchronous exceptions, so everything can "throw."
4897 CannotThrow = false;
4898 } else if (isCleanupPadScope() &&
4899 EHPersonality::get(*this).isMSVCXXPersonality()) {
4900 // The MSVC++ personality will implicitly terminate the program if an
4901 // exception is thrown during a cleanup outside of a try/catch.
4902 // We don't need to model anything in IR to get this behavior.
4903 CannotThrow = true;
4904 } else {
4905 // Otherwise, nounwind call sites will never throw.
4906 CannotThrow = Attrs.hasFnAttribute(llvm::Attribute::NoUnwind);
4907
4908 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
4909 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
4910 CannotThrow = true;
4911 }
4912
4913 // If we made a temporary, be sure to clean up after ourselves. Note that we
4914 // can't depend on being inside of an ExprWithCleanups, so we need to manually
4915 // pop this cleanup later on. Being eager about this is OK, since this
4916 // temporary is 'invisible' outside of the callee.
4917 if (UnusedReturnSizePtr)
4918 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
4919 UnusedReturnSizePtr);
4920
4921 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
4922
4923 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4924 getBundlesForFunclet(CalleePtr);
4925
4926 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
4927 if (FD->hasAttr<StrictFPAttr>())
4928 // All calls within a strictfp function are marked strictfp
4929 Attrs =
4930 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
4931 llvm::Attribute::StrictFP);
4932
4933 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
4934 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
4935
4936 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
4937 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
4938
4939 // Emit the actual call/invoke instruction.
4940 llvm::CallBase *CI;
4941 if (!InvokeDest) {
4942 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
4943 } else {
4944 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
4945 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
4946 BundleList);
4947 EmitBlock(Cont);
4948 }
4949 if (callOrInvoke)
4950 *callOrInvoke = CI;
4951
4952 // If this is within a function that has the guard(nocf) attribute and is an
4953 // indirect call, add the "guard_nocf" attribute to this call to indicate that
4954 // Control Flow Guard checks should not be added, even if the call is inlined.
4955 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
4956 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
4957 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
4958 Attrs = Attrs.addAttribute(
4959 getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf");
4960 }
4961 }
4962
4963 // Apply the attributes and calling convention.
4964 CI->setAttributes(Attrs);
4965 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
4966
4967 // Apply various metadata.
4968
4969 if (!CI->getType()->isVoidTy())
4970 CI->setName("call");
4971
4972 // Update largest vector width from the return type.
4973 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
4974 LargestVectorWidth =
4975 std::max((uint64_t)LargestVectorWidth,
4976 VT->getPrimitiveSizeInBits().getKnownMinSize());
4977
4978 // Insert instrumentation or attach profile metadata at indirect call sites.
4979 // For more details, see the comment before the definition of
4980 // IPVK_IndirectCallTarget in InstrProfData.inc.
4981 if (!CI->getCalledFunction())
4982 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
4983 CI, CalleePtr);
4984
4985 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4986 // optimizer it can aggressively ignore unwind edges.
4987 if (CGM.getLangOpts().ObjCAutoRefCount)
4988 AddObjCARCExceptionMetadata(CI);
4989
4990 // Suppress tail calls if requested.
4991 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4992 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4993 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4994 }
4995
4996 // Add metadata for calls to MSAllocator functions
4997 if (getDebugInfo() && TargetDecl &&
4998 TargetDecl->hasAttr<MSAllocatorAttr>())
4999 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
5000
5001 // 4. Finish the call.
5002
5003 // If the call doesn't return, finish the basic block and clear the
5004 // insertion point; this allows the rest of IRGen to discard
5005 // unreachable code.
5006 if (CI->doesNotReturn()) {
5007 if (UnusedReturnSizePtr)
5008 PopCleanupBlock();
5009
5010 // Strip away the noreturn attribute to better diagnose unreachable UB.
5011 if (SanOpts.has(SanitizerKind::Unreachable)) {
5012 // Also remove from function since CallBase::hasFnAttr additionally checks
5013 // attributes of the called function.
5014 if (auto *F = CI->getCalledFunction())
5015 F->removeFnAttr(llvm::Attribute::NoReturn);
5016 CI->removeAttribute(llvm::AttributeList::FunctionIndex,
5017 llvm::Attribute::NoReturn);
5018
5019 // Avoid incompatibility with ASan which relies on the `noreturn`
5020 // attribute to insert handler calls.
5021 if (SanOpts.hasOneOf(SanitizerKind::Address |
5022 SanitizerKind::KernelAddress)) {
5023 SanitizerScope SanScope(this);
5024 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5025 Builder.SetInsertPoint(CI);
5026 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5027 llvm::FunctionCallee Fn =
5028 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5029 EmitNounwindRuntimeCall(Fn);
5030 }
5031 }
5032
5033 EmitUnreachable(Loc);
5034 Builder.ClearInsertionPoint();
5035
5036 // FIXME: For now, emit a dummy basic block because expr emitters in
5037 // generally are not ready to handle emitting expressions at unreachable
5038 // points.
5039 EnsureInsertPoint();
5040
5041 // Return a reasonable RValue.
5042 return GetUndefRValue(RetTy);
5043 }
5044
5045 // Perform the swifterror writeback.
5046 if (swiftErrorTemp.isValid()) {
5047 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5048 Builder.CreateStore(errorResult, swiftErrorArg);
5049 }
5050
5051 // Emit any call-associated writebacks immediately. Arguably this
5052 // should happen after any return-value munging.
5053 if (CallArgs.hasWritebacks())
5054 emitWritebacks(*this, CallArgs);
5055
5056 // The stack cleanup for inalloca arguments has to run out of the normal
5057 // lexical order, so deactivate it and run it manually here.
5058 CallArgs.freeArgumentMemory(*this);
5059
5060 // Extract the return value.
5061 RValue Ret = [&] {
5062 switch (RetAI.getKind()) {
5063 case ABIArgInfo::CoerceAndExpand: {
5064 auto coercionType = RetAI.getCoerceAndExpandType();
5065
5066 Address addr = SRetPtr;
5067 addr = Builder.CreateElementBitCast(addr, coercionType);
5068
5069 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType())((CI->getType() == RetAI.getUnpaddedCoerceAndExpandType())
? static_cast<void> (0) : __assert_fail ("CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 5069, __PRETTY_FUNCTION__))
;
5070 bool requiresExtract = isa<llvm::StructType>(CI->getType());
5071
5072 unsigned unpaddedIndex = 0;
5073 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5074 llvm::Type *eltType = coercionType->getElementType(i);
5075 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5076 Address eltAddr = Builder.CreateStructGEP(addr, i);
5077 llvm::Value *elt = CI;
5078 if (requiresExtract)
5079 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5080 else
5081 assert(unpaddedIndex == 0)((unpaddedIndex == 0) ? static_cast<void> (0) : __assert_fail
("unpaddedIndex == 0", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 5081, __PRETTY_FUNCTION__))
;
5082 Builder.CreateStore(elt, eltAddr);
5083 }
5084 // FALLTHROUGH
5085 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5086 }
5087
5088 case ABIArgInfo::InAlloca:
5089 case ABIArgInfo::Indirect: {
5090 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5091 if (UnusedReturnSizePtr)
5092 PopCleanupBlock();
5093 return ret;
5094 }
5095
5096 case ABIArgInfo::Ignore:
5097 // If we are ignoring an argument that had a result, make sure to
5098 // construct the appropriate return value for our caller.
5099 return GetUndefRValue(RetTy);
5100
5101 case ABIArgInfo::Extend:
5102 case ABIArgInfo::Direct: {
5103 llvm::Type *RetIRTy = ConvertType(RetTy);
5104 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5105 switch (getEvaluationKind(RetTy)) {
5106 case TEK_Complex: {
5107 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5108 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5109 return RValue::getComplex(std::make_pair(Real, Imag));
5110 }
5111 case TEK_Aggregate: {
5112 Address DestPtr = ReturnValue.getValue();
5113 bool DestIsVolatile = ReturnValue.isVolatile();
5114
5115 if (!DestPtr.isValid()) {
5116 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5117 DestIsVolatile = false;
5118 }
5119 EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5120 return RValue::getAggregate(DestPtr);
5121 }
5122 case TEK_Scalar: {
5123 // If the argument doesn't match, perform a bitcast to coerce it. This
5124 // can happen due to trivial type mismatches.
5125 llvm::Value *V = CI;
5126 if (V->getType() != RetIRTy)
5127 V = Builder.CreateBitCast(V, RetIRTy);
5128 return RValue::get(V);
5129 }
5130 }
5131 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 5131)
;
5132 }
5133
5134 Address DestPtr = ReturnValue.getValue();
5135 bool DestIsVolatile = ReturnValue.isVolatile();
5136
5137 if (!DestPtr.isValid()) {
5138 DestPtr = CreateMemTemp(RetTy, "coerce");
5139 DestIsVolatile = false;
5140 }
5141
5142 // If the value is offset in memory, apply the offset now.
5143 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5144 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
5145
5146 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5147 }
5148
5149 case ABIArgInfo::Expand:
5150 case ABIArgInfo::IndirectAliased:
5151 llvm_unreachable("Invalid ABI kind for return argument")::llvm::llvm_unreachable_internal("Invalid ABI kind for return argument"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 5151)
;
5152 }
5153
5154 llvm_unreachable("Unhandled ABIArgInfo::Kind")::llvm::llvm_unreachable_internal("Unhandled ABIArgInfo::Kind"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/CGCall.cpp"
, 5154)
;
5155 } ();
5156
5157 // Emit the assume_aligned check on the return value.
5158 if (Ret.isScalar() && TargetDecl) {
5159 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5160 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5161 }
5162
5163 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5164 // we can't use the full cleanup mechanism.
5165 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
5166 LifetimeEnd.Emit(*this, /*Flags=*/{});
5167
5168 if (!ReturnValue.isExternallyDestructed() &&
5169 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5170 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5171 RetTy);
5172
5173 return Ret;
5174}
5175
5176CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
5177 if (isVirtual()) {
5178 const CallExpr *CE = getVirtualCallExpr();
5179 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
5180 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
5181 CE ? CE->getBeginLoc() : SourceLocation());
5182 }
5183
5184 return *this;
5185}
5186
5187/* VarArg handling */
5188
5189Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
5190 VAListAddr = VE->isMicrosoftABI()
5191 ? EmitMSVAListRef(VE->getSubExpr())
5192 : EmitVAListRef(VE->getSubExpr());
5193 QualType Ty = VE->getType();
5194 if (VE->isMicrosoftABI())
5195 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
5196 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
5197}