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