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