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