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