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