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