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