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