1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This is the internal per-translation-unit state used for llvm translation.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
16 #include "CGVTables.h"
17 #include "CodeGenTypeCache.h"
18 #include "CodeGenTypes.h"
19 #include "SanitizerMetadata.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclOpenMP.h"
23 #include "clang/AST/GlobalDecl.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/Basic/ABI.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/NoSanitizeList.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Basic/XRayLists.h"
31 #include "clang/Lex/PreprocessorOptions.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/MapVector.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/StringMap.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Transforms/Utils/SanitizerStats.h"
51 class IndexedInstrProfReader
;
63 class ObjCImplementationDecl
;
76 class HeaderSearchOptions
;
77 class DiagnosticsEngine
;
79 class CXXDestructorDecl
;
81 class CoverageSourceInfo
;
86 class CodeGenFunction
;
91 class CGOpenCLRuntime
;
92 class CGOpenMPRuntime
;
95 class CoverageMappingModuleGen
;
96 class TargetCodeGenInfo
;
98 enum ForDefinition_t
: bool {
99 NotForDefinition
= false,
103 struct OrderGlobalInitsOrStermFinalizers
{
104 unsigned int priority
;
105 unsigned int lex_order
;
106 OrderGlobalInitsOrStermFinalizers(unsigned int p
, unsigned int l
)
107 : priority(p
), lex_order(l
) {}
109 bool operator==(const OrderGlobalInitsOrStermFinalizers
&RHS
) const {
110 return priority
== RHS
.priority
&& lex_order
== RHS
.lex_order
;
113 bool operator<(const OrderGlobalInitsOrStermFinalizers
&RHS
) const {
114 return std::tie(priority
, lex_order
) <
115 std::tie(RHS
.priority
, RHS
.lex_order
);
119 struct ObjCEntrypoints
{
120 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
122 /// void objc_alloc(id);
123 llvm::FunctionCallee objc_alloc
;
125 /// void objc_allocWithZone(id);
126 llvm::FunctionCallee objc_allocWithZone
;
128 /// void objc_alloc_init(id);
129 llvm::FunctionCallee objc_alloc_init
;
131 /// void objc_autoreleasePoolPop(void*);
132 llvm::FunctionCallee objc_autoreleasePoolPop
;
134 /// void objc_autoreleasePoolPop(void*);
135 /// Note this method is used when we are using exception handling
136 llvm::FunctionCallee objc_autoreleasePoolPopInvoke
;
138 /// void *objc_autoreleasePoolPush(void);
139 llvm::Function
*objc_autoreleasePoolPush
;
141 /// id objc_autorelease(id);
142 llvm::Function
*objc_autorelease
;
144 /// id objc_autorelease(id);
145 /// Note this is the runtime method not the intrinsic.
146 llvm::FunctionCallee objc_autoreleaseRuntimeFunction
;
148 /// id objc_autoreleaseReturnValue(id);
149 llvm::Function
*objc_autoreleaseReturnValue
;
151 /// void objc_copyWeak(id *dest, id *src);
152 llvm::Function
*objc_copyWeak
;
154 /// void objc_destroyWeak(id*);
155 llvm::Function
*objc_destroyWeak
;
157 /// id objc_initWeak(id*, id);
158 llvm::Function
*objc_initWeak
;
160 /// id objc_loadWeak(id*);
161 llvm::Function
*objc_loadWeak
;
163 /// id objc_loadWeakRetained(id*);
164 llvm::Function
*objc_loadWeakRetained
;
166 /// void objc_moveWeak(id *dest, id *src);
167 llvm::Function
*objc_moveWeak
;
169 /// id objc_retain(id);
170 llvm::Function
*objc_retain
;
172 /// id objc_retain(id);
173 /// Note this is the runtime method not the intrinsic.
174 llvm::FunctionCallee objc_retainRuntimeFunction
;
176 /// id objc_retainAutorelease(id);
177 llvm::Function
*objc_retainAutorelease
;
179 /// id objc_retainAutoreleaseReturnValue(id);
180 llvm::Function
*objc_retainAutoreleaseReturnValue
;
182 /// id objc_retainAutoreleasedReturnValue(id);
183 llvm::Function
*objc_retainAutoreleasedReturnValue
;
185 /// id objc_retainBlock(id);
186 llvm::Function
*objc_retainBlock
;
188 /// void objc_release(id);
189 llvm::Function
*objc_release
;
191 /// void objc_release(id);
192 /// Note this is the runtime method not the intrinsic.
193 llvm::FunctionCallee objc_releaseRuntimeFunction
;
195 /// void objc_storeStrong(id*, id);
196 llvm::Function
*objc_storeStrong
;
198 /// id objc_storeWeak(id*, id);
199 llvm::Function
*objc_storeWeak
;
201 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
202 llvm::Function
*objc_unsafeClaimAutoreleasedReturnValue
;
204 /// A void(void) inline asm to use to mark that the return value of
205 /// a call will be immediately retain.
206 llvm::InlineAsm
*retainAutoreleasedReturnValueMarker
;
208 /// void clang.arc.use(...);
209 llvm::Function
*clang_arc_use
;
211 /// void clang.arc.noop.use(...);
212 llvm::Function
*clang_arc_noop_use
;
215 /// This class records statistics on instrumentation based profiling.
216 class InstrProfStats
{
217 uint32_t VisitedInMainFile
;
218 uint32_t MissingInMainFile
;
225 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
227 /// Record that we've visited a function and whether or not that function was
228 /// in the main source file.
229 void addVisited(bool MainFile
) {
234 /// Record that a function we've visited has no profile data.
235 void addMissing(bool MainFile
) {
240 /// Record that a function we've visited has mismatched profile data.
241 void addMismatched(bool MainFile
) { ++Mismatched
; }
242 /// Whether or not the stats we've gathered indicate any potential problems.
243 bool hasDiagnostics() { return Missing
|| Mismatched
; }
244 /// Report potential problems we've found to \c Diags.
245 void reportDiagnostics(DiagnosticsEngine
&Diags
, StringRef MainFile
);
248 /// A pair of helper functions for a __block variable.
249 class BlockByrefHelpers
: public llvm::FoldingSetNode
{
250 // MSVC requires this type to be complete in order to process this
253 llvm::Constant
*CopyHelper
;
254 llvm::Constant
*DisposeHelper
;
256 /// The alignment of the field. This is important because
257 /// different offsets to the field within the byref struct need to
258 /// have different helper functions.
261 BlockByrefHelpers(CharUnits alignment
)
262 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment
) {}
263 BlockByrefHelpers(const BlockByrefHelpers
&) = default;
264 virtual ~BlockByrefHelpers();
266 void Profile(llvm::FoldingSetNodeID
&id
) const {
267 id
.AddInteger(Alignment
.getQuantity());
270 virtual void profileImpl(llvm::FoldingSetNodeID
&id
) const = 0;
272 virtual bool needsCopy() const { return true; }
273 virtual void emitCopy(CodeGenFunction
&CGF
, Address dest
, Address src
) = 0;
275 virtual bool needsDispose() const { return true; }
276 virtual void emitDispose(CodeGenFunction
&CGF
, Address field
) = 0;
279 /// This class organizes the cross-function state that is used while generating
281 class CodeGenModule
: public CodeGenTypeCache
{
282 CodeGenModule(const CodeGenModule
&) = delete;
283 void operator=(const CodeGenModule
&) = delete;
288 : Priority(0), LexOrder(~0u), Initializer(nullptr),
289 AssociatedData(nullptr) {}
290 Structor(int Priority
, unsigned LexOrder
, llvm::Constant
*Initializer
,
291 llvm::Constant
*AssociatedData
)
292 : Priority(Priority
), LexOrder(LexOrder
), Initializer(Initializer
),
293 AssociatedData(AssociatedData
) {}
296 llvm::Constant
*Initializer
;
297 llvm::Constant
*AssociatedData
;
300 typedef std::vector
<Structor
> CtorList
;
304 const LangOptions
&LangOpts
;
305 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
; // Only used for debug info.
306 const HeaderSearchOptions
&HeaderSearchOpts
; // Only used for debug info.
307 const PreprocessorOptions
&PreprocessorOpts
; // Only used for debug info.
308 const CodeGenOptions
&CodeGenOpts
;
309 unsigned NumAutoVarInit
= 0;
310 llvm::Module
&TheModule
;
311 DiagnosticsEngine
&Diags
;
312 const TargetInfo
&Target
;
313 std::unique_ptr
<CGCXXABI
> ABI
;
314 llvm::LLVMContext
&VMContext
;
315 std::string ModuleNameHash
;
316 bool CXX20ModuleInits
= false;
317 std::unique_ptr
<CodeGenTBAA
> TBAA
;
319 mutable std::unique_ptr
<TargetCodeGenInfo
> TheTargetCodeGenInfo
;
321 // This should not be moved earlier, since its initialization depends on some
322 // of the previous reference members being already initialized and also checks
323 // if TheTargetCodeGenInfo is NULL
326 /// Holds information about C++ vtables.
327 CodeGenVTables VTables
;
329 std::unique_ptr
<CGObjCRuntime
> ObjCRuntime
;
330 std::unique_ptr
<CGOpenCLRuntime
> OpenCLRuntime
;
331 std::unique_ptr
<CGOpenMPRuntime
> OpenMPRuntime
;
332 std::unique_ptr
<CGCUDARuntime
> CUDARuntime
;
333 std::unique_ptr
<CGHLSLRuntime
> HLSLRuntime
;
334 std::unique_ptr
<CGDebugInfo
> DebugInfo
;
335 std::unique_ptr
<ObjCEntrypoints
> ObjCData
;
336 llvm::MDNode
*NoObjCARCExceptionsMetadata
= nullptr;
337 std::unique_ptr
<llvm::IndexedInstrProfReader
> PGOReader
;
338 InstrProfStats PGOStats
;
339 std::unique_ptr
<llvm::SanitizerStatReport
> SanStats
;
341 // A set of references that have only been seen via a weakref so far. This is
342 // used to remove the weak of the reference if we ever see a direct reference
344 llvm::SmallPtrSet
<llvm::GlobalValue
*, 10> WeakRefReferences
;
346 /// This contains all the decls which have definitions but/ which are deferred
347 /// for emission and therefore should only be output if they are actually
348 /// used. If a decl is in this, then it is known to have not been referenced
350 llvm::DenseMap
<StringRef
, GlobalDecl
> DeferredDecls
;
352 /// This is a list of deferred decls which we have seen that *are* actually
353 /// referenced. These get code generated when the module is done.
354 std::vector
<GlobalDecl
> DeferredDeclsToEmit
;
355 void addDeferredDeclToEmit(GlobalDecl GD
) {
356 DeferredDeclsToEmit
.emplace_back(GD
);
357 addEmittedDeferredDecl(GD
);
360 /// Decls that were DeferredDecls and have now been emitted.
361 llvm::DenseMap
<llvm::StringRef
, GlobalDecl
> EmittedDeferredDecls
;
363 void addEmittedDeferredDecl(GlobalDecl GD
) {
364 // Reemission is only needed in incremental mode.
365 if (!Context
.getLangOpts().IncrementalExtensions
)
368 // Assume a linkage by default that does not need reemission.
369 auto L
= llvm::GlobalValue::ExternalLinkage
;
370 if (llvm::isa
<FunctionDecl
>(GD
.getDecl()))
371 L
= getFunctionLinkage(GD
);
372 else if (auto *VD
= llvm::dyn_cast
<VarDecl
>(GD
.getDecl()))
373 L
= getLLVMLinkageVarDefinition(VD
);
375 if (llvm::GlobalValue::isInternalLinkage(L
) ||
376 llvm::GlobalValue::isLinkOnceLinkage(L
) ||
377 llvm::GlobalValue::isWeakLinkage(L
)) {
378 EmittedDeferredDecls
[getMangledName(GD
)] = GD
;
382 /// List of alias we have emitted. Used to make sure that what they point to
383 /// is defined once we get to the end of the of the translation unit.
384 std::vector
<GlobalDecl
> Aliases
;
386 /// List of multiversion functions to be emitted. This list is processed in
387 /// conjunction with other deferred symbols and is used to ensure that
388 /// multiversion function resolvers and ifuncs are defined and emitted.
389 std::vector
<GlobalDecl
> MultiVersionFuncs
;
391 llvm::MapVector
<StringRef
, llvm::TrackingVH
<llvm::Constant
>> Replacements
;
393 /// List of global values to be replaced with something else. Used when we
394 /// want to replace a GlobalValue but can't identify it by its mangled name
395 /// anymore (because the name is already taken).
396 llvm::SmallVector
<std::pair
<llvm::GlobalValue
*, llvm::Constant
*>, 8>
397 GlobalValReplacements
;
399 /// Variables for which we've emitted globals containing their constant
400 /// values along with the corresponding globals, for opportunistic reuse.
401 llvm::DenseMap
<const VarDecl
*, llvm::GlobalVariable
*> InitializerConstants
;
403 /// Set of global decls for which we already diagnosed mangled name conflict.
404 /// Required to not issue a warning (on a mangling conflict) multiple times
405 /// for the same decl.
406 llvm::DenseSet
<GlobalDecl
> DiagnosedConflictingDefinitions
;
408 /// A queue of (optional) vtables to consider emitting.
409 std::vector
<const CXXRecordDecl
*> DeferredVTables
;
411 /// A queue of (optional) vtables that may be emitted opportunistically.
412 std::vector
<const CXXRecordDecl
*> OpportunisticVTables
;
414 /// List of global values which are required to be present in the object file;
415 /// bitcast to i8*. This is used for forcing visibility of symbols which may
416 /// otherwise be optimized out.
417 std::vector
<llvm::WeakTrackingVH
> LLVMUsed
;
418 std::vector
<llvm::WeakTrackingVH
> LLVMCompilerUsed
;
420 /// Store the list of global constructors and their respective priorities to
421 /// be emitted when the translation unit is complete.
422 CtorList GlobalCtors
;
424 /// Store the list of global destructors and their respective priorities to be
425 /// emitted when the translation unit is complete.
426 CtorList GlobalDtors
;
428 /// An ordered map of canonical GlobalDecls to their mangled names.
429 llvm::MapVector
<GlobalDecl
, StringRef
> MangledDeclNames
;
430 llvm::StringMap
<GlobalDecl
, llvm::BumpPtrAllocator
> Manglings
;
432 /// Global annotations.
433 std::vector
<llvm::Constant
*> Annotations
;
435 /// Map used to get unique annotation strings.
436 llvm::StringMap
<llvm::Constant
*> AnnotationStrings
;
438 /// Used for uniquing of annotation arguments.
439 llvm::DenseMap
<unsigned, llvm::Constant
*> AnnotationArgs
;
441 llvm::StringMap
<llvm::GlobalVariable
*> CFConstantStringMap
;
443 llvm::DenseMap
<llvm::Constant
*, llvm::GlobalVariable
*> ConstantStringMap
;
444 llvm::DenseMap
<const UnnamedGlobalConstantDecl
*, llvm::GlobalVariable
*>
445 UnnamedGlobalConstantDeclMap
;
446 llvm::DenseMap
<const Decl
*, llvm::Constant
*> StaticLocalDeclMap
;
447 llvm::DenseMap
<const Decl
*, llvm::GlobalVariable
*> StaticLocalDeclGuardMap
;
448 llvm::DenseMap
<const Expr
*, llvm::Constant
*> MaterializedGlobalTemporaryMap
;
450 llvm::DenseMap
<QualType
, llvm::Constant
*> AtomicSetterHelperFnMap
;
451 llvm::DenseMap
<QualType
, llvm::Constant
*> AtomicGetterHelperFnMap
;
453 /// Map used to get unique type descriptor constants for sanitizers.
454 llvm::DenseMap
<QualType
, llvm::Constant
*> TypeDescriptorMap
;
456 /// Map used to track internal linkage functions declared within
457 /// extern "C" regions.
458 typedef llvm::MapVector
<IdentifierInfo
*,
459 llvm::GlobalValue
*> StaticExternCMap
;
460 StaticExternCMap StaticExternCValues
;
462 /// thread_local variables defined or used in this TU.
463 std::vector
<const VarDecl
*> CXXThreadLocals
;
465 /// thread_local variables with initializers that need to run
466 /// before any thread_local variable in this TU is odr-used.
467 std::vector
<llvm::Function
*> CXXThreadLocalInits
;
468 std::vector
<const VarDecl
*> CXXThreadLocalInitVars
;
470 /// Global variables with initializers that need to run before main.
471 std::vector
<llvm::Function
*> CXXGlobalInits
;
473 /// When a C++ decl with an initializer is deferred, null is
474 /// appended to CXXGlobalInits, and the index of that null is placed
475 /// here so that the initializer will be performed in the correct
476 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
477 /// that we don't re-emit the initializer.
478 llvm::DenseMap
<const Decl
*, unsigned> DelayedCXXInitPosition
;
480 typedef std::pair
<OrderGlobalInitsOrStermFinalizers
, llvm::Function
*>
483 struct GlobalInitPriorityCmp
{
484 bool operator()(const GlobalInitData
&LHS
,
485 const GlobalInitData
&RHS
) const {
486 return LHS
.first
.priority
< RHS
.first
.priority
;
490 /// Global variables with initializers whose order of initialization is set by
491 /// init_priority attribute.
492 SmallVector
<GlobalInitData
, 8> PrioritizedCXXGlobalInits
;
494 /// Global destructor functions and arguments that need to run on termination.
495 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
496 /// functions, which also run on unloading a shared library.
497 typedef std::tuple
<llvm::FunctionType
*, llvm::WeakTrackingVH
,
499 CXXGlobalDtorsOrStermFinalizer_t
;
500 SmallVector
<CXXGlobalDtorsOrStermFinalizer_t
, 8>
501 CXXGlobalDtorsOrStermFinalizers
;
503 typedef std::pair
<OrderGlobalInitsOrStermFinalizers
, llvm::Function
*>
506 struct StermFinalizerPriorityCmp
{
507 bool operator()(const StermFinalizerData
&LHS
,
508 const StermFinalizerData
&RHS
) const {
509 return LHS
.first
.priority
< RHS
.first
.priority
;
513 /// Global variables with sterm finalizers whose order of initialization is
514 /// set by init_priority attribute.
515 SmallVector
<StermFinalizerData
, 8> PrioritizedCXXStermFinalizers
;
517 /// The complete set of modules that has been imported.
518 llvm::SetVector
<clang::Module
*> ImportedModules
;
520 /// The set of modules for which the module initializers
521 /// have been emitted.
522 llvm::SmallPtrSet
<clang::Module
*, 16> EmittedModuleInitializers
;
524 /// A vector of metadata strings for linker options.
525 SmallVector
<llvm::MDNode
*, 16> LinkerOptionsMetadata
;
527 /// A vector of metadata strings for dependent libraries for ELF.
528 SmallVector
<llvm::MDNode
*, 16> ELFDependentLibraries
;
530 /// @name Cache for Objective-C runtime types
533 /// Cached reference to the class for constant strings. This value has type
534 /// int * but is actually an Obj-C class pointer.
535 llvm::WeakTrackingVH CFConstantStringClassRef
;
537 /// The type used to describe the state of a fast enumeration in
538 /// Objective-C's for..in loop.
539 QualType ObjCFastEnumerationStateType
;
543 /// Lazily create the Objective-C runtime
544 void createObjCRuntime();
546 void createOpenCLRuntime();
547 void createOpenMPRuntime();
548 void createCUDARuntime();
549 void createHLSLRuntime();
551 bool isTriviallyRecursive(const FunctionDecl
*F
);
552 bool shouldEmitFunction(GlobalDecl GD
);
553 bool shouldOpportunisticallyEmitVTables();
554 /// Map used to be sure we don't emit the same CompoundLiteral twice.
555 llvm::DenseMap
<const CompoundLiteralExpr
*, llvm::GlobalVariable
*>
556 EmittedCompoundLiterals
;
558 /// Map of the global blocks we've emitted, so that we don't have to re-emit
559 /// them if the constexpr evaluator gets aggressive.
560 llvm::DenseMap
<const BlockExpr
*, llvm::Constant
*> EmittedGlobalBlocks
;
562 /// @name Cache for Blocks Runtime Globals
565 llvm::Constant
*NSConcreteGlobalBlock
= nullptr;
566 llvm::Constant
*NSConcreteStackBlock
= nullptr;
568 llvm::FunctionCallee BlockObjectAssign
= nullptr;
569 llvm::FunctionCallee BlockObjectDispose
= nullptr;
571 llvm::Type
*BlockDescriptorType
= nullptr;
572 llvm::Type
*GenericBlockLiteralType
= nullptr;
575 int GlobalUniqueCount
;
578 GlobalDecl initializedGlobalDecl
;
582 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
583 llvm::Function
*LifetimeStartFn
= nullptr;
585 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
586 llvm::Function
*LifetimeEndFn
= nullptr;
588 std::unique_ptr
<SanitizerMetadata
> SanitizerMD
;
590 llvm::MapVector
<const Decl
*, bool> DeferredEmptyCoverageMappingDecls
;
592 std::unique_ptr
<CoverageMappingModuleGen
> CoverageMapping
;
594 /// Mapping from canonical types to their metadata identifiers. We need to
595 /// maintain this mapping because identifiers may be formed from distinct
597 typedef llvm::DenseMap
<QualType
, llvm::Metadata
*> MetadataTypeMap
;
598 MetadataTypeMap MetadataIdMap
;
599 MetadataTypeMap VirtualMetadataIdMap
;
600 MetadataTypeMap GeneralizedMetadataIdMap
;
602 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
603 // when used with -fincremental-extensions.
604 std::pair
<std::unique_ptr
<CodeGenFunction
>, const TopLevelStmtDecl
*>
605 GlobalTopLevelStmtBlockInFlight
;
608 CodeGenModule(ASTContext
&C
, IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
,
609 const HeaderSearchOptions
&headersearchopts
,
610 const PreprocessorOptions
&ppopts
,
611 const CodeGenOptions
&CodeGenOpts
, llvm::Module
&M
,
612 DiagnosticsEngine
&Diags
,
613 CoverageSourceInfo
*CoverageInfo
= nullptr);
619 /// Finalize LLVM code generation.
622 /// Return true if we should emit location information for expressions.
623 bool getExpressionLocationsEnabled() const;
625 /// Return a reference to the configured Objective-C runtime.
626 CGObjCRuntime
&getObjCRuntime() {
627 if (!ObjCRuntime
) createObjCRuntime();
631 /// Return true iff an Objective-C runtime has been configured.
632 bool hasObjCRuntime() { return !!ObjCRuntime
; }
634 const std::string
&getModuleNameHash() const { return ModuleNameHash
; }
636 /// Return a reference to the configured OpenCL runtime.
637 CGOpenCLRuntime
&getOpenCLRuntime() {
638 assert(OpenCLRuntime
!= nullptr);
639 return *OpenCLRuntime
;
642 /// Return a reference to the configured OpenMP runtime.
643 CGOpenMPRuntime
&getOpenMPRuntime() {
644 assert(OpenMPRuntime
!= nullptr);
645 return *OpenMPRuntime
;
648 /// Return a reference to the configured CUDA runtime.
649 CGCUDARuntime
&getCUDARuntime() {
650 assert(CUDARuntime
!= nullptr);
654 /// Return a reference to the configured HLSL runtime.
655 CGHLSLRuntime
&getHLSLRuntime() {
656 assert(HLSLRuntime
!= nullptr);
660 ObjCEntrypoints
&getObjCEntrypoints() const {
661 assert(ObjCData
!= nullptr);
665 // Version checking functions, used to implement ObjC's @available:
666 // i32 @__isOSVersionAtLeast(i32, i32, i32)
667 llvm::FunctionCallee IsOSVersionAtLeastFn
= nullptr;
668 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
669 llvm::FunctionCallee IsPlatformVersionAtLeastFn
= nullptr;
671 InstrProfStats
&getPGOStats() { return PGOStats
; }
672 llvm::IndexedInstrProfReader
*getPGOReader() const { return PGOReader
.get(); }
674 CoverageMappingModuleGen
*getCoverageMapping() const {
675 return CoverageMapping
.get();
678 llvm::Constant
*getStaticLocalDeclAddress(const VarDecl
*D
) {
679 return StaticLocalDeclMap
[D
];
681 void setStaticLocalDeclAddress(const VarDecl
*D
,
683 StaticLocalDeclMap
[D
] = C
;
687 getOrCreateStaticVarDecl(const VarDecl
&D
,
688 llvm::GlobalValue::LinkageTypes Linkage
);
690 llvm::GlobalVariable
*getStaticLocalDeclGuardAddress(const VarDecl
*D
) {
691 return StaticLocalDeclGuardMap
[D
];
693 void setStaticLocalDeclGuardAddress(const VarDecl
*D
,
694 llvm::GlobalVariable
*C
) {
695 StaticLocalDeclGuardMap
[D
] = C
;
698 Address
createUnnamedGlobalFrom(const VarDecl
&D
, llvm::Constant
*Constant
,
701 bool lookupRepresentativeDecl(StringRef MangledName
,
702 GlobalDecl
&Result
) const;
704 llvm::Constant
*getAtomicSetterHelperFnMap(QualType Ty
) {
705 return AtomicSetterHelperFnMap
[Ty
];
707 void setAtomicSetterHelperFnMap(QualType Ty
,
708 llvm::Constant
*Fn
) {
709 AtomicSetterHelperFnMap
[Ty
] = Fn
;
712 llvm::Constant
*getAtomicGetterHelperFnMap(QualType Ty
) {
713 return AtomicGetterHelperFnMap
[Ty
];
715 void setAtomicGetterHelperFnMap(QualType Ty
,
716 llvm::Constant
*Fn
) {
717 AtomicGetterHelperFnMap
[Ty
] = Fn
;
720 llvm::Constant
*getTypeDescriptorFromMap(QualType Ty
) {
721 return TypeDescriptorMap
[Ty
];
723 void setTypeDescriptorInMap(QualType Ty
, llvm::Constant
*C
) {
724 TypeDescriptorMap
[Ty
] = C
;
727 CGDebugInfo
*getModuleDebugInfo() { return DebugInfo
.get(); }
729 llvm::MDNode
*getNoObjCARCExceptionsMetadata() {
730 if (!NoObjCARCExceptionsMetadata
)
731 NoObjCARCExceptionsMetadata
=
732 llvm::MDNode::get(getLLVMContext(), std::nullopt
);
733 return NoObjCARCExceptionsMetadata
;
736 ASTContext
&getContext() const { return Context
; }
737 const LangOptions
&getLangOpts() const { return LangOpts
; }
738 const IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> &getFileSystem() const {
741 const HeaderSearchOptions
&getHeaderSearchOpts()
742 const { return HeaderSearchOpts
; }
743 const PreprocessorOptions
&getPreprocessorOpts()
744 const { return PreprocessorOpts
; }
745 const CodeGenOptions
&getCodeGenOpts() const { return CodeGenOpts
; }
746 llvm::Module
&getModule() const { return TheModule
; }
747 DiagnosticsEngine
&getDiags() const { return Diags
; }
748 const llvm::DataLayout
&getDataLayout() const {
749 return TheModule
.getDataLayout();
751 const TargetInfo
&getTarget() const { return Target
; }
752 const llvm::Triple
&getTriple() const { return Target
.getTriple(); }
753 bool supportsCOMDAT() const;
754 void maybeSetTrivialComdat(const Decl
&D
, llvm::GlobalObject
&GO
);
756 CGCXXABI
&getCXXABI() const { return *ABI
; }
757 llvm::LLVMContext
&getLLVMContext() { return VMContext
; }
759 bool shouldUseTBAA() const { return TBAA
!= nullptr; }
761 const TargetCodeGenInfo
&getTargetCodeGenInfo();
763 CodeGenTypes
&getTypes() { return Types
; }
765 CodeGenVTables
&getVTables() { return VTables
; }
767 ItaniumVTableContext
&getItaniumVTableContext() {
768 return VTables
.getItaniumVTableContext();
771 const ItaniumVTableContext
&getItaniumVTableContext() const {
772 return VTables
.getItaniumVTableContext();
775 MicrosoftVTableContext
&getMicrosoftVTableContext() {
776 return VTables
.getMicrosoftVTableContext();
779 CtorList
&getGlobalCtors() { return GlobalCtors
; }
780 CtorList
&getGlobalDtors() { return GlobalDtors
; }
782 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
784 llvm::MDNode
*getTBAATypeInfo(QualType QTy
);
786 /// getTBAAAccessInfo - Get TBAA information that describes an access to
787 /// an object of the given type.
788 TBAAAccessInfo
getTBAAAccessInfo(QualType AccessType
);
790 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
791 /// access to a virtual table pointer.
792 TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type
*VTablePtrType
);
794 llvm::MDNode
*getTBAAStructInfo(QualType QTy
);
796 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
797 /// type. Return null if the type is not suitable for use in TBAA access tags.
798 llvm::MDNode
*getTBAABaseTypeInfo(QualType QTy
);
800 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
801 llvm::MDNode
*getTBAAAccessTagInfo(TBAAAccessInfo Info
);
803 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
805 TBAAAccessInfo
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo
,
806 TBAAAccessInfo TargetInfo
);
808 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
809 /// purposes of conditional operator.
810 TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA
,
811 TBAAAccessInfo InfoB
);
813 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
814 /// purposes of memory transfer calls.
815 TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo
,
816 TBAAAccessInfo SrcInfo
);
818 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
820 TBAAAccessInfo
getTBAAInfoForSubobject(LValue Base
, QualType AccessType
) {
821 if (Base
.getTBAAInfo().isMayAlias())
822 return TBAAAccessInfo::getMayAliasInfo();
823 return getTBAAAccessInfo(AccessType
);
826 bool isPaddedAtomicType(QualType type
);
827 bool isPaddedAtomicType(const AtomicType
*type
);
829 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
830 void DecorateInstructionWithTBAA(llvm::Instruction
*Inst
,
831 TBAAAccessInfo TBAAInfo
);
833 /// Adds !invariant.barrier !tag to instruction
834 void DecorateInstructionWithInvariantGroup(llvm::Instruction
*I
,
835 const CXXRecordDecl
*RD
);
837 /// Emit the given number of characters as a value of type size_t.
838 llvm::ConstantInt
*getSize(CharUnits numChars
);
840 /// Set the visibility for the given LLVM GlobalValue.
841 void setGlobalVisibility(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
843 void setDSOLocal(llvm::GlobalValue
*GV
) const;
845 bool shouldMapVisibilityToDLLExport(const NamedDecl
*D
) const {
846 return getLangOpts().hasDefaultVisibilityExportMapping() && D
&&
847 (D
->getLinkageAndVisibility().getVisibility() ==
848 DefaultVisibility
) &&
849 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
850 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
851 D
->getLinkageAndVisibility().isVisibilityExplicit()));
853 void setDLLImportDLLExport(llvm::GlobalValue
*GV
, GlobalDecl D
) const;
854 void setDLLImportDLLExport(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
855 /// Set visibility, dllimport/dllexport and dso_local.
856 /// This must be called after dllimport/dllexport is set.
857 void setGVProperties(llvm::GlobalValue
*GV
, GlobalDecl GD
) const;
858 void setGVProperties(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
860 void setGVPropertiesAux(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
862 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
863 /// variable declaration D.
864 void setTLSMode(llvm::GlobalValue
*GV
, const VarDecl
&D
) const;
866 /// Get LLVM TLS mode from CodeGenOptions.
867 llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const;
869 static llvm::GlobalValue::VisibilityTypes
GetLLVMVisibility(Visibility V
) {
871 case DefaultVisibility
: return llvm::GlobalValue::DefaultVisibility
;
872 case HiddenVisibility
: return llvm::GlobalValue::HiddenVisibility
;
873 case ProtectedVisibility
: return llvm::GlobalValue::ProtectedVisibility
;
875 llvm_unreachable("unknown visibility!");
878 llvm::Constant
*GetAddrOfGlobal(GlobalDecl GD
,
879 ForDefinition_t IsForDefinition
882 /// Will return a global variable of the given type. If a variable with a
883 /// different type already exists then a new variable with the right type
884 /// will be created and all uses of the old variable will be replaced with a
885 /// bitcast to the new variable.
886 llvm::GlobalVariable
*
887 CreateOrReplaceCXXRuntimeVariable(StringRef Name
, llvm::Type
*Ty
,
888 llvm::GlobalValue::LinkageTypes Linkage
,
889 llvm::Align Alignment
);
891 llvm::Function
*CreateGlobalInitOrCleanUpFunction(
892 llvm::FunctionType
*ty
, const Twine
&name
, const CGFunctionInfo
&FI
,
893 SourceLocation Loc
= SourceLocation(), bool TLS
= false,
894 llvm::GlobalVariable::LinkageTypes Linkage
=
895 llvm::GlobalVariable::InternalLinkage
);
897 /// Return the AST address space of the underlying global variable for D, as
898 /// determined by its declaration. Normally this is the same as the address
899 /// space of D's type, but in CUDA, address spaces are associated with
900 /// declarations, not types. If D is nullptr, return the default address
901 /// space for global variable.
903 /// For languages without explicit address spaces, if D has default address
904 /// space, target-specific global or constant address space may be returned.
905 LangAS
GetGlobalVarAddressSpace(const VarDecl
*D
);
907 /// Return the AST address space of constant literal, which is used to emit
908 /// the constant literal as global variable in LLVM IR.
909 /// Note: This is not necessarily the address space of the constant literal
910 /// in AST. For address space agnostic language, e.g. C++, constant literal
911 /// in AST is always in default address space.
912 LangAS
GetGlobalConstantAddressSpace() const;
914 /// Return the llvm::Constant for the address of the given global variable.
915 /// If Ty is non-null and if the global doesn't exist, then it will be created
916 /// with the specified type instead of whatever the normal requested type
917 /// would be. If IsForDefinition is true, it is guaranteed that an actual
918 /// global with type Ty will be returned, not conversion of a variable with
919 /// the same mangled name but some other type.
920 llvm::Constant
*GetAddrOfGlobalVar(const VarDecl
*D
,
921 llvm::Type
*Ty
= nullptr,
922 ForDefinition_t IsForDefinition
925 /// Return the address of the given function. If Ty is non-null, then this
926 /// function will use the specified type if it has to create it.
927 llvm::Constant
*GetAddrOfFunction(GlobalDecl GD
, llvm::Type
*Ty
= nullptr,
928 bool ForVTable
= false,
929 bool DontDefer
= false,
930 ForDefinition_t IsForDefinition
933 // Return the function body address of the given function.
934 llvm::Constant
*GetFunctionStart(const ValueDecl
*Decl
);
936 // Return whether RTTI information should be emitted for this target.
937 bool shouldEmitRTTI(bool ForEH
= false) {
938 return (ForEH
|| getLangOpts().RTTI
) && !getLangOpts().CUDAIsDevice
&&
939 !(getLangOpts().OpenMP
&& getLangOpts().OpenMPIsTargetDevice
&&
940 getTriple().isNVPTX());
943 /// Get the address of the RTTI descriptor for the given type.
944 llvm::Constant
*GetAddrOfRTTIDescriptor(QualType Ty
, bool ForEH
= false);
946 /// Get the address of a GUID.
947 ConstantAddress
GetAddrOfMSGuidDecl(const MSGuidDecl
*GD
);
949 /// Get the address of a UnnamedGlobalConstant
951 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl
*GCD
);
953 /// Get the address of a template parameter object.
955 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl
*TPO
);
957 /// Get the address of the thunk for the given global decl.
958 llvm::Constant
*GetAddrOfThunk(StringRef Name
, llvm::Type
*FnTy
,
961 /// Get a reference to the target of VD.
962 ConstantAddress
GetWeakRefReference(const ValueDecl
*VD
);
964 /// Returns the assumed alignment of an opaque pointer to the given class.
965 CharUnits
getClassPointerAlignment(const CXXRecordDecl
*CD
);
967 /// Returns the minimum object size for an object of the given class type
968 /// (or a class derived from it).
969 CharUnits
getMinimumClassObjectSize(const CXXRecordDecl
*CD
);
971 /// Returns the minimum object size for an object of the given type.
972 CharUnits
getMinimumObjectSize(QualType Ty
) {
973 if (CXXRecordDecl
*RD
= Ty
->getAsCXXRecordDecl())
974 return getMinimumClassObjectSize(RD
);
975 return getContext().getTypeSizeInChars(Ty
);
978 /// Returns the assumed alignment of a virtual base of a class.
979 CharUnits
getVBaseAlignment(CharUnits DerivedAlign
,
980 const CXXRecordDecl
*Derived
,
981 const CXXRecordDecl
*VBase
);
983 /// Given a class pointer with an actual known alignment, and the
984 /// expected alignment of an object at a dynamic offset w.r.t that
985 /// pointer, return the alignment to assume at the offset.
986 CharUnits
getDynamicOffsetAlignment(CharUnits ActualAlign
,
987 const CXXRecordDecl
*Class
,
988 CharUnits ExpectedTargetAlign
);
991 computeNonVirtualBaseClassOffset(const CXXRecordDecl
*DerivedClass
,
992 CastExpr::path_const_iterator Start
,
993 CastExpr::path_const_iterator End
);
995 /// Returns the offset from a derived class to a class. Returns null if the
998 GetNonVirtualBaseClassOffset(const CXXRecordDecl
*ClassDecl
,
999 CastExpr::path_const_iterator PathBegin
,
1000 CastExpr::path_const_iterator PathEnd
);
1002 llvm::FoldingSet
<BlockByrefHelpers
> ByrefHelpersCache
;
1004 /// Fetches the global unique block count.
1005 int getUniqueBlockCount() { return ++Block
.GlobalUniqueCount
; }
1007 /// Fetches the type of a generic block descriptor.
1008 llvm::Type
*getBlockDescriptorType();
1010 /// The type of a generic block literal.
1011 llvm::Type
*getGenericBlockLiteralType();
1013 /// Gets the address of a block which requires no captures.
1014 llvm::Constant
*GetAddrOfGlobalBlock(const BlockExpr
*BE
, StringRef Name
);
1016 /// Returns the address of a block which requires no caputres, or null if
1017 /// we've yet to emit the block for BE.
1018 llvm::Constant
*getAddrOfGlobalBlockIfEmitted(const BlockExpr
*BE
) {
1019 return EmittedGlobalBlocks
.lookup(BE
);
1022 /// Notes that BE's global block is available via Addr. Asserts that BE
1023 /// isn't already emitted.
1024 void setAddrOfGlobalBlock(const BlockExpr
*BE
, llvm::Constant
*Addr
);
1026 /// Return a pointer to a constant CFString object for the given string.
1027 ConstantAddress
GetAddrOfConstantCFString(const StringLiteral
*Literal
);
1029 /// Return a constant array for the given string.
1030 llvm::Constant
*GetConstantArrayFromStringLiteral(const StringLiteral
*E
);
1032 /// Return a pointer to a constant array for the given string literal.
1034 GetAddrOfConstantStringFromLiteral(const StringLiteral
*S
,
1035 StringRef Name
= ".str");
1037 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1039 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr
*);
1041 /// Returns a pointer to a character array containing the literal and a
1042 /// terminating '\0' character. The result has pointer to array type.
1044 /// \param GlobalName If provided, the name to use for the global (if one is
1047 GetAddrOfConstantCString(const std::string
&Str
,
1048 const char *GlobalName
= nullptr);
1050 /// Returns a pointer to a constant global variable for the given file-scope
1051 /// compound literal expression.
1052 ConstantAddress
GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr
*E
);
1054 /// If it's been emitted already, returns the GlobalVariable corresponding to
1055 /// a compound literal. Otherwise, returns null.
1056 llvm::GlobalVariable
*
1057 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr
*E
);
1059 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1061 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr
*CLE
,
1062 llvm::GlobalVariable
*GV
);
1064 /// Returns a pointer to a global variable representing a temporary
1065 /// with static or thread storage duration.
1066 ConstantAddress
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr
*E
,
1069 /// Retrieve the record type that describes the state of an
1070 /// Objective-C fast enumeration loop (for..in).
1071 QualType
getObjCFastEnumerationStateType();
1073 // Produce code for this constructor/destructor. This method doesn't try
1074 // to apply any ABI rules about which other constructors/destructors
1075 // are needed or if they are alias to each other.
1076 llvm::Function
*codegenCXXStructor(GlobalDecl GD
);
1078 /// Return the address of the constructor/destructor of the given type.
1080 getAddrOfCXXStructor(GlobalDecl GD
, const CGFunctionInfo
*FnInfo
= nullptr,
1081 llvm::FunctionType
*FnType
= nullptr,
1082 bool DontDefer
= false,
1083 ForDefinition_t IsForDefinition
= NotForDefinition
) {
1084 return cast
<llvm::Constant
>(getAddrAndTypeOfCXXStructor(GD
, FnInfo
, FnType
,
1090 llvm::FunctionCallee
getAddrAndTypeOfCXXStructor(
1091 GlobalDecl GD
, const CGFunctionInfo
*FnInfo
= nullptr,
1092 llvm::FunctionType
*FnType
= nullptr, bool DontDefer
= false,
1093 ForDefinition_t IsForDefinition
= NotForDefinition
);
1095 /// Given a builtin id for a function like "__builtin_fabsf", return a
1096 /// Function* for "fabsf".
1097 llvm::Constant
*getBuiltinLibFunction(const FunctionDecl
*FD
,
1098 unsigned BuiltinID
);
1100 llvm::Function
*getIntrinsic(unsigned IID
,
1101 ArrayRef
<llvm::Type
*> Tys
= std::nullopt
);
1103 /// Emit code for a single top level declaration.
1104 void EmitTopLevelDecl(Decl
*D
);
1106 /// Stored a deferred empty coverage mapping for an unused
1107 /// and thus uninstrumented top level declaration.
1108 void AddDeferredUnusedCoverageMapping(Decl
*D
);
1110 /// Remove the deferred empty coverage mapping as this
1111 /// declaration is actually instrumented.
1112 void ClearUnusedCoverageMapping(const Decl
*D
);
1114 /// Emit all the deferred coverage mappings
1115 /// for the uninstrumented functions.
1116 void EmitDeferredUnusedCoverageMappings();
1118 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1119 void EmitMainVoidAlias();
1121 /// Tell the consumer that this variable has been instantiated.
1122 void HandleCXXStaticMemberVarInstantiation(VarDecl
*VD
);
1124 /// If the declaration has internal linkage but is inside an
1125 /// extern "C" linkage specification, prepare to emit an alias for it
1126 /// to the expected name.
1127 template<typename SomeDecl
>
1128 void MaybeHandleStaticInExternC(const SomeDecl
*D
, llvm::GlobalValue
*GV
);
1130 /// Add a global to a list to be added to the llvm.used metadata.
1131 void addUsedGlobal(llvm::GlobalValue
*GV
);
1133 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1134 void addCompilerUsedGlobal(llvm::GlobalValue
*GV
);
1136 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1137 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue
*GV
);
1139 /// Add a destructor and object to add to the C++ global destructor function.
1140 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn
, llvm::Constant
*Object
) {
1141 CXXGlobalDtorsOrStermFinalizers
.emplace_back(DtorFn
.getFunctionType(),
1142 DtorFn
.getCallee(), Object
);
1145 /// Add an sterm finalizer to the C++ global cleanup function.
1146 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn
) {
1147 CXXGlobalDtorsOrStermFinalizers
.emplace_back(DtorFn
.getFunctionType(),
1148 DtorFn
.getCallee(), nullptr);
1151 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1152 void AddCXXStermFinalizerToGlobalDtor(llvm::Function
*StermFinalizer
,
1154 AddGlobalDtor(StermFinalizer
, Priority
);
1157 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function
*StermFinalizer
,
1159 OrderGlobalInitsOrStermFinalizers
Key(Priority
,
1160 PrioritizedCXXStermFinalizers
.size());
1161 PrioritizedCXXStermFinalizers
.push_back(
1162 std::make_pair(Key
, StermFinalizer
));
1165 /// Create or return a runtime function declaration with the specified type
1166 /// and name. If \p AssumeConvergent is true, the call will have the
1167 /// convergent attribute added.
1168 llvm::FunctionCallee
1169 CreateRuntimeFunction(llvm::FunctionType
*Ty
, StringRef Name
,
1170 llvm::AttributeList ExtraAttrs
= llvm::AttributeList(),
1171 bool Local
= false, bool AssumeConvergent
= false);
1173 /// Create a new runtime global variable with the specified type and name.
1174 llvm::Constant
*CreateRuntimeVariable(llvm::Type
*Ty
,
1177 ///@name Custom Blocks Runtime Interfaces
1180 llvm::Constant
*getNSConcreteGlobalBlock();
1181 llvm::Constant
*getNSConcreteStackBlock();
1182 llvm::FunctionCallee
getBlockObjectAssign();
1183 llvm::FunctionCallee
getBlockObjectDispose();
1187 llvm::Function
*getLLVMLifetimeStartFn();
1188 llvm::Function
*getLLVMLifetimeEndFn();
1190 // Make sure that this type is translated.
1191 void UpdateCompletedType(const TagDecl
*TD
);
1193 llvm::Constant
*getMemberPointerConstant(const UnaryOperator
*e
);
1195 /// Emit type info if type of an expression is a variably modified
1196 /// type. Also emit proper debug info for cast types.
1197 void EmitExplicitCastExprType(const ExplicitCastExpr
*E
,
1198 CodeGenFunction
*CGF
= nullptr);
1200 /// Return the result of value-initializing the given type, i.e. a null
1201 /// expression of the given type. This is usually, but not always, an LLVM
1203 llvm::Constant
*EmitNullConstant(QualType T
);
1205 /// Return a null constant appropriate for zero-initializing a base class with
1206 /// the given type. This is usually, but not always, an LLVM null constant.
1207 llvm::Constant
*EmitNullConstantForBase(const CXXRecordDecl
*Record
);
1209 /// Emit a general error that something can't be done.
1210 void Error(SourceLocation loc
, StringRef error
);
1212 /// Print out an error that codegen doesn't support the specified stmt yet.
1213 void ErrorUnsupported(const Stmt
*S
, const char *Type
);
1215 /// Print out an error that codegen doesn't support the specified decl yet.
1216 void ErrorUnsupported(const Decl
*D
, const char *Type
);
1218 /// Set the attributes on the LLVM function for the given decl and function
1219 /// info. This applies attributes necessary for handling the ABI as well as
1220 /// user specified attributes like section.
1221 void SetInternalFunctionAttributes(GlobalDecl GD
, llvm::Function
*F
,
1222 const CGFunctionInfo
&FI
);
1224 /// Set the LLVM function attributes (sext, zext, etc).
1225 void SetLLVMFunctionAttributes(GlobalDecl GD
, const CGFunctionInfo
&Info
,
1226 llvm::Function
*F
, bool IsThunk
);
1228 /// Set the LLVM function attributes which only apply to a function
1230 void SetLLVMFunctionAttributesForDefinition(const Decl
*D
, llvm::Function
*F
);
1232 /// Set the LLVM function attributes that represent floating point
1234 void setLLVMFunctionFEnvAttributes(const FunctionDecl
*D
, llvm::Function
*F
);
1236 /// Return true iff the given type uses 'sret' when used as a return type.
1237 bool ReturnTypeUsesSRet(const CGFunctionInfo
&FI
);
1239 /// Return true iff the given type uses an argument slot when 'sret' is used
1240 /// as a return type.
1241 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo
&FI
);
1243 /// Return true iff the given type uses 'fpret' when used as a return type.
1244 bool ReturnTypeUsesFPRet(QualType ResultType
);
1246 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1247 bool ReturnTypeUsesFP2Ret(QualType ResultType
);
1249 /// Get the LLVM attributes and calling convention to use for a particular
1252 /// \param Name - The function name.
1253 /// \param Info - The function type information.
1254 /// \param CalleeInfo - The callee information these attributes are being
1255 /// constructed for. If valid, the attributes applied to this decl may
1256 /// contribute to the function attributes and calling convention.
1257 /// \param Attrs [out] - On return, the attribute list to use.
1258 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1259 void ConstructAttributeList(StringRef Name
, const CGFunctionInfo
&Info
,
1260 CGCalleeInfo CalleeInfo
,
1261 llvm::AttributeList
&Attrs
, unsigned &CallingConv
,
1262 bool AttrOnCallSite
, bool IsThunk
);
1264 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1265 /// though we had emitted it ourselves. We remove any attributes on F that
1266 /// conflict with the attributes we add here.
1268 /// This is useful for adding attrs to bitcode modules that you want to link
1269 /// with but don't control, such as CUDA's libdevice. When linking with such
1270 /// a bitcode library, you might want to set e.g. its functions'
1271 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1272 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1273 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1274 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1275 /// function in the bitcode library!
1277 /// With the exception of fast-math attrs, this will only make the attributes
1278 /// on the function more conservative. But it's unsafe to call this on a
1279 /// function which relies on particular fast-math attributes for correctness.
1280 /// It's up to you to ensure that this is safe.
1281 void addDefaultFunctionDefinitionAttributes(llvm::Function
&F
);
1282 void mergeDefaultFunctionDefinitionAttributes(llvm::Function
&F
,
1283 bool WillInternalize
);
1285 /// Like the overload taking a `Function &`, but intended specifically
1286 /// for frontends that want to build on Clang's target-configuration logic.
1287 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder
&attrs
);
1289 StringRef
getMangledName(GlobalDecl GD
);
1290 StringRef
getBlockMangledName(GlobalDecl GD
, const BlockDecl
*BD
);
1291 const GlobalDecl
getMangledNameDecl(StringRef
);
1293 void EmitTentativeDefinition(const VarDecl
*D
);
1295 void EmitExternalDeclaration(const VarDecl
*D
);
1297 void EmitVTable(CXXRecordDecl
*Class
);
1299 void RefreshTypeCacheForClass(const CXXRecordDecl
*Class
);
1301 /// Appends Opts to the "llvm.linker.options" metadata value.
1302 void AppendLinkerOptions(StringRef Opts
);
1304 /// Appends a detect mismatch command to the linker options.
1305 void AddDetectMismatch(StringRef Name
, StringRef Value
);
1307 /// Appends a dependent lib to the appropriate metadata value.
1308 void AddDependentLib(StringRef Lib
);
1311 llvm::GlobalVariable::LinkageTypes
getFunctionLinkage(GlobalDecl GD
);
1313 void setFunctionLinkage(GlobalDecl GD
, llvm::Function
*F
) {
1314 F
->setLinkage(getFunctionLinkage(GD
));
1317 /// Return the appropriate linkage for the vtable, VTT, and type information
1318 /// of the given class.
1319 llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl
*RD
);
1321 /// Return the store size, in character units, of the given LLVM type.
1322 CharUnits
GetTargetTypeStoreSize(llvm::Type
*Ty
) const;
1324 /// Returns LLVM linkage for a declarator.
1325 llvm::GlobalValue::LinkageTypes
1326 getLLVMLinkageForDeclarator(const DeclaratorDecl
*D
, GVALinkage Linkage
);
1328 /// Returns LLVM linkage for a declarator.
1329 llvm::GlobalValue::LinkageTypes
1330 getLLVMLinkageVarDefinition(const VarDecl
*VD
);
1332 /// Emit all the global annotations.
1333 void EmitGlobalAnnotations();
1335 /// Emit an annotation string.
1336 llvm::Constant
*EmitAnnotationString(StringRef Str
);
1338 /// Emit the annotation's translation unit.
1339 llvm::Constant
*EmitAnnotationUnit(SourceLocation Loc
);
1341 /// Emit the annotation line number.
1342 llvm::Constant
*EmitAnnotationLineNo(SourceLocation L
);
1344 /// Emit additional args of the annotation.
1345 llvm::Constant
*EmitAnnotationArgs(const AnnotateAttr
*Attr
);
1347 /// Generate the llvm::ConstantStruct which contains the annotation
1348 /// information for a given GlobalValue. The annotation struct is
1349 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1350 /// GlobalValue being annotated. The second field is the constant string
1351 /// created from the AnnotateAttr's annotation. The third field is a constant
1352 /// string containing the name of the translation unit. The fourth field is
1353 /// the line number in the file of the annotated value declaration.
1354 llvm::Constant
*EmitAnnotateAttr(llvm::GlobalValue
*GV
,
1355 const AnnotateAttr
*AA
,
1358 /// Add global annotations that are set on D, for the global GV. Those
1359 /// annotations are emitted during finalization of the LLVM code.
1360 void AddGlobalAnnotations(const ValueDecl
*D
, llvm::GlobalValue
*GV
);
1362 bool isInNoSanitizeList(SanitizerMask Kind
, llvm::Function
*Fn
,
1363 SourceLocation Loc
) const;
1365 bool isInNoSanitizeList(SanitizerMask Kind
, llvm::GlobalVariable
*GV
,
1366 SourceLocation Loc
, QualType Ty
,
1367 StringRef Category
= StringRef()) const;
1369 /// Imbue XRay attributes to a function, applying the always/never attribute
1370 /// lists in the process. Returns true if we did imbue attributes this way,
1371 /// false otherwise.
1372 bool imbueXRayAttrs(llvm::Function
*Fn
, SourceLocation Loc
,
1373 StringRef Category
= StringRef()) const;
1375 /// \returns true if \p Fn at \p Loc should be excluded from profile
1376 /// instrumentation by the SCL passed by \p -fprofile-list.
1377 ProfileList::ExclusionType
1378 isFunctionBlockedByProfileList(llvm::Function
*Fn
, SourceLocation Loc
) const;
1380 /// \returns true if \p Fn at \p Loc should be excluded from profile
1381 /// instrumentation.
1382 ProfileList::ExclusionType
1383 isFunctionBlockedFromProfileInstr(llvm::Function
*Fn
,
1384 SourceLocation Loc
) const;
1386 SanitizerMetadata
*getSanitizerMetadata() {
1387 return SanitizerMD
.get();
1390 void addDeferredVTable(const CXXRecordDecl
*RD
) {
1391 DeferredVTables
.push_back(RD
);
1394 /// Emit code for a single global function or var decl. Forward declarations
1395 /// are emitted lazily.
1396 void EmitGlobal(GlobalDecl D
);
1398 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl
*D
);
1400 llvm::GlobalValue
*GetGlobalValue(StringRef Ref
);
1402 /// Set attributes which are common to any form of a global definition (alias,
1403 /// Objective-C method, function, global variable).
1405 /// NOTE: This should only be called for definitions.
1406 void SetCommonAttributes(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1408 void addReplacement(StringRef Name
, llvm::Constant
*C
);
1410 void addGlobalValReplacement(llvm::GlobalValue
*GV
, llvm::Constant
*C
);
1412 /// Emit a code for threadprivate directive.
1413 /// \param D Threadprivate declaration.
1414 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl
*D
);
1416 /// Emit a code for declare reduction construct.
1417 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl
*D
,
1418 CodeGenFunction
*CGF
= nullptr);
1420 /// Emit a code for declare mapper construct.
1421 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl
*D
,
1422 CodeGenFunction
*CGF
= nullptr);
1424 /// Emit a code for requires directive.
1425 /// \param D Requires declaration
1426 void EmitOMPRequiresDecl(const OMPRequiresDecl
*D
);
1428 /// Emit a code for the allocate directive.
1429 /// \param D The allocate declaration
1430 void EmitOMPAllocateDecl(const OMPAllocateDecl
*D
);
1432 /// Return the alignment specified in an allocate directive, if present.
1433 std::optional
<CharUnits
> getOMPAllocateAlignment(const VarDecl
*VD
);
1435 /// Returns whether the given record has hidden LTO visibility and therefore
1436 /// may participate in (single-module) CFI and whole-program vtable
1438 bool HasHiddenLTOVisibility(const CXXRecordDecl
*RD
);
1440 /// Returns whether the given record has public LTO visibility (regardless of
1441 /// -lto-whole-program-visibility) and therefore may not participate in
1442 /// (single-module) CFI and whole-program vtable optimization.
1443 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl
*RD
);
1445 /// Returns the vcall visibility of the given type. This is the scope in which
1446 /// a virtual function call could be made which ends up being dispatched to a
1447 /// member function of this class. This scope can be wider than the visibility
1448 /// of the class itself when the class has a more-visible dynamic base class.
1449 /// The client should pass in an empty Visited set, which is used to prevent
1450 /// redundant recursive processing.
1451 llvm::GlobalObject::VCallVisibility
1452 GetVCallVisibilityLevel(const CXXRecordDecl
*RD
,
1453 llvm::DenseSet
<const CXXRecordDecl
*> &Visited
);
1455 /// Emit type metadata for the given vtable using the given layout.
1456 void EmitVTableTypeMetadata(const CXXRecordDecl
*RD
,
1457 llvm::GlobalVariable
*VTable
,
1458 const VTableLayout
&VTLayout
);
1460 llvm::Type
*getVTableComponentType() const;
1462 /// Generate a cross-DSO type identifier for MD.
1463 llvm::ConstantInt
*CreateCrossDsoCfiTypeId(llvm::Metadata
*MD
);
1465 /// Generate a KCFI type identifier for T.
1466 llvm::ConstantInt
*CreateKCFITypeId(QualType T
);
1468 /// Create a metadata identifier for the given type. This may either be an
1469 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1470 /// internal identifiers).
1471 llvm::Metadata
*CreateMetadataIdentifierForType(QualType T
);
1473 /// Create a metadata identifier that is intended to be used to check virtual
1474 /// calls via a member function pointer.
1475 llvm::Metadata
*CreateMetadataIdentifierForVirtualMemPtrType(QualType T
);
1477 /// Create a metadata identifier for the generalization of the given type.
1478 /// This may either be an MDString (for external identifiers) or a distinct
1479 /// unnamed MDNode (for internal identifiers).
1480 llvm::Metadata
*CreateMetadataIdentifierGeneralized(QualType T
);
1482 /// Create and attach type metadata to the given function.
1483 void CreateFunctionTypeMetadataForIcall(const FunctionDecl
*FD
,
1486 /// Set type metadata to the given function.
1487 void setKCFIType(const FunctionDecl
*FD
, llvm::Function
*F
);
1489 /// Emit KCFI type identifier constants and remove unused identifiers.
1490 void finalizeKCFITypes();
1492 /// Whether this function's return type has no side effects, and thus may
1493 /// be trivially discarded if it is unused.
1494 bool MayDropFunctionReturn(const ASTContext
&Context
,
1495 QualType ReturnType
) const;
1497 /// Returns whether this module needs the "all-vtables" type identifier.
1498 bool NeedAllVtablesTypeId() const;
1500 /// Create and attach type metadata for the given vtable.
1501 void AddVTableTypeMetadata(llvm::GlobalVariable
*VTable
, CharUnits Offset
,
1502 const CXXRecordDecl
*RD
);
1504 /// Return a vector of most-base classes for RD. This is used to implement
1505 /// control flow integrity checks for member function pointers.
1507 /// A most-base class of a class C is defined as a recursive base class of C,
1508 /// including C itself, that does not have any bases.
1509 SmallVector
<const CXXRecordDecl
*, 0>
1510 getMostBaseClasses(const CXXRecordDecl
*RD
);
1512 /// Get the declaration of std::terminate for the platform.
1513 llvm::FunctionCallee
getTerminateFn();
1515 llvm::SanitizerStatReport
&getSanStats();
1518 createOpenCLIntToSamplerConversion(const Expr
*E
, CodeGenFunction
&CGF
);
1520 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1521 /// information in the program executable. The argument information stored
1522 /// includes the argument name, its type, the address and access qualifiers
1523 /// used. This helper can be used to generate metadata for source code kernel
1524 /// function as well as generated implicitly kernels. If a kernel is generated
1525 /// implicitly null value has to be passed to the last two parameters,
1526 /// otherwise all parameters must have valid non-null values.
1527 /// \param FN is a pointer to IR function being generated.
1528 /// \param FD is a pointer to function declaration if any.
1529 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1530 void GenKernelArgMetadata(llvm::Function
*FN
,
1531 const FunctionDecl
*FD
= nullptr,
1532 CodeGenFunction
*CGF
= nullptr);
1534 /// Get target specific null pointer.
1535 /// \param T is the LLVM type of the null pointer.
1536 /// \param QT is the clang QualType of the null pointer.
1537 llvm::Constant
*getNullPointer(llvm::PointerType
*T
, QualType QT
);
1539 CharUnits
getNaturalTypeAlignment(QualType T
,
1540 LValueBaseInfo
*BaseInfo
= nullptr,
1541 TBAAAccessInfo
*TBAAInfo
= nullptr,
1542 bool forPointeeType
= false);
1543 CharUnits
getNaturalPointeeTypeAlignment(QualType T
,
1544 LValueBaseInfo
*BaseInfo
= nullptr,
1545 TBAAAccessInfo
*TBAAInfo
= nullptr);
1546 bool stopAutoInit();
1548 /// Print the postfix for externalized static variable or kernels for single
1549 /// source offloading languages CUDA and HIP. The unique postfix is created
1550 /// using either the CUID argument, or the file's UniqueID and active macros.
1551 /// The fallback method without a CUID requires that the offloading toolchain
1552 /// does not define separate macros via the -cc1 options.
1553 void printPostfixForExternalizedDecl(llvm::raw_ostream
&OS
,
1554 const Decl
*D
) const;
1556 /// Move some lazily-emitted states to the NewBuilder. This is especially
1557 /// essential for the incremental parsing environment like Clang Interpreter,
1558 /// because we'll lose all important information after each repl.
1559 void moveLazyEmissionStates(CodeGenModule
*NewBuilder
);
1561 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1562 void handleCUDALaunchBoundsAttr(llvm::Function
*F
,
1563 const CUDALaunchBoundsAttr
*A
);
1565 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1566 /// to \p F. Alternatively, the work group size can be taken from a \p
1568 void handleAMDGPUFlatWorkGroupSizeAttr(
1569 llvm::Function
*F
, const AMDGPUFlatWorkGroupSizeAttr
*A
,
1570 const ReqdWorkGroupSizeAttr
*ReqdWGS
= nullptr);
1572 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1573 void handleAMDGPUWavesPerEUAttr(llvm::Function
*F
,
1574 const AMDGPUWavesPerEUAttr
*A
);
1577 llvm::Constant
*GetOrCreateLLVMFunction(
1578 StringRef MangledName
, llvm::Type
*Ty
, GlobalDecl D
, bool ForVTable
,
1579 bool DontDefer
= false, bool IsThunk
= false,
1580 llvm::AttributeList ExtraAttrs
= llvm::AttributeList(),
1581 ForDefinition_t IsForDefinition
= NotForDefinition
);
1583 // References to multiversion functions are resolved through an implicitly
1584 // defined resolver function. This function is responsible for creating
1585 // the resolver symbol for the provided declaration. The value returned
1586 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1587 // that feature and for a regular function (llvm::GlobalValue) otherwise.
1588 llvm::Constant
*GetOrCreateMultiVersionResolver(GlobalDecl GD
);
1590 // In scenarios where a function is not known to be a multiversion function
1591 // until a later declaration, it is sometimes necessary to change the
1592 // previously created mangled name to align with requirements of whatever
1593 // multiversion function kind the function is now known to be. This function
1594 // is responsible for performing such mangled name updates.
1595 void UpdateMultiVersionNames(GlobalDecl GD
, const FunctionDecl
*FD
,
1596 StringRef
&CurName
);
1599 GetOrCreateLLVMGlobal(StringRef MangledName
, llvm::Type
*Ty
, LangAS AddrSpace
,
1601 ForDefinition_t IsForDefinition
= NotForDefinition
);
1603 bool GetCPUAndFeaturesAttributes(GlobalDecl GD
,
1604 llvm::AttrBuilder
&AttrBuilder
,
1605 bool SetTargetFeatures
= true);
1606 void setNonAliasAttributes(GlobalDecl GD
, llvm::GlobalObject
*GO
);
1608 /// Set function attributes for a function declaration.
1609 void SetFunctionAttributes(GlobalDecl GD
, llvm::Function
*F
,
1610 bool IsIncompleteFunction
, bool IsThunk
);
1612 void EmitGlobalDefinition(GlobalDecl D
, llvm::GlobalValue
*GV
= nullptr);
1614 void EmitGlobalFunctionDefinition(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1615 void EmitMultiVersionFunctionDefinition(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1617 void EmitGlobalVarDefinition(const VarDecl
*D
, bool IsTentative
= false);
1618 void EmitExternalVarDeclaration(const VarDecl
*D
);
1619 void EmitAliasDefinition(GlobalDecl GD
);
1620 void emitIFuncDefinition(GlobalDecl GD
);
1621 void emitCPUDispatchDefinition(GlobalDecl GD
);
1622 void EmitObjCPropertyImplementations(const ObjCImplementationDecl
*D
);
1623 void EmitObjCIvarInitializations(ObjCImplementationDecl
*D
);
1625 // C++ related functions.
1627 void EmitDeclContext(const DeclContext
*DC
);
1628 void EmitLinkageSpec(const LinkageSpecDecl
*D
);
1629 void EmitTopLevelStmt(const TopLevelStmtDecl
*D
);
1631 /// Emit the function that initializes C++ thread_local variables.
1632 void EmitCXXThreadLocalInitFunc();
1634 /// Emit the function that initializes global variables for a C++ Module.
1635 void EmitCXXModuleInitFunc(clang::Module
*Primary
);
1637 /// Emit the function that initializes C++ globals.
1638 void EmitCXXGlobalInitFunc();
1640 /// Emit the function that performs cleanup associated with C++ globals.
1641 void EmitCXXGlobalCleanUpFunc();
1643 /// Emit the function that initializes the specified global (if PerformInit is
1644 /// true) and registers its destructor.
1645 void EmitCXXGlobalVarDeclInitFunc(const VarDecl
*D
,
1646 llvm::GlobalVariable
*Addr
,
1649 void EmitPointerToInitFunc(const VarDecl
*VD
, llvm::GlobalVariable
*Addr
,
1650 llvm::Function
*InitFunc
, InitSegAttr
*ISA
);
1652 // FIXME: Hardcoding priority here is gross.
1653 void AddGlobalCtor(llvm::Function
*Ctor
, int Priority
= 65535,
1654 unsigned LexOrder
= ~0U,
1655 llvm::Constant
*AssociatedData
= nullptr);
1656 void AddGlobalDtor(llvm::Function
*Dtor
, int Priority
= 65535,
1657 bool IsDtorAttrFunc
= false);
1659 /// EmitCtorList - Generates a global array of functions and priorities using
1660 /// the given list and name. This array will have appending linkage and is
1661 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1662 void EmitCtorList(CtorList
&Fns
, const char *GlobalName
);
1664 /// Emit any needed decls for which code generation was deferred.
1665 void EmitDeferred();
1667 /// Try to emit external vtables as available_externally if they have emitted
1668 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1669 /// is not allowed to create new references to things that need to be emitted
1671 void EmitVTablesOpportunistically();
1673 /// Call replaceAllUsesWith on all pairs in Replacements.
1674 void applyReplacements();
1676 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1677 void applyGlobalValReplacements();
1679 void checkAliases();
1681 std::map
<int, llvm::TinyPtrVector
<llvm::Function
*>> DtorsUsingAtExit
;
1683 /// Register functions annotated with __attribute__((destructor)) using
1684 /// __cxa_atexit, if it is available, or atexit otherwise.
1685 void registerGlobalDtorsWithAtExit();
1687 // When using sinit and sterm functions, unregister
1688 // __attribute__((destructor)) annotated functions which were previously
1689 // registered by the atexit subroutine using unatexit.
1690 void unregisterGlobalDtorsWithUnAtExit();
1692 /// Emit deferred multiversion function resolvers and associated variants.
1693 void emitMultiVersionFunctions();
1695 /// Emit any vtables which we deferred and still have a use for.
1696 void EmitDeferredVTables();
1698 /// Emit a dummy function that reference a CoreFoundation symbol when
1699 /// @available is used on Darwin.
1700 void emitAtAvailableLinkGuard();
1702 /// Emit the llvm.used and llvm.compiler.used metadata.
1703 void emitLLVMUsed();
1705 /// For C++20 Itanium ABI, emit the initializers for the module.
1706 void EmitModuleInitializers(clang::Module
*Primary
);
1708 /// Emit the link options introduced by imported modules.
1709 void EmitModuleLinkOptions();
1711 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
1712 /// have a resolver name that matches 'Elem' to instead resolve to the name of
1713 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
1714 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
1715 /// may not reference aliases. Redirection is only performed if 'Elem' is only
1716 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
1717 /// redirection is successful, and 'false' is returned otherwise.
1718 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue
*Elem
,
1719 llvm::GlobalValue
*CppFunc
);
1721 /// Emit aliases for internal-linkage declarations inside "C" language
1722 /// linkage specifications, giving them the "expected" name where possible.
1723 void EmitStaticExternCAliases();
1725 void EmitDeclMetadata();
1727 /// Emit the Clang version as llvm.ident metadata.
1728 void EmitVersionIdentMetadata();
1730 /// Emit the Clang commandline as llvm.commandline metadata.
1731 void EmitCommandLineMetadata();
1733 /// Emit the module flag metadata used to pass options controlling the
1734 /// the backend to LLVM.
1735 void EmitBackendOptionsMetadata(const CodeGenOptions
&CodeGenOpts
);
1737 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1738 void EmitOpenCLMetadata();
1740 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1741 /// .gcda files in a way that persists in .bc files.
1742 void EmitCoverageFile();
1744 /// Determine whether the definition must be emitted; if this returns \c
1745 /// false, the definition can be emitted lazily if it's used.
1746 bool MustBeEmitted(const ValueDecl
*D
);
1748 /// Determine whether the definition can be emitted eagerly, or should be
1749 /// delayed until the end of the translation unit. This is relevant for
1750 /// definitions whose linkage can change, e.g. implicit function instantions
1751 /// which may later be explicitly instantiated.
1752 bool MayBeEmittedEagerly(const ValueDecl
*D
);
1754 /// Check whether we can use a "simpler", more core exceptions personality
1756 void SimplifyPersonality();
1758 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
1759 /// attributes which can be simply added to a function.
1760 void getTrivialDefaultFunctionAttributes(StringRef Name
, bool HasOptnone
,
1761 bool AttrOnCallSite
,
1762 llvm::AttrBuilder
&FuncAttrs
);
1764 /// Helper function for ConstructAttributeList and
1765 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1766 /// attributes to add to a function with the given properties.
1767 void getDefaultFunctionAttributes(StringRef Name
, bool HasOptnone
,
1768 bool AttrOnCallSite
,
1769 llvm::AttrBuilder
&FuncAttrs
);
1771 llvm::Metadata
*CreateMetadataIdentifierImpl(QualType T
, MetadataTypeMap
&Map
,
1775 } // end namespace CodeGen
1776 } // end namespace clang
1778 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H