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 (CodeGenOpts.SoftFloat)
2016 FuncAttrs.addAttribute("use-soft-float", "true");
2017 FuncAttrs.addAttribute("stack-protector-buffer-size",
2018 llvm::utostr(CodeGenOpts.SSPBufferSize));
2019 if (LangOpts.NoSignedZero)
2020 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
2021
2022 // TODO: Reciprocal estimate codegen options should apply to instructions?
2023 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
2024 if (!Recips.empty())
2025 FuncAttrs.addAttribute("reciprocal-estimates", llvm::join(Recips, ","));
2026
2027 if (!CodeGenOpts.PreferVectorWidth.empty() &&
2028 CodeGenOpts.PreferVectorWidth != "none")
2029 FuncAttrs.addAttribute("prefer-vector-width",
2030 CodeGenOpts.PreferVectorWidth);
2031
2032 if (CodeGenOpts.StackRealignment)
2033 FuncAttrs.addAttribute("stackrealign");
2034 if (CodeGenOpts.Backchain)
2035 FuncAttrs.addAttribute("backchain");
2036 if (CodeGenOpts.EnableSegmentedStacks)
2037 FuncAttrs.addAttribute("split-stack");
2038
2039 if (CodeGenOpts.SpeculativeLoadHardening)
2040 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2041
2042 // Add zero-call-used-regs attribute.
2043 switch (CodeGenOpts.getZeroCallUsedRegs()) {
2044 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
2045 FuncAttrs.removeAttribute("zero-call-used-regs");
2046 break;
2047 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
2048 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr-arg");
2049 break;
2050 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
2051 FuncAttrs.addAttribute("zero-call-used-regs", "used-gpr");
2052 break;
2053 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
2054 FuncAttrs.addAttribute("zero-call-used-regs", "used-arg");
2055 break;
2056 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
2057 FuncAttrs.addAttribute("zero-call-used-regs", "used");
2058 break;
2059 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
2060 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr-arg");
2061 break;
2062 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2063 FuncAttrs.addAttribute("zero-call-used-regs", "all-gpr");
2064 break;
2065 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2066 FuncAttrs.addAttribute("zero-call-used-regs", "all-arg");
2067 break;
2068 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2069 FuncAttrs.addAttribute("zero-call-used-regs", "all");
2070 break;
2071 }
2072 }
2073
2074 if (LangOpts.assumeFunctionsAreConvergent()) {
2075 // Conservatively, mark all functions and calls in CUDA and OpenCL as
2076 // convergent (meaning, they may call an intrinsically convergent op, such
2077 // as __syncthreads() / barrier(), and so can't have certain optimizations
2078 // applied around them). LLVM will remove this attribute where it safely
2079 // can.
2080 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2081 }
2082
2083 // TODO: NoUnwind attribute should be added for other GPU modes HIP,
2084 // OpenMP offload. AFAIK, neither of them support exceptions in device code.
2085 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2086 LangOpts.SYCLIsDevice) {
2087 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2088 }
2089
2090 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2091 FuncAttrs.addAttribute("save-reg-params");
2092
2093 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
2094 StringRef Var, Value;
2095 std::tie(Var, Value) = Attr.split('=');
2096 FuncAttrs.addAttribute(Var, Value);
2097 }
2098
2101}
2102
2103/// Merges `target-features` from \TargetOpts and \F, and sets the result in
2104/// \FuncAttr
2105/// * features from \F are always kept
2106/// * a feature from \TargetOpts is kept if itself and its opposite are absent
2107/// from \F
2108static void
2110 const llvm::Function &F,
2111 const TargetOptions &TargetOpts) {
2112 auto FFeatures = F.getFnAttribute("target-features");
2113
2114 llvm::StringSet<> MergedNames;
2115 SmallVector<StringRef> MergedFeatures;
2116 MergedFeatures.reserve(TargetOpts.Features.size());
2117
2118 auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
2119 for (StringRef Feature : FeatureRange) {
2120 if (Feature.empty())
2121 continue;
2122 assert(Feature[0] == '+' || Feature[0] == '-');
2123 StringRef Name = Feature.drop_front(1);
2124 bool Merged = !MergedNames.insert(Name).second;
2125 if (!Merged)
2126 MergedFeatures.push_back(Feature);
2127 }
2128 };
2129
2130 if (FFeatures.isValid())
2131 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
2132 AddUnmergedFeatures(TargetOpts.Features);
2133
2134 if (!MergedFeatures.empty()) {
2135 llvm::sort(MergedFeatures);
2136 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
2137 }
2138}
2139
2141 llvm::Function &F, const CodeGenOptions &CodeGenOpts,
2142 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
2143 bool WillInternalize) {
2144
2145 llvm::AttrBuilder FuncAttrs(F.getContext());
2146 // Here we only extract the options that are relevant compared to the version
2147 // from GetCPUAndFeaturesAttributes.
2148 if (!TargetOpts.CPU.empty())
2149 FuncAttrs.addAttribute("target-cpu", TargetOpts.CPU);
2150 if (!TargetOpts.TuneCPU.empty())
2151 FuncAttrs.addAttribute("tune-cpu", TargetOpts.TuneCPU);
2152
2153 ::getTrivialDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
2154 CodeGenOpts, LangOpts,
2155 /*AttrOnCallSite=*/false, FuncAttrs);
2156
2157 if (!WillInternalize && F.isInterposable()) {
2158 // Do not promote "dynamic" denormal-fp-math to this translation unit's
2159 // setting for weak functions that won't be internalized. The user has no
2160 // real control for how builtin bitcode is linked, so we shouldn't assume
2161 // later copies will use a consistent mode.
2162 F.addFnAttrs(FuncAttrs);
2163 return;
2164 }
2165
2166 llvm::AttributeMask AttrsToRemove;
2167
2168 llvm::DenormalMode DenormModeToMerge = F.getDenormalModeRaw();
2169 llvm::DenormalMode DenormModeToMergeF32 = F.getDenormalModeF32Raw();
2170 llvm::DenormalMode Merged =
2171 CodeGenOpts.FPDenormalMode.mergeCalleeMode(DenormModeToMerge);
2172 llvm::DenormalMode MergedF32 = CodeGenOpts.FP32DenormalMode;
2173
2174 if (DenormModeToMergeF32.isValid()) {
2175 MergedF32 =
2176 CodeGenOpts.FP32DenormalMode.mergeCalleeMode(DenormModeToMergeF32);
2177 }
2178
2179 if (Merged == llvm::DenormalMode::getDefault()) {
2180 AttrsToRemove.addAttribute("denormal-fp-math");
2181 } else if (Merged != DenormModeToMerge) {
2182 // Overwrite existing attribute
2183 FuncAttrs.addAttribute("denormal-fp-math",
2184 CodeGenOpts.FPDenormalMode.str());
2185 }
2186
2187 if (MergedF32 == llvm::DenormalMode::getDefault()) {
2188 AttrsToRemove.addAttribute("denormal-fp-math-f32");
2189 } else if (MergedF32 != DenormModeToMergeF32) {
2190 // Overwrite existing attribute
2191 FuncAttrs.addAttribute("denormal-fp-math-f32",
2192 CodeGenOpts.FP32DenormalMode.str());
2193 }
2194
2195 F.removeFnAttrs(AttrsToRemove);
2196 addDenormalModeAttrs(Merged, MergedF32, FuncAttrs);
2197
2198 overrideFunctionFeaturesWithTargetFeatures(FuncAttrs, F, TargetOpts);
2199
2200 F.addFnAttrs(FuncAttrs);
2201}
2202
2203void CodeGenModule::getTrivialDefaultFunctionAttributes(
2204 StringRef Name, bool HasOptnone, bool AttrOnCallSite,
2205 llvm::AttrBuilder &FuncAttrs) {
2206 ::getTrivialDefaultFunctionAttributes(Name, HasOptnone, getCodeGenOpts(),
2207 getLangOpts(), AttrOnCallSite,
2208 FuncAttrs);
2209}
2210
2211void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2212 bool HasOptnone,
2213 bool AttrOnCallSite,
2214 llvm::AttrBuilder &FuncAttrs) {
2215 getTrivialDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite,
2216 FuncAttrs);
2217
2218 if (!AttrOnCallSite)
2219 TargetCodeGenInfo::initPointerAuthFnAttributes(CodeGenOpts.PointerAuth,
2220 FuncAttrs);
2221
2222 // If we're just getting the default, get the default values for mergeable
2223 // attributes.
2224 if (!AttrOnCallSite)
2225 addMergableDefaultFunctionAttributes(CodeGenOpts, FuncAttrs);
2226}
2227
2229 llvm::AttrBuilder &attrs) {
2230 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
2231 /*for call*/ false, attrs);
2232 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
2233}
2234
2235static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
2236 const LangOptions &LangOpts,
2237 const NoBuiltinAttr *NBA = nullptr) {
2238 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2239 SmallString<32> AttributeName;
2240 AttributeName += "no-builtin-";
2241 AttributeName += BuiltinName;
2242 FuncAttrs.addAttribute(AttributeName);
2243 };
2244
2245 // First, handle the language options passed through -fno-builtin.
2246 if (LangOpts.NoBuiltin) {
2247 // -fno-builtin disables them all.
2248 FuncAttrs.addAttribute("no-builtins");
2249 return;
2250 }
2251
2252 // Then, add attributes for builtins specified through -fno-builtin-<name>.
2253 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
2254
2255 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
2256 // the source.
2257 if (!NBA)
2258 return;
2259
2260 // If there is a wildcard in the builtin names specified through the
2261 // attribute, disable them all.
2262 if (llvm::is_contained(NBA->builtinNames(), "*")) {
2263 FuncAttrs.addAttribute("no-builtins");
2264 return;
2265 }
2266
2267 // And last, add the rest of the builtin names.
2268 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2269}
2270
2272 const llvm::DataLayout &DL, const ABIArgInfo &AI,
2273 bool CheckCoerce = true) {
2274 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
2275 if (AI.getKind() == ABIArgInfo::Indirect ||
2277 return true;
2278 if (AI.getKind() == ABIArgInfo::Extend && !AI.isNoExt())
2279 return true;
2280 if (!DL.typeSizeEqualsStoreSize(Ty))
2281 // TODO: This will result in a modest amount of values not marked noundef
2282 // when they could be. We care about values that *invisibly* contain undef
2283 // bits from the perspective of LLVM IR.
2284 return false;
2285 if (CheckCoerce && AI.canHaveCoerceToType()) {
2286 llvm::Type *CoerceTy = AI.getCoerceToType();
2287 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2288 DL.getTypeSizeInBits(Ty)))
2289 // If we're coercing to a type with a greater size than the canonical one,
2290 // we're introducing new undef bits.
2291 // Coercing to a type of smaller or equal size is ok, as we know that
2292 // there's no internal padding (typeSizeEqualsStoreSize).
2293 return false;
2294 }
2295 if (QTy->isBitIntType())
2296 return true;
2297 if (QTy->isReferenceType())
2298 return true;
2299 if (QTy->isNullPtrType())
2300 return false;
2301 if (QTy->isMemberPointerType())
2302 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
2303 // now, never mark them.
2304 return false;
2305 if (QTy->isScalarType()) {
2306 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
2307 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
2308 return true;
2309 }
2310 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
2311 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
2312 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2313 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
2314 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
2315 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
2316
2317 // TODO: Some structs may be `noundef`, in specific situations.
2318 return false;
2319}
2320
2321/// Check if the argument of a function has maybe_undef attribute.
2322static bool IsArgumentMaybeUndef(const Decl *TargetDecl,
2323 unsigned NumRequiredArgs, unsigned ArgNo) {
2324 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2325 if (!FD)
2326 return false;
2327
2328 // Assume variadic arguments do not have maybe_undef attribute.
2329 if (ArgNo >= NumRequiredArgs)
2330 return false;
2331
2332 // Check if argument has maybe_undef attribute.
2333 if (ArgNo < FD->getNumParams()) {
2334 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2335 if (Param && Param->hasAttr<MaybeUndefAttr>())
2336 return true;
2337 }
2338
2339 return false;
2340}
2341
2342/// Test if it's legal to apply nofpclass for the given parameter type and it's
2343/// lowered IR type.
2344static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType,
2345 bool IsReturn) {
2346 // Should only apply to FP types in the source, not ABI promoted.
2347 if (!ParamType->hasFloatingRepresentation())
2348 return false;
2349
2350 // The promoted-to IR type also needs to support nofpclass.
2351 llvm::Type *IRTy = AI.getCoerceToType();
2352 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2353 return true;
2354
2355 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2356 return !IsReturn && AI.getCanBeFlattened() &&
2357 llvm::all_of(ST->elements(),
2358 llvm::AttributeFuncs::isNoFPClassCompatibleType);
2359 }
2360
2361 return false;
2362}
2363
2364/// Return the nofpclass mask that can be applied to floating-point parameters.
2365static llvm::FPClassTest getNoFPClassTestMask(const LangOptions &LangOpts) {
2366 llvm::FPClassTest Mask = llvm::fcNone;
2367 if (LangOpts.NoHonorInfs)
2368 Mask |= llvm::fcInf;
2369 if (LangOpts.NoHonorNaNs)
2370 Mask |= llvm::fcNan;
2371 return Mask;
2372}
2373
2375 CGCalleeInfo CalleeInfo,
2376 llvm::AttributeList &Attrs) {
2377 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2378 Attrs = Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Memory);
2379 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2380 getLLVMContext(), llvm::MemoryEffects::writeOnly());
2381 Attrs = Attrs.addFnAttribute(getLLVMContext(), MemoryAttr);
2382 }
2383}
2384
2385/// Construct the IR attribute list of a function or call.
2386///
2387/// When adding an attribute, please consider where it should be handled:
2388///
2389/// - getDefaultFunctionAttributes is for attributes that are essentially
2390/// part of the global target configuration (but perhaps can be
2391/// overridden on a per-function basis). Adding attributes there
2392/// will cause them to also be set in frontends that build on Clang's
2393/// target-configuration logic, as well as for code defined in library
2394/// modules such as CUDA's libdevice.
2395///
2396/// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
2397/// and adds declaration-specific, convention-specific, and
2398/// frontend-specific logic. The last is of particular importance:
2399/// attributes that restrict how the frontend generates code must be
2400/// added here rather than getDefaultFunctionAttributes.
2401///
2403 const CGFunctionInfo &FI,
2404 CGCalleeInfo CalleeInfo,
2405 llvm::AttributeList &AttrList,
2406 unsigned &CallingConv,
2407 bool AttrOnCallSite, bool IsThunk) {
2408 llvm::AttrBuilder FuncAttrs(getLLVMContext());
2409 llvm::AttrBuilder RetAttrs(getLLVMContext());
2410
2411 // Collect function IR attributes from the CC lowering.
2412 // We'll collect the paramete and result attributes later.
2414 if (FI.isNoReturn())
2415 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2416 if (FI.isCmseNSCall())
2417 FuncAttrs.addAttribute("cmse_nonsecure_call");
2418
2419 // Collect function IR attributes from the callee prototype if we have one.
2421 CalleeInfo.getCalleeFunctionProtoType());
2422 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2423
2424 // Attach assumption attributes to the declaration. If this is a call
2425 // site, attach assumptions from the caller to the call as well.
2426 AddAttributesFromOMPAssumes(FuncAttrs, TargetDecl);
2427
2428 bool HasOptnone = false;
2429 // The NoBuiltinAttr attached to the target FunctionDecl.
2430 const NoBuiltinAttr *NBA = nullptr;
2431
2432 // Some ABIs may result in additional accesses to arguments that may
2433 // otherwise not be present.
2434 std::optional<llvm::Attribute::AttrKind> MemAttrForPtrArgs;
2435 bool AddedPotentialArgAccess = false;
2436 auto AddPotentialArgAccess = [&]() {
2437 AddedPotentialArgAccess = true;
2438 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2439 if (A.isValid())
2440 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2441 llvm::MemoryEffects::argMemOnly());
2442 };
2443
2444 // Collect function IR attributes based on declaration-specific
2445 // information.
2446 // FIXME: handle sseregparm someday...
2447 if (TargetDecl) {
2448 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2449 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2450 if (TargetDecl->hasAttr<NoThrowAttr>())
2451 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2452 if (TargetDecl->hasAttr<NoReturnAttr>())
2453 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2454 if (TargetDecl->hasAttr<ColdAttr>())
2455 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2456 if (TargetDecl->hasAttr<HotAttr>())
2457 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2458 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2459 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2460 if (TargetDecl->hasAttr<ConvergentAttr>())
2461 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2462
2463 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2465 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2466 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2467 // A sane operator new returns a non-aliasing pointer.
2468 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2469 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2470 (Kind == OO_New || Kind == OO_Array_New))
2471 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2472 }
2473 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2474 const bool IsVirtualCall = MD && MD->isVirtual();
2475 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2476 // virtual function. These attributes are not inherited by overloads.
2477 if (!(AttrOnCallSite && IsVirtualCall)) {
2478 if (Fn->isNoReturn())
2479 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2480 NBA = Fn->getAttr<NoBuiltinAttr>();
2481 }
2482 }
2483
2484 if (isa<FunctionDecl>(TargetDecl) || isa<VarDecl>(TargetDecl)) {
2485 // Only place nomerge attribute on call sites, never functions. This
2486 // allows it to work on indirect virtual function calls.
2487 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2488 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2489 }
2490
2491 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2492 if (TargetDecl->hasAttr<ConstAttr>()) {
2493 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2494 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2495 // gcc specifies that 'const' functions have greater restrictions than
2496 // 'pure' functions, so they also cannot have infinite loops.
2497 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2498 MemAttrForPtrArgs = llvm::Attribute::ReadNone;
2499 } else if (TargetDecl->hasAttr<PureAttr>()) {
2500 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2501 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2502 // gcc specifies that 'pure' functions cannot have infinite loops.
2503 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2504 MemAttrForPtrArgs = llvm::Attribute::ReadOnly;
2505 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2506 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2507 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2508 }
2509 if (const auto *RA = TargetDecl->getAttr<RestrictAttr>();
2510 RA && RA->getDeallocator() == nullptr)
2511 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2512 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2513 !CodeGenOpts.NullPointerIsValid)
2514 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2515 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2516 FuncAttrs.addAttribute("no_caller_saved_registers");
2517 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2518 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2519 if (TargetDecl->hasAttr<LeafAttr>())
2520 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2521 if (TargetDecl->hasAttr<BPFFastCallAttr>())
2522 FuncAttrs.addAttribute("bpf_fastcall");
2523
2524 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2525 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2526 std::optional<unsigned> NumElemsParam;
2527 if (AllocSize->getNumElemsParam().isValid())
2528 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2529 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2530 NumElemsParam);
2531 }
2532
2533 if (DeviceKernelAttr::isOpenCLSpelling(
2534 TargetDecl->getAttr<DeviceKernelAttr>()) &&
2537 // Check CallingConv to avoid adding uniform-work-group-size attribute to
2538 // OpenCL Kernel Stub
2539 if (getLangOpts().OpenCLVersion <= 120) {
2540 // OpenCL v1.2 Work groups are always uniform
2541 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2542 } else {
2543 // OpenCL v2.0 Work groups may be whether uniform or not.
2544 // '-cl-uniform-work-group-size' compile option gets a hint
2545 // to the compiler that the global work-size be a multiple of
2546 // the work-group size specified to clEnqueueNDRangeKernel
2547 // (i.e. work groups are uniform).
2548 FuncAttrs.addAttribute(
2549 "uniform-work-group-size",
2550 llvm::toStringRef(getLangOpts().OffloadUniformBlock));
2551 }
2552 }
2553
2554 if (TargetDecl->hasAttr<CUDAGlobalAttr>() &&
2555 getLangOpts().OffloadUniformBlock)
2556 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2557
2558 if (TargetDecl->hasAttr<ArmLocallyStreamingAttr>())
2559 FuncAttrs.addAttribute("aarch64_pstate_sm_body");
2560 }
2561
2562 // Attach "no-builtins" attributes to:
2563 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2564 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2565 // The attributes can come from:
2566 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2567 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2568 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2569
2570 // Collect function IR attributes based on global settiings.
2571 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2572
2573 // Override some default IR attributes based on declaration-specific
2574 // information.
2575 if (TargetDecl) {
2576 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2577 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2578 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2579 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2580 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2581 FuncAttrs.removeAttribute("split-stack");
2582 if (TargetDecl->hasAttr<ZeroCallUsedRegsAttr>()) {
2583 // A function "__attribute__((...))" overrides the command-line flag.
2584 auto Kind =
2585 TargetDecl->getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2586 FuncAttrs.removeAttribute("zero-call-used-regs");
2587 FuncAttrs.addAttribute(
2588 "zero-call-used-regs",
2589 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2590 }
2591
2592 // Add NonLazyBind attribute to function declarations when -fno-plt
2593 // is used.
2594 // FIXME: what if we just haven't processed the function definition
2595 // yet, or if it's an external definition like C99 inline?
2596 if (CodeGenOpts.NoPLT) {
2597 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2598 if (!Fn->isDefined() && !AttrOnCallSite) {
2599 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2600 }
2601 }
2602 }
2603 // Remove 'convergent' if requested.
2604 if (TargetDecl->hasAttr<NoConvergentAttr>())
2605 FuncAttrs.removeAttribute(llvm::Attribute::Convergent);
2606 }
2607
2608 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2609 // functions with -funique-internal-linkage-names.
2610 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2611 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2612 if (!FD->isExternallyVisible())
2613 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2614 "selected");
2615 }
2616 }
2617
2618 // Collect non-call-site function IR attributes from declaration-specific
2619 // information.
2620 if (!AttrOnCallSite) {
2621 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2622 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2623
2624 // Whether tail calls are enabled.
2625 auto shouldDisableTailCalls = [&] {
2626 // Should this be honored in getDefaultFunctionAttributes?
2627 if (CodeGenOpts.DisableTailCalls)
2628 return true;
2629
2630 if (!TargetDecl)
2631 return false;
2632
2633 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2634 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2635 return true;
2636
2637 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2638 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2639 if (!BD->doesNotEscape())
2640 return true;
2641 }
2642
2643 return false;
2644 };
2645 if (shouldDisableTailCalls())
2646 FuncAttrs.addAttribute("disable-tail-calls", "true");
2647
2648 // These functions require the returns_twice attribute for correct codegen,
2649 // but the attribute may not be added if -fno-builtin is specified. We
2650 // explicitly add that attribute here.
2651 static const llvm::StringSet<> ReturnsTwiceFn{
2652 "_setjmpex", "setjmp", "_setjmp", "vfork",
2653 "sigsetjmp", "__sigsetjmp", "savectx", "getcontext"};
2654 if (ReturnsTwiceFn.contains(Name))
2655 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2656
2657 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2658 // handles these separately to set them based on the global defaults.
2659 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2660
2661 // Windows hotpatching support
2662 if (!MSHotPatchFunctions.empty()) {
2663 bool IsHotPatched = llvm::binary_search(MSHotPatchFunctions, Name);
2664 if (IsHotPatched)
2665 FuncAttrs.addAttribute("marked_for_windows_hot_patching");
2666 }
2667 }
2668
2669 // Mark functions that are replaceable by the loader.
2670 if (CodeGenOpts.isLoaderReplaceableFunctionName(Name))
2671 FuncAttrs.addAttribute("loader-replaceable");
2672
2673 // Collect attributes from arguments and return values.
2674 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2675
2676 QualType RetTy = FI.getReturnType();
2677 const ABIArgInfo &RetAI = FI.getReturnInfo();
2678 const llvm::DataLayout &DL = getDataLayout();
2679
2680 // Determine if the return type could be partially undef
2681 if (CodeGenOpts.EnableNoundefAttrs &&
2682 HasStrictReturn(*this, RetTy, TargetDecl)) {
2683 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2684 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2685 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2686 }
2687
2688 switch (RetAI.getKind()) {
2689 case ABIArgInfo::Extend:
2690 if (RetAI.isSignExt())
2691 RetAttrs.addAttribute(llvm::Attribute::SExt);
2692 else if (RetAI.isZeroExt())
2693 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2694 else
2695 RetAttrs.addAttribute(llvm::Attribute::NoExt);
2696 [[fallthrough]];
2698 case ABIArgInfo::Direct:
2699 if (RetAI.getInReg())
2700 RetAttrs.addAttribute(llvm::Attribute::InReg);
2701
2702 if (canApplyNoFPClass(RetAI, RetTy, true))
2703 RetAttrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2704
2705 break;
2706 case ABIArgInfo::Ignore:
2707 break;
2708
2710 case ABIArgInfo::Indirect: {
2711 // inalloca and sret disable readnone and readonly
2712 AddPotentialArgAccess();
2713 break;
2714 }
2715
2717 break;
2718
2719 case ABIArgInfo::Expand:
2721 llvm_unreachable("Invalid ABI kind for return argument");
2722 }
2723
2724 if (!IsThunk) {
2725 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2726 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2727 QualType PTy = RefTy->getPointeeType();
2728 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2729 RetAttrs.addDereferenceableAttr(
2730 getMinimumObjectSize(PTy).getQuantity());
2731 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2732 !CodeGenOpts.NullPointerIsValid)
2733 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2734 if (PTy->isObjectType()) {
2735 llvm::Align Alignment =
2736 getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2737 RetAttrs.addAlignmentAttr(Alignment);
2738 }
2739 }
2740 }
2741
2742 bool hasUsedSRet = false;
2743 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2744
2745 // Attach attributes to sret.
2746 if (IRFunctionArgs.hasSRetArg()) {
2747 llvm::AttrBuilder SRETAttrs(getLLVMContext());
2748 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2749 SRETAttrs.addAttribute(llvm::Attribute::Writable);
2750 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
2751 hasUsedSRet = true;
2752 if (RetAI.getInReg())
2753 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2754 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2755 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2756 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2757 }
2758
2759 // Attach attributes to inalloca argument.
2760 if (IRFunctionArgs.hasInallocaArg()) {
2761 llvm::AttrBuilder Attrs(getLLVMContext());
2762 Attrs.addInAllocaAttr(FI.getArgStruct());
2763 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2764 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2765 }
2766
2767 // Apply `nonnull`, `dereferenceable(N)` and `align N` to the `this` argument,
2768 // unless this is a thunk function.
2769 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2770 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2771 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2772 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2773
2774 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2775
2776 llvm::AttrBuilder Attrs(getLLVMContext());
2777
2778 QualType ThisTy = FI.arg_begin()->type.getTypePtr()->getPointeeType();
2779
2780 if (!CodeGenOpts.NullPointerIsValid &&
2781 getTypes().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2782 Attrs.addAttribute(llvm::Attribute::NonNull);
2783 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2784 } else {
2785 // FIXME dereferenceable should be correct here, regardless of
2786 // NullPointerIsValid. However, dereferenceable currently does not always
2787 // respect NullPointerIsValid and may imply nonnull and break the program.
2788 // See https://reviews.llvm.org/D66618 for discussions.
2789 Attrs.addDereferenceableOrNullAttr(
2792 .getQuantity());
2793 }
2794
2795 llvm::Align Alignment =
2796 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2797 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2798 .getAsAlign();
2799 Attrs.addAlignmentAttr(Alignment);
2800
2801 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2802 }
2803
2804 unsigned ArgNo = 0;
2806 I != E; ++I, ++ArgNo) {
2807 QualType ParamType = I->type;
2808 const ABIArgInfo &AI = I->info;
2809 llvm::AttrBuilder Attrs(getLLVMContext());
2810
2811 // Add attribute for padding argument, if necessary.
2812 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2813 if (AI.getPaddingInReg()) {
2814 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2815 llvm::AttributeSet::get(getLLVMContext(),
2816 llvm::AttrBuilder(getLLVMContext())
2817 .addAttribute(llvm::Attribute::InReg));
2818 }
2819 }
2820
2821 // Decide whether the argument we're handling could be partially undef
2822 if (CodeGenOpts.EnableNoundefAttrs &&
2823 DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
2824 Attrs.addAttribute(llvm::Attribute::NoUndef);
2825 }
2826
2827 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2828 // have the corresponding parameter variable. It doesn't make
2829 // sense to do it here because parameters are so messed up.
2830 switch (AI.getKind()) {
2831 case ABIArgInfo::Extend:
2832 if (AI.isSignExt())
2833 Attrs.addAttribute(llvm::Attribute::SExt);
2834 else if (AI.isZeroExt())
2835 Attrs.addAttribute(llvm::Attribute::ZExt);
2836 else
2837 Attrs.addAttribute(llvm::Attribute::NoExt);
2838 [[fallthrough]];
2840 case ABIArgInfo::Direct:
2841 if (ArgNo == 0 && FI.isChainCall())
2842 Attrs.addAttribute(llvm::Attribute::Nest);
2843 else if (AI.getInReg())
2844 Attrs.addAttribute(llvm::Attribute::InReg);
2845 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2846
2847 if (canApplyNoFPClass(AI, ParamType, false))
2848 Attrs.addNoFPClassAttr(getNoFPClassTestMask(getLangOpts()));
2849 break;
2850 case ABIArgInfo::Indirect: {
2851 if (AI.getInReg())
2852 Attrs.addAttribute(llvm::Attribute::InReg);
2853
2854 // HLSL out and inout parameters must not be marked with ByVal or
2855 // DeadOnReturn attributes because stores to these parameters by the
2856 // callee are visible to the caller.
2857 if (auto ParamABI = FI.getExtParameterInfo(ArgNo).getABI();
2858 ParamABI != ParameterABI::HLSLOut &&
2859 ParamABI != ParameterABI::HLSLInOut) {
2860
2861 // Depending on the ABI, this may be either a byval or a dead_on_return
2862 // argument.
2863 if (AI.getIndirectByVal()) {
2864 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2865 } else {
2866 // Add dead_on_return when the object's lifetime ends in the callee.
2867 // This includes trivially-destructible objects, as well as objects
2868 // whose destruction / clean-up is carried out within the callee
2869 // (e.g., Obj-C ARC-managed structs, MSVC callee-destroyed objects).
2870 if (!ParamType.isDestructedType() || !ParamType->isRecordType() ||
2872 Attrs.addAttribute(llvm::Attribute::DeadOnReturn);
2873 }
2874 }
2875
2876 auto *Decl = ParamType->getAsRecordDecl();
2877 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2878 Decl->getArgPassingRestrictions() ==
2880 // When calling the function, the pointer passed in will be the only
2881 // reference to the underlying object. Mark it accordingly.
2882 Attrs.addAttribute(llvm::Attribute::NoAlias);
2883
2884 // TODO: We could add the byref attribute if not byval, but it would
2885 // require updating many testcases.
2886
2887 CharUnits Align = AI.getIndirectAlign();
2888
2889 // In a byval argument, it is important that the required
2890 // alignment of the type is honored, as LLVM might be creating a
2891 // *new* stack object, and needs to know what alignment to give
2892 // it. (Sometimes it can deduce a sensible alignment on its own,
2893 // but not if clang decides it must emit a packed struct, or the
2894 // user specifies increased alignment requirements.)
2895 //
2896 // This is different from indirect *not* byval, where the object
2897 // exists already, and the align attribute is purely
2898 // informative.
2899 assert(!Align.isZero());
2900
2901 // For now, only add this when we have a byval argument.
2902 // TODO: be less lazy about updating test cases.
2903 if (AI.getIndirectByVal())
2904 Attrs.addAlignmentAttr(Align.getQuantity());
2905
2906 // byval disables readnone and readonly.
2907 AddPotentialArgAccess();
2908 break;
2909 }
2911 CharUnits Align = AI.getIndirectAlign();
2912 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2913 Attrs.addAlignmentAttr(Align.getQuantity());
2914 break;
2915 }
2916 case ABIArgInfo::Ignore:
2917 case ABIArgInfo::Expand:
2919 break;
2920
2922 // inalloca disables readnone and readonly.
2923 AddPotentialArgAccess();
2924 continue;
2925 }
2926
2927 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2928 QualType PTy = RefTy->getPointeeType();
2929 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2930 Attrs.addDereferenceableAttr(getMinimumObjectSize(PTy).getQuantity());
2931 if (getTypes().getTargetAddressSpace(PTy) == 0 &&
2932 !CodeGenOpts.NullPointerIsValid)
2933 Attrs.addAttribute(llvm::Attribute::NonNull);
2934 if (PTy->isObjectType()) {
2935 llvm::Align Alignment =
2936 getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2937 Attrs.addAlignmentAttr(Alignment);
2938 }
2939 }
2940
2941 // From OpenCL spec v3.0.10 section 6.3.5 Alignment of Types:
2942 // > For arguments to a __kernel function declared to be a pointer to a
2943 // > data type, the OpenCL compiler can assume that the pointee is always
2944 // > appropriately aligned as required by the data type.
2945 if (TargetDecl &&
2946 DeviceKernelAttr::isOpenCLSpelling(
2947 TargetDecl->getAttr<DeviceKernelAttr>()) &&
2948 ParamType->isPointerType()) {
2949 QualType PTy = ParamType->getPointeeType();
2950 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2951 llvm::Align Alignment =
2952 getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2953 Attrs.addAlignmentAttr(Alignment);
2954 }
2955 }
2956
2957 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2960 Attrs.addAttribute(llvm::Attribute::NoAlias);
2961 break;
2963 break;
2964
2966 // Add 'sret' if we haven't already used it for something, but
2967 // only if the result is void.
2968 if (!hasUsedSRet && RetTy->isVoidType()) {
2969 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2970 hasUsedSRet = true;
2971 }
2972
2973 // Add 'noalias' in either case.
2974 Attrs.addAttribute(llvm::Attribute::NoAlias);
2975
2976 // Add 'dereferenceable' and 'alignment'.
2977 auto PTy = ParamType->getPointeeType();
2978 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2979 auto info = getContext().getTypeInfoInChars(PTy);
2980 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2981 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2982 }
2983 break;
2984 }
2985
2987 Attrs.addAttribute(llvm::Attribute::SwiftError);
2988 break;
2989
2991 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2992 break;
2993
2995 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2996 break;
2997 }
2998
2999 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
3000 Attrs.addCapturesAttr(llvm::CaptureInfo::none());
3001
3002 if (Attrs.hasAttributes()) {
3003 unsigned FirstIRArg, NumIRArgs;
3004 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3005 for (unsigned i = 0; i < NumIRArgs; i++)
3006 ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
3007 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
3008 }
3009 }
3010 assert(ArgNo == FI.arg_size());
3011
3012 ArgNo = 0;
3013 if (AddedPotentialArgAccess && MemAttrForPtrArgs) {
3014 llvm::FunctionType *FunctionType = getTypes().GetFunctionType(FI);
3016 E = FI.arg_end();
3017 I != E; ++I, ++ArgNo) {
3018 if (I->info.isDirect() || I->info.isExpand() ||
3019 I->info.isCoerceAndExpand()) {
3020 unsigned FirstIRArg, NumIRArgs;
3021 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3022 for (unsigned i = FirstIRArg; i < FirstIRArg + NumIRArgs; ++i) {
3023 if (FunctionType->getParamType(i)->isPointerTy()) {
3024 ArgAttrs[i] =
3025 ArgAttrs[i].addAttribute(getLLVMContext(), *MemAttrForPtrArgs);
3026 }
3027 }
3028 }
3029 }
3030 }
3031
3032 AttrList = llvm::AttributeList::get(
3033 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
3034 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
3035}
3036
3037/// An argument came in as a promoted argument; demote it back to its
3038/// declared type.
3039static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
3040 const VarDecl *var,
3041 llvm::Value *value) {
3042 llvm::Type *varType = CGF.ConvertType(var->getType());
3043
3044 // This can happen with promotions that actually don't change the
3045 // underlying type, like the enum promotions.
3046 if (value->getType() == varType)
3047 return value;
3048
3049 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) &&
3050 "unexpected promotion type");
3051
3052 if (isa<llvm::IntegerType>(varType))
3053 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
3054
3055 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
3056}
3057
3058/// Returns the attribute (either parameter attribute, or function
3059/// attribute), which declares argument ArgNo to be non-null.
3060static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
3061 QualType ArgType, unsigned ArgNo) {
3062 // FIXME: __attribute__((nonnull)) can also be applied to:
3063 // - references to pointers, where the pointee is known to be
3064 // nonnull (apparently a Clang extension)
3065 // - transparent unions containing pointers
3066 // In the former case, LLVM IR cannot represent the constraint. In
3067 // the latter case, we have no guarantee that the transparent union
3068 // is in fact passed as a pointer.
3069 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
3070 return nullptr;
3071 // First, check attribute on parameter itself.
3072 if (PVD) {
3073 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
3074 return ParmNNAttr;
3075 }
3076 // Check function attributes.
3077 if (!FD)
3078 return nullptr;
3079 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
3080 if (NNAttr->isNonNull(ArgNo))
3081 return NNAttr;
3082 }
3083 return nullptr;
3084}
3085
3086namespace {
3087struct CopyBackSwiftError final : EHScopeStack::Cleanup {
3088 Address Temp;
3089 Address Arg;
3090 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
3091 void Emit(CodeGenFunction &CGF, Flags flags) override {
3092 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
3093 CGF.Builder.CreateStore(errorValue, Arg);
3094 }
3095};
3096} // namespace
3097
3099 llvm::Function *Fn,
3100 const FunctionArgList &Args) {
3101 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
3102 // Naked functions don't have prologues.
3103 return;
3104
3105 // If this is an implicit-return-zero function, go ahead and
3106 // initialize the return value. TODO: it might be nice to have
3107 // a more general mechanism for this that didn't require synthesized
3108 // return statements.
3109 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
3110 if (FD->hasImplicitReturnZero()) {
3111 QualType RetTy = FD->getReturnType().getUnqualifiedType();
3112 llvm::Type *LLVMTy = CGM.getTypes().ConvertType(RetTy);
3113 llvm::Constant *Zero = llvm::Constant::getNullValue(LLVMTy);
3114 Builder.CreateStore(Zero, ReturnValue);
3115 }
3116 }
3117
3118 // FIXME: We no longer need the types from FunctionArgList; lift up and
3119 // simplify.
3120
3121 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
3122 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
3123
3124 // If we're using inalloca, all the memory arguments are GEPs off of the last
3125 // parameter, which is a pointer to the complete memory area.
3126 Address ArgStruct = Address::invalid();
3127 if (IRFunctionArgs.hasInallocaArg())
3128 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
3130
3131 // Name the struct return parameter.
3132 if (IRFunctionArgs.hasSRetArg()) {
3133 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
3134 AI->setName("agg.result");
3135 AI->addAttr(llvm::Attribute::NoAlias);
3136 }
3137
3138 // Track if we received the parameter as a pointer (indirect, byval, or
3139 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
3140 // into a local alloca for us.
3142 ArgVals.reserve(Args.size());
3143
3144 // Create a pointer value for every parameter declaration. This usually
3145 // entails copying one or more LLVM IR arguments into an alloca. Don't push
3146 // any cleanups or do anything that might unwind. We do that separately, so
3147 // we can push the cleanups in the correct order for the ABI.
3148 assert(FI.arg_size() == Args.size() &&
3149 "Mismatch between function signature & arguments.");
3150 unsigned ArgNo = 0;
3152 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e;
3153 ++i, ++info_it, ++ArgNo) {
3154 const VarDecl *Arg = *i;
3155 const ABIArgInfo &ArgI = info_it->info;
3156
3157 bool isPromoted =
3158 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
3159 // We are converting from ABIArgInfo type to VarDecl type directly, unless
3160 // the parameter is promoted. In this case we convert to
3161 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
3162 QualType Ty = isPromoted ? info_it->type : Arg->getType();
3163 assert(hasScalarEvaluationKind(Ty) ==
3165
3166 unsigned FirstIRArg, NumIRArgs;
3167 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3168
3169 switch (ArgI.getKind()) {
3170 case ABIArgInfo::InAlloca: {
3171 assert(NumIRArgs == 0);
3172 auto FieldIndex = ArgI.getInAllocaFieldIndex();
3173 Address V =
3174 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
3175 if (ArgI.getInAllocaIndirect())
3176 V = Address(Builder.CreateLoad(V), ConvertTypeForMem(Ty),
3177 getContext().getTypeAlignInChars(Ty));
3178 ArgVals.push_back(ParamValue::forIndirect(V));
3179 break;
3180 }
3181
3184 assert(NumIRArgs == 1);
3186 Fn->getArg(FirstIRArg), Ty, ArgI.getIndirectAlign(), false, nullptr,
3187 nullptr, KnownNonNull);
3188
3189 if (!hasScalarEvaluationKind(Ty)) {
3190 // Aggregates and complex variables are accessed by reference. All we
3191 // need to do is realign the value, if requested. Also, if the address
3192 // may be aliased, copy it to ensure that the parameter variable is
3193 // mutable and has a unique adress, as C requires.
3194 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
3195 RawAddress AlignedTemp = CreateMemTemp(Ty, "coerce");
3196
3197 // Copy from the incoming argument pointer to the temporary with the
3198 // appropriate alignment.
3199 //
3200 // FIXME: We should have a common utility for generating an aggregate
3201 // copy.
3202 CharUnits Size = getContext().getTypeSizeInChars(Ty);
3203 Builder.CreateMemCpy(
3204 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
3205 ParamAddr.emitRawPointer(*this),
3206 ParamAddr.getAlignment().getAsAlign(),
3207 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
3208 ParamAddr = AlignedTemp;
3209 }
3210 ArgVals.push_back(ParamValue::forIndirect(ParamAddr));
3211 } else {
3212 // Load scalar value from indirect argument.
3213 llvm::Value *V =
3214 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
3215
3216 if (isPromoted)
3217 V = emitArgumentDemotion(*this, Arg, V);
3218 ArgVals.push_back(ParamValue::forDirect(V));
3219 }
3220 break;
3221 }
3222
3223 case ABIArgInfo::Extend:
3224 case ABIArgInfo::Direct: {
3225 auto AI = Fn->getArg(FirstIRArg);
3226 llvm::Type *LTy = ConvertType(Arg->getType());
3227
3228 // Prepare parameter attributes. So far, only attributes for pointer
3229 // parameters are prepared. See
3230 // http://llvm.org/docs/LangRef.html#paramattrs.
3231 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
3232 ArgI.getCoerceToType()->isPointerTy()) {
3233 assert(NumIRArgs == 1);
3234
3235 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3236 // Set `nonnull` attribute if any.
3237 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
3238 PVD->getFunctionScopeIndex()) &&
3239 !CGM.getCodeGenOpts().NullPointerIsValid)
3240 AI->addAttr(llvm::Attribute::NonNull);
3241
3242 QualType OTy = PVD->getOriginalType();
3243 if (const auto *ArrTy = getContext().getAsConstantArrayType(OTy)) {
3244 // A C99 array parameter declaration with the static keyword also
3245 // indicates dereferenceability, and if the size is constant we can
3246 // use the dereferenceable attribute (which requires the size in
3247 // bytes).
3248 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3249 QualType ETy = ArrTy->getElementType();
3250 llvm::Align Alignment =
3251 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
3252 AI->addAttrs(llvm::AttrBuilder(getLLVMContext())
3253 .addAlignmentAttr(Alignment));
3254 uint64_t ArrSize = ArrTy->getZExtSize();
3255 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
3256 ArrSize) {
3257 llvm::AttrBuilder Attrs(getLLVMContext());
3258 Attrs.addDereferenceableAttr(
3259 getContext().getTypeSizeInChars(ETy).getQuantity() *
3260 ArrSize);
3261 AI->addAttrs(Attrs);
3262 } else if (getContext().getTargetInfo().getNullPointerValue(
3263 ETy.getAddressSpace()) == 0 &&
3264 !CGM.getCodeGenOpts().NullPointerIsValid) {
3265 AI->addAttr(llvm::Attribute::NonNull);
3266 }
3267 }
3268 } else if (const auto *ArrTy =
3269 getContext().getAsVariableArrayType(OTy)) {
3270 // For C99 VLAs with the static keyword, we don't know the size so
3271 // we can't use the dereferenceable attribute, but in addrspace(0)
3272 // we know that it must be nonnull.
3273 if (ArrTy->getSizeModifier() == ArraySizeModifier::Static) {
3274 QualType ETy = ArrTy->getElementType();
3275 llvm::Align Alignment =
3276 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
3277 AI->addAttrs(llvm::AttrBuilder(getLLVMContext())
3278 .addAlignmentAttr(Alignment));
3279 if (!getTypes().getTargetAddressSpace(ETy) &&
3280 !CGM.getCodeGenOpts().NullPointerIsValid)
3281 AI->addAttr(llvm::Attribute::NonNull);
3282 }
3283 }
3284
3285 // Set `align` attribute if any.
3286 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3287 if (!AVAttr)
3288 if (const auto *TOTy = OTy->getAs<TypedefType>())
3289 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3290 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
3291 // If alignment-assumption sanitizer is enabled, we do *not* add
3292 // alignment attribute here, but emit normal alignment assumption,
3293 // so the UBSAN check could function.
3294 llvm::ConstantInt *AlignmentCI =
3295 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
3296 uint64_t AlignmentInt =
3297 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3298 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3299 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3300 AI->addAttrs(llvm::AttrBuilder(getLLVMContext())
3301 .addAlignmentAttr(llvm::Align(AlignmentInt)));
3302 }
3303 }
3304 }
3305
3306 // Set 'noalias' if an argument type has the `restrict` qualifier.
3307 if (Arg->getType().isRestrictQualified())
3308 AI->addAttr(llvm::Attribute::NoAlias);
3309 }
3310
3311 // Prepare the argument value. If we have the trivial case, handle it
3312 // with no muss and fuss.
3314 ArgI.getCoerceToType() == ConvertType(Ty) &&
3315 ArgI.getDirectOffset() == 0) {
3316 assert(NumIRArgs == 1);
3317
3318 // LLVM expects swifterror parameters to be used in very restricted
3319 // ways. Copy the value into a less-restricted temporary.
3320 llvm::Value *V = AI;
3321 if (FI.getExtParameterInfo(ArgNo).getABI() ==
3323 QualType pointeeTy = Ty->getPointeeType();
3324 assert(pointeeTy->isPointerType());
3325 RawAddress temp =
3326 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3328 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
3329 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
3330 Builder.CreateStore(incomingErrorValue, temp);
3331 V = temp.getPointer();
3332
3333 // Push a cleanup to copy the value back at the end of the function.
3334 // The convention does not guarantee that the value will be written
3335 // back if the function exits with an unwind exception.
3336 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
3337 }
3338
3339 // Ensure the argument is the correct type.
3340 if (V->getType() != ArgI.getCoerceToType())
3341 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
3342
3343 if (isPromoted)
3344 V = emitArgumentDemotion(*this, Arg, V);
3345
3346 // Because of merging of function types from multiple decls it is
3347 // possible for the type of an argument to not match the corresponding
3348 // type in the function type. Since we are codegening the callee
3349 // in here, add a cast to the argument type.
3350 llvm::Type *LTy = ConvertType(Arg->getType());
3351 if (V->getType() != LTy)
3352 V = Builder.CreateBitCast(V, LTy);
3353
3354 ArgVals.push_back(ParamValue::forDirect(V));
3355 break;
3356 }
3357
3358 // VLST arguments are coerced to VLATs at the function boundary for
3359 // ABI consistency. If this is a VLST that was coerced to
3360 // a VLAT at the function boundary and the types match up, use
3361 // llvm.vector.extract to convert back to the original VLST.
3362 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
3363 llvm::Value *ArgVal = Fn->getArg(FirstIRArg);
3364 if (auto *VecTyFrom =
3365 dyn_cast<llvm::ScalableVectorType>(ArgVal->getType())) {
3366 auto [Coerced, Extracted] = CoerceScalableToFixed(
3367 *this, VecTyTo, VecTyFrom, ArgVal, Arg->getName());
3368 if (Extracted) {
3369 assert(NumIRArgs == 1);
3370 ArgVals.push_back(ParamValue::forDirect(Coerced));
3371 break;
3372 }
3373 }
3374 }
3375
3376 llvm::StructType *STy =
3377 dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
3378 Address Alloca =
3379 CreateMemTemp(Ty, getContext().getDeclAlign(Arg), Arg->getName());
3380
3381 // Pointer to store into.
3382 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3383
3384 // Fast-isel and the optimizer generally like scalar values better than
3385 // FCAs, so we flatten them if this is safe to do for this argument.
3386 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
3387 STy->getNumElements() > 1) {
3388 llvm::TypeSize StructSize = CGM.getDataLayout().getTypeAllocSize(STy);
3389 llvm::TypeSize PtrElementSize =
3390 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3391 if (StructSize.isScalable()) {
3392 assert(STy->containsHomogeneousScalableVectorTypes() &&
3393 "ABI only supports structure with homogeneous scalable vector "
3394 "type");
3395 assert(StructSize == PtrElementSize &&
3396 "Only allow non-fractional movement of structure with"
3397 "homogeneous scalable vector type");
3398 assert(STy->getNumElements() == NumIRArgs);
3399
3400 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3401 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3402 auto *AI = Fn->getArg(FirstIRArg + i);
3403 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3404 LoadedStructValue =
3405 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3406 }
3407
3408 Builder.CreateStore(LoadedStructValue, Ptr);
3409 } else {
3410 uint64_t SrcSize = StructSize.getFixedValue();
3411 uint64_t DstSize = PtrElementSize.getFixedValue();
3412
3413 Address AddrToStoreInto = Address::invalid();
3414 if (SrcSize <= DstSize) {
3415 AddrToStoreInto = Ptr.withElementType(STy);
3416 } else {
3417 AddrToStoreInto =
3418 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
3419 }
3420
3421 assert(STy->getNumElements() == NumIRArgs);
3422 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3423 auto AI = Fn->getArg(FirstIRArg + i);
3424 AI->setName(Arg->getName() + ".coerce" + Twine(i));
3425 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
3426 Builder.CreateStore(AI, EltPtr);
3427 }
3428
3429 if (SrcSize > DstSize) {
3430 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3431 }
3432 }
3433 } else {
3434 // Simple case, just do a coerced store of the argument into the alloca.
3435 assert(NumIRArgs == 1);
3436 auto AI = Fn->getArg(FirstIRArg);
3437 AI->setName(Arg->getName() + ".coerce");
3439 AI, Ptr,
3440 llvm::TypeSize::getFixed(
3441 getContext().getTypeSizeInChars(Ty).getQuantity() -
3442 ArgI.getDirectOffset()),
3443 /*DstIsVolatile=*/false);
3444 }
3445
3446 // Match to what EmitParmDecl is expecting for this type.
3448 llvm::Value *V =
3449 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3450 if (isPromoted)
3451 V = emitArgumentDemotion(*this, Arg, V);
3452 ArgVals.push_back(ParamValue::forDirect(V));
3453 } else {
3454 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3455 }
3456 break;
3457 }
3458
3460 // Reconstruct into a temporary.
3461 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3462 ArgVals.push_back(ParamValue::forIndirect(alloca));
3463
3464 auto coercionType = ArgI.getCoerceAndExpandType();
3465 auto unpaddedCoercionType = ArgI.getUnpaddedCoerceAndExpandType();
3466 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
3467
3468 alloca = alloca.withElementType(coercionType);
3469
3470 unsigned argIndex = FirstIRArg;
3471 unsigned unpaddedIndex = 0;
3472 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3473 llvm::Type *eltType = coercionType->getElementType(i);
3475 continue;
3476
3477 auto eltAddr = Builder.CreateStructGEP(alloca, i);
3478 llvm::Value *elt = Fn->getArg(argIndex++);
3479
3480 auto paramType = unpaddedStruct
3481 ? unpaddedStruct->getElementType(unpaddedIndex++)
3482 : unpaddedCoercionType;
3483
3484 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(eltType)) {
3485 if (auto *VecTyFrom = dyn_cast<llvm::ScalableVectorType>(paramType)) {
3486 bool Extracted;
3487 std::tie(elt, Extracted) = CoerceScalableToFixed(
3488 *this, VecTyTo, VecTyFrom, elt, elt->getName());
3489 assert(Extracted && "Unexpected scalable to fixed vector coercion");
3490 }
3491 }
3492 Builder.CreateStore(elt, eltAddr);
3493 }
3494 assert(argIndex == FirstIRArg + NumIRArgs);
3495 break;
3496 }
3497
3498 case ABIArgInfo::Expand: {
3499 // If this structure was expanded into multiple arguments then
3500 // we need to create a temporary and reconstruct it from the
3501 // arguments.
3502 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
3503 LValue LV = MakeAddrLValue(Alloca, Ty);
3504 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3505
3506 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3507 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3508 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3509 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3510 auto AI = Fn->getArg(FirstIRArg + i);
3511 AI->setName(Arg->getName() + "." + Twine(i));
3512 }
3513 break;
3514 }
3515
3517 auto *AI = Fn->getArg(FirstIRArg);
3518 AI->setName(Arg->getName() + ".target_coerce");
3519 Address Alloca =
3520 CreateMemTemp(Ty, getContext().getDeclAlign(Arg), Arg->getName());
3521 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
3522 CGM.getABIInfo().createCoercedStore(AI, Ptr, ArgI, false, *this);
3524 llvm::Value *V =
3525 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
3526 if (isPromoted) {
3527 V = emitArgumentDemotion(*this, Arg, V);
3528 }
3529 ArgVals.push_back(ParamValue::forDirect(V));
3530 } else {
3531 ArgVals.push_back(ParamValue::forIndirect(Alloca));
3532 }
3533 break;
3534 }
3535 case ABIArgInfo::Ignore:
3536 assert(NumIRArgs == 0);
3537 // Initialize the local variable appropriately.
3538 if (!hasScalarEvaluationKind(Ty)) {
3539 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
3540 } else {
3541 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
3542 ArgVals.push_back(ParamValue::forDirect(U));
3543 }
3544 break;
3545 }
3546 }
3547
3548 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3549 for (int I = Args.size() - 1; I >= 0; --I)
3550 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3551 } else {
3552 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3553 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3554 }
3555}
3556
3557static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3558 while (insn->use_empty()) {
3559 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3560 if (!bitcast)
3561 return;
3562
3563 // This is "safe" because we would have used a ConstantExpr otherwise.
3564 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3565 bitcast->eraseFromParent();
3566 }
3567}
3568
3569/// Try to emit a fused autorelease of a return result.
3571 llvm::Value *result) {
3572 // We must be immediately followed the cast.
3573 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3574 if (BB->empty())
3575 return nullptr;
3576 if (&BB->back() != result)
3577 return nullptr;
3578
3579 llvm::Type *resultType = result->getType();
3580
3581 // result is in a BasicBlock and is therefore an Instruction.
3582 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3583
3585
3586 // Look for:
3587 // %generator = bitcast %type1* %generator2 to %type2*
3588 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3589 // We would have emitted this as a constant if the operand weren't
3590 // an Instruction.
3591 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3592
3593 // Require the generator to be immediately followed by the cast.
3594 if (generator->getNextNode() != bitcast)
3595 return nullptr;
3596
3597 InstsToKill.push_back(bitcast);
3598 }
3599
3600 // Look for:
3601 // %generator = call i8* @objc_retain(i8* %originalResult)
3602 // or
3603 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3604 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3605 if (!call)
3606 return nullptr;
3607
3608 bool doRetainAutorelease;
3609
3610 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3611 doRetainAutorelease = true;
3612 } else if (call->getCalledOperand() ==
3614 doRetainAutorelease = false;
3615
3616 // If we emitted an assembly marker for this call (and the
3617 // ARCEntrypoints field should have been set if so), go looking
3618 // for that call. If we can't find it, we can't do this
3619 // optimization. But it should always be the immediately previous
3620 // instruction, unless we needed bitcasts around the call.
3622 llvm::Instruction *prev = call->getPrevNode();
3623 assert(prev);
3624 if (isa<llvm::BitCastInst>(prev)) {
3625 prev = prev->getPrevNode();
3626 assert(prev);
3627 }
3628 assert(isa<llvm::CallInst>(prev));
3629 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3631 InstsToKill.push_back(prev);
3632 }
3633 } else {
3634 return nullptr;
3635 }
3636
3637 result = call->getArgOperand(0);
3638 InstsToKill.push_back(call);
3639
3640 // Keep killing bitcasts, for sanity. Note that we no longer care
3641 // about precise ordering as long as there's exactly one use.
3642 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3643 if (!bitcast->hasOneUse())
3644 break;
3645 InstsToKill.push_back(bitcast);
3646 result = bitcast->getOperand(0);
3647 }
3648
3649 // Delete all the unnecessary instructions, from latest to earliest.
3650 for (auto *I : InstsToKill)
3651 I->eraseFromParent();
3652
3653 // Do the fused retain/autorelease if we were asked to.
3654 if (doRetainAutorelease)
3655 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3656
3657 // Cast back to the result type.
3658 return CGF.Builder.CreateBitCast(result, resultType);
3659}
3660
3661/// If this is a +1 of the value of an immutable 'self', remove it.
3663 llvm::Value *result) {
3664 // This is only applicable to a method with an immutable 'self'.
3665 const ObjCMethodDecl *method =
3666 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3667 if (!method)
3668 return nullptr;
3669 const VarDecl *self = method->getSelfDecl();
3670 if (!self->getType().isConstQualified())
3671 return nullptr;
3672
3673 // Look for a retain call. Note: stripPointerCasts looks through returned arg
3674 // functions, which would cause us to miss the retain.
3675 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
3676 if (!retainCall || retainCall->getCalledOperand() !=
3678 return nullptr;
3679
3680 // Look for an ordinary load of 'self'.
3681 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3682 llvm::LoadInst *load =
3683 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3684 if (!load || load->isAtomic() || load->isVolatile() ||
3685 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getBasePointer())
3686 return nullptr;
3687
3688 // Okay! Burn it all down. This relies for correctness on the
3689 // assumption that the retain is emitted as part of the return and
3690 // that thereafter everything is used "linearly".
3691 llvm::Type *resultType = result->getType();
3693 assert(retainCall->use_empty());
3694 retainCall->eraseFromParent();
3696
3697 return CGF.Builder.CreateBitCast(load, resultType);
3698}
3699
3700/// Emit an ARC autorelease of the result of a function.
3701///
3702/// \return the value to actually return from the function
3704 llvm::Value *result) {
3705 // If we're returning 'self', kill the initial retain. This is a
3706 // heuristic attempt to "encourage correctness" in the really unfortunate
3707 // case where we have a return of self during a dealloc and we desperately
3708 // need to avoid the possible autorelease.
3709 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3710 return self;
3711
3712 // At -O0, try to emit a fused retain/autorelease.
3713 if (CGF.shouldUseFusedARCCalls())
3714 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3715 return fused;
3716
3717 return CGF.EmitARCAutoreleaseReturnValue(result);
3718}
3719
3720/// Heuristically search for a dominating store to the return-value slot.
3722 llvm::Value *ReturnValuePtr = CGF.ReturnValue.getBasePointer();
3723
3724 // Check if a User is a store which pointerOperand is the ReturnValue.
3725 // We are looking for stores to the ReturnValue, not for stores of the
3726 // ReturnValue to some other location.
3727 auto GetStoreIfValid = [&CGF,
3728 ReturnValuePtr](llvm::User *U) -> llvm::StoreInst * {
3729 auto *SI = dyn_cast<llvm::StoreInst>(U);
3730 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
3731 SI->getValueOperand()->getType() != CGF.ReturnValue.getElementType())
3732 return nullptr;
3733 // These aren't actually possible for non-coerced returns, and we
3734 // only care about non-coerced returns on this code path.
3735 // All memory instructions inside __try block are volatile.
3736 assert(!SI->isAtomic() &&
3737 (!SI->isVolatile() || CGF.currentFunctionUsesSEHTry()));
3738 return SI;
3739 };
3740 // If there are multiple uses of the return-value slot, just check
3741 // for something immediately preceding the IP. Sometimes this can
3742 // happen with how we generate implicit-returns; it can also happen
3743 // with noreturn cleanups.
3744 if (!ReturnValuePtr->hasOneUse()) {
3745 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3746 if (IP->empty())
3747 return nullptr;
3748
3749 // Look at directly preceding instruction, skipping bitcasts, lifetime
3750 // markers, and fake uses and their operands.
3751 const llvm::Instruction *LoadIntoFakeUse = nullptr;
3752 for (llvm::Instruction &I : llvm::reverse(*IP)) {
3753 // Ignore instructions that are just loads for fake uses; the load should
3754 // immediately precede the fake use, so we only need to remember the
3755 // operand for the last fake use seen.
3756 if (LoadIntoFakeUse == &I)
3757 continue;
3758 if (isa<llvm::BitCastInst>(&I))
3759 continue;
3760 if (auto *II = dyn_cast<llvm::IntrinsicInst>(&I)) {
3761 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
3762 continue;
3763
3764 if (II->getIntrinsicID() == llvm::Intrinsic::fake_use) {
3765 LoadIntoFakeUse = dyn_cast<llvm::Instruction>(II->getArgOperand(0));
3766 continue;
3767 }
3768 }
3769 return GetStoreIfValid(&I);
3770 }
3771 return nullptr;
3772 }
3773
3774 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
3775 if (!store)
3776 return nullptr;
3777
3778 // Now do a first-and-dirty dominance check: just walk up the
3779 // single-predecessors chain from the current insertion point.
3780 llvm::BasicBlock *StoreBB = store->getParent();
3781 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3783 while (IP != StoreBB) {
3784 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
3785 return nullptr;
3786 }
3787
3788 // Okay, the store's basic block dominates the insertion point; we
3789 // can do our thing.
3790 return store;
3791}
3792
3793// Helper functions for EmitCMSEClearRecord
3794
3795// Set the bits corresponding to a field having width `BitWidth` and located at
3796// offset `BitOffset` (from the least significant bit) within a storage unit of
3797// `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3798// Use little-endian layout, i.e.`Bits[0]` is the LSB.
3799static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3800 int BitWidth, int CharWidth) {
3801 assert(CharWidth <= 64);
3802 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3803
3804 int Pos = 0;
3805 if (BitOffset >= CharWidth) {
3806 Pos += BitOffset / CharWidth;
3807 BitOffset = BitOffset % CharWidth;
3808 }
3809
3810 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3811 if (BitOffset + BitWidth >= CharWidth) {
3812 Bits[Pos++] |= (Used << BitOffset) & Used;
3813 BitWidth -= CharWidth - BitOffset;
3814 BitOffset = 0;
3815 }
3816
3817 while (BitWidth >= CharWidth) {
3818 Bits[Pos++] = Used;
3819 BitWidth -= CharWidth;
3820 }
3821
3822 if (BitWidth > 0)
3823 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3824}
3825
3826// Set the bits corresponding to a field having width `BitWidth` and located at
3827// offset `BitOffset` (from the least significant bit) within a storage unit of
3828// `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3829// `Bits` corresponds to one target byte. Use target endian layout.
3830static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3831 int StorageSize, int BitOffset, int BitWidth,
3832 int CharWidth, bool BigEndian) {
3833
3834 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3835 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3836
3837 if (BigEndian)
3838 std::reverse(TmpBits.begin(), TmpBits.end());
3839
3840 for (uint64_t V : TmpBits)
3841 Bits[StorageOffset++] |= V;
3842}
3843
3844static void setUsedBits(CodeGenModule &, QualType, int,
3845 SmallVectorImpl<uint64_t> &);
3846
3847// Set the bits in `Bits`, which correspond to the value representations of
3848// the actual members of the record type `RTy`. Note that this function does
3849// not handle base classes, virtual tables, etc, since they cannot happen in
3850// CMSE function arguments or return. The bit mask corresponds to the target
3851// memory layout, i.e. it's endian dependent.
3852static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3854 ASTContext &Context = CGM.getContext();
3855 int CharWidth = Context.getCharWidth();
3856 const RecordDecl *RD = RTy->getOriginalDecl()->getDefinition();
3857 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3858 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3859
3860 int Idx = 0;
3861 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3862 const FieldDecl *F = *I;
3863
3864 if (F->isUnnamedBitField() || F->isZeroLengthBitField() ||
3866 continue;
3867
3868 if (F->isBitField()) {
3869 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3870 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3871 BFI.StorageSize / CharWidth, BFI.Offset, BFI.Size, CharWidth,
3872 CGM.getDataLayout().isBigEndian());
3873 continue;
3874 }
3875
3876 setUsedBits(CGM, F->getType(),
3877 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3878 }
3879}
3880
3881// Set the bits in `Bits`, which correspond to the value representations of
3882// the elements of an array type `ATy`.
3883static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3884 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3885 const ASTContext &Context = CGM.getContext();
3886
3887 QualType ETy = Context.getBaseElementType(ATy);
3888 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3889 SmallVector<uint64_t, 4> TmpBits(Size);
3890 setUsedBits(CGM, ETy, 0, TmpBits);
3891
3892 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3893 auto Src = TmpBits.begin();
3894 auto Dst = Bits.begin() + Offset + I * Size;
3895 for (int J = 0; J < Size; ++J)
3896 *Dst++ |= *Src++;
3897 }
3898}
3899
3900// Set the bits in `Bits`, which correspond to the value representations of
3901// the type `QTy`.
3902static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3904 if (const auto *RTy = QTy->getAsCanonical<RecordType>())
3905 return setUsedBits(CGM, RTy, Offset, Bits);
3906
3907 ASTContext &Context = CGM.getContext();
3908 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3909 return setUsedBits(CGM, ATy, Offset, Bits);
3910
3911 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3912 if (Size <= 0)
3913 return;
3914
3915 std::fill_n(Bits.begin() + Offset, Size,
3916 (uint64_t(1) << Context.getCharWidth()) - 1);
3917}
3918
3920 int Pos, int Size, int CharWidth,
3921 bool BigEndian) {
3922 assert(Size > 0);
3923 uint64_t Mask = 0;
3924 if (BigEndian) {
3925 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3926 ++P)
3927 Mask = (Mask << CharWidth) | *P;
3928 } else {
3929 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3930 do
3931 Mask = (Mask << CharWidth) | *--P;
3932 while (P != End);
3933 }
3934 return Mask;
3935}
3936
3937// Emit code to clear the bits in a record, which aren't a part of any user
3938// declared member, when the record is a function return.
3939llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3940 llvm::IntegerType *ITy,
3941 QualType QTy) {
3942 assert(Src->getType() == ITy);
3943 assert(ITy->getScalarSizeInBits() <= 64);
3944
3945 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3946 int Size = DataLayout.getTypeStoreSize(ITy);
3947 SmallVector<uint64_t, 4> Bits(Size);
3948 setUsedBits(CGM, QTy->castAsCanonical<RecordType>(), 0, Bits);
3949
3950 int CharWidth = CGM.getContext().getCharWidth();
3951 uint64_t Mask =
3952 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3953
3954 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3955}
3956
3957// Emit code to clear the bits in a record, which aren't a part of any user
3958// declared member, when the record is a function argument.
3959llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3960 llvm::ArrayType *ATy,
3961 QualType QTy) {
3962 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3963 int Size = DataLayout.getTypeStoreSize(ATy);
3964 SmallVector<uint64_t, 16> Bits(Size);
3965 setUsedBits(CGM, QTy->castAsCanonical<RecordType>(), 0, Bits);
3966
3967 // Clear each element of the LLVM array.
3968 int CharWidth = CGM.getContext().getCharWidth();
3969 int CharsPerElt =
3970 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3971 int MaskIndex = 0;
3972 llvm::Value *R = llvm::PoisonValue::get(ATy);
3973 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3974 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3975 DataLayout.isBigEndian());
3976 MaskIndex += CharsPerElt;
3977 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3978 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3979 R = Builder.CreateInsertValue(R, T1, I);
3980 }
3981
3982 return R;
3983}
3984
3986 const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc,
3987 uint64_t RetKeyInstructionsSourceAtom) {
3988 if (FI.isNoReturn()) {
3989 // Noreturn functions don't return.
3990 EmitUnreachable(EndLoc);
3991 return;
3992 }
3993
3994 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3995 // Naked functions don't have epilogues.
3996 Builder.CreateUnreachable();
3997 return;
3998 }
3999
4000 // Functions with no result always return void.
4001 if (!ReturnValue.isValid()) {
4002 auto *I = Builder.CreateRetVoid();
4003 if (RetKeyInstructionsSourceAtom)
4004 addInstToSpecificSourceAtom(I, nullptr, RetKeyInstructionsSourceAtom);
4005 else
4006 addInstToNewSourceAtom(I, nullptr);
4007 return;
4008 }
4009
4010 llvm::DebugLoc RetDbgLoc;
4011 llvm::Value *RV = nullptr;
4012 QualType RetTy = FI.getReturnType();
4013 const ABIArgInfo &RetAI = FI.getReturnInfo();
4014
4015 switch (RetAI.getKind()) {
4017 // Aggregates get evaluated directly into the destination. Sometimes we
4018 // need to return the sret value in a register, though.
4019 assert(hasAggregateEvaluationKind(RetTy));
4020 if (RetAI.getInAllocaSRet()) {
4021 llvm::Function::arg_iterator EI = CurFn->arg_end();
4022 --EI;
4023 llvm::Value *ArgStruct = &*EI;
4024 llvm::Value *SRet = Builder.CreateStructGEP(
4025 FI.getArgStruct(), ArgStruct, RetAI.getInAllocaFieldIndex());
4026 llvm::Type *Ty =
4027 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
4028 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
4029 }
4030 break;
4031
4032 case ABIArgInfo::Indirect: {
4033 auto AI = CurFn->arg_begin();
4034 if (RetAI.isSRetAfterThis())
4035 ++AI;
4036 switch (getEvaluationKind(RetTy)) {
4037 case TEK_Complex: {
4038 ComplexPairTy RT =
4041 /*isInit*/ true);
4042 break;
4043 }
4044 case TEK_Aggregate:
4045 // Do nothing; aggregates get evaluated directly into the destination.
4046 break;
4047 case TEK_Scalar: {
4048 LValueBaseInfo BaseInfo;
4049 TBAAAccessInfo TBAAInfo;
4050 CharUnits Alignment =
4051 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
4052 Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
4053 LValue ArgVal =
4054 LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
4056 EmitLoadOfScalar(MakeAddrLValue(ReturnValue, RetTy), EndLoc), ArgVal,
4057 /*isInit*/ true);
4058 break;
4059 }
4060 }
4061 break;
4062 }
4063
4064 case ABIArgInfo::Extend:
4065 case ABIArgInfo::Direct:
4066 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
4067 RetAI.getDirectOffset() == 0) {
4068 // The internal return value temp always will have pointer-to-return-type
4069 // type, just do a load.
4070
4071 // If there is a dominating store to ReturnValue, we can elide
4072 // the load, zap the store, and usually zap the alloca.
4073 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
4074 // Reuse the debug location from the store unless there is
4075 // cleanup code to be emitted between the store and return
4076 // instruction.
4077 if (EmitRetDbgLoc && !AutoreleaseResult)
4078 RetDbgLoc = SI->getDebugLoc();
4079 // Get the stored value and nuke the now-dead store.
4080 RV = SI->getValueOperand();
4081 SI->eraseFromParent();
4082
4083 // Otherwise, we have to do a simple load.
4084 } else {
4085 RV = Builder.CreateLoad(ReturnValue);
4086 }
4087 } else {
4088 // If the value is offset in memory, apply the offset now.
4089 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
4090
4091 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
4092 }
4093
4094 // In ARC, end functions that return a retainable type with a call
4095 // to objc_autoreleaseReturnValue.
4096 if (AutoreleaseResult) {
4097#ifndef NDEBUG
4098 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
4099 // been stripped of the typedefs, so we cannot use RetTy here. Get the
4100 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
4101 // CurCodeDecl or BlockInfo.
4102 QualType RT;
4103
4104 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
4105 RT = FD->getReturnType();
4106 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
4107 RT = MD->getReturnType();
4108 else if (isa<BlockDecl>(CurCodeDecl))
4109 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
4110 else
4111 llvm_unreachable("Unexpected function/method type");
4112
4113 assert(getLangOpts().ObjCAutoRefCount && !FI.isReturnsRetained() &&
4114 RT->isObjCRetainableType());
4115#endif
4116 RV = emitAutoreleaseOfResult(*this, RV);
4117 }
4118
4119 break;
4120
4121 case ABIArgInfo::Ignore:
4122 break;
4123
4125 auto coercionType = RetAI.getCoerceAndExpandType();
4126 auto unpaddedCoercionType = RetAI.getUnpaddedCoerceAndExpandType();
4127 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
4128
4129 // Load all of the coerced elements out into results.
4131 Address addr = ReturnValue.withElementType(coercionType);
4132 unsigned unpaddedIndex = 0;
4133 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4134 auto coercedEltType = coercionType->getElementType(i);
4135 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
4136 continue;
4137
4138 auto eltAddr = Builder.CreateStructGEP(addr, i);
4139 llvm::Value *elt = CreateCoercedLoad(
4140 eltAddr,
4141 unpaddedStruct ? unpaddedStruct->getElementType(unpaddedIndex++)
4142 : unpaddedCoercionType,
4143 *this);
4144 results.push_back(elt);
4145 }
4146
4147 // If we have one result, it's the single direct result type.
4148 if (results.size() == 1) {
4149 RV = results[0];
4150
4151 // Otherwise, we need to make a first-class aggregate.
4152 } else {
4153 // Construct a return type that lacks padding elements.
4154 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
4155
4156 RV = llvm::PoisonValue::get(returnType);
4157 for (unsigned i = 0, e = results.size(); i != e; ++i) {
4158 RV = Builder.CreateInsertValue(RV, results[i], i);
4159 }
4160 }
4161 break;
4162 }
4164 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
4165 RV = CGM.getABIInfo().createCoercedLoad(V, RetAI, *this);
4166 break;
4167 }
4168 case ABIArgInfo::Expand:
4170 llvm_unreachable("Invalid ABI kind for return argument");
4171 }
4172
4173 llvm::Instruction *Ret;
4174 if (RV) {
4175 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
4176 // For certain return types, clear padding bits, as they may reveal
4177 // sensitive information.
4178 // Small struct/union types are passed as integers.
4179 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
4180 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
4181 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
4182 }
4184 Ret = Builder.CreateRet(RV);
4185 } else {
4186 Ret = Builder.CreateRetVoid();
4187 }
4188
4189 if (RetDbgLoc)
4190 Ret->setDebugLoc(std::move(RetDbgLoc));
4191
4192 llvm::Value *Backup = RV ? Ret->getOperand(0) : nullptr;
4193 if (RetKeyInstructionsSourceAtom)
4194 addInstToSpecificSourceAtom(Ret, Backup, RetKeyInstructionsSourceAtom);
4195 else
4196 addInstToNewSourceAtom(Ret, Backup);
4197}
4198
4200 // A current decl may not be available when emitting vtable thunks.
4201 if (!CurCodeDecl)
4202 return;
4203
4204 // If the return block isn't reachable, neither is this check, so don't emit
4205 // it.
4206 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
4207 return;
4208
4209 ReturnsNonNullAttr *RetNNAttr = nullptr;
4210 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4211 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4212
4213 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4214 return;
4215
4216 // Prefer the returns_nonnull attribute if it's present.
4217 SourceLocation AttrLoc;
4219 SanitizerHandler Handler;
4220 if (RetNNAttr) {
4221 assert(!requiresReturnValueNullabilityCheck() &&
4222 "Cannot check nullability and the nonnull attribute");
4223 AttrLoc = RetNNAttr->getLocation();
4224 CheckKind = SanitizerKind::SO_ReturnsNonnullAttribute;
4225 Handler = SanitizerHandler::NonnullReturn;
4226 } else {
4227 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
4228 if (auto *TSI = DD->getTypeSourceInfo())
4229 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
4230 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4231 CheckKind = SanitizerKind::SO_NullabilityReturn;
4232 Handler = SanitizerHandler::NullabilityReturn;
4233 }
4234
4235 SanitizerDebugLocation SanScope(this, {CheckKind}, Handler);
4236
4237 // Make sure the "return" source location is valid. If we're checking a
4238 // nullability annotation, make sure the preconditions for the check are met.
4239 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
4240 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
4241 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
4242 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
4243 if (requiresReturnValueNullabilityCheck())
4244 CanNullCheck =
4245 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4246 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4247 EmitBlock(Check);
4248
4249 // Now do the null check.
4250 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
4251 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
4252 llvm::Value *DynamicData[] = {SLocPtr};
4253 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4254
4255 EmitBlock(NoCheck);
4256
4257#ifndef NDEBUG
4258 // The return location should not be used after the check has been emitted.
4259 ReturnLocation = Address::invalid();
4260#endif
4261}
4262
4264 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
4265 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
4266}
4267
4269 // FIXME: Generate IR in one pass, rather than going back and fixing up these
4270 // placeholders.
4271 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
4272 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
4273 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4274
4275 // FIXME: When we generate this IR in one pass, we shouldn't need
4276 // this win32-specific alignment hack.
4278 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
4279
4280 return AggValueSlot::forAddr(
4281 Address(Placeholder, IRTy, Align), Ty.getQualifiers(),
4284}
4285
4287 const VarDecl *param,
4288 SourceLocation loc) {
4289 // StartFunction converted the ABI-lowered parameter(s) into a
4290 // local alloca. We need to turn that into an r-value suitable
4291 // for EmitCall.
4292 Address local = GetAddrOfLocalVar(param);
4293
4294 QualType type = param->getType();
4295
4296 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
4297 // but the argument needs to be the original pointer.
4298 if (type->isReferenceType()) {
4299 args.add(RValue::get(Builder.CreateLoad(local)), type);
4300
4301 // In ARC, move out of consumed arguments so that the release cleanup
4302 // entered by StartFunction doesn't cause an over-release. This isn't
4303 // optimal -O0 code generation, but it should get cleaned up when
4304 // optimization is enabled. This also assumes that delegate calls are
4305 // performed exactly once for a set of arguments, but that should be safe.
4306 } else if (getLangOpts().ObjCAutoRefCount &&
4307 param->hasAttr<NSConsumedAttr>() && type->isObjCRetainableType()) {
4308 llvm::Value *ptr = Builder.CreateLoad(local);
4309 auto null =
4310 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
4311 Builder.CreateStore(null, local);
4312 args.add(RValue::get(ptr), type);
4313
4314 // For the most part, we just need to load the alloca, except that
4315 // aggregate r-values are actually pointers to temporaries.
4316 } else {
4317 args.add(convertTempToRValue(local, type, loc), type);
4318 }
4319
4320 // Deactivate the cleanup for the callee-destructed param that was pushed.
4321 if (type->isRecordType() && !CurFuncIsThunk &&
4322 type->castAsRecordDecl()->isParamDestroyedInCallee() &&
4323 param->needsDestruction(getContext())) {
4325 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
4326 assert(cleanup.isValid() &&
4327 "cleanup for callee-destructed param not recorded");
4328 // This unreachable is a temporary marker which will be removed later.
4329 llvm::Instruction *isActive = Builder.CreateUnreachable();
4330 args.addArgCleanupDeactivation(cleanup, isActive);
4331 }
4332}
4333
4334static bool isProvablyNull(llvm::Value *addr) {
4335 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4336}
4337
4339 return llvm::isKnownNonZero(Addr.getBasePointer(), CGF.CGM.getDataLayout());
4340}
4341
4342/// Emit the actual writing-back of a writeback.
4344 const CallArgList::Writeback &writeback) {
4345 const LValue &srcLV = writeback.Source;
4346 Address srcAddr = srcLV.getAddress();
4347 assert(!isProvablyNull(srcAddr.getBasePointer()) &&
4348 "shouldn't have writeback for provably null argument");
4349
4350 if (writeback.WritebackExpr) {
4351 CGF.EmitIgnoredExpr(writeback.WritebackExpr);
4352 CGF.EmitLifetimeEnd(writeback.Temporary.getBasePointer());
4353 return;
4354 }
4355
4356 llvm::BasicBlock *contBB = nullptr;
4357
4358 // If the argument wasn't provably non-null, we need to null check
4359 // before doing the store.
4360 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4361
4362 if (!provablyNonNull) {
4363 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
4364 contBB = CGF.createBasicBlock("icr.done");
4365
4366 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4367 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
4368 CGF.EmitBlock(writebackBB);
4369 }
4370
4371 // Load the value to writeback.
4372 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
4373
4374 // Cast it back, in case we're writing an id to a Foo* or something.
4375 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
4376 "icr.writeback-cast");
4377
4378 // Perform the writeback.
4379
4380 // If we have a "to use" value, it's something we need to emit a use
4381 // of. This has to be carefully threaded in: if it's done after the
4382 // release it's potentially undefined behavior (and the optimizer
4383 // will ignore it), and if it happens before the retain then the
4384 // optimizer could move the release there.
4385 if (writeback.ToUse) {
4386 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
4387
4388 // Retain the new value. No need to block-copy here: the block's
4389 // being passed up the stack.
4390 value = CGF.EmitARCRetainNonBlock(value);
4391
4392 // Emit the intrinsic use here.
4393 CGF.EmitARCIntrinsicUse(writeback.ToUse);
4394
4395 // Load the old value (primitively).
4396 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
4397
4398 // Put the new value in place (primitively).
4399 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
4400
4401 // Release the old value.
4402 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
4403
4404 // Otherwise, we can just do a normal lvalue store.
4405 } else {
4406 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
4407 }
4408
4409 // Jump to the continuation block.
4410 if (!provablyNonNull)
4411 CGF.EmitBlock(contBB);
4412}
4413
4415 const CallArgList &CallArgs) {
4417 CallArgs.getCleanupsToDeactivate();
4418 // Iterate in reverse to increase the likelihood of popping the cleanup.
4419 for (const auto &I : llvm::reverse(Cleanups)) {
4420 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
4421 I.IsActiveIP->eraseFromParent();
4422 }
4423}
4424
4425static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
4426 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
4427 if (uop->getOpcode() == UO_AddrOf)
4428 return uop->getSubExpr();
4429 return nullptr;
4430}
4431
4432/// Emit an argument that's being passed call-by-writeback. That is,
4433/// we are passing the address of an __autoreleased temporary; it
4434/// might be copy-initialized with the current value of the given
4435/// address, but it will definitely be copied out of after the call.
4437 const ObjCIndirectCopyRestoreExpr *CRE) {
4438 LValue srcLV;
4439
4440 // Make an optimistic effort to emit the address as an l-value.
4441 // This can fail if the argument expression is more complicated.
4442 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
4443 srcLV = CGF.EmitLValue(lvExpr);
4444
4445 // Otherwise, just emit it as a scalar.
4446 } else {
4447 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
4448
4449 QualType srcAddrType =
4451 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
4452 }
4453 Address srcAddr = srcLV.getAddress();
4454
4455 // The dest and src types don't necessarily match in LLVM terms
4456 // because of the crazy ObjC compatibility rules.
4457
4458 llvm::PointerType *destType =
4460 llvm::Type *destElemType =
4462
4463 // If the address is a constant null, just pass the appropriate null.
4464 if (isProvablyNull(srcAddr.getBasePointer())) {
4465 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
4466 CRE->getType());
4467 return;
4468 }
4469
4470 // Create the temporary.
4471 Address temp =
4472 CGF.CreateTempAlloca(destElemType, CGF.getPointerAlign(), "icr.temp");
4473 // Loading an l-value can introduce a cleanup if the l-value is __weak,
4474 // and that cleanup will be conditional if we can't prove that the l-value
4475 // isn't null, so we need to register a dominating point so that the cleanups
4476 // system will make valid IR.
4478
4479 // Zero-initialize it if we're not doing a copy-initialization.
4480 bool shouldCopy = CRE->shouldCopy();
4481 if (!shouldCopy) {
4482 llvm::Value *null =
4483 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destElemType));
4484 CGF.Builder.CreateStore(null, temp);
4485 }
4486
4487 llvm::BasicBlock *contBB = nullptr;
4488 llvm::BasicBlock *originBB = nullptr;
4489
4490 // If the address is *not* known to be non-null, we need to switch.
4491 llvm::Value *finalArgument;
4492
4493 bool provablyNonNull = isProvablyNonNull(srcAddr, CGF);
4494
4495 if (provablyNonNull) {
4496 finalArgument = temp.emitRawPointer(CGF);
4497 } else {
4498 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
4499
4500 finalArgument = CGF.Builder.CreateSelect(
4501 isNull, llvm::ConstantPointerNull::get(destType),
4502 temp.emitRawPointer(CGF), "icr.argument");
4503
4504 // If we need to copy, then the load has to be conditional, which
4505 // means we need control flow.
4506 if (shouldCopy) {
4507 originBB = CGF.Builder.GetInsertBlock();
4508 contBB = CGF.createBasicBlock("icr.cont");
4509 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
4510 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
4511 CGF.EmitBlock(copyBB);
4512 condEval.begin(CGF);
4513 }
4514 }
4515
4516 llvm::Value *valueToUse = nullptr;
4517
4518 // Perform a copy if necessary.
4519 if (shouldCopy) {
4520 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
4521 assert(srcRV.isScalar());
4522
4523 llvm::Value *src = srcRV.getScalarVal();
4524 src = CGF.Builder.CreateBitCast(src, destElemType, "icr.cast");
4525
4526 // Use an ordinary store, not a store-to-lvalue.
4527 CGF.Builder.CreateStore(src, temp);
4528
4529 // If optimization is enabled, and the value was held in a
4530 // __strong variable, we need to tell the optimizer that this
4531 // value has to stay alive until we're doing the store back.
4532 // This is because the temporary is effectively unretained,
4533 // and so otherwise we can violate the high-level semantics.
4534 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4535 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
4536 valueToUse = src;
4537 }
4538 }
4539
4540 // Finish the control flow if we needed it.
4541 if (shouldCopy && !provablyNonNull) {
4542 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
4543 CGF.EmitBlock(contBB);
4544
4545 // Make a phi for the value to intrinsically use.
4546 if (valueToUse) {
4547 llvm::PHINode *phiToUse =
4548 CGF.Builder.CreatePHI(valueToUse->getType(), 2, "icr.to-use");
4549 phiToUse->addIncoming(valueToUse, copyBB);
4550 phiToUse->addIncoming(llvm::PoisonValue::get(valueToUse->getType()),
4551 originBB);
4552 valueToUse = phiToUse;
4553 }
4554
4555 condEval.end(CGF);
4556 }
4557
4558 args.addWriteback(srcLV, temp, valueToUse);
4559 args.add(RValue::get(finalArgument), CRE->getType());
4560}
4561
4563 assert(!StackBase);
4564
4565 // Save the stack.
4566 StackBase = CGF.Builder.CreateStackSave("inalloca.save");
4567}
4568
4570 if (StackBase) {
4571 // Restore the stack after the call.
4572 CGF.Builder.CreateStackRestore(StackBase);
4573 }
4574}
4575
4577 SourceLocation ArgLoc,
4578 AbstractCallee AC, unsigned ParmNum) {
4579 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4580 SanOpts.has(SanitizerKind::NullabilityArg)))
4581 return;
4582
4583 // The param decl may be missing in a variadic function.
4584 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
4585 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4586
4587 // Prefer the nonnull attribute if it's present.
4588 const NonNullAttr *NNAttr = nullptr;
4589 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4590 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4591
4592 bool CanCheckNullability = false;
4593 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4594 !PVD->getType()->isRecordType()) {
4595 auto Nullability = PVD->getType()->getNullability();
4596 CanCheckNullability = Nullability &&
4597 *Nullability == NullabilityKind::NonNull &&
4598 PVD->getTypeSourceInfo();
4599 }
4600
4601 if (!NNAttr && !CanCheckNullability)
4602 return;
4603
4604 SourceLocation AttrLoc;
4606 SanitizerHandler Handler;
4607 if (NNAttr) {
4608 AttrLoc = NNAttr->getLocation();
4609 CheckKind = SanitizerKind::SO_NonnullAttribute;
4610 Handler = SanitizerHandler::NonnullArg;
4611 } else {
4612 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4613 CheckKind = SanitizerKind::SO_NullabilityArg;
4614 Handler = SanitizerHandler::NullabilityArg;
4615 }
4616
4617 SanitizerDebugLocation SanScope(this, {CheckKind}, Handler);
4618 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4619 llvm::Constant *StaticData[] = {
4621 EmitCheckSourceLocation(AttrLoc),
4622 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4623 };
4624 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, {});
4625}
4626
4628 SourceLocation ArgLoc,
4629 AbstractCallee AC, unsigned ParmNum) {
4630 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
4631 SanOpts.has(SanitizerKind::NullabilityArg)))
4632 return;
4633
4634 EmitNonNullArgCheck(RValue::get(Addr, *this), ArgType, ArgLoc, AC, ParmNum);
4635}
4636
4637// Check if the call is going to use the inalloca convention. This needs to
4638// agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4639// later, so we can't check it directly.
4640static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4641 ArrayRef<QualType> ArgTypes) {
4642 // The Swift calling conventions don't go through the target-specific
4643 // argument classification, they never use inalloca.
4644 // TODO: Consider limiting inalloca use to only calling conventions supported
4645 // by MSVC.
4646 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4647 return false;
4648 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4649 return false;
4650 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4651 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4652 });
4653}
4654
4655#ifndef NDEBUG
4656// Determine whether the given argument is an Objective-C method
4657// that may have type parameters in its signature.
4658static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4659 const DeclContext *dc = method->getDeclContext();
4660 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4661 return classDecl->getTypeParamListAsWritten();
4662 }
4663
4664 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4665 return catDecl->getTypeParamList();
4666 }
4667
4668 return false;
4669}
4670#endif
4671
4672/// EmitCallArgs - Emit call arguments for a function.
4675 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4676 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4678
4679 assert((ParamsToSkip == 0 || Prototype.P) &&
4680 "Can't skip parameters if type info is not provided");
4681
4682 // This variable only captures *explicitly* written conventions, not those
4683 // applied by default via command line flags or target defaults, such as
4684 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4685 // require knowing if this is a C++ instance method or being able to see
4686 // unprototyped FunctionTypes.
4687 CallingConv ExplicitCC = CC_C;
4688
4689 // First, if a prototype was provided, use those argument types.
4690 bool IsVariadic = false;
4691 if (Prototype.P) {
4692 const auto *MD = dyn_cast<const ObjCMethodDecl *>(Prototype.P);
4693 if (MD) {
4694 IsVariadic = MD->isVariadic();
4695 ExplicitCC = getCallingConventionForDecl(
4696 MD, CGM.getTarget().getTriple().isOSWindows());
4697 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4698 MD->param_type_end());
4699 } else {
4700 const auto *FPT = cast<const FunctionProtoType *>(Prototype.P);
4701 IsVariadic = FPT->isVariadic();
4702 ExplicitCC = FPT->getExtInfo().getCC();
4703 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4704 FPT->param_type_end());
4705 }
4706
4707#ifndef NDEBUG
4708 // Check that the prototyped types match the argument expression types.
4709 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4710 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4711 for (QualType Ty : ArgTypes) {
4712 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4713 assert(
4714 (isGenericMethod || Ty->isVariablyModifiedType() ||
4716 getContext()
4717 .getCanonicalType(Ty.getNonReferenceType())
4718 .getTypePtr() ==
4719 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4720 "type mismatch in call argument!");
4721 ++Arg;
4722 }
4723
4724 // Either we've emitted all the call args, or we have a call to variadic
4725 // function.
4726 assert((Arg == ArgRange.end() || IsVariadic) &&
4727 "Extra arguments in non-variadic function!");
4728#endif
4729 }
4730
4731 // If we still have any arguments, emit them using the type of the argument.
4732 for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
4733 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4734 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4735
4736 // We must evaluate arguments from right to left in the MS C++ ABI,
4737 // because arguments are destroyed left to right in the callee. As a special
4738 // case, there are certain language constructs that require left-to-right
4739 // evaluation, and in those cases we consider the evaluation order requirement
4740 // to trump the "destruction order is reverse construction order" guarantee.
4741 bool LeftToRight =
4742 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4745
4746 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4747 RValue EmittedArg) {
4748 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4749 return;
4750 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4751 if (PS == nullptr)
4752 return;
4753
4754 const auto &Context = getContext();
4755 auto SizeTy = Context.getSizeType();
4756 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4757 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4758 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(
4759 Arg, PS->getType(), T, EmittedArg.getScalarVal(), PS->isDynamic());
4760 Args.add(RValue::get(V), SizeTy);
4761 // If we're emitting args in reverse, be sure to do so with
4762 // pass_object_size, as well.
4763 if (!LeftToRight)
4764 std::swap(Args.back(), *(&Args.back() - 1));
4765 };
4766
4767 // Insert a stack save if we're going to need any inalloca args.
4768 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4769 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4770 "inalloca only supported on x86");
4771 Args.allocateArgumentMemory(*this);
4772 }
4773
4774 // Evaluate each argument in the appropriate order.
4775 size_t CallArgsStart = Args.size();
4776 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4777 unsigned Idx = LeftToRight ? I : E - I - 1;
4778 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4779 unsigned InitialArgSize = Args.size();
4780 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4781 // the argument and parameter match or the objc method is parameterized.
4782 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4783 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4784 ArgTypes[Idx]) ||
4787 "Argument and parameter types don't match");
4788 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4789 // In particular, we depend on it being the last arg in Args, and the
4790 // objectsize bits depend on there only being one arg if !LeftToRight.
4791 assert(InitialArgSize + 1 == Args.size() &&
4792 "The code below depends on only adding one arg per EmitCallArg");
4793 (void)InitialArgSize;
4794 // Since pointer argument are never emitted as LValue, it is safe to emit
4795 // non-null argument check for r-value only.
4796 if (!Args.back().hasLValue()) {
4797 RValue RVArg = Args.back().getKnownRValue();
4798 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4799 ParamsToSkip + Idx);
4800 // @llvm.objectsize should never have side-effects and shouldn't need
4801 // destruction/cleanups, so we can safely "emit" it after its arg,
4802 // regardless of right-to-leftness
4803 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4804 }
4805 }
4806
4807 if (!LeftToRight) {
4808 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4809 // IR function.
4810 std::reverse(Args.begin() + CallArgsStart, Args.end());
4811
4812 // Reverse the writebacks to match the MSVC ABI.
4813 Args.reverseWritebacks();
4814 }
4815}
4816
4817namespace {
4818
4819struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
4820 DestroyUnpassedArg(Address Addr, QualType Ty) : Addr(Addr), Ty(Ty) {}
4821
4822 Address Addr;
4823 QualType Ty;
4824
4825 void Emit(CodeGenFunction &CGF, Flags flags) override {
4827 if (DtorKind == QualType::DK_cxx_destructor) {
4828 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4829 assert(!Dtor->isTrivial());
4830 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4831 /*Delegating=*/false, Addr, Ty);
4832 } else {
4834 }
4835 }
4836};
4837
4838} // end anonymous namespace
4839
4841 if (!HasLV)
4842 return RV;
4845 LV.isVolatile());
4846 IsUsed = true;
4847 return RValue::getAggregate(Copy.getAddress());
4848}
4849
4851 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4852 if (!HasLV && RV.isScalar())
4853 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4854 else if (!HasLV && RV.isComplex())
4855 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4856 else {
4857 auto Addr = HasLV ? LV.getAddress() : RV.getAggregateAddress();
4858 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4859 // We assume that call args are never copied into subobjects.
4861 HasLV ? LV.isVolatileQualified()
4862 : RV.isVolatileQualified());
4863 }
4864 IsUsed = true;
4865}
4866
4868 for (const auto &I : args.writebacks())
4869 emitWriteback(*this, I);
4870}
4871
4873 QualType type) {
4874 std::optional<DisableDebugLocationUpdates> Dis;
4876 Dis.emplace(*this);
4877 if (const ObjCIndirectCopyRestoreExpr *CRE =
4878 dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4879 assert(getLangOpts().ObjCAutoRefCount);
4880 return emitWritebackArg(*this, args, CRE);
4881 }
4882
4883 // Add writeback for HLSLOutParamExpr.
4884 // Needs to be before the assert below because HLSLOutArgExpr is an LValue
4885 // and is not a reference.
4886 if (const HLSLOutArgExpr *OE = dyn_cast<HLSLOutArgExpr>(E)) {
4887 EmitHLSLOutArgExpr(OE, args, type);
4888 return;
4889 }
4890
4891 assert(type->isReferenceType() == E->isGLValue() &&
4892 "reference binding to unmaterialized r-value!");
4893
4894 if (E->isGLValue()) {
4895 assert(E->getObjectKind() == OK_Ordinary);
4896 return args.add(EmitReferenceBindingToExpr(E), type);
4897 }
4898
4899 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4900
4901 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4902 // However, we still have to push an EH-only cleanup in case we unwind before
4903 // we make it to the call.
4904 if (type->isRecordType() &&
4905 type->castAsRecordDecl()->isParamDestroyedInCallee()) {
4906 // If we're using inalloca, use the argument memory. Otherwise, use a
4907 // temporary.
4908 AggValueSlot Slot = args.isUsingInAlloca()
4909 ? createPlaceholderSlot(*this, type)
4910 : CreateAggTemp(type, "agg.tmp");
4911
4912 bool DestroyedInCallee = true, NeedsCleanup = true;
4913 if (const auto *RD = type->getAsCXXRecordDecl())
4914 DestroyedInCallee = RD->hasNonTrivialDestructor();
4915 else
4916 NeedsCleanup = type.isDestructedType();
4917
4918 if (DestroyedInCallee)
4920
4921 EmitAggExpr(E, Slot);
4922 RValue RV = Slot.asRValue();
4923 args.add(RV, type);
4924
4925 if (DestroyedInCallee && NeedsCleanup) {
4926 // Create a no-op GEP between the placeholder and the cleanup so we can
4927 // RAUW it successfully. It also serves as a marker of the first
4928 // instruction where the cleanup is active.
4930 Slot.getAddress(), type);
4931 // This unreachable is a temporary marker which will be removed later.
4932 llvm::Instruction *IsActive =
4933 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
4934 args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
4935 }
4936 return;
4937 }
4938
4939 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4940 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue &&
4941 !type->isArrayParameterType() && !type.isNonTrivialToPrimitiveCopy()) {
4942 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4943 assert(L.isSimple());
4944 args.addUncopiedAggregate(L, type);
4945 return;
4946 }
4947
4948 args.add(EmitAnyExprToTemp(E), type);
4949}
4950
4951QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4952 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4953 // implicitly widens null pointer constants that are arguments to varargs
4954 // functions to pointer-sized ints.
4955 if (!getTarget().getTriple().isOSWindows())
4956 return Arg->getType();
4957
4958 if (Arg->getType()->isIntegerType() &&
4959 getContext().getTypeSize(Arg->getType()) <
4960 getContext().getTargetInfo().getPointerWidth(LangAS::Default) &&
4961 Arg->isNullPointerConstant(getContext(),
4963 return getContext().getIntPtrType();
4964 }
4965
4966 return Arg->getType();
4967}
4968
4969// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4970// optimizer it can aggressively ignore unwind edges.
4971void CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4972 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4973 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4974 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4975 CGM.getNoObjCARCExceptionsMetadata());
4976}
4977
4978/// Emits a call to the given no-arguments nounwind runtime function.
4979llvm::CallInst *
4980CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4981 const llvm::Twine &name) {
4982 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
4983}
4984
4985/// Emits a call to the given nounwind runtime function.
4986llvm::CallInst *
4987CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4988 ArrayRef<Address> args,
4989 const llvm::Twine &name) {
4990 SmallVector<llvm::Value *, 3> values;
4991 for (auto arg : args)
4992 values.push_back(arg.emitRawPointer(*this));
4993 return EmitNounwindRuntimeCall(callee, values, name);
4994}
4995
4996llvm::CallInst *
4997CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4998 ArrayRef<llvm::Value *> args,
4999 const llvm::Twine &name) {
5000 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
5001 call->setDoesNotThrow();
5002 return call;
5003}
5004
5005/// Emits a simple call (never an invoke) to the given no-arguments
5006/// runtime function.
5007llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
5008 const llvm::Twine &name) {
5009 return EmitRuntimeCall(callee, {}, name);
5010}
5011
5012// Calls which may throw must have operand bundles indicating which funclet
5013// they are nested within.
5014SmallVector<llvm::OperandBundleDef, 1>
5016 // There is no need for a funclet operand bundle if we aren't inside a
5017 // funclet.
5018 if (!CurrentFuncletPad)
5020
5021 // Skip intrinsics which cannot throw (as long as they don't lower into
5022 // regular function calls in the course of IR transformations).
5023 if (auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
5024 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
5025 auto IID = CalleeFn->getIntrinsicID();
5026 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
5028 }
5029 }
5030
5032 BundleList.emplace_back("funclet", CurrentFuncletPad);
5033 return BundleList;
5034}
5035
5036/// Emits a simple call (never an invoke) to the given runtime function.
5037llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
5039 const llvm::Twine &name) {
5040 llvm::CallInst *call = Builder.CreateCall(
5041 callee, args, getBundlesForFunclet(callee.getCallee()), name);
5042 call->setCallingConv(getRuntimeCC());
5043
5044 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
5045 return cast<llvm::CallInst>(addConvergenceControlToken(call));
5046 return call;
5047}
5048
5049/// Emits a call or invoke to the given noreturn runtime function.
5051 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
5053 getBundlesForFunclet(callee.getCallee());
5054
5055 if (getInvokeDest()) {
5056 llvm::InvokeInst *invoke = Builder.CreateInvoke(
5057 callee, getUnreachableBlock(), getInvokeDest(), args, BundleList);
5058 invoke->setDoesNotReturn();
5059 invoke->setCallingConv(getRuntimeCC());
5060 } else {
5061 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
5062 call->setDoesNotReturn();
5063 call->setCallingConv(getRuntimeCC());
5064 Builder.CreateUnreachable();
5065 }
5066}
5067
5068/// Emits a call or invoke instruction to the given nullary runtime function.
5069llvm::CallBase *
5071 const Twine &name) {
5072 return EmitRuntimeCallOrInvoke(callee, {}, name);
5073}
5074
5075/// Emits a call or invoke instruction to the given runtime function.
5076llvm::CallBase *
5079 const Twine &name) {
5080 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
5081 call->setCallingConv(getRuntimeCC());
5082 return call;
5083}
5084
5085/// Emits a call or invoke instruction to the given function, depending
5086/// on the current state of the EH stack.
5087llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
5089 const Twine &Name) {
5090 llvm::BasicBlock *InvokeDest = getInvokeDest();
5092 getBundlesForFunclet(Callee.getCallee());
5093
5094 llvm::CallBase *Inst;
5095 if (!InvokeDest)
5096 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
5097 else {
5098 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
5099 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
5100 Name);
5101 EmitBlock(ContBB);
5102 }
5103
5104 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5105 // optimizer it can aggressively ignore unwind edges.
5106 if (CGM.getLangOpts().ObjCAutoRefCount)
5107 AddObjCARCExceptionMetadata(Inst);
5108
5109 return Inst;
5110}
5111
5112void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
5113 llvm::Value *New) {
5114 DeferredReplacements.push_back(
5115 std::make_pair(llvm::WeakTrackingVH(Old), New));
5116}
5117
5118namespace {
5119
5120/// Specify given \p NewAlign as the alignment of return value attribute. If
5121/// such attribute already exists, re-set it to the maximal one of two options.
5122[[nodiscard]] llvm::AttributeList
5123maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
5124 const llvm::AttributeList &Attrs,
5125 llvm::Align NewAlign) {
5126 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
5127 if (CurAlign >= NewAlign)
5128 return Attrs;
5129 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
5130 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
5131 .addRetAttribute(Ctx, AlignAttr);
5132}
5133
5134template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
5135protected:
5136 CodeGenFunction &CGF;
5137
5138 /// We do nothing if this is, or becomes, nullptr.
5139 const AlignedAttrTy *AA = nullptr;
5140
5141 llvm::Value *Alignment = nullptr; // May or may not be a constant.
5142 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
5143
5144 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5145 : CGF(CGF_) {
5146 if (!FuncDecl)
5147 return;
5148 AA = FuncDecl->getAttr<AlignedAttrTy>();
5149 }
5150
5151public:
5152 /// If we can, materialize the alignment as an attribute on return value.
5153 [[nodiscard]] llvm::AttributeList
5154 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
5155 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
5156 return Attrs;
5157 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
5158 if (!AlignmentCI)
5159 return Attrs;
5160 // We may legitimately have non-power-of-2 alignment here.
5161 // If so, this is UB land, emit it via `@llvm.assume` instead.
5162 if (!AlignmentCI->getValue().isPowerOf2())
5163 return Attrs;
5164 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
5165 CGF.getLLVMContext(), Attrs,
5166 llvm::Align(
5167 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
5168 AA = nullptr; // We're done. Disallow doing anything else.
5169 return NewAttrs;
5170 }
5171
5172 /// Emit alignment assumption.
5173 /// This is a general fallback that we take if either there is an offset,
5174 /// or the alignment is variable or we are sanitizing for alignment.
5175 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
5176 if (!AA)
5177 return;
5178 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
5179 AA->getLocation(), Alignment, OffsetCI);
5180 AA = nullptr; // We're done. Disallow doing anything else.
5181 }
5182};
5183
5184/// Helper data structure to emit `AssumeAlignedAttr`.
5185class AssumeAlignedAttrEmitter final
5186 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
5187public:
5188 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
5189 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5190 if (!AA)
5191 return;
5192 // It is guaranteed that the alignment/offset are constants.
5193 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
5194 if (Expr *Offset = AA->getOffset()) {
5195 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
5196 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
5197 OffsetCI = nullptr;
5198 }
5199 }
5200};
5201
5202/// Helper data structure to emit `AllocAlignAttr`.
5203class AllocAlignAttrEmitter final
5204 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5205public:
5206 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
5207 const CallArgList &CallArgs)
5208 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5209 if (!AA)
5210 return;
5211 // Alignment may or may not be a constant, and that is okay.
5212 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5213 .getRValue(CGF)
5214 .getScalarVal();
5215 }
5216};
5217
5218} // namespace
5219
5220static unsigned getMaxVectorWidth(const llvm::Type *Ty) {
5221 if (auto *VT = dyn_cast<llvm::VectorType>(Ty))
5222 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5223 if (auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5224 return getMaxVectorWidth(AT->getElementType());
5225
5226 unsigned MaxVectorWidth = 0;
5227 if (auto *ST = dyn_cast<llvm::StructType>(Ty))
5228 for (auto *I : ST->elements())
5229 MaxVectorWidth = std::max(MaxVectorWidth, getMaxVectorWidth(I));
5230 return MaxVectorWidth;
5231}
5232
5234 const CGCallee &Callee,
5236 const CallArgList &CallArgs,
5237 llvm::CallBase **callOrInvoke, bool IsMustTail,
5238 SourceLocation Loc,
5239 bool IsVirtualFunctionPointerThunk) {
5240 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
5241
5242 assert(Callee.isOrdinary() || Callee.isVirtual());
5243
5244 // Handle struct-return functions by passing a pointer to the
5245 // location that we would like to return into.
5246 QualType RetTy = CallInfo.getReturnType();
5247 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
5248
5249 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
5250
5251 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5252 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5253 // We can only guarantee that a function is called from the correct
5254 // context/function based on the appropriate target attributes,
5255 // so only check in the case where we have both always_inline and target
5256 // since otherwise we could be making a conditional call after a check for
5257 // the proper cpu features (and it won't cause code generation issues due to
5258 // function based code generation).
5259 if ((TargetDecl->hasAttr<AlwaysInlineAttr>() &&
5260 (TargetDecl->hasAttr<TargetAttr>() ||
5261 (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>()))) ||
5262 (CurFuncDecl && CurFuncDecl->hasAttr<FlattenAttr>() &&
5263 (CurFuncDecl->hasAttr<TargetAttr>() ||
5264 TargetDecl->hasAttr<TargetAttr>())))
5265 checkTargetFeatures(Loc, FD);
5266 }
5267
5268 // Some architectures (such as x86-64) have the ABI changed based on
5269 // attribute-target/features. Give them a chance to diagnose.
5270 const FunctionDecl *CallerDecl = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
5271 const FunctionDecl *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl);
5272 CGM.getTargetCodeGenInfo().checkFunctionCallABI(CGM, Loc, CallerDecl,
5273 CalleeDecl, CallArgs, RetTy);
5274
5275 // 1. Set up the arguments.
5276
5277 // If we're using inalloca, insert the allocation after the stack save.
5278 // FIXME: Do this earlier rather than hacking it in here!
5279 RawAddress ArgMemory = RawAddress::invalid();
5280 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
5281 const llvm::DataLayout &DL = CGM.getDataLayout();
5282 llvm::Instruction *IP = CallArgs.getStackBase();
5283 llvm::AllocaInst *AI;
5284 if (IP) {
5285 IP = IP->getNextNode();
5286 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), "argmem",
5287 IP->getIterator());
5288 } else {
5289 AI = CreateTempAlloca(ArgStruct, "argmem");
5290 }
5291 auto Align = CallInfo.getArgStructAlignment();
5292 AI->setAlignment(Align.getAsAlign());
5293 AI->setUsedWithInAlloca(true);
5294 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5295 ArgMemory = RawAddress(AI, ArgStruct, Align);
5296 }
5297
5298 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
5299 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
5300
5301 // If the call returns a temporary with struct return, create a temporary
5302 // alloca to hold the result, unless one is given to us.
5303 Address SRetPtr = Address::invalid();
5304 bool NeedSRetLifetimeEnd = false;
5305 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
5306 // For virtual function pointer thunks and musttail calls, we must always
5307 // forward an incoming SRet pointer to the callee, because a local alloca
5308 // would be de-allocated before the call. These cases both guarantee that
5309 // there will be an incoming SRet argument of the correct type.
5310 if ((IsVirtualFunctionPointerThunk || IsMustTail) && RetAI.isIndirect()) {
5311 SRetPtr = makeNaturalAddressForPointer(CurFn->arg_begin() +
5312 IRFunctionArgs.getSRetArgNo(),
5313 RetTy, CharUnits::fromQuantity(1));
5314 } else if (!ReturnValue.isNull()) {
5315 SRetPtr = ReturnValue.getAddress();
5316 } else {
5317 SRetPtr = CreateMemTempWithoutCast(RetTy, "tmp");
5318 if (HaveInsertPoint() && ReturnValue.isUnused())
5319 NeedSRetLifetimeEnd = EmitLifetimeStart(SRetPtr.getBasePointer());
5320 }
5321 if (IRFunctionArgs.hasSRetArg()) {
5322 // A mismatch between the allocated return value's AS and the target's
5323 // chosen IndirectAS can happen e.g. when passing the this pointer through
5324 // a chain involving stores to / loads from the DefaultAS; we address this
5325 // here, symmetrically with the handling we have for normal pointer args.
5326 if (SRetPtr.getAddressSpace() != RetAI.getIndirectAddrSpace()) {
5327 llvm::Value *V = SRetPtr.getBasePointer();
5329 llvm::Type *Ty = llvm::PointerType::get(getLLVMContext(),
5330 RetAI.getIndirectAddrSpace());
5331
5332 SRetPtr = SRetPtr.withPointer(
5333 getTargetHooks().performAddrSpaceCast(*this, V, SAS, Ty, true),
5334 SRetPtr.isKnownNonNull());
5335 }
5336 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5337 getAsNaturalPointerTo(SRetPtr, RetTy);
5338 } else if (RetAI.isInAlloca()) {
5339 Address Addr =
5340 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
5341 Builder.CreateStore(getAsNaturalPointerTo(SRetPtr, RetTy), Addr);
5342 }
5343 }
5344
5345 RawAddress swiftErrorTemp = RawAddress::invalid();
5346 Address swiftErrorArg = Address::invalid();
5347
5348 // When passing arguments using temporary allocas, we need to add the
5349 // appropriate lifetime markers. This vector keeps track of all the lifetime
5350 // markers that need to be ended right after the call.
5351 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
5352
5353 // Translate all of the arguments as necessary to match the IR lowering.
5354 assert(CallInfo.arg_size() == CallArgs.size() &&
5355 "Mismatch between function signature & arguments.");
5356 unsigned ArgNo = 0;
5357 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
5358 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5359 I != E; ++I, ++info_it, ++ArgNo) {
5360 const ABIArgInfo &ArgInfo = info_it->info;
5361
5362 // Insert a padding argument to ensure proper alignment.
5363 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5364 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5365 llvm::UndefValue::get(ArgInfo.getPaddingType());
5366
5367 unsigned FirstIRArg, NumIRArgs;
5368 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5369
5370 bool ArgHasMaybeUndefAttr =
5371 IsArgumentMaybeUndef(TargetDecl, CallInfo.getNumRequiredArgs(), ArgNo);
5372
5373 switch (ArgInfo.getKind()) {
5374 case ABIArgInfo::InAlloca: {
5375 assert(NumIRArgs == 0);
5376 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
5377 if (I->isAggregate()) {
5378 RawAddress Addr = I->hasLValue()
5379 ? I->getKnownLValue().getAddress()
5380 : I->getKnownRValue().getAggregateAddress();
5381 llvm::Instruction *Placeholder =
5382 cast<llvm::Instruction>(Addr.getPointer());
5383
5384 if (!ArgInfo.getInAllocaIndirect()) {
5385 // Replace the placeholder with the appropriate argument slot GEP.
5386 CGBuilderTy::InsertPoint IP = Builder.saveIP();
5387 Builder.SetInsertPoint(Placeholder);
5388 Addr = Builder.CreateStructGEP(ArgMemory,
5389 ArgInfo.getInAllocaFieldIndex());
5390 Builder.restoreIP(IP);
5391 } else {
5392 // For indirect things such as overaligned structs, replace the
5393 // placeholder with a regular aggregate temporary alloca. Store the
5394 // address of this alloca into the struct.
5395 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
5396 Address ArgSlot = Builder.CreateStructGEP(
5397 ArgMemory, ArgInfo.getInAllocaFieldIndex());
5398 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5399 }
5400 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
5401 } else if (ArgInfo.getInAllocaIndirect()) {
5402 // Make a temporary alloca and store the address of it into the argument
5403 // struct.
5405 I->Ty, getContext().getTypeAlignInChars(I->Ty),
5406 "indirect-arg-temp");
5407 I->copyInto(*this, Addr);
5408 Address ArgSlot =
5409 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5410 Builder.CreateStore(Addr.getPointer(), ArgSlot);
5411 } else {
5412 // Store the RValue into the argument struct.
5413 Address Addr =
5414 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
5415 Addr = Addr.withElementType(ConvertTypeForMem(I->Ty));
5416 I->copyInto(*this, Addr);
5417 }
5418 break;
5419 }
5420
5423 assert(NumIRArgs == 1);
5424 if (I->isAggregate()) {
5425 // We want to avoid creating an unnecessary temporary+copy here;
5426 // however, we need one in three cases:
5427 // 1. If the argument is not byval, and we are required to copy the
5428 // source. (This case doesn't occur on any common architecture.)
5429 // 2. If the argument is byval, RV is not sufficiently aligned, and
5430 // we cannot force it to be sufficiently aligned.
5431 // 3. If the argument is byval, but RV is not located in default
5432 // or alloca address space.
5433 Address Addr = I->hasLValue()
5434 ? I->getKnownLValue().getAddress()
5435 : I->getKnownRValue().getAggregateAddress();
5436 CharUnits Align = ArgInfo.getIndirectAlign();
5437 const llvm::DataLayout *TD = &CGM.getDataLayout();
5438
5439 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5440 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5441 TD->getAllocaAddrSpace()) &&
5442 "indirect argument must be in alloca address space");
5443
5444 bool NeedCopy = false;
5445 if (Addr.getAlignment() < Align &&
5446 llvm::getOrEnforceKnownAlignment(Addr.emitRawPointer(*this),
5447 Align.getAsAlign(),
5448 *TD) < Align.getAsAlign()) {
5449 NeedCopy = true;
5450 } else if (I->hasLValue()) {
5451 auto LV = I->getKnownLValue();
5452
5453 bool isByValOrRef =
5454 ArgInfo.isIndirectAliased() || ArgInfo.getIndirectByVal();
5455
5456 if (!isByValOrRef ||
5457 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
5458 NeedCopy = true;
5459 }
5460
5461 if (isByValOrRef && Addr.getType()->getAddressSpace() !=
5462 ArgInfo.getIndirectAddrSpace()) {
5463 NeedCopy = true;
5464 }
5465 }
5466
5467 if (!NeedCopy) {
5468 // Skip the extra memcpy call.
5469 llvm::Value *V = getAsNaturalPointerTo(Addr, I->Ty);
5470 auto *T = llvm::PointerType::get(CGM.getLLVMContext(),
5471 ArgInfo.getIndirectAddrSpace());
5472
5473 // FIXME: This should not depend on the language address spaces, and
5474 // only the contextual values. If the address space mismatches, see if
5475 // we can look through a cast to a compatible address space value,
5476 // otherwise emit a copy.
5477 llvm::Value *Val = getTargetHooks().performAddrSpaceCast(
5478 *this, V, I->Ty.getAddressSpace(), T, true);
5479 if (ArgHasMaybeUndefAttr)
5480 Val = Builder.CreateFreeze(Val);
5481 IRCallArgs[FirstIRArg] = Val;
5482 break;
5483 }
5484 } else if (I->getType()->isArrayParameterType()) {
5485 // Don't produce a temporary for ArrayParameterType arguments.
5486 // ArrayParameterType arguments are only created from
5487 // HLSL_ArrayRValue casts and HLSLOutArgExpr expressions, both
5488 // of which create temporaries already. This allows us to just use the
5489 // scalar for the decayed array pointer as the argument directly.
5490 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5491 break;
5492 }
5493
5494 // For non-aggregate args and aggregate args meeting conditions above
5495 // we need to create an aligned temporary, and copy to it.
5497 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
5498 llvm::Value *Val = getAsNaturalPointerTo(AI, I->Ty);
5499 if (ArgHasMaybeUndefAttr)
5500 Val = Builder.CreateFreeze(Val);
5501 IRCallArgs[FirstIRArg] = Val;
5502
5503 // Emit lifetime markers for the temporary alloca and add cleanup code to
5504 // emit the end lifetime marker after the call.
5505 if (EmitLifetimeStart(AI.getPointer()))
5506 CallLifetimeEndAfterCall.emplace_back(AI);
5507
5508 // Generate the copy.
5509 I->copyInto(*this, AI);
5510 break;
5511 }
5512
5513 case ABIArgInfo::Ignore:
5514 assert(NumIRArgs == 0);
5515 break;
5516
5517 case ABIArgInfo::Extend:
5518 case ABIArgInfo::Direct: {
5519 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
5520 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
5521 ArgInfo.getDirectOffset() == 0) {
5522 assert(NumIRArgs == 1);
5523 llvm::Value *V;
5524 if (!I->isAggregate())
5525 V = I->getKnownRValue().getScalarVal();
5526 else
5527 V = Builder.CreateLoad(
5528 I->hasLValue() ? I->getKnownLValue().getAddress()
5529 : I->getKnownRValue().getAggregateAddress());
5530
5531 // Implement swifterror by copying into a new swifterror argument.
5532 // We'll write back in the normal path out of the call.
5533 if (CallInfo.getExtParameterInfo(ArgNo).getABI() ==
5535 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
5536
5537 QualType pointeeTy = I->Ty->getPointeeType();
5538 swiftErrorArg = makeNaturalAddressForPointer(
5539 V, pointeeTy, getContext().getTypeAlignInChars(pointeeTy));
5540
5541 swiftErrorTemp =
5542 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
5543 V = swiftErrorTemp.getPointer();
5544 cast<llvm::AllocaInst>(V)->setSwiftError(true);
5545
5546 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
5547 Builder.CreateStore(errorValue, swiftErrorTemp);
5548 }
5549
5550 // We might have to widen integers, but we should never truncate.
5551 if (ArgInfo.getCoerceToType() != V->getType() &&
5552 V->getType()->isIntegerTy())
5553 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
5554
5555 // The only plausible mismatch here would be for pointer address spaces.
5556 // We assume that the target has a reasonable mapping for the DefaultAS
5557 // (it can be casted to from incoming specific ASes), and insert an AS
5558 // cast to address the mismatch.
5559 if (FirstIRArg < IRFuncTy->getNumParams() &&
5560 V->getType() != IRFuncTy->getParamType(FirstIRArg)) {
5561 assert(V->getType()->isPointerTy() && "Only pointers can mismatch!");
5562 auto ActualAS = I->Ty.getAddressSpace();
5563 V = getTargetHooks().performAddrSpaceCast(
5564 *this, V, ActualAS, IRFuncTy->getParamType(FirstIRArg));
5565 }
5566
5567 if (ArgHasMaybeUndefAttr)
5568 V = Builder.CreateFreeze(V);
5569 IRCallArgs[FirstIRArg] = V;
5570 break;
5571 }
5572
5573 llvm::StructType *STy =
5574 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
5575
5576 // FIXME: Avoid the conversion through memory if possible.
5577 Address Src = Address::invalid();
5578 if (!I->isAggregate()) {
5579 Src = CreateMemTemp(I->Ty, "coerce");
5580 I->copyInto(*this, Src);
5581 } else {
5582 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5583 : I->getKnownRValue().getAggregateAddress();
5584 }
5585
5586 // If the value is offset in memory, apply the offset now.
5587 Src = emitAddressAtOffset(*this, Src, ArgInfo);
5588
5589 // Fast-isel and the optimizer generally like scalar values better than
5590 // FCAs, so we flatten them if this is safe to do for this argument.
5591 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
5592 llvm::Type *SrcTy = Src.getElementType();
5593 llvm::TypeSize SrcTypeSize =
5594 CGM.getDataLayout().getTypeAllocSize(SrcTy);
5595 llvm::TypeSize DstTypeSize = CGM.getDataLayout().getTypeAllocSize(STy);
5596 if (SrcTypeSize.isScalable()) {
5597 assert(STy->containsHomogeneousScalableVectorTypes() &&
5598 "ABI only supports structure with homogeneous scalable vector "
5599 "type");
5600 assert(SrcTypeSize == DstTypeSize &&
5601 "Only allow non-fractional movement of structure with "
5602 "homogeneous scalable vector type");
5603 assert(NumIRArgs == STy->getNumElements());
5604
5605 llvm::Value *StoredStructValue =
5606 Builder.CreateLoad(Src, Src.getName() + ".tuple");
5607 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5608 llvm::Value *Extract = Builder.CreateExtractValue(
5609 StoredStructValue, i, Src.getName() + ".extract" + Twine(i));
5610 IRCallArgs[FirstIRArg + i] = Extract;
5611 }
5612 } else {
5613 uint64_t SrcSize = SrcTypeSize.getFixedValue();
5614 uint64_t DstSize = DstTypeSize.getFixedValue();
5615
5616 // If the source type is smaller than the destination type of the
5617 // coerce-to logic, copy the source value into a temp alloca the size
5618 // of the destination type to allow loading all of it. The bits past
5619 // the source value are left undef.
5620 if (SrcSize < DstSize) {
5621 Address TempAlloca = CreateTempAlloca(STy, Src.getAlignment(),
5622 Src.getName() + ".coerce");
5623 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
5624 Src = TempAlloca;
5625 } else {
5626 Src = Src.withElementType(STy);
5627 }
5628
5629 assert(NumIRArgs == STy->getNumElements());
5630 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5631 Address EltPtr = Builder.CreateStructGEP(Src, i);
5632 llvm::Value *LI = Builder.CreateLoad(EltPtr);
5633 if (ArgHasMaybeUndefAttr)
5634 LI = Builder.CreateFreeze(LI);
5635 IRCallArgs[FirstIRArg + i] = LI;
5636 }
5637 }
5638 } else {
5639 // In the simple case, just pass the coerced loaded value.
5640 assert(NumIRArgs == 1);
5641 llvm::Value *Load =
5642 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
5643
5644 if (CallInfo.isCmseNSCall()) {
5645 // For certain parameter types, clear padding bits, as they may reveal
5646 // sensitive information.
5647 // Small struct/union types are passed as integer arrays.
5648 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
5649 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
5650 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
5651 }
5652
5653 if (ArgHasMaybeUndefAttr)
5654 Load = Builder.CreateFreeze(Load);
5655 IRCallArgs[FirstIRArg] = Load;
5656 }
5657
5658 break;
5659 }
5660
5662 auto coercionType = ArgInfo.getCoerceAndExpandType();
5663 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5664 auto unpaddedCoercionType = ArgInfo.getUnpaddedCoerceAndExpandType();
5665 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
5666
5667 Address addr = Address::invalid();
5668 RawAddress AllocaAddr = RawAddress::invalid();
5669 bool NeedLifetimeEnd = false;
5670 if (I->isAggregate()) {
5671 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
5672 : I->getKnownRValue().getAggregateAddress();
5673
5674 } else {
5675 RValue RV = I->getKnownRValue();
5676 assert(RV.isScalar()); // complex should always just be direct
5677
5678 llvm::Type *scalarType = RV.getScalarVal()->getType();
5679 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlign(scalarType);
5680
5681 // Materialize to a temporary.
5682 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
5683 CharUnits::fromQuantity(std::max(
5684 layout->getAlignment(), scalarAlign)),
5685 "tmp",
5686 /*ArraySize=*/nullptr, &AllocaAddr);
5687 NeedLifetimeEnd = EmitLifetimeStart(AllocaAddr.getPointer());
5688
5689 Builder.CreateStore(RV.getScalarVal(), addr);
5690 }
5691
5692 addr = addr.withElementType(coercionType);
5693
5694 unsigned IRArgPos = FirstIRArg;
5695 unsigned unpaddedIndex = 0;
5696 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5697 llvm::Type *eltType = coercionType->getElementType(i);
5699 continue;
5700 Address eltAddr = Builder.CreateStructGEP(addr, i);
5701 llvm::Value *elt = CreateCoercedLoad(
5702 eltAddr,
5703 unpaddedStruct ? unpaddedStruct->getElementType(unpaddedIndex++)
5704 : unpaddedCoercionType,
5705 *this);
5706 if (ArgHasMaybeUndefAttr)
5707 elt = Builder.CreateFreeze(elt);
5708 IRCallArgs[IRArgPos++] = elt;
5709 }
5710 assert(IRArgPos == FirstIRArg + NumIRArgs);
5711
5712 if (NeedLifetimeEnd)
5713 EmitLifetimeEnd(AllocaAddr.getPointer());
5714 break;
5715 }
5716
5717 case ABIArgInfo::Expand: {
5718 unsigned IRArgPos = FirstIRArg;
5719 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5720 assert(IRArgPos == FirstIRArg + NumIRArgs);
5721 break;
5722 }
5723
5725 Address Src = Address::invalid();
5726 if (!I->isAggregate()) {
5727 Src = CreateMemTemp(I->Ty, "target_coerce");
5728 I->copyInto(*this, Src);
5729 } else {
5730 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
5731 : I->getKnownRValue().getAggregateAddress();
5732 }
5733
5734 // If the value is offset in memory, apply the offset now.
5735 Src = emitAddressAtOffset(*this, Src, ArgInfo);
5736 llvm::Value *Load =
5737 CGM.getABIInfo().createCoercedLoad(Src, ArgInfo, *this);
5738 IRCallArgs[FirstIRArg] = Load;
5739 break;
5740 }
5741 }
5742 }
5743
5744 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5745 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5746
5747 // If we're using inalloca, set up that argument.
5748 if (ArgMemory.isValid()) {
5749 llvm::Value *Arg = ArgMemory.getPointer();
5750 assert(IRFunctionArgs.hasInallocaArg());
5751 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5752 }
5753
5754 // 2. Prepare the function pointer.
5755
5756 // If the callee is a bitcast of a non-variadic function to have a
5757 // variadic function pointer type, check to see if we can remove the
5758 // bitcast. This comes up with unprototyped functions.
5759 //
5760 // This makes the IR nicer, but more importantly it ensures that we
5761 // can inline the function at -O0 if it is marked always_inline.
5762 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5763 llvm::Value *Ptr) -> llvm::Function * {
5764 if (!CalleeFT->isVarArg())
5765 return nullptr;
5766
5767 // Get underlying value if it's a bitcast
5768 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5769 if (CE->getOpcode() == llvm::Instruction::BitCast)
5770 Ptr = CE->getOperand(0);
5771 }
5772
5773 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5774 if (!OrigFn)
5775 return nullptr;
5776
5777 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5778
5779 // If the original type is variadic, or if any of the component types
5780 // disagree, we cannot remove the cast.
5781 if (OrigFT->isVarArg() ||
5782 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5783 OrigFT->getReturnType() != CalleeFT->getReturnType())
5784 return nullptr;
5785
5786 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5787 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5788 return nullptr;
5789
5790 return OrigFn;
5791 };
5792
5793 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5794 CalleePtr = OrigFn;
5795 IRFuncTy = OrigFn->getFunctionType();
5796 }
5797
5798 // 3. Perform the actual call.
5799
5800 // Deactivate any cleanups that we're supposed to do immediately before
5801 // the call.
5802 if (!CallArgs.getCleanupsToDeactivate().empty())
5803 deactivateArgCleanupsBeforeCall(*this, CallArgs);
5804
5805 // Update the largest vector width if any arguments have vector types.
5806 for (unsigned i = 0; i < IRCallArgs.size(); ++i)
5807 LargestVectorWidth = std::max(LargestVectorWidth,
5808 getMaxVectorWidth(IRCallArgs[i]->getType()));
5809
5810 // Compute the calling convention and attributes.
5811 unsigned CallingConv;
5812 llvm::AttributeList Attrs;
5813 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5814 Callee.getAbstractInfo(), Attrs, CallingConv,
5815 /*AttrOnCallSite=*/true,
5816 /*IsThunk=*/false);
5817
5818 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
5819 getTarget().getTriple().isWindowsArm64EC()) {
5820 CGM.Error(Loc, "__vectorcall calling convention is not currently "
5821 "supported");
5822 }
5823
5824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5825 if (FD->hasAttr<StrictFPAttr>())
5826 // All calls within a strictfp function are marked strictfp
5827 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5828
5829 // If -ffast-math is enabled and the function is guarded by an
5830 // '__attribute__((optnone)) adjust the memory attribute so the BE emits the
5831 // library call instead of the intrinsic.
5832 if (FD->hasAttr<OptimizeNoneAttr>() && getLangOpts().FastMath)
5833 CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
5834 Attrs);
5835 }
5836 // Add call-site nomerge attribute if exists.
5838 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
5839
5840 // Add call-site noinline attribute if exists.
5842 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5843
5844 // Add call-site always_inline attribute if exists.
5845 // Note: This corresponds to the [[clang::always_inline]] statement attribute.
5847 !CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
5848 CallerDecl, CalleeDecl))
5849 Attrs =
5850 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5851
5852 // Remove call-site convergent attribute if requested.
5854 Attrs =
5855 Attrs.removeFnAttribute(getLLVMContext(), llvm::Attribute::Convergent);
5856
5857 // Apply some call-site-specific attributes.
5858 // TODO: work this into building the attribute set.
5859
5860 // Apply always_inline to all calls within flatten functions.
5861 // FIXME: should this really take priority over __try, below?
5862 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5864 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>()) &&
5865 !CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
5866 CallerDecl, CalleeDecl)) {
5867 Attrs =
5868 Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
5869 }
5870
5871 // Disable inlining inside SEH __try blocks.
5872 if (isSEHTryScope()) {
5873 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
5874 }
5875
5876 // Decide whether to use a call or an invoke.
5877 bool CannotThrow;
5879 // SEH cares about asynchronous exceptions, so everything can "throw."
5880 CannotThrow = false;
5881 } else if (isCleanupPadScope() &&
5882 EHPersonality::get(*this).isMSVCXXPersonality()) {
5883 // The MSVC++ personality will implicitly terminate the program if an
5884 // exception is thrown during a cleanup outside of a try/catch.
5885 // We don't need to model anything in IR to get this behavior.
5886 CannotThrow = true;
5887 } else {
5888 // Otherwise, nounwind call sites will never throw.
5889 CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
5890
5891 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5892 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5893 CannotThrow = true;
5894 }
5895
5896 // If we made a temporary, be sure to clean up after ourselves. Note that we
5897 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5898 // pop this cleanup later on. Being eager about this is OK, since this
5899 // temporary is 'invisible' outside of the callee.
5900 if (NeedSRetLifetimeEnd)
5902
5903 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5904
5906 getBundlesForFunclet(CalleePtr);
5907
5908 if (SanOpts.has(SanitizerKind::KCFI) &&
5909 !isa_and_nonnull<FunctionDecl>(TargetDecl))
5910 EmitKCFIOperandBundle(ConcreteCallee, BundleList);
5911
5912 // Add the pointer-authentication bundle.
5913 EmitPointerAuthOperandBundle(ConcreteCallee.getPointerAuthInfo(), BundleList);
5914
5915 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5916 if (FD->hasAttr<StrictFPAttr>())
5917 // All calls within a strictfp function are marked strictfp
5918 Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
5919
5920 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5921 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5922
5923 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5924 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5925
5926 // Emit the actual call/invoke instruction.
5927 llvm::CallBase *CI;
5928 if (!InvokeDest) {
5929 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5930 } else {
5931 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5932 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5933 BundleList);
5934 EmitBlock(Cont);
5935 }
5936 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
5937 CI->getCalledFunction()->getName().starts_with("_Z4sqrt")) {
5939 }
5940 if (callOrInvoke)
5941 *callOrInvoke = CI;
5942
5943 // If this is within a function that has the guard(nocf) attribute and is an
5944 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5945 // Control Flow Guard checks should not be added, even if the call is inlined.
5946 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5947 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5948 if (A->getGuard() == CFGuardAttr::GuardArg::nocf &&
5949 !CI->getCalledFunction())
5950 Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
5951 }
5952 }
5953
5954 // Apply the attributes and calling convention.
5955 CI->setAttributes(Attrs);
5956 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5957
5958 // Apply various metadata.
5959
5960 if (!CI->getType()->isVoidTy())
5961 CI->setName("call");
5962
5963 if (CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
5964 CI = addConvergenceControlToken(CI);
5965
5966 // Update largest vector width from the return type.
5967 LargestVectorWidth =
5968 std::max(LargestVectorWidth, getMaxVectorWidth(CI->getType()));
5969
5970 // Insert instrumentation or attach profile metadata at indirect call sites.
5971 // For more details, see the comment before the definition of
5972 // IPVK_IndirectCallTarget in InstrProfData.inc.
5973 if (!CI->getCalledFunction())
5974 PGO->valueProfile(Builder, llvm::IPVK_IndirectCallTarget, CI, CalleePtr);
5975
5976 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5977 // optimizer it can aggressively ignore unwind edges.
5978 if (CGM.getLangOpts().ObjCAutoRefCount)
5979 AddObjCARCExceptionMetadata(CI);
5980
5981 // Set tail call kind if necessary.
5982 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5983 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5984 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5985 else if (IsMustTail) {
5986 if (getTarget().getTriple().isPPC()) {
5987 if (getTarget().getTriple().isOSAIX())
5988 CGM.getDiags().Report(Loc, diag::err_aix_musttail_unsupported);
5989 else if (!getTarget().hasFeature("pcrelative-memops")) {
5990 if (getTarget().hasFeature("longcall"))
5991 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 0;
5992 else if (Call->isIndirectCall())
5993 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 1;
5994 else if (isa_and_nonnull<FunctionDecl>(TargetDecl)) {
5995 if (!cast<FunctionDecl>(TargetDecl)->isDefined())
5996 // The undefined callee may be a forward declaration. Without
5997 // knowning all symbols in the module, we won't know the symbol is
5998 // defined or not. Collect all these symbols for later diagnosing.
5999 CGM.addUndefinedGlobalForTailCall(
6000 {cast<FunctionDecl>(TargetDecl), Loc});
6001 else {
6002 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(
6003 GlobalDecl(cast<FunctionDecl>(TargetDecl)));
6004 if (llvm::GlobalValue::isWeakForLinker(Linkage) ||
6005 llvm::GlobalValue::isDiscardableIfUnused(Linkage))
6006 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail)
6007 << 2;
6008 }
6009 }
6010 }
6011 }
6012 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
6013 }
6014 }
6015
6016 // Add metadata for calls to MSAllocator functions
6017 if (getDebugInfo() && TargetDecl && TargetDecl->hasAttr<MSAllocatorAttr>())
6018 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
6019
6020 // Add metadata if calling an __attribute__((error(""))) or warning fn.
6021 if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
6022 llvm::ConstantInt *Line =
6023 llvm::ConstantInt::get(Int64Ty, Loc.getRawEncoding());
6024 llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
6025 llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
6026 CI->setMetadata("srcloc", MDT);
6027 }
6028
6029 // 4. Finish the call.
6030
6031 // If the call doesn't return, finish the basic block and clear the
6032 // insertion point; this allows the rest of IRGen to discard
6033 // unreachable code.
6034 if (CI->doesNotReturn()) {
6035 if (NeedSRetLifetimeEnd)
6037
6038 // Strip away the noreturn attribute to better diagnose unreachable UB.
6039 if (SanOpts.has(SanitizerKind::Unreachable)) {
6040 // Also remove from function since CallBase::hasFnAttr additionally checks
6041 // attributes of the called function.
6042 if (auto *F = CI->getCalledFunction())
6043 F->removeFnAttr(llvm::Attribute::NoReturn);
6044 CI->removeFnAttr(llvm::Attribute::NoReturn);
6045
6046 // Avoid incompatibility with ASan which relies on the `noreturn`
6047 // attribute to insert handler calls.
6048 if (SanOpts.hasOneOf(SanitizerKind::Address |
6049 SanitizerKind::KernelAddress)) {
6050 SanitizerScope SanScope(this);
6051 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
6052 Builder.SetInsertPoint(CI);
6053 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
6054 llvm::FunctionCallee Fn =
6055 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
6057 }
6058 }
6059
6060 EmitUnreachable(Loc);
6061 Builder.ClearInsertionPoint();
6062
6063 // FIXME: For now, emit a dummy basic block because expr emitters in
6064 // generally are not ready to handle emitting expressions at unreachable
6065 // points.
6067
6068 // Return a reasonable RValue.
6069 return GetUndefRValue(RetTy);
6070 }
6071
6072 // If this is a musttail call, return immediately. We do not branch to the
6073 // epilogue in this case.
6074 if (IsMustTail) {
6075 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
6076 ++it) {
6077 EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
6078 // Fake uses can be safely emitted immediately prior to the tail call, so
6079 // we choose to emit them just before the call here.
6080 if (Cleanup && Cleanup->isFakeUse()) {
6081 CGBuilderTy::InsertPointGuard IPG(Builder);
6082 Builder.SetInsertPoint(CI);
6083 Cleanup->getCleanup()->Emit(*this, EHScopeStack::Cleanup::Flags());
6084 } else if (!(Cleanup &&
6085 Cleanup->getCleanup()->isRedundantBeforeReturn())) {
6086 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
6087 }
6088 }
6089 if (CI->getType()->isVoidTy())
6090 Builder.CreateRetVoid();
6091 else
6092 Builder.CreateRet(CI);
6093 Builder.ClearInsertionPoint();
6095 return GetUndefRValue(RetTy);
6096 }
6097
6098 // Perform the swifterror writeback.
6099 if (swiftErrorTemp.isValid()) {
6100 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
6101 Builder.CreateStore(errorResult, swiftErrorArg);
6102 }
6103
6104 // Emit any call-associated writebacks immediately. Arguably this
6105 // should happen after any return-value munging.
6106 if (CallArgs.hasWritebacks())
6107 EmitWritebacks(CallArgs);
6108
6109 // The stack cleanup for inalloca arguments has to run out of the normal
6110 // lexical order, so deactivate it and run it manually here.
6111 CallArgs.freeArgumentMemory(*this);
6112
6113 // Extract the return value.
6114 RValue Ret;
6115
6116 // If the current function is a virtual function pointer thunk, avoid copying
6117 // the return value of the musttail call to a temporary.
6118 if (IsVirtualFunctionPointerThunk) {
6119 Ret = RValue::get(CI);
6120 } else {
6121 Ret = [&] {
6122 switch (RetAI.getKind()) {
6124 auto coercionType = RetAI.getCoerceAndExpandType();
6125
6126 Address addr = SRetPtr.withElementType(coercionType);
6127
6128 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
6129 bool requiresExtract = isa<llvm::StructType>(CI->getType());
6130
6131 unsigned unpaddedIndex = 0;
6132 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
6133 llvm::Type *eltType = coercionType->getElementType(i);
6135 continue;
6136 Address eltAddr = Builder.CreateStructGEP(addr, i);
6137 llvm::Value *elt = CI;
6138 if (requiresExtract)
6139 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
6140 else
6141 assert(unpaddedIndex == 0);
6142 Builder.CreateStore(elt, eltAddr);
6143 }
6144 [[fallthrough]];
6145 }
6146
6148 case ABIArgInfo::Indirect: {
6149 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
6150 if (NeedSRetLifetimeEnd)
6152 return ret;
6153 }
6154
6155 case ABIArgInfo::Ignore:
6156 // If we are ignoring an argument that had a result, make sure to
6157 // construct the appropriate return value for our caller.
6158 return GetUndefRValue(RetTy);
6159
6160 case ABIArgInfo::Extend:
6161 case ABIArgInfo::Direct: {
6162 llvm::Type *RetIRTy = ConvertType(RetTy);
6163 if (RetAI.getCoerceToType() == RetIRTy &&
6164 RetAI.getDirectOffset() == 0) {
6165 switch (getEvaluationKind(RetTy)) {
6166 case TEK_Complex: {
6167 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
6168 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
6169 return RValue::getComplex(std::make_pair(Real, Imag));
6170 }
6171 case TEK_Aggregate:
6172 break;
6173 case TEK_Scalar: {
6174 // If the argument doesn't match, perform a bitcast to coerce it.
6175 // This can happen due to trivial type mismatches.
6176 llvm::Value *V = CI;
6177 if (V->getType() != RetIRTy)
6178 V = Builder.CreateBitCast(V, RetIRTy);
6179 return RValue::get(V);
6180 }
6181 }
6182 }
6183
6184 // If coercing a fixed vector from a scalable vector for ABI
6185 // compatibility, and the types match, use the llvm.vector.extract
6186 // intrinsic to perform the conversion.
6187 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
6188 llvm::Value *V = CI;
6189 if (auto *ScalableSrcTy =
6190 dyn_cast<llvm::ScalableVectorType>(V->getType())) {
6191 if (FixedDstTy->getElementType() ==
6192 ScalableSrcTy->getElementType()) {
6193 V = Builder.CreateExtractVector(FixedDstTy, V, uint64_t(0),
6194 "cast.fixed");
6195 return RValue::get(V);
6196 }
6197 }
6198 }
6199
6200 Address DestPtr = ReturnValue.getValue();
6201 bool DestIsVolatile = ReturnValue.isVolatile();
6202 uint64_t DestSize =
6203 getContext().getTypeInfoDataSizeInChars(RetTy).Width.getQuantity();
6204
6205 if (!DestPtr.isValid()) {
6206 DestPtr = CreateMemTemp(RetTy, "coerce");
6207 DestIsVolatile = false;
6208 DestSize = getContext().getTypeSizeInChars(RetTy).getQuantity();
6209 }
6210
6211 // An empty record can overlap other data (if declared with
6212 // no_unique_address); omit the store for such types - as there is no
6213 // actual data to store.
6214 if (!isEmptyRecord(getContext(), RetTy, true)) {
6215 // If the value is offset in memory, apply the offset now.
6216 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
6218 CI, StorePtr,
6219 llvm::TypeSize::getFixed(DestSize - RetAI.getDirectOffset()),
6220 DestIsVolatile);
6221 }
6222
6223 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
6224 }
6225
6227 Address DestPtr = ReturnValue.getValue();
6228 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
6229 bool DestIsVolatile = ReturnValue.isVolatile();
6230 if (!DestPtr.isValid()) {
6231 DestPtr = CreateMemTemp(RetTy, "target_coerce");
6232 DestIsVolatile = false;
6233 }
6234 CGM.getABIInfo().createCoercedStore(CI, StorePtr, RetAI, DestIsVolatile,
6235 *this);
6236 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
6237 }
6238
6239 case ABIArgInfo::Expand:
6241 llvm_unreachable("Invalid ABI kind for return argument");
6242 }
6243
6244 llvm_unreachable("Unhandled ABIArgInfo::Kind");
6245 }();
6246 }
6247
6248 // Emit the assume_aligned check on the return value.
6249 if (Ret.isScalar() && TargetDecl) {
6250 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6251 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6252 }
6253
6254 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
6255 // we can't use the full cleanup mechanism.
6256 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
6257 LifetimeEnd.Emit(*this, /*Flags=*/{});
6258
6259 if (!ReturnValue.isExternallyDestructed() &&
6261 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
6262 RetTy);
6263
6264 return Ret;
6265}
6266
6268 if (isVirtual()) {
6269 const CallExpr *CE = getVirtualCallExpr();
6272 CE ? CE->getBeginLoc() : SourceLocation());
6273 }
6274
6275 return *this;
6276}
6277
6278/* VarArg handling */
6279
6281 AggValueSlot Slot) {
6282 VAListAddr = VE->isMicrosoftABI() ? EmitMSVAListRef(VE->getSubExpr())
6283 : EmitVAListRef(VE->getSubExpr());
6284 QualType Ty = VE->getType();
6285 if (Ty->isVariablyModifiedType())
6287 if (VE->isMicrosoftABI())
6288 return CGM.getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty, Slot);
6289 return CGM.getABIInfo().EmitVAArg(*this, VAListAddr, Ty, Slot);
6290}
6291
6296
#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:4263
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
Definition CGCall.cpp:3919
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:3662
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:3060
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:4268
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:3799
static bool isProvablyNull(llvm::Value *addr)
Definition CGCall.cpp:4334
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
Definition CGCall.cpp:1839
static void eraseUnusedBitCasts(llvm::Instruction *insn)
Definition CGCall.cpp:3557
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
Definition CGCall.cpp:4658
static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, const LangOptions &LangOpts, const NoBuiltinAttr *NBA=nullptr)
Definition CGCall.cpp:2235
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
Definition CGCall.cpp:4436
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:2109
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:2271
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
Definition CGCall.cpp:4425
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:4414
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
Definition CGCall.cpp:4338
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:3039
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:2344
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:2365
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:2322
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
Definition CGCall.cpp:4640
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:3902
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
Definition CGCall.cpp:3721
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:3570
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:3703
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
Definition CGCall.cpp:4343
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:5220
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:220
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:891
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:3722
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:2877
SourceLocation getBeginLoc() const
Definition Expr.h:3211
ConstExprIterator const_arg_iterator
Definition Expr.h:3125
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:6267
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:4562
void freeArgumentMemory(CodeGenFunction &CGF) const
Definition CGCall.cpp:4569
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:5087
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
Emits a call or invoke to the given noreturn runtime function.
Definition CGCall.cpp:5050
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:5077
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:6833
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:3839
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:6859
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:6280
void EmitReturnValueCheck(llvm::Value *RV)
Emit a test that checks if the return value RV is nonnull.
Definition CGCall.cpp:4199
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:4286
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:685
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:2278
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:2577
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:4576
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:6047
void EmitWritebacks(const CallArgList &Args)
EmitWriteback - Emit callbacks for function.
Definition CGCall.cpp:4867
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:243
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2527
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:4872
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:3979
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:1356
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:152
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:5233
const TargetCodeGenInfo & getTargetHooks() const
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1368
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:216
bool InNoInlineAttributedStmt
True if the current statement has noinline attribute.
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
Definition CGCall.cpp:5015
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition CGExpr.cpp:284
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:3098
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:2724
Address EmitVAListRef(const Expr *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1723
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Definition CGDecl.cpp:2653
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:3985
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:1706
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:187
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:4673
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:4319
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:1822
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:1716
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:3939
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:655
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:2374
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:2402
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:2228
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:3760
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
Definition DeclCXX.h:3777
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:831
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
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:4042
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3266
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4753
Represents a function declaration or definition.
Definition Decl.h:2000
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4844
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5573
unsigned getNumParams() const
Definition TypeBase.h:5544
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5763
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5665
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5739
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5735
Wrapper for source info for functions.
Definition TypeLoc.h:1619
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4573
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4685
CallingConv getCC() const
Definition TypeBase.h:4632
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4651
unsigned getRegParm() const
Definition TypeBase.h:4625
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4621
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4488
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4501
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4528
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4462
ExtInfo getExtInfo() const
Definition TypeBase.h:4818
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4771
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4767
QualType getReturnType() const
Definition TypeBase.h:4802
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:7283
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:4337
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:301
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition ExprObjC.h: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:1790
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:8368
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:8416
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8330
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:8475
QualType getCanonicalType() const
Definition TypeBase.h:8342
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8363
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:4312
field_iterator field_end() const
Definition Decl.h:4518
bool isParamDestroyedInCallee() const
Definition Decl.h:4462
field_iterator field_begin() const
Definition Decl.cpp:5205
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
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:8883
bool isIncompleteArrayType() const
Definition TypeBase.h:8634
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:8527
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8927
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9170
bool isReferenceType() const
Definition TypeBase.h:8551
bool isScalarType() const
Definition TypeBase.h:8985
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:8792
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isMemberPointerType() const
Definition TypeBase.h:8608
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:9103
bool isNullPtrType() const
Definition TypeBase.h:8920
bool isRecordType() const
Definition TypeBase.h:8654
bool isObjCRetainableType() const
Definition Type.cpp:5285
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4891
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
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:4175
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:217
@ 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:2140
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:2815
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:4291
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:4850
bool hasLValue() const
Definition CGCall.h:247
RValue getRValue(CodeGenFunction &CGF) const
Definition CGCall.cpp:4840
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
DisableDebugLocationUpdates(CodeGenFunction &CGF)
Definition CGCall.cpp:6292
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