[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / CodeGen / CodeGenModule.h
blob793861f23b15f953ae32c517f86d8efb362949d7
1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // 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/ProfileList.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/XRayLists.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/MapVector.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/StringMap.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/Transforms/Utils/SanitizerStats.h"
41 #include <optional>
43 namespace llvm {
44 class Module;
45 class Constant;
46 class ConstantInt;
47 class Function;
48 class GlobalValue;
49 class DataLayout;
50 class FunctionType;
51 class LLVMContext;
52 class IndexedInstrProfReader;
54 namespace vfs {
55 class FileSystem;
59 namespace clang {
60 class ASTContext;
61 class AtomicType;
62 class FunctionDecl;
63 class IdentifierInfo;
64 class ObjCImplementationDecl;
65 class ObjCEncodeExpr;
66 class BlockExpr;
67 class CharUnits;
68 class Decl;
69 class Expr;
70 class Stmt;
71 class StringLiteral;
72 class NamedDecl;
73 class ValueDecl;
74 class VarDecl;
75 class LangOptions;
76 class CodeGenOptions;
77 class HeaderSearchOptions;
78 class DiagnosticsEngine;
79 class AnnotateAttr;
80 class CXXDestructorDecl;
81 class Module;
82 class CoverageSourceInfo;
83 class InitSegAttr;
85 namespace CodeGen {
87 class CodeGenFunction;
88 class CodeGenTBAA;
89 class CGCXXABI;
90 class CGDebugInfo;
91 class CGObjCRuntime;
92 class CGOpenCLRuntime;
93 class CGOpenMPRuntime;
94 class CGCUDARuntime;
95 class CGHLSLRuntime;
96 class CoverageMappingModuleGen;
97 class TargetCodeGenInfo;
99 enum ForDefinition_t : bool {
100 NotForDefinition = false,
101 ForDefinition = true
104 struct OrderGlobalInitsOrStermFinalizers {
105 unsigned int priority;
106 unsigned int lex_order;
107 OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
108 : priority(p), lex_order(l) {}
110 bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
111 return priority == RHS.priority && lex_order == RHS.lex_order;
114 bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
115 return std::tie(priority, lex_order) <
116 std::tie(RHS.priority, RHS.lex_order);
120 struct ObjCEntrypoints {
121 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
123 /// void objc_alloc(id);
124 llvm::FunctionCallee objc_alloc;
126 /// void objc_allocWithZone(id);
127 llvm::FunctionCallee objc_allocWithZone;
129 /// void objc_alloc_init(id);
130 llvm::FunctionCallee objc_alloc_init;
132 /// void objc_autoreleasePoolPop(void*);
133 llvm::FunctionCallee objc_autoreleasePoolPop;
135 /// void objc_autoreleasePoolPop(void*);
136 /// Note this method is used when we are using exception handling
137 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
139 /// void *objc_autoreleasePoolPush(void);
140 llvm::Function *objc_autoreleasePoolPush;
142 /// id objc_autorelease(id);
143 llvm::Function *objc_autorelease;
145 /// id objc_autorelease(id);
146 /// Note this is the runtime method not the intrinsic.
147 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
149 /// id objc_autoreleaseReturnValue(id);
150 llvm::Function *objc_autoreleaseReturnValue;
152 /// void objc_copyWeak(id *dest, id *src);
153 llvm::Function *objc_copyWeak;
155 /// void objc_destroyWeak(id*);
156 llvm::Function *objc_destroyWeak;
158 /// id objc_initWeak(id*, id);
159 llvm::Function *objc_initWeak;
161 /// id objc_loadWeak(id*);
162 llvm::Function *objc_loadWeak;
164 /// id objc_loadWeakRetained(id*);
165 llvm::Function *objc_loadWeakRetained;
167 /// void objc_moveWeak(id *dest, id *src);
168 llvm::Function *objc_moveWeak;
170 /// id objc_retain(id);
171 llvm::Function *objc_retain;
173 /// id objc_retain(id);
174 /// Note this is the runtime method not the intrinsic.
175 llvm::FunctionCallee objc_retainRuntimeFunction;
177 /// id objc_retainAutorelease(id);
178 llvm::Function *objc_retainAutorelease;
180 /// id objc_retainAutoreleaseReturnValue(id);
181 llvm::Function *objc_retainAutoreleaseReturnValue;
183 /// id objc_retainAutoreleasedReturnValue(id);
184 llvm::Function *objc_retainAutoreleasedReturnValue;
186 /// id objc_retainBlock(id);
187 llvm::Function *objc_retainBlock;
189 /// void objc_release(id);
190 llvm::Function *objc_release;
192 /// void objc_release(id);
193 /// Note this is the runtime method not the intrinsic.
194 llvm::FunctionCallee objc_releaseRuntimeFunction;
196 /// void objc_storeStrong(id*, id);
197 llvm::Function *objc_storeStrong;
199 /// id objc_storeWeak(id*, id);
200 llvm::Function *objc_storeWeak;
202 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
203 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
205 /// A void(void) inline asm to use to mark that the return value of
206 /// a call will be immediately retain.
207 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
209 /// void clang.arc.use(...);
210 llvm::Function *clang_arc_use;
212 /// void clang.arc.noop.use(...);
213 llvm::Function *clang_arc_noop_use;
216 /// This class records statistics on instrumentation based profiling.
217 class InstrProfStats {
218 uint32_t VisitedInMainFile = 0;
219 uint32_t MissingInMainFile = 0;
220 uint32_t Visited = 0;
221 uint32_t Missing = 0;
222 uint32_t Mismatched = 0;
224 public:
225 InstrProfStats() = default;
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) {
229 if (MainFile)
230 ++VisitedInMainFile;
231 ++Visited;
233 /// Record that a function we've visited has no profile data.
234 void addMissing(bool MainFile) {
235 if (MainFile)
236 ++MissingInMainFile;
237 ++Missing;
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
250 // header.
251 public:
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.
258 CharUnits Alignment;
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());
267 profileImpl(id);
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
279 /// LLVM code.
280 class CodeGenModule : public CodeGenTypeCache {
281 CodeGenModule(const CodeGenModule &) = delete;
282 void operator=(const CodeGenModule &) = delete;
284 public:
285 struct Structor {
286 Structor()
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) {}
293 int Priority;
294 unsigned LexOrder;
295 llvm::Constant *Initializer;
296 llvm::Constant *AssociatedData;
299 typedef std::vector<Structor> CtorList;
301 private:
302 ASTContext &Context;
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
323 CodeGenTypes Types;
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
342 // or a definition.
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
348 /// yet.
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 // Reemission is only needed in incremental mode.
364 if (!Context.getLangOpts().IncrementalExtensions)
365 return;
367 // Assume a linkage by default that does not need reemission.
368 auto L = llvm::GlobalValue::ExternalLinkage;
369 if (llvm::isa<FunctionDecl>(GD.getDecl()))
370 L = getFunctionLinkage(GD);
371 else if (auto *VD = llvm::dyn_cast<VarDecl>(GD.getDecl()))
372 L = getLLVMLinkageVarDefinition(VD);
374 if (llvm::GlobalValue::isInternalLinkage(L) ||
375 llvm::GlobalValue::isLinkOnceLinkage(L) ||
376 llvm::GlobalValue::isWeakLinkage(L)) {
377 EmittedDeferredDecls[getMangledName(GD)] = GD;
381 /// List of alias we have emitted. Used to make sure that what they point to
382 /// is defined once we get to the end of the of the translation unit.
383 std::vector<GlobalDecl> Aliases;
385 /// List of multiversion functions to be emitted. This list is processed in
386 /// conjunction with other deferred symbols and is used to ensure that
387 /// multiversion function resolvers and ifuncs are defined and emitted.
388 std::vector<GlobalDecl> MultiVersionFuncs;
390 llvm::MapVector<StringRef, llvm::TrackingVH<llvm::Constant>> Replacements;
392 /// List of global values to be replaced with something else. Used when we
393 /// want to replace a GlobalValue but can't identify it by its mangled name
394 /// anymore (because the name is already taken).
395 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
396 GlobalValReplacements;
398 /// Variables for which we've emitted globals containing their constant
399 /// values along with the corresponding globals, for opportunistic reuse.
400 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
402 /// Set of global decls for which we already diagnosed mangled name conflict.
403 /// Required to not issue a warning (on a mangling conflict) multiple times
404 /// for the same decl.
405 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
407 /// A queue of (optional) vtables to consider emitting.
408 std::vector<const CXXRecordDecl*> DeferredVTables;
410 /// A queue of (optional) vtables that may be emitted opportunistically.
411 std::vector<const CXXRecordDecl *> OpportunisticVTables;
413 /// List of global values which are required to be present in the object file;
414 /// bitcast to i8*. This is used for forcing visibility of symbols which may
415 /// otherwise be optimized out.
416 std::vector<llvm::WeakTrackingVH> LLVMUsed;
417 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
419 /// Store the list of global constructors and their respective priorities to
420 /// be emitted when the translation unit is complete.
421 CtorList GlobalCtors;
423 /// Store the list of global destructors and their respective priorities to be
424 /// emitted when the translation unit is complete.
425 CtorList GlobalDtors;
427 /// An ordered map of canonical GlobalDecls to their mangled names.
428 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
429 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
431 /// Global annotations.
432 std::vector<llvm::Constant*> Annotations;
434 /// Map used to get unique annotation strings.
435 llvm::StringMap<llvm::Constant*> AnnotationStrings;
437 /// Used for uniquing of annotation arguments.
438 llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
440 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
442 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
443 llvm::DenseMap<const UnnamedGlobalConstantDecl *, llvm::GlobalVariable *>
444 UnnamedGlobalConstantDeclMap;
445 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
446 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
447 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
449 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
450 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
452 /// Map used to get unique type descriptor constants for sanitizers.
453 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
455 /// Map used to track internal linkage functions declared within
456 /// extern "C" regions.
457 typedef llvm::MapVector<IdentifierInfo *,
458 llvm::GlobalValue *> StaticExternCMap;
459 StaticExternCMap StaticExternCValues;
461 /// thread_local variables defined or used in this TU.
462 std::vector<const VarDecl *> CXXThreadLocals;
464 /// thread_local variables with initializers that need to run
465 /// before any thread_local variable in this TU is odr-used.
466 std::vector<llvm::Function *> CXXThreadLocalInits;
467 std::vector<const VarDecl *> CXXThreadLocalInitVars;
469 /// Global variables with initializers that need to run before main.
470 std::vector<llvm::Function *> CXXGlobalInits;
472 /// When a C++ decl with an initializer is deferred, null is
473 /// appended to CXXGlobalInits, and the index of that null is placed
474 /// here so that the initializer will be performed in the correct
475 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
476 /// that we don't re-emit the initializer.
477 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
479 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
480 GlobalInitData;
482 struct GlobalInitPriorityCmp {
483 bool operator()(const GlobalInitData &LHS,
484 const GlobalInitData &RHS) const {
485 return LHS.first.priority < RHS.first.priority;
489 /// Global variables with initializers whose order of initialization is set by
490 /// init_priority attribute.
491 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
493 /// Global destructor functions and arguments that need to run on termination.
494 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
495 /// functions, which also run on unloading a shared library.
496 typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
497 llvm::Constant *>
498 CXXGlobalDtorsOrStermFinalizer_t;
499 SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
500 CXXGlobalDtorsOrStermFinalizers;
502 typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
503 StermFinalizerData;
505 struct StermFinalizerPriorityCmp {
506 bool operator()(const StermFinalizerData &LHS,
507 const StermFinalizerData &RHS) const {
508 return LHS.first.priority < RHS.first.priority;
512 /// Global variables with sterm finalizers whose order of initialization is
513 /// set by init_priority attribute.
514 SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
516 /// The complete set of modules that has been imported.
517 llvm::SetVector<clang::Module *> ImportedModules;
519 /// The set of modules for which the module initializers
520 /// have been emitted.
521 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
523 /// A vector of metadata strings for linker options.
524 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
526 /// A vector of metadata strings for dependent libraries for ELF.
527 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
529 /// @name Cache for Objective-C runtime types
530 /// @{
532 /// Cached reference to the class for constant strings. This value has type
533 /// int * but is actually an Obj-C class pointer.
534 llvm::WeakTrackingVH CFConstantStringClassRef;
536 /// The type used to describe the state of a fast enumeration in
537 /// Objective-C's for..in loop.
538 QualType ObjCFastEnumerationStateType;
540 /// @}
542 /// Lazily create the Objective-C runtime
543 void createObjCRuntime();
545 void createOpenCLRuntime();
546 void createOpenMPRuntime();
547 void createCUDARuntime();
548 void createHLSLRuntime();
550 bool isTriviallyRecursive(const FunctionDecl *F);
551 bool shouldEmitFunction(GlobalDecl GD);
552 bool shouldOpportunisticallyEmitVTables();
553 /// Map used to be sure we don't emit the same CompoundLiteral twice.
554 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
555 EmittedCompoundLiterals;
557 /// Map of the global blocks we've emitted, so that we don't have to re-emit
558 /// them if the constexpr evaluator gets aggressive.
559 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
561 /// @name Cache for Blocks Runtime Globals
562 /// @{
564 llvm::Constant *NSConcreteGlobalBlock = nullptr;
565 llvm::Constant *NSConcreteStackBlock = nullptr;
567 llvm::FunctionCallee BlockObjectAssign = nullptr;
568 llvm::FunctionCallee BlockObjectDispose = nullptr;
570 llvm::Type *BlockDescriptorType = nullptr;
571 llvm::Type *GenericBlockLiteralType = nullptr;
573 struct {
574 int GlobalUniqueCount;
575 } Block;
577 GlobalDecl initializedGlobalDecl;
579 /// @}
581 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
582 llvm::Function *LifetimeStartFn = nullptr;
584 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
585 llvm::Function *LifetimeEndFn = nullptr;
587 std::unique_ptr<SanitizerMetadata> SanitizerMD;
589 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
591 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
593 /// Mapping from canonical types to their metadata identifiers. We need to
594 /// maintain this mapping because identifiers may be formed from distinct
595 /// MDNodes.
596 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
597 MetadataTypeMap MetadataIdMap;
598 MetadataTypeMap VirtualMetadataIdMap;
599 MetadataTypeMap GeneralizedMetadataIdMap;
601 // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
602 // when used with -fincremental-extensions.
603 std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *>
604 GlobalTopLevelStmtBlockInFlight;
606 public:
607 CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
608 const HeaderSearchOptions &headersearchopts,
609 const PreprocessorOptions &ppopts,
610 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
611 DiagnosticsEngine &Diags,
612 CoverageSourceInfo *CoverageInfo = nullptr);
614 ~CodeGenModule();
616 void clear();
618 /// Finalize LLVM code generation.
619 void Release();
621 /// Return true if we should emit location information for expressions.
622 bool getExpressionLocationsEnabled() const;
624 /// Return a reference to the configured Objective-C runtime.
625 CGObjCRuntime &getObjCRuntime() {
626 if (!ObjCRuntime) createObjCRuntime();
627 return *ObjCRuntime;
630 /// Return true iff an Objective-C runtime has been configured.
631 bool hasObjCRuntime() { return !!ObjCRuntime; }
633 const std::string &getModuleNameHash() const { return ModuleNameHash; }
635 /// Return a reference to the configured OpenCL runtime.
636 CGOpenCLRuntime &getOpenCLRuntime() {
637 assert(OpenCLRuntime != nullptr);
638 return *OpenCLRuntime;
641 /// Return a reference to the configured OpenMP runtime.
642 CGOpenMPRuntime &getOpenMPRuntime() {
643 assert(OpenMPRuntime != nullptr);
644 return *OpenMPRuntime;
647 /// Return a reference to the configured CUDA runtime.
648 CGCUDARuntime &getCUDARuntime() {
649 assert(CUDARuntime != nullptr);
650 return *CUDARuntime;
653 /// Return a reference to the configured HLSL runtime.
654 CGHLSLRuntime &getHLSLRuntime() {
655 assert(HLSLRuntime != nullptr);
656 return *HLSLRuntime;
659 ObjCEntrypoints &getObjCEntrypoints() const {
660 assert(ObjCData != nullptr);
661 return *ObjCData;
664 // Version checking functions, used to implement ObjC's @available:
665 // i32 @__isOSVersionAtLeast(i32, i32, i32)
666 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
667 // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
668 llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
670 InstrProfStats &getPGOStats() { return PGOStats; }
671 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
673 CoverageMappingModuleGen *getCoverageMapping() const {
674 return CoverageMapping.get();
677 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
678 return StaticLocalDeclMap[D];
680 void setStaticLocalDeclAddress(const VarDecl *D,
681 llvm::Constant *C) {
682 StaticLocalDeclMap[D] = C;
685 llvm::Constant *
686 getOrCreateStaticVarDecl(const VarDecl &D,
687 llvm::GlobalValue::LinkageTypes Linkage);
689 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
690 return StaticLocalDeclGuardMap[D];
692 void setStaticLocalDeclGuardAddress(const VarDecl *D,
693 llvm::GlobalVariable *C) {
694 StaticLocalDeclGuardMap[D] = C;
697 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
698 CharUnits Align);
700 bool lookupRepresentativeDecl(StringRef MangledName,
701 GlobalDecl &Result) const;
703 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
704 return AtomicSetterHelperFnMap[Ty];
706 void setAtomicSetterHelperFnMap(QualType Ty,
707 llvm::Constant *Fn) {
708 AtomicSetterHelperFnMap[Ty] = Fn;
711 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
712 return AtomicGetterHelperFnMap[Ty];
714 void setAtomicGetterHelperFnMap(QualType Ty,
715 llvm::Constant *Fn) {
716 AtomicGetterHelperFnMap[Ty] = Fn;
719 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
720 return TypeDescriptorMap[Ty];
722 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
723 TypeDescriptorMap[Ty] = C;
726 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
728 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
729 if (!NoObjCARCExceptionsMetadata)
730 NoObjCARCExceptionsMetadata =
731 llvm::MDNode::get(getLLVMContext(), std::nullopt);
732 return NoObjCARCExceptionsMetadata;
735 ASTContext &getContext() const { return Context; }
736 const LangOptions &getLangOpts() const { return LangOpts; }
737 const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const {
738 return FS;
740 const HeaderSearchOptions &getHeaderSearchOpts()
741 const { return HeaderSearchOpts; }
742 const PreprocessorOptions &getPreprocessorOpts()
743 const { return PreprocessorOpts; }
744 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
745 llvm::Module &getModule() const { return TheModule; }
746 DiagnosticsEngine &getDiags() const { return Diags; }
747 const llvm::DataLayout &getDataLayout() const {
748 return TheModule.getDataLayout();
750 const TargetInfo &getTarget() const { return Target; }
751 const llvm::Triple &getTriple() const { return Target.getTriple(); }
752 bool supportsCOMDAT() const;
753 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
755 CGCXXABI &getCXXABI() const { return *ABI; }
756 llvm::LLVMContext &getLLVMContext() { return VMContext; }
758 bool shouldUseTBAA() const { return TBAA != nullptr; }
760 const TargetCodeGenInfo &getTargetCodeGenInfo();
762 CodeGenTypes &getTypes() { return Types; }
764 CodeGenVTables &getVTables() { return VTables; }
766 ItaniumVTableContext &getItaniumVTableContext() {
767 return VTables.getItaniumVTableContext();
770 const ItaniumVTableContext &getItaniumVTableContext() const {
771 return VTables.getItaniumVTableContext();
774 MicrosoftVTableContext &getMicrosoftVTableContext() {
775 return VTables.getMicrosoftVTableContext();
778 CtorList &getGlobalCtors() { return GlobalCtors; }
779 CtorList &getGlobalDtors() { return GlobalDtors; }
781 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
782 /// the given type.
783 llvm::MDNode *getTBAATypeInfo(QualType QTy);
785 /// getTBAAAccessInfo - Get TBAA information that describes an access to
786 /// an object of the given type.
787 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
789 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
790 /// access to a virtual table pointer.
791 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
793 llvm::MDNode *getTBAAStructInfo(QualType QTy);
795 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
796 /// type. Return null if the type is not suitable for use in TBAA access tags.
797 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
799 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
800 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
802 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
803 /// type casts.
804 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
805 TBAAAccessInfo TargetInfo);
807 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
808 /// purposes of conditional operator.
809 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
810 TBAAAccessInfo InfoB);
812 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
813 /// purposes of memory transfer calls.
814 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
815 TBAAAccessInfo SrcInfo);
817 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
818 /// base lvalue.
819 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
820 if (Base.getTBAAInfo().isMayAlias())
821 return TBAAAccessInfo::getMayAliasInfo();
822 return getTBAAAccessInfo(AccessType);
825 bool isPaddedAtomicType(QualType type);
826 bool isPaddedAtomicType(const AtomicType *type);
828 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
829 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
830 TBAAAccessInfo TBAAInfo);
832 /// Adds !invariant.barrier !tag to instruction
833 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
834 const CXXRecordDecl *RD);
836 /// Emit the given number of characters as a value of type size_t.
837 llvm::ConstantInt *getSize(CharUnits numChars);
839 /// Set the visibility for the given LLVM GlobalValue.
840 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
842 void setDSOLocal(llvm::GlobalValue *GV) const;
844 bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const {
845 return getLangOpts().hasDefaultVisibilityExportMapping() && D &&
846 (D->getLinkageAndVisibility().getVisibility() ==
847 DefaultVisibility) &&
848 (getLangOpts().isAllDefaultVisibilityExportMapping() ||
849 (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
850 D->getLinkageAndVisibility().isVisibilityExplicit()));
852 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
853 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
854 /// Set visibility, dllimport/dllexport and dso_local.
855 /// This must be called after dllimport/dllexport is set.
856 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
857 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
859 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
861 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
862 /// variable declaration D.
863 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
865 /// Get LLVM TLS mode from CodeGenOptions.
866 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
868 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
869 switch (V) {
870 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
871 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
872 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
874 llvm_unreachable("unknown visibility!");
877 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
878 ForDefinition_t IsForDefinition
879 = NotForDefinition);
881 /// Will return a global variable of the given type. If a variable with a
882 /// different type already exists then a new variable with the right type
883 /// will be created and all uses of the old variable will be replaced with a
884 /// bitcast to the new variable.
885 llvm::GlobalVariable *
886 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
887 llvm::GlobalValue::LinkageTypes Linkage,
888 llvm::Align Alignment);
890 llvm::Function *CreateGlobalInitOrCleanUpFunction(
891 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
892 SourceLocation Loc = SourceLocation(), bool TLS = false,
893 llvm::GlobalVariable::LinkageTypes Linkage =
894 llvm::GlobalVariable::InternalLinkage);
896 /// Return the AST address space of the underlying global variable for D, as
897 /// determined by its declaration. Normally this is the same as the address
898 /// space of D's type, but in CUDA, address spaces are associated with
899 /// declarations, not types. If D is nullptr, return the default address
900 /// space for global variable.
902 /// For languages without explicit address spaces, if D has default address
903 /// space, target-specific global or constant address space may be returned.
904 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
906 /// Return the AST address space of constant literal, which is used to emit
907 /// the constant literal as global variable in LLVM IR.
908 /// Note: This is not necessarily the address space of the constant literal
909 /// in AST. For address space agnostic language, e.g. C++, constant literal
910 /// in AST is always in default address space.
911 LangAS GetGlobalConstantAddressSpace() const;
913 /// Return the llvm::Constant for the address of the given global variable.
914 /// If Ty is non-null and if the global doesn't exist, then it will be created
915 /// with the specified type instead of whatever the normal requested type
916 /// would be. If IsForDefinition is true, it is guaranteed that an actual
917 /// global with type Ty will be returned, not conversion of a variable with
918 /// the same mangled name but some other type.
919 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
920 llvm::Type *Ty = nullptr,
921 ForDefinition_t IsForDefinition
922 = NotForDefinition);
924 /// Return the address of the given function. If Ty is non-null, then this
925 /// function will use the specified type if it has to create it.
926 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
927 bool ForVTable = false,
928 bool DontDefer = false,
929 ForDefinition_t IsForDefinition
930 = NotForDefinition);
932 // Return the function body address of the given function.
933 llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
935 // Return whether RTTI information should be emitted for this target.
936 bool shouldEmitRTTI(bool ForEH = false) {
937 return (ForEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
938 !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
939 getTriple().isNVPTX());
942 /// Get the address of the RTTI descriptor for the given type.
943 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
945 /// Get the address of a GUID.
946 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
948 /// Get the address of a UnnamedGlobalConstant
949 ConstantAddress
950 GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD);
952 /// Get the address of a template parameter object.
953 ConstantAddress
954 GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
956 /// Get the address of the thunk for the given global decl.
957 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
958 GlobalDecl GD);
960 /// Get a reference to the target of VD.
961 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
963 /// Returns the assumed alignment of an opaque pointer to the given class.
964 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
966 /// Returns the minimum object size for an object of the given class type
967 /// (or a class derived from it).
968 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
970 /// Returns the minimum object size for an object of the given type.
971 CharUnits getMinimumObjectSize(QualType Ty) {
972 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
973 return getMinimumClassObjectSize(RD);
974 return getContext().getTypeSizeInChars(Ty);
977 /// Returns the assumed alignment of a virtual base of a class.
978 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
979 const CXXRecordDecl *Derived,
980 const CXXRecordDecl *VBase);
982 /// Given a class pointer with an actual known alignment, and the
983 /// expected alignment of an object at a dynamic offset w.r.t that
984 /// pointer, return the alignment to assume at the offset.
985 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
986 const CXXRecordDecl *Class,
987 CharUnits ExpectedTargetAlign);
989 CharUnits
990 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
991 CastExpr::path_const_iterator Start,
992 CastExpr::path_const_iterator End);
994 /// Returns the offset from a derived class to a class. Returns null if the
995 /// offset is 0.
996 llvm::Constant *
997 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
998 CastExpr::path_const_iterator PathBegin,
999 CastExpr::path_const_iterator PathEnd);
1001 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
1003 /// Fetches the global unique block count.
1004 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
1006 /// Fetches the type of a generic block descriptor.
1007 llvm::Type *getBlockDescriptorType();
1009 /// The type of a generic block literal.
1010 llvm::Type *getGenericBlockLiteralType();
1012 /// Gets the address of a block which requires no captures.
1013 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
1015 /// Returns the address of a block which requires no caputres, or null if
1016 /// we've yet to emit the block for BE.
1017 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
1018 return EmittedGlobalBlocks.lookup(BE);
1021 /// Notes that BE's global block is available via Addr. Asserts that BE
1022 /// isn't already emitted.
1023 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
1025 /// Return a pointer to a constant CFString object for the given string.
1026 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
1028 /// Return a constant array for the given string.
1029 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
1031 /// Return a pointer to a constant array for the given string literal.
1032 ConstantAddress
1033 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
1034 StringRef Name = ".str");
1036 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1037 ConstantAddress
1038 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
1040 /// Returns a pointer to a character array containing the literal and a
1041 /// terminating '\0' character. The result has pointer to array type.
1043 /// \param GlobalName If provided, the name to use for the global (if one is
1044 /// created).
1045 ConstantAddress
1046 GetAddrOfConstantCString(const std::string &Str,
1047 const char *GlobalName = nullptr);
1049 /// Returns a pointer to a constant global variable for the given file-scope
1050 /// compound literal expression.
1051 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
1053 /// If it's been emitted already, returns the GlobalVariable corresponding to
1054 /// a compound literal. Otherwise, returns null.
1055 llvm::GlobalVariable *
1056 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
1058 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1059 /// emitted.
1060 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
1061 llvm::GlobalVariable *GV);
1063 /// Returns a pointer to a global variable representing a temporary
1064 /// with static or thread storage duration.
1065 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
1066 const Expr *Inner);
1068 /// Retrieve the record type that describes the state of an
1069 /// Objective-C fast enumeration loop (for..in).
1070 QualType getObjCFastEnumerationStateType();
1072 // Produce code for this constructor/destructor. This method doesn't try
1073 // to apply any ABI rules about which other constructors/destructors
1074 // are needed or if they are alias to each other.
1075 llvm::Function *codegenCXXStructor(GlobalDecl GD);
1077 /// Return the address of the constructor/destructor of the given type.
1078 llvm::Constant *
1079 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1080 llvm::FunctionType *FnType = nullptr,
1081 bool DontDefer = false,
1082 ForDefinition_t IsForDefinition = NotForDefinition) {
1083 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1084 DontDefer,
1085 IsForDefinition)
1086 .getCallee());
1089 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1090 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1091 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1092 ForDefinition_t IsForDefinition = NotForDefinition);
1094 /// Given a builtin id for a function like "__builtin_fabsf", return a
1095 /// Function* for "fabsf".
1096 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1097 unsigned BuiltinID);
1099 llvm::Function *getIntrinsic(unsigned IID,
1100 ArrayRef<llvm::Type *> Tys = std::nullopt);
1102 /// Emit code for a single top level declaration.
1103 void EmitTopLevelDecl(Decl *D);
1105 /// Stored a deferred empty coverage mapping for an unused
1106 /// and thus uninstrumented top level declaration.
1107 void AddDeferredUnusedCoverageMapping(Decl *D);
1109 /// Remove the deferred empty coverage mapping as this
1110 /// declaration is actually instrumented.
1111 void ClearUnusedCoverageMapping(const Decl *D);
1113 /// Emit all the deferred coverage mappings
1114 /// for the uninstrumented functions.
1115 void EmitDeferredUnusedCoverageMappings();
1117 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1118 void EmitMainVoidAlias();
1120 /// Tell the consumer that this variable has been instantiated.
1121 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1123 /// If the declaration has internal linkage but is inside an
1124 /// extern "C" linkage specification, prepare to emit an alias for it
1125 /// to the expected name.
1126 template<typename SomeDecl>
1127 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1129 /// Add a global to a list to be added to the llvm.used metadata.
1130 void addUsedGlobal(llvm::GlobalValue *GV);
1132 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1133 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1135 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1136 void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1138 /// Add a destructor and object to add to the C++ global destructor function.
1139 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1140 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1141 DtorFn.getCallee(), Object);
1144 /// Add an sterm finalizer to the C++ global cleanup function.
1145 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1146 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1147 DtorFn.getCallee(), nullptr);
1150 /// Add an sterm finalizer to its own llvm.global_dtors entry.
1151 void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1152 int Priority) {
1153 AddGlobalDtor(StermFinalizer, Priority);
1156 void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1157 int Priority) {
1158 OrderGlobalInitsOrStermFinalizers Key(Priority,
1159 PrioritizedCXXStermFinalizers.size());
1160 PrioritizedCXXStermFinalizers.push_back(
1161 std::make_pair(Key, StermFinalizer));
1164 /// Create or return a runtime function declaration with the specified type
1165 /// and name. If \p AssumeConvergent is true, the call will have the
1166 /// convergent attribute added.
1167 llvm::FunctionCallee
1168 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1169 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1170 bool Local = false, bool AssumeConvergent = false);
1172 /// Create a new runtime global variable with the specified type and name.
1173 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1174 StringRef Name);
1176 ///@name Custom Blocks Runtime Interfaces
1177 ///@{
1179 llvm::Constant *getNSConcreteGlobalBlock();
1180 llvm::Constant *getNSConcreteStackBlock();
1181 llvm::FunctionCallee getBlockObjectAssign();
1182 llvm::FunctionCallee getBlockObjectDispose();
1184 ///@}
1186 llvm::Function *getLLVMLifetimeStartFn();
1187 llvm::Function *getLLVMLifetimeEndFn();
1189 // Make sure that this type is translated.
1190 void UpdateCompletedType(const TagDecl *TD);
1192 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1194 /// Emit type info if type of an expression is a variably modified
1195 /// type. Also emit proper debug info for cast types.
1196 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1197 CodeGenFunction *CGF = nullptr);
1199 /// Return the result of value-initializing the given type, i.e. a null
1200 /// expression of the given type. This is usually, but not always, an LLVM
1201 /// null constant.
1202 llvm::Constant *EmitNullConstant(QualType T);
1204 /// Return a null constant appropriate for zero-initializing a base class with
1205 /// the given type. This is usually, but not always, an LLVM null constant.
1206 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1208 /// Emit a general error that something can't be done.
1209 void Error(SourceLocation loc, StringRef error);
1211 /// Print out an error that codegen doesn't support the specified stmt yet.
1212 void ErrorUnsupported(const Stmt *S, const char *Type);
1214 /// Print out an error that codegen doesn't support the specified decl yet.
1215 void ErrorUnsupported(const Decl *D, const char *Type);
1217 /// Set the attributes on the LLVM function for the given decl and function
1218 /// info. This applies attributes necessary for handling the ABI as well as
1219 /// user specified attributes like section.
1220 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1221 const CGFunctionInfo &FI);
1223 /// Set the LLVM function attributes (sext, zext, etc).
1224 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1225 llvm::Function *F, bool IsThunk);
1227 /// Set the LLVM function attributes which only apply to a function
1228 /// definition.
1229 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1231 /// Set the LLVM function attributes that represent floating point
1232 /// environment.
1233 void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1235 /// Return true iff the given type uses 'sret' when used as a return type.
1236 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1238 /// Return true iff the given type uses an argument slot when 'sret' is used
1239 /// as a return type.
1240 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1242 /// Return true iff the given type uses 'fpret' when used as a return type.
1243 bool ReturnTypeUsesFPRet(QualType ResultType);
1245 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1246 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1248 /// Get the LLVM attributes and calling convention to use for a particular
1249 /// function type.
1251 /// \param Name - The function name.
1252 /// \param Info - The function type information.
1253 /// \param CalleeInfo - The callee information these attributes are being
1254 /// constructed for. If valid, the attributes applied to this decl may
1255 /// contribute to the function attributes and calling convention.
1256 /// \param Attrs [out] - On return, the attribute list to use.
1257 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1258 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1259 CGCalleeInfo CalleeInfo,
1260 llvm::AttributeList &Attrs, unsigned &CallingConv,
1261 bool AttrOnCallSite, bool IsThunk);
1263 /// Adjust Memory attribute to ensure that the BE gets the right attribute
1264 // in order to generate the library call or the intrinsic for the function
1265 // name 'Name'.
1266 void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo,
1267 llvm::AttributeList &Attrs);
1269 /// Like the overload taking a `Function &`, but intended specifically
1270 /// for frontends that want to build on Clang's target-configuration logic.
1271 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1273 StringRef getMangledName(GlobalDecl GD);
1274 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1275 const GlobalDecl getMangledNameDecl(StringRef);
1277 void EmitTentativeDefinition(const VarDecl *D);
1279 void EmitExternalDeclaration(const VarDecl *D);
1281 void EmitVTable(CXXRecordDecl *Class);
1283 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1285 /// Appends Opts to the "llvm.linker.options" metadata value.
1286 void AppendLinkerOptions(StringRef Opts);
1288 /// Appends a detect mismatch command to the linker options.
1289 void AddDetectMismatch(StringRef Name, StringRef Value);
1291 /// Appends a dependent lib to the appropriate metadata value.
1292 void AddDependentLib(StringRef Lib);
1295 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1297 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1298 F->setLinkage(getFunctionLinkage(GD));
1301 /// Return the appropriate linkage for the vtable, VTT, and type information
1302 /// of the given class.
1303 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1305 /// Return the store size, in character units, of the given LLVM type.
1306 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1308 /// Returns LLVM linkage for a declarator.
1309 llvm::GlobalValue::LinkageTypes
1310 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage);
1312 /// Returns LLVM linkage for a declarator.
1313 llvm::GlobalValue::LinkageTypes
1314 getLLVMLinkageVarDefinition(const VarDecl *VD);
1316 /// Emit all the global annotations.
1317 void EmitGlobalAnnotations();
1319 /// Emit an annotation string.
1320 llvm::Constant *EmitAnnotationString(StringRef Str);
1322 /// Emit the annotation's translation unit.
1323 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1325 /// Emit the annotation line number.
1326 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1328 /// Emit additional args of the annotation.
1329 llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1331 /// Generate the llvm::ConstantStruct which contains the annotation
1332 /// information for a given GlobalValue. The annotation struct is
1333 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1334 /// GlobalValue being annotated. The second field is the constant string
1335 /// created from the AnnotateAttr's annotation. The third field is a constant
1336 /// string containing the name of the translation unit. The fourth field is
1337 /// the line number in the file of the annotated value declaration.
1338 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1339 const AnnotateAttr *AA,
1340 SourceLocation L);
1342 /// Add global annotations that are set on D, for the global GV. Those
1343 /// annotations are emitted during finalization of the LLVM code.
1344 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1346 bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1347 SourceLocation Loc) const;
1349 bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV,
1350 SourceLocation Loc, QualType Ty,
1351 StringRef Category = StringRef()) const;
1353 /// Imbue XRay attributes to a function, applying the always/never attribute
1354 /// lists in the process. Returns true if we did imbue attributes this way,
1355 /// false otherwise.
1356 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1357 StringRef Category = StringRef()) const;
1359 /// \returns true if \p Fn at \p Loc should be excluded from profile
1360 /// instrumentation by the SCL passed by \p -fprofile-list.
1361 ProfileList::ExclusionType
1362 isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const;
1364 /// \returns true if \p Fn at \p Loc should be excluded from profile
1365 /// instrumentation.
1366 ProfileList::ExclusionType
1367 isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
1368 SourceLocation Loc) const;
1370 SanitizerMetadata *getSanitizerMetadata() {
1371 return SanitizerMD.get();
1374 void addDeferredVTable(const CXXRecordDecl *RD) {
1375 DeferredVTables.push_back(RD);
1378 /// Emit code for a single global function or var decl. Forward declarations
1379 /// are emitted lazily.
1380 void EmitGlobal(GlobalDecl D);
1382 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1384 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1386 /// Set attributes which are common to any form of a global definition (alias,
1387 /// Objective-C method, function, global variable).
1389 /// NOTE: This should only be called for definitions.
1390 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1392 void addReplacement(StringRef Name, llvm::Constant *C);
1394 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1396 /// Emit a code for threadprivate directive.
1397 /// \param D Threadprivate declaration.
1398 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1400 /// Emit a code for declare reduction construct.
1401 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1402 CodeGenFunction *CGF = nullptr);
1404 /// Emit a code for declare mapper construct.
1405 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1406 CodeGenFunction *CGF = nullptr);
1408 /// Emit a code for requires directive.
1409 /// \param D Requires declaration
1410 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1412 /// Emit a code for the allocate directive.
1413 /// \param D The allocate declaration
1414 void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1416 /// Return the alignment specified in an allocate directive, if present.
1417 std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD);
1419 /// Returns whether the given record has hidden LTO visibility and therefore
1420 /// may participate in (single-module) CFI and whole-program vtable
1421 /// optimization.
1422 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1424 /// Returns whether the given record has public LTO visibility (regardless of
1425 /// -lto-whole-program-visibility) and therefore may not participate in
1426 /// (single-module) CFI and whole-program vtable optimization.
1427 bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD);
1429 /// Returns the vcall visibility of the given type. This is the scope in which
1430 /// a virtual function call could be made which ends up being dispatched to a
1431 /// member function of this class. This scope can be wider than the visibility
1432 /// of the class itself when the class has a more-visible dynamic base class.
1433 /// The client should pass in an empty Visited set, which is used to prevent
1434 /// redundant recursive processing.
1435 llvm::GlobalObject::VCallVisibility
1436 GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1437 llvm::DenseSet<const CXXRecordDecl *> &Visited);
1439 /// Emit type metadata for the given vtable using the given layout.
1440 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1441 llvm::GlobalVariable *VTable,
1442 const VTableLayout &VTLayout);
1444 llvm::Type *getVTableComponentType() const;
1446 /// Generate a cross-DSO type identifier for MD.
1447 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1449 /// Generate a KCFI type identifier for T.
1450 llvm::ConstantInt *CreateKCFITypeId(QualType T);
1452 /// Create a metadata identifier for the given type. This may either be an
1453 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1454 /// internal identifiers).
1455 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1457 /// Create a metadata identifier that is intended to be used to check virtual
1458 /// calls via a member function pointer.
1459 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1461 /// Create a metadata identifier for the generalization of the given type.
1462 /// This may either be an MDString (for external identifiers) or a distinct
1463 /// unnamed MDNode (for internal identifiers).
1464 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1466 /// Create and attach type metadata to the given function.
1467 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1468 llvm::Function *F);
1470 /// Set type metadata to the given function.
1471 void setKCFIType(const FunctionDecl *FD, llvm::Function *F);
1473 /// Emit KCFI type identifier constants and remove unused identifiers.
1474 void finalizeKCFITypes();
1476 /// Whether this function's return type has no side effects, and thus may
1477 /// be trivially discarded if it is unused.
1478 bool MayDropFunctionReturn(const ASTContext &Context,
1479 QualType ReturnType) const;
1481 /// Returns whether this module needs the "all-vtables" type identifier.
1482 bool NeedAllVtablesTypeId() const;
1484 /// Create and attach type metadata for the given vtable.
1485 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1486 const CXXRecordDecl *RD);
1488 /// Return a vector of most-base classes for RD. This is used to implement
1489 /// control flow integrity checks for member function pointers.
1491 /// A most-base class of a class C is defined as a recursive base class of C,
1492 /// including C itself, that does not have any bases.
1493 SmallVector<const CXXRecordDecl *, 0>
1494 getMostBaseClasses(const CXXRecordDecl *RD);
1496 /// Get the declaration of std::terminate for the platform.
1497 llvm::FunctionCallee getTerminateFn();
1499 llvm::SanitizerStatReport &getSanStats();
1501 llvm::Value *
1502 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1504 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1505 /// information in the program executable. The argument information stored
1506 /// includes the argument name, its type, the address and access qualifiers
1507 /// used. This helper can be used to generate metadata for source code kernel
1508 /// function as well as generated implicitly kernels. If a kernel is generated
1509 /// implicitly null value has to be passed to the last two parameters,
1510 /// otherwise all parameters must have valid non-null values.
1511 /// \param FN is a pointer to IR function being generated.
1512 /// \param FD is a pointer to function declaration if any.
1513 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1514 void GenKernelArgMetadata(llvm::Function *FN,
1515 const FunctionDecl *FD = nullptr,
1516 CodeGenFunction *CGF = nullptr);
1518 /// Get target specific null pointer.
1519 /// \param T is the LLVM type of the null pointer.
1520 /// \param QT is the clang QualType of the null pointer.
1521 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1523 CharUnits getNaturalTypeAlignment(QualType T,
1524 LValueBaseInfo *BaseInfo = nullptr,
1525 TBAAAccessInfo *TBAAInfo = nullptr,
1526 bool forPointeeType = false);
1527 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1528 LValueBaseInfo *BaseInfo = nullptr,
1529 TBAAAccessInfo *TBAAInfo = nullptr);
1530 bool stopAutoInit();
1532 /// Print the postfix for externalized static variable or kernels for single
1533 /// source offloading languages CUDA and HIP. The unique postfix is created
1534 /// using either the CUID argument, or the file's UniqueID and active macros.
1535 /// The fallback method without a CUID requires that the offloading toolchain
1536 /// does not define separate macros via the -cc1 options.
1537 void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
1538 const Decl *D) const;
1540 /// Move some lazily-emitted states to the NewBuilder. This is especially
1541 /// essential for the incremental parsing environment like Clang Interpreter,
1542 /// because we'll lose all important information after each repl.
1543 void moveLazyEmissionStates(CodeGenModule *NewBuilder);
1545 /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1546 /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it,
1547 /// if a valid one was found.
1548 void handleCUDALaunchBoundsAttr(llvm::Function *F,
1549 const CUDALaunchBoundsAttr *A,
1550 int32_t *MaxThreadsVal = nullptr,
1551 int32_t *MinBlocksVal = nullptr,
1552 int32_t *MaxClusterRankVal = nullptr);
1554 /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1555 /// to \p F. Alternatively, the work group size can be taken from a \p
1556 /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is
1557 /// stored in it, if a valid one was found. If \p MaxThreadsVal is not
1558 /// nullptr, the max threads value is stored in it, if a valid one was found.
1559 void handleAMDGPUFlatWorkGroupSizeAttr(
1560 llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A,
1561 const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr,
1562 int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr);
1564 /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1565 void handleAMDGPUWavesPerEUAttr(llvm::Function *F,
1566 const AMDGPUWavesPerEUAttr *A);
1568 llvm::Constant *
1569 GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1570 const VarDecl *D,
1571 ForDefinition_t IsForDefinition = NotForDefinition);
1573 private:
1574 llvm::Constant *GetOrCreateLLVMFunction(
1575 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1576 bool DontDefer = false, bool IsThunk = false,
1577 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1578 ForDefinition_t IsForDefinition = NotForDefinition);
1580 // References to multiversion functions are resolved through an implicitly
1581 // defined resolver function. This function is responsible for creating
1582 // the resolver symbol for the provided declaration. The value returned
1583 // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1584 // that feature and for a regular function (llvm::GlobalValue) otherwise.
1585 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD);
1587 // In scenarios where a function is not known to be a multiversion function
1588 // until a later declaration, it is sometimes necessary to change the
1589 // previously created mangled name to align with requirements of whatever
1590 // multiversion function kind the function is now known to be. This function
1591 // is responsible for performing such mangled name updates.
1592 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
1593 StringRef &CurName);
1595 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1596 llvm::AttrBuilder &AttrBuilder,
1597 bool SetTargetFeatures = true);
1598 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1600 /// Set function attributes for a function declaration.
1601 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1602 bool IsIncompleteFunction, bool IsThunk);
1604 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1606 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1607 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1609 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1610 void EmitExternalVarDeclaration(const VarDecl *D);
1611 void EmitAliasDefinition(GlobalDecl GD);
1612 void emitIFuncDefinition(GlobalDecl GD);
1613 void emitCPUDispatchDefinition(GlobalDecl GD);
1614 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1615 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1617 // C++ related functions.
1619 void EmitDeclContext(const DeclContext *DC);
1620 void EmitLinkageSpec(const LinkageSpecDecl *D);
1621 void EmitTopLevelStmt(const TopLevelStmtDecl *D);
1623 /// Emit the function that initializes C++ thread_local variables.
1624 void EmitCXXThreadLocalInitFunc();
1626 /// Emit the function that initializes global variables for a C++ Module.
1627 void EmitCXXModuleInitFunc(clang::Module *Primary);
1629 /// Emit the function that initializes C++ globals.
1630 void EmitCXXGlobalInitFunc();
1632 /// Emit the function that performs cleanup associated with C++ globals.
1633 void EmitCXXGlobalCleanUpFunc();
1635 /// Emit the function that initializes the specified global (if PerformInit is
1636 /// true) and registers its destructor.
1637 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1638 llvm::GlobalVariable *Addr,
1639 bool PerformInit);
1641 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1642 llvm::Function *InitFunc, InitSegAttr *ISA);
1644 // FIXME: Hardcoding priority here is gross.
1645 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1646 unsigned LexOrder = ~0U,
1647 llvm::Constant *AssociatedData = nullptr);
1648 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1649 bool IsDtorAttrFunc = false);
1651 /// EmitCtorList - Generates a global array of functions and priorities using
1652 /// the given list and name. This array will have appending linkage and is
1653 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1654 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1656 /// Emit any needed decls for which code generation was deferred.
1657 void EmitDeferred();
1659 /// Try to emit external vtables as available_externally if they have emitted
1660 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1661 /// is not allowed to create new references to things that need to be emitted
1662 /// lazily.
1663 void EmitVTablesOpportunistically();
1665 /// Call replaceAllUsesWith on all pairs in Replacements.
1666 void applyReplacements();
1668 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1669 void applyGlobalValReplacements();
1671 void checkAliases();
1673 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1675 /// Register functions annotated with __attribute__((destructor)) using
1676 /// __cxa_atexit, if it is available, or atexit otherwise.
1677 void registerGlobalDtorsWithAtExit();
1679 // When using sinit and sterm functions, unregister
1680 // __attribute__((destructor)) annotated functions which were previously
1681 // registered by the atexit subroutine using unatexit.
1682 void unregisterGlobalDtorsWithUnAtExit();
1684 /// Emit deferred multiversion function resolvers and associated variants.
1685 void emitMultiVersionFunctions();
1687 /// Emit any vtables which we deferred and still have a use for.
1688 void EmitDeferredVTables();
1690 /// Emit a dummy function that reference a CoreFoundation symbol when
1691 /// @available is used on Darwin.
1692 void emitAtAvailableLinkGuard();
1694 /// Emit the llvm.used and llvm.compiler.used metadata.
1695 void emitLLVMUsed();
1697 /// For C++20 Itanium ABI, emit the initializers for the module.
1698 void EmitModuleInitializers(clang::Module *Primary);
1700 /// Emit the link options introduced by imported modules.
1701 void EmitModuleLinkOptions();
1703 /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
1704 /// have a resolver name that matches 'Elem' to instead resolve to the name of
1705 /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
1706 /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
1707 /// may not reference aliases. Redirection is only performed if 'Elem' is only
1708 /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
1709 /// redirection is successful, and 'false' is returned otherwise.
1710 bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
1711 llvm::GlobalValue *CppFunc);
1713 /// Emit aliases for internal-linkage declarations inside "C" language
1714 /// linkage specifications, giving them the "expected" name where possible.
1715 void EmitStaticExternCAliases();
1717 void EmitDeclMetadata();
1719 /// Emit the Clang version as llvm.ident metadata.
1720 void EmitVersionIdentMetadata();
1722 /// Emit the Clang commandline as llvm.commandline metadata.
1723 void EmitCommandLineMetadata();
1725 /// Emit the module flag metadata used to pass options controlling the
1726 /// the backend to LLVM.
1727 void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts);
1729 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1730 void EmitOpenCLMetadata();
1732 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1733 /// .gcda files in a way that persists in .bc files.
1734 void EmitCoverageFile();
1736 /// Determine whether the definition must be emitted; if this returns \c
1737 /// false, the definition can be emitted lazily if it's used.
1738 bool MustBeEmitted(const ValueDecl *D);
1740 /// Determine whether the definition can be emitted eagerly, or should be
1741 /// delayed until the end of the translation unit. This is relevant for
1742 /// definitions whose linkage can change, e.g. implicit function instantions
1743 /// which may later be explicitly instantiated.
1744 bool MayBeEmittedEagerly(const ValueDecl *D);
1746 /// Check whether we can use a "simpler", more core exceptions personality
1747 /// function.
1748 void SimplifyPersonality();
1750 /// Helper function for getDefaultFunctionAttributes. Builds a set of function
1751 /// attributes which can be simply added to a function.
1752 void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1753 bool AttrOnCallSite,
1754 llvm::AttrBuilder &FuncAttrs);
1756 /// Helper function for ConstructAttributeList and
1757 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1758 /// attributes to add to a function with the given properties.
1759 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1760 bool AttrOnCallSite,
1761 llvm::AttrBuilder &FuncAttrs);
1763 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1764 StringRef Suffix);
1767 } // end namespace CodeGen
1768 } // end namespace clang
1770 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H