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