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