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