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