xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.h (revision c978f0f7ac33a5085053da7189201babd366c82d)
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.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15 
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/NoSanitizeList.h"
28 #include "clang/Basic/ProfileList.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Basic/XRayLists.h"
31 #include "clang/Lex/PreprocessorOptions.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/MapVector.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/StringMap.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Transforms/Utils/SanitizerStats.h"
40 #include <optional>
41 
42 namespace llvm {
43 class Module;
44 class Constant;
45 class ConstantInt;
46 class Function;
47 class GlobalValue;
48 class DataLayout;
49 class FunctionType;
50 class LLVMContext;
51 class IndexedInstrProfReader;
52 
53 namespace vfs {
54 class FileSystem;
55 }
56 }
57 
58 namespace clang {
59 class ASTContext;
60 class AtomicType;
61 class FunctionDecl;
62 class IdentifierInfo;
63 class ObjCImplementationDecl;
64 class ObjCEncodeExpr;
65 class BlockExpr;
66 class CharUnits;
67 class Decl;
68 class Expr;
69 class Stmt;
70 class StringLiteral;
71 class NamedDecl;
72 class PointerAuthSchema;
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;
84 
85 namespace CodeGen {
86 
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;
98 
99 enum ForDefinition_t : bool {
100   NotForDefinition = false,
101   ForDefinition = true
102 };
103 
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) {}
109 
110   bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
111     return priority == RHS.priority && lex_order == RHS.lex_order;
112   }
113 
114   bool operator<(const OrderGlobalInitsOrStermFinalizers &RHS) const {
115     return std::tie(priority, lex_order) <
116            std::tie(RHS.priority, RHS.lex_order);
117   }
118 };
119 
120 struct ObjCEntrypoints {
121   ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
122 
123   /// void objc_alloc(id);
124   llvm::FunctionCallee objc_alloc;
125 
126   /// void objc_allocWithZone(id);
127   llvm::FunctionCallee objc_allocWithZone;
128 
129   /// void objc_alloc_init(id);
130   llvm::FunctionCallee objc_alloc_init;
131 
132   /// void objc_autoreleasePoolPop(void*);
133   llvm::FunctionCallee objc_autoreleasePoolPop;
134 
135   /// void objc_autoreleasePoolPop(void*);
136   /// Note this method is used when we are using exception handling
137   llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
138 
139   /// void *objc_autoreleasePoolPush(void);
140   llvm::Function *objc_autoreleasePoolPush;
141 
142   /// id objc_autorelease(id);
143   llvm::Function *objc_autorelease;
144 
145   /// id objc_autorelease(id);
146   /// Note this is the runtime method not the intrinsic.
147   llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
148 
149   /// id objc_autoreleaseReturnValue(id);
150   llvm::Function *objc_autoreleaseReturnValue;
151 
152   /// void objc_copyWeak(id *dest, id *src);
153   llvm::Function *objc_copyWeak;
154 
155   /// void objc_destroyWeak(id*);
156   llvm::Function *objc_destroyWeak;
157 
158   /// id objc_initWeak(id*, id);
159   llvm::Function *objc_initWeak;
160 
161   /// id objc_loadWeak(id*);
162   llvm::Function *objc_loadWeak;
163 
164   /// id objc_loadWeakRetained(id*);
165   llvm::Function *objc_loadWeakRetained;
166 
167   /// void objc_moveWeak(id *dest, id *src);
168   llvm::Function *objc_moveWeak;
169 
170   /// id objc_retain(id);
171   llvm::Function *objc_retain;
172 
173   /// id objc_retain(id);
174   /// Note this is the runtime method not the intrinsic.
175   llvm::FunctionCallee objc_retainRuntimeFunction;
176 
177   /// id objc_retainAutorelease(id);
178   llvm::Function *objc_retainAutorelease;
179 
180   /// id objc_retainAutoreleaseReturnValue(id);
181   llvm::Function *objc_retainAutoreleaseReturnValue;
182 
183   /// id objc_retainAutoreleasedReturnValue(id);
184   llvm::Function *objc_retainAutoreleasedReturnValue;
185 
186   /// id objc_retainBlock(id);
187   llvm::Function *objc_retainBlock;
188 
189   /// void objc_release(id);
190   llvm::Function *objc_release;
191 
192   /// void objc_release(id);
193   /// Note this is the runtime method not the intrinsic.
194   llvm::FunctionCallee objc_releaseRuntimeFunction;
195 
196   /// void objc_storeStrong(id*, id);
197   llvm::Function *objc_storeStrong;
198 
199   /// id objc_storeWeak(id*, id);
200   llvm::Function *objc_storeWeak;
201 
202   /// id objc_unsafeClaimAutoreleasedReturnValue(id);
203   llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
204 
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;
208 
209   /// void clang.arc.use(...);
210   llvm::Function *clang_arc_use;
211 
212   /// void clang.arc.noop.use(...);
213   llvm::Function *clang_arc_noop_use;
214 };
215 
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;
223 
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;
232   }
233   /// Record that a function we've visited has no profile data.
234   void addMissing(bool MainFile) {
235     if (MainFile)
236       ++MissingInMainFile;
237     ++Missing;
238   }
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);
245 };
246 
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;
254 
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;
259 
260   BlockByrefHelpers(CharUnits alignment)
261       : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
262   BlockByrefHelpers(const BlockByrefHelpers &) = default;
263   virtual ~BlockByrefHelpers();
264 
265   void Profile(llvm::FoldingSetNodeID &id) const {
266     id.AddInteger(Alignment.getQuantity());
267     profileImpl(id);
268   }
269   virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
270 
271   virtual bool needsCopy() const { return true; }
272   virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
273 
274   virtual bool needsDispose() const { return true; }
275   virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
276 };
277 
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;
283 
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;
297   };
298 
299   typedef std::vector<Structor> CtorList;
300 
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;
317 
318   mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
319 
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   std::unique_ptr<CodeGenTypes> Types;
324 
325   /// Holds information about C++ vtables.
326   CodeGenVTables VTables;
327 
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;
339   bool WarnedStackExhausted = false;
340 
341   // A set of references that have only been seen via a weakref so far. This is
342   // used to remove the weak of the reference if we ever see a direct reference
343   // or a definition.
344   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
345 
346   /// This contains all the decls which have definitions but/ which are deferred
347   /// for emission and therefore should only be output if they are actually
348   /// used. If a decl is in this, then it is known to have not been referenced
349   /// yet.
350   llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
351 
352   llvm::StringSet<llvm::BumpPtrAllocator> DeferredResolversToEmit;
353 
354   /// This is a list of deferred decls which we have seen that *are* actually
355   /// referenced. These get code generated when the module is done.
356   std::vector<GlobalDecl> DeferredDeclsToEmit;
357   void addDeferredDeclToEmit(GlobalDecl GD) {
358     DeferredDeclsToEmit.emplace_back(GD);
359     addEmittedDeferredDecl(GD);
360   }
361 
362   /// Decls that were DeferredDecls and have now been emitted.
363   llvm::DenseMap<llvm::StringRef, GlobalDecl> EmittedDeferredDecls;
364 
365   void addEmittedDeferredDecl(GlobalDecl GD) {
366     // Reemission is only needed in incremental mode.
367     if (!Context.getLangOpts().IncrementalExtensions)
368       return;
369 
370     // Assume a linkage by default that does not need reemission.
371     auto L = llvm::GlobalValue::ExternalLinkage;
372     if (llvm::isa<FunctionDecl>(GD.getDecl()))
373       L = getFunctionLinkage(GD);
374     else if (auto *VD = llvm::dyn_cast<VarDecl>(GD.getDecl()))
375       L = getLLVMLinkageVarDefinition(VD);
376 
377     if (llvm::GlobalValue::isInternalLinkage(L) ||
378         llvm::GlobalValue::isLinkOnceLinkage(L) ||
379         llvm::GlobalValue::isWeakLinkage(L)) {
380       EmittedDeferredDecls[getMangledName(GD)] = GD;
381     }
382   }
383 
384   /// List of alias we have emitted. Used to make sure that what they point to
385   /// is defined once we get to the end of the of the translation unit.
386   std::vector<GlobalDecl> Aliases;
387 
388   /// List of multiversion functions to be emitted. This list is processed in
389   /// conjunction with other deferred symbols and is used to ensure that
390   /// multiversion function resolvers and ifuncs are defined and emitted.
391   std::vector<GlobalDecl> MultiVersionFuncs;
392 
393   llvm::MapVector<StringRef, llvm::TrackingVH<llvm::Constant>> Replacements;
394 
395   /// List of global values to be replaced with something else. Used when we
396   /// want to replace a GlobalValue but can't identify it by its mangled name
397   /// anymore (because the name is already taken).
398   llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
399     GlobalValReplacements;
400 
401   /// Variables for which we've emitted globals containing their constant
402   /// values along with the corresponding globals, for opportunistic reuse.
403   llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
404 
405   /// Set of global decls for which we already diagnosed mangled name conflict.
406   /// Required to not issue a warning (on a mangling conflict) multiple times
407   /// for the same decl.
408   llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
409 
410   /// A queue of (optional) vtables to consider emitting.
411   std::vector<const CXXRecordDecl*> DeferredVTables;
412 
413   /// A queue of (optional) vtables that may be emitted opportunistically.
414   std::vector<const CXXRecordDecl *> OpportunisticVTables;
415 
416   /// List of global values which are required to be present in the object file;
417   /// bitcast to i8*. This is used for forcing visibility of symbols which may
418   /// otherwise be optimized out.
419   std::vector<llvm::WeakTrackingVH> LLVMUsed;
420   std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
421 
422   /// Store the list of global constructors and their respective priorities to
423   /// be emitted when the translation unit is complete.
424   CtorList GlobalCtors;
425 
426   /// Store the list of global destructors and their respective priorities to be
427   /// emitted when the translation unit is complete.
428   CtorList GlobalDtors;
429 
430   /// An ordered map of canonical GlobalDecls to their mangled names.
431   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
432   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
433 
434   /// Global annotations.
435   std::vector<llvm::Constant*> Annotations;
436 
437   // Store deferred function annotations so they can be emitted at the end with
438   // most up to date ValueDecl that will have all the inherited annotations.
439   llvm::MapVector<StringRef, const ValueDecl *> DeferredAnnotations;
440 
441   /// Map used to get unique annotation strings.
442   llvm::StringMap<llvm::Constant*> AnnotationStrings;
443 
444   /// Used for uniquing of annotation arguments.
445   llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
446 
447   llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
448 
449   llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
450   llvm::DenseMap<const UnnamedGlobalConstantDecl *, llvm::GlobalVariable *>
451       UnnamedGlobalConstantDeclMap;
452   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
453   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
454   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
455 
456   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
457   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
458 
459   /// Map used to get unique type descriptor constants for sanitizers.
460   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
461 
462   /// Map used to track internal linkage functions declared within
463   /// extern "C" regions.
464   typedef llvm::MapVector<IdentifierInfo *,
465                           llvm::GlobalValue *> StaticExternCMap;
466   StaticExternCMap StaticExternCValues;
467 
468   /// thread_local variables defined or used in this TU.
469   std::vector<const VarDecl *> CXXThreadLocals;
470 
471   /// thread_local variables with initializers that need to run
472   /// before any thread_local variable in this TU is odr-used.
473   std::vector<llvm::Function *> CXXThreadLocalInits;
474   std::vector<const VarDecl *> CXXThreadLocalInitVars;
475 
476   /// Global variables with initializers that need to run before main.
477   std::vector<llvm::Function *> CXXGlobalInits;
478 
479   /// When a C++ decl with an initializer is deferred, null is
480   /// appended to CXXGlobalInits, and the index of that null is placed
481   /// here so that the initializer will be performed in the correct
482   /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
483   /// that we don't re-emit the initializer.
484   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
485 
486   typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
487       GlobalInitData;
488 
489   // When a tail call is performed on an "undefined" symbol, on PPC without pc
490   // relative feature, the tail call is not allowed. In "EmitCall" for such
491   // tail calls, the "undefined" symbols may be forward declarations, their
492   // definitions are provided in the module after the callsites. For such tail
493   // calls, diagnose message should not be emitted.
494   llvm::SmallSetVector<std::pair<const FunctionDecl *, SourceLocation>, 4>
495       MustTailCallUndefinedGlobals;
496 
497   struct GlobalInitPriorityCmp {
498     bool operator()(const GlobalInitData &LHS,
499                     const GlobalInitData &RHS) const {
500       return LHS.first.priority < RHS.first.priority;
501     }
502   };
503 
504   /// Global variables with initializers whose order of initialization is set by
505   /// init_priority attribute.
506   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
507 
508   /// Global destructor functions and arguments that need to run on termination.
509   /// When UseSinitAndSterm is set, it instead contains sterm finalizer
510   /// functions, which also run on unloading a shared library.
511   typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
512                      llvm::Constant *>
513       CXXGlobalDtorsOrStermFinalizer_t;
514   SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
515       CXXGlobalDtorsOrStermFinalizers;
516 
517   typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
518       StermFinalizerData;
519 
520   struct StermFinalizerPriorityCmp {
521     bool operator()(const StermFinalizerData &LHS,
522                     const StermFinalizerData &RHS) const {
523       return LHS.first.priority < RHS.first.priority;
524     }
525   };
526 
527   /// Global variables with sterm finalizers whose order of initialization is
528   /// set by init_priority attribute.
529   SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
530 
531   /// The complete set of modules that has been imported.
532   llvm::SetVector<clang::Module *> ImportedModules;
533 
534   /// The set of modules for which the module initializers
535   /// have been emitted.
536   llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
537 
538   /// A vector of metadata strings for linker options.
539   SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
540 
541   /// A vector of metadata strings for dependent libraries for ELF.
542   SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
543 
544   /// @name Cache for Objective-C runtime types
545   /// @{
546 
547   /// Cached reference to the class for constant strings. This value has type
548   /// int * but is actually an Obj-C class pointer.
549   llvm::WeakTrackingVH CFConstantStringClassRef;
550 
551   /// The type used to describe the state of a fast enumeration in
552   /// Objective-C's for..in loop.
553   QualType ObjCFastEnumerationStateType;
554 
555   /// @}
556 
557   /// Lazily create the Objective-C runtime
558   void createObjCRuntime();
559 
560   void createOpenCLRuntime();
561   void createOpenMPRuntime();
562   void createCUDARuntime();
563   void createHLSLRuntime();
564 
565   bool isTriviallyRecursive(const FunctionDecl *F);
566   bool shouldEmitFunction(GlobalDecl GD);
567   // Whether a global variable should be emitted by CUDA/HIP host/device
568   // related attributes.
569   bool shouldEmitCUDAGlobalVar(const VarDecl *VD) const;
570   bool shouldOpportunisticallyEmitVTables();
571   /// Map used to be sure we don't emit the same CompoundLiteral twice.
572   llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
573       EmittedCompoundLiterals;
574 
575   /// Map of the global blocks we've emitted, so that we don't have to re-emit
576   /// them if the constexpr evaluator gets aggressive.
577   llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
578 
579   /// @name Cache for Blocks Runtime Globals
580   /// @{
581 
582   llvm::Constant *NSConcreteGlobalBlock = nullptr;
583   llvm::Constant *NSConcreteStackBlock = nullptr;
584 
585   llvm::FunctionCallee BlockObjectAssign = nullptr;
586   llvm::FunctionCallee BlockObjectDispose = nullptr;
587 
588   llvm::Type *BlockDescriptorType = nullptr;
589   llvm::Type *GenericBlockLiteralType = nullptr;
590 
591   struct {
592     int GlobalUniqueCount;
593   } Block;
594 
595   GlobalDecl initializedGlobalDecl;
596 
597   /// @}
598 
599   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
600   llvm::Function *LifetimeStartFn = nullptr;
601 
602   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
603   llvm::Function *LifetimeEndFn = nullptr;
604 
605   std::unique_ptr<SanitizerMetadata> SanitizerMD;
606 
607   llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
608 
609   std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
610 
611   /// Mapping from canonical types to their metadata identifiers. We need to
612   /// maintain this mapping because identifiers may be formed from distinct
613   /// MDNodes.
614   typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
615   MetadataTypeMap MetadataIdMap;
616   MetadataTypeMap VirtualMetadataIdMap;
617   MetadataTypeMap GeneralizedMetadataIdMap;
618 
619   // Helps squashing blocks of TopLevelStmtDecl into a single llvm::Function
620   // when used with -fincremental-extensions.
621   std::pair<std::unique_ptr<CodeGenFunction>, const TopLevelStmtDecl *>
622       GlobalTopLevelStmtBlockInFlight;
623 
624   llvm::DenseMap<GlobalDecl, uint16_t> PtrAuthDiscriminatorHashes;
625 
626   llvm::DenseMap<const CXXRecordDecl *, std::optional<PointerAuthQualifier>>
627       VTablePtrAuthInfos;
628   std::optional<PointerAuthQualifier>
629   computeVTPointerAuthentication(const CXXRecordDecl *ThisClass);
630 
631 public:
632   CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
633                 const HeaderSearchOptions &headersearchopts,
634                 const PreprocessorOptions &ppopts,
635                 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
636                 DiagnosticsEngine &Diags,
637                 CoverageSourceInfo *CoverageInfo = nullptr);
638 
639   ~CodeGenModule();
640 
641   void clear();
642 
643   /// Finalize LLVM code generation.
644   void Release();
645 
646   /// Return true if we should emit location information for expressions.
647   bool getExpressionLocationsEnabled() const;
648 
649   /// Return a reference to the configured Objective-C runtime.
650   CGObjCRuntime &getObjCRuntime() {
651     if (!ObjCRuntime) createObjCRuntime();
652     return *ObjCRuntime;
653   }
654 
655   /// Return true iff an Objective-C runtime has been configured.
656   bool hasObjCRuntime() { return !!ObjCRuntime; }
657 
658   const std::string &getModuleNameHash() const { return ModuleNameHash; }
659 
660   /// Return a reference to the configured OpenCL runtime.
661   CGOpenCLRuntime &getOpenCLRuntime() {
662     assert(OpenCLRuntime != nullptr);
663     return *OpenCLRuntime;
664   }
665 
666   /// Return a reference to the configured OpenMP runtime.
667   CGOpenMPRuntime &getOpenMPRuntime() {
668     assert(OpenMPRuntime != nullptr);
669     return *OpenMPRuntime;
670   }
671 
672   /// Return a reference to the configured CUDA runtime.
673   CGCUDARuntime &getCUDARuntime() {
674     assert(CUDARuntime != nullptr);
675     return *CUDARuntime;
676   }
677 
678   /// Return a reference to the configured HLSL runtime.
679   CGHLSLRuntime &getHLSLRuntime() {
680     assert(HLSLRuntime != nullptr);
681     return *HLSLRuntime;
682   }
683 
684   ObjCEntrypoints &getObjCEntrypoints() const {
685     assert(ObjCData != nullptr);
686     return *ObjCData;
687   }
688 
689   // Version checking functions, used to implement ObjC's @available:
690   // i32 @__isOSVersionAtLeast(i32, i32, i32)
691   llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
692   // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
693   llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
694 
695   InstrProfStats &getPGOStats() { return PGOStats; }
696   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
697 
698   CoverageMappingModuleGen *getCoverageMapping() const {
699     return CoverageMapping.get();
700   }
701 
702   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
703     return StaticLocalDeclMap[D];
704   }
705   void setStaticLocalDeclAddress(const VarDecl *D,
706                                  llvm::Constant *C) {
707     StaticLocalDeclMap[D] = C;
708   }
709 
710   llvm::Constant *
711   getOrCreateStaticVarDecl(const VarDecl &D,
712                            llvm::GlobalValue::LinkageTypes Linkage);
713 
714   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
715     return StaticLocalDeclGuardMap[D];
716   }
717   void setStaticLocalDeclGuardAddress(const VarDecl *D,
718                                       llvm::GlobalVariable *C) {
719     StaticLocalDeclGuardMap[D] = C;
720   }
721 
722   Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
723                                   CharUnits Align);
724 
725   bool lookupRepresentativeDecl(StringRef MangledName,
726                                 GlobalDecl &Result) const;
727 
728   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
729     return AtomicSetterHelperFnMap[Ty];
730   }
731   void setAtomicSetterHelperFnMap(QualType Ty,
732                             llvm::Constant *Fn) {
733     AtomicSetterHelperFnMap[Ty] = Fn;
734   }
735 
736   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
737     return AtomicGetterHelperFnMap[Ty];
738   }
739   void setAtomicGetterHelperFnMap(QualType Ty,
740                             llvm::Constant *Fn) {
741     AtomicGetterHelperFnMap[Ty] = Fn;
742   }
743 
744   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
745     return TypeDescriptorMap[Ty];
746   }
747   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
748     TypeDescriptorMap[Ty] = C;
749   }
750 
751   CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
752 
753   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
754     if (!NoObjCARCExceptionsMetadata)
755       NoObjCARCExceptionsMetadata =
756           llvm::MDNode::get(getLLVMContext(), std::nullopt);
757     return NoObjCARCExceptionsMetadata;
758   }
759 
760   ASTContext &getContext() const { return Context; }
761   const LangOptions &getLangOpts() const { return LangOpts; }
762   const IntrusiveRefCntPtr<llvm::vfs::FileSystem> &getFileSystem() const {
763     return FS;
764   }
765   const HeaderSearchOptions &getHeaderSearchOpts()
766     const { return HeaderSearchOpts; }
767   const PreprocessorOptions &getPreprocessorOpts()
768     const { return PreprocessorOpts; }
769   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
770   llvm::Module &getModule() const { return TheModule; }
771   DiagnosticsEngine &getDiags() const { return Diags; }
772   const llvm::DataLayout &getDataLayout() const {
773     return TheModule.getDataLayout();
774   }
775   const TargetInfo &getTarget() const { return Target; }
776   const llvm::Triple &getTriple() const { return Target.getTriple(); }
777   bool supportsCOMDAT() const;
778   void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
779 
780   const ABIInfo &getABIInfo();
781   CGCXXABI &getCXXABI() const { return *ABI; }
782   llvm::LLVMContext &getLLVMContext() { return VMContext; }
783 
784   bool shouldUseTBAA() const { return TBAA != nullptr; }
785 
786   const TargetCodeGenInfo &getTargetCodeGenInfo();
787 
788   CodeGenTypes &getTypes() { return *Types; }
789 
790   CodeGenVTables &getVTables() { return VTables; }
791 
792   ItaniumVTableContext &getItaniumVTableContext() {
793     return VTables.getItaniumVTableContext();
794   }
795 
796   const ItaniumVTableContext &getItaniumVTableContext() const {
797     return VTables.getItaniumVTableContext();
798   }
799 
800   MicrosoftVTableContext &getMicrosoftVTableContext() {
801     return VTables.getMicrosoftVTableContext();
802   }
803 
804   CtorList &getGlobalCtors() { return GlobalCtors; }
805   CtorList &getGlobalDtors() { return GlobalDtors; }
806 
807   /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
808   /// the given type.
809   llvm::MDNode *getTBAATypeInfo(QualType QTy);
810 
811   /// getTBAAAccessInfo - Get TBAA information that describes an access to
812   /// an object of the given type.
813   TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
814 
815   /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
816   /// access to a virtual table pointer.
817   TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
818 
819   llvm::MDNode *getTBAAStructInfo(QualType QTy);
820 
821   /// getTBAABaseTypeInfo - Get metadata that describes the given base access
822   /// type. Return null if the type is not suitable for use in TBAA access tags.
823   llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
824 
825   /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
826   llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
827 
828   /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
829   /// type casts.
830   TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
831                                       TBAAAccessInfo TargetInfo);
832 
833   /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
834   /// purposes of conditional operator.
835   TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
836                                                      TBAAAccessInfo InfoB);
837 
838   /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
839   /// purposes of memory transfer calls.
840   TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
841                                                 TBAAAccessInfo SrcInfo);
842 
843   /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
844   /// base lvalue.
845   TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
846     if (Base.getTBAAInfo().isMayAlias())
847       return TBAAAccessInfo::getMayAliasInfo();
848     return getTBAAAccessInfo(AccessType);
849   }
850 
851   bool isPaddedAtomicType(QualType type);
852   bool isPaddedAtomicType(const AtomicType *type);
853 
854   /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
855   void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
856                                    TBAAAccessInfo TBAAInfo);
857 
858   /// Adds !invariant.barrier !tag to instruction
859   void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
860                                              const CXXRecordDecl *RD);
861 
862   /// Emit the given number of characters as a value of type size_t.
863   llvm::ConstantInt *getSize(CharUnits numChars);
864 
865   /// Set the visibility for the given LLVM GlobalValue.
866   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
867 
868   void setDSOLocal(llvm::GlobalValue *GV) const;
869 
870   bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const {
871     return getLangOpts().hasDefaultVisibilityExportMapping() && D &&
872            (D->getLinkageAndVisibility().getVisibility() ==
873             DefaultVisibility) &&
874            (getLangOpts().isAllDefaultVisibilityExportMapping() ||
875             (getLangOpts().isExplicitDefaultVisibilityExportMapping() &&
876              D->getLinkageAndVisibility().isVisibilityExplicit()));
877   }
878   void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
879   void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
880   /// Set visibility, dllimport/dllexport and dso_local.
881   /// This must be called after dllimport/dllexport is set.
882   void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
883   void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
884 
885   void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
886 
887   /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
888   /// variable declaration D.
889   void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
890 
891   /// Get LLVM TLS mode from CodeGenOptions.
892   llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
893 
894   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
895     switch (V) {
896     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
897     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
898     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
899     }
900     llvm_unreachable("unknown visibility!");
901   }
902 
903   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
904                                   ForDefinition_t IsForDefinition
905                                     = NotForDefinition);
906 
907   /// Will return a global variable of the given type. If a variable with a
908   /// different type already exists then a new  variable with the right type
909   /// will be created and all uses of the old variable will be replaced with a
910   /// bitcast to the new variable.
911   llvm::GlobalVariable *
912   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
913                                     llvm::GlobalValue::LinkageTypes Linkage,
914                                     llvm::Align Alignment);
915 
916   llvm::Function *CreateGlobalInitOrCleanUpFunction(
917       llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
918       SourceLocation Loc = SourceLocation(), bool TLS = false,
919       llvm::GlobalVariable::LinkageTypes Linkage =
920           llvm::GlobalVariable::InternalLinkage);
921 
922   /// Return the AST address space of the underlying global variable for D, as
923   /// determined by its declaration. Normally this is the same as the address
924   /// space of D's type, but in CUDA, address spaces are associated with
925   /// declarations, not types. If D is nullptr, return the default address
926   /// space for global variable.
927   ///
928   /// For languages without explicit address spaces, if D has default address
929   /// space, target-specific global or constant address space may be returned.
930   LangAS GetGlobalVarAddressSpace(const VarDecl *D);
931 
932   /// Return the AST address space of constant literal, which is used to emit
933   /// the constant literal as global variable in LLVM IR.
934   /// Note: This is not necessarily the address space of the constant literal
935   /// in AST. For address space agnostic language, e.g. C++, constant literal
936   /// in AST is always in default address space.
937   LangAS GetGlobalConstantAddressSpace() const;
938 
939   /// Return the llvm::Constant for the address of the given global variable.
940   /// If Ty is non-null and if the global doesn't exist, then it will be created
941   /// with the specified type instead of whatever the normal requested type
942   /// would be. If IsForDefinition is true, it is guaranteed that an actual
943   /// global with type Ty will be returned, not conversion of a variable with
944   /// the same mangled name but some other type.
945   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
946                                      llvm::Type *Ty = nullptr,
947                                      ForDefinition_t IsForDefinition
948                                        = NotForDefinition);
949 
950   /// Return the address of the given function. If Ty is non-null, then this
951   /// function will use the specified type if it has to create it.
952   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
953                                     bool ForVTable = false,
954                                     bool DontDefer = false,
955                                     ForDefinition_t IsForDefinition
956                                       = NotForDefinition);
957 
958   // Return the function body address of the given function.
959   llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
960 
961   /// Return a function pointer for a reference to the given function.
962   /// This correctly handles weak references, but does not apply a
963   /// pointer signature.
964   llvm::Constant *getRawFunctionPointer(GlobalDecl GD,
965                                         llvm::Type *Ty = nullptr);
966 
967   /// Return the ABI-correct function pointer value for a reference
968   /// to the given function.  This will apply a pointer signature if
969   /// necessary, caching the result for the given function.
970   llvm::Constant *getFunctionPointer(GlobalDecl GD, llvm::Type *Ty = nullptr);
971 
972   /// Return the ABI-correct function pointer value for a reference
973   /// to the given function.  This will apply a pointer signature if
974   /// necessary.
975   llvm::Constant *getFunctionPointer(llvm::Constant *Pointer,
976                                      QualType FunctionType);
977 
978   llvm::Constant *getMemberFunctionPointer(const FunctionDecl *FD,
979                                            llvm::Type *Ty = nullptr);
980 
981   llvm::Constant *getMemberFunctionPointer(llvm::Constant *Pointer,
982                                            QualType FT);
983 
984   CGPointerAuthInfo getFunctionPointerAuthInfo(QualType T);
985 
986   CGPointerAuthInfo getMemberFunctionPointerAuthInfo(QualType FT);
987 
988   CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type);
989 
990   CGPointerAuthInfo getPointerAuthInfoForType(QualType type);
991 
992   bool shouldSignPointer(const PointerAuthSchema &Schema);
993   llvm::Constant *getConstantSignedPointer(llvm::Constant *Pointer,
994                                            const PointerAuthSchema &Schema,
995                                            llvm::Constant *StorageAddress,
996                                            GlobalDecl SchemaDecl,
997                                            QualType SchemaType);
998 
999   llvm::Constant *
1000   getConstantSignedPointer(llvm::Constant *Pointer, unsigned Key,
1001                            llvm::Constant *StorageAddress,
1002                            llvm::ConstantInt *OtherDiscriminator);
1003 
1004   llvm::ConstantInt *
1005   getPointerAuthOtherDiscriminator(const PointerAuthSchema &Schema,
1006                                    GlobalDecl SchemaDecl, QualType SchemaType);
1007 
1008   uint16_t getPointerAuthDeclDiscriminator(GlobalDecl GD);
1009   std::optional<CGPointerAuthInfo>
1010   getVTablePointerAuthInfo(CodeGenFunction *Context,
1011                            const CXXRecordDecl *Record,
1012                            llvm::Value *StorageAddress);
1013 
1014   std::optional<PointerAuthQualifier>
1015   getVTablePointerAuthentication(const CXXRecordDecl *thisClass);
1016 
1017   CGPointerAuthInfo EmitPointerAuthInfo(const RecordDecl *RD);
1018 
1019   // Return whether RTTI information should be emitted for this target.
1020   bool shouldEmitRTTI(bool ForEH = false) {
1021     return (ForEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice &&
1022            !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
1023              (getTriple().isNVPTX() || getTriple().isAMDGPU()));
1024   }
1025 
1026   /// Get the address of the RTTI descriptor for the given type.
1027   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
1028 
1029   /// Get the address of a GUID.
1030   ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
1031 
1032   /// Get the address of a UnnamedGlobalConstant
1033   ConstantAddress
1034   GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD);
1035 
1036   /// Get the address of a template parameter object.
1037   ConstantAddress
1038   GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
1039 
1040   /// Get the address of the thunk for the given global decl.
1041   llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
1042                                  GlobalDecl GD);
1043 
1044   /// Get a reference to the target of VD.
1045   ConstantAddress GetWeakRefReference(const ValueDecl *VD);
1046 
1047   /// Returns the assumed alignment of an opaque pointer to the given class.
1048   CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
1049 
1050   /// Returns the minimum object size for an object of the given class type
1051   /// (or a class derived from it).
1052   CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
1053 
1054   /// Returns the minimum object size for an object of the given type.
1055   CharUnits getMinimumObjectSize(QualType Ty) {
1056     if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
1057       return getMinimumClassObjectSize(RD);
1058     return getContext().getTypeSizeInChars(Ty);
1059   }
1060 
1061   /// Returns the assumed alignment of a virtual base of a class.
1062   CharUnits getVBaseAlignment(CharUnits DerivedAlign,
1063                               const CXXRecordDecl *Derived,
1064                               const CXXRecordDecl *VBase);
1065 
1066   /// Given a class pointer with an actual known alignment, and the
1067   /// expected alignment of an object at a dynamic offset w.r.t that
1068   /// pointer, return the alignment to assume at the offset.
1069   CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
1070                                       const CXXRecordDecl *Class,
1071                                       CharUnits ExpectedTargetAlign);
1072 
1073   CharUnits
1074   computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
1075                                    CastExpr::path_const_iterator Start,
1076                                    CastExpr::path_const_iterator End);
1077 
1078   /// Returns the offset from a derived class to  a class. Returns null if the
1079   /// offset is 0.
1080   llvm::Constant *
1081   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
1082                                CastExpr::path_const_iterator PathBegin,
1083                                CastExpr::path_const_iterator PathEnd);
1084 
1085   llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
1086 
1087   /// Fetches the global unique block count.
1088   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
1089 
1090   /// Fetches the type of a generic block descriptor.
1091   llvm::Type *getBlockDescriptorType();
1092 
1093   /// The type of a generic block literal.
1094   llvm::Type *getGenericBlockLiteralType();
1095 
1096   /// Gets the address of a block which requires no captures.
1097   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
1098 
1099   /// Returns the address of a block which requires no caputres, or null if
1100   /// we've yet to emit the block for BE.
1101   llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
1102     return EmittedGlobalBlocks.lookup(BE);
1103   }
1104 
1105   /// Notes that BE's global block is available via Addr. Asserts that BE
1106   /// isn't already emitted.
1107   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
1108 
1109   /// Return a pointer to a constant CFString object for the given string.
1110   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
1111 
1112   /// Return a constant array for the given string.
1113   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
1114 
1115   /// Return a pointer to a constant array for the given string literal.
1116   ConstantAddress
1117   GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
1118                                      StringRef Name = ".str");
1119 
1120   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
1121   ConstantAddress
1122   GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
1123 
1124   /// Returns a pointer to a character array containing the literal and a
1125   /// terminating '\0' character. The result has pointer to array type.
1126   ///
1127   /// \param GlobalName If provided, the name to use for the global (if one is
1128   /// created).
1129   ConstantAddress
1130   GetAddrOfConstantCString(const std::string &Str,
1131                            const char *GlobalName = nullptr);
1132 
1133   /// Returns a pointer to a constant global variable for the given file-scope
1134   /// compound literal expression.
1135   ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
1136 
1137   /// If it's been emitted already, returns the GlobalVariable corresponding to
1138   /// a compound literal. Otherwise, returns null.
1139   llvm::GlobalVariable *
1140   getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
1141 
1142   /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
1143   /// emitted.
1144   void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
1145                                         llvm::GlobalVariable *GV);
1146 
1147   /// Returns a pointer to a global variable representing a temporary
1148   /// with static or thread storage duration.
1149   ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
1150                                            const Expr *Inner);
1151 
1152   /// Retrieve the record type that describes the state of an
1153   /// Objective-C fast enumeration loop (for..in).
1154   QualType getObjCFastEnumerationStateType();
1155 
1156   // Produce code for this constructor/destructor. This method doesn't try
1157   // to apply any ABI rules about which other constructors/destructors
1158   // are needed or if they are alias to each other.
1159   llvm::Function *codegenCXXStructor(GlobalDecl GD);
1160 
1161   /// Return the address of the constructor/destructor of the given type.
1162   llvm::Constant *
1163   getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1164                        llvm::FunctionType *FnType = nullptr,
1165                        bool DontDefer = false,
1166                        ForDefinition_t IsForDefinition = NotForDefinition) {
1167     return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1168                                                             DontDefer,
1169                                                             IsForDefinition)
1170                                     .getCallee());
1171   }
1172 
1173   llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1174       GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1175       llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1176       ForDefinition_t IsForDefinition = NotForDefinition);
1177 
1178   /// Given a builtin id for a function like "__builtin_fabsf", return a
1179   /// Function* for "fabsf".
1180   llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1181                                         unsigned BuiltinID);
1182 
1183   llvm::Function *getIntrinsic(unsigned IID,
1184                                ArrayRef<llvm::Type *> Tys = std::nullopt);
1185 
1186   /// Emit code for a single top level declaration.
1187   void EmitTopLevelDecl(Decl *D);
1188 
1189   /// Stored a deferred empty coverage mapping for an unused
1190   /// and thus uninstrumented top level declaration.
1191   void AddDeferredUnusedCoverageMapping(Decl *D);
1192 
1193   /// Remove the deferred empty coverage mapping as this
1194   /// declaration is actually instrumented.
1195   void ClearUnusedCoverageMapping(const Decl *D);
1196 
1197   /// Emit all the deferred coverage mappings
1198   /// for the uninstrumented functions.
1199   void EmitDeferredUnusedCoverageMappings();
1200 
1201   /// Emit an alias for "main" if it has no arguments (needed for wasm).
1202   void EmitMainVoidAlias();
1203 
1204   /// Tell the consumer that this variable has been instantiated.
1205   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1206 
1207   /// If the declaration has internal linkage but is inside an
1208   /// extern "C" linkage specification, prepare to emit an alias for it
1209   /// to the expected name.
1210   template<typename SomeDecl>
1211   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1212 
1213   /// Add a global to a list to be added to the llvm.used metadata.
1214   void addUsedGlobal(llvm::GlobalValue *GV);
1215 
1216   /// Add a global to a list to be added to the llvm.compiler.used metadata.
1217   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1218 
1219   /// Add a global to a list to be added to the llvm.compiler.used metadata.
1220   void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
1221 
1222   /// Add a destructor and object to add to the C++ global destructor function.
1223   void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1224     CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1225                                                  DtorFn.getCallee(), Object);
1226   }
1227 
1228   /// Add an sterm finalizer to the C++ global cleanup function.
1229   void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1230     CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1231                                                  DtorFn.getCallee(), nullptr);
1232   }
1233 
1234   /// Add an sterm finalizer to its own llvm.global_dtors entry.
1235   void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
1236                                         int Priority) {
1237     AddGlobalDtor(StermFinalizer, Priority);
1238   }
1239 
1240   void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
1241                                             int Priority) {
1242     OrderGlobalInitsOrStermFinalizers Key(Priority,
1243                                           PrioritizedCXXStermFinalizers.size());
1244     PrioritizedCXXStermFinalizers.push_back(
1245         std::make_pair(Key, StermFinalizer));
1246   }
1247 
1248   /// Create or return a runtime function declaration with the specified type
1249   /// and name. If \p AssumeConvergent is true, the call will have the
1250   /// convergent attribute added.
1251   llvm::FunctionCallee
1252   CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1253                         llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1254                         bool Local = false, bool AssumeConvergent = false);
1255 
1256   /// Create a new runtime global variable with the specified type and name.
1257   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1258                                         StringRef Name);
1259 
1260   ///@name Custom Blocks Runtime Interfaces
1261   ///@{
1262 
1263   llvm::Constant *getNSConcreteGlobalBlock();
1264   llvm::Constant *getNSConcreteStackBlock();
1265   llvm::FunctionCallee getBlockObjectAssign();
1266   llvm::FunctionCallee getBlockObjectDispose();
1267 
1268   ///@}
1269 
1270   llvm::Function *getLLVMLifetimeStartFn();
1271   llvm::Function *getLLVMLifetimeEndFn();
1272 
1273   // Make sure that this type is translated.
1274   void UpdateCompletedType(const TagDecl *TD);
1275 
1276   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1277 
1278   /// Emit type info if type of an expression is a variably modified
1279   /// type. Also emit proper debug info for cast types.
1280   void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1281                                 CodeGenFunction *CGF = nullptr);
1282 
1283   /// Return the result of value-initializing the given type, i.e. a null
1284   /// expression of the given type.  This is usually, but not always, an LLVM
1285   /// null constant.
1286   llvm::Constant *EmitNullConstant(QualType T);
1287 
1288   /// Return a null constant appropriate for zero-initializing a base class with
1289   /// the given type. This is usually, but not always, an LLVM null constant.
1290   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1291 
1292   /// Emit a general error that something can't be done.
1293   void Error(SourceLocation loc, StringRef error);
1294 
1295   /// Print out an error that codegen doesn't support the specified stmt yet.
1296   void ErrorUnsupported(const Stmt *S, const char *Type);
1297 
1298   /// Print out an error that codegen doesn't support the specified decl yet.
1299   void ErrorUnsupported(const Decl *D, const char *Type);
1300 
1301   /// Warn that the stack is nearly exhausted.
1302   void warnStackExhausted(SourceLocation Loc);
1303 
1304   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1305   /// guaranteed). Produces a warning if we're low on stack space and allocates
1306   /// more in that case. Use this in code that may recurse deeply to avoid stack
1307   /// overflow.
1308   void runWithSufficientStackSpace(SourceLocation Loc,
1309                                    llvm::function_ref<void()> Fn);
1310 
1311   /// Set the attributes on the LLVM function for the given decl and function
1312   /// info. This applies attributes necessary for handling the ABI as well as
1313   /// user specified attributes like section.
1314   void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1315                                      const CGFunctionInfo &FI);
1316 
1317   /// Set the LLVM function attributes (sext, zext, etc).
1318   void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1319                                  llvm::Function *F, bool IsThunk);
1320 
1321   /// Set the LLVM function attributes which only apply to a function
1322   /// definition.
1323   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1324 
1325   /// Set the LLVM function attributes that represent floating point
1326   /// environment.
1327   void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
1328 
1329   /// Return true iff the given type uses 'sret' when used as a return type.
1330   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1331 
1332   /// Return true iff the given type has `inreg` set.
1333   bool ReturnTypeHasInReg(const CGFunctionInfo &FI);
1334 
1335   /// Return true iff the given type uses an argument slot when 'sret' is used
1336   /// as a return type.
1337   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1338 
1339   /// Return true iff the given type uses 'fpret' when used as a return type.
1340   bool ReturnTypeUsesFPRet(QualType ResultType);
1341 
1342   /// Return true iff the given type uses 'fp2ret' when used as a return type.
1343   bool ReturnTypeUsesFP2Ret(QualType ResultType);
1344 
1345   /// Get the LLVM attributes and calling convention to use for a particular
1346   /// function type.
1347   ///
1348   /// \param Name - The function name.
1349   /// \param Info - The function type information.
1350   /// \param CalleeInfo - The callee information these attributes are being
1351   /// constructed for. If valid, the attributes applied to this decl may
1352   /// contribute to the function attributes and calling convention.
1353   /// \param Attrs [out] - On return, the attribute list to use.
1354   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1355   void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1356                               CGCalleeInfo CalleeInfo,
1357                               llvm::AttributeList &Attrs, unsigned &CallingConv,
1358                               bool AttrOnCallSite, bool IsThunk);
1359 
1360   /// Adjust Memory attribute to ensure that the BE gets the right attribute
1361   // in order to generate the library call or the intrinsic for the function
1362   // name 'Name'.
1363   void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo,
1364                              llvm::AttributeList &Attrs);
1365 
1366   /// Like the overload taking a `Function &`, but intended specifically
1367   /// for frontends that want to build on Clang's target-configuration logic.
1368   void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1369 
1370   StringRef getMangledName(GlobalDecl GD);
1371   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1372   const GlobalDecl getMangledNameDecl(StringRef);
1373 
1374   void EmitTentativeDefinition(const VarDecl *D);
1375 
1376   void EmitExternalDeclaration(const DeclaratorDecl *D);
1377 
1378   void EmitVTable(CXXRecordDecl *Class);
1379 
1380   void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1381 
1382   /// Appends Opts to the "llvm.linker.options" metadata value.
1383   void AppendLinkerOptions(StringRef Opts);
1384 
1385   /// Appends a detect mismatch command to the linker options.
1386   void AddDetectMismatch(StringRef Name, StringRef Value);
1387 
1388   /// Appends a dependent lib to the appropriate metadata value.
1389   void AddDependentLib(StringRef Lib);
1390 
1391 
1392   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1393 
1394   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1395     F->setLinkage(getFunctionLinkage(GD));
1396   }
1397 
1398   /// Return the appropriate linkage for the vtable, VTT, and type information
1399   /// of the given class.
1400   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1401 
1402   /// Return the store size, in character units, of the given LLVM type.
1403   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1404 
1405   /// Returns LLVM linkage for a declarator.
1406   llvm::GlobalValue::LinkageTypes
1407   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage);
1408 
1409   /// Returns LLVM linkage for a declarator.
1410   llvm::GlobalValue::LinkageTypes
1411   getLLVMLinkageVarDefinition(const VarDecl *VD);
1412 
1413   /// Emit all the global annotations.
1414   void EmitGlobalAnnotations();
1415 
1416   /// Emit an annotation string.
1417   llvm::Constant *EmitAnnotationString(StringRef Str);
1418 
1419   /// Emit the annotation's translation unit.
1420   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1421 
1422   /// Emit the annotation line number.
1423   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1424 
1425   /// Emit additional args of the annotation.
1426   llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
1427 
1428   /// Generate the llvm::ConstantStruct which contains the annotation
1429   /// information for a given GlobalValue. The annotation struct is
1430   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1431   /// GlobalValue being annotated. The second field is the constant string
1432   /// created from the AnnotateAttr's annotation. The third field is a constant
1433   /// string containing the name of the translation unit. The fourth field is
1434   /// the line number in the file of the annotated value declaration.
1435   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1436                                    const AnnotateAttr *AA,
1437                                    SourceLocation L);
1438 
1439   /// Add global annotations that are set on D, for the global GV. Those
1440   /// annotations are emitted during finalization of the LLVM code.
1441   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1442 
1443   bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
1444                           SourceLocation Loc) const;
1445 
1446   bool isInNoSanitizeList(SanitizerMask Kind, llvm::GlobalVariable *GV,
1447                           SourceLocation Loc, QualType Ty,
1448                           StringRef Category = StringRef()) const;
1449 
1450   /// Imbue XRay attributes to a function, applying the always/never attribute
1451   /// lists in the process. Returns true if we did imbue attributes this way,
1452   /// false otherwise.
1453   bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1454                       StringRef Category = StringRef()) const;
1455 
1456   /// \returns true if \p Fn at \p Loc should be excluded from profile
1457   /// instrumentation by the SCL passed by \p -fprofile-list.
1458   ProfileList::ExclusionType
1459   isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const;
1460 
1461   /// \returns true if \p Fn at \p Loc should be excluded from profile
1462   /// instrumentation.
1463   ProfileList::ExclusionType
1464   isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
1465                                     SourceLocation Loc) const;
1466 
1467   SanitizerMetadata *getSanitizerMetadata() {
1468     return SanitizerMD.get();
1469   }
1470 
1471   void addDeferredVTable(const CXXRecordDecl *RD) {
1472     DeferredVTables.push_back(RD);
1473   }
1474 
1475   /// Emit code for a single global function or var decl. Forward declarations
1476   /// are emitted lazily.
1477   void EmitGlobal(GlobalDecl D);
1478 
1479   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1480 
1481   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1482 
1483   /// Set attributes which are common to any form of a global definition (alias,
1484   /// Objective-C method, function, global variable).
1485   ///
1486   /// NOTE: This should only be called for definitions.
1487   void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1488 
1489   void addReplacement(StringRef Name, llvm::Constant *C);
1490 
1491   void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1492 
1493   /// Emit a code for threadprivate directive.
1494   /// \param D Threadprivate declaration.
1495   void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1496 
1497   /// Emit a code for declare reduction construct.
1498   void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1499                                CodeGenFunction *CGF = nullptr);
1500 
1501   /// Emit a code for declare mapper construct.
1502   void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1503                             CodeGenFunction *CGF = nullptr);
1504 
1505   /// Emit a code for requires directive.
1506   /// \param D Requires declaration
1507   void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1508 
1509   /// Emit a code for the allocate directive.
1510   /// \param D The allocate declaration
1511   void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
1512 
1513   /// Return the alignment specified in an allocate directive, if present.
1514   std::optional<CharUnits> getOMPAllocateAlignment(const VarDecl *VD);
1515 
1516   /// Returns whether the given record has hidden LTO visibility and therefore
1517   /// may participate in (single-module) CFI and whole-program vtable
1518   /// optimization.
1519   bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1520 
1521   /// Returns whether the given record has public LTO visibility (regardless of
1522   /// -lto-whole-program-visibility) and therefore may not participate in
1523   /// (single-module) CFI and whole-program vtable optimization.
1524   bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD);
1525 
1526   /// Returns the vcall visibility of the given type. This is the scope in which
1527   /// a virtual function call could be made which ends up being dispatched to a
1528   /// member function of this class. This scope can be wider than the visibility
1529   /// of the class itself when the class has a more-visible dynamic base class.
1530   /// The client should pass in an empty Visited set, which is used to prevent
1531   /// redundant recursive processing.
1532   llvm::GlobalObject::VCallVisibility
1533   GetVCallVisibilityLevel(const CXXRecordDecl *RD,
1534                           llvm::DenseSet<const CXXRecordDecl *> &Visited);
1535 
1536   /// Emit type metadata for the given vtable using the given layout.
1537   void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1538                               llvm::GlobalVariable *VTable,
1539                               const VTableLayout &VTLayout);
1540 
1541   llvm::Type *getVTableComponentType() const;
1542 
1543   /// Generate a cross-DSO type identifier for MD.
1544   llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1545 
1546   /// Generate a KCFI type identifier for T.
1547   llvm::ConstantInt *CreateKCFITypeId(QualType T);
1548 
1549   /// Create a metadata identifier for the given type. This may either be an
1550   /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1551   /// internal identifiers).
1552   llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1553 
1554   /// Create a metadata identifier that is intended to be used to check virtual
1555   /// calls via a member function pointer.
1556   llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1557 
1558   /// Create a metadata identifier for the generalization of the given type.
1559   /// This may either be an MDString (for external identifiers) or a distinct
1560   /// unnamed MDNode (for internal identifiers).
1561   llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1562 
1563   /// Create and attach type metadata to the given function.
1564   void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1565                                           llvm::Function *F);
1566 
1567   /// Set type metadata to the given function.
1568   void setKCFIType(const FunctionDecl *FD, llvm::Function *F);
1569 
1570   /// Emit KCFI type identifier constants and remove unused identifiers.
1571   void finalizeKCFITypes();
1572 
1573   /// Whether this function's return type has no side effects, and thus may
1574   /// be trivially discarded if it is unused.
1575   bool MayDropFunctionReturn(const ASTContext &Context,
1576                              QualType ReturnType) const;
1577 
1578   /// Returns whether this module needs the "all-vtables" type identifier.
1579   bool NeedAllVtablesTypeId() const;
1580 
1581   /// Create and attach type metadata for the given vtable.
1582   void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1583                              const CXXRecordDecl *RD);
1584 
1585   /// Return a vector of most-base classes for RD. This is used to implement
1586   /// control flow integrity checks for member function pointers.
1587   ///
1588   /// A most-base class of a class C is defined as a recursive base class of C,
1589   /// including C itself, that does not have any bases.
1590   SmallVector<const CXXRecordDecl *, 0>
1591   getMostBaseClasses(const CXXRecordDecl *RD);
1592 
1593   /// Get the declaration of std::terminate for the platform.
1594   llvm::FunctionCallee getTerminateFn();
1595 
1596   llvm::SanitizerStatReport &getSanStats();
1597 
1598   llvm::Value *
1599   createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1600 
1601   /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1602   /// information in the program executable. The argument information stored
1603   /// includes the argument name, its type, the address and access qualifiers
1604   /// used. This helper can be used to generate metadata for source code kernel
1605   /// function as well as generated implicitly kernels. If a kernel is generated
1606   /// implicitly null value has to be passed to the last two parameters,
1607   /// otherwise all parameters must have valid non-null values.
1608   /// \param FN is a pointer to IR function being generated.
1609   /// \param FD is a pointer to function declaration if any.
1610   /// \param CGF is a pointer to CodeGenFunction that generates this function.
1611   void GenKernelArgMetadata(llvm::Function *FN,
1612                             const FunctionDecl *FD = nullptr,
1613                             CodeGenFunction *CGF = nullptr);
1614 
1615   /// Get target specific null pointer.
1616   /// \param T is the LLVM type of the null pointer.
1617   /// \param QT is the clang QualType of the null pointer.
1618   llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1619 
1620   CharUnits getNaturalTypeAlignment(QualType T,
1621                                     LValueBaseInfo *BaseInfo = nullptr,
1622                                     TBAAAccessInfo *TBAAInfo = nullptr,
1623                                     bool forPointeeType = false);
1624   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1625                                            LValueBaseInfo *BaseInfo = nullptr,
1626                                            TBAAAccessInfo *TBAAInfo = nullptr);
1627   bool stopAutoInit();
1628 
1629   /// Print the postfix for externalized static variable or kernels for single
1630   /// source offloading languages CUDA and HIP. The unique postfix is created
1631   /// using either the CUID argument, or the file's UniqueID and active macros.
1632   /// The fallback method without a CUID requires that the offloading toolchain
1633   /// does not define separate macros via the -cc1 options.
1634   void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
1635                                        const Decl *D) const;
1636 
1637   /// Move some lazily-emitted states to the NewBuilder. This is especially
1638   /// essential for the incremental parsing environment like Clang Interpreter,
1639   /// because we'll lose all important information after each repl.
1640   void moveLazyEmissionStates(CodeGenModule *NewBuilder);
1641 
1642   /// Emit the IR encoding to attach the CUDA launch bounds attribute to \p F.
1643   /// If \p MaxThreadsVal is not nullptr, the max threads value is stored in it,
1644   /// if a valid one was found.
1645   void handleCUDALaunchBoundsAttr(llvm::Function *F,
1646                                   const CUDALaunchBoundsAttr *A,
1647                                   int32_t *MaxThreadsVal = nullptr,
1648                                   int32_t *MinBlocksVal = nullptr,
1649                                   int32_t *MaxClusterRankVal = nullptr);
1650 
1651   /// Emit the IR encoding to attach the AMD GPU flat-work-group-size attribute
1652   /// to \p F. Alternatively, the work group size can be taken from a \p
1653   /// ReqdWGS. If \p MinThreadsVal is not nullptr, the min threads value is
1654   /// stored in it, if a valid one was found. If \p MaxThreadsVal is not
1655   /// nullptr, the max threads value is stored in it, if a valid one was found.
1656   void handleAMDGPUFlatWorkGroupSizeAttr(
1657       llvm::Function *F, const AMDGPUFlatWorkGroupSizeAttr *A,
1658       const ReqdWorkGroupSizeAttr *ReqdWGS = nullptr,
1659       int32_t *MinThreadsVal = nullptr, int32_t *MaxThreadsVal = nullptr);
1660 
1661   /// Emit the IR encoding to attach the AMD GPU waves-per-eu attribute to \p F.
1662   void handleAMDGPUWavesPerEUAttr(llvm::Function *F,
1663                                   const AMDGPUWavesPerEUAttr *A);
1664 
1665   llvm::Constant *
1666   GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
1667                         const VarDecl *D,
1668                         ForDefinition_t IsForDefinition = NotForDefinition);
1669 
1670   // FIXME: Hardcoding priority here is gross.
1671   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1672                      unsigned LexOrder = ~0U,
1673                      llvm::Constant *AssociatedData = nullptr);
1674   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
1675                      bool IsDtorAttrFunc = false);
1676 
1677   // Return whether structured convergence intrinsics should be generated for
1678   // this target.
1679   bool shouldEmitConvergenceTokens() const {
1680     // TODO: this should probably become unconditional once the controlled
1681     // convergence becomes the norm.
1682     return getTriple().isSPIRVLogical();
1683   }
1684 
1685   void addUndefinedGlobalForTailCall(
1686       std::pair<const FunctionDecl *, SourceLocation> Global) {
1687     MustTailCallUndefinedGlobals.insert(Global);
1688   }
1689 
1690 private:
1691   bool shouldDropDLLAttribute(const Decl *D, const llvm::GlobalValue *GV) const;
1692 
1693   llvm::Constant *GetOrCreateLLVMFunction(
1694       StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1695       bool DontDefer = false, bool IsThunk = false,
1696       llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1697       ForDefinition_t IsForDefinition = NotForDefinition);
1698 
1699   // Adds a declaration to the list of multi version functions if not present.
1700   void AddDeferredMultiVersionResolverToEmit(GlobalDecl GD);
1701 
1702   // References to multiversion functions are resolved through an implicitly
1703   // defined resolver function. This function is responsible for creating
1704   // the resolver symbol for the provided declaration. The value returned
1705   // will be for an ifunc (llvm::GlobalIFunc) if the current target supports
1706   // that feature and for a regular function (llvm::GlobalValue) otherwise.
1707   llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD);
1708 
1709   // In scenarios where a function is not known to be a multiversion function
1710   // until a later declaration, it is sometimes necessary to change the
1711   // previously created mangled name to align with requirements of whatever
1712   // multiversion function kind the function is now known to be. This function
1713   // is responsible for performing such mangled name updates.
1714   void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
1715                                StringRef &CurName);
1716 
1717   bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1718                                    llvm::AttrBuilder &AttrBuilder,
1719                                    bool SetTargetFeatures = true);
1720   void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1721 
1722   /// Set function attributes for a function declaration.
1723   void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1724                              bool IsIncompleteFunction, bool IsThunk);
1725 
1726   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1727 
1728   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1729   void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1730 
1731   void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1732   void EmitExternalVarDeclaration(const VarDecl *D);
1733   void EmitExternalFunctionDeclaration(const FunctionDecl *D);
1734   void EmitAliasDefinition(GlobalDecl GD);
1735   void emitIFuncDefinition(GlobalDecl GD);
1736   void emitCPUDispatchDefinition(GlobalDecl GD);
1737   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1738   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1739 
1740   // C++ related functions.
1741 
1742   void EmitDeclContext(const DeclContext *DC);
1743   void EmitLinkageSpec(const LinkageSpecDecl *D);
1744   void EmitTopLevelStmt(const TopLevelStmtDecl *D);
1745 
1746   /// Emit the function that initializes C++ thread_local variables.
1747   void EmitCXXThreadLocalInitFunc();
1748 
1749   /// Emit the function that initializes global variables for a C++ Module.
1750   void EmitCXXModuleInitFunc(clang::Module *Primary);
1751 
1752   /// Emit the function that initializes C++ globals.
1753   void EmitCXXGlobalInitFunc();
1754 
1755   /// Emit the function that performs cleanup associated with C++ globals.
1756   void EmitCXXGlobalCleanUpFunc();
1757 
1758   /// Emit the function that initializes the specified global (if PerformInit is
1759   /// true) and registers its destructor.
1760   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1761                                     llvm::GlobalVariable *Addr,
1762                                     bool PerformInit);
1763 
1764   void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1765                              llvm::Function *InitFunc, InitSegAttr *ISA);
1766 
1767   /// EmitCtorList - Generates a global array of functions and priorities using
1768   /// the given list and name. This array will have appending linkage and is
1769   /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1770   void EmitCtorList(CtorList &Fns, const char *GlobalName);
1771 
1772   /// Emit any needed decls for which code generation was deferred.
1773   void EmitDeferred();
1774 
1775   /// Try to emit external vtables as available_externally if they have emitted
1776   /// all inlined virtual functions.  It runs after EmitDeferred() and therefore
1777   /// is not allowed to create new references to things that need to be emitted
1778   /// lazily.
1779   void EmitVTablesOpportunistically();
1780 
1781   /// Call replaceAllUsesWith on all pairs in Replacements.
1782   void applyReplacements();
1783 
1784   /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1785   void applyGlobalValReplacements();
1786 
1787   void checkAliases();
1788 
1789   std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1790 
1791   /// Register functions annotated with __attribute__((destructor)) using
1792   /// __cxa_atexit, if it is available, or atexit otherwise.
1793   void registerGlobalDtorsWithAtExit();
1794 
1795   // When using sinit and sterm functions, unregister
1796   // __attribute__((destructor)) annotated functions which were previously
1797   // registered by the atexit subroutine using unatexit.
1798   void unregisterGlobalDtorsWithUnAtExit();
1799 
1800   /// Emit deferred multiversion function resolvers and associated variants.
1801   void emitMultiVersionFunctions();
1802 
1803   /// Emit any vtables which we deferred and still have a use for.
1804   void EmitDeferredVTables();
1805 
1806   /// Emit a dummy function that reference a CoreFoundation symbol when
1807   /// @available is used on Darwin.
1808   void emitAtAvailableLinkGuard();
1809 
1810   /// Emit the llvm.used and llvm.compiler.used metadata.
1811   void emitLLVMUsed();
1812 
1813   /// For C++20 Itanium ABI, emit the initializers for the module.
1814   void EmitModuleInitializers(clang::Module *Primary);
1815 
1816   /// Emit the link options introduced by imported modules.
1817   void EmitModuleLinkOptions();
1818 
1819   /// Helper function for EmitStaticExternCAliases() to redirect ifuncs that
1820   /// have a resolver name that matches 'Elem' to instead resolve to the name of
1821   /// 'CppFunc'. This redirection is necessary in cases where 'Elem' has a name
1822   /// that will be emitted as an alias of the name bound to 'CppFunc'; ifuncs
1823   /// may not reference aliases. Redirection is only performed if 'Elem' is only
1824   /// used by ifuncs in which case, 'Elem' is destroyed. 'true' is returned if
1825   /// redirection is successful, and 'false' is returned otherwise.
1826   bool CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
1827                                     llvm::GlobalValue *CppFunc);
1828 
1829   /// Emit aliases for internal-linkage declarations inside "C" language
1830   /// linkage specifications, giving them the "expected" name where possible.
1831   void EmitStaticExternCAliases();
1832 
1833   void EmitDeclMetadata();
1834 
1835   /// Emit the Clang version as llvm.ident metadata.
1836   void EmitVersionIdentMetadata();
1837 
1838   /// Emit the Clang commandline as llvm.commandline metadata.
1839   void EmitCommandLineMetadata();
1840 
1841   /// Emit the module flag metadata used to pass options controlling the
1842   /// the backend to LLVM.
1843   void EmitBackendOptionsMetadata(const CodeGenOptions &CodeGenOpts);
1844 
1845   /// Emits OpenCL specific Metadata e.g. OpenCL version.
1846   void EmitOpenCLMetadata();
1847 
1848   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1849   /// .gcda files in a way that persists in .bc files.
1850   void EmitCoverageFile();
1851 
1852   /// Determine whether the definition must be emitted; if this returns \c
1853   /// false, the definition can be emitted lazily if it's used.
1854   bool MustBeEmitted(const ValueDecl *D);
1855 
1856   /// Determine whether the definition can be emitted eagerly, or should be
1857   /// delayed until the end of the translation unit. This is relevant for
1858   /// definitions whose linkage can change, e.g. implicit function instantions
1859   /// which may later be explicitly instantiated.
1860   bool MayBeEmittedEagerly(const ValueDecl *D);
1861 
1862   /// Check whether we can use a "simpler", more core exceptions personality
1863   /// function.
1864   void SimplifyPersonality();
1865 
1866   /// Helper function for getDefaultFunctionAttributes. Builds a set of function
1867   /// attributes which can be simply added to a function.
1868   void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1869                                            bool AttrOnCallSite,
1870                                            llvm::AttrBuilder &FuncAttrs);
1871 
1872   /// Helper function for ConstructAttributeList and
1873   /// addDefaultFunctionDefinitionAttributes.  Builds a set of function
1874   /// attributes to add to a function with the given properties.
1875   void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1876                                     bool AttrOnCallSite,
1877                                     llvm::AttrBuilder &FuncAttrs);
1878 
1879   llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1880                                                StringRef Suffix);
1881 };
1882 
1883 }  // end namespace CodeGen
1884 }  // end namespace clang
1885 
1886 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
1887