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