1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This is the internal per-translation-unit state used for llvm translation.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
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"
48 class IndexedInstrProfReader;
57 class ObjCImplementationDecl;
58 class ObjCCategoryImplDecl;
59 class ObjCProtocolDecl;
73 class HeaderSearchOptions;
74 class PreprocessorOptions;
75 class DiagnosticsEngine;
77 class CXXDestructorDecl;
79 class CoverageSourceInfo;
84 class CodeGenFunction;
89 class CGOpenCLRuntime;
90 class CGOpenMPRuntime;
92 class BlockFieldFlags;
93 class FunctionArgList;
94 class CoverageMappingModuleGen;
95 class TargetCodeGenInfo;
97 enum ForDefinition_t : bool {
98 NotForDefinition = false,
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) {}
108 bool operator==(const OrderGlobalInits &RHS) const {
109 return priority == RHS.priority && lex_order == RHS.lex_order;
112 bool operator<(const OrderGlobalInits &RHS) const {
113 return std::tie(priority, lex_order) <
114 std::tie(RHS.priority, RHS.lex_order);
118 struct ObjCEntrypoints {
119 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
121 /// void objc_alloc(id);
122 llvm::FunctionCallee objc_alloc;
124 /// void objc_allocWithZone(id);
125 llvm::FunctionCallee objc_allocWithZone;
127 /// void objc_alloc_init(id);
128 llvm::FunctionCallee objc_alloc_init;
130 /// void objc_autoreleasePoolPop(void*);
131 llvm::FunctionCallee objc_autoreleasePoolPop;
133 /// void objc_autoreleasePoolPop(void*);
134 /// Note this method is used when we are using exception handling
135 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
137 /// void *objc_autoreleasePoolPush(void);
138 llvm::Function *objc_autoreleasePoolPush;
140 /// id objc_autorelease(id);
141 llvm::Function *objc_autorelease;
143 /// id objc_autorelease(id);
144 /// Note this is the runtime method not the intrinsic.
145 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
147 /// id objc_autoreleaseReturnValue(id);
148 llvm::Function *objc_autoreleaseReturnValue;
150 /// void objc_copyWeak(id *dest, id *src);
151 llvm::Function *objc_copyWeak;
153 /// void objc_destroyWeak(id*);
154 llvm::Function *objc_destroyWeak;
156 /// id objc_initWeak(id*, id);
157 llvm::Function *objc_initWeak;
159 /// id objc_loadWeak(id*);
160 llvm::Function *objc_loadWeak;
162 /// id objc_loadWeakRetained(id*);
163 llvm::Function *objc_loadWeakRetained;
165 /// void objc_moveWeak(id *dest, id *src);
166 llvm::Function *objc_moveWeak;
168 /// id objc_retain(id);
169 llvm::Function *objc_retain;
171 /// id objc_retain(id);
172 /// Note this is the runtime method not the intrinsic.
173 llvm::FunctionCallee objc_retainRuntimeFunction;
175 /// id objc_retainAutorelease(id);
176 llvm::Function *objc_retainAutorelease;
178 /// id objc_retainAutoreleaseReturnValue(id);
179 llvm::Function *objc_retainAutoreleaseReturnValue;
181 /// id objc_retainAutoreleasedReturnValue(id);
182 llvm::Function *objc_retainAutoreleasedReturnValue;
184 /// id objc_retainBlock(id);
185 llvm::Function *objc_retainBlock;
187 /// void objc_release(id);
188 llvm::Function *objc_release;
190 /// void objc_release(id);
191 /// Note this is the runtime method not the intrinsic.
192 llvm::FunctionCallee objc_releaseRuntimeFunction;
194 /// void objc_storeStrong(id*, id);
195 llvm::Function *objc_storeStrong;
197 /// id objc_storeWeak(id*, id);
198 llvm::Function *objc_storeWeak;
200 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
201 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
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;
207 /// void clang.arc.use(...);
208 llvm::Function *clang_arc_use;
211 /// This class records statistics on instrumentation based profiling.
212 class InstrProfStats {
213 uint32_t VisitedInMainFile;
214 uint32_t MissingInMainFile;
221 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(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) {
230 /// Record that a function we've visited has no profile data.
231 void addMissing(bool MainFile) {
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);
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
249 llvm::Constant *CopyHelper;
250 llvm::Constant *DisposeHelper;
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.
257 BlockByrefHelpers(CharUnits alignment)
258 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
259 BlockByrefHelpers(const BlockByrefHelpers &) = default;
260 virtual ~BlockByrefHelpers();
262 void Profile(llvm::FoldingSetNodeID &id) const {
263 id.AddInteger(Alignment.getQuantity());
266 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
268 virtual bool needsCopy() const { return true; }
269 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
271 virtual bool needsDispose() const { return true; }
272 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
275 /// This class organizes the cross-function state that is used while generating
277 class CodeGenModule : public CodeGenTypeCache {
278 CodeGenModule(const CodeGenModule &) = delete;
279 void operator=(const CodeGenModule &) = delete;
283 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
284 Structor(int Priority, llvm::Constant *Initializer,
285 llvm::Constant *AssociatedData)
286 : Priority(Priority), Initializer(Initializer),
287 AssociatedData(AssociatedData) {}
289 llvm::Constant *Initializer;
290 llvm::Constant *AssociatedData;
293 typedef std::vector<Structor> CtorList;
297 const LangOptions &LangOpts;
298 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
299 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
300 const CodeGenOptions &CodeGenOpts;
301 llvm::Module &TheModule;
302 DiagnosticsEngine &Diags;
303 const TargetInfo &Target;
304 std::unique_ptr<CGCXXABI> ABI;
305 llvm::LLVMContext &VMContext;
307 std::unique_ptr<CodeGenTBAA> TBAA;
309 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
311 // This should not be moved earlier, since its initialization depends on some
312 // of the previous reference members being already initialized and also checks
313 // if TheTargetCodeGenInfo is NULL
316 /// Holds information about C++ vtables.
317 CodeGenVTables VTables;
319 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
320 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
321 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
322 std::unique_ptr<CGCUDARuntime> CUDARuntime;
323 std::unique_ptr<CGDebugInfo> DebugInfo;
324 std::unique_ptr<ObjCEntrypoints> ObjCData;
325 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
326 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
327 InstrProfStats PGOStats;
328 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
330 // A set of references that have only been seen via a weakref so far. This is
331 // used to remove the weak of the reference if we ever see a direct reference
333 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
335 /// This contains all the decls which have definitions but/ which are deferred
336 /// for emission and therefore should only be output if they are actually
337 /// used. If a decl is in this, then it is known to have not been referenced
339 std::map<StringRef, GlobalDecl> DeferredDecls;
341 /// This is a list of deferred decls which we have seen that *are* actually
342 /// referenced. These get code generated when the module is done.
343 std::vector<GlobalDecl> DeferredDeclsToEmit;
344 void addDeferredDeclToEmit(GlobalDecl GD) {
345 DeferredDeclsToEmit.emplace_back(GD);
348 /// List of alias we have emitted. Used to make sure that what they point to
349 /// is defined once we get to the end of the of the translation unit.
350 std::vector<GlobalDecl> Aliases;
352 /// List of multiversion functions that have to be emitted. Used to make sure
353 /// we properly emit the iFunc.
354 std::vector<GlobalDecl> MultiVersionFuncs;
356 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
357 ReplacementsTy Replacements;
359 /// List of global values to be replaced with something else. Used when we
360 /// want to replace a GlobalValue but can't identify it by its mangled name
361 /// anymore (because the name is already taken).
362 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
363 GlobalValReplacements;
365 /// Variables for which we've emitted globals containing their constant
366 /// values along with the corresponding globals, for opportunistic reuse.
367 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
369 /// Set of global decls for which we already diagnosed mangled name conflict.
370 /// Required to not issue a warning (on a mangling conflict) multiple times
371 /// for the same decl.
372 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
374 /// A queue of (optional) vtables to consider emitting.
375 std::vector<const CXXRecordDecl*> DeferredVTables;
377 /// A queue of (optional) vtables that may be emitted opportunistically.
378 std::vector<const CXXRecordDecl *> OpportunisticVTables;
380 /// List of global values which are required to be present in the object file;
381 /// bitcast to i8*. This is used for forcing visibility of symbols which may
382 /// otherwise be optimized out.
383 std::vector<llvm::WeakTrackingVH> LLVMUsed;
384 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
386 /// Store the list of global constructors and their respective priorities to
387 /// be emitted when the translation unit is complete.
388 CtorList GlobalCtors;
390 /// Store the list of global destructors and their respective priorities to be
391 /// emitted when the translation unit is complete.
392 CtorList GlobalDtors;
394 /// An ordered map of canonical GlobalDecls to their mangled names.
395 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
396 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
398 // An ordered map of canonical GlobalDecls paired with the cpu-index for
399 // cpu-specific name manglings.
400 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef>
401 CPUSpecificMangledDeclNames;
402 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator>
403 CPUSpecificManglings;
405 /// Global annotations.
406 std::vector<llvm::Constant*> Annotations;
408 /// Map used to get unique annotation strings.
409 llvm::StringMap<llvm::Constant*> AnnotationStrings;
411 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
413 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
414 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
415 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
416 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
418 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
419 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
421 /// Map used to get unique type descriptor constants for sanitizers.
422 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
424 /// Map used to track internal linkage functions declared within
425 /// extern "C" regions.
426 typedef llvm::MapVector<IdentifierInfo *,
427 llvm::GlobalValue *> StaticExternCMap;
428 StaticExternCMap StaticExternCValues;
430 /// thread_local variables defined or used in this TU.
431 std::vector<const VarDecl *> CXXThreadLocals;
433 /// thread_local variables with initializers that need to run
434 /// before any thread_local variable in this TU is odr-used.
435 std::vector<llvm::Function *> CXXThreadLocalInits;
436 std::vector<const VarDecl *> CXXThreadLocalInitVars;
438 /// Global variables with initializers that need to run before main.
439 std::vector<llvm::Function *> CXXGlobalInits;
441 /// When a C++ decl with an initializer is deferred, null is
442 /// appended to CXXGlobalInits, and the index of that null is placed
443 /// here so that the initializer will be performed in the correct
444 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
445 /// that we don't re-emit the initializer.
446 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
448 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
450 struct GlobalInitPriorityCmp {
451 bool operator()(const GlobalInitData &LHS,
452 const GlobalInitData &RHS) const {
453 return LHS.first.priority < RHS.first.priority;
457 /// Global variables with initializers whose order of initialization is set by
458 /// init_priority attribute.
459 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
461 /// Global destructor functions and arguments that need to run on termination.
463 std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>>
466 /// The complete set of modules that has been imported.
467 llvm::SetVector<clang::Module *> ImportedModules;
469 /// The set of modules for which the module initializers
470 /// have been emitted.
471 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
473 /// A vector of metadata strings for linker options.
474 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
476 /// A vector of metadata strings for dependent libraries for ELF.
477 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
479 /// @name Cache for Objective-C runtime types
482 /// Cached reference to the class for constant strings. This value has type
483 /// int * but is actually an Obj-C class pointer.
484 llvm::WeakTrackingVH CFConstantStringClassRef;
486 /// The type used to describe the state of a fast enumeration in
487 /// Objective-C's for..in loop.
488 QualType ObjCFastEnumerationStateType;
492 /// Lazily create the Objective-C runtime
493 void createObjCRuntime();
495 void createOpenCLRuntime();
496 void createOpenMPRuntime();
497 void createCUDARuntime();
499 bool isTriviallyRecursive(const FunctionDecl *F);
500 bool shouldEmitFunction(GlobalDecl GD);
501 bool shouldOpportunisticallyEmitVTables();
502 /// Map used to be sure we don't emit the same CompoundLiteral twice.
503 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
504 EmittedCompoundLiterals;
506 /// Map of the global blocks we've emitted, so that we don't have to re-emit
507 /// them if the constexpr evaluator gets aggressive.
508 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
510 /// @name Cache for Blocks Runtime Globals
513 llvm::Constant *NSConcreteGlobalBlock = nullptr;
514 llvm::Constant *NSConcreteStackBlock = nullptr;
516 llvm::FunctionCallee BlockObjectAssign = nullptr;
517 llvm::FunctionCallee BlockObjectDispose = nullptr;
519 llvm::Type *BlockDescriptorType = nullptr;
520 llvm::Type *GenericBlockLiteralType = nullptr;
523 int GlobalUniqueCount;
526 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
527 llvm::Function *LifetimeStartFn = nullptr;
529 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
530 llvm::Function *LifetimeEndFn = nullptr;
532 GlobalDecl initializedGlobalDecl;
534 std::unique_ptr<SanitizerMetadata> SanitizerMD;
538 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
540 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
542 /// Mapping from canonical types to their metadata identifiers. We need to
543 /// maintain this mapping because identifiers may be formed from distinct
545 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
546 MetadataTypeMap MetadataIdMap;
547 MetadataTypeMap VirtualMetadataIdMap;
548 MetadataTypeMap GeneralizedMetadataIdMap;
551 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
552 const PreprocessorOptions &ppopts,
553 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
554 DiagnosticsEngine &Diags,
555 CoverageSourceInfo *CoverageInfo = nullptr);
561 /// Finalize LLVM code generation.
564 /// Return true if we should emit location information for expressions.
565 bool getExpressionLocationsEnabled() const;
567 /// Return a reference to the configured Objective-C runtime.
568 CGObjCRuntime &getObjCRuntime() {
569 if (!ObjCRuntime) createObjCRuntime();
573 /// Return true iff an Objective-C runtime has been configured.
574 bool hasObjCRuntime() { return !!ObjCRuntime; }
576 /// Return a reference to the configured OpenCL runtime.
577 CGOpenCLRuntime &getOpenCLRuntime() {
578 assert(OpenCLRuntime != nullptr);
579 return *OpenCLRuntime;
582 /// Return a reference to the configured OpenMP runtime.
583 CGOpenMPRuntime &getOpenMPRuntime() {
584 assert(OpenMPRuntime != nullptr);
585 return *OpenMPRuntime;
588 /// Return a reference to the configured CUDA runtime.
589 CGCUDARuntime &getCUDARuntime() {
590 assert(CUDARuntime != nullptr);
594 ObjCEntrypoints &getObjCEntrypoints() const {
595 assert(ObjCData != nullptr);
599 // Version checking function, used to implement ObjC's @available:
600 // i32 @__isOSVersionAtLeast(i32, i32, i32)
601 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
603 InstrProfStats &getPGOStats() { return PGOStats; }
604 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
606 CoverageMappingModuleGen *getCoverageMapping() const {
607 return CoverageMapping.get();
610 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
611 return StaticLocalDeclMap[D];
613 void setStaticLocalDeclAddress(const VarDecl *D,
615 StaticLocalDeclMap[D] = C;
619 getOrCreateStaticVarDecl(const VarDecl &D,
620 llvm::GlobalValue::LinkageTypes Linkage);
622 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
623 return StaticLocalDeclGuardMap[D];
625 void setStaticLocalDeclGuardAddress(const VarDecl *D,
626 llvm::GlobalVariable *C) {
627 StaticLocalDeclGuardMap[D] = C;
630 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
633 bool lookupRepresentativeDecl(StringRef MangledName,
634 GlobalDecl &Result) const;
636 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
637 return AtomicSetterHelperFnMap[Ty];
639 void setAtomicSetterHelperFnMap(QualType Ty,
640 llvm::Constant *Fn) {
641 AtomicSetterHelperFnMap[Ty] = Fn;
644 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
645 return AtomicGetterHelperFnMap[Ty];
647 void setAtomicGetterHelperFnMap(QualType Ty,
648 llvm::Constant *Fn) {
649 AtomicGetterHelperFnMap[Ty] = Fn;
652 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
653 return TypeDescriptorMap[Ty];
655 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
656 TypeDescriptorMap[Ty] = C;
659 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
661 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
662 if (!NoObjCARCExceptionsMetadata)
663 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
664 return NoObjCARCExceptionsMetadata;
667 ASTContext &getContext() const { return Context; }
668 const LangOptions &getLangOpts() const { return LangOpts; }
669 const HeaderSearchOptions &getHeaderSearchOpts()
670 const { return HeaderSearchOpts; }
671 const PreprocessorOptions &getPreprocessorOpts()
672 const { return PreprocessorOpts; }
673 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
674 llvm::Module &getModule() const { return TheModule; }
675 DiagnosticsEngine &getDiags() const { return Diags; }
676 const llvm::DataLayout &getDataLayout() const {
677 return TheModule.getDataLayout();
679 const TargetInfo &getTarget() const { return Target; }
680 const llvm::Triple &getTriple() const { return Target.getTriple(); }
681 bool supportsCOMDAT() const;
682 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
684 CGCXXABI &getCXXABI() const { return *ABI; }
685 llvm::LLVMContext &getLLVMContext() { return VMContext; }
687 bool shouldUseTBAA() const { return TBAA != nullptr; }
689 const TargetCodeGenInfo &getTargetCodeGenInfo();
691 CodeGenTypes &getTypes() { return Types; }
693 CodeGenVTables &getVTables() { return VTables; }
695 ItaniumVTableContext &getItaniumVTableContext() {
696 return VTables.getItaniumVTableContext();
699 MicrosoftVTableContext &getMicrosoftVTableContext() {
700 return VTables.getMicrosoftVTableContext();
703 CtorList &getGlobalCtors() { return GlobalCtors; }
704 CtorList &getGlobalDtors() { return GlobalDtors; }
706 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
708 llvm::MDNode *getTBAATypeInfo(QualType QTy);
710 /// getTBAAAccessInfo - Get TBAA information that describes an access to
711 /// an object of the given type.
712 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
714 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
715 /// access to a virtual table pointer.
716 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
718 llvm::MDNode *getTBAAStructInfo(QualType QTy);
720 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
721 /// type. Return null if the type is not suitable for use in TBAA access tags.
722 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
724 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
725 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
727 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
729 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
730 TBAAAccessInfo TargetInfo);
732 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
733 /// purposes of conditional operator.
734 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
735 TBAAAccessInfo InfoB);
737 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
738 /// purposes of memory transfer calls.
739 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
740 TBAAAccessInfo SrcInfo);
742 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
744 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
745 if (Base.getTBAAInfo().isMayAlias())
746 return TBAAAccessInfo::getMayAliasInfo();
747 return getTBAAAccessInfo(AccessType);
750 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
752 bool isPaddedAtomicType(QualType type);
753 bool isPaddedAtomicType(const AtomicType *type);
755 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
756 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
757 TBAAAccessInfo TBAAInfo);
759 /// Adds !invariant.barrier !tag to instruction
760 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
761 const CXXRecordDecl *RD);
763 /// Emit the given number of characters as a value of type size_t.
764 llvm::ConstantInt *getSize(CharUnits numChars);
766 /// Set the visibility for the given LLVM GlobalValue.
767 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
769 void setDSOLocal(llvm::GlobalValue *GV) const;
771 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
772 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
773 /// Set visibility, dllimport/dllexport and dso_local.
774 /// This must be called after dllimport/dllexport is set.
775 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
776 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
778 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
780 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
781 /// variable declaration D.
782 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
784 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
786 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
787 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
788 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
790 llvm_unreachable("unknown visibility!");
793 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
794 ForDefinition_t IsForDefinition
797 /// Will return a global variable of the given type. If a variable with a
798 /// different type already exists then a new variable with the right type
799 /// will be created and all uses of the old variable will be replaced with a
800 /// bitcast to the new variable.
801 llvm::GlobalVariable *
802 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
803 llvm::GlobalValue::LinkageTypes Linkage,
807 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
808 const CGFunctionInfo &FI,
809 SourceLocation Loc = SourceLocation(),
812 /// Return the AST address space of the underlying global variable for D, as
813 /// determined by its declaration. Normally this is the same as the address
814 /// space of D's type, but in CUDA, address spaces are associated with
815 /// declarations, not types. If D is nullptr, return the default address
816 /// space for global variable.
818 /// For languages without explicit address spaces, if D has default address
819 /// space, target-specific global or constant address space may be returned.
820 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
822 /// Return the llvm::Constant for the address of the given global variable.
823 /// If Ty is non-null and if the global doesn't exist, then it will be created
824 /// with the specified type instead of whatever the normal requested type
825 /// would be. If IsForDefinition is true, it is guaranteed that an actual
826 /// global with type Ty will be returned, not conversion of a variable with
827 /// the same mangled name but some other type.
828 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
829 llvm::Type *Ty = nullptr,
830 ForDefinition_t IsForDefinition
833 /// Return the AST address space of string literal, which is used to emit
834 /// the string literal as global variable in LLVM IR.
835 /// Note: This is not necessarily the address space of the string literal
836 /// in AST. For address space agnostic language, e.g. C++, string literal
837 /// in AST is always in default address space.
838 LangAS getStringLiteralAddressSpace() const;
840 /// Return the address of the given function. If Ty is non-null, then this
841 /// function will use the specified type if it has to create it.
842 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
843 bool ForVTable = false,
844 bool DontDefer = false,
845 ForDefinition_t IsForDefinition
848 /// Get the address of the RTTI descriptor for the given type.
849 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
851 /// Get the address of a uuid descriptor .
852 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
854 /// Get the address of the thunk for the given global decl.
855 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
858 /// Get a reference to the target of VD.
859 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
861 /// Returns the assumed alignment of an opaque pointer to the given class.
862 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
864 /// Returns the assumed alignment of a virtual base of a class.
865 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
866 const CXXRecordDecl *Derived,
867 const CXXRecordDecl *VBase);
869 /// Given a class pointer with an actual known alignment, and the
870 /// expected alignment of an object at a dynamic offset w.r.t that
871 /// pointer, return the alignment to assume at the offset.
872 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
873 const CXXRecordDecl *Class,
874 CharUnits ExpectedTargetAlign);
877 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
878 CastExpr::path_const_iterator Start,
879 CastExpr::path_const_iterator End);
881 /// Returns the offset from a derived class to a class. Returns null if the
884 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
885 CastExpr::path_const_iterator PathBegin,
886 CastExpr::path_const_iterator PathEnd);
888 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
890 /// Fetches the global unique block count.
891 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
893 /// Fetches the type of a generic block descriptor.
894 llvm::Type *getBlockDescriptorType();
896 /// The type of a generic block literal.
897 llvm::Type *getGenericBlockLiteralType();
899 /// Gets the address of a block which requires no captures.
900 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
902 /// Returns the address of a block which requires no caputres, or null if
903 /// we've yet to emit the block for BE.
904 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
905 return EmittedGlobalBlocks.lookup(BE);
908 /// Notes that BE's global block is available via Addr. Asserts that BE
909 /// isn't already emitted.
910 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
912 /// Return a pointer to a constant CFString object for the given string.
913 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
915 /// Return a pointer to a constant NSString object for the given string. Or a
916 /// user defined String object as defined via
917 /// -fconstant-string-class=class_name option.
918 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
920 /// Return a constant array for the given string.
921 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
923 /// Return a pointer to a constant array for the given string literal.
925 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
926 StringRef Name = ".str");
928 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
930 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
932 /// Returns a pointer to a character array containing the literal and a
933 /// terminating '\0' character. The result has pointer to array type.
935 /// \param GlobalName If provided, the name to use for the global (if one is
938 GetAddrOfConstantCString(const std::string &Str,
939 const char *GlobalName = nullptr);
941 /// Returns a pointer to a constant global variable for the given file-scope
942 /// compound literal expression.
943 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
945 /// If it's been emitted already, returns the GlobalVariable corresponding to
946 /// a compound literal. Otherwise, returns null.
947 llvm::GlobalVariable *
948 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
950 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
952 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
953 llvm::GlobalVariable *GV);
955 /// Returns a pointer to a global variable representing a temporary
956 /// with static or thread storage duration.
957 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
960 /// Retrieve the record type that describes the state of an
961 /// Objective-C fast enumeration loop (for..in).
962 QualType getObjCFastEnumerationStateType();
964 // Produce code for this constructor/destructor. This method doesn't try
965 // to apply any ABI rules about which other constructors/destructors
966 // are needed or if they are alias to each other.
967 llvm::Function *codegenCXXStructor(GlobalDecl GD);
969 /// Return the address of the constructor/destructor of the given type.
971 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
972 llvm::FunctionType *FnType = nullptr,
973 bool DontDefer = false,
974 ForDefinition_t IsForDefinition = NotForDefinition) {
975 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
981 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
982 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
983 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
984 ForDefinition_t IsForDefinition = NotForDefinition);
986 /// Given a builtin id for a function like "__builtin_fabsf", return a
987 /// Function* for "fabsf".
988 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
991 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
993 /// Emit code for a single top level declaration.
994 void EmitTopLevelDecl(Decl *D);
996 /// Stored a deferred empty coverage mapping for an unused
997 /// and thus uninstrumented top level declaration.
998 void AddDeferredUnusedCoverageMapping(Decl *D);
1000 /// Remove the deferred empty coverage mapping as this
1001 /// declaration is actually instrumented.
1002 void ClearUnusedCoverageMapping(const Decl *D);
1004 /// Emit all the deferred coverage mappings
1005 /// for the uninstrumented functions.
1006 void EmitDeferredUnusedCoverageMappings();
1008 /// Tell the consumer that this variable has been instantiated.
1009 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1011 /// If the declaration has internal linkage but is inside an
1012 /// extern "C" linkage specification, prepare to emit an alias for it
1013 /// to the expected name.
1014 template<typename SomeDecl>
1015 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1017 /// Add a global to a list to be added to the llvm.used metadata.
1018 void addUsedGlobal(llvm::GlobalValue *GV);
1020 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1021 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1023 /// Add a destructor and object to add to the C++ global destructor function.
1024 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1025 CXXGlobalDtors.emplace_back(DtorFn.getFunctionType(), DtorFn.getCallee(),
1029 /// Create or return a runtime function declaration with the specified type
1031 llvm::FunctionCallee
1032 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1033 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1034 bool Local = false);
1036 /// Create a new runtime global variable with the specified type and name.
1037 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1040 ///@name Custom Blocks Runtime Interfaces
1043 llvm::Constant *getNSConcreteGlobalBlock();
1044 llvm::Constant *getNSConcreteStackBlock();
1045 llvm::FunctionCallee getBlockObjectAssign();
1046 llvm::FunctionCallee getBlockObjectDispose();
1050 llvm::Function *getLLVMLifetimeStartFn();
1051 llvm::Function *getLLVMLifetimeEndFn();
1053 // Make sure that this type is translated.
1054 void UpdateCompletedType(const TagDecl *TD);
1056 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1058 /// Emit type info if type of an expression is a variably modified
1059 /// type. Also emit proper debug info for cast types.
1060 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1061 CodeGenFunction *CGF = nullptr);
1063 /// Return the result of value-initializing the given type, i.e. a null
1064 /// expression of the given type. This is usually, but not always, an LLVM
1066 llvm::Constant *EmitNullConstant(QualType T);
1068 /// Return a null constant appropriate for zero-initializing a base class with
1069 /// the given type. This is usually, but not always, an LLVM null constant.
1070 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1072 /// Emit a general error that something can't be done.
1073 void Error(SourceLocation loc, StringRef error);
1075 /// Print out an error that codegen doesn't support the specified stmt yet.
1076 void ErrorUnsupported(const Stmt *S, const char *Type);
1078 /// Print out an error that codegen doesn't support the specified decl yet.
1079 void ErrorUnsupported(const Decl *D, const char *Type);
1081 /// Set the attributes on the LLVM function for the given decl and function
1082 /// info. This applies attributes necessary for handling the ABI as well as
1083 /// user specified attributes like section.
1084 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1085 const CGFunctionInfo &FI);
1087 /// Set the LLVM function attributes (sext, zext, etc).
1088 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1091 /// Set the LLVM function attributes which only apply to a function
1093 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1095 /// Return true iff the given type uses 'sret' when used as a return type.
1096 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1098 /// Return true iff the given type uses an argument slot when 'sret' is used
1099 /// as a return type.
1100 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1102 /// Return true iff the given type uses 'fpret' when used as a return type.
1103 bool ReturnTypeUsesFPRet(QualType ResultType);
1105 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1106 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1108 /// Get the LLVM attributes and calling convention to use for a particular
1111 /// \param Name - The function name.
1112 /// \param Info - The function type information.
1113 /// \param CalleeInfo - The callee information these attributes are being
1114 /// constructed for. If valid, the attributes applied to this decl may
1115 /// contribute to the function attributes and calling convention.
1116 /// \param Attrs [out] - On return, the attribute list to use.
1117 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1118 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1119 CGCalleeInfo CalleeInfo,
1120 llvm::AttributeList &Attrs, unsigned &CallingConv,
1121 bool AttrOnCallSite);
1123 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1124 /// though we had emitted it ourselves. We remove any attributes on F that
1125 /// conflict with the attributes we add here.
1127 /// This is useful for adding attrs to bitcode modules that you want to link
1128 /// with but don't control, such as CUDA's libdevice. When linking with such
1129 /// a bitcode library, you might want to set e.g. its functions'
1130 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1131 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1132 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1133 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1134 /// function in the bitcode library!
1136 /// With the exception of fast-math attrs, this will only make the attributes
1137 /// on the function more conservative. But it's unsafe to call this on a
1138 /// function which relies on particular fast-math attributes for correctness.
1139 /// It's up to you to ensure that this is safe.
1140 void AddDefaultFnAttrs(llvm::Function &F);
1142 /// Parses the target attributes passed in, and returns only the ones that are
1143 /// valid feature names.
1144 TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD);
1146 // Fills in the supplied string map with the set of target features for the
1147 // passed in function.
1148 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, GlobalDecl GD);
1150 StringRef getMangledName(GlobalDecl GD);
1151 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1153 void EmitTentativeDefinition(const VarDecl *D);
1155 void EmitVTable(CXXRecordDecl *Class);
1157 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1159 /// Appends Opts to the "llvm.linker.options" metadata value.
1160 void AppendLinkerOptions(StringRef Opts);
1162 /// Appends a detect mismatch command to the linker options.
1163 void AddDetectMismatch(StringRef Name, StringRef Value);
1165 /// Appends a dependent lib to the appropriate metadata value.
1166 void AddDependentLib(StringRef Lib);
1169 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1171 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1172 F->setLinkage(getFunctionLinkage(GD));
1175 /// Return the appropriate linkage for the vtable, VTT, and type information
1176 /// of the given class.
1177 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1179 /// Return the store size, in character units, of the given LLVM type.
1180 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1182 /// Returns LLVM linkage for a declarator.
1183 llvm::GlobalValue::LinkageTypes
1184 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1185 bool IsConstantVariable);
1187 /// Returns LLVM linkage for a declarator.
1188 llvm::GlobalValue::LinkageTypes
1189 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1191 /// Emit all the global annotations.
1192 void EmitGlobalAnnotations();
1194 /// Emit an annotation string.
1195 llvm::Constant *EmitAnnotationString(StringRef Str);
1197 /// Emit the annotation's translation unit.
1198 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1200 /// Emit the annotation line number.
1201 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1203 /// Generate the llvm::ConstantStruct which contains the annotation
1204 /// information for a given GlobalValue. The annotation struct is
1205 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1206 /// GlobalValue being annotated. The second field is the constant string
1207 /// created from the AnnotateAttr's annotation. The third field is a constant
1208 /// string containing the name of the translation unit. The fourth field is
1209 /// the line number in the file of the annotated value declaration.
1210 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1211 const AnnotateAttr *AA,
1214 /// Add global annotations that are set on D, for the global GV. Those
1215 /// annotations are emitted during finalization of the LLVM code.
1216 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1218 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1219 SourceLocation Loc) const;
1221 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1223 StringRef Category = StringRef()) const;
1225 /// Imbue XRay attributes to a function, applying the always/never attribute
1226 /// lists in the process. Returns true if we did imbue attributes this way,
1227 /// false otherwise.
1228 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1229 StringRef Category = StringRef()) const;
1231 SanitizerMetadata *getSanitizerMetadata() {
1232 return SanitizerMD.get();
1235 void addDeferredVTable(const CXXRecordDecl *RD) {
1236 DeferredVTables.push_back(RD);
1239 /// Emit code for a single global function or var decl. Forward declarations
1240 /// are emitted lazily.
1241 void EmitGlobal(GlobalDecl D);
1243 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1245 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1247 /// Set attributes which are common to any form of a global definition (alias,
1248 /// Objective-C method, function, global variable).
1250 /// NOTE: This should only be called for definitions.
1251 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1253 void addReplacement(StringRef Name, llvm::Constant *C);
1255 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1257 /// Emit a code for threadprivate directive.
1258 /// \param D Threadprivate declaration.
1259 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1261 /// Emit a code for declare reduction construct.
1262 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1263 CodeGenFunction *CGF = nullptr);
1265 /// Emit a code for declare mapper construct.
1266 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1267 CodeGenFunction *CGF = nullptr);
1269 /// Emit a code for requires directive.
1270 /// \param D Requires declaration
1271 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1273 /// Returns whether the given record has hidden LTO visibility and therefore
1274 /// may participate in (single-module) CFI and whole-program vtable
1276 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1278 /// Emit type metadata for the given vtable using the given layout.
1279 void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1280 const VTableLayout &VTLayout);
1282 /// Generate a cross-DSO type identifier for MD.
1283 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1285 /// Create a metadata identifier for the given type. This may either be an
1286 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1287 /// internal identifiers).
1288 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1290 /// Create a metadata identifier that is intended to be used to check virtual
1291 /// calls via a member function pointer.
1292 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1294 /// Create a metadata identifier for the generalization of the given type.
1295 /// This may either be an MDString (for external identifiers) or a distinct
1296 /// unnamed MDNode (for internal identifiers).
1297 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1299 /// Create and attach type metadata to the given function.
1300 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1303 /// Returns whether this module needs the "all-vtables" type identifier.
1304 bool NeedAllVtablesTypeId() const;
1306 /// Create and attach type metadata for the given vtable.
1307 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1308 const CXXRecordDecl *RD);
1310 /// Return a vector of most-base classes for RD. This is used to implement
1311 /// control flow integrity checks for member function pointers.
1313 /// A most-base class of a class C is defined as a recursive base class of C,
1314 /// including C itself, that does not have any bases.
1315 std::vector<const CXXRecordDecl *>
1316 getMostBaseClasses(const CXXRecordDecl *RD);
1318 /// Get the declaration of std::terminate for the platform.
1319 llvm::FunctionCallee getTerminateFn();
1321 llvm::SanitizerStatReport &getSanStats();
1324 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1326 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1327 /// information in the program executable. The argument information stored
1328 /// includes the argument name, its type, the address and access qualifiers
1329 /// used. This helper can be used to generate metadata for source code kernel
1330 /// function as well as generated implicitly kernels. If a kernel is generated
1331 /// implicitly null value has to be passed to the last two parameters,
1332 /// otherwise all parameters must have valid non-null values.
1333 /// \param FN is a pointer to IR function being generated.
1334 /// \param FD is a pointer to function declaration if any.
1335 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1336 void GenOpenCLArgMetadata(llvm::Function *FN,
1337 const FunctionDecl *FD = nullptr,
1338 CodeGenFunction *CGF = nullptr);
1340 /// Get target specific null pointer.
1341 /// \param T is the LLVM type of the null pointer.
1342 /// \param QT is the clang QualType of the null pointer.
1343 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1346 llvm::Constant *GetOrCreateLLVMFunction(
1347 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1348 bool DontDefer = false, bool IsThunk = false,
1349 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1350 ForDefinition_t IsForDefinition = NotForDefinition);
1352 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
1354 const FunctionDecl *FD);
1355 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD);
1357 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1358 llvm::PointerType *PTy,
1360 ForDefinition_t IsForDefinition
1361 = NotForDefinition);
1363 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1364 llvm::AttrBuilder &AttrBuilder);
1365 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1367 /// Set function attributes for a function declaration.
1368 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1369 bool IsIncompleteFunction, bool IsThunk);
1371 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1373 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1374 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1376 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1377 void EmitAliasDefinition(GlobalDecl GD);
1378 void emitIFuncDefinition(GlobalDecl GD);
1379 void emitCPUDispatchDefinition(GlobalDecl GD);
1380 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1381 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1383 // C++ related functions.
1385 void EmitDeclContext(const DeclContext *DC);
1386 void EmitLinkageSpec(const LinkageSpecDecl *D);
1388 /// Emit the function that initializes C++ thread_local variables.
1389 void EmitCXXThreadLocalInitFunc();
1391 /// Emit the function that initializes C++ globals.
1392 void EmitCXXGlobalInitFunc();
1394 /// Emit the function that destroys C++ globals.
1395 void EmitCXXGlobalDtorFunc();
1397 /// Emit the function that initializes the specified global (if PerformInit is
1398 /// true) and registers its destructor.
1399 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1400 llvm::GlobalVariable *Addr,
1403 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1404 llvm::Function *InitFunc, InitSegAttr *ISA);
1406 // FIXME: Hardcoding priority here is gross.
1407 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1408 llvm::Constant *AssociatedData = nullptr);
1409 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1411 /// EmitCtorList - Generates a global array of functions and priorities using
1412 /// the given list and name. This array will have appending linkage and is
1413 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1414 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1416 /// Emit any needed decls for which code generation was deferred.
1417 void EmitDeferred();
1419 /// Try to emit external vtables as available_externally if they have emitted
1420 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1421 /// is not allowed to create new references to things that need to be emitted
1423 void EmitVTablesOpportunistically();
1425 /// Call replaceAllUsesWith on all pairs in Replacements.
1426 void applyReplacements();
1428 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1429 void applyGlobalValReplacements();
1431 void checkAliases();
1433 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1435 /// Register functions annotated with __attribute__((destructor)) using
1436 /// __cxa_atexit, if it is available, or atexit otherwise.
1437 void registerGlobalDtorsWithAtExit();
1439 void emitMultiVersionFunctions();
1441 /// Emit any vtables which we deferred and still have a use for.
1442 void EmitDeferredVTables();
1444 /// Emit a dummy function that reference a CoreFoundation symbol when
1445 /// @available is used on Darwin.
1446 void emitAtAvailableLinkGuard();
1448 /// Emit the llvm.used and llvm.compiler.used metadata.
1449 void emitLLVMUsed();
1451 /// Emit the link options introduced by imported modules.
1452 void EmitModuleLinkOptions();
1454 /// Emit aliases for internal-linkage declarations inside "C" language
1455 /// linkage specifications, giving them the "expected" name where possible.
1456 void EmitStaticExternCAliases();
1458 void EmitDeclMetadata();
1460 /// Emit the Clang version as llvm.ident metadata.
1461 void EmitVersionIdentMetadata();
1463 /// Emit the Clang commandline as llvm.commandline metadata.
1464 void EmitCommandLineMetadata();
1466 /// Emits target specific Metadata for global declarations.
1467 void EmitTargetMetadata();
1469 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1470 void EmitOpenCLMetadata();
1472 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1473 /// .gcda files in a way that persists in .bc files.
1474 void EmitCoverageFile();
1476 /// Emits the initializer for a uuidof string.
1477 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1479 /// Determine whether the definition must be emitted; if this returns \c
1480 /// false, the definition can be emitted lazily if it's used.
1481 bool MustBeEmitted(const ValueDecl *D);
1483 /// Determine whether the definition can be emitted eagerly, or should be
1484 /// delayed until the end of the translation unit. This is relevant for
1485 /// definitions whose linkage can change, e.g. implicit function instantions
1486 /// which may later be explicitly instantiated.
1487 bool MayBeEmittedEagerly(const ValueDecl *D);
1489 /// Check whether we can use a "simpler", more core exceptions personality
1491 void SimplifyPersonality();
1493 /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1494 /// Constructs an AttrList for a function with the given properties.
1495 void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1496 bool AttrOnCallSite,
1497 llvm::AttrBuilder &FuncAttrs);
1499 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1503 } // end namespace CodeGen
1504 } // end namespace clang
1506 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H