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/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
50 class IndexedInstrProfReader
;
62 class ObjCImplementationDecl
;
75 class HeaderSearchOptions
;
76 class DiagnosticsEngine
;
78 class CXXDestructorDecl
;
80 class CoverageSourceInfo
;
85 class CodeGenFunction
;
90 class CGOpenCLRuntime
;
91 class CGOpenMPRuntime
;
94 class CoverageMappingModuleGen
;
95 class TargetCodeGenInfo
;
97 enum ForDefinition_t
: bool {
98 NotForDefinition
= false,
102 struct OrderGlobalInitsOrStermFinalizers
{
103 unsigned int priority
;
104 unsigned int lex_order
;
105 OrderGlobalInitsOrStermFinalizers(unsigned int p
, unsigned int l
)
106 : priority(p
), lex_order(l
) {}
108 bool operator==(const OrderGlobalInitsOrStermFinalizers
&RHS
) const {
109 return priority
== RHS
.priority
&& lex_order
== RHS
.lex_order
;
112 bool operator<(const OrderGlobalInitsOrStermFinalizers
&RHS
) const {
113 return std::tie(priority
, lex_order
) <
114 std::tie(RHS
.priority
, RHS
.lex_order
);
118 struct ObjCEntrypoints
{
119 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
121 /// void objc_alloc(id);
122 llvm::FunctionCallee objc_alloc
;
124 /// void objc_allocWithZone(id);
125 llvm::FunctionCallee objc_allocWithZone
;
127 /// void objc_alloc_init(id);
128 llvm::FunctionCallee objc_alloc_init
;
130 /// void objc_autoreleasePoolPop(void*);
131 llvm::FunctionCallee objc_autoreleasePoolPop
;
133 /// void objc_autoreleasePoolPop(void*);
134 /// Note this method is used when we are using exception handling
135 llvm::FunctionCallee objc_autoreleasePoolPopInvoke
;
137 /// void *objc_autoreleasePoolPush(void);
138 llvm::Function
*objc_autoreleasePoolPush
;
140 /// id objc_autorelease(id);
141 llvm::Function
*objc_autorelease
;
143 /// id objc_autorelease(id);
144 /// Note this is the runtime method not the intrinsic.
145 llvm::FunctionCallee objc_autoreleaseRuntimeFunction
;
147 /// id objc_autoreleaseReturnValue(id);
148 llvm::Function
*objc_autoreleaseReturnValue
;
150 /// void objc_copyWeak(id *dest, id *src);
151 llvm::Function
*objc_copyWeak
;
153 /// void objc_destroyWeak(id*);
154 llvm::Function
*objc_destroyWeak
;
156 /// id objc_initWeak(id*, id);
157 llvm::Function
*objc_initWeak
;
159 /// id objc_loadWeak(id*);
160 llvm::Function
*objc_loadWeak
;
162 /// id objc_loadWeakRetained(id*);
163 llvm::Function
*objc_loadWeakRetained
;
165 /// void objc_moveWeak(id *dest, id *src);
166 llvm::Function
*objc_moveWeak
;
168 /// id objc_retain(id);
169 llvm::Function
*objc_retain
;
171 /// id objc_retain(id);
172 /// Note this is the runtime method not the intrinsic.
173 llvm::FunctionCallee objc_retainRuntimeFunction
;
175 /// id objc_retainAutorelease(id);
176 llvm::Function
*objc_retainAutorelease
;
178 /// id objc_retainAutoreleaseReturnValue(id);
179 llvm::Function
*objc_retainAutoreleaseReturnValue
;
181 /// id objc_retainAutoreleasedReturnValue(id);
182 llvm::Function
*objc_retainAutoreleasedReturnValue
;
184 /// id objc_retainBlock(id);
185 llvm::Function
*objc_retainBlock
;
187 /// void objc_release(id);
188 llvm::Function
*objc_release
;
190 /// void objc_release(id);
191 /// Note this is the runtime method not the intrinsic.
192 llvm::FunctionCallee objc_releaseRuntimeFunction
;
194 /// void objc_storeStrong(id*, id);
195 llvm::Function
*objc_storeStrong
;
197 /// id objc_storeWeak(id*, id);
198 llvm::Function
*objc_storeWeak
;
200 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
201 llvm::Function
*objc_unsafeClaimAutoreleasedReturnValue
;
203 /// A void(void) inline asm to use to mark that the return value of
204 /// a call will be immediately retain.
205 llvm::InlineAsm
*retainAutoreleasedReturnValueMarker
;
207 /// void clang.arc.use(...);
208 llvm::Function
*clang_arc_use
;
210 /// void clang.arc.noop.use(...);
211 llvm::Function
*clang_arc_noop_use
;
214 /// This class records statistics on instrumentation based profiling.
215 class InstrProfStats
{
216 uint32_t VisitedInMainFile
;
217 uint32_t MissingInMainFile
;
224 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
226 /// Record that we've visited a function and whether or not that function was
227 /// in the main source file.
228 void addVisited(bool MainFile
) {
233 /// Record that a function we've visited has no profile data.
234 void addMissing(bool MainFile
) {
239 /// Record that a function we've visited has mismatched profile data.
240 void addMismatched(bool MainFile
) { ++Mismatched
; }
241 /// Whether or not the stats we've gathered indicate any potential problems.
242 bool hasDiagnostics() { return Missing
|| Mismatched
; }
243 /// Report potential problems we've found to \c Diags.
244 void reportDiagnostics(DiagnosticsEngine
&Diags
, StringRef MainFile
);
247 /// A pair of helper functions for a __block variable.
248 class BlockByrefHelpers
: public llvm::FoldingSetNode
{
249 // MSVC requires this type to be complete in order to process this
252 llvm::Constant
*CopyHelper
;
253 llvm::Constant
*DisposeHelper
;
255 /// The alignment of the field. This is important because
256 /// different offsets to the field within the byref struct need to
257 /// have different helper functions.
260 BlockByrefHelpers(CharUnits alignment
)
261 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment
) {}
262 BlockByrefHelpers(const BlockByrefHelpers
&) = default;
263 virtual ~BlockByrefHelpers();
265 void Profile(llvm::FoldingSetNodeID
&id
) const {
266 id
.AddInteger(Alignment
.getQuantity());
269 virtual void profileImpl(llvm::FoldingSetNodeID
&id
) const = 0;
271 virtual bool needsCopy() const { return true; }
272 virtual void emitCopy(CodeGenFunction
&CGF
, Address dest
, Address src
) = 0;
274 virtual bool needsDispose() const { return true; }
275 virtual void emitDispose(CodeGenFunction
&CGF
, Address field
) = 0;
278 /// This class organizes the cross-function state that is used while generating
280 class CodeGenModule
: public CodeGenTypeCache
{
281 CodeGenModule(const CodeGenModule
&) = delete;
282 void operator=(const CodeGenModule
&) = delete;
287 : Priority(0), LexOrder(~0u), Initializer(nullptr),
288 AssociatedData(nullptr) {}
289 Structor(int Priority
, unsigned LexOrder
, llvm::Constant
*Initializer
,
290 llvm::Constant
*AssociatedData
)
291 : Priority(Priority
), LexOrder(LexOrder
), Initializer(Initializer
),
292 AssociatedData(AssociatedData
) {}
295 llvm::Constant
*Initializer
;
296 llvm::Constant
*AssociatedData
;
299 typedef std::vector
<Structor
> CtorList
;
303 const LangOptions
&LangOpts
;
304 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
; // Only used for debug info.
305 const HeaderSearchOptions
&HeaderSearchOpts
; // Only used for debug info.
306 const PreprocessorOptions
&PreprocessorOpts
; // Only used for debug info.
307 const CodeGenOptions
&CodeGenOpts
;
308 unsigned NumAutoVarInit
= 0;
309 llvm::Module
&TheModule
;
310 DiagnosticsEngine
&Diags
;
311 const TargetInfo
&Target
;
312 std::unique_ptr
<CGCXXABI
> ABI
;
313 llvm::LLVMContext
&VMContext
;
314 std::string ModuleNameHash
;
315 bool CXX20ModuleInits
= false;
316 std::unique_ptr
<CodeGenTBAA
> TBAA
;
318 mutable std::unique_ptr
<TargetCodeGenInfo
> TheTargetCodeGenInfo
;
320 // This should not be moved earlier, since its initialization depends on some
321 // of the previous reference members being already initialized and also checks
322 // if TheTargetCodeGenInfo is NULL
325 /// Holds information about C++ vtables.
326 CodeGenVTables VTables
;
328 std::unique_ptr
<CGObjCRuntime
> ObjCRuntime
;
329 std::unique_ptr
<CGOpenCLRuntime
> OpenCLRuntime
;
330 std::unique_ptr
<CGOpenMPRuntime
> OpenMPRuntime
;
331 std::unique_ptr
<CGCUDARuntime
> CUDARuntime
;
332 std::unique_ptr
<CGHLSLRuntime
> HLSLRuntime
;
333 std::unique_ptr
<CGDebugInfo
> DebugInfo
;
334 std::unique_ptr
<ObjCEntrypoints
> ObjCData
;
335 llvm::MDNode
*NoObjCARCExceptionsMetadata
= nullptr;
336 std::unique_ptr
<llvm::IndexedInstrProfReader
> PGOReader
;
337 InstrProfStats PGOStats
;
338 std::unique_ptr
<llvm::SanitizerStatReport
> SanStats
;
340 // A set of references that have only been seen via a weakref so far. This is
341 // used to remove the weak of the reference if we ever see a direct reference
343 llvm::SmallPtrSet
<llvm::GlobalValue
*, 10> WeakRefReferences
;
345 /// This contains all the decls which have definitions but/ which are deferred
346 /// for emission and therefore should only be output if they are actually
347 /// used. If a decl is in this, then it is known to have not been referenced
349 llvm::DenseMap
<StringRef
, GlobalDecl
> DeferredDecls
;
351 /// This is a list of deferred decls which we have seen that *are* actually
352 /// referenced. These get code generated when the module is done.
353 std::vector
<GlobalDecl
> DeferredDeclsToEmit
;
354 void addDeferredDeclToEmit(GlobalDecl GD
) {
355 DeferredDeclsToEmit
.emplace_back(GD
);
356 addEmittedDeferredDecl(GD
);
359 /// Decls that were DeferredDecls and have now been emitted.
360 llvm::DenseMap
<llvm::StringRef
, GlobalDecl
> EmittedDeferredDecls
;
362 void addEmittedDeferredDecl(GlobalDecl GD
) {
363 if (!llvm::isa
<FunctionDecl
>(GD
.getDecl()))
365 llvm::GlobalVariable::LinkageTypes L
= getFunctionLinkage(GD
);
366 if (llvm::GlobalValue::isLinkOnceLinkage(L
) ||
367 llvm::GlobalValue::isWeakLinkage(L
)) {
368 EmittedDeferredDecls
[getMangledName(GD
)] = GD
;
372 /// List of alias we have emitted. Used to make sure that what they point to
373 /// is defined once we get to the end of the of the translation unit.
374 std::vector
<GlobalDecl
> Aliases
;
376 /// List of multiversion functions to be emitted. This list is processed in
377 /// conjunction with other deferred symbols and is used to ensure that
378 /// multiversion function resolvers and ifuncs are defined and emitted.
379 std::vector
<GlobalDecl
> MultiVersionFuncs
;
381 typedef llvm::StringMap
<llvm::TrackingVH
<llvm::Constant
> > ReplacementsTy
;
382 ReplacementsTy Replacements
;
384 /// List of global values to be replaced with something else. Used when we
385 /// want to replace a GlobalValue but can't identify it by its mangled name
386 /// anymore (because the name is already taken).
387 llvm::SmallVector
<std::pair
<llvm::GlobalValue
*, llvm::Constant
*>, 8>
388 GlobalValReplacements
;
390 /// Variables for which we've emitted globals containing their constant
391 /// values along with the corresponding globals, for opportunistic reuse.
392 llvm::DenseMap
<const VarDecl
*, llvm::GlobalVariable
*> InitializerConstants
;
394 /// Set of global decls for which we already diagnosed mangled name conflict.
395 /// Required to not issue a warning (on a mangling conflict) multiple times
396 /// for the same decl.
397 llvm::DenseSet
<GlobalDecl
> DiagnosedConflictingDefinitions
;
399 /// A queue of (optional) vtables to consider emitting.
400 std::vector
<const CXXRecordDecl
*> DeferredVTables
;
402 /// A queue of (optional) vtables that may be emitted opportunistically.
403 std::vector
<const CXXRecordDecl
*> OpportunisticVTables
;
405 /// List of global values which are required to be present in the object file;
406 /// bitcast to i8*. This is used for forcing visibility of symbols which may
407 /// otherwise be optimized out.
408 std::vector
<llvm::WeakTrackingVH
> LLVMUsed
;
409 std::vector
<llvm::WeakTrackingVH
> LLVMCompilerUsed
;
411 /// Store the list of global constructors and their respective priorities to
412 /// be emitted when the translation unit is complete.
413 CtorList GlobalCtors
;
415 /// Store the list of global destructors and their respective priorities to be
416 /// emitted when the translation unit is complete.
417 CtorList GlobalDtors
;
419 /// An ordered map of canonical GlobalDecls to their mangled names.
420 llvm::MapVector
<GlobalDecl
, StringRef
> MangledDeclNames
;
421 llvm::StringMap
<GlobalDecl
, llvm::BumpPtrAllocator
> Manglings
;
423 /// Global annotations.
424 std::vector
<llvm::Constant
*> Annotations
;
426 /// Map used to get unique annotation strings.
427 llvm::StringMap
<llvm::Constant
*> AnnotationStrings
;
429 /// Used for uniquing of annotation arguments.
430 llvm::DenseMap
<unsigned, llvm::Constant
*> AnnotationArgs
;
432 llvm::StringMap
<llvm::GlobalVariable
*> CFConstantStringMap
;
434 llvm::DenseMap
<llvm::Constant
*, llvm::GlobalVariable
*> ConstantStringMap
;
435 llvm::DenseMap
<const UnnamedGlobalConstantDecl
*, llvm::GlobalVariable
*>
436 UnnamedGlobalConstantDeclMap
;
437 llvm::DenseMap
<const Decl
*, llvm::Constant
*> StaticLocalDeclMap
;
438 llvm::DenseMap
<const Decl
*, llvm::GlobalVariable
*> StaticLocalDeclGuardMap
;
439 llvm::DenseMap
<const Expr
*, llvm::Constant
*> MaterializedGlobalTemporaryMap
;
441 llvm::DenseMap
<QualType
, llvm::Constant
*> AtomicSetterHelperFnMap
;
442 llvm::DenseMap
<QualType
, llvm::Constant
*> AtomicGetterHelperFnMap
;
444 /// Map used to get unique type descriptor constants for sanitizers.
445 llvm::DenseMap
<QualType
, llvm::Constant
*> TypeDescriptorMap
;
447 /// Map used to track internal linkage functions declared within
448 /// extern "C" regions.
449 typedef llvm::MapVector
<IdentifierInfo
*,
450 llvm::GlobalValue
*> StaticExternCMap
;
451 StaticExternCMap StaticExternCValues
;
453 /// thread_local variables defined or used in this TU.
454 std::vector
<const VarDecl
*> CXXThreadLocals
;
456 /// thread_local variables with initializers that need to run
457 /// before any thread_local variable in this TU is odr-used.
458 std::vector
<llvm::Function
*> CXXThreadLocalInits
;
459 std::vector
<const VarDecl
*> CXXThreadLocalInitVars
;
461 /// Global variables with initializers that need to run before main.
462 std::vector
<llvm::Function
*> CXXGlobalInits
;
464 /// When a C++ decl with an initializer is deferred, null is
465 /// appended to CXXGlobalInits, and the index of that null is placed
466 /// here so that the initializer will be performed in the correct
467 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
468 /// that we don't re-emit the initializer.
469 llvm::DenseMap
<const Decl
*, unsigned> DelayedCXXInitPosition
;
471 typedef std::pair
<OrderGlobalInitsOrStermFinalizers
, llvm::Function
*>
474 struct GlobalInitPriorityCmp
{
475 bool operator()(const GlobalInitData
&LHS
,
476 const GlobalInitData
&RHS
) const {
477 return LHS
.first
.priority
< RHS
.first
.priority
;
481 /// Global variables with initializers whose order of initialization is set by
482 /// init_priority attribute.
483 SmallVector
<GlobalInitData
, 8> PrioritizedCXXGlobalInits
;
485 /// Global destructor functions and arguments that need to run on termination.
486 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
487 /// functions, which also run on unloading a shared library.
488 typedef std::tuple
<llvm::FunctionType
*, llvm::WeakTrackingVH
,
490 CXXGlobalDtorsOrStermFinalizer_t
;
491 SmallVector
<CXXGlobalDtorsOrStermFinalizer_t
, 8>
492 CXXGlobalDtorsOrStermFinalizers
;
494 typedef std::pair
<OrderGlobalInitsOrStermFinalizers
, llvm::Function
*>
497 struct StermFinalizerPriorityCmp
{
498 bool operator()(const StermFinalizerData
&LHS
,
499 const StermFinalizerData
&RHS
) const {
500 return LHS
.first
.priority
< RHS
.first
.priority
;
504 /// Global variables with sterm finalizers whose order of initialization is
505 /// set by init_priority attribute.
506 SmallVector
<StermFinalizerData
, 8> PrioritizedCXXStermFinalizers
;
508 /// The complete set of modules that has been imported.
509 llvm::SetVector
<clang::Module
*> ImportedModules
;
511 /// The set of modules for which the module initializers
512 /// have been emitted.
513 llvm::SmallPtrSet
<clang::Module
*, 16> EmittedModuleInitializers
;
515 /// A vector of metadata strings for linker options.
516 SmallVector
<llvm::MDNode
*, 16> LinkerOptionsMetadata
;
518 /// A vector of metadata strings for dependent libraries for ELF.
519 SmallVector
<llvm::MDNode
*, 16> ELFDependentLibraries
;
521 /// @name Cache for Objective-C runtime types
524 /// Cached reference to the class for constant strings. This value has type
525 /// int * but is actually an Obj-C class pointer.
526 llvm::WeakTrackingVH CFConstantStringClassRef
;
528 /// The type used to describe the state of a fast enumeration in
529 /// Objective-C's for..in loop.
530 QualType ObjCFastEnumerationStateType
;
534 /// Lazily create the Objective-C runtime
535 void createObjCRuntime();
537 void createOpenCLRuntime();
538 void createOpenMPRuntime();
539 void createCUDARuntime();
540 void createHLSLRuntime();
542 bool isTriviallyRecursive(const FunctionDecl
*F
);
543 bool shouldEmitFunction(GlobalDecl GD
);
544 bool shouldOpportunisticallyEmitVTables();
545 /// Map used to be sure we don't emit the same CompoundLiteral twice.
546 llvm::DenseMap
<const CompoundLiteralExpr
*, llvm::GlobalVariable
*>
547 EmittedCompoundLiterals
;
549 /// Map of the global blocks we've emitted, so that we don't have to re-emit
550 /// them if the constexpr evaluator gets aggressive.
551 llvm::DenseMap
<const BlockExpr
*, llvm::Constant
*> EmittedGlobalBlocks
;
553 /// @name Cache for Blocks Runtime Globals
556 llvm::Constant
*NSConcreteGlobalBlock
= nullptr;
557 llvm::Constant
*NSConcreteStackBlock
= nullptr;
559 llvm::FunctionCallee BlockObjectAssign
= nullptr;
560 llvm::FunctionCallee BlockObjectDispose
= nullptr;
562 llvm::Type
*BlockDescriptorType
= nullptr;
563 llvm::Type
*GenericBlockLiteralType
= nullptr;
566 int GlobalUniqueCount
;
569 GlobalDecl initializedGlobalDecl
;
573 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
574 llvm::Function
*LifetimeStartFn
= nullptr;
576 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
577 llvm::Function
*LifetimeEndFn
= nullptr;
579 std::unique_ptr
<SanitizerMetadata
> SanitizerMD
;
581 llvm::MapVector
<const Decl
*, bool> DeferredEmptyCoverageMappingDecls
;
583 std::unique_ptr
<CoverageMappingModuleGen
> CoverageMapping
;
585 /// Mapping from canonical types to their metadata identifiers. We need to
586 /// maintain this mapping because identifiers may be formed from distinct
588 typedef llvm::DenseMap
<QualType
, llvm::Metadata
*> MetadataTypeMap
;
589 MetadataTypeMap MetadataIdMap
;
590 MetadataTypeMap VirtualMetadataIdMap
;
591 MetadataTypeMap GeneralizedMetadataIdMap
;
593 llvm::DenseMap
<const llvm::Constant
*, llvm::GlobalVariable
*> RTTIProxyMap
;
595 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
596 // when used with -fincremental-extensions.
597 std::pair
<std::unique_ptr
<CodeGenFunction
>, const TopLevelStmtDecl
*>
598 GlobalTopLevelStmtBlockInFlight
;
601 CodeGenModule(ASTContext
&C
, IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> FS
,
602 const HeaderSearchOptions
&headersearchopts
,
603 const PreprocessorOptions
&ppopts
,
604 const CodeGenOptions
&CodeGenOpts
, llvm::Module
&M
,
605 DiagnosticsEngine
&Diags
,
606 CoverageSourceInfo
*CoverageInfo
= nullptr);
612 /// Finalize LLVM code generation.
615 /// Return true if we should emit location information for expressions.
616 bool getExpressionLocationsEnabled() const;
618 /// Return a reference to the configured Objective-C runtime.
619 CGObjCRuntime
&getObjCRuntime() {
620 if (!ObjCRuntime
) createObjCRuntime();
624 /// Return true iff an Objective-C runtime has been configured.
625 bool hasObjCRuntime() { return !!ObjCRuntime
; }
627 const std::string
&getModuleNameHash() const { return ModuleNameHash
; }
629 /// Return a reference to the configured OpenCL runtime.
630 CGOpenCLRuntime
&getOpenCLRuntime() {
631 assert(OpenCLRuntime
!= nullptr);
632 return *OpenCLRuntime
;
635 /// Return a reference to the configured OpenMP runtime.
636 CGOpenMPRuntime
&getOpenMPRuntime() {
637 assert(OpenMPRuntime
!= nullptr);
638 return *OpenMPRuntime
;
641 /// Return a reference to the configured CUDA runtime.
642 CGCUDARuntime
&getCUDARuntime() {
643 assert(CUDARuntime
!= nullptr);
647 /// Return a reference to the configured HLSL runtime.
648 CGHLSLRuntime
&getHLSLRuntime() {
649 assert(HLSLRuntime
!= nullptr);
653 ObjCEntrypoints
&getObjCEntrypoints() const {
654 assert(ObjCData
!= nullptr);
658 // Version checking functions, used to implement ObjC's @available:
659 // i32 @__isOSVersionAtLeast(i32, i32, i32)
660 llvm::FunctionCallee IsOSVersionAtLeastFn
= nullptr;
661 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
662 llvm::FunctionCallee IsPlatformVersionAtLeastFn
= nullptr;
664 InstrProfStats
&getPGOStats() { return PGOStats
; }
665 llvm::IndexedInstrProfReader
*getPGOReader() const { return PGOReader
.get(); }
667 CoverageMappingModuleGen
*getCoverageMapping() const {
668 return CoverageMapping
.get();
671 llvm::Constant
*getStaticLocalDeclAddress(const VarDecl
*D
) {
672 return StaticLocalDeclMap
[D
];
674 void setStaticLocalDeclAddress(const VarDecl
*D
,
676 StaticLocalDeclMap
[D
] = C
;
680 getOrCreateStaticVarDecl(const VarDecl
&D
,
681 llvm::GlobalValue::LinkageTypes Linkage
);
683 llvm::GlobalVariable
*getStaticLocalDeclGuardAddress(const VarDecl
*D
) {
684 return StaticLocalDeclGuardMap
[D
];
686 void setStaticLocalDeclGuardAddress(const VarDecl
*D
,
687 llvm::GlobalVariable
*C
) {
688 StaticLocalDeclGuardMap
[D
] = C
;
691 Address
createUnnamedGlobalFrom(const VarDecl
&D
, llvm::Constant
*Constant
,
694 bool lookupRepresentativeDecl(StringRef MangledName
,
695 GlobalDecl
&Result
) const;
697 llvm::Constant
*getAtomicSetterHelperFnMap(QualType Ty
) {
698 return AtomicSetterHelperFnMap
[Ty
];
700 void setAtomicSetterHelperFnMap(QualType Ty
,
701 llvm::Constant
*Fn
) {
702 AtomicSetterHelperFnMap
[Ty
] = Fn
;
705 llvm::Constant
*getAtomicGetterHelperFnMap(QualType Ty
) {
706 return AtomicGetterHelperFnMap
[Ty
];
708 void setAtomicGetterHelperFnMap(QualType Ty
,
709 llvm::Constant
*Fn
) {
710 AtomicGetterHelperFnMap
[Ty
] = Fn
;
713 llvm::Constant
*getTypeDescriptorFromMap(QualType Ty
) {
714 return TypeDescriptorMap
[Ty
];
716 void setTypeDescriptorInMap(QualType Ty
, llvm::Constant
*C
) {
717 TypeDescriptorMap
[Ty
] = C
;
720 CGDebugInfo
*getModuleDebugInfo() { return DebugInfo
.get(); }
722 llvm::MDNode
*getNoObjCARCExceptionsMetadata() {
723 if (!NoObjCARCExceptionsMetadata
)
724 NoObjCARCExceptionsMetadata
=
725 llvm::MDNode::get(getLLVMContext(), std::nullopt
);
726 return NoObjCARCExceptionsMetadata
;
729 ASTContext
&getContext() const { return Context
; }
730 const LangOptions
&getLangOpts() const { return LangOpts
; }
731 const IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> &getFileSystem() const {
734 const HeaderSearchOptions
&getHeaderSearchOpts()
735 const { return HeaderSearchOpts
; }
736 const PreprocessorOptions
&getPreprocessorOpts()
737 const { return PreprocessorOpts
; }
738 const CodeGenOptions
&getCodeGenOpts() const { return CodeGenOpts
; }
739 llvm::Module
&getModule() const { return TheModule
; }
740 DiagnosticsEngine
&getDiags() const { return Diags
; }
741 const llvm::DataLayout
&getDataLayout() const {
742 return TheModule
.getDataLayout();
744 const TargetInfo
&getTarget() const { return Target
; }
745 const llvm::Triple
&getTriple() const { return Target
.getTriple(); }
746 bool supportsCOMDAT() const;
747 void maybeSetTrivialComdat(const Decl
&D
, llvm::GlobalObject
&GO
);
749 CGCXXABI
&getCXXABI() const { return *ABI
; }
750 llvm::LLVMContext
&getLLVMContext() { return VMContext
; }
752 bool shouldUseTBAA() const { return TBAA
!= nullptr; }
754 const TargetCodeGenInfo
&getTargetCodeGenInfo();
756 CodeGenTypes
&getTypes() { return Types
; }
758 CodeGenVTables
&getVTables() { return VTables
; }
760 ItaniumVTableContext
&getItaniumVTableContext() {
761 return VTables
.getItaniumVTableContext();
764 const ItaniumVTableContext
&getItaniumVTableContext() const {
765 return VTables
.getItaniumVTableContext();
768 MicrosoftVTableContext
&getMicrosoftVTableContext() {
769 return VTables
.getMicrosoftVTableContext();
772 CtorList
&getGlobalCtors() { return GlobalCtors
; }
773 CtorList
&getGlobalDtors() { return GlobalDtors
; }
775 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
777 llvm::MDNode
*getTBAATypeInfo(QualType QTy
);
779 /// getTBAAAccessInfo - Get TBAA information that describes an access to
780 /// an object of the given type.
781 TBAAAccessInfo
getTBAAAccessInfo(QualType AccessType
);
783 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
784 /// access to a virtual table pointer.
785 TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type
*VTablePtrType
);
787 llvm::MDNode
*getTBAAStructInfo(QualType QTy
);
789 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
790 /// type. Return null if the type is not suitable for use in TBAA access tags.
791 llvm::MDNode
*getTBAABaseTypeInfo(QualType QTy
);
793 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
794 llvm::MDNode
*getTBAAAccessTagInfo(TBAAAccessInfo Info
);
796 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
798 TBAAAccessInfo
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo
,
799 TBAAAccessInfo TargetInfo
);
801 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
802 /// purposes of conditional operator.
803 TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA
,
804 TBAAAccessInfo InfoB
);
806 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
807 /// purposes of memory transfer calls.
808 TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo
,
809 TBAAAccessInfo SrcInfo
);
811 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
813 TBAAAccessInfo
getTBAAInfoForSubobject(LValue Base
, QualType AccessType
) {
814 if (Base
.getTBAAInfo().isMayAlias())
815 return TBAAAccessInfo::getMayAliasInfo();
816 return getTBAAAccessInfo(AccessType
);
819 bool isTypeConstant(QualType QTy
, bool ExcludeCtor
, bool ExcludeDtor
);
821 bool isPaddedAtomicType(QualType type
);
822 bool isPaddedAtomicType(const AtomicType
*type
);
824 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
825 void DecorateInstructionWithTBAA(llvm::Instruction
*Inst
,
826 TBAAAccessInfo TBAAInfo
);
828 /// Adds !invariant.barrier !tag to instruction
829 void DecorateInstructionWithInvariantGroup(llvm::Instruction
*I
,
830 const CXXRecordDecl
*RD
);
832 /// Emit the given number of characters as a value of type size_t.
833 llvm::ConstantInt
*getSize(CharUnits numChars
);
835 /// Set the visibility for the given LLVM GlobalValue.
836 void setGlobalVisibility(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
838 void setDSOLocal(llvm::GlobalValue
*GV
) const;
840 bool shouldMapVisibilityToDLLExport(const NamedDecl
*D
) const {
841 return getLangOpts().hasDefaultVisibilityExportMapping() && D
&&
842 (D
->getLinkageAndVisibility().getVisibility() ==
843 DefaultVisibility
) &&
844 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
845 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
846 D
->getLinkageAndVisibility().isVisibilityExplicit()));
848 void setDLLImportDLLExport(llvm::GlobalValue
*GV
, GlobalDecl D
) const;
849 void setDLLImportDLLExport(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
850 /// Set visibility, dllimport/dllexport and dso_local.
851 /// This must be called after dllimport/dllexport is set.
852 void setGVProperties(llvm::GlobalValue
*GV
, GlobalDecl GD
) const;
853 void setGVProperties(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
855 void setGVPropertiesAux(llvm::GlobalValue
*GV
, const NamedDecl
*D
) const;
857 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
858 /// variable declaration D.
859 void setTLSMode(llvm::GlobalValue
*GV
, const VarDecl
&D
) const;
861 /// Get LLVM TLS mode from CodeGenOptions.
862 llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const;
864 static llvm::GlobalValue::VisibilityTypes
GetLLVMVisibility(Visibility V
) {
866 case DefaultVisibility
: return llvm::GlobalValue::DefaultVisibility
;
867 case HiddenVisibility
: return llvm::GlobalValue::HiddenVisibility
;
868 case ProtectedVisibility
: return llvm::GlobalValue::ProtectedVisibility
;
870 llvm_unreachable("unknown visibility!");
873 llvm::Constant
*GetAddrOfGlobal(GlobalDecl GD
,
874 ForDefinition_t IsForDefinition
877 /// Will return a global variable of the given type. If a variable with a
878 /// different type already exists then a new variable with the right type
879 /// will be created and all uses of the old variable will be replaced with a
880 /// bitcast to the new variable.
881 llvm::GlobalVariable
*
882 CreateOrReplaceCXXRuntimeVariable(StringRef Name
, llvm::Type
*Ty
,
883 llvm::GlobalValue::LinkageTypes Linkage
,
884 llvm::Align Alignment
);
886 llvm::Function
*CreateGlobalInitOrCleanUpFunction(
887 llvm::FunctionType
*ty
, const Twine
&name
, const CGFunctionInfo
&FI
,
888 SourceLocation Loc
= SourceLocation(), bool TLS
= false,
889 llvm::GlobalVariable::LinkageTypes Linkage
=
890 llvm::GlobalVariable::InternalLinkage
);
892 /// Return the AST address space of the underlying global variable for D, as
893 /// determined by its declaration. Normally this is the same as the address
894 /// space of D's type, but in CUDA, address spaces are associated with
895 /// declarations, not types. If D is nullptr, return the default address
896 /// space for global variable.
898 /// For languages without explicit address spaces, if D has default address
899 /// space, target-specific global or constant address space may be returned.
900 LangAS
GetGlobalVarAddressSpace(const VarDecl
*D
);
902 /// Return the AST address space of constant literal, which is used to emit
903 /// the constant literal as global variable in LLVM IR.
904 /// Note: This is not necessarily the address space of the constant literal
905 /// in AST. For address space agnostic language, e.g. C++, constant literal
906 /// in AST is always in default address space.
907 LangAS
GetGlobalConstantAddressSpace() const;
909 /// Return the llvm::Constant for the address of the given global variable.
910 /// If Ty is non-null and if the global doesn't exist, then it will be created
911 /// with the specified type instead of whatever the normal requested type
912 /// would be. If IsForDefinition is true, it is guaranteed that an actual
913 /// global with type Ty will be returned, not conversion of a variable with
914 /// the same mangled name but some other type.
915 llvm::Constant
*GetAddrOfGlobalVar(const VarDecl
*D
,
916 llvm::Type
*Ty
= nullptr,
917 ForDefinition_t IsForDefinition
920 /// Return the address of the given function. If Ty is non-null, then this
921 /// function will use the specified type if it has to create it.
922 llvm::Constant
*GetAddrOfFunction(GlobalDecl GD
, llvm::Type
*Ty
= nullptr,
923 bool ForVTable
= false,
924 bool DontDefer
= false,
925 ForDefinition_t IsForDefinition
928 // Return the function body address of the given function.
929 llvm::Constant
*GetFunctionStart(const ValueDecl
*Decl
);
931 /// Get the address of the RTTI descriptor for the given type.
932 llvm::Constant
*GetAddrOfRTTIDescriptor(QualType Ty
, bool ForEH
= false);
934 /// Get the address of a GUID.
935 ConstantAddress
GetAddrOfMSGuidDecl(const MSGuidDecl
*GD
);
937 /// Get the address of a UnnamedGlobalConstant
939 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl
*GCD
);
941 /// Get the address of a template parameter object.
943 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl
*TPO
);
945 /// Get the address of the thunk for the given global decl.
946 llvm::Constant
*GetAddrOfThunk(StringRef Name
, llvm::Type
*FnTy
,
949 /// Get a reference to the target of VD.
950 ConstantAddress
GetWeakRefReference(const ValueDecl
*VD
);
952 /// Returns the assumed alignment of an opaque pointer to the given class.
953 CharUnits
getClassPointerAlignment(const CXXRecordDecl
*CD
);
955 /// Returns the minimum object size for an object of the given class type
956 /// (or a class derived from it).
957 CharUnits
getMinimumClassObjectSize(const CXXRecordDecl
*CD
);
959 /// Returns the minimum object size for an object of the given type.
960 CharUnits
getMinimumObjectSize(QualType Ty
) {
961 if (CXXRecordDecl
*RD
= Ty
->getAsCXXRecordDecl())
962 return getMinimumClassObjectSize(RD
);
963 return getContext().getTypeSizeInChars(Ty
);
966 /// Returns the assumed alignment of a virtual base of a class.
967 CharUnits
getVBaseAlignment(CharUnits DerivedAlign
,
968 const CXXRecordDecl
*Derived
,
969 const CXXRecordDecl
*VBase
);
971 /// Given a class pointer with an actual known alignment, and the
972 /// expected alignment of an object at a dynamic offset w.r.t that
973 /// pointer, return the alignment to assume at the offset.
974 CharUnits
getDynamicOffsetAlignment(CharUnits ActualAlign
,
975 const CXXRecordDecl
*Class
,
976 CharUnits ExpectedTargetAlign
);
979 computeNonVirtualBaseClassOffset(const CXXRecordDecl
*DerivedClass
,
980 CastExpr::path_const_iterator Start
,
981 CastExpr::path_const_iterator End
);
983 /// Returns the offset from a derived class to a class. Returns null if the
986 GetNonVirtualBaseClassOffset(const CXXRecordDecl
*ClassDecl
,
987 CastExpr::path_const_iterator PathBegin
,
988 CastExpr::path_const_iterator PathEnd
);
990 llvm::FoldingSet
<BlockByrefHelpers
> ByrefHelpersCache
;
992 /// Fetches the global unique block count.
993 int getUniqueBlockCount() { return ++Block
.GlobalUniqueCount
; }
995 /// Fetches the type of a generic block descriptor.
996 llvm::Type
*getBlockDescriptorType();
998 /// The type of a generic block literal.
999 llvm::Type
*getGenericBlockLiteralType();
1001 /// Gets the address of a block which requires no captures.
1002 llvm::Constant
*GetAddrOfGlobalBlock(const BlockExpr
*BE
, StringRef Name
);
1004 /// Returns the address of a block which requires no caputres, or null if
1005 /// we've yet to emit the block for BE.
1006 llvm::Constant
*getAddrOfGlobalBlockIfEmitted(const BlockExpr
*BE
) {
1007 return EmittedGlobalBlocks
.lookup(BE
);
1010 /// Notes that BE's global block is available via Addr. Asserts that BE
1011 /// isn't already emitted.
1012 void setAddrOfGlobalBlock(const BlockExpr
*BE
, llvm::Constant
*Addr
);
1014 /// Return a pointer to a constant CFString object for the given string.
1015 ConstantAddress
GetAddrOfConstantCFString(const StringLiteral
*Literal
);
1017 /// Return a pointer to a constant NSString object for the given string. Or a
1018 /// user defined String object as defined via
1019 /// -fconstant-string-class=class_name option.
1020 ConstantAddress
GetAddrOfConstantString(const StringLiteral
*Literal
);
1022 /// Return a constant array for the given string.
1023 llvm::Constant
*GetConstantArrayFromStringLiteral(const StringLiteral
*E
);
1025 /// Return a pointer to a constant array for the given string literal.
1027 GetAddrOfConstantStringFromLiteral(const StringLiteral
*S
,
1028 StringRef Name
= ".str");
1030 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1032 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr
*);
1034 /// Returns a pointer to a character array containing the literal and a
1035 /// terminating '\0' character. The result has pointer to array type.
1037 /// \param GlobalName If provided, the name to use for the global (if one is
1040 GetAddrOfConstantCString(const std::string
&Str
,
1041 const char *GlobalName
= nullptr);
1043 /// Returns a pointer to a constant global variable for the given file-scope
1044 /// compound literal expression.
1045 ConstantAddress
GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr
*E
);
1047 /// If it's been emitted already, returns the GlobalVariable corresponding to
1048 /// a compound literal. Otherwise, returns null.
1049 llvm::GlobalVariable
*
1050 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr
*E
);
1052 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1054 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr
*CLE
,
1055 llvm::GlobalVariable
*GV
);
1057 /// Returns a pointer to a global variable representing a temporary
1058 /// with static or thread storage duration.
1059 ConstantAddress
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr
*E
,
1062 /// Retrieve the record type that describes the state of an
1063 /// Objective-C fast enumeration loop (for..in).
1064 QualType
getObjCFastEnumerationStateType();
1066 // Produce code for this constructor/destructor. This method doesn't try
1067 // to apply any ABI rules about which other constructors/destructors
1068 // are needed or if they are alias to each other.
1069 llvm::Function
*codegenCXXStructor(GlobalDecl GD
);
1071 /// Return the address of the constructor/destructor of the given type.
1073 getAddrOfCXXStructor(GlobalDecl GD
, const CGFunctionInfo
*FnInfo
= nullptr,
1074 llvm::FunctionType
*FnType
= nullptr,
1075 bool DontDefer
= false,
1076 ForDefinition_t IsForDefinition
= NotForDefinition
) {
1077 return cast
<llvm::Constant
>(getAddrAndTypeOfCXXStructor(GD
, FnInfo
, FnType
,
1083 llvm::FunctionCallee
getAddrAndTypeOfCXXStructor(
1084 GlobalDecl GD
, const CGFunctionInfo
*FnInfo
= nullptr,
1085 llvm::FunctionType
*FnType
= nullptr, bool DontDefer
= false,
1086 ForDefinition_t IsForDefinition
= NotForDefinition
);
1088 /// Given a builtin id for a function like "__builtin_fabsf", return a
1089 /// Function* for "fabsf".
1090 llvm::Constant
*getBuiltinLibFunction(const FunctionDecl
*FD
,
1091 unsigned BuiltinID
);
1093 llvm::Function
*getIntrinsic(unsigned IID
,
1094 ArrayRef
<llvm::Type
*> Tys
= std::nullopt
);
1096 /// Emit code for a single top level declaration.
1097 void EmitTopLevelDecl(Decl
*D
);
1099 /// Stored a deferred empty coverage mapping for an unused
1100 /// and thus uninstrumented top level declaration.
1101 void AddDeferredUnusedCoverageMapping(Decl
*D
);
1103 /// Remove the deferred empty coverage mapping as this
1104 /// declaration is actually instrumented.
1105 void ClearUnusedCoverageMapping(const Decl
*D
);
1107 /// Emit all the deferred coverage mappings
1108 /// for the uninstrumented functions.
1109 void EmitDeferredUnusedCoverageMappings();
1111 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1112 void EmitMainVoidAlias();
1114 /// Tell the consumer that this variable has been instantiated.
1115 void HandleCXXStaticMemberVarInstantiation(VarDecl
*VD
);
1117 /// If the declaration has internal linkage but is inside an
1118 /// extern "C" linkage specification, prepare to emit an alias for it
1119 /// to the expected name.
1120 template<typename SomeDecl
>
1121 void MaybeHandleStaticInExternC(const SomeDecl
*D
, llvm::GlobalValue
*GV
);
1123 /// Add a global to a list to be added to the llvm.used metadata.
1124 void addUsedGlobal(llvm::GlobalValue
*GV
);
1126 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1127 void addCompilerUsedGlobal(llvm::GlobalValue
*GV
);
1129 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1130 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue
*GV
);
1132 /// Add a destructor and object to add to the C++ global destructor function.
1133 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn
, llvm::Constant
*Object
) {
1134 CXXGlobalDtorsOrStermFinalizers
.emplace_back(DtorFn
.getFunctionType(),
1135 DtorFn
.getCallee(), Object
);
1138 /// Add an sterm finalizer to the C++ global cleanup function.
1139 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn
) {
1140 CXXGlobalDtorsOrStermFinalizers
.emplace_back(DtorFn
.getFunctionType(),
1141 DtorFn
.getCallee(), nullptr);
1144 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1145 void AddCXXStermFinalizerToGlobalDtor(llvm::Function
*StermFinalizer
,
1147 AddGlobalDtor(StermFinalizer
, Priority
);
1150 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function
*StermFinalizer
,
1152 OrderGlobalInitsOrStermFinalizers
Key(Priority
,
1153 PrioritizedCXXStermFinalizers
.size());
1154 PrioritizedCXXStermFinalizers
.push_back(
1155 std::make_pair(Key
, StermFinalizer
));
1158 /// Create or return a runtime function declaration with the specified type
1159 /// and name. If \p AssumeConvergent is true, the call will have the
1160 /// convergent attribute added.
1161 llvm::FunctionCallee
1162 CreateRuntimeFunction(llvm::FunctionType
*Ty
, StringRef Name
,
1163 llvm::AttributeList ExtraAttrs
= llvm::AttributeList(),
1164 bool Local
= false, bool AssumeConvergent
= false);
1166 /// Create a new runtime global variable with the specified type and name.
1167 llvm::Constant
*CreateRuntimeVariable(llvm::Type
*Ty
,
1170 ///@name Custom Blocks Runtime Interfaces
1173 llvm::Constant
*getNSConcreteGlobalBlock();
1174 llvm::Constant
*getNSConcreteStackBlock();
1175 llvm::FunctionCallee
getBlockObjectAssign();
1176 llvm::FunctionCallee
getBlockObjectDispose();
1180 llvm::Function
*getLLVMLifetimeStartFn();
1181 llvm::Function
*getLLVMLifetimeEndFn();
1183 // Make sure that this type is translated.
1184 void UpdateCompletedType(const TagDecl
*TD
);
1186 llvm::Constant
*getMemberPointerConstant(const UnaryOperator
*e
);
1188 /// Emit type info if type of an expression is a variably modified
1189 /// type. Also emit proper debug info for cast types.
1190 void EmitExplicitCastExprType(const ExplicitCastExpr
*E
,
1191 CodeGenFunction
*CGF
= nullptr);
1193 /// Return the result of value-initializing the given type, i.e. a null
1194 /// expression of the given type. This is usually, but not always, an LLVM
1196 llvm::Constant
*EmitNullConstant(QualType T
);
1198 /// Return a null constant appropriate for zero-initializing a base class with
1199 /// the given type. This is usually, but not always, an LLVM null constant.
1200 llvm::Constant
*EmitNullConstantForBase(const CXXRecordDecl
*Record
);
1202 /// Emit a general error that something can't be done.
1203 void Error(SourceLocation loc
, StringRef error
);
1205 /// Print out an error that codegen doesn't support the specified stmt yet.
1206 void ErrorUnsupported(const Stmt
*S
, const char *Type
);
1208 /// Print out an error that codegen doesn't support the specified decl yet.
1209 void ErrorUnsupported(const Decl
*D
, const char *Type
);
1211 /// Set the attributes on the LLVM function for the given decl and function
1212 /// info. This applies attributes necessary for handling the ABI as well as
1213 /// user specified attributes like section.
1214 void SetInternalFunctionAttributes(GlobalDecl GD
, llvm::Function
*F
,
1215 const CGFunctionInfo
&FI
);
1217 /// Set the LLVM function attributes (sext, zext, etc).
1218 void SetLLVMFunctionAttributes(GlobalDecl GD
, const CGFunctionInfo
&Info
,
1219 llvm::Function
*F
, bool IsThunk
);
1221 /// Set the LLVM function attributes which only apply to a function
1223 void SetLLVMFunctionAttributesForDefinition(const Decl
*D
, llvm::Function
*F
);
1225 /// Set the LLVM function attributes that represent floating point
1227 void setLLVMFunctionFEnvAttributes(const FunctionDecl
*D
, llvm::Function
*F
);
1229 /// Return true iff the given type uses 'sret' when used as a return type.
1230 bool ReturnTypeUsesSRet(const CGFunctionInfo
&FI
);
1232 /// Return true iff the given type uses an argument slot when 'sret' is used
1233 /// as a return type.
1234 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo
&FI
);
1236 /// Return true iff the given type uses 'fpret' when used as a return type.
1237 bool ReturnTypeUsesFPRet(QualType ResultType
);
1239 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1240 bool ReturnTypeUsesFP2Ret(QualType ResultType
);
1242 /// Get the LLVM attributes and calling convention to use for a particular
1245 /// \param Name - The function name.
1246 /// \param Info - The function type information.
1247 /// \param CalleeInfo - The callee information these attributes are being
1248 /// constructed for. If valid, the attributes applied to this decl may
1249 /// contribute to the function attributes and calling convention.
1250 /// \param Attrs [out] - On return, the attribute list to use.
1251 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1252 void ConstructAttributeList(StringRef Name
, const CGFunctionInfo
&Info
,
1253 CGCalleeInfo CalleeInfo
,
1254 llvm::AttributeList
&Attrs
, unsigned &CallingConv
,
1255 bool AttrOnCallSite
, bool IsThunk
);
1257 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1258 /// though we had emitted it ourselves. We remove any attributes on F that
1259 /// conflict with the attributes we add here.
1261 /// This is useful for adding attrs to bitcode modules that you want to link
1262 /// with but don't control, such as CUDA's libdevice. When linking with such
1263 /// a bitcode library, you might want to set e.g. its functions'
1264 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1265 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1266 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1267 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1268 /// function in the bitcode library!
1270 /// With the exception of fast-math attrs, this will only make the attributes
1271 /// on the function more conservative. But it's unsafe to call this on a
1272 /// function which relies on particular fast-math attributes for correctness.
1273 /// It's up to you to ensure that this is safe.
1274 void addDefaultFunctionDefinitionAttributes(llvm::Function
&F
);
1275 void mergeDefaultFunctionDefinitionAttributes(llvm::Function
&F
,
1276 bool WillInternalize
);
1278 /// Like the overload taking a `Function &`, but intended specifically
1279 /// for frontends that want to build on Clang's target-configuration logic.
1280 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder
&attrs
);
1282 StringRef
getMangledName(GlobalDecl GD
);
1283 StringRef
getBlockMangledName(GlobalDecl GD
, const BlockDecl
*BD
);
1284 const GlobalDecl
getMangledNameDecl(StringRef
);
1286 void EmitTentativeDefinition(const VarDecl
*D
);
1288 void EmitExternalDeclaration(const VarDecl
*D
);
1290 void EmitVTable(CXXRecordDecl
*Class
);
1292 void RefreshTypeCacheForClass(const CXXRecordDecl
*Class
);
1294 /// Appends Opts to the "llvm.linker.options" metadata value.
1295 void AppendLinkerOptions(StringRef Opts
);
1297 /// Appends a detect mismatch command to the linker options.
1298 void AddDetectMismatch(StringRef Name
, StringRef Value
);
1300 /// Appends a dependent lib to the appropriate metadata value.
1301 void AddDependentLib(StringRef Lib
);
1304 llvm::GlobalVariable::LinkageTypes
getFunctionLinkage(GlobalDecl GD
);
1306 void setFunctionLinkage(GlobalDecl GD
, llvm::Function
*F
) {
1307 F
->setLinkage(getFunctionLinkage(GD
));
1310 /// Return the appropriate linkage for the vtable, VTT, and type information
1311 /// of the given class.
1312 llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl
*RD
);
1314 /// Return the store size, in character units, of the given LLVM type.
1315 CharUnits
GetTargetTypeStoreSize(llvm::Type
*Ty
) const;
1317 /// Returns LLVM linkage for a declarator.
1318 llvm::GlobalValue::LinkageTypes
1319 getLLVMLinkageForDeclarator(const DeclaratorDecl
*D
, GVALinkage Linkage
,
1320 bool IsConstantVariable
);
1322 /// Returns LLVM linkage for a declarator.
1323 llvm::GlobalValue::LinkageTypes
1324 getLLVMLinkageVarDefinition(const VarDecl
*VD
, bool IsConstant
);
1326 /// Emit all the global annotations.
1327 void EmitGlobalAnnotations();
1329 /// Emit an annotation string.
1330 llvm::Constant
*EmitAnnotationString(StringRef Str
);
1332 /// Emit the annotation's translation unit.
1333 llvm::Constant
*EmitAnnotationUnit(SourceLocation Loc
);
1335 /// Emit the annotation line number.
1336 llvm::Constant
*EmitAnnotationLineNo(SourceLocation L
);
1338 /// Emit additional args of the annotation.
1339 llvm::Constant
*EmitAnnotationArgs(const AnnotateAttr
*Attr
);
1341 /// Generate the llvm::ConstantStruct which contains the annotation
1342 /// information for a given GlobalValue. The annotation struct is
1343 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1344 /// GlobalValue being annotated. The second field is the constant string
1345 /// created from the AnnotateAttr's annotation. The third field is a constant
1346 /// string containing the name of the translation unit. The fourth field is
1347 /// the line number in the file of the annotated value declaration.
1348 llvm::Constant
*EmitAnnotateAttr(llvm::GlobalValue
*GV
,
1349 const AnnotateAttr
*AA
,
1352 /// Add global annotations that are set on D, for the global GV. Those
1353 /// annotations are emitted during finalization of the LLVM code.
1354 void AddGlobalAnnotations(const ValueDecl
*D
, llvm::GlobalValue
*GV
);
1356 bool isInNoSanitizeList(SanitizerMask Kind
, llvm::Function
*Fn
,
1357 SourceLocation Loc
) const;
1359 bool isInNoSanitizeList(SanitizerMask Kind
, llvm::GlobalVariable
*GV
,
1360 SourceLocation Loc
, QualType Ty
,
1361 StringRef Category
= StringRef()) const;
1363 /// Imbue XRay attributes to a function, applying the always/never attribute
1364 /// lists in the process. Returns true if we did imbue attributes this way,
1365 /// false otherwise.
1366 bool imbueXRayAttrs(llvm::Function
*Fn
, SourceLocation Loc
,
1367 StringRef Category
= StringRef()) const;
1369 /// \returns true if \p Fn at \p Loc should be excluded from profile
1370 /// instrumentation by the SCL passed by \p -fprofile-list.
1371 ProfileList::ExclusionType
1372 isFunctionBlockedByProfileList(llvm::Function
*Fn
, SourceLocation Loc
) const;
1374 /// \returns true if \p Fn at \p Loc should be excluded from profile
1375 /// instrumentation.
1376 ProfileList::ExclusionType
1377 isFunctionBlockedFromProfileInstr(llvm::Function
*Fn
,
1378 SourceLocation Loc
) const;
1380 SanitizerMetadata
*getSanitizerMetadata() {
1381 return SanitizerMD
.get();
1384 void addDeferredVTable(const CXXRecordDecl
*RD
) {
1385 DeferredVTables
.push_back(RD
);
1388 /// Emit code for a single global function or var decl. Forward declarations
1389 /// are emitted lazily.
1390 void EmitGlobal(GlobalDecl D
);
1392 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl
*D
);
1394 llvm::GlobalValue
*GetGlobalValue(StringRef Ref
);
1396 /// Set attributes which are common to any form of a global definition (alias,
1397 /// Objective-C method, function, global variable).
1399 /// NOTE: This should only be called for definitions.
1400 void SetCommonAttributes(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1402 void addReplacement(StringRef Name
, llvm::Constant
*C
);
1404 void addGlobalValReplacement(llvm::GlobalValue
*GV
, llvm::Constant
*C
);
1406 /// Emit a code for threadprivate directive.
1407 /// \param D Threadprivate declaration.
1408 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl
*D
);
1410 /// Emit a code for declare reduction construct.
1411 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl
*D
,
1412 CodeGenFunction
*CGF
= nullptr);
1414 /// Emit a code for declare mapper construct.
1415 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl
*D
,
1416 CodeGenFunction
*CGF
= nullptr);
1418 /// Emit a code for requires directive.
1419 /// \param D Requires declaration
1420 void EmitOMPRequiresDecl(const OMPRequiresDecl
*D
);
1422 /// Emit a code for the allocate directive.
1423 /// \param D The allocate declaration
1424 void EmitOMPAllocateDecl(const OMPAllocateDecl
*D
);
1426 /// Return the alignment specified in an allocate directive, if present.
1427 std::optional
<CharUnits
> getOMPAllocateAlignment(const VarDecl
*VD
);
1429 /// Returns whether the given record has hidden LTO visibility and therefore
1430 /// may participate in (single-module) CFI and whole-program vtable
1432 bool HasHiddenLTOVisibility(const CXXRecordDecl
*RD
);
1434 /// Returns whether the given record has public LTO visibility (regardless of
1435 /// -lto-whole-program-visibility) and therefore may not participate in
1436 /// (single-module) CFI and whole-program vtable optimization.
1437 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl
*RD
);
1439 /// Returns the vcall visibility of the given type. This is the scope in which
1440 /// a virtual function call could be made which ends up being dispatched to a
1441 /// member function of this class. This scope can be wider than the visibility
1442 /// of the class itself when the class has a more-visible dynamic base class.
1443 /// The client should pass in an empty Visited set, which is used to prevent
1444 /// redundant recursive processing.
1445 llvm::GlobalObject::VCallVisibility
1446 GetVCallVisibilityLevel(const CXXRecordDecl
*RD
,
1447 llvm::DenseSet
<const CXXRecordDecl
*> &Visited
);
1449 /// Emit type metadata for the given vtable using the given layout.
1450 void EmitVTableTypeMetadata(const CXXRecordDecl
*RD
,
1451 llvm::GlobalVariable
*VTable
,
1452 const VTableLayout
&VTLayout
);
1454 llvm::Type
*getVTableComponentType() const;
1456 /// Generate a cross-DSO type identifier for MD.
1457 llvm::ConstantInt
*CreateCrossDsoCfiTypeId(llvm::Metadata
*MD
);
1459 /// Generate a KCFI type identifier for T.
1460 llvm::ConstantInt
*CreateKCFITypeId(QualType T
);
1462 /// Create a metadata identifier for the given type. This may either be an
1463 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1464 /// internal identifiers).
1465 llvm::Metadata
*CreateMetadataIdentifierForType(QualType T
);
1467 /// Create a metadata identifier that is intended to be used to check virtual
1468 /// calls via a member function pointer.
1469 llvm::Metadata
*CreateMetadataIdentifierForVirtualMemPtrType(QualType T
);
1471 /// Create a metadata identifier for the generalization of the given type.
1472 /// This may either be an MDString (for external identifiers) or a distinct
1473 /// unnamed MDNode (for internal identifiers).
1474 llvm::Metadata
*CreateMetadataIdentifierGeneralized(QualType T
);
1476 /// Create and attach type metadata to the given function.
1477 void CreateFunctionTypeMetadataForIcall(const FunctionDecl
*FD
,
1480 /// Set type metadata to the given function.
1481 void setKCFIType(const FunctionDecl
*FD
, llvm::Function
*F
);
1483 /// Emit KCFI type identifier constants and remove unused identifiers.
1484 void finalizeKCFITypes();
1486 /// Whether this function's return type has no side effects, and thus may
1487 /// be trivially discarded if it is unused.
1488 bool MayDropFunctionReturn(const ASTContext
&Context
,
1489 QualType ReturnType
) const;
1491 /// Returns whether this module needs the "all-vtables" type identifier.
1492 bool NeedAllVtablesTypeId() const;
1494 /// Create and attach type metadata for the given vtable.
1495 void AddVTableTypeMetadata(llvm::GlobalVariable
*VTable
, CharUnits Offset
,
1496 const CXXRecordDecl
*RD
);
1498 /// Return a vector of most-base classes for RD. This is used to implement
1499 /// control flow integrity checks for member function pointers.
1501 /// A most-base class of a class C is defined as a recursive base class of C,
1502 /// including C itself, that does not have any bases.
1503 std::vector
<const CXXRecordDecl
*>
1504 getMostBaseClasses(const CXXRecordDecl
*RD
);
1506 llvm::GlobalVariable
*
1507 GetOrCreateRTTIProxyGlobalVariable(llvm::Constant
*Addr
);
1509 /// Get the declaration of std::terminate for the platform.
1510 llvm::FunctionCallee
getTerminateFn();
1512 llvm::SanitizerStatReport
&getSanStats();
1515 createOpenCLIntToSamplerConversion(const Expr
*E
, CodeGenFunction
&CGF
);
1517 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1518 /// information in the program executable. The argument information stored
1519 /// includes the argument name, its type, the address and access qualifiers
1520 /// used. This helper can be used to generate metadata for source code kernel
1521 /// function as well as generated implicitly kernels. If a kernel is generated
1522 /// implicitly null value has to be passed to the last two parameters,
1523 /// otherwise all parameters must have valid non-null values.
1524 /// \param FN is a pointer to IR function being generated.
1525 /// \param FD is a pointer to function declaration if any.
1526 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1527 void GenKernelArgMetadata(llvm::Function
*FN
,
1528 const FunctionDecl
*FD
= nullptr,
1529 CodeGenFunction
*CGF
= nullptr);
1531 /// Get target specific null pointer.
1532 /// \param T is the LLVM type of the null pointer.
1533 /// \param QT is the clang QualType of the null pointer.
1534 llvm::Constant
*getNullPointer(llvm::PointerType
*T
, QualType QT
);
1536 CharUnits
getNaturalTypeAlignment(QualType T
,
1537 LValueBaseInfo
*BaseInfo
= nullptr,
1538 TBAAAccessInfo
*TBAAInfo
= nullptr,
1539 bool forPointeeType
= false);
1540 CharUnits
getNaturalPointeeTypeAlignment(QualType T
,
1541 LValueBaseInfo
*BaseInfo
= nullptr,
1542 TBAAAccessInfo
*TBAAInfo
= nullptr);
1543 bool stopAutoInit();
1545 /// Print the postfix for externalized static variable or kernels for single
1546 /// source offloading languages CUDA and HIP. The unique postfix is created
1547 /// using either the CUID argument, or the file's UniqueID and active macros.
1548 /// The fallback method without a CUID requires that the offloading toolchain
1549 /// does not define separate macros via the -cc1 options.
1550 void printPostfixForExternalizedDecl(llvm::raw_ostream
&OS
,
1551 const Decl
*D
) const;
1553 /// Move some lazily-emitted states to the NewBuilder. This is especially
1554 /// essential for the incremental parsing environment like Clang Interpreter,
1555 /// because we'll lose all important information after each repl.
1556 void moveLazyEmissionStates(CodeGenModule
*NewBuilder
);
1559 llvm::Constant
*GetOrCreateLLVMFunction(
1560 StringRef MangledName
, llvm::Type
*Ty
, GlobalDecl D
, bool ForVTable
,
1561 bool DontDefer
= false, bool IsThunk
= false,
1562 llvm::AttributeList ExtraAttrs
= llvm::AttributeList(),
1563 ForDefinition_t IsForDefinition
= NotForDefinition
);
1565 // References to multiversion functions are resolved through an implicitly
1566 // defined resolver function. This function is responsible for creating
1567 // the resolver symbol for the provided declaration. The value returned
1568 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1569 // that feature and for a regular function (llvm::GlobalValue) otherwise.
1570 llvm::Constant
*GetOrCreateMultiVersionResolver(GlobalDecl GD
);
1572 // In scenarios where a function is not known to be a multiversion function
1573 // until a later declaration, it is sometimes necessary to change the
1574 // previously created mangled name to align with requirements of whatever
1575 // multiversion function kind the function is now known to be. This function
1576 // is responsible for performing such mangled name updates.
1577 void UpdateMultiVersionNames(GlobalDecl GD
, const FunctionDecl
*FD
,
1578 StringRef
&CurName
);
1581 GetOrCreateLLVMGlobal(StringRef MangledName
, llvm::Type
*Ty
, LangAS AddrSpace
,
1583 ForDefinition_t IsForDefinition
= NotForDefinition
);
1585 bool GetCPUAndFeaturesAttributes(GlobalDecl GD
,
1586 llvm::AttrBuilder
&AttrBuilder
,
1587 bool SetTargetFeatures
= true);
1588 void setNonAliasAttributes(GlobalDecl GD
, llvm::GlobalObject
*GO
);
1590 /// Set function attributes for a function declaration.
1591 void SetFunctionAttributes(GlobalDecl GD
, llvm::Function
*F
,
1592 bool IsIncompleteFunction
, bool IsThunk
);
1594 void EmitGlobalDefinition(GlobalDecl D
, llvm::GlobalValue
*GV
= nullptr);
1596 void EmitGlobalFunctionDefinition(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1597 void EmitMultiVersionFunctionDefinition(GlobalDecl GD
, llvm::GlobalValue
*GV
);
1599 void EmitGlobalVarDefinition(const VarDecl
*D
, bool IsTentative
= false);
1600 void EmitExternalVarDeclaration(const VarDecl
*D
);
1601 void EmitAliasDefinition(GlobalDecl GD
);
1602 void emitIFuncDefinition(GlobalDecl GD
);
1603 void emitCPUDispatchDefinition(GlobalDecl GD
);
1604 void EmitObjCPropertyImplementations(const ObjCImplementationDecl
*D
);
1605 void EmitObjCIvarInitializations(ObjCImplementationDecl
*D
);
1607 // C++ related functions.
1609 void EmitDeclContext(const DeclContext
*DC
);
1610 void EmitLinkageSpec(const LinkageSpecDecl
*D
);
1611 void EmitTopLevelStmt(const TopLevelStmtDecl
*D
);
1613 /// Emit the function that initializes C++ thread_local variables.
1614 void EmitCXXThreadLocalInitFunc();
1616 /// Emit the function that initializes global variables for a C++ Module.
1617 void EmitCXXModuleInitFunc(clang::Module
*Primary
);
1619 /// Emit the function that initializes C++ globals.
1620 void EmitCXXGlobalInitFunc();
1622 /// Emit the function that performs cleanup associated with C++ globals.
1623 void EmitCXXGlobalCleanUpFunc();
1625 /// Emit the function that initializes the specified global (if PerformInit is
1626 /// true) and registers its destructor.
1627 void EmitCXXGlobalVarDeclInitFunc(const VarDecl
*D
,
1628 llvm::GlobalVariable
*Addr
,
1631 void EmitPointerToInitFunc(const VarDecl
*VD
, llvm::GlobalVariable
*Addr
,
1632 llvm::Function
*InitFunc
, InitSegAttr
*ISA
);
1634 // FIXME: Hardcoding priority here is gross.
1635 void AddGlobalCtor(llvm::Function
*Ctor
, int Priority
= 65535,
1636 unsigned LexOrder
= ~0U,
1637 llvm::Constant
*AssociatedData
= nullptr);
1638 void AddGlobalDtor(llvm::Function
*Dtor
, int Priority
= 65535,
1639 bool IsDtorAttrFunc
= false);
1641 /// EmitCtorList - Generates a global array of functions and priorities using
1642 /// the given list and name. This array will have appending linkage and is
1643 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1644 void EmitCtorList(CtorList
&Fns
, const char *GlobalName
);
1646 /// Emit any needed decls for which code generation was deferred.
1647 void EmitDeferred();
1649 /// Try to emit external vtables as available_externally if they have emitted
1650 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1651 /// is not allowed to create new references to things that need to be emitted
1653 void EmitVTablesOpportunistically();
1655 /// Call replaceAllUsesWith on all pairs in Replacements.
1656 void applyReplacements();
1658 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1659 void applyGlobalValReplacements();
1661 void checkAliases();
1663 std::map
<int, llvm::TinyPtrVector
<llvm::Function
*>> DtorsUsingAtExit
;
1665 /// Register functions annotated with __attribute__((destructor)) using
1666 /// __cxa_atexit, if it is available, or atexit otherwise.
1667 void registerGlobalDtorsWithAtExit();
1669 // When using sinit and sterm functions, unregister
1670 // __attribute__((destructor)) annotated functions which were previously
1671 // registered by the atexit subroutine using unatexit.
1672 void unregisterGlobalDtorsWithUnAtExit();
1674 /// Emit deferred multiversion function resolvers and associated variants.
1675 void emitMultiVersionFunctions();
1677 /// Emit any vtables which we deferred and still have a use for.
1678 void EmitDeferredVTables();
1680 /// Emit a dummy function that reference a CoreFoundation symbol when
1681 /// @available is used on Darwin.
1682 void emitAtAvailableLinkGuard();
1684 /// Emit the llvm.used and llvm.compiler.used metadata.
1685 void emitLLVMUsed();
1687 /// For C++20 Itanium ABI, emit the initializers for the module.
1688 void EmitModuleInitializers(clang::Module
*Primary
);
1690 /// Emit the link options introduced by imported modules.
1691 void EmitModuleLinkOptions();
1693 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
1694 /// have a resolver name that matches 'Elem' to instead resolve to the name of
1695 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
1696 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
1697 /// may not reference aliases. Redirection is only performed if 'Elem' is only
1698 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
1699 /// redirection is successful, and 'false' is returned otherwise.
1700 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue
*Elem
,
1701 llvm::GlobalValue
*CppFunc
);
1703 /// Emit aliases for internal-linkage declarations inside "C" language
1704 /// linkage specifications, giving them the "expected" name where possible.
1705 void EmitStaticExternCAliases();
1707 void EmitDeclMetadata();
1709 /// Emit the Clang version as llvm.ident metadata.
1710 void EmitVersionIdentMetadata();
1712 /// Emit the Clang commandline as llvm.commandline metadata.
1713 void EmitCommandLineMetadata();
1715 /// Emit the module flag metadata used to pass options controlling the
1716 /// the backend to LLVM.
1717 void EmitBackendOptionsMetadata(const CodeGenOptions
&CodeGenOpts
);
1719 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1720 void EmitOpenCLMetadata();
1722 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1723 /// .gcda files in a way that persists in .bc files.
1724 void EmitCoverageFile();
1726 /// Determine whether the definition must be emitted; if this returns \c
1727 /// false, the definition can be emitted lazily if it's used.
1728 bool MustBeEmitted(const ValueDecl
*D
);
1730 /// Determine whether the definition can be emitted eagerly, or should be
1731 /// delayed until the end of the translation unit. This is relevant for
1732 /// definitions whose linkage can change, e.g. implicit function instantions
1733 /// which may later be explicitly instantiated.
1734 bool MayBeEmittedEagerly(const ValueDecl
*D
);
1736 /// Check whether we can use a "simpler", more core exceptions personality
1738 void SimplifyPersonality();
1740 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
1741 /// attributes which can be simply added to a function.
1742 void getTrivialDefaultFunctionAttributes(StringRef Name
, bool HasOptnone
,
1743 bool AttrOnCallSite
,
1744 llvm::AttrBuilder
&FuncAttrs
);
1746 /// Helper function for ConstructAttributeList and
1747 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1748 /// attributes to add to a function with the given properties.
1749 void getDefaultFunctionAttributes(StringRef Name
, bool HasOptnone
,
1750 bool AttrOnCallSite
,
1751 llvm::AttrBuilder
&FuncAttrs
);
1753 llvm::Metadata
*CreateMetadataIdentifierImpl(QualType T
, MetadataTypeMap
&Map
,
1757 } // end namespace CodeGen
1758 } // end namespace clang
1760 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H