Debian Codegraph @

clang/lib/CodeGen/CGCall.cpp

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