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