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