clang 21.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, {}, FTNP->getExtInfo(), {},
122 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 {}, 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
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())
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())
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 *PoisonVec = llvm::PoisonValue::get(ScalableDstTy);
1318 auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1319 llvm::Value *Result = CGF.Builder.CreateInsertVector(
1320 ScalableDstTy, PoisonVec, 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
1413static std::pair<llvm::Value *, bool>
1414CoerceScalableToFixed(CodeGenFunction &CGF, llvm::FixedVectorType *ToTy,
1415 llvm::ScalableVectorType *FromTy, llvm::Value *V,
1416 StringRef Name = "") {
1417 // If we are casting a scalable i1 predicate vector to a fixed i8
1418 // vector, first bitcast the source.
1419 if (FromTy->getElementType()->isIntegerTy(1) &&
1420 FromTy->getElementCount().isKnownMultipleOf(8) &&
1421 ToTy->getElementType() == CGF.Builder.getInt8Ty()) {
1422 FromTy = llvm::ScalableVectorType::get(
1423 ToTy->getElementType(),
1424 FromTy->getElementCount().getKnownMinValue() / 8);
1425 V = CGF.Builder.CreateBitCast(V, FromTy);
1426 }
1427 if (FromTy->getElementType() == ToTy->getElementType()) {
1428 llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1429
1430 V->setName(Name + ".coerce");
1431 V = CGF.Builder.CreateExtractVector(ToTy, V, Zero, "cast.fixed");
1432 return {V, true};
1433 }
1434 return {V, false};
1435}
1436
1437namespace {
1438
1439/// Encapsulates information about the way function arguments from
1440/// CGFunctionInfo should be passed to actual LLVM IR function.
1441class ClangToLLVMArgMapping {
1442 static const unsigned InvalidIndex = ~0U;
1443 unsigned InallocaArgNo;
1444 unsigned SRetArgNo;
1445 unsigned TotalIRArgs;
1446
1447 /// Arguments of LLVM IR function corresponding to single Clang argument.
1448 struct IRArgs {
1449 unsigned PaddingArgIndex;
1450 // Argument is expanded to IR arguments at positions
1451 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1452 unsigned FirstArgIndex;
1453 unsigned NumberOfArgs;
1454
1455 IRArgs()
1456 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1457 NumberOfArgs(0) {}
1458 };
1459
1460 SmallVector<IRArgs, 8> ArgInfo;
1461
1462public:
1463 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1464 bool OnlyRequiredArgs = false)
1465 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1466 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1467 construct(Context, FI, OnlyRequiredArgs);
1468 }
1469
1470 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1471 unsigned getInallocaArgNo() const {
1472 assert(hasInallocaArg());
1473 return InallocaArgNo;
1474 }
1475
1476 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1477 unsigned getSRetArgNo() const {
1478 assert(hasSRetArg());
1479 return SRetArgNo;
1480 }
1481
1482 unsigned totalIRArgs() const { return TotalIRArgs; }
1483
1484 bool hasPaddingArg(unsigned ArgNo) const {
1485 assert(ArgNo < ArgInfo.size());
1486 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1487 }
1488 unsigned getPaddingArgNo(unsigned ArgNo) const {
1489 assert(hasPaddingArg(ArgNo));
1490 return ArgInfo[ArgNo].PaddingArgIndex;
1491 }
1492
1493 /// Returns index of first IR argument corresponding to ArgNo, and their
1494 /// quantity.
1495 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1496 assert(ArgNo < ArgInfo.size());
1497 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1498 ArgInfo[ArgNo].NumberOfArgs);
1499 }
1500
1501private:
1502 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1503 bool OnlyRequiredArgs);
1504};
1505
1506void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1507 const CGFunctionInfo &FI,
1508 bool OnlyRequiredArgs) {
1509 unsigned IRArgNo = 0;
1510 bool SwapThisWithSRet = false;
1511 const ABIArgInfo &RetAI = FI.getReturnInfo();
1512
1513 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1514 SwapThisWithSRet = RetAI.isSRetAfterThis();
1515 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1516 }
1517
1518 unsigned ArgNo = 0;
1519 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1520 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1521 ++I, ++ArgNo) {
1522 assert(I != FI.arg_end());
1523 QualType ArgType = I->type;
1524 const ABIArgInfo &AI = I->info;
1525 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1526 auto &IRArgs = ArgInfo[ArgNo];
1527
1528 if (AI.getPaddingType())
1529 IRArgs.PaddingArgIndex = IRArgNo++;
1530
1531 switch (AI.getKind()) {
1532 case ABIArgInfo::Extend:
1533 case ABIArgInfo::Direct: {
1534 // FIXME: handle sseregparm someday...
1535 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1536 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1537 IRArgs.NumberOfArgs = STy->getNumElements();
1538 } else {
1539 IRArgs.NumberOfArgs = 1;
1540 }
1541 break;
1542 }
1545 IRArgs.NumberOfArgs = 1;
1546 break;
1547 case ABIArgInfo::Ignore:
1549 // ignore and inalloca doesn't have matching LLVM parameters.
1550 IRArgs.NumberOfArgs = 0;
1551 break;
1553 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1554 break;
1555 case ABIArgInfo::Expand:
1556 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1557 break;
1558 }
1559
1560 if (IRArgs.NumberOfArgs > 0) {
1561 IRArgs.FirstArgIndex = IRArgNo;
1562 IRArgNo += IRArgs.NumberOfArgs;
1563 }
1564
1565 // Skip over the sret parameter when it comes second. We already handled it
1566 // above.
1567 if (IRArgNo == 1 && SwapThisWithSRet)
1568 IRArgNo++;
1569 }
1570 assert(ArgNo == ArgInfo.size());
1571
1572 if (FI.usesInAlloca())
1573 InallocaArgNo = IRArgNo++;
1574
1575 TotalIRArgs = IRArgNo;
1576}
1577} // namespace
1578
1579/***/
1580
1582 const auto &RI = FI.getReturnInfo();
1583 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1584}
1585
1587 const auto &RI = FI.getReturnInfo();
1588 return RI.getInReg();
1589}
1590
1592 return ReturnTypeUsesSRet(FI) &&
1594}
1595
1597 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1598 switch (BT->getKind()) {
1599 default:
1600 return false;
1601 case BuiltinType::Float:
1603 case BuiltinType::Double:
1605 case BuiltinType::LongDouble:
1607 }
1608 }
1609
1610 return false;
1611}
1612
1614 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1615 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1616 if (BT->getKind() == BuiltinType::LongDouble)
1618 }
1619 }
1620
1621 return false;
1622}
1623
1626 return GetFunctionType(FI);
1627}
1628
1629llvm::FunctionType *
1631
1632 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1633 (void)Inserted;
1634 assert(Inserted && "Recursively being processed?");
1635
1636 llvm::Type *resultType = nullptr;
1637 const ABIArgInfo &retAI = FI.getReturnInfo();
1638 switch (retAI.getKind()) {
1639 case ABIArgInfo::Expand:
1641 llvm_unreachable("Invalid ABI kind for return argument");
1642
1643 case ABIArgInfo::Extend:
1644 case ABIArgInfo::Direct:
1645 resultType = retAI.getCoerceToType();
1646 break;
1647
1649 if (retAI.getInAllocaSRet()) {
1650 // sret things on win32 aren't void, they return the sret pointer.
1651 QualType ret = FI.getReturnType();
1652 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
1653 resultType = llvm::PointerType::get(getLLVMContext(), addressSpace);
1654 } else {
1655 resultType = llvm::Type::getVoidTy(getLLVMContext());
1656 }
1657 break;
1658
1660 case ABIArgInfo::Ignore:
1661 resultType = llvm::Type::getVoidTy(getLLVMContext());
1662 break;
1663
1665 resultType = retAI.getUnpaddedCoerceAndExpandType();
1666 break;
1667 }
1668
1669 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1670 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1671
1672 // Add type for sret argument.
1673 if (IRFunctionArgs.hasSRetArg()) {
1674 QualType Ret = FI.getReturnType();
1675 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
1676 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1677 llvm::PointerType::get(getLLVMContext(), AddressSpace);
1678 }
1679
1680 // Add type for inalloca argument.
1681 if (IRFunctionArgs.hasInallocaArg())
1682 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
1683 llvm::PointerType::getUnqual(getLLVMContext());
1684
1685 // Add in all of the required arguments.
1686 unsigned ArgNo = 0;
1688 ie = it + FI.getNumRequiredArgs();
1689 for (; it != ie; ++it, ++ArgNo) {
1690 const ABIArgInfo &ArgInfo = it->info;
1691
1692 // Insert a padding type to ensure proper alignment.
1693 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1694 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1695 ArgInfo.getPaddingType();
1696
1697 unsigned FirstIRArg, NumIRArgs;
1698 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1699
1700 switch (ArgInfo.getKind()) {
1701 case ABIArgInfo::Ignore:
1703 assert(NumIRArgs == 0);
1704 break;
1705
1707 assert(NumIRArgs == 1);
1708 // indirect arguments are always on the stack, which is alloca addr space.
1709 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1710 getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
1711 break;
1713 assert(NumIRArgs == 1);
1714 ArgTypes[FirstIRArg] = llvm::PointerType::get(
1716 break;
1717 case ABIArgInfo::Extend:
1718 case ABIArgInfo::Direct: {
1719 // Fast-isel and the optimizer generally like scalar values better than
1720 // FCAs, so we flatten them if this is safe to do for this argument.
1721 llvm::Type *argType = ArgInfo.getCoerceToType();
1722 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1723 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1724 assert(NumIRArgs == st->getNumElements());
1725 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1726 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1727 } else {
1728 assert(NumIRArgs == 1);
1729 ArgTypes[FirstIRArg] = argType;
1730 }
1731 break;
1732 }
1733
1735 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1736 for (auto *EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1737 *ArgTypesIter++ = EltTy;
1738 }
1739 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1740 break;
1741 }
1742
1743 case ABIArgInfo::Expand:
1744 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1745 getExpandedTypes(it->type, ArgTypesIter);
1746 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1747 break;
1748 }
1749 }
1750
1751 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1752 assert(Erased && "Not in set?");
1753
1754 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1755}
1756
1758 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1759 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1760
1761 if (!isFuncTypeConvertible(FPT))
1762 return llvm::StructType::get(getLLVMContext());
1763
1764 return GetFunctionType(GD);
1765}
1766
1768 llvm::AttrBuilder &FuncAttrs,
1769 const FunctionProtoType *FPT) {
1770 if (!FPT)
1771 return;
1772
1774 FPT->isNothrow())
1775 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1776
1777 unsigned SMEBits = FPT->getAArch64SMEAttributes();
1779 FuncAttrs.addAttribute("aarch64_pstate_sm_enabled");
1781 FuncAttrs.addAttribute("aarch64_pstate_sm_compatible");
1783 FuncAttrs.addAttribute("aarch64_za_state_agnostic");
1784
1785 // ZA
1787 FuncAttrs.addAttribute("aarch64_preserves_za");
1789 FuncAttrs.addAttribute("aarch64_in_za");
1791 FuncAttrs.addAttribute("aarch64_out_za");
1793 FuncAttrs.addAttribute("aarch64_inout_za");
1794
1795 // ZT0
1797 FuncAttrs.addAttribute("aarch64_preserves_zt0");
1799 FuncAttrs.addAttribute("aarch64_in_zt0");
1801 FuncAttrs.addAttribute("aarch64_out_zt0");
1803 FuncAttrs.addAttribute("aarch64_inout_zt0");
1804}
1805
1806static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
1807 const Decl *Callee) {
1808 if (!Callee)
1809 return;
1810
1812
1813 for (const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
1814 AA->getAssumption().split(Attrs, ",");
1815
1816 if (!Attrs.empty())
1817 FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
1818 llvm::join(Attrs.begin(), Attrs.end(), ","));
1819}
1820
1822 QualType ReturnType) const {
1823 // We can't just discard the return value for a record type with a
1824 // complex destructor or a non-trivially copyable type.
1825 if (const RecordType *RT =
1826 ReturnType.getCanonicalType()->getAs<RecordType>()) {
1827 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1828 return ClassDecl->hasTrivialDestructor();
1829 }
1830 return ReturnType.isTriviallyCopyableType(Context);
1831}
1832
1834 const Decl *TargetDecl) {
1835 // As-is msan can not tolerate noundef mismatch between caller and
1836 // implementation. Mismatch is possible for e.g. indirect calls from C-caller
1837 // into C++. Such mismatches lead to confusing false reports. To avoid
1838 // expensive workaround on msan we enforce initialization event in uncommon
1839 // cases where it's allowed.
1840 if (Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
1841 return true;
1842 // C++ explicitly makes returning undefined values UB. C's rule only applies
1843 // to used values, so we never mark them noundef for now.
1844 if (!Module.getLangOpts().CPlusPlus)
1845 return false;
1846 if (TargetDecl) {
1847 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
1848 if (FDecl->isExternC())
1849 return false;
1850 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
1851 // Function pointer.
1852 if (VDecl->isExternC())
1853 return false;
1854 }
1855 }
1856
1857 // We don't want to be too aggressive with the return checking, unless
1858 // it's explicit in the code opts or we're using an appropriate sanitizer.
1859 // Try to respect what the programmer intended.
1860 return Module.getCodeGenOpts().StrictReturn ||
1861 !Module.MayDropFunctionReturn(Module.getContext(), RetTy) ||
1862 Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
1863}
1864
1865/// Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the
1866/// requested denormal behavior, accounting for the overriding behavior of the
1867/// -f32 case.
1868static void addDenormalModeAttrs(llvm::DenormalMode FPDenormalMode,
1869 llvm::DenormalMode FP32DenormalMode,
1870 llvm::AttrBuilder &FuncAttrs) {
1871 if (FPDenormalMode != llvm::DenormalMode::getDefault())
1872 FuncAttrs.addAttribute("denormal-fp-math", FPDenormalMode.str());
1873
1874 if (FP32DenormalMode != FPDenormalMode && FP32DenormalMode.isValid())
1875 FuncAttrs.addAttribute("denormal-fp-math-f32", FP32DenormalMode.str());
1876}
1877
1878/// Add default attributes to a function, which have merge semantics under
1879/// -mlink-builtin-bitcode and should not simply overwrite any existing
1880/// attributes in the linked library.
1881static void
1883 llvm::AttrBuilder &FuncAttrs) {
1884 addDenormalModeAttrs(CodeGenOpts.FPDenormalMode, CodeGenOpts.FP32DenormalMode,
1885 FuncAttrs);
1886}
1887
1889 StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts,
1890 const LangOptions &LangOpts, bool AttrOnCallSite,
1891 llvm::AttrBuilder &FuncAttrs) {
1892 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1893 if (!HasOptnone) {
1894 if (CodeGenOpts.OptimizeSize)
1895 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1896 if (CodeGenOpts.OptimizeSize == 2)
1897 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1898 }
1899
1900 if (CodeGenOpts.DisableRedZone)
1901 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1902 if (CodeGenOpts.IndirectTlsSegRefs)
1903 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1904 if (CodeGenOpts.NoImplicitFloat)
1905 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1906
1907 if (AttrOnCallSite) {
1908 // Attributes that should go on the call site only.
1909 // FIXME: Look for 'BuiltinAttr' on the function rather than re-checking
1910 // the -fno-builtin-foo list.
1911 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1912 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1913 if (!CodeGenOpts.TrapFuncName.empty())
1914 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1915 } else {
1916 switch (CodeGenOpts.getFramePointer()) {
1918 // This is the default behavior.
1919 break;
1923 FuncAttrs.addAttribute("frame-pointer",
1925 CodeGenOpts.getFramePointer()));
1926 }
1927
1928 if (CodeGenOpts.LessPreciseFPMAD)
1929 FuncAttrs.addAttribute("less-precise-fpmad", "true");
1930
1931 if (CodeGenOpts.NullPointerIsValid)
1932 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1933
1935 FuncAttrs.addAttribute("no-trapping-math", "true");
1936
1937 // TODO: Are these all needed?
1938 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1939 if (LangOpts.NoHonorInfs)
1940 FuncAttrs.addAttribute("no-infs-fp-math", "true");
1941 if (LangOpts.NoHonorNaNs)
1942 FuncAttrs.addAttribute("no-nans-fp-math", "true");
1943 if (LangOpts.ApproxFunc)
1944 FuncAttrs.addAttribute("approx-func-fp-math", "true");
1945 if (LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
1946 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
1947 (LangOpts.getDefaultFPContractMode() ==
1949 LangOpts.getDefaultFPContractMode() ==
1951 FuncAttrs.addAttribute("unsafe-fp-math", "true");
1952 if (CodeGenOpts.SoftFloat)
1953 FuncAttrs.addAttribute("use-soft-float", "true");
1954 FuncAttrs.addAttribute("stack-protector-buffer-size",
1955 llvm::utostr(CodeGenOpts.SSPBufferSize));
1956 if (LangOpts.NoSignedZero)
1957 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1958
1959 // TODO: Reciprocal estimate codegen options should apply to instructions?
1960 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1961 if (!Recips.empty())
1962 FuncAttrs.addAttribute("reciprocal-estimates",
1963 llvm::join(Recips, ","));
1964
1965 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1966 CodeGenOpts.PreferVectorWidth != "none")
1967 FuncAttrs.addAttribute("prefer-vector-width",
1968 CodeGenOpts.PreferVectorWidth);
1969
1970 if (CodeGenOpts.StackRealignment)
1971 FuncAttrs.addAttribute("stackrealign");
1972 if (CodeGenOpts.Backchain)
1973 FuncAttrs.addAttribute("backchain");
1974 if (CodeGenOpts.EnableSegmentedStacks)
1975 FuncAttrs.addAttribute("split-stack");
1976
1977 if (CodeGenOpts.SpeculativeLoadHardening)
1978 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1979
1980 // Add zero-call-used-regs attribute.
1981 switch (CodeGenOpts.getZeroCallUsedRegs()) {
1982 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
1983 FuncAttrs.removeAttribute("zero-call-used-regs");
1984 break;
1985 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
1986 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
1987 break;
1988 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
1989 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
1990 break;
1991 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
1992 FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
1993 break;
1994 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
1995 FuncAttrs.addAttribute("zero-call-used-regs", "used");
1996 break;
1997 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
1998 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
1999 break;
2000 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2001 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
2002 break;
2003 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2004 FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
2005 break;
2006 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2007 FuncAttrs.addAttribute("zero-call-used-regs", "all");
2008 break;
2009 }
2010 }
2011
2012 if (LangOpts.assumeFunctionsAreConvergent()) {
2013 // Conservatively, mark all functions and calls in CUDA and OpenCL as
2014 // convergent (meaning, they may call an intrinsically convergent op, such
2015 // as __syncthreads() / barrier(), and so can't have certain optimizations
2016 // applied around them). LLVM will remove this attribute where it safely
2017 // can.
2018 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2019 }
2020
2021 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2022 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2023 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2024 LangOpts.SYCLIsDevice) {
2025 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2026 }
2027
2028 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2029 FuncAttrs.addAttribute("save-reg-params");
2030
2031 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2032 StringRef Var, Value;
2033 std::tie(Var, Value) = Attr.split('=');
2034 FuncAttrs.addAttribute(Var, Value);
2035 }
2036
2039}
2040
2041/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2042/// \FuncAttr
2043/// * features from \F are always kept
2044/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2045/// from \F
2046static void
2048 const llvm::Function &F,
2049 const TargetOptions &TargetOpts) {
2050 auto FFeatures = F.getFnAttribute("target-features");
2051
2052 llvm::StringSet<> MergedNames;
2053 SmallVector<StringRef> MergedFeatures;
2054 MergedFeatures.reserve(TargetOpts.Features.size());
2055
2056 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2057 for (StringRef Feature : FeatureRange) {
2058 if (Feature.empty())
2059 continue;
2060 assert(Feature[0] == '+' || Feature[0] == '-');
2061 StringRef Name = Feature.drop_front(1);
2062 bool Merged = !MergedNames.insert(Name).second;
2063 if (!Merged)
2064 MergedFeatures.push_back(Feature);
2065 }
2066 };
2067
2068 if (FFeatures.isValid())
2069 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2070 AddUnmergedFeatures(TargetOpts.Features);
2071
2072 if (!MergedFeatures.empty()) {
2073 llvm::sort(MergedFeatures);
2074 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2075 }
2076}
2077
2079 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2080 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2081 bool WillInternalize) {
2082
2083 llvm::AttrBuilder FuncAttrs(F.getContext());
2084 // Here we only extract the options that are relevant compared to the version
2085 // from GetCPUAndFeaturesAttributes.
2086 if (!TargetOpts.CPU.empty())
2087 FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2088 if (!TargetOpts.TuneCPU.empty())
2089 FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2090
2091 ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2092 CodeGenOpts, LangOpts,
2093 /*AttrOnCallSite=*/false, FuncAttrs);
2094
2095 if (!WillInternalize && F.isInterposable()) {
2096 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2097 // setting for weak functions that won't be internalized. The user has no
2098 // real control for how builtin bitcode is linked, so we shouldn't assume
2099 // later copies will use a consistent mode.
2100 F.addFnAttrs(FuncAttrs);
2101 return;
2102 }
2103
2104 llvm::AttributeMask AttrsToRemove;
2105
2106 llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2107 llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2108 llvm::DenormalMode Merged =
2109 CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2110 llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2111
2112 if (DenormModeToMergeF32.isValid()) {
2113 MergedF32 =
2114 CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2115 }
2116
2117 if (Merged == llvm::DenormalMode::getDefault()) {
2118 AttrsToRemove.addAttribute("denormal-fp-math");
2119 } else if (Merged != DenormModeToMerge) {
2120 // Overwrite existing attribute
2121 FuncAttrs.addAttribute("denormal-fp-math",
2122 CodeGenOpts.FPDenormalMode.str());
2123 }
2124
2125 if (MergedF32 == llvm::DenormalMode::getDefault()) {
2126 AttrsToRemove.addAttribute("denormal-fp-math-f32");
2127 } else if (MergedF32 != DenormModeToMergeF32) {
2128 // Overwrite existing attribute
2129 FuncAttrs.addAttribute("denormal-fp-math-f32",
2130 CodeGenOpts.FP32DenormalMode.str());
2131 }
2132
2133 F.removeFnAttrs(AttrsToRemove);
2134 addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2135
2136 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2137
2138 F.addFnAttrs(FuncAttrs);
2139}
2140
2141void CodeGenModule::getTrivialDefaultFunctionAttributes(
2142 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2143 llvm::AttrBuilder &FuncAttrs) {
2144 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2145 getLangOpts(), AttrOnCallSite,
2146 FuncAttrs);
2147}
2148
2149void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2150 bool HasOptnone,
2151 bool AttrOnCallSite,
2152 llvm::AttrBuilder &FuncAttrs) {
2153 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2154 FuncAttrs);
2155 // If we're just getting the default, get the default values for mergeable
2156 // attributes.
2157 if (!AttrOnCallSite)
2158 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2159}
2160
2162 llvm::AttrBuilder &attrs) {
2163 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2164 /*for call*/ false, attrs);
2165 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2166}
2167
2168static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2169 const LangOptions &LangOpts,
2170 const NoBuiltinAttr *NBA = nullptr) {
2171 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2172 SmallString<32> AttributeName;
2173 AttributeName += "no-builtin-";
2174 AttributeName += BuiltinName;
2175 FuncAttrs.addAttribute(AttributeName);
2176 };
2177
2178 // First, handle the language options passed through -fno-builtin.
2179 if (LangOpts.NoBuiltin) {
2180 // -fno-builtin disables them all.
2181 FuncAttrs.addAttribute("no-builtins");
2182 return;
2183 }
2184
2185 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2186 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2187
2188 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2189 // the source.
2190 if (!NBA)
2191 return;
2192
2193 // If there is a wildcard in the builtin names specified through the
2194 // attribute, disable them all.
2195 if (llvm::is_contained(NBA->builtinNames(), "*")) {
2196 FuncAttrs.addAttribute("no-builtins");
2197 return;
2198 }
2199
2200 // And last, add the rest of the builtin names.
2201 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2202}
2203
2205 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2206 bool CheckCoerce = true) {
2207 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2208 if (AI.getKind() == ABIArgInfo::Indirect ||
2210 return true;
2211 if (AI.getKind() == ABIArgInfo::Extend && !AI.isNoExt())
2212 return true;
2213 if (!DL.typeSizeEqualsStoreSize(Ty))
2214 // TODO: This will result in a modest amount of values not marked noundef
2215 // when they could be. We care about values that *invisibly* contain undef
2216 // bits from the perspective of LLVM IR.
2217 return false;
2218 if (CheckCoerce && AI.canHaveCoerceToType()) {
2219 llvm::Type *CoerceTy = AI.getCoerceToType();
2220 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2221 DL.getTypeSizeInBits(Ty)))
2222 // If we're coercing to a type with a greater size than the canonical one,
2223 // we're introducing new undef bits.
2224 // Coercing to a type of smaller or equal size is ok, as we know that
2225 // there's no internal padding (typeSizeEqualsStoreSize).
2226 return false;
2227 }
2228 if (QTy->isBitIntType())
2229 return true;
2230 if (QTy->isReferenceType())
2231 return true;
2232 if (QTy->isNullPtrType())
2233 return false;
2234 if (QTy->isMemberPointerType())
2235 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2236 // now, never mark them.
2237 return false;
2238 if (QTy->isScalarType()) {
2239 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2240 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2241 return true;
2242 }
2243 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2244 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2245 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2246 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2247 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2248 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2249
2250 // TODO: Some structs may be `noundef`, in specific situations.
2251 return false;
2252}
2253
2254/// Check if the argument of a function has maybe_undef attribute.
2255static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2256 unsigned NumRequiredArgs, unsigned ArgNo) {
2257 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2258 if (!FD)
2259 return false;
2260
2261 // Assume variadic arguments do not have maybe_undef attribute.
2262 if (ArgNo >= NumRequiredArgs)
2263 return false;
2264
2265 // Check if argument has maybe_undef attribute.
2266 if (ArgNo < FD->getNumParams()) {
2267 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2268 if (Param && Param->hasAttr<MaybeUndefAttr>())
2269 return true;
2270 }
2271
2272 return false;
2273}
2274
2275/// Test if it's legal to apply nofpclass for the given parameter type and it's
2276/// lowered IR type.
2277static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2278 bool IsReturn) {
2279 // Should only apply to FP types in the source, not ABI promoted.
2280 if (!ParamType->hasFloatingRepresentation())
2281 return false;
2282
2283 // The promoted-to IR type also needs to support nofpclass.
2284 llvm::Type *IRTy = AI.getCoerceToType();
2285 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2286 return true;
2287
2288 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2289 return !IsReturn && AI.getCanBeFlattened() &&
2290 llvm::all_of(ST->elements(), [](llvm::Type *Ty) {
2291 return llvm::AttributeFuncs::isNoFPClassCompatibleType(Ty);
2292 });
2293 }
2294
2295 return false;
2296}
2297
2298/// Return the nofpclass mask that can be applied to floating-point parameters.
2299static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2300 llvm::FPClassTest Mask = llvm::fcNone;
2301 if (LangOpts.NoHonorInfs)
2302 Mask |= llvm::fcInf;
2303 if (LangOpts.NoHonorNaNs)
2304 Mask |= llvm::fcNan;
2305 return Mask;
2306}
2307
2309 CGCalleeInfo CalleeInfo,
2310 llvm::AttributeList &Attrs) {
2311 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2312 Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2313 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2314 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2315 Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2316 }
2317}
2318
2319/// Construct the IR attribute list of a function or call.
2320///
2321/// When adding an attribute, please consider where it should be handled:
2322///
2323/// - getDefaultFunctionAttributes is for attributes that are essentially
2324/// part of the global target configuration (but perhaps can be
2325/// overridden on a per-function basis). Adding attributes there
2326/// will cause them to also be set in frontends that build on Clang's
2327/// target-configuration logic, as well as for code defined in library
2328/// modules such as CUDA's libdevice.
2329///
2330/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2331/// and adds declaration-specific, convention-specific, and
2332/// frontend-specific logic. The last is of particular importance:
2333/// attributes that restrict how the frontend generates code must be
2334/// added here rather than getDefaultFunctionAttributes.
2335///
2337 const CGFunctionInfo &FI,
2338 CGCalleeInfo CalleeInfo,
2339 llvm::AttributeList &AttrList,
2340 unsigned &CallingConv,
2341 bool AttrOnCallSite, bool IsThunk) {
2342 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2343 llvm::AttrBuilder RetAttrs(getLLVMContext());
2344
2345 // Collect function IR attributes from the CC lowering.
2346 // We'll collect the paramete and result attributes later.
2348 if (FI.isNoReturn())
2349 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2350 if (FI.isCmseNSCall())
2351 FuncAttrs.addAttribute("cmse_nonsecure_call");
2352
2353 // Collect function IR attributes from the callee prototype if we have one.
2355 CalleeInfo.getCalleeFunctionProtoType());
2356
2357 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2358
2359 // Attach assumption attributes to the declaration. If this is a call
2360 // site, attach assumptions from the caller to the call as well.
2361 AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2362
2363 bool HasOptnone = false;
2364 // The NoBuiltinAttr attached to the target FunctionDecl.
2365 const NoBuiltinAttr *NBA = nullptr;
2366
2367 // Some ABIs may result in additional accesses to arguments that may
2368 // otherwise not be present.
2369 auto AddPotentialArgAccess = [&]() {
2370 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2371 if (A.isValid())
2372 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2373 llvm::MemoryEffects::argMemOnly());
2374 };
2375
2376 // Collect function IR attributes based on declaration-specific
2377 // information.
2378 // FIXME: handle sseregparm someday...
2379 if (TargetDecl) {
2380 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2381 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2382 if (TargetDecl->hasAttr<NoThrowAttr>())
2383 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2384 if (TargetDecl->hasAttr<NoReturnAttr>())
2385 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2386 if (TargetDecl->hasAttr<ColdAttr>())
2387 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2388 if (TargetDecl->hasAttr<HotAttr>())
2389 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2390 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2391 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2392 if (TargetDecl->hasAttr<ConvergentAttr>())
2393 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2394
2395 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2397 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2398 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2399 // A sane operator new returns a non-aliasing pointer.
2400 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2401 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2402 (Kind == OO_New || Kind == OO_Array_New))
2403 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2404 }
2405 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2406 const bool IsVirtualCall = MD && MD->isVirtual();
2407 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2408 // virtual function. These attributes are not inherited by overloads.
2409 if (!(AttrOnCallSite && IsVirtualCall)) {
2410 if (Fn->isNoReturn())
2411 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2412 NBA = Fn->getAttr<NoBuiltinAttr>();
2413 }
2414 }
2415
2416 if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2417 // Only place nomerge attribute on call sites, never functions. This
2418 // allows it to work on indirect virtual function calls.
2419 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2420 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2421 }
2422
2423 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2424 if (TargetDecl->hasAttr<ConstAttr>()) {
2425 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2426 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2427 // gcc specifies that 'const' functions have greater restrictions than
2428 // 'pure' functions, so they also cannot have infinite loops.
2429 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2430 } else if (TargetDecl->hasAttr<PureAttr>()) {
2431 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2432 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2433 // gcc specifies that 'pure' functions cannot have infinite loops.
2434 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2435 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2436 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2437 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2438 }
2439 if (TargetDecl->hasAttr<RestrictAttr>())
2440 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2441 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2442 !CodeGenOpts.NullPointerIsValid)
2443 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2444 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2445 FuncAttrs.addAttribute("no_caller_saved_registers");
2446 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2447 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2448 if (TargetDecl->hasAttr<LeafAttr>())
2449 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2450 if (TargetDecl->hasAttr<BPFFastCallAttr>())
2451 FuncAttrs.addAttribute("bpf_fastcall");
2452
2453 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2454 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2455 std::optional<unsigned> NumElemsParam;
2456 if (AllocSize->getNumElemsParam().isValid())
2457 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2458 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2459 NumElemsParam);
2460 }
2461
2462 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2463 if (getLangOpts().OpenCLVersion <= 120) {
2464 // OpenCL v1.2 Work groups are always uniform
2465 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2466 } else {
2467 // OpenCL v2.0 Work groups may be whether uniform or not.
2468 // '-cl-uniform-work-group-size' compile option gets a hint
2469 // to the compiler that the global work-size be a multiple of
2470 // the work-group size specified to clEnqueueNDRangeKernel
2471 // (i.e. work groups are uniform).
2472 FuncAttrs.addAttribute(
2473 "uniform-work-group-size",
2474 llvm::toStringRef(getLangOpts().OffloadUniformBlock));
2475 }
2476 }
2477
2478 if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
2479 getLangOpts().OffloadUniformBlock)
2480 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2481
2482 if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2483 FuncAttrs.addAttribute("aarch64_pstate_sm_body");
2484 }
2485
2486 // Attach "no-builtins" attributes to:
2487 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2488 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2489 // The attributes can come from:
2490 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2491 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2492 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2493
2494 // Collect function IR attributes based on global settiings.
2495 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2496
2497 // Override some default IR attributes based on declaration-specific
2498 // information.
2499 if (TargetDecl) {
2500 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2501 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2502 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2503 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2504 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2505 FuncAttrs.removeAttribute("split-stack");
2506 if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2507 // A function "__attribute__((...))" overrides the command-line flag.
2508 auto Kind =
2509 TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2510 FuncAttrs.removeAttribute("zero-call-used-regs");
2511 FuncAttrs.addAttribute(
2512 "zero-call-used-regs",
2513 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2514 }
2515
2516 // Add NonLazyBind attribute to function declarations when -fno-plt
2517 // is used.
2518 // FIXME: what if we just haven't processed the function definition
2519 // yet, or if it's an external definition like C99 inline?
2520 if (CodeGenOpts.NoPLT) {
2521 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2522 if (!Fn->isDefined() && !AttrOnCallSite) {
2523 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2524 }
2525 }
2526 }
2527 // Remove 'convergent' if requested.
2528 if (TargetDecl->hasAttr<NoConvergentAttr>())
2529 FuncAttrs.removeAttribute(llvm::Attribute::Convergent);
2530 }
2531
2532 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2533 // functions with -funique-internal-linkage-names.
2534 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2535 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2536 if (!FD->isExternallyVisible())
2537 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2538 "selected");
2539 }
2540 }
2541
2542 // Collect non-call-site function IR attributes from declaration-specific
2543 // information.
2544 if (!AttrOnCallSite) {
2545 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2546 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2547
2548 // Whether tail calls are enabled.
2549 auto shouldDisableTailCalls = [&] {
2550 // Should this be honored in getDefaultFunctionAttributes?
2551 if (CodeGenOpts.DisableTailCalls)
2552 return true;
2553
2554 if (!TargetDecl)
2555 return false;
2556
2557 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2558 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2559 return true;
2560
2561 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2562 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2563 if (!BD->doesNotEscape())
2564 return true;
2565 }
2566
2567 return false;
2568 };
2569 if (shouldDisableTailCalls())
2570 FuncAttrs.addAttribute("disable-tail-calls", "true");
2571
2572 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2573 // handles these separately to set them based on the global defaults.
2574 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2575 }
2576
2577 // Collect attributes from arguments and return values.
2578 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2579
2580 QualType RetTy = FI.getReturnType();
2581 const ABIArgInfo &RetAI = FI.getReturnInfo();
2582 const llvm::DataLayout &DL = getDataLayout();
2583
2584 // Determine if the return type could be partially undef
2585 if (CodeGenOpts.EnableNoundefAttrs &&
2586 HasStrictReturn(*this, RetTy, TargetDecl)) {
2587 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2588 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2589 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2590 }
2591
2592 switch (RetAI.getKind()) {
2593 case ABIArgInfo::Extend:
2594 if (RetAI.isSignExt())
2595 RetAttrs.addAttribute(llvm::Attribute::SExt);
2596 else if (RetAI.isZeroExt())
2597 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2598 else
2599 RetAttrs.addAttribute(llvm::Attribute::NoExt);
2600 [[fallthrough]];
2601 case ABIArgInfo::Direct:
2602 if (RetAI.getInReg())
2603 RetAttrs.addAttribute(llvm::Attribute::InReg);
2604
2605 if (canApplyNoFPClass(RetAI, RetTy, true))
2606 RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2607
2608 break;
2609 case ABIArgInfo::Ignore:
2610 break;
2611
2613 case ABIArgInfo::Indirect: {
2614 // inalloca and sret disable readnone and readonly
2615 AddPotentialArgAccess();
2616 break;
2617 }
2618
2620 break;
2621
2622 case ABIArgInfo::Expand:
2624 llvm_unreachable("Invalid ABI kind for return argument");
2625 }
2626
2627 if (!IsThunk) {
2628 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2629 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2630 QualType PTy = RefTy->getPointeeType();
2631 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2632 RetAttrs.addDereferenceableAttr(
2633 getMinimumObjectSize(PTy).getQuantity());
2634 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2635 !CodeGenOpts.NullPointerIsValid)
2636 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2637 if (PTy->isObjectType()) {
2638 llvm::Align Alignment =
2640 RetAttrs.addAlignmentAttr(Alignment);
2641 }
2642 }
2643 }
2644
2645 bool hasUsedSRet = false;
2646 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2647
2648 // Attach attributes to sret.
2649 if (IRFunctionArgs.hasSRetArg()) {
2650 llvm::AttrBuilder SRETAttrs(getLLVMContext());
2651 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2652 SRETAttrs.addAttribute(llvm::Attribute::Writable);
2653 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2654 hasUsedSRet = true;
2655 if (RetAI.getInReg())
2656 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2657 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2658 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2659 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2660 }
2661
2662 // Attach attributes to inalloca argument.
2663 if (IRFunctionArgs.hasInallocaArg()) {
2664 llvm::AttrBuilder Attrs(getLLVMContext());
2665 Attrs.addInAllocaAttr(FI.getArgStruct());
2666 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2667 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2668 }
2669
2670 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2671 // unless this is a thunk function.
2672 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2673 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2674 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2675 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2676
2677 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2678
2679 llvm::AttrBuilder Attrs(getLLVMContext());
2680
2681 QualType ThisTy =
2683
2684 if (!CodeGenOpts.NullPointerIsValid &&
2685 getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2686 Attrs.addAttribute(llvm::Attribute::NonNull);
2687 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2688 } else {
2689 // FIXME dereferenceable should be correct here, regardless of
2690 // NullPointerIsValid. However, dereferenceable currently does not always
2691 // respect NullPointerIsValid and may imply nonnull and break the program.
2692 // See https://reviews.llvm.org/D66618 for discussions.
2693 Attrs.addDereferenceableOrNullAttr(
2696 .getQuantity());
2697 }
2698
2699 llvm::Align Alignment =
2700 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2701 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2702 .getAsAlign();
2703 Attrs.addAlignmentAttr(Alignment);
2704
2705 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2706 }
2707
2708 unsigned ArgNo = 0;
2710 E = FI.arg_end();
2711 I != E; ++I, ++ArgNo) {
2712 QualType ParamType = I->type;
2713 const ABIArgInfo &AI = I->info;
2714 llvm::AttrBuilder Attrs(getLLVMContext());
2715
2716 // Add attribute for padding argument, if necessary.
2717 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2718 if (AI.getPaddingInReg()) {
2719 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2720 llvm::AttributeSet::get(
2722 llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
2723 }
2724 }
2725
2726 // Decide whether the argument we're handling could be partially undef
2727 if (CodeGenOpts.EnableNoundefAttrs &&
2728 DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2729 Attrs.addAttribute(llvm::Attribute::NoUndef);
2730 }
2731
2732 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2733 // have the corresponding parameter variable. It doesn't make
2734 // sense to do it here because parameters are so messed up.
2735 switch (AI.getKind()) {
2736 case ABIArgInfo::Extend:
2737 if (AI.isSignExt())
2738 Attrs.addAttribute(llvm::Attribute::SExt);
2739 else if (AI.isZeroExt())
2740 Attrs.addAttribute(llvm::Attribute::ZExt);
2741 else
2742 Attrs.addAttribute(llvm::Attribute::NoExt);
2743 [[fallthrough]];
2744 case ABIArgInfo::Direct:
2745 if (ArgNo == 0 && FI.isChainCall())
2746 Attrs.addAttribute(llvm::Attribute::Nest);
2747 else if (AI.getInReg())
2748 Attrs.addAttribute(llvm::Attribute::InReg);
2749 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2750
2751 if (canApplyNoFPClass(AI, ParamType, false))
2752 Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2753 break;
2754 case ABIArgInfo::Indirect: {
2755 if (AI.getInReg())
2756 Attrs.addAttribute(llvm::Attribute::InReg);
2757
2758 if (AI.getIndirectByVal())
2759 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2760
2761 auto *Decl = ParamType->getAsRecordDecl();
2762 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2763 Decl->getArgPassingRestrictions() ==
2765 // When calling the function, the pointer passed in will be the only
2766 // reference to the underlying object. Mark it accordingly.
2767 Attrs.addAttribute(llvm::Attribute::NoAlias);
2768
2769 // TODO: We could add the byref attribute if not byval, but it would
2770 // require updating many testcases.
2771
2772 CharUnits Align = AI.getIndirectAlign();
2773
2774 // In a byval argument, it is important that the required
2775 // alignment of the type is honored, as LLVM might be creating a
2776 // *new* stack object, and needs to know what alignment to give
2777 // it. (Sometimes it can deduce a sensible alignment on its own,
2778 // but not if clang decides it must emit a packed struct, or the
2779 // user specifies increased alignment requirements.)
2780 //
2781 // This is different from indirect *not* byval, where the object
2782 // exists already, and the align attribute is purely
2783 // informative.
2784 assert(!Align.isZero());
2785
2786 // For now, only add this when we have a byval argument.
2787 // TODO: be less lazy about updating test cases.
2788 if (AI.getIndirectByVal())
2789 Attrs.addAlignmentAttr(Align.getQuantity());
2790
2791 // byval disables readnone and readonly.
2792 AddPotentialArgAccess();
2793 break;
2794 }
2796 CharUnits Align = AI.getIndirectAlign();
2797 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2798 Attrs.addAlignmentAttr(Align.getQuantity());
2799 break;
2800 }
2801 case ABIArgInfo::Ignore:
2802 case ABIArgInfo::Expand:
2804 break;
2805
2807 // inalloca disables readnone and readonly.
2808 AddPotentialArgAccess();
2809 continue;
2810 }
2811
2812 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2813 QualType PTy = RefTy->getPointeeType();
2814 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2815 Attrs.addDereferenceableAttr(
2816 getMinimumObjectSize(PTy).getQuantity());
2817 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2818 !CodeGenOpts.NullPointerIsValid)
2819 Attrs.addAttribute(llvm::Attribute::NonNull);
2820 if (PTy->isObjectType()) {
2821 llvm::Align Alignment =
2823 Attrs.addAlignmentAttr(Alignment);
2824 }
2825 }
2826
2827 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2828 // > For arguments to a __kernel function declared to be a pointer to a
2829 // > data type, the OpenCL compiler can assume that the pointee is always
2830 // > appropriately aligned as required by the data type.
2831 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>() &&
2832 ParamType->isPointerType()) {
2833 QualType PTy = ParamType->getPointeeType();
2834 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2835 llvm::Align Alignment =
2837 Attrs.addAlignmentAttr(Alignment);
2838 }
2839 }
2840
2841 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2844 Attrs.addAttribute(llvm::Attribute::NoAlias);
2845 break;
2847 break;
2848
2850 // Add 'sret' if we haven't already used it for something, but
2851 // only if the result is void.
2852 if (!hasUsedSRet && RetTy->isVoidType()) {
2853 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2854 hasUsedSRet = true;
2855 }
2856
2857 // Add 'noalias' in either case.
2858 Attrs.addAttribute(llvm::Attribute::NoAlias);
2859
2860 // Add 'dereferenceable' and 'alignment'.
2861 auto PTy = ParamType->getPointeeType();
2862 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2863 auto info = getContext().getTypeInfoInChars(PTy);
2864 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2865 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2866 }
2867 break;
2868 }
2869
2871 Attrs.addAttribute(llvm::Attribute::SwiftError);
2872 break;
2873
2875 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2876 break;
2877
2879 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2880 break;
2881 }
2882
2883 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2884 Attrs.addCapturesAttr(llvm::CaptureInfo::none());
2885
2886 if (Attrs.hasAttributes()) {
2887 unsigned FirstIRArg, NumIRArgs;
2888 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2889 for (unsigned i = 0; i < NumIRArgs; i++)
2890 ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
2891 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
2892 }
2893 }
2894 assert(ArgNo == FI.arg_size());
2895
2896 AttrList = llvm::AttributeList::get(
2897 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2898 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2899}
2900
2901/// An argument came in as a promoted argument; demote it back to its
2902/// declared type.
2903static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2904 const VarDecl *var,
2905 llvm::Value *value) {
2906 llvm::Type *varType = CGF.ConvertType(var->getType());
2907
2908 // This can happen with promotions that actually don't change the
2909 // underlying type, like the enum promotions.
2910 if (value->getType() == varType) return value;
2911
2912 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2913 && "unexpected promotion type");
2914
2915 if (isa<llvm::IntegerType>(varType))
2916 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2917
2918 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2919}
2920
2921/// Returns the attribute (either parameter attribute, or function
2922/// attribute), which declares argument ArgNo to be non-null.
2923static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2924 QualType ArgType, unsigned ArgNo) {
2925 // FIXME: __attribute__((nonnull)) can also be applied to:
2926 // - references to pointers, where the pointee is known to be
2927 // nonnull (apparently a Clang extension)
2928 // - transparent unions containing pointers
2929 // In the former case, LLVM IR cannot represent the constraint. In
2930 // the latter case, we have no guarantee that the transparent union
2931 // is in fact passed as a pointer.
2932 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2933 return nullptr;
2934 // First, check attribute on parameter itself.
2935 if (PVD) {
2936 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2937 return ParmNNAttr;
2938 }
2939 // Check function attributes.
2940 if (!FD)
2941 return nullptr;
2942 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2943 if (NNAttr->isNonNull(ArgNo))
2944 return NNAttr;
2945 }
2946 return nullptr;
2947}
2948
2949namespace {
2950 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2951 Address Temp;
2952 Address Arg;
2953 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2954 void Emit(CodeGenFunction &CGF, Flags flags) override {
2955 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2956 CGF.Builder.CreateStore(errorValue, Arg);
2957 }
2958 };
2959}
2960
2962 llvm::Function *Fn,
2963 const FunctionArgList &Args) {
2964 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2965 // Naked functions don't have prologues.
2966 return;
2967
2968 // If this is an implicit-return-zero function, go ahead and
2969 // initialize the return value. TODO: it might be nice to have
2970 // a more general mechanism for this that didn't require synthesized
2971 // return statements.
2972 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2973 if (FD->hasImplicitReturnZero()) {
2974 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2975 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2976 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2978 }
2979 }
2980
2981 // FIXME: We no longer need the types from FunctionArgList; lift up and
2982 // simplify.
2983
2984 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2985 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2986
2987 // If we're using inalloca, all the memory arguments are GEPs off of the last
2988 // parameter, which is a pointer to the complete memory area.
2989 Address ArgStruct = Address::invalid();
2990 if (IRFunctionArgs.hasInallocaArg())
2991 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2993
2994 // Name the struct return parameter.
2995 if (IRFunctionArgs.hasSRetArg()) {
2996 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2997 AI->setName("agg.result");
2998 AI->addAttr(llvm::Attribute::NoAlias);
2999 }
3000
3001 // Track if we received the parameter as a pointer (indirect, byval, or
3002 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
3003 // into a local alloca for us.
3005 ArgVals.reserve(Args.size());
3006
3007 // Create a pointer value for every parameter declaration. This usually
3008 // entails copying one or more LLVM IR arguments into an alloca. Don't push
3009 // any cleanups or do anything that might unwind. We do that separately, so
3010 // we can push the cleanups in the correct order for the ABI.
3011 assert(FI.arg_size() == Args.size() &&
3012 "Mismatch between function signature & arguments.");
3013 unsigned ArgNo = 0;
3015 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
3016 i != e; ++i, ++info_it, ++ArgNo) {
3017 const VarDecl *Arg = *i;
3018 const ABIArgInfo &ArgI = info_it->info;
3019
3020 bool isPromoted =
3021 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
3022 // We are converting from ABIArgInfo type to VarDecl type directly, unless
3023 // the parameter is promoted. In this case we convert to
3024 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3025 QualType Ty = isPromoted ? info_it->type : Arg->getType();
3026 assert(hasScalarEvaluationKind(Ty) ==
3028
3029 unsigned FirstIRArg, NumIRArgs;
3030 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3031
3032 switch (ArgI.getKind()) {
3033 case ABIArgInfo::InAlloca: {
3034 assert(NumIRArgs == 0);
3035 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3036 Address V =
3037 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3038 if (ArgI.getInAllocaIndirect())
3040 getContext().getTypeAlignInChars(Ty));
3041 ArgVals.push_back(ParamValue::forIndirect(V));
3042 break;
3043 }
3044
3047 assert(NumIRArgs == 1);
3049 Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3050 nullptr, KnownNonNull);
3051
3052 if (!hasScalarEvaluationKind(Ty)) {
3053 // Aggregates and complex variables are accessed by reference. All we
3054 // need to do is realign the value, if requested. Also, if the address
3055 // may be aliased, copy it to ensure that the parameter variable is
3056 // mutable and has a unique adress, as C requires.
3057 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3058 RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3059
3060 // Copy from the incoming argument pointer to the temporary with the
3061 // appropriate alignment.
3062 //
3063 // FIXME: We should have a common utility for generating an aggregate
3064 // copy.
3067 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3068 ParamAddr.emitRawPointer(*this),
3069 ParamAddr.getAlignment().getAsAlign(),
3070 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3071 ParamAddr = AlignedTemp;
3072 }
3073 ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3074 } else {
3075 // Load scalar value from indirect argument.
3076 llvm::Value *V =
3077 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3078
3079 if (isPromoted)
3080 V = emitArgumentDemotion(*this, Arg, V);
3081 ArgVals.push_back(ParamValue::forDirect(V));
3082 }
3083 break;
3084 }
3085
3086 case ABIArgInfo::Extend:
3087 case ABIArgInfo::Direct: {
3088 auto AI = Fn->getArg(FirstIRArg);
3089 llvm::Type *LTy = ConvertType(Arg->getType());
3090
3091 // Prepare parameter attributes. So far, only attributes for pointer
3092 // parameters are prepared. See
3093 // http://llvm.org/docs/LangRef.html#paramattrs.
3094 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3095 ArgI.getCoerceToType()->isPointerTy()) {
3096 assert(NumIRArgs == 1);
3097
3098 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3099 // Set `nonnull` attribute if any.
3100 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3101 PVD->getFunctionScopeIndex()) &&
3102 !CGM.getCodeGenOpts().NullPointerIsValid)
3103 AI->addAttr(llvm::Attribute::NonNull);
3104
3105 QualType OTy = PVD->getOriginalType();
3106 if (const auto *ArrTy =
3107 getContext().getAsConstantArrayType(OTy)) {
3108 // A C99 array parameter declaration with the static keyword also
3109 // indicates dereferenceability, and if the size is constant we can
3110 // use the dereferenceable attribute (which requires the size in
3111 // bytes).
3112 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3113 QualType ETy = ArrTy->getElementType();
3114 llvm::Align Alignment =
3116 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3117 uint64_t ArrSize = ArrTy->getZExtSize();
3118 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3119 ArrSize) {
3120 llvm::AttrBuilder Attrs(getLLVMContext());
3121 Attrs.addDereferenceableAttr(
3122 getContext().getTypeSizeInChars(ETy).getQuantity() *
3123 ArrSize);
3124 AI->addAttrs(Attrs);
3125 } else if (getContext().getTargetInfo().getNullPointerValue(
3126 ETy.getAddressSpace()) == 0 &&
3127 !CGM.getCodeGenOpts().NullPointerIsValid) {
3128 AI->addAttr(llvm::Attribute::NonNull);
3129 }
3130 }
3131 } else if (const auto *ArrTy =
3132 getContext().getAsVariableArrayType(OTy)) {
3133 // For C99 VLAs with the static keyword, we don't know the size so
3134 // we can't use the dereferenceable attribute, but in addrspace(0)
3135 // we know that it must be nonnull.
3136 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3137 QualType ETy = ArrTy->getElementType();
3138 llvm::Align Alignment =
3140 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
3141 if (!getTypes().getTargetAddressSpace(ETy) &&
3142 !CGM.getCodeGenOpts().NullPointerIsValid)
3143 AI->addAttr(llvm::Attribute::NonNull);
3144 }
3145 }
3146
3147 // Set `align` attribute if any.
3148 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3149 if (!AVAttr)
3150 if (const auto *TOTy = OTy->getAs<TypedefType>())
3151 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3152 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3153 // If alignment-assumption sanitizer is enabled, we do *not* add
3154 // alignment attribute here, but emit normal alignment assumption,
3155 // so the UBSAN check could function.
3156 llvm::ConstantInt *AlignmentCI =
3157 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3158 uint64_t AlignmentInt =
3159 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3160 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3161 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3162 AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
3163 llvm::Align(AlignmentInt)));
3164 }
3165 }
3166 }
3167
3168 // Set 'noalias' if an argument type has the `restrict` qualifier.
3169 if (Arg->getType().isRestrictQualified())
3170 AI->addAttr(llvm::Attribute::NoAlias);
3171 }
3172
3173 // Prepare the argument value. If we have the trivial case, handle it
3174 // with no muss and fuss.
3175 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
3176 ArgI.getCoerceToType() == ConvertType(Ty) &&
3177 ArgI.getDirectOffset() == 0) {
3178 assert(NumIRArgs == 1);
3179
3180 // LLVM expects swifterror parameters to be used in very restricted
3181 // ways. Copy the value into a less-restricted temporary.
3182 llvm::Value *V = AI;
3183 if (FI.getExtParameterInfo(ArgNo).getABI()
3185 QualType pointeeTy = Ty->getPointeeType();
3186 assert(pointeeTy->isPointerType());
3187 RawAddress temp =
3188 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3190 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3191 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3192 Builder.CreateStore(incomingErrorValue, temp);
3193 V = temp.getPointer();
3194
3195 // Push a cleanup to copy the value back at the end of the function.
3196 // The convention does not guarantee that the value will be written
3197 // back if the function exits with an unwind exception.
3198 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3199 }
3200
3201 // Ensure the argument is the correct type.
3202 if (V->getType() != ArgI.getCoerceToType())
3203 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3204
3205 if (isPromoted)
3206 V = emitArgumentDemotion(*this, Arg, V);
3207
3208 // Because of merging of function types from multiple decls it is
3209 // possible for the type of an argument to not match the corresponding
3210 // type in the function type. Since we are codegening the callee
3211 // in here, add a cast to the argument type.
3212 llvm::Type *LTy = ConvertType(Arg->getType());
3213 if (V->getType() != LTy)
3214 V = Builder.CreateBitCast(V, LTy);
3215
3216 ArgVals.push_back(ParamValue::forDirect(V));
3217 break;
3218 }
3219
3220 // VLST arguments are coerced to VLATs at the function boundary for
3221 // ABI consistency. If this is a VLST that was coerced to
3222 // a VLAT at the function boundary and the types match up, use
3223 // llvm.vector.extract to convert back to the original VLST.
3224 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3225 llvm::Value *ArgVal = Fn->getArg(FirstIRArg);
3226 if (auto *VecTyFrom =
3227 dyn_cast<llvm::ScalableVectorType>(ArgVal->getType())) {
3228 auto [Coerced, Extracted] = CoerceScalableToFixed(
3229 *this, VecTyTo, VecTyFrom, ArgVal, Arg->getName());
3230 if (Extracted) {
3231 assert(NumIRArgs == 1);
3232 ArgVals.push_back(ParamValue::forDirect(Coerced));
3233 break;
3234 }
3235 }
3236 }
3237
3238 llvm::StructType *STy =
3239 dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3240 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
3241 Arg->getName());
3242
3243 // Pointer to store into.
3244 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3245
3246 // Fast-isel and the optimizer generally like scalar values better than
3247 // FCAs, so we flatten them if this is safe to do for this argument.
3248 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3249 STy->getNumElements() > 1) {
3250 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3251 llvm::TypeSize PtrElementSize =
3252 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3253 if (StructSize.isScalable()) {
3254 assert(STy->containsHomogeneousScalableVectorTypes() &&
3255 "ABI only supports structure with homogeneous scalable vector "
3256 "type");
3257 assert(StructSize == PtrElementSize &&
3258 "Only allow non-fractional movement of structure with"
3259 "homogeneous scalable vector type");
3260 assert(STy->getNumElements() == NumIRArgs);
3261
3262 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3263 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3264 auto *AI = Fn->getArg(FirstIRArg + i);
3265 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3266 LoadedStructValue =
3267 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3268 }
3269
3270 Builder.CreateStore(LoadedStructValue, Ptr);
3271 } else {
3272 uint64_t SrcSize = StructSize.getFixedValue();
3273 uint64_t DstSize = PtrElementSize.getFixedValue();
3274
3275 Address AddrToStoreInto = Address::invalid();
3276 if (SrcSize <= DstSize) {
3277 AddrToStoreInto = Ptr.withElementType(STy);
3278 } else {
3279 AddrToStoreInto =
3280 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3281 }
3282
3283 assert(STy->getNumElements() == NumIRArgs);
3284 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3285 auto AI = Fn->getArg(FirstIRArg + i);
3286 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3287 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3288 Builder.CreateStore(AI, EltPtr);
3289 }
3290
3291 if (SrcSize > DstSize) {
3292 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3293 }
3294 }
3295 } else {
3296 // Simple case, just do a coerced store of the argument into the alloca.
3297 assert(NumIRArgs == 1);
3298 auto AI = Fn->getArg(FirstIRArg);
3299 AI->setName(Arg->getName() + ".coerce");
3301 AI, Ptr,
3302 llvm::TypeSize::getFixed(
3303 getContext().getTypeSizeInChars(Ty).getQuantity() -
3304 ArgI.getDirectOffset()),
3305 /*DstIsVolatile=*/false);
3306 }
3307
3308 // Match to what EmitParmDecl is expecting for this type.
3310 llvm::Value *V =
3311 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3312 if (isPromoted)
3313 V = emitArgumentDemotion(*this, Arg, V);
3314 ArgVals.push_back(ParamValue::forDirect(V));
3315 } else {
3316 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3317 }
3318 break;
3319 }
3320
3322 // Reconstruct into a temporary.
3323 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3324 ArgVals.push_back(ParamValue::forIndirect(alloca));
3325
3326 auto coercionType = ArgI.getCoerceAndExpandType();
3327 auto unpaddedCoercionType = ArgI.getUnpaddedCoerceAndExpandType();
3328 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
3329
3330 alloca = alloca.withElementType(coercionType);
3331
3332 unsigned argIndex = FirstIRArg;
3333 unsigned unpaddedIndex = 0;
3334 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3335 llvm::Type *eltType = coercionType->getElementType(i);
3337 continue;
3338
3339 auto eltAddr = Builder.CreateStructGEP(alloca, i);
3340 llvm::Value *elt = Fn->getArg(argIndex++);
3341
3342 auto paramType = unpaddedStruct
3343 ? unpaddedStruct->getElementType(unpaddedIndex++)
3344 : unpaddedCoercionType;
3345
3346 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(eltType)) {
3347 if (auto *VecTyFrom = dyn_cast<llvm::ScalableVectorType>(paramType)) {
3348 bool Extracted;
3349 std::tie(elt, Extracted) = CoerceScalableToFixed(
3350 *this, VecTyTo, VecTyFrom, elt, elt->getName());
3351 assert(Extracted && "Unexpected scalable to fixed vector coercion");
3352 }
3353 }
3354 Builder.CreateStore(elt, eltAddr);
3355 }
3356 assert(argIndex == FirstIRArg + NumIRArgs);
3357 break;
3358 }
3359
3360 case ABIArgInfo::Expand: {
3361 // If this structure was expanded into multiple arguments then
3362 // we need to create a temporary and reconstruct it from the
3363 // arguments.
3364 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3365 LValue LV = MakeAddrLValue(Alloca, Ty);
3366 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3367
3368 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3369 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3370 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3371 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3372 auto AI = Fn->getArg(FirstIRArg + i);
3373 AI->setName(Arg->getName() + "." + Twine(i));
3374 }
3375 break;
3376 }
3377
3378 case ABIArgInfo::Ignore:
3379 assert(NumIRArgs == 0);
3380 // Initialize the local variable appropriately.
3381 if (!hasScalarEvaluationKind(Ty)) {
3382 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3383 } else {
3384 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3385 ArgVals.push_back(ParamValue::forDirect(U));
3386 }
3387 break;
3388 }
3389 }
3390
3391 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3392 for (int I = Args.size() - 1; I >= 0; --I)
3393 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3394 } else {
3395 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3396 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3397 }
3398}
3399
3400static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3401 while (insn->use_empty()) {
3402 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3403 if (!bitcast) return;
3404
3405 // This is "safe" because we would have used a ConstantExpr otherwise.
3406 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3407 bitcast->eraseFromParent();
3408 }
3409}
3410
3411/// Try to emit a fused autorelease of a return result.
3413 llvm::Value *result) {
3414 // We must be immediately followed the cast.
3415 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3416 if (BB->empty()) return nullptr;
3417 if (&BB->back() != result) return nullptr;
3418
3419 llvm::Type *resultType = result->getType();
3420
3421 // result is in a BasicBlock and is therefore an Instruction.
3422 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3423
3425
3426 // Look for:
3427 // %generator = bitcast %type1* %generator2 to %type2*
3428 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3429 // We would have emitted this as a constant if the operand weren't
3430 // an Instruction.
3431 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3432
3433 // Require the generator to be immediately followed by the cast.
3434 if (generator->getNextNode() != bitcast)
3435 return nullptr;
3436
3437 InstsToKill.push_back(bitcast);
3438 }
3439
3440 // Look for:
3441 // %generator = call i8* @objc_retain(i8* %originalResult)
3442 // or
3443 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3444 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3445 if (!call) return nullptr;
3446
3447 bool doRetainAutorelease;
3448
3449 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3450 doRetainAutorelease = true;
3451 } else if (call->getCalledOperand() ==
3453 doRetainAutorelease = false;
3454
3455 // If we emitted an assembly marker for this call (and the
3456 // ARCEntrypoints field should have been set if so), go looking
3457 // for that call. If we can't find it, we can't do this
3458 // optimization. But it should always be the immediately previous
3459 // instruction, unless we needed bitcasts around the call.
3461 llvm::Instruction *prev = call->getPrevNode();
3462 assert(prev);
3463 if (isa<llvm::BitCastInst>(prev)) {
3464 prev = prev->getPrevNode();
3465 assert(prev);
3466 }
3467 assert(isa<llvm::CallInst>(prev));
3468 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3470 InstsToKill.push_back(prev);
3471 }
3472 } else {
3473 return nullptr;
3474 }
3475
3476 result = call->getArgOperand(0);
3477 InstsToKill.push_back(call);
3478
3479 // Keep killing bitcasts, for sanity. Note that we no longer care
3480 // about precise ordering as long as there's exactly one use.
3481 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3482 if (!bitcast->hasOneUse()) break;
3483 InstsToKill.push_back(bitcast);
3484 result = bitcast->getOperand(0);
3485 }
3486
3487 // Delete all the unnecessary instructions, from latest to earliest.
3488 for (auto *I : InstsToKill)
3489 I->eraseFromParent();
3490
3491 // Do the fused retain/autorelease if we were asked to.
3492 if (doRetainAutorelease)
3493 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3494
3495 // Cast back to the result type.
3496 return CGF.Builder.CreateBitCast(result, resultType);
3497}
3498
3499/// If this is a +1 of the value of an immutable 'self', remove it.
3501 llvm::Value *result) {
3502 // This is only applicable to a method with an immutable 'self'.
3503 const ObjCMethodDecl *method =
3504 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3505 if (!method) return nullptr;
3506 const VarDecl *self = method->getSelfDecl();
3507 if (!self->getType().isConstQualified()) return nullptr;
3508
3509 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3510 // functions, which would cause us to miss the retain.
3511 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3512 if (!retainCall || retainCall->getCalledOperand() !=
3514 return nullptr;
3515
3516 // Look for an ordinary load of 'self'.
3517 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3518 llvm::LoadInst *load =
3519 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3520 if (!load || load->isAtomic() || load->isVolatile() ||
3521 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3522 return nullptr;
3523
3524 // Okay! Burn it all down. This relies for correctness on the
3525 // assumption that the retain is emitted as part of the return and
3526 // that thereafter everything is used "linearly".
3527 llvm::Type *resultType = result->getType();
3528 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3529 assert(retainCall->use_empty());
3530 retainCall->eraseFromParent();
3531 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3532
3533 return CGF.Builder.CreateBitCast(load, resultType);
3534}
3535
3536/// Emit an ARC autorelease of the result of a function.
3537///
3538/// \return the value to actually return from the function
3540 llvm::Value *result) {
3541 // If we're returning 'self', kill the initial retain. This is a
3542 // heuristic attempt to "encourage correctness" in the really unfortunate
3543 // case where we have a return of self during a dealloc and we desperately
3544 // need to avoid the possible autorelease.
3545 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3546 return self;
3547
3548 // At -O0, try to emit a fused retain/autorelease.
3549 if (CGF.shouldUseFusedARCCalls())
3550 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3551 return fused;
3552
3553 return CGF.EmitARCAutoreleaseReturnValue(result);
3554}
3555
3556/// Heuristically search for a dominating store to the return-value slot.
3558 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3559
3560 // Check if a User is a store which pointerOperand is the ReturnValue.
3561 // We are looking for stores to the ReturnValue, not for stores of the
3562 // ReturnValue to some other location.
3563 auto GetStoreIfValid = [&CGF,
3564 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3565 auto *SI = dyn_cast<llvm::StoreInst>(U);
3566 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3567 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3568 return nullptr;
3569 // These aren't actually possible for non-coerced returns, and we
3570 // only care about non-coerced returns on this code path.
3571 // All memory instructions inside __try block are volatile.
3572 assert(!SI->isAtomic() &&
3573 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3574 return SI;
3575 };
3576 // If there are multiple uses of the return-value slot, just check
3577 // for something immediately preceding the IP. Sometimes this can
3578 // happen with how we generate implicit-returns; it can also happen
3579 // with noreturn cleanups.
3580 if (!ReturnValuePtr->hasOneUse()) {
3581 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3582 if (IP->empty()) return nullptr;
3583
3584 // Look at directly preceding instruction, skipping bitcasts, lifetime
3585 // markers, and fake uses and their operands.
3586 const llvm::Instruction *LoadIntoFakeUse = nullptr;
3587 for (llvm::Instruction &I : make_range(IP->rbegin(), IP->rend())) {
3588 // Ignore instructions that are just loads for fake uses; the load should
3589 // immediately precede the fake use, so we only need to remember the
3590 // operand for the last fake use seen.
3591 if (LoadIntoFakeUse == &I)
3592 continue;
3593 if (isa<llvm::BitCastInst>(&I))
3594 continue;
3595 if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I)) {
3596 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3597 continue;
3598
3599 if (II->getIntrinsicID() == llvm::Intrinsic::fake_use) {
3600 LoadIntoFakeUse = dyn_cast<llvm::Instruction>(II->getArgOperand(0));
3601 continue;
3602 }
3603 }
3604 return GetStoreIfValid(&I);
3605 }
3606 return nullptr;
3607 }
3608
3609 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3610 if (!store) return nullptr;
3611
3612 // Now do a first-and-dirty dominance check: just walk up the
3613 // single-predecessors chain from the current insertion point.
3614 llvm::BasicBlock *StoreBB = store->getParent();
3615 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3617 while (IP != StoreBB) {
3618 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3619 return nullptr;
3620 }
3621
3622 // Okay, the store's basic block dominates the insertion point; we
3623 // can do our thing.
3624 return store;
3625}
3626
3627// Helper functions for EmitCMSEClearRecord
3628
3629// Set the bits corresponding to a field having width `BitWidth` and located at
3630// offset `BitOffset` (from the least significant bit) within a storage unit of
3631// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3632// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3633static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3634 int BitWidth, int CharWidth) {
3635 assert(CharWidth <= 64);
3636 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3637
3638 int Pos = 0;
3639 if (BitOffset >= CharWidth) {
3640 Pos += BitOffset / CharWidth;
3641 BitOffset = BitOffset % CharWidth;
3642 }
3643
3644 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3645 if (BitOffset + BitWidth >= CharWidth) {
3646 Bits[Pos++] |= (Used << BitOffset) & Used;
3647 BitWidth -= CharWidth - BitOffset;
3648 BitOffset = 0;
3649 }
3650
3651 while (BitWidth >= CharWidth) {
3652 Bits[Pos++] = Used;
3653 BitWidth -= CharWidth;
3654 }
3655
3656 if (BitWidth > 0)
3657 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3658}
3659
3660// Set the bits corresponding to a field having width `BitWidth` and located at
3661// offset `BitOffset` (from the least significant bit) within a storage unit of
3662// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3663// `Bits` corresponds to one target byte. Use target endian layout.
3664static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3665 int StorageSize, int BitOffset, int BitWidth,
3666 int CharWidth, bool BigEndian) {
3667
3668 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3669 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3670
3671 if (BigEndian)
3672 std::reverse(TmpBits.begin(), TmpBits.end());
3673
3674 for (uint64_t V : TmpBits)
3675 Bits[StorageOffset++] |= V;
3676}
3677
3678static void setUsedBits(CodeGenModule &, QualType, int,
3680
3681// Set the bits in `Bits`, which correspond to the value representations of
3682// the actual members of the record type `RTy`. Note that this function does
3683// not handle base classes, virtual tables, etc, since they cannot happen in
3684// CMSE function arguments or return. The bit mask corresponds to the target
3685// memory layout, i.e. it's endian dependent.
3686static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3688 ASTContext &Context = CGM.getContext();
3689 int CharWidth = Context.getCharWidth();
3690 const RecordDecl *RD = RTy->getDecl()->getDefinition();
3691 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3692 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3693
3694 int Idx = 0;
3695 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3696 const FieldDecl *F = *I;
3697
3698 if (F->isUnnamedBitField() || F->isZeroLengthBitField() ||
3700 continue;
3701
3702 if (F->isBitField()) {
3703 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3704 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3705 BFI.StorageSize / CharWidth, BFI.Offset,
3706 BFI.Size, CharWidth,
3707 CGM.getDataLayout().isBigEndian());
3708 continue;
3709 }
3710
3711 setUsedBits(CGM, F->getType(),
3712 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3713 }
3714}
3715
3716// Set the bits in `Bits`, which correspond to the value representations of
3717// the elements of an array type `ATy`.
3718static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3719 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3720 const ASTContext &Context = CGM.getContext();
3721
3722 QualType ETy = Context.getBaseElementType(ATy);
3723 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3724 SmallVector<uint64_t, 4> TmpBits(Size);
3725 setUsedBits(CGM, ETy, 0, TmpBits);
3726
3727 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3728 auto Src = TmpBits.begin();
3729 auto Dst = Bits.begin() + Offset + I * Size;
3730 for (int J = 0; J < Size; ++J)
3731 *Dst++ |= *Src++;
3732 }
3733}
3734
3735// Set the bits in `Bits`, which correspond to the value representations of
3736// the type `QTy`.
3737static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3739 if (const auto *RTy = QTy->getAs<RecordType>())
3740 return setUsedBits(CGM, RTy, Offset, Bits);
3741
3742 ASTContext &Context = CGM.getContext();
3743 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3744 return setUsedBits(CGM, ATy, Offset, Bits);
3745
3746 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3747 if (Size <= 0)
3748 return;
3749
3750 std::fill_n(Bits.begin() + Offset, Size,
3751 (uint64_t(1) << Context.getCharWidth()) - 1);
3752}
3753
3755 int Pos, int Size, int CharWidth,
3756 bool BigEndian) {
3757 assert(Size > 0);
3758 uint64_t Mask = 0;
3759 if (BigEndian) {
3760 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3761 ++P)
3762 Mask = (Mask << CharWidth) | *P;
3763 } else {
3764 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3765 do
3766 Mask = (Mask << CharWidth) | *--P;
3767 while (P != End);
3768 }
3769 return Mask;
3770}
3771
3772// Emit code to clear the bits in a record, which aren't a part of any user
3773// declared member, when the record is a function return.
3774llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3775 llvm::IntegerType *ITy,
3776 QualType QTy) {
3777 assert(Src->getType() == ITy);
3778 assert(ITy->getScalarSizeInBits() <= 64);
3779
3780 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3781 int Size = DataLayout.getTypeStoreSize(ITy);
3782 SmallVector<uint64_t, 4> Bits(Size);
3783 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3784
3785 int CharWidth = CGM.getContext().getCharWidth();
3786 uint64_t Mask =
3787 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3788
3789 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3790}
3791
3792// Emit code to clear the bits in a record, which aren't a part of any user
3793// declared member, when the record is a function argument.
3794llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3795 llvm::ArrayType *ATy,
3796 QualType QTy) {
3797 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3798 int Size = DataLayout.getTypeStoreSize(ATy);
3799 SmallVector<uint64_t, 16> Bits(Size);
3800 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3801
3802 // Clear each element of the LLVM array.
3803 int CharWidth = CGM.getContext().getCharWidth();
3804 int CharsPerElt =
3805 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3806 int MaskIndex = 0;
3807 llvm::Value *R = llvm::PoisonValue::get(ATy);
3808 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3809 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3810 DataLayout.isBigEndian());
3811 MaskIndex += CharsPerElt;
3812 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3813 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3814 R = Builder.CreateInsertValue(R, T1, I);
3815 }
3816
3817 return R;
3818}
3819
3821 bool EmitRetDbgLoc,
3822 SourceLocation EndLoc) {
3823 if (FI.isNoReturn()) {
3824 // Noreturn functions don't return.
3825 EmitUnreachable(EndLoc);
3826 return;
3827 }
3828
3829 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3830 // Naked functions don't have epilogues.
3831 Builder.CreateUnreachable();
3832 return;
3833 }
3834
3835 // Functions with no result always return void.
3836 if (!ReturnValue.isValid()) {
3837 Builder.CreateRetVoid();
3838 return;
3839 }
3840
3841 llvm::DebugLoc RetDbgLoc;
3842 llvm::Value *RV = nullptr;
3843 QualType RetTy = FI.getReturnType();
3844 const ABIArgInfo &RetAI = FI.getReturnInfo();
3845
3846 switch (RetAI.getKind()) {
3848 // Aggregates get evaluated directly into the destination. Sometimes we
3849 // need to return the sret value in a register, though.
3850 assert(hasAggregateEvaluationKind(RetTy));
3851 if (RetAI.getInAllocaSRet()) {
3852 llvm::Function::arg_iterator EI = CurFn->arg_end();
3853 --EI;
3854 llvm::Value *ArgStruct = &*EI;
3855 llvm::Value *SRet = Builder.CreateStructGEP(
3856 FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
3857 llvm::Type *Ty =
3858 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3859 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3860 }
3861 break;
3862
3863 case ABIArgInfo::Indirect: {
3864 auto AI = CurFn->arg_begin();
3865 if (RetAI.isSRetAfterThis())
3866 ++AI;
3867 switch (getEvaluationKind(RetTy)) {
3868 case TEK_Complex: {
3869 ComplexPairTy RT =
3872 /*isInit*/ true);
3873 break;
3874 }
3875 case TEK_Aggregate:
3876 // Do nothing; aggregates get evaluated directly into the destination.
3877 break;
3878 case TEK_Scalar: {
3879 LValueBaseInfo BaseInfo;
3880 TBAAAccessInfo TBAAInfo;
3881 CharUnits Alignment =
3882 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
3883 Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
3884 LValue ArgVal =
3885 LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
3887 EmitLoadOfScalar(MakeAddrLValue(ReturnValue, RetTy), EndLoc), ArgVal,
3888 /*isInit*/ true);
3889 break;
3890 }
3891 }
3892 break;
3893 }
3894
3895 case ABIArgInfo::Extend:
3896 case ABIArgInfo::Direct:
3897 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3898 RetAI.getDirectOffset() == 0) {
3899 // The internal return value temp always will have pointer-to-return-type
3900 // type, just do a load.
3901
3902 // If there is a dominating store to ReturnValue, we can elide
3903 // the load, zap the store, and usually zap the alloca.
3904 if (llvm::StoreInst *SI =
3906 // Reuse the debug location from the store unless there is
3907 // cleanup code to be emitted between the store and return
3908 // instruction.
3909 if (EmitRetDbgLoc && !AutoreleaseResult)
3910 RetDbgLoc = SI->getDebugLoc();
3911 // Get the stored value and nuke the now-dead store.
3912 RV = SI->getValueOperand();
3913 SI->eraseFromParent();
3914
3915 // Otherwise, we have to do a simple load.
3916 } else {
3918 }
3919 } else {
3920 // If the value is offset in memory, apply the offset now.
3921 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3922
3923 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3924 }
3925
3926 // In ARC, end functions that return a retainable type with a call
3927 // to objc_autoreleaseReturnValue.
3928 if (AutoreleaseResult) {
3929#ifndef NDEBUG
3930 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3931 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3932 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3933 // CurCodeDecl or BlockInfo.
3934 QualType RT;
3935
3936 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3937 RT = FD->getReturnType();
3938 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3939 RT = MD->getReturnType();
3940 else if (isa<BlockDecl>(CurCodeDecl))
3942 else
3943 llvm_unreachable("Unexpected function/method type");
3944
3945 assert(getLangOpts().ObjCAutoRefCount &&
3946 !FI.isReturnsRetained() &&
3947 RT->isObjCRetainableType());
3948#endif
3949 RV = emitAutoreleaseOfResult(*this, RV);
3950 }
3951
3952 break;
3953
3954 case ABIArgInfo::Ignore:
3955 break;
3956
3958 auto coercionType = RetAI.getCoerceAndExpandType();
3959 auto unpaddedCoercionType = RetAI.getUnpaddedCoerceAndExpandType();
3960 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
3961
3962 // Load all of the coerced elements out into results.
3964 Address addr = ReturnValue.withElementType(coercionType);
3965 unsigned unpaddedIndex = 0;
3966 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3967 auto coercedEltType = coercionType->getElementType(i);
3968 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3969 continue;
3970
3971 auto eltAddr = Builder.CreateStructGEP(addr, i);
3972 llvm::Value *elt = CreateCoercedLoad(
3973 eltAddr,
3974 unpaddedStruct ? unpaddedStruct->getElementType(unpaddedIndex++)
3975 : unpaddedCoercionType,
3976 *this);
3977 results.push_back(elt);
3978 }
3979
3980 // If we have one result, it's the single direct result type.
3981 if (results.size() == 1) {
3982 RV = results[0];
3983
3984 // Otherwise, we need to make a first-class aggregate.
3985 } else {
3986 // Construct a return type that lacks padding elements.
3987 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3988
3989 RV = llvm::PoisonValue::get(returnType);
3990 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3991 RV = Builder.CreateInsertValue(RV, results[i], i);
3992 }
3993 }
3994 break;
3995 }
3996 case ABIArgInfo::Expand:
3998 llvm_unreachable("Invalid ABI kind for return argument");
3999 }
4000
4001 llvm::Instruction *Ret;
4002 if (RV) {
4003 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
4004 // For certain return types, clear padding bits, as they may reveal
4005 // sensitive information.
4006 // Small struct/union types are passed as integers.
4007 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
4008 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
4009 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
4010 }
4012 Ret = Builder.CreateRet(RV);
4013 } else {
4014 Ret = Builder.CreateRetVoid();
4015 }
4016
4017 if (RetDbgLoc)
4018 Ret->setDebugLoc(std::move(RetDbgLoc));
4019}
4020
4021void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
4022 // A current decl may not be available when emitting vtable thunks.
4023 if (!CurCodeDecl)
4024 return;
4025
4026 // If the return block isn't reachable, neither is this check, so don't emit
4027 // it.
4028 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
4029 return;
4030
4031 ReturnsNonNullAttr *RetNNAttr = nullptr;
4032 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4033 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4034
4035 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4036 return;
4037
4038 // Prefer the returns_nonnull attribute if it's present.
4039 SourceLocation AttrLoc;
4041 SanitizerHandler Handler;
4042 if (RetNNAttr) {
4043 assert(!requiresReturnValueNullabilityCheck() &&
4044 "Cannot check nullability and the nonnull attribute");
4045 AttrLoc = RetNNAttr->getLocation();
4046 CheckKind = SanitizerKind::SO_ReturnsNonnullAttribute;
4047 Handler = SanitizerHandler::NonnullReturn;
4048 } else {
4049 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4050 if (auto *TSI = DD->getTypeSourceInfo())
4051 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4052 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4053 CheckKind = SanitizerKind::SO_NullabilityReturn;
4054 Handler = SanitizerHandler::NullabilityReturn;
4055 }
4056
4057 SanitizerScope SanScope(this);
4058
4059 // Make sure the "return" source location is valid. If we're checking a
4060 // nullability annotation, make sure the preconditions for the check are met.
4061 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4062 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4063 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4064 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4065 if (requiresReturnValueNullabilityCheck())
4066 CanNullCheck =
4067 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4068 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4069 EmitBlock(Check);
4070
4071 // Now do the null check.
4072 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4073 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4074 llvm::Value *DynamicData[] = {SLocPtr};
4075 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4076
4077 EmitBlock(NoCheck);
4078
4079#ifndef NDEBUG
4080 // The return location should not be used after the check has been emitted.
4081 ReturnLocation = Address::invalid();
4082#endif
4083}
4084
4086 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4087 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4088}
4089
4091 QualType Ty) {
4092 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4093 // placeholders.
4094 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4095 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4096 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4097
4098 // FIXME: When we generate this IR in one pass, we shouldn't need
4099 // this win32-specific alignment hack.
4101 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4102
4103 return AggValueSlot::forAddr(Address(Placeholder, IRTy, Align),
4104 Ty.getQualifiers(),
4109}
4110
4112 const VarDecl *param,
4113 SourceLocation loc) {
4114 // StartFunction converted the ABI-lowered parameter(s) into a
4115 // local alloca. We need to turn that into an r-value suitable
4116 // for EmitCall.
4117 Address local = GetAddrOfLocalVar(param);
4118
4119 QualType type = param->getType();
4120
4121 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4122 // but the argument needs to be the original pointer.
4123 if (type->isReferenceType()) {
4124 args.add(RValue::get(Builder.CreateLoad(local)), type);
4125
4126 // In ARC, move out of consumed arguments so that the release cleanup
4127 // entered by StartFunction doesn't cause an over-release. This isn't
4128 // optimal -O0 code generation, but it should get cleaned up when
4129 // optimization is enabled. This also assumes that delegate calls are
4130 // performed exactly once for a set of arguments, but that should be safe.
4131 } else if (getLangOpts().ObjCAutoRefCount &&
4132 param->hasAttr<NSConsumedAttr>() &&
4133 type->isObjCRetainableType()) {
4134 llvm::Value *ptr = Builder.CreateLoad(local);
4135 auto null =
4136 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4137 Builder.CreateStore(null, local);
4138 args.add(RValue::get(ptr), type);
4139
4140 // For the most part, we just need to load the alloca, except that
4141 // aggregate r-values are actually pointers to temporaries.
4142 } else {
4143 args.add(convertTempToRValue(local, type, loc), type);
4144 }
4145
4146 // Deactivate the cleanup for the callee-destructed param that was pushed.
4147 if (type->isRecordType() && !CurFuncIsThunk &&
4149 param->needsDestruction(getContext())) {
4151 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4152 assert(cleanup.isValid() &&
4153 "cleanup for callee-destructed param not recorded");
4154 // This unreachable is a temporary marker which will be removed later.
4155 llvm::Instruction *isActive = Builder.CreateUnreachable();
4156 args.addArgCleanupDeactivation(cleanup, isActive);
4157 }
4158}
4159
4160static bool isProvablyNull(llvm::Value *addr) {
4161 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4162}
4163
4165 return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4166}
4167
4168/// Emit the actual writing-back of a writeback.
4170 const CallArgList::Writeback &writeback) {
4171 const LValue &srcLV = writeback.Source;
4172 Address srcAddr = srcLV.getAddress();
4173 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4174 "shouldn't have writeback for provably null argument");
4175
4176 if (writeback.WritebackExpr) {
4177 CGF.EmitIgnoredExpr(writeback.WritebackExpr);
4178
4179 if (writeback.LifetimeSz)
4180 CGF.EmitLifetimeEnd(writeback.LifetimeSz,
4181 writeback.Temporary.getBasePointer());
4182 return;
4183 }
4184
4185 llvm::BasicBlock *contBB = nullptr;
4186
4187 // If the argument wasn't provably non-null, we need to null check
4188 // before doing the store.
4189 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4190
4191 if (!provablyNonNull) {
4192 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4193 contBB = CGF.createBasicBlock("icr.done");
4194
4195 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4196 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4197 CGF.EmitBlock(writebackBB);
4198 }
4199
4200 // Load the value to writeback.
4201 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4202
4203 // Cast it back, in case we're writing an id to a Foo* or something.
4204 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4205 "icr.writeback-cast");
4206
4207 // Perform the writeback.
4208
4209 // If we have a "to use" value, it's something we need to emit a use
4210 // of. This has to be carefully threaded in: if it's done after the
4211 // release it's potentially undefined behavior (and the optimizer
4212 // will ignore it), and if it happens before the retain then the
4213 // optimizer could move the release there.
4214 if (writeback.ToUse) {
4215 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4216
4217 // Retain the new value. No need to block-copy here: the block's
4218 // being passed up the stack.
4219 value = CGF.EmitARCRetainNonBlock(value);
4220
4221 // Emit the intrinsic use here.
4222 CGF.EmitARCIntrinsicUse(writeback.ToUse);
4223
4224 // Load the old value (primitively).
4225 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4226
4227 // Put the new value in place (primitively).
4228 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4229
4230 // Release the old value.
4231 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4232
4233 // Otherwise, we can just do a normal lvalue store.
4234 } else {
4235 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4236 }
4237
4238 // Jump to the continuation block.
4239 if (!provablyNonNull)
4240 CGF.EmitBlock(contBB);
4241}
4242
4244 const CallArgList &CallArgs) {
4246 CallArgs.getCleanupsToDeactivate();
4247 // Iterate in reverse to increase the likelihood of popping the cleanup.
4248 for (const auto &I : llvm::reverse(Cleanups)) {
4249 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4250 I.IsActiveIP->eraseFromParent();
4251 }
4252}
4253
4254static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4255 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4256 if (uop->getOpcode() == UO_AddrOf)
4257 return uop->getSubExpr();
4258 return nullptr;
4259}
4260
4261/// Emit an argument that's being passed call-by-writeback. That is,
4262/// we are passing the address of an __autoreleased temporary; it
4263/// might be copy-initialized with the current value of the given
4264/// address, but it will definitely be copied out of after the call.
4266 const ObjCIndirectCopyRestoreExpr *CRE) {
4267 LValue srcLV;
4268
4269 // Make an optimistic effort to emit the address as an l-value.
4270 // This can fail if the argument expression is more complicated.
4271 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4272 srcLV = CGF.EmitLValue(lvExpr);
4273
4274 // Otherwise, just emit it as a scalar.
4275 } else {
4276 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4277
4278 QualType srcAddrType =
4280 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4281 }
4282 Address srcAddr = srcLV.getAddress();
4283
4284 // The dest and src types don't necessarily match in LLVM terms
4285 // because of the crazy ObjC compatibility rules.
4286
4287 llvm::PointerType *destType =
4288 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
4289 llvm::Type *destElemType =
4291
4292 // If the address is a constant null, just pass the appropriate null.
4293 if (isProvablyNull(srcAddr.getBasePointer())) {
4294 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4295 CRE->getType());
4296 return;
4297 }
4298
4299 // Create the temporary.
4300 Address temp =
4301 CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4302 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4303 // and that cleanup will be conditional if we can't prove that the l-value
4304 // isn't null, so we need to register a dominating point so that the cleanups
4305 // system will make valid IR.
4306 CodeGenFunction::ConditionalEvaluation condEval(CGF);
4307
4308 // Zero-initialize it if we're not doing a copy-initialization.
4309 bool shouldCopy = CRE->shouldCopy();
4310 if (!shouldCopy) {
4311 llvm::Value *null =
4312 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4313 CGF.Builder.CreateStore(null, temp);
4314 }
4315
4316 llvm::BasicBlock *contBB = nullptr;
4317 llvm::BasicBlock *originBB = nullptr;
4318
4319 // If the address is *not* known to be non-null, we need to switch.
4320 llvm::Value *finalArgument;
4321
4322 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4323
4324 if (provablyNonNull) {
4325 finalArgument = temp.emitRawPointer(CGF);
4326 } else {
4327 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4328
4329 finalArgument = CGF.Builder.CreateSelect(
4330 isNull, llvm::ConstantPointerNull::get(destType),
4331 temp.emitRawPointer(CGF), "icr.argument");
4332
4333 // If we need to copy, then the load has to be conditional, which
4334 // means we need control flow.
4335 if (shouldCopy) {
4336 originBB = CGF.Builder.GetInsertBlock();
4337 contBB = CGF.createBasicBlock("icr.cont");
4338 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4339 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4340 CGF.EmitBlock(copyBB);
4341 condEval.begin(CGF);
4342 }
4343 }
4344
4345 llvm::Value *valueToUse = nullptr;
4346
4347 // Perform a copy if necessary.
4348 if (shouldCopy) {
4349 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4350 assert(srcRV.isScalar());
4351
4352 llvm::Value *src = srcRV.getScalarVal();
4353 src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4354
4355 // Use an ordinary store, not a store-to-lvalue.
4356 CGF.Builder.CreateStore(src, temp);
4357
4358 // If optimization is enabled, and the value was held in a
4359 // __strong variable, we need to tell the optimizer that this
4360 // value has to stay alive until we're doing the store back.
4361 // This is because the temporary is effectively unretained,
4362 // and so otherwise we can violate the high-level semantics.
4363 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4365 valueToUse = src;
4366 }
4367 }
4368
4369 // Finish the control flow if we needed it.
4370 if (shouldCopy && !provablyNonNull) {
4371 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4372 CGF.EmitBlock(contBB);
4373
4374 // Make a phi for the value to intrinsically use.
4375 if (valueToUse) {
4376 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
4377 "icr.to-use");
4378 phiToUse->addIncoming(valueToUse, copyBB);
4379 phiToUse->addIncoming(llvm::PoisonValue::get(valueToUse->getType()),
4380 originBB);
4381 valueToUse = phiToUse;
4382 }
4383
4384 condEval.end(CGF);
4385 }
4386
4387 args.addWriteback(srcLV, temp, valueToUse);
4388 args.add(RValue::get(finalArgument), CRE->getType());
4389}
4390
4392 assert(!StackBase);
4393
4394 // Save the stack.
4395 StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4396}
4397
4399 if (StackBase) {
4400 // Restore the stack after the call.
4401 CGF.Builder.CreateStackRestore(StackBase);
4402 }
4403}
4404
4406 SourceLocation ArgLoc,
4407 AbstractCallee AC,
4408 unsigned ParmNum) {
4409 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4410 SanOpts.has(SanitizerKind::NullabilityArg)))
4411 return;
4412
4413 // The param decl may be missing in a variadic function.
4414 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4415 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4416
4417 // Prefer the nonnull attribute if it's present.
4418 const NonNullAttr *NNAttr = nullptr;
4419 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4420 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4421
4422 bool CanCheckNullability = false;
4423 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4424 !PVD->getType()->isRecordType()) {
4425 auto Nullability = PVD->getType()->getNullability();
4426 CanCheckNullability = Nullability &&
4427 *Nullability == NullabilityKind::NonNull &&
4428 PVD->getTypeSourceInfo();
4429 }
4430
4431 if (!NNAttr && !CanCheckNullability)
4432 return;
4433
4434 SourceLocation AttrLoc;
4436 SanitizerHandler Handler;
4437 if (NNAttr) {
4438 AttrLoc = NNAttr->getLocation();
4439 CheckKind = SanitizerKind::SO_NonnullAttribute;
4440 Handler = SanitizerHandler::NonnullArg;
4441 } else {
4442 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4443 CheckKind = SanitizerKind::SO_NullabilityArg;
4444 Handler = SanitizerHandler::NullabilityArg;
4445 }
4446
4447 SanitizerScope SanScope(this);
4448 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4449 llvm::Constant *StaticData[] = {
4451 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4452 };
4453 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, {});
4454}
4455
4457 SourceLocation ArgLoc,
4458 AbstractCallee AC, unsigned ParmNum) {
4459 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4460 SanOpts.has(SanitizerKind::NullabilityArg)))
4461 return;
4462
4463 EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4464}
4465
4466// Check if the call is going to use the inalloca convention. This needs to
4467// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4468// later, so we can't check it directly.
4469static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4470 ArrayRef<QualType> ArgTypes) {
4471 // The Swift calling conventions don't go through the target-specific
4472 // argument classification, they never use inalloca.
4473 // TODO: Consider limiting inalloca use to only calling conventions supported
4474 // by MSVC.
4475 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4476 return false;
4477 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4478 return false;
4479 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4480 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4481 });
4482}
4483
4484#ifndef NDEBUG
4485// Determine whether the given argument is an Objective-C method
4486// that may have type parameters in its signature.
4487static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4488 const DeclContext *dc = method->getDeclContext();
4489 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4490 return classDecl->getTypeParamListAsWritten();
4491 }
4492
4493 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4494 return catDecl->getTypeParamList();
4495 }
4496
4497 return false;
4498}
4499#endif
4500
4501/// EmitCallArgs - Emit call arguments for a function.
4503 CallArgList &Args, PrototypeWrapper Prototype,
4504 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4505 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4507
4508 assert((ParamsToSkip == 0 || Prototype.P) &&
4509 "Can't skip parameters if type info is not provided");
4510
4511 // This variable only captures *explicitly* written conventions, not those
4512 // applied by default via command line flags or target defaults, such as
4513 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4514 // require knowing if this is a C++ instance method or being able to see
4515 // unprototyped FunctionTypes.
4516 CallingConv ExplicitCC = CC_C;
4517
4518 // First, if a prototype was provided, use those argument types.
4519 bool IsVariadic = false;
4520 if (Prototype.P) {
4521 const auto *MD = dyn_cast<const ObjCMethodDecl *>(Prototype.P);
4522 if (MD) {
4523 IsVariadic = MD->isVariadic();
4524 ExplicitCC = getCallingConventionForDecl(
4525 MD, CGM.getTarget().getTriple().isOSWindows());
4526 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4527 MD->param_type_end());
4528 } else {
4529 const auto *FPT = cast<const FunctionProtoType *>(Prototype.P);
4530 IsVariadic = FPT->isVariadic();
4531 ExplicitCC = FPT->getExtInfo().getCC();
4532 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4533 FPT->param_type_end());
4534 }
4535
4536#ifndef NDEBUG
4537 // Check that the prototyped types match the argument expression types.
4538 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4539 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4540 for (QualType Ty : ArgTypes) {
4541 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4542 assert(
4543 (isGenericMethod || Ty->isVariablyModifiedType() ||
4544 Ty.getNonReferenceType()->isObjCRetainableType() ||
4545 getContext()
4546 .getCanonicalType(Ty.getNonReferenceType())
4547 .getTypePtr() ==
4548 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4549 "type mismatch in call argument!");
4550 ++Arg;
4551 }
4552
4553 // Either we've emitted all the call args, or we have a call to variadic
4554 // function.
4555 assert((Arg == ArgRange.end() || IsVariadic) &&
4556 "Extra arguments in non-variadic function!");
4557#endif
4558 }
4559
4560 // If we still have any arguments, emit them using the type of the argument.
4561 for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4562 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4563 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4564
4565 // We must evaluate arguments from right to left in the MS C++ ABI,
4566 // because arguments are destroyed left to right in the callee. As a special
4567 // case, there are certain language constructs that require left-to-right
4568 // evaluation, and in those cases we consider the evaluation order requirement
4569 // to trump the "destruction order is reverse construction order" guarantee.
4570 bool LeftToRight =
4574
4575 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4576 RValue EmittedArg) {
4577 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4578 return;
4579 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4580 if (PS == nullptr)
4581 return;
4582
4583 const auto &Context = getContext();
4584 auto SizeTy = Context.getSizeType();
4585 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4586 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4587 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4588 EmittedArg.getScalarVal(),
4589 PS->isDynamic());
4590 Args.add(RValue::get(V), SizeTy);
4591 // If we're emitting args in reverse, be sure to do so with
4592 // pass_object_size, as well.
4593 if (!LeftToRight)
4594 std::swap(Args.back(), *(&Args.back() - 1));
4595 };
4596
4597 // Insert a stack save if we're going to need any inalloca args.
4598 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4599 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4600 "inalloca only supported on x86");
4601 Args.allocateArgumentMemory(*this);
4602 }
4603
4604 // Evaluate each argument in the appropriate order.
4605 size_t CallArgsStart = Args.size();
4606 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4607 unsigned Idx = LeftToRight ? I : E - I - 1;
4608 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4609 unsigned InitialArgSize = Args.size();
4610 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4611 // the argument and parameter match or the objc method is parameterized.
4612 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4613 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4614 ArgTypes[Idx]) ||
4615 (isa<ObjCMethodDecl>(AC.getDecl()) &&
4616 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4617 "Argument and parameter types don't match");
4618 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4619 // In particular, we depend on it being the last arg in Args, and the
4620 // objectsize bits depend on there only being one arg if !LeftToRight.
4621 assert(InitialArgSize + 1 == Args.size() &&
4622 "The code below depends on only adding one arg per EmitCallArg");
4623 (void)InitialArgSize;
4624 // Since pointer argument are never emitted as LValue, it is safe to emit
4625 // non-null argument check for r-value only.
4626 if (!Args.back().hasLValue()) {
4627 RValue RVArg = Args.back().getKnownRValue();
4628 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4629 ParamsToSkip + Idx);
4630 // @llvm.objectsize should never have side-effects and shouldn't need
4631 // destruction/cleanups, so we can safely "emit" it after its arg,
4632 // regardless of right-to-leftness
4633 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4634 }
4635 }
4636
4637 if (!LeftToRight) {
4638 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4639 // IR function.
4640 std::reverse(Args.begin() + CallArgsStart, Args.end());
4641
4642 // Reverse the writebacks to match the MSVC ABI.
4643 Args.reverseWritebacks();
4644 }
4645}
4646
4647namespace {
4648
4649struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4650 DestroyUnpassedArg(Address Addr, QualType Ty)
4651 : Addr(Addr), Ty(Ty) {}
4652
4653 Address Addr;
4654 QualType Ty;
4655
4656 void Emit(CodeGenFunction &CGF, Flags flags) override {
4658 if (DtorKind == QualType::DK_cxx_destructor) {
4659 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4660 assert(!Dtor->isTrivial());
4661 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4662 /*Delegating=*/false, Addr, Ty);
4663 } else {
4664 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4665 }
4666 }
4667};
4668
4669struct DisableDebugLocationUpdates {
4670 CodeGenFunction &CGF;
4671 bool disabledDebugInfo;
4672 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4673 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4674 CGF.disableDebugInfo();
4675 }
4676 ~DisableDebugLocationUpdates() {
4677 if (disabledDebugInfo)
4678 CGF.enableDebugInfo();
4679 }
4680};
4681
4682} // end anonymous namespace
4683
4685 if (!HasLV)
4686 return RV;
4689 LV.isVolatile());
4690 IsUsed = true;
4691 return RValue::getAggregate(Copy.getAddress());
4692}
4693
4695 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4696 if (!HasLV && RV.isScalar())
4697 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4698 else if (!HasLV && RV.isComplex())
4699 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4700 else {
4701 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4702 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4703 // We assume that call args are never copied into subobjects.
4705 HasLV ? LV.isVolatileQualified()
4707 }
4708 IsUsed = true;
4709}
4710
4712 for (const auto &I : args.writebacks())
4713 emitWriteback(*this, I);
4714}
4715
4717 QualType type) {
4718 DisableDebugLocationUpdates Dis(*this, E);
4719 if (const ObjCIndirectCopyRestoreExpr *CRE
4720 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4721 assert(getLangOpts().ObjCAutoRefCount);
4722 return emitWritebackArg(*this, args, CRE);
4723 }
4724
4725 // Add writeback for HLSLOutParamExpr.
4726 // Needs to be before the assert below because HLSLOutArgExpr is an LValue
4727 // and is not a reference.
4728 if (const HLSLOutArgExpr *OE = dyn_cast<HLSLOutArgExpr>(E)) {
4729 EmitHLSLOutArgExpr(OE, args, type);
4730 return;
4731 }
4732
4733 assert(type->isReferenceType() == E->isGLValue() &&
4734 "reference binding to unmaterialized r-value!");
4735
4736 if (E->isGLValue()) {
4737 assert(E->getObjectKind() == OK_Ordinary);
4738 return args.add(EmitReferenceBindingToExpr(E), type);
4739 }
4740
4741 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4742
4743 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4744 // However, we still have to push an EH-only cleanup in case we unwind before
4745 // we make it to the call.
4746 if (type->isRecordType() &&
4748 // If we're using inalloca, use the argument memory. Otherwise, use a
4749 // temporary.
4750 AggValueSlot Slot = args.isUsingInAlloca()
4751 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
4752
4753 bool DestroyedInCallee = true, NeedsCleanup = true;
4754 if (const auto *RD = type->getAsCXXRecordDecl())
4755 DestroyedInCallee = RD->hasNonTrivialDestructor();
4756 else
4757 NeedsCleanup = type.isDestructedType();
4758
4759 if (DestroyedInCallee)
4761
4762 EmitAggExpr(E, Slot);
4763 RValue RV = Slot.asRValue();
4764 args.add(RV, type);
4765
4766 if (DestroyedInCallee && NeedsCleanup) {
4767 // Create a no-op GEP between the placeholder and the cleanup so we can
4768 // RAUW it successfully. It also serves as a marker of the first
4769 // instruction where the cleanup is active.
4770 pushFullExprCleanup<DestroyUnpassedArg>(NormalAndEHCleanup,
4771 Slot.getAddress(), type);
4772 // This unreachable is a temporary marker which will be removed later.
4773 llvm::Instruction *IsActive =
4774 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4776 }
4777 return;
4778 }
4779
4780 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4781 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4782 !type->isArrayParameterType()) {
4783 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4784 assert(L.isSimple());
4785 args.addUncopiedAggregate(L, type);
4786 return;
4787 }
4788
4789 args.add(EmitAnyExprToTemp(E), type);
4790}
4791
4792QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4793 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4794 // implicitly widens null pointer constants that are arguments to varargs
4795 // functions to pointer-sized ints.
4796 if (!getTarget().getTriple().isOSWindows())
4797 return Arg->getType();
4798
4799 if (Arg->getType()->isIntegerType() &&
4800 getContext().getTypeSize(Arg->getType()) <
4801 getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4804 return getContext().getIntPtrType();
4805 }
4806
4807 return Arg->getType();
4808}
4809
4810// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4811// optimizer it can aggressively ignore unwind edges.
4812void
4813CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4814 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4815 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4816 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4818}
4819
4820/// Emits a call to the given no-arguments nounwind runtime function.
4821llvm::CallInst *
4822CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4823 const llvm::Twine &name) {
4824 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
4825}
4826
4827/// Emits a call to the given nounwind runtime function.
4828llvm::CallInst *
4829CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4830 ArrayRef<Address> args,
4831 const llvm::Twine &name) {
4833 for (auto arg : args)
4834 values.push_back(arg.emitRawPointer(*this));
4835 return EmitNounwindRuntimeCall(callee, values, name);
4836}
4837
4838llvm::CallInst *
4839CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4841 const llvm::Twine &name) {
4842 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4843 call->setDoesNotThrow();
4844 return call;
4845}
4846
4847/// Emits a simple call (never an invoke) to the given no-arguments
4848/// runtime function.
4849llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4850 const llvm::Twine &name) {
4851 return EmitRuntimeCall(callee, {}, name);
4852}
4853
4854// Calls which may throw must have operand bundles indicating which funclet
4855// they are nested within.
4857CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4858 // There is no need for a funclet operand bundle if we aren't inside a
4859 // funclet.
4860 if (!CurrentFuncletPad)
4862
4863 // Skip intrinsics which cannot throw (as long as they don't lower into
4864 // regular function calls in the course of IR transformations).
4865 if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
4866 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
4867 auto IID = CalleeFn->getIntrinsicID();
4868 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
4870 }
4871 }
4872
4874 BundleList.emplace_back("funclet", CurrentFuncletPad);
4875 return BundleList;
4876}
4877
4878/// Emits a simple call (never an invoke) to the given runtime function.
4879llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4881 const llvm::Twine &name) {
4882 llvm::CallInst *call = Builder.CreateCall(
4883 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4884 call->setCallingConv(getRuntimeCC());
4885
4886 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
4887 return cast<llvm::CallInst>(addConvergenceControlToken(call));
4888 return call;
4889}
4890
4891/// Emits a call or invoke to the given noreturn runtime function.
4893 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4895 getBundlesForFunclet(callee.getCallee());
4896
4897 if (getInvokeDest()) {
4898 llvm::InvokeInst *invoke =
4899 Builder.CreateInvoke(callee,
4901 getInvokeDest(),
4902 args,
4903 BundleList);
4904 invoke->setDoesNotReturn();
4905 invoke->setCallingConv(getRuntimeCC());
4906 } else {
4907 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4908 call->setDoesNotReturn();
4909 call->setCallingConv(getRuntimeCC());
4910 Builder.CreateUnreachable();
4911 }
4912}
4913
4914/// Emits a call or invoke instruction to the given nullary runtime function.
4915llvm::CallBase *
4916CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4917 const Twine &name) {
4918 return EmitRuntimeCallOrInvoke(callee, {}, name);
4919}
4920
4921/// Emits a call or invoke instruction to the given runtime function.
4922llvm::CallBase *
4923CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4925 const Twine &name) {
4926 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4927 call->setCallingConv(getRuntimeCC());
4928 return call;
4929}
4930
4931/// Emits a call or invoke instruction to the given function, depending
4932/// on the current state of the EH stack.
4933llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4935 const Twine &Name) {
4936 llvm::BasicBlock *InvokeDest = getInvokeDest();
4938 getBundlesForFunclet(Callee.getCallee());
4939
4940 llvm::CallBase *Inst;
4941 if (!InvokeDest)
4942 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4943 else {
4944 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4945 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4946 Name);
4947 EmitBlock(ContBB);
4948 }
4949
4950 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4951 // optimizer it can aggressively ignore unwind edges.
4952 if (CGM.getLangOpts().ObjCAutoRefCount)
4953 AddObjCARCExceptionMetadata(Inst);
4954
4955 return Inst;
4956}
4957
4958void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4959 llvm::Value *New) {
4960 DeferredReplacements.push_back(
4961 std::make_pair(llvm::WeakTrackingVH(Old), New));
4962}
4963
4964namespace {
4965
4966/// Specify given \p NewAlign as the alignment of return value attribute. If
4967/// such attribute already exists, re-set it to the maximal one of two options.
4968[[nodiscard]] llvm::AttributeList
4969maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4970 const llvm::AttributeList &Attrs,
4971 llvm::Align NewAlign) {
4972 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4973 if (CurAlign >= NewAlign)
4974 return Attrs;
4975 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4976 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
4977 .addRetAttribute(Ctx, AlignAttr);
4978}
4979
4980template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4981protected:
4982 CodeGenFunction &CGF;
4983
4984 /// We do nothing if this is, or becomes, nullptr.
4985 const AlignedAttrTy *AA = nullptr;
4986
4987 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4988 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4989
4990 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4991 : CGF(CGF_) {
4992 if (!FuncDecl)
4993 return;
4994 AA = FuncDecl->getAttr<AlignedAttrTy>();
4995 }
4996
4997public:
4998 /// If we can, materialize the alignment as an attribute on return value.
4999 [[nodiscard]] llvm::AttributeList
5000 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
5001 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
5002 return Attrs;
5003 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
5004 if (!AlignmentCI)
5005 return Attrs;
5006 // We may legitimately have non-power-of-2 alignment here.
5007 // If so, this is UB land, emit it via `@llvm.assume` instead.
5008 if (!AlignmentCI->getValue().isPowerOf2())
5009 return Attrs;
5010 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
5011 CGF.getLLVMContext(), Attrs,
5012 llvm::Align(
5013 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
5014 AA = nullptr; // We're done. Disallow doing anything else.
5015 return NewAttrs;
5016 }
5017
5018 /// Emit alignment assumption.
5019 /// This is a general fallback that we take if either there is an offset,
5020 /// or the alignment is variable or we are sanitizing for alignment.
5021 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
5022 if (!AA)
5023 return;
5024 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
5025 AA->getLocation(), Alignment, OffsetCI);
5026 AA = nullptr; // We're done. Disallow doing anything else.
5027 }
5028};
5029
5030/// Helper data structure to emit `AssumeAlignedAttr`.
5031class AssumeAlignedAttrEmitter final
5032 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
5033public:
5034 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5035 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5036 if (!AA)
5037 return;
5038 // It is guaranteed that the alignment/offset are constants.
5039 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
5040 if (Expr *Offset = AA->getOffset()) {
5041 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
5042 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
5043 OffsetCI = nullptr;
5044 }
5045 }
5046};
5047
5048/// Helper data structure to emit `AllocAlignAttr`.
5049class AllocAlignAttrEmitter final
5050 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5051public:
5052 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5053 const CallArgList &CallArgs)
5054 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5055 if (!AA)
5056 return;
5057 // Alignment may or may not be a constant, and that is okay.
5058 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5059 .getRValue(CGF)
5060 .getScalarVal();
5061 }
5062};
5063
5064} // namespace
5065
5066static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5067 if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5068 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5069 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5070 return getMaxVectorWidth(AT->getElementType());
5071
5072 unsigned MaxVectorWidth = 0;
5073 if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5074 for (auto *I : ST->elements())
5075 MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5076 return MaxVectorWidth;
5077}
5078
5080 const CGCallee &Callee,
5081 ReturnValueSlot ReturnValue,
5082 const CallArgList &CallArgs,
5083 llvm::CallBase **callOrInvoke, bool IsMustTail,
5085 bool IsVirtualFunctionPointerThunk) {
5086 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5087
5088 assert(Callee.isOrdinary() || Callee.isVirtual());
5089
5090 // Handle struct-return functions by passing a pointer to the
5091 // location that we would like to return into.
5092 QualType RetTy = CallInfo.getReturnType();
5093 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5094
5095 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5096
5097 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5098 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5099 // We can only guarantee that a function is called from the correct
5100 // context/function based on the appropriate target attributes,
5101 // so only check in the case where we have both always_inline and target
5102 // since otherwise we could be making a conditional call after a check for
5103 // the proper cpu features (and it won't cause code generation issues due to
5104 // function based code generation).
5105 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5106 (TargetDecl->hasAttr<TargetAttr>() ||
5107 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>())))
5109 }
5110
5111 // Some architectures (such as x86-64) have the ABI changed based on
5112 // attribute-target/features. Give them a chance to diagnose.
5113 const FunctionDecl *CallerDecl = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
5114 const FunctionDecl *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl);
5116 CalleeDecl, CallArgs, RetTy);
5117
5118 // 1. Set up the arguments.
5119
5120 // If we're using inalloca, insert the allocation after the stack save.
5121 // FIXME: Do this earlier rather than hacking it in here!
5122 RawAddress ArgMemory = RawAddress::invalid();
5123 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5124 const llvm::DataLayout &DL = CGM.getDataLayout();
5125 llvm::Instruction *IP = CallArgs.getStackBase();
5126 llvm::AllocaInst *AI;
5127 if (IP) {
5128 IP = IP->getNextNode();
5129 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), "argmem",
5130 IP->getIterator());
5131 } else {
5132 AI = CreateTempAlloca(ArgStruct, "argmem");
5133 }
5134 auto Align = CallInfo.getArgStructAlignment();
5135 AI->setAlignment(Align.getAsAlign());
5136 AI->setUsedWithInAlloca(true);
5137 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5138 ArgMemory = RawAddress(AI, ArgStruct, Align);
5139 }
5140
5141 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5142 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5143
5144 // If the call returns a temporary with struct return, create a temporary
5145 // alloca to hold the result, unless one is given to us.
5146 Address SRetPtr = Address::invalid();
5147 RawAddress SRetAlloca = RawAddress::invalid();
5148 llvm::Value *UnusedReturnSizePtr = nullptr;
5149 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5150 // For virtual function pointer thunks and musttail calls, we must always
5151 // forward an incoming SRet pointer to the callee, because a local alloca
5152 // would be de-allocated before the call. These cases both guarantee that
5153 // there will be an incoming SRet argument of the correct type.
5154 if ((IsVirtualFunctionPointerThunk || IsMustTail) && RetAI.isIndirect()) {
5155 SRetPtr = makeNaturalAddressForPointer(CurFn->arg_begin() +
5156 IRFunctionArgs.getSRetArgNo(),
5157 RetTy, CharUnits::fromQuantity(1));
5158 } else if (!ReturnValue.isNull()) {
5159 SRetPtr = ReturnValue.getAddress();
5160 } else {
5161 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
5162 if (HaveInsertPoint() && ReturnValue.isUnused()) {
5163 llvm::TypeSize size =
5164 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
5165 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
5166 }
5167 }
5168 if (IRFunctionArgs.hasSRetArg()) {
5169 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5170 getAsNaturalPointerTo(SRetPtr, RetTy);
5171 } else if (RetAI.isInAlloca()) {
5172 Address Addr =
5173 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
5174 Builder.CreateStore(getAsNaturalPointerTo(SRetPtr, RetTy), Addr);
5175 }
5176 }
5177
5178 RawAddress swiftErrorTemp = RawAddress::invalid();
5179 Address swiftErrorArg = Address::invalid();
5180
5181 // When passing arguments using temporary allocas, we need to add the
5182 // appropriate lifetime markers. This vector keeps track of all the lifetime
5183 // markers that need to be ended right after the call.
5184 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5185
5186 // Translate all of the arguments as necessary to match the IR lowering.
5187 assert(CallInfo.arg_size() == CallArgs.size() &&
5188 "Mismatch between function signature & arguments.");
5189 unsigned ArgNo = 0;
5190 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5191 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5192 I != E; ++I, ++info_it, ++ArgNo) {
5193 const ABIArgInfo &ArgInfo = info_it->info;
5194
5195 // Insert a padding argument to ensure proper alignment.
5196 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5197 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5198 llvm::UndefValue::get(ArgInfo.getPaddingType());
5199
5200 unsigned FirstIRArg, NumIRArgs;
5201 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5202
5203 bool ArgHasMaybeUndefAttr =
5204 IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
5205
5206 switch (ArgInfo.getKind()) {
5207 case ABIArgInfo::InAlloca: {
5208 assert(NumIRArgs == 0);
5209 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5210 if (I->isAggregate()) {
5211 RawAddress Addr = I->hasLValue()
5212 ? I->getKnownLValue().getAddress()
5213 : I->getKnownRValue().getAggregateAddress();
5214 llvm::Instruction *Placeholder =
5215 cast<llvm::Instruction>(Addr.getPointer());
5216
5217 if (!ArgInfo.getInAllocaIndirect()) {
5218 // Replace the placeholder with the appropriate argument slot GEP.
5219 CGBuilderTy::InsertPoint IP = Builder.saveIP();
5220 Builder.SetInsertPoint(Placeholder);
5221 Addr = Builder.CreateStructGEP(ArgMemory,
5222 ArgInfo.getInAllocaFieldIndex());
5223 Builder.restoreIP(IP);
5224 } else {
5225 // For indirect things such as overaligned structs, replace the
5226 // placeholder with a regular aggregate temporary alloca. Store the
5227 // address of this alloca into the struct.
5228 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
5230 ArgMemory, ArgInfo.getInAllocaFieldIndex());
5231 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5232 }
5233 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
5234 } else if (ArgInfo.getInAllocaIndirect()) {
5235 // Make a temporary alloca and store the address of it into the argument
5236 // struct.
5238 I->Ty, getContext().getTypeAlignInChars(I->Ty),
5239 "indirect-arg-temp");
5240 I->copyInto(*this, Addr);
5241 Address ArgSlot =
5242 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5243 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5244 } else {
5245 // Store the RValue into the argument struct.
5246 Address Addr =
5247 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5248 Addr = Addr.withElementType(ConvertTypeForMem(I->Ty));
5249 I->copyInto(*this, Addr);
5250 }
5251 break;
5252 }
5253
5256 assert(NumIRArgs == 1);
5257 if (I->isAggregate()) {
5258 // We want to avoid creating an unnecessary temporary+copy here;
5259 // however, we need one in three cases:
5260 // 1. If the argument is not byval, and we are required to copy the
5261 // source. (This case doesn't occur on any common architecture.)
5262 // 2. If the argument is byval, RV is not sufficiently aligned, and
5263 // we cannot force it to be sufficiently aligned.
5264 // 3. If the argument is byval, but RV is not located in default
5265 // or alloca address space.
5266 Address Addr = I->hasLValue()
5267 ? I->getKnownLValue().getAddress()
5268 : I->getKnownRValue().getAggregateAddress();
5269 CharUnits Align = ArgInfo.getIndirectAlign();
5270 const llvm::DataLayout *TD = &CGM.getDataLayout();
5271
5272 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5273 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5274 TD->getAllocaAddrSpace()) &&
5275 "indirect argument must be in alloca address space");
5276
5277 bool NeedCopy = false;
5278 if (Addr.getAlignment() < Align &&
5279 llvm::getOrEnforceKnownAlignment(Addr.emitRawPointer(*this),
5280 Align.getAsAlign(),
5281 *TD) < Align.getAsAlign()) {
5282 NeedCopy = true;
5283 } else if (I->hasLValue()) {
5284 auto LV = I->getKnownLValue();
5285 auto AS = LV.getAddressSpace();
5286
5287 bool isByValOrRef =
5288 ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5289
5290 if (!isByValOrRef ||
5291 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
5292 NeedCopy = true;
5293 }
5294 if (!getLangOpts().OpenCL) {
5295 if ((isByValOrRef &&
5296 (AS != LangAS::Default &&
5297 AS != CGM.getASTAllocaAddressSpace()))) {
5298 NeedCopy = true;
5299 }
5300 }
5301 // For OpenCL even if RV is located in default or alloca address space
5302 // we don't want to perform address space cast for it.
5303 else if ((isByValOrRef &&
5304 Addr.getType()->getAddressSpace() != IRFuncTy->
5305 getParamType(FirstIRArg)->getPointerAddressSpace())) {
5306 NeedCopy = true;
5307 }
5308 }
5309
5310 if (!NeedCopy) {
5311 // Skip the extra memcpy call.
5312 llvm::Value *V = getAsNaturalPointerTo(Addr, I->Ty);
5313 auto *T = llvm::PointerType::get(
5314 CGM.getLLVMContext(), CGM.getDataLayout().getAllocaAddrSpace());
5315
5316 llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5318 true);
5319 if (ArgHasMaybeUndefAttr)
5320 Val = Builder.CreateFreeze(Val);
5321 IRCallArgs[FirstIRArg] = Val;
5322 break;
5323 }
5324 } else if (I->getType()->isArrayParameterType()) {
5325 // Don't produce a temporary for ArrayParameterType arguments.
5326 // ArrayParameterType arguments are only created from
5327 // HLSL_ArrayRValue casts and HLSLOutArgExpr expressions, both
5328 // of which create temporaries already. This allows us to just use the
5329 // scalar for the decayed array pointer as the argument directly.
5330 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5331 break;
5332 }
5333
5334 // For non-aggregate args and aggregate args meeting conditions above
5335 // we need to create an aligned temporary, and copy to it.
5337 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
5338 llvm::Value *Val = getAsNaturalPointerTo(AI, I->Ty);
5339 if (ArgHasMaybeUndefAttr)
5340 Val = Builder.CreateFreeze(Val);
5341 IRCallArgs[FirstIRArg] = Val;
5342
5343 // Emit lifetime markers for the temporary alloca.
5344 llvm::TypeSize ByvalTempElementSize =
5345 CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
5346 llvm::Value *LifetimeSize =
5347 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
5348
5349 // Add cleanup code to emit the end lifetime marker after the call.
5350 if (LifetimeSize) // In case we disabled lifetime markers.
5351 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
5352
5353 // Generate the copy.
5354 I->copyInto(*this, AI);
5355 break;
5356 }
5357
5358 case ABIArgInfo::Ignore:
5359 assert(NumIRArgs == 0);
5360 break;
5361
5362 case ABIArgInfo::Extend:
5363 case ABIArgInfo::Direct: {
5364 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5365 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5366 ArgInfo.getDirectOffset() == 0) {
5367 assert(NumIRArgs == 1);
5368 llvm::Value *V;
5369 if (!I->isAggregate())
5370 V = I->getKnownRValue().getScalarVal();
5371 else
5373 I->hasLValue() ? I->getKnownLValue().getAddress()
5374 : I->getKnownRValue().getAggregateAddress());
5375
5376 // Implement swifterror by copying into a new swifterror argument.
5377 // We'll write back in the normal path out of the call.
5378 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
5380 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5381
5382 QualType pointeeTy = I->Ty->getPointeeType();
5383 swiftErrorArg = makeNaturalAddressForPointer(
5384 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
5385
5386 swiftErrorTemp =
5387 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5388 V = swiftErrorTemp.getPointer();
5389 cast<llvm::AllocaInst>(V)->setSwiftError(true);
5390
5391 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5392 Builder.CreateStore(errorValue, swiftErrorTemp);
5393 }
5394
5395 // We might have to widen integers, but we should never truncate.
5396 if (ArgInfo.getCoerceToType() != V->getType() &&
5397 V->getType()->isIntegerTy())
5398 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5399
5400 // If the argument doesn't match, perform a bitcast to coerce it. This
5401 // can happen due to trivial type mismatches.
5402 if (FirstIRArg < IRFuncTy->getNumParams() &&
5403 V->getType() != IRFuncTy->getParamType(FirstIRArg))
5404 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
5405
5406 if (ArgHasMaybeUndefAttr)
5407 V = Builder.CreateFreeze(V);
5408 IRCallArgs[FirstIRArg] = V;
5409 break;
5410 }
5411
5412 llvm::StructType *STy =
5413 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5414
5415 // FIXME: Avoid the conversion through memory if possible.
5416 Address Src = Address::invalid();
5417 if (!I->isAggregate()) {
5418 Src = CreateMemTemp(I->Ty, "coerce");
5419 I->copyInto(*this, Src);
5420 } else {
5421 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5422 : I->getKnownRValue().getAggregateAddress();
5423 }
5424
5425 // If the value is offset in memory, apply the offset now.
5426 Src = emitAddressAtOffset(*this, Src, ArgInfo);
5427
5428 // Fast-isel and the optimizer generally like scalar values better than
5429 // FCAs, so we flatten them if this is safe to do for this argument.
5430 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5431 llvm::Type *SrcTy = Src.getElementType();
5432 llvm::TypeSize SrcTypeSize =
5433 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5434 llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(STy);
5435 if (SrcTypeSize.isScalable()) {
5436 assert(STy->containsHomogeneousScalableVectorTypes() &&
5437 "ABI only supports structure with homogeneous scalable vector "
5438 "type");
5439 assert(SrcTypeSize == DstTypeSize &&
5440 "Only allow non-fractional movement of structure with "
5441 "homogeneous scalable vector type");
5442 assert(NumIRArgs == STy->getNumElements());
5443
5444 llvm::Value *StoredStructValue =
5445 Builder.CreateLoad(Src, Src.getName() + ".tuple");
5446 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5447 llvm::Value *Extract = Builder.CreateExtractValue(
5448 StoredStructValue, i, Src.getName() + ".extract" + Twine(i));
5449 IRCallArgs[FirstIRArg + i] = Extract;
5450 }
5451 } else {
5452 uint64_t SrcSize = SrcTypeSize.getFixedValue();
5453 uint64_t DstSize = DstTypeSize.getFixedValue();
5454
5455 // If the source type is smaller than the destination type of the
5456 // coerce-to logic, copy the source value into a temp alloca the size
5457 // of the destination type to allow loading all of it. The bits past
5458 // the source value are left undef.
5459 if (SrcSize < DstSize) {
5460 Address TempAlloca = CreateTempAlloca(STy, Src.getAlignment(),
5461 Src.getName() + ".coerce");
5462 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5463 Src = TempAlloca;
5464 } else {
5465 Src = Src.withElementType(STy);
5466 }
5467
5468 assert(NumIRArgs == STy->getNumElements());
5469 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5470 Address EltPtr = Builder.CreateStructGEP(Src, i);
5471 llvm::Value *LI = Builder.CreateLoad(EltPtr);
5472 if (ArgHasMaybeUndefAttr)
5473 LI = Builder.CreateFreeze(LI);
5474 IRCallArgs[FirstIRArg + i] = LI;
5475 }
5476 }
5477 } else {
5478 // In the simple case, just pass the coerced loaded value.
5479 assert(NumIRArgs == 1);
5480 llvm::Value *Load =
5481 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5482
5483 if (CallInfo.isCmseNSCall()) {
5484 // For certain parameter types, clear padding bits, as they may reveal
5485 // sensitive information.
5486 // Small struct/union types are passed as integer arrays.
5487 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5488 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5489 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5490 }
5491
5492 if (ArgHasMaybeUndefAttr)
5493 Load = Builder.CreateFreeze(Load);
5494 IRCallArgs[FirstIRArg] = Load;
5495 }
5496
5497 break;
5498 }
5499
5501 auto coercionType = ArgInfo.getCoerceAndExpandType();
5502 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5503 auto unpaddedCoercionType = ArgInfo.getUnpaddedCoerceAndExpandType();
5504 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
5505
5506 llvm::Value *tempSize = nullptr;
5507 Address addr = Address::invalid();
5508 RawAddress AllocaAddr = RawAddress::invalid();
5509 if (I->isAggregate()) {
5510 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
5511 : I->getKnownRValue().getAggregateAddress();
5512
5513 } else {
5514 RValue RV = I->getKnownRValue();
5515 assert(RV.isScalar()); // complex should always just be direct
5516
5517 llvm::Type *scalarType = RV.getScalarVal()->getType();
5518 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5519 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5520
5521 // Materialize to a temporary.
5522 addr = CreateTempAlloca(
5523 RV.getScalarVal()->getType(),
5524 CharUnits::fromQuantity(std::max(layout->getAlignment(), scalarAlign)),
5525 "tmp",
5526 /*ArraySize=*/nullptr, &AllocaAddr);
5527 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5528
5529 Builder.CreateStore(RV.getScalarVal(), addr);
5530 }
5531
5532 addr = addr.withElementType(coercionType);
5533
5534 unsigned IRArgPos = FirstIRArg;
5535 unsigned unpaddedIndex = 0;
5536 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5537 llvm::Type *eltType = coercionType->getElementType(i);
5538 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5539 Address eltAddr = Builder.CreateStructGEP(addr, i);
5540 llvm::Value *elt = CreateCoercedLoad(
5541 eltAddr,
5542 unpaddedStruct ? unpaddedStruct->getElementType(unpaddedIndex++)
5543 : unpaddedCoercionType,
5544 *this);
5545 if (ArgHasMaybeUndefAttr)
5546 elt = Builder.CreateFreeze(elt);
5547 IRCallArgs[IRArgPos++] = elt;
5548 }
5549 assert(IRArgPos == FirstIRArg + NumIRArgs);
5550
5551 if (tempSize) {
5552 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5553 }
5554
5555 break;
5556 }
5557
5558 case ABIArgInfo::Expand: {
5559 unsigned IRArgPos = FirstIRArg;
5560 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5561 assert(IRArgPos == FirstIRArg + NumIRArgs);
5562 break;
5563 }
5564 }
5565 }
5566
5567 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5568 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5569
5570 // If we're using inalloca, set up that argument.
5571 if (ArgMemory.isValid()) {
5572 llvm::Value *Arg = ArgMemory.getPointer();
5573 assert(IRFunctionArgs.hasInallocaArg());
5574 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5575 }
5576
5577 // 2. Prepare the function pointer.
5578
5579 // If the callee is a bitcast of a non-variadic function to have a
5580 // variadic function pointer type, check to see if we can remove the
5581 // bitcast. This comes up with unprototyped functions.
5582 //
5583 // This makes the IR nicer, but more importantly it ensures that we
5584 // can inline the function at -O0 if it is marked always_inline.
5585 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5586 llvm::Value *Ptr) -> llvm::Function * {
5587 if (!CalleeFT->isVarArg())
5588 return nullptr;
5589
5590 // Get underlying value if it's a bitcast
5591 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5592 if (CE->getOpcode() == llvm::Instruction::BitCast)
5593 Ptr = CE->getOperand(0);
5594 }
5595
5596 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5597 if (!OrigFn)
5598 return nullptr;
5599
5600 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5601
5602 // If the original type is variadic, or if any of the component types
5603 // disagree, we cannot remove the cast.
5604 if (OrigFT->isVarArg() ||
5605 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5606 OrigFT->getReturnType() != CalleeFT->getReturnType())
5607 return nullptr;
5608
5609 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5610 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5611 return nullptr;
5612
5613 return OrigFn;
5614 };
5615
5616 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5617 CalleePtr = OrigFn;
5618 IRFuncTy = OrigFn->getFunctionType();
5619 }
5620
5621 // 3. Perform the actual call.
5622
5623 // Deactivate any cleanups that we're supposed to do immediately before
5624 // the call.
5625 if (!CallArgs.getCleanupsToDeactivate().empty())
5626 deactivateArgCleanupsBeforeCall(*this, CallArgs);
5627
5628 // Assert that the arguments we computed match up. The IR verifier
5629 // will catch this, but this is a common enough source of problems
5630 // during IRGen changes that it's way better for debugging to catch
5631 // it ourselves here.
5632#ifndef NDEBUG
5633 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5634 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5635 // Inalloca argument can have different type.
5636 if (IRFunctionArgs.hasInallocaArg() &&
5637 i == IRFunctionArgs.getInallocaArgNo())
5638 continue;
5639 if (i < IRFuncTy->getNumParams())
5640 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5641 }
5642#endif
5643
5644 // Update the largest vector width if any arguments have vector types.
5645 for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5646 LargestVectorWidth = std::max(LargestVectorWidth,
5647 getMaxVectorWidth(IRCallArgs[i]->getType()));
5648
5649 // Compute the calling convention and attributes.
5650 unsigned CallingConv;
5651 llvm::AttributeList Attrs;
5652 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5653 Callee.getAbstractInfo(), Attrs, CallingConv,
5654 /*AttrOnCallSite=*/true,
5655 /*IsThunk=*/false);
5656
5657 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
5658 getTarget().getTriple().isWindowsArm64EC()) {
5659 CGM.Error(Loc, "__vectorcall calling convention is not currently "
5660 "supported");
5661 }
5662
5663 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5664 if (FD->hasAttr<StrictFPAttr>())
5665 // All calls within a strictfp function are marked strictfp
5666 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5667
5668 // If -ffast-math is enabled and the function is guarded by an
5669 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5670 // library call instead of the intrinsic.
5671 if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
5672 CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
5673 Attrs);
5674 }
5675 // Add call-site nomerge attribute if exists.
5677 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5678
5679 // Add call-site noinline attribute if exists.
5681 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5682
5683 // Add call-site always_inline attribute if exists.
5684 // Note: This corresponds to the [[clang::always_inline]] statement attribute.
5687 CallerDecl, CalleeDecl))
5688 Attrs =
5689 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5690
5691 // Remove call-site convergent attribute if requested.
5693 Attrs =
5694 Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Convergent);
5695
5696 // Apply some call-site-specific attributes.
5697 // TODO: work this into building the attribute set.
5698
5699 // Apply always_inline to all calls within flatten functions.
5700 // FIXME: should this really take priority over __try, below?
5701 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5703 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>()) &&
5705 CallerDecl, CalleeDecl)) {
5706 Attrs =
5707 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5708 }
5709
5710 // Disable inlining inside SEH __try blocks.
5711 if (isSEHTryScope()) {
5712 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5713 }
5714
5715 // Decide whether to use a call or an invoke.
5716 bool CannotThrow;
5718 // SEH cares about asynchronous exceptions, so everything can "throw."
5719 CannotThrow = false;
5720 } else if (isCleanupPadScope() &&
5722 // The MSVC++ personality will implicitly terminate the program if an
5723 // exception is thrown during a cleanup outside of a try/catch.
5724 // We don't need to model anything in IR to get this behavior.
5725 CannotThrow = true;
5726 } else {
5727 // Otherwise, nounwind call sites will never throw.
5728 CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5729
5730 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5731 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5732 CannotThrow = true;
5733 }
5734
5735 // If we made a temporary, be sure to clean up after ourselves. Note that we
5736 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5737 // pop this cleanup later on. Being eager about this is OK, since this
5738 // temporary is 'invisible' outside of the callee.
5739 if (UnusedReturnSizePtr)
5740 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5741 UnusedReturnSizePtr);
5742
5743 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5744
5746 getBundlesForFunclet(CalleePtr);
5747
5748 if (SanOpts.has(SanitizerKind::KCFI) &&
5749 !isa_and_nonnull<FunctionDecl>(TargetDecl))
5750 EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5751
5752 // Add the pointer-authentication bundle.
5753 EmitPointerAuthOperandBundle(ConcreteCallee.getPointerAuthInfo(), BundleList);
5754
5755 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5756 if (FD->hasAttr<StrictFPAttr>())
5757 // All calls within a strictfp function are marked strictfp
5758 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5759
5760 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5761 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5762
5763 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5764 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5765
5766 // Emit the actual call/invoke instruction.
5767 llvm::CallBase *CI;
5768 if (!InvokeDest) {
5769 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5770 } else {
5771 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5772 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5773 BundleList);
5774 EmitBlock(Cont);
5775 }
5776 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
5777 CI->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5779 }
5780 if (callOrInvoke)
5781 *callOrInvoke = CI;
5782
5783 // If this is within a function that has the guard(nocf) attribute and is an
5784 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5785 // Control Flow Guard checks should not be added, even if the call is inlined.
5786 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5787 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5788 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5789 Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5790 }
5791 }
5792
5793 // Apply the attributes and calling convention.
5794 CI->setAttributes(Attrs);
5795 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5796
5797 // Apply various metadata.
5798
5799 if (!CI->getType()->isVoidTy())
5800 CI->setName("call");
5801
5802 if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
5803 CI = addConvergenceControlToken(CI);
5804
5805 // Update largest vector width from the return type.
5806 LargestVectorWidth =
5807 std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5808
5809 // Insert instrumentation or attach profile metadata at indirect call sites.
5810 // For more details, see the comment before the definition of
5811 // IPVK_IndirectCallTarget in InstrProfData.inc.
5812 if (!CI->getCalledFunction())
5813 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5814 CI, CalleePtr);
5815
5816 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5817 // optimizer it can aggressively ignore unwind edges.
5818 if (CGM.getLangOpts().ObjCAutoRefCount)
5819 AddObjCARCExceptionMetadata(CI);
5820
5821 // Set tail call kind if necessary.
5822 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5823 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5824 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5825 else if (IsMustTail) {
5826 if (getTarget().getTriple().isPPC()) {
5827 if (getTarget().getTriple().isOSAIX())
5828 CGM.getDiags().Report(Loc, diag::err_aix_musttail_unsupported);
5829 else if (!getTarget().hasFeature("pcrelative-memops")) {
5830 if (getTarget().hasFeature("longcall"))
5831 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 0;
5832 else if (Call->isIndirectCall())
5833 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 1;
5834 else if (isa_and_nonnull<FunctionDecl>(TargetDecl)) {
5835 if (!cast<FunctionDecl>(TargetDecl)->isDefined())
5836 // The undefined callee may be a forward declaration. Without
5837 // knowning all symbols in the module, we won't know the symbol is
5838 // defined or not. Collect all these symbols for later diagnosing.
5840 {cast<FunctionDecl>(TargetDecl), Loc});
5841 else {
5842 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(
5843 GlobalDecl(cast<FunctionDecl>(TargetDecl)));
5844 if (llvm::GlobalValue::isWeakForLinker(Linkage) ||
5845 llvm::GlobalValue::isDiscardableIfUnused(Linkage))
5846 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail)
5847 << 2;
5848 }
5849 }
5850 }
5851 }
5852 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5853 }
5854 }
5855
5856 // Add metadata for calls to MSAllocator functions
5857 if (getDebugInfo() && TargetDecl &&
5858 TargetDecl->hasAttr<MSAllocatorAttr>())
5860
5861 // Add metadata if calling an __attribute__((error(""))) or warning fn.
5862 if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
5863 llvm::ConstantInt *Line =
5864 llvm::ConstantInt::get(Int64Ty, Loc.getRawEncoding());
5865 llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
5866 llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
5867 CI->setMetadata("srcloc", MDT);
5868 }
5869
5870 // 4. Finish the call.
5871
5872 // If the call doesn't return, finish the basic block and clear the
5873 // insertion point; this allows the rest of IRGen to discard
5874 // unreachable code.
5875 if (CI->doesNotReturn()) {
5876 if (UnusedReturnSizePtr)
5878
5879 // Strip away the noreturn attribute to better diagnose unreachable UB.
5880 if (SanOpts.has(SanitizerKind::Unreachable)) {
5881 // Also remove from function since CallBase::hasFnAttr additionally checks
5882 // attributes of the called function.
5883 if (auto *F = CI->getCalledFunction())
5884 F->removeFnAttr(llvm::Attribute::NoReturn);
5885 CI->removeFnAttr(llvm::Attribute::NoReturn);
5886
5887 // Avoid incompatibility with ASan which relies on the `noreturn`
5888 // attribute to insert handler calls.
5889 if (SanOpts.hasOneOf(SanitizerKind::Address |
5890 SanitizerKind::KernelAddress)) {
5891 SanitizerScope SanScope(this);
5892 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5893 Builder.SetInsertPoint(CI);
5894 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5895 llvm::FunctionCallee Fn =
5896 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5898 }
5899 }
5900
5902 Builder.ClearInsertionPoint();
5903
5904 // FIXME: For now, emit a dummy basic block because expr emitters in
5905 // generally are not ready to handle emitting expressions at unreachable
5906 // points.
5908
5909 // Return a reasonable RValue.
5910 return GetUndefRValue(RetTy);
5911 }
5912
5913 // If this is a musttail call, return immediately. We do not branch to the
5914 // epilogue in this case.
5915 if (IsMustTail) {
5916 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5917 ++it) {
5918 EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5919 if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5920 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5921 }
5922 if (CI->getType()->isVoidTy())
5923 Builder.CreateRetVoid();
5924 else
5925 Builder.CreateRet(CI);
5926 Builder.ClearInsertionPoint();
5928 return GetUndefRValue(RetTy);
5929 }
5930
5931 // Perform the swifterror writeback.
5932 if (swiftErrorTemp.isValid()) {
5933 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5934 Builder.CreateStore(errorResult, swiftErrorArg);
5935 }
5936
5937 // Emit any call-associated writebacks immediately. Arguably this
5938 // should happen after any return-value munging.
5939 if (CallArgs.hasWritebacks())
5940 EmitWritebacks(CallArgs);
5941
5942 // The stack cleanup for inalloca arguments has to run out of the normal
5943 // lexical order, so deactivate it and run it manually here.
5944 CallArgs.freeArgumentMemory(*this);
5945
5946 // Extract the return value.
5947 RValue Ret;
5948
5949 // If the current function is a virtual function pointer thunk, avoid copying
5950 // the return value of the musttail call to a temporary.
5951 if (IsVirtualFunctionPointerThunk) {
5952 Ret = RValue::get(CI);
5953 } else {
5954 Ret = [&] {
5955 switch (RetAI.getKind()) {
5957 auto coercionType = RetAI.getCoerceAndExpandType();
5958
5959 Address addr = SRetPtr.withElementType(coercionType);
5960
5961 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5962 bool requiresExtract = isa<llvm::StructType>(CI->getType());
5963
5964 unsigned unpaddedIndex = 0;
5965 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5966 llvm::Type *eltType = coercionType->getElementType(i);
5968 continue;
5969 Address eltAddr = Builder.CreateStructGEP(addr, i);
5970 llvm::Value *elt = CI;
5971 if (requiresExtract)
5972 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5973 else
5974 assert(unpaddedIndex == 0);
5975 Builder.CreateStore(elt, eltAddr);
5976 }
5977 [[fallthrough]];
5978 }
5979
5981 case ABIArgInfo::Indirect: {
5982 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5983 if (UnusedReturnSizePtr)
5985 return ret;
5986 }
5987
5988 case ABIArgInfo::Ignore:
5989 // If we are ignoring an argument that had a result, make sure to
5990 // construct the appropriate return value for our caller.
5991 return GetUndefRValue(RetTy);
5992
5993 case ABIArgInfo::Extend:
5994 case ABIArgInfo::Direct: {
5995 llvm::Type *RetIRTy = ConvertType(RetTy);
5996 if (RetAI.getCoerceToType() == RetIRTy &&
5997 RetAI.getDirectOffset() == 0) {
5998 switch (getEvaluationKind(RetTy)) {
5999 case TEK_Complex: {
6000 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
6001 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
6002 return RValue::getComplex(std::make_pair(Real, Imag));
6003 }
6004 case TEK_Aggregate:
6005 break;
6006 case TEK_Scalar: {
6007 // If the argument doesn't match, perform a bitcast to coerce it.
6008 // This can happen due to trivial type mismatches.
6009 llvm::Value *V = CI;
6010 if (V->getType() != RetIRTy)
6011 V = Builder.CreateBitCast(V, RetIRTy);
6012 return RValue::get(V);
6013 }
6014 }
6015 }
6016
6017 // If coercing a fixed vector from a scalable vector for ABI
6018 // compatibility, and the types match, use the llvm.vector.extract
6019 // intrinsic to perform the conversion.
6020 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
6021 llvm::Value *V = CI;
6022 if (auto *ScalableSrcTy =
6023 dyn_cast<llvm::ScalableVectorType>(V->getType())) {
6024 if (FixedDstTy->getElementType() ==
6025 ScalableSrcTy->getElementType()) {
6026 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
6027 V = Builder.CreateExtractVector(FixedDstTy, V, Zero,
6028 "cast.fixed");
6029 return RValue::get(V);
6030 }
6031 }
6032 }
6033
6034 Address DestPtr = ReturnValue.getValue();
6035 bool DestIsVolatile = ReturnValue.isVolatile();
6036 uint64_t DestSize =
6038
6039 if (!DestPtr.isValid()) {
6040 DestPtr = CreateMemTemp(RetTy, "coerce");
6041 DestIsVolatile = false;
6042 DestSize = getContext().getTypeSizeInChars(RetTy).getQuantity();
6043 }
6044
6045 // An empty record can overlap other data (if declared with
6046 // no_unique_address); omit the store for such types - as there is no
6047 // actual data to store.
6048 if (!isEmptyRecord(getContext(), RetTy, true)) {
6049 // If the value is offset in memory, apply the offset now.
6050 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
6052 CI, StorePtr,
6053 llvm::TypeSize::getFixed(DestSize - RetAI.getDirectOffset()),
6054 DestIsVolatile);
6055 }
6056
6057 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
6058 }
6059
6060 case ABIArgInfo::Expand:
6062 llvm_unreachable("Invalid ABI kind for return argument");
6063 }
6064
6065 llvm_unreachable("Unhandled ABIArgInfo::Kind");
6066 }();
6067 }
6068
6069 // Emit the assume_aligned check on the return value.
6070 if (Ret.isScalar() && TargetDecl) {
6071 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6072 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6073 }
6074
6075 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6076 // we can't use the full cleanup mechanism.
6077 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6078 LifetimeEnd.Emit(*this, /*Flags=*/{});
6079
6080 if (!ReturnValue.isExternallyDestructed() &&
6082 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
6083 RetTy);
6084
6085 return Ret;
6086}
6087
6089 if (isVirtual()) {
6090 const CallExpr *CE = getVirtualCallExpr();
6093 CE ? CE->getBeginLoc() : SourceLocation());
6094 }
6095
6096 return *this;
6097}
6098
6099/* VarArg handling */
6100
6102 AggValueSlot Slot) {
6103 VAListAddr = VE->isMicrosoftABI() ? EmitMSVAListRef(VE->getSubExpr())
6104 : EmitVAListRef(VE->getSubExpr());
6105 QualType Ty = VE->getType();
6106 if (Ty->isVariablyModifiedType())
6108 if (VE->isMicrosoftABI())
6109 return CGM.getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty, Slot);
6110 return CGM.getABIInfo().EmitVAArg(*this, VAListAddr, Ty, Slot);
6111}
#define V(N, I)
Definition: ASTContext.h:3460
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:4085
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
Definition: CGCall.cpp:3754
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:3500
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:2923
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, const ABIArgInfo &info)
Definition: CGCall.cpp:1402
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty)
Definition: CGCall.cpp:4090
static void setBitRange(SmallVectorImpl< uint64_t > &Bits, int BitOffset, int BitWidth, int CharWidth)
Definition: CGCall.cpp:3633
static SmallVector< CanQualType, 16 > getArgTypesForCall(ASTContext &ctx, const CallArgList &args)
Definition: CGCall.cpp:385
static bool isProvablyNull(llvm::Value *addr)
Definition: CGCall.cpp:4160
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
Definition: CGCall.cpp:1767
static void eraseUnusedBitCasts(llvm::Instruction *insn)
Definition: CGCall.cpp:3400
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
Definition: CGCall.cpp:4487
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, const LangOptions &LangOpts, const NoBuiltinAttr *NBA=nullptr)
Definition: CGCall.cpp:2168
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
Definition: CGCall.cpp:4265
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:2047
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:2204
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
Definition: CGCall.cpp:4254
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:1868
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, const CallArgList &CallArgs)
Definition: CGCall.cpp:4243
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
Definition: CGCall.cpp:4164
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:2903
static std::pair< llvm::Value *, bool > CoerceScalableToFixed(CodeGenFunction &CGF, llvm::FixedVectorType *ToTy, llvm::ScalableVectorType *FromTy, llvm::Value *V, StringRef Name="")
Definition: CGCall.cpp:1414
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:2277
static void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, bool AttrOnCallSite, llvm::AttrBuilder &FuncAttrs)
Definition: CGCall.cpp:1888
static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts)
Return the nofpclass mask that can be applied to floating-point parameters.
Definition: CGCall.cpp:2299
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:2255
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
Definition: CGCall.cpp:4469
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:3737
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
Definition: CGCall.cpp:3557
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:3412
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:3539
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
Definition: CGCall.cpp:4169
static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy, const Decl *TargetDecl)
Definition: CGCall.cpp:1833
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:1882
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:1806
static unsigned getMaxVectorWidth(const llvm::Type *Ty)
Definition: CGCall.cpp:5066
CodeGenFunction::ComplexPairTy ComplexPairTy
const Decl * D
enum clang::sema::@1727::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:96
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:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
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:1187
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:2213
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1169
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:2489
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
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:2493
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:3578
Attr - This represents one attribute.
Definition: Attr.h:43
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2536
This class is used for builtin types like 'int'.
Definition: Type.h:3035
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:2592
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2856
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2117
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:2601
bool isVirtual() const
Definition: DeclCXX.h:2172
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2243
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2278
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2083
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:2874
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1644
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:84
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:136
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:305
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition: CGBuilder.h:356
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition: CGBuilder.h:331
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:158
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:365
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
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:6088
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:355
void addUncopiedAggregate(LValue LV, QualType type)
Definition: CGCall.h:307
void addArgCleanupDeactivation(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *IsActiveIP)
Definition: CGCall.h:342
ArrayRef< CallArgCleanup > getCleanupsToDeactivate() const
Definition: CGCall.h:350
bool hasWritebacks() const
Definition: CGCall.h:333
void add(RValue rvalue, QualType type)
Definition: CGCall.h:305
bool isUsingInAlloca() const
Returns if we're using an inalloca struct to pass arguments in memory.
Definition: CGCall.h:360
void allocateArgumentMemory(CodeGenFunction &CGF)
Definition: CGCall.cpp:4391
void freeArgumentMemory(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4398
writeback_const_range writebacks() const
Definition: CGCall.h:338
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr, llvm::Value *lifetimeSz=nullptr)
Definition: CGCall.h:326
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)
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
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)
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
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
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)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
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()
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > 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...
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 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,...
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
void EmitWritebacks(const CallArgList &Args)
EmitWriteback - Emit callbacks for function.
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...
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:1596
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:1613
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:1591
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition: CGCall.cpp:1586
void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs)
Adjust Memory attribute to ensure that the BE gets the right attribute.
Definition: CGCall.cpp:2308
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:2336
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:1581
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:2161
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:1821
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:1630
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:1757
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:247
EHScopeStack::Cleanup * getCleanup()
Definition: CGCleanup.h:426
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:146
A saved depth on the scope stack.
Definition: EHScopeStack.h:106
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:398
iterator end() const
Returns an iterator pointing to the outermost EH scope.
Definition: CGCleanup.h:627
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:647
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:382
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:386
virtual bool doesReturnSlotInterfereWithArgs() const
doesReturnSlotInterfereWithArgs - Return true if the target uses an argument slot for an 'sret' type.
Definition: TargetInfo.h:213
virtual bool wouldInliningViolateFunctionCallABI(const FunctionDecl *Caller, const FunctionDecl *Callee) const
Returns true if inlining the function call would produce incorrect code for the current target and sh...
Definition: TargetInfo.h:114
virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const
Definition: TargetInfo.h:402
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:3146
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3616
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
Definition: DeclCXX.h:3760
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
DeclContext * getDeclContext()
Definition: DeclBase.h:451
bool hasAttr() const
Definition: DeclBase.h:580
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:790
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1497
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:3092
@ 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:3970
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3040
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3143
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3146
bool isZeroLengthBitField() 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:4629
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2312
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4687
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5388
unsigned getNumParams() const
Definition: Type.h:5361
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5567
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5480
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5550
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5546
Wrapper for source info for functions.
Definition: TypeLoc.h:1460
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4433
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4548
CallingConv getCC() const
Definition: Type.h:4495
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4514
bool getCmseNSCall() const
Definition: Type.h:4483
bool getNoCfCheck() const
Definition: Type.h:4485
unsigned getRegParm() const
Definition: Type.h:4488
bool getNoCallerSavedRegs() const
Definition: Type.h:4484
bool getHasRegParm() const
Definition: Type.h:4486
bool getNoReturn() const
Definition: Type.h:4481
bool getProducesResult() const
Definition: Type.h:4482
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4348
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4361
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4388
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
ExtInfo getExtInfo() const
Definition: Type.h:4661
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4619
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4615
QualType getReturnType() const
Definition: Type.h:4649
@ SME_PStateSMEnabledMask
Definition: Type.h:4588
@ SME_PStateSMCompatibleMask
Definition: Type.h:4589
@ SME_AgnosticZAStateMask
Definition: Type.h:4599
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:105
const Decl * getDecl() const
Definition: GlobalDecl.h:103
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition: Expr.h:7152
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2563
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2575
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:290
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:500
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
Definition: LangOptions.h:567
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:817
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:698
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4197
Describes a module or submodule.
Definition: Module.h:115
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1571
bool shouldCopy() const
shouldCopy - True if we should do the 'copy' part of the copy-restore.
Definition: ExprObjC.h:1599
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:869
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
QualType getPointeeType() const
Definition: Type.h:3209
A (possibly-)qualified type.
Definition: Type.h:929
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8015
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2794
@ DK_cxx_destructor
Definition: Type.h:1521
@ DK_nontrivial_c_struct
Definition: Type.h:1524
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
QualType getCanonicalType() const
Definition: Type.h:7989
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8010
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
LangAS getAddressSpace() const
Definition: Type.h:564
Represents a struct/union/class.
Definition: Decl.h:4169
bool hasFlexibleArrayMember() const
Definition: Decl.h:4202
field_iterator field_end() const
Definition: Decl.h:4386
field_range fields() const
Definition: Decl.h:4383
bool isParamDestroyedInCallee() const
Definition: Decl.h:4319
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4368
field_iterator field_begin() const
Definition: Decl.cpp:5111
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
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:3791
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:1262
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:988
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool useObjCFP2RetForComplexLongDouble() const
Check whether _Complex long double should use the "fp2ret" flavor of Objective-C message passing on t...
Definition: TargetInfo.h:994
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:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8206
bool isVoidType() const
Definition: Type.h:8516
bool isIncompleteArrayType() const
Definition: Type.h:8272
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isPointerType() const
Definition: Type.h:8192
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8560
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isReferenceType() const
Definition: Type.h:8210
bool isScalarType() const
Definition: Type.h:8619
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isBitIntType() const
Definition: Type.h:8430
QualType getCanonicalTypeInternal() const
Definition: Type.h:2990
bool isMemberPointerType() const
Definition: Type.h:8246
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2292
bool isAnyPointerType() const
Definition: Type.h:8200
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isNullPtrType() const
Definition: Type.h:8553
bool isObjCRetainableType() const
Definition: Type.cpp:5026
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4750
bool isMicrosoftABI() const
Returns whether this is really a Win64 ABI va_arg expression.
Definition: Expr.h:4771
const Expr * getSubExpr() const
Definition: Expr.h:4766
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:886
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2823
Represents a GCC generic vector type.
Definition: Type.h:4035
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:205
@ 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:2078
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:3893
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2387
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2350
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1693
bool Ret(InterpState &S, CodePtr &PC)
Definition: Interp.h:318
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
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:65
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
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
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
const Expr * WritebackExpr
An Expression (optional) that performs the writeback with any required casting.
Definition: CGCall.h:291
LValue getKnownLValue() const
Definition: CGCall.h:254
RValue getKnownRValue() const
Definition: CGCall.h:258
void copyInto(CodeGenFunction &CGF, Address A) const
Definition: CGCall.cpp:4694
bool hasLValue() const
Definition: CGCall.h:247
RValue getRValue(CodeGenFunction &CGF) const
Definition: CGCall.cpp:4684
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
bool isMSVCXXPersonality() const
Definition: CGCleanup.h:703
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:169
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:179
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1338