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/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/TargetInfo.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 OpenMPIRBuilder;
49 class IndexedInstrProfReader;
58 class ObjCImplementationDecl;
59 class ObjCCategoryImplDecl;
60 class ObjCProtocolDecl;
74 class HeaderSearchOptions;
75 class PreprocessorOptions;
76 class DiagnosticsEngine;
78 class CXXDestructorDecl;
80 class CoverageSourceInfo;
83 struct ParsedTargetAttr;
88 class CodeGenFunction;
93 class CGOpenCLRuntime;
94 class CGOpenMPRuntime;
96 class BlockFieldFlags;
97 class FunctionArgList;
98 class CoverageMappingModuleGen;
99 class TargetCodeGenInfo;
101 enum ForDefinition_t : bool {
102 NotForDefinition = false,
106 struct OrderGlobalInits {
107 unsigned int priority;
108 unsigned int lex_order;
109 OrderGlobalInits(unsigned int p, unsigned int l)
110 : priority(p), lex_order(l) {}
112 bool operator==(const OrderGlobalInits &RHS) const {
113 return priority == RHS.priority && lex_order == RHS.lex_order;
116 bool operator<(const OrderGlobalInits &RHS) const {
117 return std::tie(priority, lex_order) <
118 std::tie(RHS.priority, RHS.lex_order);
122 struct ObjCEntrypoints {
123 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
125 /// void objc_alloc(id);
126 llvm::FunctionCallee objc_alloc;
128 /// void objc_allocWithZone(id);
129 llvm::FunctionCallee objc_allocWithZone;
131 /// void objc_alloc_init(id);
132 llvm::FunctionCallee objc_alloc_init;
134 /// void objc_autoreleasePoolPop(void*);
135 llvm::FunctionCallee objc_autoreleasePoolPop;
137 /// void objc_autoreleasePoolPop(void*);
138 /// Note this method is used when we are using exception handling
139 llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
141 /// void *objc_autoreleasePoolPush(void);
142 llvm::Function *objc_autoreleasePoolPush;
144 /// id objc_autorelease(id);
145 llvm::Function *objc_autorelease;
147 /// id objc_autorelease(id);
148 /// Note this is the runtime method not the intrinsic.
149 llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
151 /// id objc_autoreleaseReturnValue(id);
152 llvm::Function *objc_autoreleaseReturnValue;
154 /// void objc_copyWeak(id *dest, id *src);
155 llvm::Function *objc_copyWeak;
157 /// void objc_destroyWeak(id*);
158 llvm::Function *objc_destroyWeak;
160 /// id objc_initWeak(id*, id);
161 llvm::Function *objc_initWeak;
163 /// id objc_loadWeak(id*);
164 llvm::Function *objc_loadWeak;
166 /// id objc_loadWeakRetained(id*);
167 llvm::Function *objc_loadWeakRetained;
169 /// void objc_moveWeak(id *dest, id *src);
170 llvm::Function *objc_moveWeak;
172 /// id objc_retain(id);
173 llvm::Function *objc_retain;
175 /// id objc_retain(id);
176 /// Note this is the runtime method not the intrinsic.
177 llvm::FunctionCallee objc_retainRuntimeFunction;
179 /// id objc_retainAutorelease(id);
180 llvm::Function *objc_retainAutorelease;
182 /// id objc_retainAutoreleaseReturnValue(id);
183 llvm::Function *objc_retainAutoreleaseReturnValue;
185 /// id objc_retainAutoreleasedReturnValue(id);
186 llvm::Function *objc_retainAutoreleasedReturnValue;
188 /// id objc_retainBlock(id);
189 llvm::Function *objc_retainBlock;
191 /// void objc_release(id);
192 llvm::Function *objc_release;
194 /// void objc_release(id);
195 /// Note this is the runtime method not the intrinsic.
196 llvm::FunctionCallee objc_releaseRuntimeFunction;
198 /// void objc_storeStrong(id*, id);
199 llvm::Function *objc_storeStrong;
201 /// id objc_storeWeak(id*, id);
202 llvm::Function *objc_storeWeak;
204 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
205 llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
207 /// A void(void) inline asm to use to mark that the return value of
208 /// a call will be immediately retain.
209 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
211 /// void clang.arc.use(...);
212 llvm::Function *clang_arc_use;
215 /// This class records statistics on instrumentation based profiling.
216 class InstrProfStats {
217 uint32_t VisitedInMainFile;
218 uint32_t MissingInMainFile;
225 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
227 /// Record that we've visited a function and whether or not that function was
228 /// in the main source file.
229 void addVisited(bool MainFile) {
234 /// Record that a function we've visited has no profile data.
235 void addMissing(bool MainFile) {
240 /// Record that a function we've visited has mismatched profile data.
241 void addMismatched(bool MainFile) { ++Mismatched; }
242 /// Whether or not the stats we've gathered indicate any potential problems.
243 bool hasDiagnostics() { return Missing || Mismatched; }
244 /// Report potential problems we've found to \c Diags.
245 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
248 /// A pair of helper functions for a __block variable.
249 class BlockByrefHelpers : public llvm::FoldingSetNode {
250 // MSVC requires this type to be complete in order to process this
253 llvm::Constant *CopyHelper;
254 llvm::Constant *DisposeHelper;
256 /// The alignment of the field. This is important because
257 /// different offsets to the field within the byref struct need to
258 /// have different helper functions.
261 BlockByrefHelpers(CharUnits alignment)
262 : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
263 BlockByrefHelpers(const BlockByrefHelpers &) = default;
264 virtual ~BlockByrefHelpers();
266 void Profile(llvm::FoldingSetNodeID &id) const {
267 id.AddInteger(Alignment.getQuantity());
270 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
272 virtual bool needsCopy() const { return true; }
273 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
275 virtual bool needsDispose() const { return true; }
276 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
279 /// This class organizes the cross-function state that is used while generating
281 class CodeGenModule : public CodeGenTypeCache {
282 CodeGenModule(const CodeGenModule &) = delete;
283 void operator=(const CodeGenModule &) = delete;
287 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
288 Structor(int Priority, llvm::Constant *Initializer,
289 llvm::Constant *AssociatedData)
290 : Priority(Priority), Initializer(Initializer),
291 AssociatedData(AssociatedData) {}
293 llvm::Constant *Initializer;
294 llvm::Constant *AssociatedData;
297 typedef std::vector<Structor> CtorList;
301 const LangOptions &LangOpts;
302 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
303 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
304 const CodeGenOptions &CodeGenOpts;
305 unsigned NumAutoVarInit = 0;
306 llvm::Module &TheModule;
307 DiagnosticsEngine &Diags;
308 const TargetInfo &Target;
309 std::unique_ptr<CGCXXABI> ABI;
310 llvm::LLVMContext &VMContext;
312 std::unique_ptr<CodeGenTBAA> TBAA;
314 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
316 // This should not be moved earlier, since its initialization depends on some
317 // of the previous reference members being already initialized and also checks
318 // if TheTargetCodeGenInfo is NULL
321 /// Holds information about C++ vtables.
322 CodeGenVTables VTables;
324 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
325 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
326 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
327 std::unique_ptr<CGCUDARuntime> CUDARuntime;
328 std::unique_ptr<CGDebugInfo> DebugInfo;
329 std::unique_ptr<ObjCEntrypoints> ObjCData;
330 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
331 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
332 InstrProfStats PGOStats;
333 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
335 // A set of references that have only been seen via a weakref so far. This is
336 // used to remove the weak of the reference if we ever see a direct reference
338 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
340 /// This contains all the decls which have definitions but/ which are deferred
341 /// for emission and therefore should only be output if they are actually
342 /// used. If a decl is in this, then it is known to have not been referenced
344 std::map<StringRef, GlobalDecl> DeferredDecls;
346 /// This is a list of deferred decls which we have seen that *are* actually
347 /// referenced. These get code generated when the module is done.
348 std::vector<GlobalDecl> DeferredDeclsToEmit;
349 void addDeferredDeclToEmit(GlobalDecl GD) {
350 DeferredDeclsToEmit.emplace_back(GD);
353 /// List of alias we have emitted. Used to make sure that what they point to
354 /// is defined once we get to the end of the of the translation unit.
355 std::vector<GlobalDecl> Aliases;
357 /// List of multiversion functions that have to be emitted. Used to make sure
358 /// we properly emit the iFunc.
359 std::vector<GlobalDecl> MultiVersionFuncs;
361 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
362 ReplacementsTy Replacements;
364 /// List of global values to be replaced with something else. Used when we
365 /// want to replace a GlobalValue but can't identify it by its mangled name
366 /// anymore (because the name is already taken).
367 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
368 GlobalValReplacements;
370 /// Variables for which we've emitted globals containing their constant
371 /// values along with the corresponding globals, for opportunistic reuse.
372 llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
374 /// Set of global decls for which we already diagnosed mangled name conflict.
375 /// Required to not issue a warning (on a mangling conflict) multiple times
376 /// for the same decl.
377 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
379 /// A queue of (optional) vtables to consider emitting.
380 std::vector<const CXXRecordDecl*> DeferredVTables;
382 /// A queue of (optional) vtables that may be emitted opportunistically.
383 std::vector<const CXXRecordDecl *> OpportunisticVTables;
385 /// List of global values which are required to be present in the object file;
386 /// bitcast to i8*. This is used for forcing visibility of symbols which may
387 /// otherwise be optimized out.
388 std::vector<llvm::WeakTrackingVH> LLVMUsed;
389 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
391 /// Store the list of global constructors and their respective priorities to
392 /// be emitted when the translation unit is complete.
393 CtorList GlobalCtors;
395 /// Store the list of global destructors and their respective priorities to be
396 /// emitted when the translation unit is complete.
397 CtorList GlobalDtors;
399 /// A unique trailing identifier as a part of sinit/sterm function when
400 /// UseSinitAndSterm of CXXABI is set as true.
401 std::string GlobalUniqueModuleId;
403 /// An ordered map of canonical GlobalDecls to their mangled names.
404 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
405 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
407 // An ordered map of canonical GlobalDecls paired with the cpu-index for
408 // cpu-specific name manglings.
409 llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef>
410 CPUSpecificMangledDeclNames;
411 llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator>
412 CPUSpecificManglings;
414 /// Global annotations.
415 std::vector<llvm::Constant*> Annotations;
417 /// Map used to get unique annotation strings.
418 llvm::StringMap<llvm::Constant*> AnnotationStrings;
420 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
422 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
423 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
424 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
425 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
427 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
428 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
430 /// Map used to get unique type descriptor constants for sanitizers.
431 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
433 /// Map used to track internal linkage functions declared within
434 /// extern "C" regions.
435 typedef llvm::MapVector<IdentifierInfo *,
436 llvm::GlobalValue *> StaticExternCMap;
437 StaticExternCMap StaticExternCValues;
439 /// thread_local variables defined or used in this TU.
440 std::vector<const VarDecl *> CXXThreadLocals;
442 /// thread_local variables with initializers that need to run
443 /// before any thread_local variable in this TU is odr-used.
444 std::vector<llvm::Function *> CXXThreadLocalInits;
445 std::vector<const VarDecl *> CXXThreadLocalInitVars;
447 /// Global variables with initializers that need to run before main.
448 std::vector<llvm::Function *> CXXGlobalInits;
450 /// When a C++ decl with an initializer is deferred, null is
451 /// appended to CXXGlobalInits, and the index of that null is placed
452 /// here so that the initializer will be performed in the correct
453 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
454 /// that we don't re-emit the initializer.
455 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
457 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
459 struct GlobalInitPriorityCmp {
460 bool operator()(const GlobalInitData &LHS,
461 const GlobalInitData &RHS) const {
462 return LHS.first.priority < RHS.first.priority;
466 /// Global variables with initializers whose order of initialization is set by
467 /// init_priority attribute.
468 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
470 /// Global destructor functions and arguments that need to run on termination.
471 /// When UseSinitAndSterm is set, it instead contains sterm finalizer
472 /// functions, which also run on unloading a shared library.
474 std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, llvm::Constant *>>
475 CXXGlobalDtorsOrStermFinalizers;
477 /// The complete set of modules that has been imported.
478 llvm::SetVector<clang::Module *> ImportedModules;
480 /// The set of modules for which the module initializers
481 /// have been emitted.
482 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
484 /// A vector of metadata strings for linker options.
485 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
487 /// A vector of metadata strings for dependent libraries for ELF.
488 SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
490 /// @name Cache for Objective-C runtime types
493 /// Cached reference to the class for constant strings. This value has type
494 /// int * but is actually an Obj-C class pointer.
495 llvm::WeakTrackingVH CFConstantStringClassRef;
497 /// The type used to describe the state of a fast enumeration in
498 /// Objective-C's for..in loop.
499 QualType ObjCFastEnumerationStateType;
503 /// Lazily create the Objective-C runtime
504 void createObjCRuntime();
506 void createOpenCLRuntime();
507 void createOpenMPRuntime();
508 void createCUDARuntime();
510 bool isTriviallyRecursive(const FunctionDecl *F);
511 bool shouldEmitFunction(GlobalDecl GD);
512 bool shouldOpportunisticallyEmitVTables();
513 /// Map used to be sure we don't emit the same CompoundLiteral twice.
514 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
515 EmittedCompoundLiterals;
517 /// Map of the global blocks we've emitted, so that we don't have to re-emit
518 /// them if the constexpr evaluator gets aggressive.
519 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
521 /// @name Cache for Blocks Runtime Globals
524 llvm::Constant *NSConcreteGlobalBlock = nullptr;
525 llvm::Constant *NSConcreteStackBlock = nullptr;
527 llvm::FunctionCallee BlockObjectAssign = nullptr;
528 llvm::FunctionCallee BlockObjectDispose = nullptr;
530 llvm::Type *BlockDescriptorType = nullptr;
531 llvm::Type *GenericBlockLiteralType = nullptr;
534 int GlobalUniqueCount;
537 GlobalDecl initializedGlobalDecl;
541 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
542 llvm::Function *LifetimeStartFn = nullptr;
544 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
545 llvm::Function *LifetimeEndFn = nullptr;
547 std::unique_ptr<SanitizerMetadata> SanitizerMD;
549 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
551 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
553 /// Mapping from canonical types to their metadata identifiers. We need to
554 /// maintain this mapping because identifiers may be formed from distinct
556 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
557 MetadataTypeMap MetadataIdMap;
558 MetadataTypeMap VirtualMetadataIdMap;
559 MetadataTypeMap GeneralizedMetadataIdMap;
562 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
563 const PreprocessorOptions &ppopts,
564 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
565 DiagnosticsEngine &Diags,
566 CoverageSourceInfo *CoverageInfo = nullptr);
572 /// Finalize LLVM code generation.
575 /// Return true if we should emit location information for expressions.
576 bool getExpressionLocationsEnabled() const;
578 /// Return a reference to the configured Objective-C runtime.
579 CGObjCRuntime &getObjCRuntime() {
580 if (!ObjCRuntime) createObjCRuntime();
584 /// Return true iff an Objective-C runtime has been configured.
585 bool hasObjCRuntime() { return !!ObjCRuntime; }
587 /// Return a reference to the configured OpenCL runtime.
588 CGOpenCLRuntime &getOpenCLRuntime() {
589 assert(OpenCLRuntime != nullptr);
590 return *OpenCLRuntime;
593 /// Return a reference to the configured OpenMP runtime.
594 CGOpenMPRuntime &getOpenMPRuntime() {
595 assert(OpenMPRuntime != nullptr);
596 return *OpenMPRuntime;
599 /// Return a reference to the configured CUDA runtime.
600 CGCUDARuntime &getCUDARuntime() {
601 assert(CUDARuntime != nullptr);
605 ObjCEntrypoints &getObjCEntrypoints() const {
606 assert(ObjCData != nullptr);
610 // Version checking function, used to implement ObjC's @available:
611 // i32 @__isOSVersionAtLeast(i32, i32, i32)
612 llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
614 InstrProfStats &getPGOStats() { return PGOStats; }
615 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
617 CoverageMappingModuleGen *getCoverageMapping() const {
618 return CoverageMapping.get();
621 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
622 return StaticLocalDeclMap[D];
624 void setStaticLocalDeclAddress(const VarDecl *D,
626 StaticLocalDeclMap[D] = C;
630 getOrCreateStaticVarDecl(const VarDecl &D,
631 llvm::GlobalValue::LinkageTypes Linkage);
633 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
634 return StaticLocalDeclGuardMap[D];
636 void setStaticLocalDeclGuardAddress(const VarDecl *D,
637 llvm::GlobalVariable *C) {
638 StaticLocalDeclGuardMap[D] = C;
641 Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
644 bool lookupRepresentativeDecl(StringRef MangledName,
645 GlobalDecl &Result) const;
647 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
648 return AtomicSetterHelperFnMap[Ty];
650 void setAtomicSetterHelperFnMap(QualType Ty,
651 llvm::Constant *Fn) {
652 AtomicSetterHelperFnMap[Ty] = Fn;
655 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
656 return AtomicGetterHelperFnMap[Ty];
658 void setAtomicGetterHelperFnMap(QualType Ty,
659 llvm::Constant *Fn) {
660 AtomicGetterHelperFnMap[Ty] = Fn;
663 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
664 return TypeDescriptorMap[Ty];
666 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
667 TypeDescriptorMap[Ty] = C;
670 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
672 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
673 if (!NoObjCARCExceptionsMetadata)
674 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
675 return NoObjCARCExceptionsMetadata;
678 ASTContext &getContext() const { return Context; }
679 const LangOptions &getLangOpts() const { return LangOpts; }
680 const HeaderSearchOptions &getHeaderSearchOpts()
681 const { return HeaderSearchOpts; }
682 const PreprocessorOptions &getPreprocessorOpts()
683 const { return PreprocessorOpts; }
684 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
685 llvm::Module &getModule() const { return TheModule; }
686 DiagnosticsEngine &getDiags() const { return Diags; }
687 const llvm::DataLayout &getDataLayout() const {
688 return TheModule.getDataLayout();
690 const TargetInfo &getTarget() const { return Target; }
691 const llvm::Triple &getTriple() const { return Target.getTriple(); }
692 bool supportsCOMDAT() const;
693 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
695 CGCXXABI &getCXXABI() const { return *ABI; }
696 llvm::LLVMContext &getLLVMContext() { return VMContext; }
698 bool shouldUseTBAA() const { return TBAA != nullptr; }
700 const TargetCodeGenInfo &getTargetCodeGenInfo();
702 CodeGenTypes &getTypes() { return Types; }
704 CodeGenVTables &getVTables() { return VTables; }
706 ItaniumVTableContext &getItaniumVTableContext() {
707 return VTables.getItaniumVTableContext();
710 MicrosoftVTableContext &getMicrosoftVTableContext() {
711 return VTables.getMicrosoftVTableContext();
714 CtorList &getGlobalCtors() { return GlobalCtors; }
715 CtorList &getGlobalDtors() { return GlobalDtors; }
717 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
719 llvm::MDNode *getTBAATypeInfo(QualType QTy);
721 /// getTBAAAccessInfo - Get TBAA information that describes an access to
722 /// an object of the given type.
723 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
725 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
726 /// access to a virtual table pointer.
727 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
729 llvm::MDNode *getTBAAStructInfo(QualType QTy);
731 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
732 /// type. Return null if the type is not suitable for use in TBAA access tags.
733 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
735 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
736 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
738 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
740 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
741 TBAAAccessInfo TargetInfo);
743 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
744 /// purposes of conditional operator.
745 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
746 TBAAAccessInfo InfoB);
748 /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
749 /// purposes of memory transfer calls.
750 TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
751 TBAAAccessInfo SrcInfo);
753 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
755 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
756 if (Base.getTBAAInfo().isMayAlias())
757 return TBAAAccessInfo::getMayAliasInfo();
758 return getTBAAAccessInfo(AccessType);
761 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
763 bool isPaddedAtomicType(QualType type);
764 bool isPaddedAtomicType(const AtomicType *type);
766 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
767 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
768 TBAAAccessInfo TBAAInfo);
770 /// Adds !invariant.barrier !tag to instruction
771 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
772 const CXXRecordDecl *RD);
774 /// Emit the given number of characters as a value of type size_t.
775 llvm::ConstantInt *getSize(CharUnits numChars);
777 /// Set the visibility for the given LLVM GlobalValue.
778 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
780 void setDSOLocal(llvm::GlobalValue *GV) const;
782 void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
783 void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
784 /// Set visibility, dllimport/dllexport and dso_local.
785 /// This must be called after dllimport/dllexport is set.
786 void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
787 void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
789 void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
791 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
792 /// variable declaration D.
793 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
795 /// Get LLVM TLS mode from CodeGenOptions.
796 llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
798 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
800 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
801 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
802 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
804 llvm_unreachable("unknown visibility!");
807 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
808 ForDefinition_t IsForDefinition
811 /// Will return a global variable of the given type. If a variable with a
812 /// different type already exists then a new variable with the right type
813 /// will be created and all uses of the old variable will be replaced with a
814 /// bitcast to the new variable.
815 llvm::GlobalVariable *
816 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
817 llvm::GlobalValue::LinkageTypes Linkage,
820 llvm::Function *CreateGlobalInitOrCleanUpFunction(
821 llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
822 SourceLocation Loc = SourceLocation(), bool TLS = false,
823 bool IsExternalLinkage = false);
825 /// Return the AST address space of the underlying global variable for D, as
826 /// determined by its declaration. Normally this is the same as the address
827 /// space of D's type, but in CUDA, address spaces are associated with
828 /// declarations, not types. If D is nullptr, return the default address
829 /// space for global variable.
831 /// For languages without explicit address spaces, if D has default address
832 /// space, target-specific global or constant address space may be returned.
833 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
835 /// Return the llvm::Constant for the address of the given global variable.
836 /// If Ty is non-null and if the global doesn't exist, then it will be created
837 /// with the specified type instead of whatever the normal requested type
838 /// would be. If IsForDefinition is true, it is guaranteed that an actual
839 /// global with type Ty will be returned, not conversion of a variable with
840 /// the same mangled name but some other type.
841 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
842 llvm::Type *Ty = nullptr,
843 ForDefinition_t IsForDefinition
846 /// Return the AST address space of string literal, which is used to emit
847 /// the string literal as global variable in LLVM IR.
848 /// Note: This is not necessarily the address space of the string literal
849 /// in AST. For address space agnostic language, e.g. C++, string literal
850 /// in AST is always in default address space.
851 LangAS getStringLiteralAddressSpace() const;
853 /// Return the address of the given function. If Ty is non-null, then this
854 /// function will use the specified type if it has to create it.
855 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
856 bool ForVTable = false,
857 bool DontDefer = false,
858 ForDefinition_t IsForDefinition
861 /// Get the address of the RTTI descriptor for the given type.
862 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
864 /// Get the address of a GUID.
865 ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
867 /// Get the address of the thunk for the given global decl.
868 llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
871 /// Get a reference to the target of VD.
872 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
874 /// Returns the assumed alignment of an opaque pointer to the given class.
875 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
877 /// Returns the minimum object size for an object of the given class type
878 /// (or a class derived from it).
879 CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
881 /// Returns the minimum object size for an object of the given type.
882 CharUnits getMinimumObjectSize(QualType Ty) {
883 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
884 return getMinimumClassObjectSize(RD);
885 return getContext().getTypeSizeInChars(Ty);
888 /// Returns the assumed alignment of a virtual base of a class.
889 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
890 const CXXRecordDecl *Derived,
891 const CXXRecordDecl *VBase);
893 /// Given a class pointer with an actual known alignment, and the
894 /// expected alignment of an object at a dynamic offset w.r.t that
895 /// pointer, return the alignment to assume at the offset.
896 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
897 const CXXRecordDecl *Class,
898 CharUnits ExpectedTargetAlign);
901 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
902 CastExpr::path_const_iterator Start,
903 CastExpr::path_const_iterator End);
905 /// Returns the offset from a derived class to a class. Returns null if the
908 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
909 CastExpr::path_const_iterator PathBegin,
910 CastExpr::path_const_iterator PathEnd);
912 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
914 /// Fetches the global unique block count.
915 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
917 /// Fetches the type of a generic block descriptor.
918 llvm::Type *getBlockDescriptorType();
920 /// The type of a generic block literal.
921 llvm::Type *getGenericBlockLiteralType();
923 /// Gets the address of a block which requires no captures.
924 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
926 /// Returns the address of a block which requires no caputres, or null if
927 /// we've yet to emit the block for BE.
928 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
929 return EmittedGlobalBlocks.lookup(BE);
932 /// Notes that BE's global block is available via Addr. Asserts that BE
933 /// isn't already emitted.
934 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
936 /// Return a pointer to a constant CFString object for the given string.
937 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
939 /// Return a pointer to a constant NSString object for the given string. Or a
940 /// user defined String object as defined via
941 /// -fconstant-string-class=class_name option.
942 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
944 /// Return a constant array for the given string.
945 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
947 /// Return a pointer to a constant array for the given string literal.
949 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
950 StringRef Name = ".str");
952 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
954 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
956 /// Returns a pointer to a character array containing the literal and a
957 /// terminating '\0' character. The result has pointer to array type.
959 /// \param GlobalName If provided, the name to use for the global (if one is
962 GetAddrOfConstantCString(const std::string &Str,
963 const char *GlobalName = nullptr);
965 /// Returns a pointer to a constant global variable for the given file-scope
966 /// compound literal expression.
967 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
969 /// If it's been emitted already, returns the GlobalVariable corresponding to
970 /// a compound literal. Otherwise, returns null.
971 llvm::GlobalVariable *
972 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
974 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
976 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
977 llvm::GlobalVariable *GV);
979 /// Returns a pointer to a global variable representing a temporary
980 /// with static or thread storage duration.
981 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
984 /// Retrieve the record type that describes the state of an
985 /// Objective-C fast enumeration loop (for..in).
986 QualType getObjCFastEnumerationStateType();
988 // Produce code for this constructor/destructor. This method doesn't try
989 // to apply any ABI rules about which other constructors/destructors
990 // are needed or if they are alias to each other.
991 llvm::Function *codegenCXXStructor(GlobalDecl GD);
993 /// Return the address of the constructor/destructor of the given type.
995 getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
996 llvm::FunctionType *FnType = nullptr,
997 bool DontDefer = false,
998 ForDefinition_t IsForDefinition = NotForDefinition) {
999 return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
1005 llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
1006 GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
1007 llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
1008 ForDefinition_t IsForDefinition = NotForDefinition);
1010 /// Given a builtin id for a function like "__builtin_fabsf", return a
1011 /// Function* for "fabsf".
1012 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
1013 unsigned BuiltinID);
1015 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
1017 /// Emit code for a single top level declaration.
1018 void EmitTopLevelDecl(Decl *D);
1020 /// Stored a deferred empty coverage mapping for an unused
1021 /// and thus uninstrumented top level declaration.
1022 void AddDeferredUnusedCoverageMapping(Decl *D);
1024 /// Remove the deferred empty coverage mapping as this
1025 /// declaration is actually instrumented.
1026 void ClearUnusedCoverageMapping(const Decl *D);
1028 /// Emit all the deferred coverage mappings
1029 /// for the uninstrumented functions.
1030 void EmitDeferredUnusedCoverageMappings();
1032 /// Emit an alias for "main" if it has no arguments (needed for wasm).
1033 void EmitMainVoidAlias();
1035 /// Tell the consumer that this variable has been instantiated.
1036 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
1038 /// If the declaration has internal linkage but is inside an
1039 /// extern "C" linkage specification, prepare to emit an alias for it
1040 /// to the expected name.
1041 template<typename SomeDecl>
1042 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
1044 /// Add a global to a list to be added to the llvm.used metadata.
1045 void addUsedGlobal(llvm::GlobalValue *GV);
1047 /// Add a global to a list to be added to the llvm.compiler.used metadata.
1048 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1050 /// Add a destructor and object to add to the C++ global destructor function.
1051 void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
1052 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1053 DtorFn.getCallee(), Object);
1056 /// Add an sterm finalizer to the C++ global cleanup function.
1057 void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
1058 CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1059 DtorFn.getCallee(), nullptr);
1062 /// Create or return a runtime function declaration with the specified type
1063 /// and name. If \p AssumeConvergent is true, the call will have the
1064 /// convergent attribute added.
1065 llvm::FunctionCallee
1066 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1067 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1068 bool Local = false, bool AssumeConvergent = false);
1070 /// Create or return a runtime function declaration with the specified type
1071 /// and name. This will automatically add the convergent attribute to the
1072 /// function declaration.
1073 llvm::FunctionCallee CreateConvergentRuntimeFunction(
1074 llvm::FunctionType *Ty, StringRef Name,
1075 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1076 bool Local = false) {
1077 return CreateRuntimeFunction(Ty, Name, ExtraAttrs, Local, true);
1080 /// Create a new runtime global variable with the specified type and name.
1081 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1084 ///@name Custom Blocks Runtime Interfaces
1087 llvm::Constant *getNSConcreteGlobalBlock();
1088 llvm::Constant *getNSConcreteStackBlock();
1089 llvm::FunctionCallee getBlockObjectAssign();
1090 llvm::FunctionCallee getBlockObjectDispose();
1094 llvm::Function *getLLVMLifetimeStartFn();
1095 llvm::Function *getLLVMLifetimeEndFn();
1097 // Make sure that this type is translated.
1098 void UpdateCompletedType(const TagDecl *TD);
1100 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1102 /// Emit type info if type of an expression is a variably modified
1103 /// type. Also emit proper debug info for cast types.
1104 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1105 CodeGenFunction *CGF = nullptr);
1107 /// Return the result of value-initializing the given type, i.e. a null
1108 /// expression of the given type. This is usually, but not always, an LLVM
1110 llvm::Constant *EmitNullConstant(QualType T);
1112 /// Return a null constant appropriate for zero-initializing a base class with
1113 /// the given type. This is usually, but not always, an LLVM null constant.
1114 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1116 /// Emit a general error that something can't be done.
1117 void Error(SourceLocation loc, StringRef error);
1119 /// Print out an error that codegen doesn't support the specified stmt yet.
1120 void ErrorUnsupported(const Stmt *S, const char *Type);
1122 /// Print out an error that codegen doesn't support the specified decl yet.
1123 void ErrorUnsupported(const Decl *D, const char *Type);
1125 /// Set the attributes on the LLVM function for the given decl and function
1126 /// info. This applies attributes necessary for handling the ABI as well as
1127 /// user specified attributes like section.
1128 void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1129 const CGFunctionInfo &FI);
1131 /// Set the LLVM function attributes (sext, zext, etc).
1132 void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1135 /// Set the LLVM function attributes which only apply to a function
1137 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1139 /// Return true iff the given type uses 'sret' when used as a return type.
1140 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1142 /// Return true iff the given type uses an argument slot when 'sret' is used
1143 /// as a return type.
1144 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1146 /// Return true iff the given type uses 'fpret' when used as a return type.
1147 bool ReturnTypeUsesFPRet(QualType ResultType);
1149 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1150 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1152 /// Get the LLVM attributes and calling convention to use for a particular
1155 /// \param Name - The function name.
1156 /// \param Info - The function type information.
1157 /// \param CalleeInfo - The callee information these attributes are being
1158 /// constructed for. If valid, the attributes applied to this decl may
1159 /// contribute to the function attributes and calling convention.
1160 /// \param Attrs [out] - On return, the attribute list to use.
1161 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1162 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1163 CGCalleeInfo CalleeInfo,
1164 llvm::AttributeList &Attrs, unsigned &CallingConv,
1165 bool AttrOnCallSite);
1167 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1168 /// though we had emitted it ourselves. We remove any attributes on F that
1169 /// conflict with the attributes we add here.
1171 /// This is useful for adding attrs to bitcode modules that you want to link
1172 /// with but don't control, such as CUDA's libdevice. When linking with such
1173 /// a bitcode library, you might want to set e.g. its functions'
1174 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1175 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1176 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1177 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1178 /// function in the bitcode library!
1180 /// With the exception of fast-math attrs, this will only make the attributes
1181 /// on the function more conservative. But it's unsafe to call this on a
1182 /// function which relies on particular fast-math attributes for correctness.
1183 /// It's up to you to ensure that this is safe.
1184 void addDefaultFunctionDefinitionAttributes(llvm::Function &F);
1186 /// Like the overload taking a `Function &`, but intended specifically
1187 /// for frontends that want to build on Clang's target-configuration logic.
1188 void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
1190 StringRef getMangledName(GlobalDecl GD);
1191 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1193 void EmitTentativeDefinition(const VarDecl *D);
1195 void EmitExternalDeclaration(const VarDecl *D);
1197 void EmitVTable(CXXRecordDecl *Class);
1199 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1201 /// Appends Opts to the "llvm.linker.options" metadata value.
1202 void AppendLinkerOptions(StringRef Opts);
1204 /// Appends a detect mismatch command to the linker options.
1205 void AddDetectMismatch(StringRef Name, StringRef Value);
1207 /// Appends a dependent lib to the appropriate metadata value.
1208 void AddDependentLib(StringRef Lib);
1211 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1213 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1214 F->setLinkage(getFunctionLinkage(GD));
1217 /// Return the appropriate linkage for the vtable, VTT, and type information
1218 /// of the given class.
1219 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1221 /// Return the store size, in character units, of the given LLVM type.
1222 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1224 /// Returns LLVM linkage for a declarator.
1225 llvm::GlobalValue::LinkageTypes
1226 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1227 bool IsConstantVariable);
1229 /// Returns LLVM linkage for a declarator.
1230 llvm::GlobalValue::LinkageTypes
1231 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1233 /// Emit all the global annotations.
1234 void EmitGlobalAnnotations();
1236 /// Emit an annotation string.
1237 llvm::Constant *EmitAnnotationString(StringRef Str);
1239 /// Emit the annotation's translation unit.
1240 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1242 /// Emit the annotation line number.
1243 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1245 /// Generate the llvm::ConstantStruct which contains the annotation
1246 /// information for a given GlobalValue. The annotation struct is
1247 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1248 /// GlobalValue being annotated. The second field is the constant string
1249 /// created from the AnnotateAttr's annotation. The third field is a constant
1250 /// string containing the name of the translation unit. The fourth field is
1251 /// the line number in the file of the annotated value declaration.
1252 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1253 const AnnotateAttr *AA,
1256 /// Add global annotations that are set on D, for the global GV. Those
1257 /// annotations are emitted during finalization of the LLVM code.
1258 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1260 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1261 SourceLocation Loc) const;
1263 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1265 StringRef Category = StringRef()) const;
1267 /// Imbue XRay attributes to a function, applying the always/never attribute
1268 /// lists in the process. Returns true if we did imbue attributes this way,
1269 /// false otherwise.
1270 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1271 StringRef Category = StringRef()) const;
1273 SanitizerMetadata *getSanitizerMetadata() {
1274 return SanitizerMD.get();
1277 void addDeferredVTable(const CXXRecordDecl *RD) {
1278 DeferredVTables.push_back(RD);
1281 /// Emit code for a single global function or var decl. Forward declarations
1282 /// are emitted lazily.
1283 void EmitGlobal(GlobalDecl D);
1285 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1287 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1289 /// Set attributes which are common to any form of a global definition (alias,
1290 /// Objective-C method, function, global variable).
1292 /// NOTE: This should only be called for definitions.
1293 void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1295 void addReplacement(StringRef Name, llvm::Constant *C);
1297 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1299 /// Emit a code for threadprivate directive.
1300 /// \param D Threadprivate declaration.
1301 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1303 /// Emit a code for declare reduction construct.
1304 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1305 CodeGenFunction *CGF = nullptr);
1307 /// Emit a code for declare mapper construct.
1308 void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
1309 CodeGenFunction *CGF = nullptr);
1311 /// Emit a code for requires directive.
1312 /// \param D Requires declaration
1313 void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1315 /// Returns whether the given record has hidden LTO visibility and therefore
1316 /// may participate in (single-module) CFI and whole-program vtable
1318 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1320 /// Returns whether the given record has public std LTO visibility
1321 /// and therefore may not participate in (single-module) CFI and whole-program
1322 /// vtable optimization.
1323 bool HasLTOVisibilityPublicStd(const CXXRecordDecl *RD);
1325 /// Returns the vcall visibility of the given type. This is the scope in which
1326 /// a virtual function call could be made which ends up being dispatched to a
1327 /// member function of this class. This scope can be wider than the visibility
1328 /// of the class itself when the class has a more-visible dynamic base class.
1329 llvm::GlobalObject::VCallVisibility
1330 GetVCallVisibilityLevel(const CXXRecordDecl *RD);
1332 /// Emit type metadata for the given vtable using the given layout.
1333 void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1334 llvm::GlobalVariable *VTable,
1335 const VTableLayout &VTLayout);
1337 /// Generate a cross-DSO type identifier for MD.
1338 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1340 /// Create a metadata identifier for the given type. This may either be an
1341 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1342 /// internal identifiers).
1343 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1345 /// Create a metadata identifier that is intended to be used to check virtual
1346 /// calls via a member function pointer.
1347 llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1349 /// Create a metadata identifier for the generalization of the given type.
1350 /// This may either be an MDString (for external identifiers) or a distinct
1351 /// unnamed MDNode (for internal identifiers).
1352 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1354 /// Create and attach type metadata to the given function.
1355 void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1358 /// Returns whether this module needs the "all-vtables" type identifier.
1359 bool NeedAllVtablesTypeId() const;
1361 /// Create and attach type metadata for the given vtable.
1362 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1363 const CXXRecordDecl *RD);
1365 /// Return a vector of most-base classes for RD. This is used to implement
1366 /// control flow integrity checks for member function pointers.
1368 /// A most-base class of a class C is defined as a recursive base class of C,
1369 /// including C itself, that does not have any bases.
1370 std::vector<const CXXRecordDecl *>
1371 getMostBaseClasses(const CXXRecordDecl *RD);
1373 /// Get the declaration of std::terminate for the platform.
1374 llvm::FunctionCallee getTerminateFn();
1376 llvm::SanitizerStatReport &getSanStats();
1379 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1381 /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
1382 /// information in the program executable. The argument information stored
1383 /// includes the argument name, its type, the address and access qualifiers
1384 /// used. This helper can be used to generate metadata for source code kernel
1385 /// function as well as generated implicitly kernels. If a kernel is generated
1386 /// implicitly null value has to be passed to the last two parameters,
1387 /// otherwise all parameters must have valid non-null values.
1388 /// \param FN is a pointer to IR function being generated.
1389 /// \param FD is a pointer to function declaration if any.
1390 /// \param CGF is a pointer to CodeGenFunction that generates this function.
1391 void GenOpenCLArgMetadata(llvm::Function *FN,
1392 const FunctionDecl *FD = nullptr,
1393 CodeGenFunction *CGF = nullptr);
1395 /// Get target specific null pointer.
1396 /// \param T is the LLVM type of the null pointer.
1397 /// \param QT is the clang QualType of the null pointer.
1398 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1400 CharUnits getNaturalTypeAlignment(QualType T,
1401 LValueBaseInfo *BaseInfo = nullptr,
1402 TBAAAccessInfo *TBAAInfo = nullptr,
1403 bool forPointeeType = false);
1404 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1405 LValueBaseInfo *BaseInfo = nullptr,
1406 TBAAAccessInfo *TBAAInfo = nullptr);
1407 bool stopAutoInit();
1410 llvm::Constant *GetOrCreateLLVMFunction(
1411 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1412 bool DontDefer = false, bool IsThunk = false,
1413 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1414 ForDefinition_t IsForDefinition = NotForDefinition);
1416 llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
1418 const FunctionDecl *FD);
1419 void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD);
1421 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1422 llvm::PointerType *PTy,
1424 ForDefinition_t IsForDefinition
1425 = NotForDefinition);
1427 bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1428 llvm::AttrBuilder &AttrBuilder);
1429 void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1431 /// Set function attributes for a function declaration.
1432 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1433 bool IsIncompleteFunction, bool IsThunk);
1435 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1437 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1438 void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1440 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1441 void EmitExternalVarDeclaration(const VarDecl *D);
1442 void EmitAliasDefinition(GlobalDecl GD);
1443 void emitIFuncDefinition(GlobalDecl GD);
1444 void emitCPUDispatchDefinition(GlobalDecl GD);
1445 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1446 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1448 // C++ related functions.
1450 void EmitDeclContext(const DeclContext *DC);
1451 void EmitLinkageSpec(const LinkageSpecDecl *D);
1453 /// Emit the function that initializes C++ thread_local variables.
1454 void EmitCXXThreadLocalInitFunc();
1456 /// Emit the function that initializes C++ globals.
1457 void EmitCXXGlobalInitFunc();
1459 /// Emit the function that performs cleanup associated with C++ globals.
1460 void EmitCXXGlobalCleanUpFunc();
1462 /// Emit the function that initializes the specified global (if PerformInit is
1463 /// true) and registers its destructor.
1464 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1465 llvm::GlobalVariable *Addr,
1468 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1469 llvm::Function *InitFunc, InitSegAttr *ISA);
1471 // FIXME: Hardcoding priority here is gross.
1472 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1473 llvm::Constant *AssociatedData = nullptr);
1474 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1476 /// EmitCtorList - Generates a global array of functions and priorities using
1477 /// the given list and name. This array will have appending linkage and is
1478 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1479 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1481 /// Emit any needed decls for which code generation was deferred.
1482 void EmitDeferred();
1484 /// Try to emit external vtables as available_externally if they have emitted
1485 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1486 /// is not allowed to create new references to things that need to be emitted
1488 void EmitVTablesOpportunistically();
1490 /// Call replaceAllUsesWith on all pairs in Replacements.
1491 void applyReplacements();
1493 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1494 void applyGlobalValReplacements();
1496 void checkAliases();
1498 std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1500 /// Register functions annotated with __attribute__((destructor)) using
1501 /// __cxa_atexit, if it is available, or atexit otherwise.
1502 void registerGlobalDtorsWithAtExit();
1504 void emitMultiVersionFunctions();
1506 /// Emit any vtables which we deferred and still have a use for.
1507 void EmitDeferredVTables();
1509 /// Emit a dummy function that reference a CoreFoundation symbol when
1510 /// @available is used on Darwin.
1511 void emitAtAvailableLinkGuard();
1513 /// Emit the llvm.used and llvm.compiler.used metadata.
1514 void emitLLVMUsed();
1516 /// Emit the link options introduced by imported modules.
1517 void EmitModuleLinkOptions();
1519 /// Emit aliases for internal-linkage declarations inside "C" language
1520 /// linkage specifications, giving them the "expected" name where possible.
1521 void EmitStaticExternCAliases();
1523 void EmitDeclMetadata();
1525 /// Emit the Clang version as llvm.ident metadata.
1526 void EmitVersionIdentMetadata();
1528 /// Emit the Clang commandline as llvm.commandline metadata.
1529 void EmitCommandLineMetadata();
1531 /// Emit the module flag metadata used to pass options controlling the
1532 /// the backend to LLVM.
1533 void EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts);
1535 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1536 void EmitOpenCLMetadata();
1538 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1539 /// .gcda files in a way that persists in .bc files.
1540 void EmitCoverageFile();
1542 /// Determine whether the definition must be emitted; if this returns \c
1543 /// false, the definition can be emitted lazily if it's used.
1544 bool MustBeEmitted(const ValueDecl *D);
1546 /// Determine whether the definition can be emitted eagerly, or should be
1547 /// delayed until the end of the translation unit. This is relevant for
1548 /// definitions whose linkage can change, e.g. implicit function instantions
1549 /// which may later be explicitly instantiated.
1550 bool MayBeEmittedEagerly(const ValueDecl *D);
1552 /// Check whether we can use a "simpler", more core exceptions personality
1554 void SimplifyPersonality();
1556 /// Helper function for ConstructAttributeList and
1557 /// addDefaultFunctionDefinitionAttributes. Builds a set of function
1558 /// attributes to add to a function with the given properties.
1559 void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
1560 bool AttrOnCallSite,
1561 llvm::AttrBuilder &FuncAttrs);
1563 llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1567 } // end namespace CodeGen
1568 } // end namespace clang
1570 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H