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