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