1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the internal per-translation-unit state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
16 
17 #include "CGVTables.h"
18 #include "CodeGenTypeCache.h"
19 #include "CodeGenTypes.h"
20 #include "SanitizerMetadata.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/GlobalDecl.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/SanitizerBlacklist.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 IndexedInstrProfReader;
49 }
50 
51 namespace clang {
52 class ASTContext;
53 class AtomicType;
54 class FunctionDecl;
55 class IdentifierInfo;
56 class ObjCMethodDecl;
57 class ObjCImplementationDecl;
58 class ObjCCategoryImplDecl;
59 class ObjCProtocolDecl;
60 class ObjCEncodeExpr;
61 class BlockExpr;
62 class CharUnits;
63 class Decl;
64 class Expr;
65 class Stmt;
66 class InitListExpr;
67 class StringLiteral;
68 class NamedDecl;
69 class ValueDecl;
70 class VarDecl;
71 class LangOptions;
72 class CodeGenOptions;
73 class HeaderSearchOptions;
74 class PreprocessorOptions;
75 class DiagnosticsEngine;
76 class AnnotateAttr;
77 class CXXDestructorDecl;
78 class Module;
79 class CoverageSourceInfo;
80 
81 namespace CodeGen {
82 
83 class CallArgList;
84 class CodeGenFunction;
85 class CodeGenTBAA;
86 class CGCXXABI;
87 class CGDebugInfo;
88 class CGObjCRuntime;
89 class CGOpenCLRuntime;
90 class CGOpenMPRuntime;
91 class CGCUDARuntime;
92 class BlockFieldFlags;
93 class FunctionArgList;
94 class CoverageMappingModuleGen;
95 class TargetCodeGenInfo;
96 
97 struct OrderGlobalInits {
98   unsigned int priority;
99   unsigned int lex_order;
100   OrderGlobalInits(unsigned int p, unsigned int l)
101       : priority(p), lex_order(l) {}
102 
103   bool operator==(const OrderGlobalInits &RHS) const {
104     return priority == RHS.priority && lex_order == RHS.lex_order;
105   }
106 
107   bool operator<(const OrderGlobalInits &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_autoreleasePoolPop(void*);
117   llvm::Constant *objc_autoreleasePoolPop;
118 
119   /// void *objc_autoreleasePoolPush(void);
120   llvm::Constant *objc_autoreleasePoolPush;
121 
122   /// id objc_autorelease(id);
123   llvm::Constant *objc_autorelease;
124 
125   /// id objc_autoreleaseReturnValue(id);
126   llvm::Constant *objc_autoreleaseReturnValue;
127 
128   /// void objc_copyWeak(id *dest, id *src);
129   llvm::Constant *objc_copyWeak;
130 
131   /// void objc_destroyWeak(id*);
132   llvm::Constant *objc_destroyWeak;
133 
134   /// id objc_initWeak(id*, id);
135   llvm::Constant *objc_initWeak;
136 
137   /// id objc_loadWeak(id*);
138   llvm::Constant *objc_loadWeak;
139 
140   /// id objc_loadWeakRetained(id*);
141   llvm::Constant *objc_loadWeakRetained;
142 
143   /// void objc_moveWeak(id *dest, id *src);
144   llvm::Constant *objc_moveWeak;
145 
146   /// id objc_retain(id);
147   llvm::Constant *objc_retain;
148 
149   /// id objc_retainAutorelease(id);
150   llvm::Constant *objc_retainAutorelease;
151 
152   /// id objc_retainAutoreleaseReturnValue(id);
153   llvm::Constant *objc_retainAutoreleaseReturnValue;
154 
155   /// id objc_retainAutoreleasedReturnValue(id);
156   llvm::Constant *objc_retainAutoreleasedReturnValue;
157 
158   /// id objc_retainBlock(id);
159   llvm::Constant *objc_retainBlock;
160 
161   /// void objc_release(id);
162   llvm::Constant *objc_release;
163 
164   /// id objc_storeStrong(id*, id);
165   llvm::Constant *objc_storeStrong;
166 
167   /// id objc_storeWeak(id*, id);
168   llvm::Constant *objc_storeWeak;
169 
170   /// id objc_unsafeClaimAutoreleasedReturnValue(id);
171   llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
172 
173   /// A void(void) inline asm to use to mark that the return value of
174   /// a call will be immediately retain.
175   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
176 
177   /// void clang.arc.use(...);
178   llvm::Constant *clang_arc_use;
179 };
180 
181 /// This class records statistics on instrumentation based profiling.
182 class InstrProfStats {
183   uint32_t VisitedInMainFile;
184   uint32_t MissingInMainFile;
185   uint32_t Visited;
186   uint32_t Missing;
187   uint32_t Mismatched;
188 
189 public:
190   InstrProfStats()
191       : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
192         Mismatched(0) {}
193   /// Record that we've visited a function and whether or not that function was
194   /// in the main source file.
195   void addVisited(bool MainFile) {
196     if (MainFile)
197       ++VisitedInMainFile;
198     ++Visited;
199   }
200   /// Record that a function we've visited has no profile data.
201   void addMissing(bool MainFile) {
202     if (MainFile)
203       ++MissingInMainFile;
204     ++Missing;
205   }
206   /// Record that a function we've visited has mismatched profile data.
207   void addMismatched(bool MainFile) { ++Mismatched; }
208   /// Whether or not the stats we've gathered indicate any potential problems.
209   bool hasDiagnostics() { return Missing || Mismatched; }
210   /// Report potential problems we've found to \c Diags.
211   void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
212 };
213 
214 /// A pair of helper functions for a __block variable.
215 class BlockByrefHelpers : public llvm::FoldingSetNode {
216   // MSVC requires this type to be complete in order to process this
217   // header.
218 public:
219   llvm::Constant *CopyHelper;
220   llvm::Constant *DisposeHelper;
221 
222   /// The alignment of the field.  This is important because
223   /// different offsets to the field within the byref struct need to
224   /// have different helper functions.
225   CharUnits Alignment;
226 
227   BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
228   BlockByrefHelpers(const BlockByrefHelpers &) = default;
229   virtual ~BlockByrefHelpers();
230 
231   void Profile(llvm::FoldingSetNodeID &id) const {
232     id.AddInteger(Alignment.getQuantity());
233     profileImpl(id);
234   }
235   virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
236 
237   virtual bool needsCopy() const { return true; }
238   virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
239 
240   virtual bool needsDispose() const { return true; }
241   virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
242 };
243 
244 /// This class organizes the cross-function state that is used while generating
245 /// LLVM code.
246 class CodeGenModule : public CodeGenTypeCache {
247   CodeGenModule(const CodeGenModule &) = delete;
248   void operator=(const CodeGenModule &) = delete;
249 
250 public:
251   struct Structor {
252     Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
253     Structor(int Priority, llvm::Constant *Initializer,
254              llvm::Constant *AssociatedData)
255         : Priority(Priority), Initializer(Initializer),
256           AssociatedData(AssociatedData) {}
257     int Priority;
258     llvm::Constant *Initializer;
259     llvm::Constant *AssociatedData;
260   };
261 
262   typedef std::vector<Structor> CtorList;
263 
264 private:
265   ASTContext &Context;
266   const LangOptions &LangOpts;
267   const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
268   const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
269   const CodeGenOptions &CodeGenOpts;
270   llvm::Module &TheModule;
271   DiagnosticsEngine &Diags;
272   const TargetInfo &Target;
273   std::unique_ptr<CGCXXABI> ABI;
274   llvm::LLVMContext &VMContext;
275 
276   std::unique_ptr<CodeGenTBAA> TBAA;
277 
278   mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
279 
280   // This should not be moved earlier, since its initialization depends on some
281   // of the previous reference members being already initialized and also checks
282   // if TheTargetCodeGenInfo is NULL
283   CodeGenTypes Types;
284 
285   /// Holds information about C++ vtables.
286   CodeGenVTables VTables;
287 
288   std::unique_ptr<CGObjCRuntime> ObjCRuntime;
289   std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
290   std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
291   std::unique_ptr<CGCUDARuntime> CUDARuntime;
292   std::unique_ptr<CGDebugInfo> DebugInfo;
293   std::unique_ptr<ObjCEntrypoints> ObjCData;
294   llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
295   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
296   InstrProfStats PGOStats;
297   std::unique_ptr<llvm::SanitizerStatReport> SanStats;
298 
299   // A set of references that have only been seen via a weakref so far. This is
300   // used to remove the weak of the reference if we ever see a direct reference
301   // or a definition.
302   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
303 
304   /// This contains all the decls which have definitions but/ which are deferred
305   /// for emission and therefore should only be output if they are actually
306   /// used. If a decl is in this, then it is known to have not been referenced
307   /// yet.
308   std::map<StringRef, GlobalDecl> DeferredDecls;
309 
310   /// This is a list of deferred decls which we have seen that *are* actually
311   /// referenced. These get code generated when the module is done.
312   struct DeferredGlobal {
313     DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
314     llvm::TrackingVH<llvm::GlobalValue> GV;
315     GlobalDecl GD;
316   };
317   std::vector<DeferredGlobal> DeferredDeclsToEmit;
318   void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
319     DeferredDeclsToEmit.emplace_back(GV, GD);
320   }
321 
322   /// List of alias we have emitted. Used to make sure that what they point to
323   /// is defined once we get to the end of the of the translation unit.
324   std::vector<GlobalDecl> Aliases;
325 
326   typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
327   ReplacementsTy Replacements;
328 
329   /// List of global values to be replaced with something else. Used when we
330   /// want to replace a GlobalValue but can't identify it by its mangled name
331   /// anymore (because the name is already taken).
332   llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
333     GlobalValReplacements;
334 
335   /// Set of global decls for which we already diagnosed mangled name conflict.
336   /// Required to not issue a warning (on a mangling conflict) multiple times
337   /// for the same decl.
338   llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
339 
340   /// A queue of (optional) vtables to consider emitting.
341   std::vector<const CXXRecordDecl*> DeferredVTables;
342 
343   /// List of global values which are required to be present in the object file;
344   /// bitcast to i8*. This is used for forcing visibility of symbols which may
345   /// otherwise be optimized out.
346   std::vector<llvm::WeakVH> LLVMUsed;
347   std::vector<llvm::WeakVH> LLVMCompilerUsed;
348 
349   /// Store the list of global constructors and their respective priorities to
350   /// be emitted when the translation unit is complete.
351   CtorList GlobalCtors;
352 
353   /// Store the list of global destructors and their respective priorities to be
354   /// emitted when the translation unit is complete.
355   CtorList GlobalDtors;
356 
357   /// An ordered map of canonical GlobalDecls to their mangled names.
358   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
359   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
360 
361   /// Global annotations.
362   std::vector<llvm::Constant*> Annotations;
363 
364   /// Map used to get unique annotation strings.
365   llvm::StringMap<llvm::Constant*> AnnotationStrings;
366 
367   llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
368 
369   llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
370   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
371   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
372   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
373 
374   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
375   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
376 
377   /// Map used to get unique type descriptor constants for sanitizers.
378   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
379 
380   /// Map used to track internal linkage functions declared within
381   /// extern "C" regions.
382   typedef llvm::MapVector<IdentifierInfo *,
383                           llvm::GlobalValue *> StaticExternCMap;
384   StaticExternCMap StaticExternCValues;
385 
386   /// \brief thread_local variables defined or used in this TU.
387   std::vector<const VarDecl *> CXXThreadLocals;
388 
389   /// \brief thread_local variables with initializers that need to run
390   /// before any thread_local variable in this TU is odr-used.
391   std::vector<llvm::Function *> CXXThreadLocalInits;
392   std::vector<const VarDecl *> CXXThreadLocalInitVars;
393 
394   /// Global variables with initializers that need to run before main.
395   std::vector<llvm::Function *> CXXGlobalInits;
396 
397   /// When a C++ decl with an initializer is deferred, null is
398   /// appended to CXXGlobalInits, and the index of that null is placed
399   /// here so that the initializer will be performed in the correct
400   /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
401   /// that we don't re-emit the initializer.
402   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
403 
404   typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
405 
406   struct GlobalInitPriorityCmp {
407     bool operator()(const GlobalInitData &LHS,
408                     const GlobalInitData &RHS) const {
409       return LHS.first.priority < RHS.first.priority;
410     }
411   };
412 
413   /// Global variables with initializers whose order of initialization is set by
414   /// init_priority attribute.
415   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
416 
417   /// Global destructor functions and arguments that need to run on termination.
418   std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
419 
420   /// \brief The complete set of modules that has been imported.
421   llvm::SetVector<clang::Module *> ImportedModules;
422 
423   /// \brief A vector of metadata strings.
424   SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
425 
426   /// @name Cache for Objective-C runtime types
427   /// @{
428 
429   /// Cached reference to the class for constant strings. This value has type
430   /// int * but is actually an Obj-C class pointer.
431   llvm::WeakVH CFConstantStringClassRef;
432 
433   /// Cached reference to the class for constant strings. This value has type
434   /// int * but is actually an Obj-C class pointer.
435   llvm::WeakVH ConstantStringClassRef;
436 
437   /// \brief The LLVM type corresponding to NSConstantString.
438   llvm::StructType *NSConstantStringType = nullptr;
439 
440   /// \brief The type used to describe the state of a fast enumeration in
441   /// Objective-C's for..in loop.
442   QualType ObjCFastEnumerationStateType;
443 
444   /// @}
445 
446   /// Lazily create the Objective-C runtime
447   void createObjCRuntime();
448 
449   void createOpenCLRuntime();
450   void createOpenMPRuntime();
451   void createCUDARuntime();
452 
453   bool isTriviallyRecursive(const FunctionDecl *F);
454   bool shouldEmitFunction(GlobalDecl GD);
455 
456   /// @name Cache for Blocks Runtime Globals
457   /// @{
458 
459   llvm::Constant *NSConcreteGlobalBlock = nullptr;
460   llvm::Constant *NSConcreteStackBlock = nullptr;
461 
462   llvm::Constant *BlockObjectAssign = nullptr;
463   llvm::Constant *BlockObjectDispose = nullptr;
464 
465   llvm::Type *BlockDescriptorType = nullptr;
466   llvm::Type *GenericBlockLiteralType = nullptr;
467 
468   struct {
469     int GlobalUniqueCount;
470   } Block;
471 
472   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
473   llvm::Constant *LifetimeStartFn = nullptr;
474 
475   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
476   llvm::Constant *LifetimeEndFn = nullptr;
477 
478   GlobalDecl initializedGlobalDecl;
479 
480   std::unique_ptr<SanitizerMetadata> SanitizerMD;
481 
482   /// @}
483 
484   llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
485 
486   std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
487 
488   /// Mapping from canonical types to their metadata identifiers. We need to
489   /// maintain this mapping because identifiers may be formed from distinct
490   /// MDNodes.
491   llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
492 
493   SanitizerBlacklist WholeProgramVTablesBlacklist;
494 
495 public:
496   CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
497                 const PreprocessorOptions &ppopts,
498                 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
499                 DiagnosticsEngine &Diags,
500                 CoverageSourceInfo *CoverageInfo = nullptr);
501 
502   ~CodeGenModule();
503 
504   void clear();
505 
506   /// Finalize LLVM code generation.
507   void Release();
508 
509   /// Return a reference to the configured Objective-C runtime.
510   CGObjCRuntime &getObjCRuntime() {
511     if (!ObjCRuntime) createObjCRuntime();
512     return *ObjCRuntime;
513   }
514 
515   /// Return true iff an Objective-C runtime has been configured.
516   bool hasObjCRuntime() { return !!ObjCRuntime; }
517 
518   /// Return a reference to the configured OpenCL runtime.
519   CGOpenCLRuntime &getOpenCLRuntime() {
520     assert(OpenCLRuntime != nullptr);
521     return *OpenCLRuntime;
522   }
523 
524   /// Return a reference to the configured OpenMP runtime.
525   CGOpenMPRuntime &getOpenMPRuntime() {
526     assert(OpenMPRuntime != nullptr);
527     return *OpenMPRuntime;
528   }
529 
530   /// Return a reference to the configured CUDA runtime.
531   CGCUDARuntime &getCUDARuntime() {
532     assert(CUDARuntime != nullptr);
533     return *CUDARuntime;
534   }
535 
536   ObjCEntrypoints &getObjCEntrypoints() const {
537     assert(ObjCData != nullptr);
538     return *ObjCData;
539   }
540 
541   InstrProfStats &getPGOStats() { return PGOStats; }
542   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
543 
544   CoverageMappingModuleGen *getCoverageMapping() const {
545     return CoverageMapping.get();
546   }
547 
548   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
549     return StaticLocalDeclMap[D];
550   }
551   void setStaticLocalDeclAddress(const VarDecl *D,
552                                  llvm::Constant *C) {
553     StaticLocalDeclMap[D] = C;
554   }
555 
556   llvm::Constant *
557   getOrCreateStaticVarDecl(const VarDecl &D,
558                            llvm::GlobalValue::LinkageTypes Linkage);
559 
560   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
561     return StaticLocalDeclGuardMap[D];
562   }
563   void setStaticLocalDeclGuardAddress(const VarDecl *D,
564                                       llvm::GlobalVariable *C) {
565     StaticLocalDeclGuardMap[D] = C;
566   }
567 
568   bool lookupRepresentativeDecl(StringRef MangledName,
569                                 GlobalDecl &Result) const;
570 
571   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
572     return AtomicSetterHelperFnMap[Ty];
573   }
574   void setAtomicSetterHelperFnMap(QualType Ty,
575                             llvm::Constant *Fn) {
576     AtomicSetterHelperFnMap[Ty] = Fn;
577   }
578 
579   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
580     return AtomicGetterHelperFnMap[Ty];
581   }
582   void setAtomicGetterHelperFnMap(QualType Ty,
583                             llvm::Constant *Fn) {
584     AtomicGetterHelperFnMap[Ty] = Fn;
585   }
586 
587   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
588     return TypeDescriptorMap[Ty];
589   }
590   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
591     TypeDescriptorMap[Ty] = C;
592   }
593 
594   CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
595 
596   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
597     if (!NoObjCARCExceptionsMetadata)
598       NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
599     return NoObjCARCExceptionsMetadata;
600   }
601 
602   ASTContext &getContext() const { return Context; }
603   const LangOptions &getLangOpts() const { return LangOpts; }
604   const HeaderSearchOptions &getHeaderSearchOpts()
605     const { return HeaderSearchOpts; }
606   const PreprocessorOptions &getPreprocessorOpts()
607     const { return PreprocessorOpts; }
608   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
609   llvm::Module &getModule() const { return TheModule; }
610   DiagnosticsEngine &getDiags() const { return Diags; }
611   const llvm::DataLayout &getDataLayout() const {
612     return TheModule.getDataLayout();
613   }
614   const TargetInfo &getTarget() const { return Target; }
615   const llvm::Triple &getTriple() const;
616   bool supportsCOMDAT() const;
617   void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
618 
619   CGCXXABI &getCXXABI() const { return *ABI; }
620   llvm::LLVMContext &getLLVMContext() { return VMContext; }
621 
622   bool shouldUseTBAA() const { return TBAA != nullptr; }
623 
624   const TargetCodeGenInfo &getTargetCodeGenInfo();
625 
626   CodeGenTypes &getTypes() { return Types; }
627 
628   CodeGenVTables &getVTables() { return VTables; }
629 
630   ItaniumVTableContext &getItaniumVTableContext() {
631     return VTables.getItaniumVTableContext();
632   }
633 
634   MicrosoftVTableContext &getMicrosoftVTableContext() {
635     return VTables.getMicrosoftVTableContext();
636   }
637 
638   CtorList &getGlobalCtors() { return GlobalCtors; }
639   CtorList &getGlobalDtors() { return GlobalDtors; }
640 
641   llvm::MDNode *getTBAAInfo(QualType QTy);
642   llvm::MDNode *getTBAAInfoForVTablePtr();
643   llvm::MDNode *getTBAAStructInfo(QualType QTy);
644   /// Return the path-aware tag for given base type, access node and offset.
645   llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
646                                      uint64_t O);
647 
648   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
649 
650   bool isPaddedAtomicType(QualType type);
651   bool isPaddedAtomicType(const AtomicType *type);
652 
653   /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
654   /// is the same as the type. For struct-path aware TBAA, the tag
655   /// is different from the type: base type, access type and offset.
656   /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
657   void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
658                                    llvm::MDNode *TBAAInfo,
659                                    bool ConvertTypeToTag = true);
660 
661   /// Adds !invariant.barrier !tag to instruction
662   void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
663                                              const CXXRecordDecl *RD);
664 
665   /// Emit the given number of characters as a value of type size_t.
666   llvm::ConstantInt *getSize(CharUnits numChars);
667 
668   /// Set the visibility for the given LLVM GlobalValue.
669   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
670 
671   /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
672   /// variable declaration D.
673   void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
674 
675   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
676     switch (V) {
677     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
678     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
679     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
680     }
681     llvm_unreachable("unknown visibility!");
682   }
683 
684   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
685 
686   /// Will return a global variable of the given type. If a variable with a
687   /// different type already exists then a new  variable with the right type
688   /// will be created and all uses of the old variable will be replaced with a
689   /// bitcast to the new variable.
690   llvm::GlobalVariable *
691   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
692                                     llvm::GlobalValue::LinkageTypes Linkage);
693 
694   llvm::Function *
695   CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
696                                      const CGFunctionInfo &FI,
697                                      SourceLocation Loc = SourceLocation(),
698                                      bool TLS = false);
699 
700   /// Return the address space of the underlying global variable for D, as
701   /// determined by its declaration. Normally this is the same as the address
702   /// space of D's type, but in CUDA, address spaces are associated with
703   /// declarations, not types.
704   unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
705 
706   /// Return the llvm::Constant for the address of the given global variable.
707   /// If Ty is non-null and if the global doesn't exist, then it will be created
708   /// with the specified type instead of whatever the normal requested type
709   /// would be. If IsForDefinition is true, it is guranteed that an actual
710   /// global with type Ty will be returned, not conversion of a variable with
711   /// the same mangled name but some other type.
712   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
713                                      llvm::Type *Ty = nullptr,
714                                      bool IsForDefinition = false);
715 
716   /// Return the address of the given function. If Ty is non-null, then this
717   /// function will use the specified type if it has to create it.
718   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
719                                     bool ForVTable = false,
720                                     bool DontDefer = false,
721                                     bool IsForDefinition = false);
722 
723   /// Get the address of the RTTI descriptor for the given type.
724   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
725 
726   /// Get the address of a uuid descriptor .
727   ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
728 
729   /// Get the address of the thunk for the given global decl.
730   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
731 
732   /// Get a reference to the target of VD.
733   ConstantAddress GetWeakRefReference(const ValueDecl *VD);
734 
735   /// Returns the assumed alignment of an opaque pointer to the given class.
736   CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
737 
738   /// Returns the assumed alignment of a virtual base of a class.
739   CharUnits getVBaseAlignment(CharUnits DerivedAlign,
740                               const CXXRecordDecl *Derived,
741                               const CXXRecordDecl *VBase);
742 
743   /// Given a class pointer with an actual known alignment, and the
744   /// expected alignment of an object at a dynamic offset w.r.t that
745   /// pointer, return the alignment to assume at the offset.
746   CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
747                                       const CXXRecordDecl *Class,
748                                       CharUnits ExpectedTargetAlign);
749 
750   CharUnits
751   computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
752                                    CastExpr::path_const_iterator Start,
753                                    CastExpr::path_const_iterator End);
754 
755   /// Returns the offset from a derived class to  a class. Returns null if the
756   /// offset is 0.
757   llvm::Constant *
758   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
759                                CastExpr::path_const_iterator PathBegin,
760                                CastExpr::path_const_iterator PathEnd);
761 
762   llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
763 
764   /// Fetches the global unique block count.
765   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
766 
767   /// Fetches the type of a generic block descriptor.
768   llvm::Type *getBlockDescriptorType();
769 
770   /// The type of a generic block literal.
771   llvm::Type *getGenericBlockLiteralType();
772 
773   /// Gets the address of a block which requires no captures.
774   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
775 
776   /// Return a pointer to a constant CFString object for the given string.
777   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
778 
779   /// Return a pointer to a constant NSString object for the given string. Or a
780   /// user defined String object as defined via
781   /// -fconstant-string-class=class_name option.
782   ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
783 
784   /// Return a constant array for the given string.
785   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
786 
787   /// Return a pointer to a constant array for the given string literal.
788   ConstantAddress
789   GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
790                                      StringRef Name = ".str");
791 
792   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
793   ConstantAddress
794   GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
795 
796   /// Returns a pointer to a character array containing the literal and a
797   /// terminating '\0' character. The result has pointer to array type.
798   ///
799   /// \param GlobalName If provided, the name to use for the global (if one is
800   /// created).
801   ConstantAddress
802   GetAddrOfConstantCString(const std::string &Str,
803                            const char *GlobalName = nullptr);
804 
805   /// Returns a pointer to a constant global variable for the given file-scope
806   /// compound literal expression.
807   ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
808 
809   /// \brief Returns a pointer to a global variable representing a temporary
810   /// with static or thread storage duration.
811   ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
812                                            const Expr *Inner);
813 
814   /// \brief Retrieve the record type that describes the state of an
815   /// Objective-C fast enumeration loop (for..in).
816   QualType getObjCFastEnumerationStateType();
817 
818   // Produce code for this constructor/destructor. This method doesn't try
819   // to apply any ABI rules about which other constructors/destructors
820   // are needed or if they are alias to each other.
821   llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
822                                      StructorType Type);
823 
824   /// Return the address of the constructor/destructor of the given type.
825   llvm::Constant *
826   getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
827                        const CGFunctionInfo *FnInfo = nullptr,
828                        llvm::FunctionType *FnType = nullptr,
829                        bool DontDefer = false, bool IsForDefinition = false);
830 
831   /// Given a builtin id for a function like "__builtin_fabsf", return a
832   /// Function* for "fabsf".
833   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
834                                      unsigned BuiltinID);
835 
836   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
837 
838   /// Emit code for a single top level declaration.
839   void EmitTopLevelDecl(Decl *D);
840 
841   /// \brief Stored a deferred empty coverage mapping for an unused
842   /// and thus uninstrumented top level declaration.
843   void AddDeferredUnusedCoverageMapping(Decl *D);
844 
845   /// \brief Remove the deferred empty coverage mapping as this
846   /// declaration is actually instrumented.
847   void ClearUnusedCoverageMapping(const Decl *D);
848 
849   /// \brief Emit all the deferred coverage mappings
850   /// for the uninstrumented functions.
851   void EmitDeferredUnusedCoverageMappings();
852 
853   /// Tell the consumer that this variable has been instantiated.
854   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
855 
856   /// \brief If the declaration has internal linkage but is inside an
857   /// extern "C" linkage specification, prepare to emit an alias for it
858   /// to the expected name.
859   template<typename SomeDecl>
860   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
861 
862   /// Add a global to a list to be added to the llvm.used metadata.
863   void addUsedGlobal(llvm::GlobalValue *GV);
864 
865   /// Add a global to a list to be added to the llvm.compiler.used metadata.
866   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
867 
868   /// Add a destructor and object to add to the C++ global destructor function.
869   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
870     CXXGlobalDtors.emplace_back(DtorFn, Object);
871   }
872 
873   /// Create a new runtime function with the specified type and name.
874   llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
875                                         StringRef Name,
876                                         llvm::AttributeSet ExtraAttrs =
877                                           llvm::AttributeSet());
878   /// Create a new compiler builtin function with the specified type and name.
879   llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
880                                         StringRef Name,
881                                         llvm::AttributeSet ExtraAttrs =
882                                           llvm::AttributeSet());
883   /// Create a new runtime global variable with the specified type and name.
884   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
885                                         StringRef Name);
886 
887   ///@name Custom Blocks Runtime Interfaces
888   ///@{
889 
890   llvm::Constant *getNSConcreteGlobalBlock();
891   llvm::Constant *getNSConcreteStackBlock();
892   llvm::Constant *getBlockObjectAssign();
893   llvm::Constant *getBlockObjectDispose();
894 
895   ///@}
896 
897   llvm::Constant *getLLVMLifetimeStartFn();
898   llvm::Constant *getLLVMLifetimeEndFn();
899 
900   // Make sure that this type is translated.
901   void UpdateCompletedType(const TagDecl *TD);
902 
903   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
904 
905   /// Try to emit the initializer for the given declaration as a constant;
906   /// returns 0 if the expression cannot be emitted as a constant.
907   llvm::Constant *EmitConstantInit(const VarDecl &D,
908                                    CodeGenFunction *CGF = nullptr);
909 
910   /// Try to emit the given expression as a constant; returns 0 if the
911   /// expression cannot be emitted as a constant.
912   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
913                                    CodeGenFunction *CGF = nullptr);
914 
915   /// Emit the given constant value as a constant, in the type's scalar
916   /// representation.
917   llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
918                                     CodeGenFunction *CGF = nullptr);
919 
920   /// Emit the given constant value as a constant, in the type's memory
921   /// representation.
922   llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
923                                              QualType DestType,
924                                              CodeGenFunction *CGF = nullptr);
925 
926   /// \brief Emit type info if type of an expression is a variably modified
927   /// type. Also emit proper debug info for cast types.
928   void EmitExplicitCastExprType(const ExplicitCastExpr *E,
929                                 CodeGenFunction *CGF = nullptr);
930 
931   /// Return the result of value-initializing the given type, i.e. a null
932   /// expression of the given type.  This is usually, but not always, an LLVM
933   /// null constant.
934   llvm::Constant *EmitNullConstant(QualType T);
935 
936   /// Return a null constant appropriate for zero-initializing a base class with
937   /// the given type. This is usually, but not always, an LLVM null constant.
938   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
939 
940   /// Emit a general error that something can't be done.
941   void Error(SourceLocation loc, StringRef error);
942 
943   /// Print out an error that codegen doesn't support the specified stmt yet.
944   void ErrorUnsupported(const Stmt *S, const char *Type);
945 
946   /// Print out an error that codegen doesn't support the specified decl yet.
947   void ErrorUnsupported(const Decl *D, const char *Type);
948 
949   /// Set the attributes on the LLVM function for the given decl and function
950   /// info. This applies attributes necessary for handling the ABI as well as
951   /// user specified attributes like section.
952   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
953                                      const CGFunctionInfo &FI);
954 
955   /// Set the LLVM function attributes (sext, zext, etc).
956   void SetLLVMFunctionAttributes(const Decl *D,
957                                  const CGFunctionInfo &Info,
958                                  llvm::Function *F);
959 
960   /// Set the LLVM function attributes which only apply to a function
961   /// definition.
962   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
963 
964   /// Return true iff the given type uses 'sret' when used as a return type.
965   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
966 
967   /// Return true iff the given type uses an argument slot when 'sret' is used
968   /// as a return type.
969   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
970 
971   /// Return true iff the given type uses 'fpret' when used as a return type.
972   bool ReturnTypeUsesFPRet(QualType ResultType);
973 
974   /// Return true iff the given type uses 'fp2ret' when used as a return type.
975   bool ReturnTypeUsesFP2Ret(QualType ResultType);
976 
977   /// Get the LLVM attributes and calling convention to use for a particular
978   /// function type.
979   ///
980   /// \param Name - The function name.
981   /// \param Info - The function type information.
982   /// \param CalleeInfo - The callee information these attributes are being
983   /// constructed for. If valid, the attributes applied to this decl may
984   /// contribute to the function attributes and calling convention.
985   /// \param PAL [out] - On return, the attribute list to use.
986   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
987   void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
988                               CGCalleeInfo CalleeInfo, AttributeListType &PAL,
989                               unsigned &CallingConv, bool AttrOnCallSite);
990 
991   // Fills in the supplied string map with the set of target features for the
992   // passed in function.
993   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
994                              const FunctionDecl *FD);
995 
996   StringRef getMangledName(GlobalDecl GD);
997   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
998 
999   void EmitTentativeDefinition(const VarDecl *D);
1000 
1001   void EmitVTable(CXXRecordDecl *Class);
1002 
1003   void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1004 
1005   /// \brief Appends Opts to the "Linker Options" metadata value.
1006   void AppendLinkerOptions(StringRef Opts);
1007 
1008   /// \brief Appends a detect mismatch command to the linker options.
1009   void AddDetectMismatch(StringRef Name, StringRef Value);
1010 
1011   /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1012   void AddDependentLib(StringRef Lib);
1013 
1014   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1015 
1016   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1017     F->setLinkage(getFunctionLinkage(GD));
1018   }
1019 
1020   /// Set the DLL storage class on F.
1021   void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1022 
1023   /// Return the appropriate linkage for the vtable, VTT, and type information
1024   /// of the given class.
1025   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1026 
1027   /// Return the store size, in character units, of the given LLVM type.
1028   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1029 
1030   /// Returns LLVM linkage for a declarator.
1031   llvm::GlobalValue::LinkageTypes
1032   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1033                               bool IsConstantVariable);
1034 
1035   /// Returns LLVM linkage for a declarator.
1036   llvm::GlobalValue::LinkageTypes
1037   getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1038 
1039   /// Emit all the global annotations.
1040   void EmitGlobalAnnotations();
1041 
1042   /// Emit an annotation string.
1043   llvm::Constant *EmitAnnotationString(StringRef Str);
1044 
1045   /// Emit the annotation's translation unit.
1046   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1047 
1048   /// Emit the annotation line number.
1049   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1050 
1051   /// Generate the llvm::ConstantStruct which contains the annotation
1052   /// information for a given GlobalValue. The annotation struct is
1053   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1054   /// GlobalValue being annotated. The second field is the constant string
1055   /// created from the AnnotateAttr's annotation. The third field is a constant
1056   /// string containing the name of the translation unit. The fourth field is
1057   /// the line number in the file of the annotated value declaration.
1058   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1059                                    const AnnotateAttr *AA,
1060                                    SourceLocation L);
1061 
1062   /// Add global annotations that are set on D, for the global GV. Those
1063   /// annotations are emitted during finalization of the LLVM code.
1064   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1065 
1066   bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1067 
1068   bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1069                               QualType Ty,
1070                               StringRef Category = StringRef()) const;
1071 
1072   SanitizerMetadata *getSanitizerMetadata() {
1073     return SanitizerMD.get();
1074   }
1075 
1076   void addDeferredVTable(const CXXRecordDecl *RD) {
1077     DeferredVTables.push_back(RD);
1078   }
1079 
1080   /// Emit code for a singal global function or var decl. Forward declarations
1081   /// are emitted lazily.
1082   void EmitGlobal(GlobalDecl D);
1083 
1084   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1085                                 bool InEveryTU);
1086   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1087 
1088   /// Set attributes for a global definition.
1089   void setFunctionDefinitionAttributes(const FunctionDecl *D,
1090                                        llvm::Function *F);
1091 
1092   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1093 
1094   /// Set attributes which are common to any form of a global definition (alias,
1095   /// Objective-C method, function, global variable).
1096   ///
1097   /// NOTE: This should only be called for definitions.
1098   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1099 
1100   /// Set attributes which must be preserved by an alias. This includes common
1101   /// attributes (i.e. it includes a call to SetCommonAttributes).
1102   ///
1103   /// NOTE: This should only be called for definitions.
1104   void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1105 
1106   void addReplacement(StringRef Name, llvm::Constant *C);
1107 
1108   void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1109 
1110   /// \brief Emit a code for threadprivate directive.
1111   /// \param D Threadprivate declaration.
1112   void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1113 
1114   /// \brief Emit a code for declare reduction construct.
1115   void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1116                                CodeGenFunction *CGF = nullptr);
1117 
1118   /// Returns whether we need bit sets attached to vtables.
1119   bool NeedVTableBitSets();
1120 
1121   /// Returns whether the given record is blacklisted from whole-program
1122   /// transformations (i.e. CFI or whole-program vtable optimization).
1123   bool IsBitSetBlacklistedRecord(const CXXRecordDecl *RD);
1124 
1125   /// Emit bit set entries for the given vtable using the given layout if
1126   /// vptr CFI is enabled.
1127   void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1128                                const VTableLayout &VTLayout);
1129 
1130   /// Generate a cross-DSO type identifier for type.
1131   llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
1132 
1133   /// Create a metadata identifier for the given type. This may either be an
1134   /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1135   /// internal identifiers).
1136   llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1137 
1138   /// Create a bitset entry for the given function and add it to BitsetsMD.
1139   void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
1140 
1141   /// Returns whether this module needs the "all-vtables" bitset.
1142   bool NeedAllVtablesBitSet() const;
1143 
1144   /// Create a bitset entry for the given vtable and add it to BitsetsMD.
1145   void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
1146                                llvm::GlobalVariable *VTable, CharUnits Offset,
1147                                const CXXRecordDecl *RD);
1148 
1149   /// \breif Get the declaration of std::terminate for the platform.
1150   llvm::Constant *getTerminateFn();
1151 
1152   llvm::SanitizerStatReport &getSanStats();
1153 
1154 private:
1155   llvm::Constant *
1156   GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1157                           bool ForVTable, bool DontDefer = false,
1158                           bool IsThunk = false,
1159                           llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
1160                           bool IsForDefinition = false);
1161 
1162   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1163                                         llvm::PointerType *PTy,
1164                                         const VarDecl *D,
1165                                         bool IsForDefinition = false);
1166 
1167   void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1168 
1169   /// Set function attributes for a function declaration.
1170   void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1171                              bool IsIncompleteFunction, bool IsThunk);
1172 
1173   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1174 
1175   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1176   void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1177   void EmitAliasDefinition(GlobalDecl GD);
1178   void emitIFuncDefinition(GlobalDecl GD);
1179   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1180   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1181 
1182   // C++ related functions.
1183 
1184   void EmitNamespace(const NamespaceDecl *D);
1185   void EmitLinkageSpec(const LinkageSpecDecl *D);
1186   void CompleteDIClassType(const CXXMethodDecl* D);
1187 
1188   /// \brief Emit the function that initializes C++ thread_local variables.
1189   void EmitCXXThreadLocalInitFunc();
1190 
1191   /// Emit the function that initializes C++ globals.
1192   void EmitCXXGlobalInitFunc();
1193 
1194   /// Emit the function that destroys C++ globals.
1195   void EmitCXXGlobalDtorFunc();
1196 
1197   /// Emit the function that initializes the specified global (if PerformInit is
1198   /// true) and registers its destructor.
1199   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1200                                     llvm::GlobalVariable *Addr,
1201                                     bool PerformInit);
1202 
1203   void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1204                              llvm::Function *InitFunc, InitSegAttr *ISA);
1205 
1206   // FIXME: Hardcoding priority here is gross.
1207   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1208                      llvm::Constant *AssociatedData = nullptr);
1209   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1210 
1211   /// Generates a global array of functions and priorities using the given list
1212   /// and name. This array will have appending linkage and is suitable for use
1213   /// as a LLVM constructor or destructor array.
1214   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1215 
1216   /// Emit any needed decls for which code generation was deferred.
1217   void EmitDeferred();
1218 
1219   /// Call replaceAllUsesWith on all pairs in Replacements.
1220   void applyReplacements();
1221 
1222   /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1223   void applyGlobalValReplacements();
1224 
1225   void checkAliases();
1226 
1227   /// Emit any vtables which we deferred and still have a use for.
1228   void EmitDeferredVTables();
1229 
1230   /// Emit the llvm.used and llvm.compiler.used metadata.
1231   void emitLLVMUsed();
1232 
1233   /// \brief Emit the link options introduced by imported modules.
1234   void EmitModuleLinkOptions();
1235 
1236   /// \brief Emit aliases for internal-linkage declarations inside "C" language
1237   /// linkage specifications, giving them the "expected" name where possible.
1238   void EmitStaticExternCAliases();
1239 
1240   void EmitDeclMetadata();
1241 
1242   /// \brief Emit the Clang version as llvm.ident metadata.
1243   void EmitVersionIdentMetadata();
1244 
1245   /// Emits target specific Metadata for global declarations.
1246   void EmitTargetMetadata();
1247 
1248   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1249   /// .gcda files in a way that persists in .bc files.
1250   void EmitCoverageFile();
1251 
1252   /// Emits the initializer for a uuidof string.
1253   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1254 
1255   /// Determine whether the definition must be emitted; if this returns \c
1256   /// false, the definition can be emitted lazily if it's used.
1257   bool MustBeEmitted(const ValueDecl *D);
1258 
1259   /// Determine whether the definition can be emitted eagerly, or should be
1260   /// delayed until the end of the translation unit. This is relevant for
1261   /// definitions whose linkage can change, e.g. implicit function instantions
1262   /// which may later be explicitly instantiated.
1263   bool MayBeEmittedEagerly(const ValueDecl *D);
1264 
1265   /// Check whether we can use a "simpler", more core exceptions personality
1266   /// function.
1267   void SimplifyPersonality();
1268 };
1269 }  // end namespace CodeGen
1270 }  // end namespace clang
1271 
1272 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
1273