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