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