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