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