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_autoreleasePoolPop(void*);
123 llvm::Constant *objc_autoreleasePoolPop;
125 /// void *objc_autoreleasePoolPush(void);
126 llvm::Constant *objc_autoreleasePoolPush;
128 /// id objc_autorelease(id);
129 llvm::Constant *objc_autorelease;
131 /// id objc_autoreleaseReturnValue(id);
132 llvm::Constant *objc_autoreleaseReturnValue;
134 /// void objc_copyWeak(id *dest, id *src);
135 llvm::Constant *objc_copyWeak;
137 /// void objc_destroyWeak(id*);
138 llvm::Constant *objc_destroyWeak;
140 /// id objc_initWeak(id*, id);
141 llvm::Constant *objc_initWeak;
143 /// id objc_loadWeak(id*);
144 llvm::Constant *objc_loadWeak;
146 /// id objc_loadWeakRetained(id*);
147 llvm::Constant *objc_loadWeakRetained;
149 /// void objc_moveWeak(id *dest, id *src);
150 llvm::Constant *objc_moveWeak;
152 /// id objc_retain(id);
153 llvm::Constant *objc_retain;
155 /// id objc_retainAutorelease(id);
156 llvm::Constant *objc_retainAutorelease;
158 /// id objc_retainAutoreleaseReturnValue(id);
159 llvm::Constant *objc_retainAutoreleaseReturnValue;
161 /// id objc_retainAutoreleasedReturnValue(id);
162 llvm::Constant *objc_retainAutoreleasedReturnValue;
164 /// id objc_retainBlock(id);
165 llvm::Constant *objc_retainBlock;
167 /// void objc_release(id);
168 llvm::Constant *objc_release;
170 /// void objc_storeStrong(id*, id);
171 llvm::Constant *objc_storeStrong;
173 /// id objc_storeWeak(id*, id);
174 llvm::Constant *objc_storeWeak;
176 /// id objc_unsafeClaimAutoreleasedReturnValue(id);
177 llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
179 /// A void(void) inline asm to use to mark that the return value of
180 /// a call will be immediately retain.
181 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
183 /// void clang.arc.use(...);
184 llvm::Constant *clang_arc_use;
187 /// This class records statistics on instrumentation based profiling.
188 class InstrProfStats {
189 uint32_t VisitedInMainFile;
190 uint32_t MissingInMainFile;
197 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
199 /// Record that we've visited a function and whether or not that function was
200 /// in the main source file.
201 void addVisited(bool MainFile) {
206 /// Record that a function we've visited has no profile data.
207 void addMissing(bool MainFile) {
212 /// Record that a function we've visited has mismatched profile data.
213 void addMismatched(bool MainFile) { ++Mismatched; }
214 /// Whether or not the stats we've gathered indicate any potential problems.
215 bool hasDiagnostics() { return Missing || Mismatched; }
216 /// Report potential problems we've found to \c Diags.
217 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
220 /// A pair of helper functions for a __block variable.
221 class BlockByrefHelpers : public llvm::FoldingSetNode {
222 // MSVC requires this type to be complete in order to process this
225 llvm::Constant *CopyHelper;
226 llvm::Constant *DisposeHelper;
228 /// The alignment of the field. This is important because
229 /// different offsets to the field within the byref struct need to
230 /// have different helper functions.
233 BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
234 BlockByrefHelpers(const BlockByrefHelpers &) = default;
235 virtual ~BlockByrefHelpers();
237 void Profile(llvm::FoldingSetNodeID &id) const {
238 id.AddInteger(Alignment.getQuantity());
241 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
243 virtual bool needsCopy() const { return true; }
244 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
246 virtual bool needsDispose() const { return true; }
247 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
250 /// This class organizes the cross-function state that is used while generating
252 class CodeGenModule : public CodeGenTypeCache {
253 CodeGenModule(const CodeGenModule &) = delete;
254 void operator=(const CodeGenModule &) = delete;
258 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
259 Structor(int Priority, llvm::Constant *Initializer,
260 llvm::Constant *AssociatedData)
261 : Priority(Priority), Initializer(Initializer),
262 AssociatedData(AssociatedData) {}
264 llvm::Constant *Initializer;
265 llvm::Constant *AssociatedData;
268 typedef std::vector<Structor> CtorList;
272 const LangOptions &LangOpts;
273 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
274 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
275 const CodeGenOptions &CodeGenOpts;
276 llvm::Module &TheModule;
277 DiagnosticsEngine &Diags;
278 const TargetInfo &Target;
279 std::unique_ptr<CGCXXABI> ABI;
280 llvm::LLVMContext &VMContext;
282 std::unique_ptr<CodeGenTBAA> TBAA;
284 mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
286 // This should not be moved earlier, since its initialization depends on some
287 // of the previous reference members being already initialized and also checks
288 // if TheTargetCodeGenInfo is NULL
291 /// Holds information about C++ vtables.
292 CodeGenVTables VTables;
294 std::unique_ptr<CGObjCRuntime> ObjCRuntime;
295 std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
296 std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
297 std::unique_ptr<CGCUDARuntime> CUDARuntime;
298 std::unique_ptr<CGDebugInfo> DebugInfo;
299 std::unique_ptr<ObjCEntrypoints> ObjCData;
300 llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
301 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
302 InstrProfStats PGOStats;
303 std::unique_ptr<llvm::SanitizerStatReport> SanStats;
305 // A set of references that have only been seen via a weakref so far. This is
306 // used to remove the weak of the reference if we ever see a direct reference
308 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
310 /// This contains all the decls which have definitions but/ which are deferred
311 /// for emission and therefore should only be output if they are actually
312 /// used. If a decl is in this, then it is known to have not been referenced
314 std::map<StringRef, GlobalDecl> DeferredDecls;
316 /// This is a list of deferred decls which we have seen that *are* actually
317 /// referenced. These get code generated when the module is done.
318 std::vector<GlobalDecl> DeferredDeclsToEmit;
319 void addDeferredDeclToEmit(GlobalDecl GD) {
320 DeferredDeclsToEmit.emplace_back(GD);
323 /// List of alias we have emitted. Used to make sure that what they point to
324 /// is defined once we get to the end of the of the translation unit.
325 std::vector<GlobalDecl> Aliases;
327 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
328 ReplacementsTy Replacements;
330 /// List of global values to be replaced with something else. Used when we
331 /// want to replace a GlobalValue but can't identify it by its mangled name
332 /// anymore (because the name is already taken).
333 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
334 GlobalValReplacements;
336 /// Set of global decls for which we already diagnosed mangled name conflict.
337 /// Required to not issue a warning (on a mangling conflict) multiple times
338 /// for the same decl.
339 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
341 /// A queue of (optional) vtables to consider emitting.
342 std::vector<const CXXRecordDecl*> DeferredVTables;
344 /// A queue of (optional) vtables that may be emitted opportunistically.
345 std::vector<const CXXRecordDecl *> OpportunisticVTables;
347 /// List of global values which are required to be present in the object file;
348 /// bitcast to i8*. This is used for forcing visibility of symbols which may
349 /// otherwise be optimized out.
350 std::vector<llvm::WeakTrackingVH> LLVMUsed;
351 std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
353 /// Store the list of global constructors and their respective priorities to
354 /// be emitted when the translation unit is complete.
355 CtorList GlobalCtors;
357 /// Store the list of global destructors and their respective priorities to be
358 /// emitted when the translation unit is complete.
359 CtorList GlobalDtors;
361 /// An ordered map of canonical GlobalDecls to their mangled names.
362 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
363 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
365 /// Global annotations.
366 std::vector<llvm::Constant*> Annotations;
368 /// Map used to get unique annotation strings.
369 llvm::StringMap<llvm::Constant*> AnnotationStrings;
371 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
373 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
374 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
375 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
376 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
378 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
379 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
381 /// Map used to get unique type descriptor constants for sanitizers.
382 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
384 /// Map used to track internal linkage functions declared within
385 /// extern "C" regions.
386 typedef llvm::MapVector<IdentifierInfo *,
387 llvm::GlobalValue *> StaticExternCMap;
388 StaticExternCMap StaticExternCValues;
390 /// \brief thread_local variables defined or used in this TU.
391 std::vector<const VarDecl *> CXXThreadLocals;
393 /// \brief thread_local variables with initializers that need to run
394 /// before any thread_local variable in this TU is odr-used.
395 std::vector<llvm::Function *> CXXThreadLocalInits;
396 std::vector<const VarDecl *> CXXThreadLocalInitVars;
398 /// Global variables with initializers that need to run before main.
399 std::vector<llvm::Function *> CXXGlobalInits;
401 /// When a C++ decl with an initializer is deferred, null is
402 /// appended to CXXGlobalInits, and the index of that null is placed
403 /// here so that the initializer will be performed in the correct
404 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
405 /// that we don't re-emit the initializer.
406 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
408 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
410 struct GlobalInitPriorityCmp {
411 bool operator()(const GlobalInitData &LHS,
412 const GlobalInitData &RHS) const {
413 return LHS.first.priority < RHS.first.priority;
417 /// Global variables with initializers whose order of initialization is set by
418 /// init_priority attribute.
419 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
421 /// Global destructor functions and arguments that need to run on termination.
422 std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>> CXXGlobalDtors;
424 /// \brief The complete set of modules that has been imported.
425 llvm::SetVector<clang::Module *> ImportedModules;
427 /// \brief The set of modules for which the module initializers
428 /// have been emitted.
429 llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
431 /// \brief A vector of metadata strings.
432 SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
434 /// @name Cache for Objective-C runtime types
437 /// Cached reference to the class for constant strings. This value has type
438 /// int * but is actually an Obj-C class pointer.
439 llvm::WeakTrackingVH CFConstantStringClassRef;
441 /// \brief The type used to describe the state of a fast enumeration in
442 /// Objective-C's for..in loop.
443 QualType ObjCFastEnumerationStateType;
447 /// Lazily create the Objective-C runtime
448 void createObjCRuntime();
450 void createOpenCLRuntime();
451 void createOpenMPRuntime();
452 void createCUDARuntime();
454 bool isTriviallyRecursive(const FunctionDecl *F);
455 bool shouldEmitFunction(GlobalDecl GD);
456 bool shouldOpportunisticallyEmitVTables();
457 /// Map used to be sure we don't emit the same CompoundLiteral twice.
458 llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
459 EmittedCompoundLiterals;
461 /// Map of the global blocks we've emitted, so that we don't have to re-emit
462 /// them if the constexpr evaluator gets aggressive.
463 llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
465 /// @name Cache for Blocks Runtime Globals
468 llvm::Constant *NSConcreteGlobalBlock = nullptr;
469 llvm::Constant *NSConcreteStackBlock = nullptr;
471 llvm::Constant *BlockObjectAssign = nullptr;
472 llvm::Constant *BlockObjectDispose = nullptr;
474 llvm::Type *BlockDescriptorType = nullptr;
475 llvm::Type *GenericBlockLiteralType = nullptr;
478 int GlobalUniqueCount;
481 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
482 llvm::Constant *LifetimeStartFn = nullptr;
484 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
485 llvm::Constant *LifetimeEndFn = nullptr;
487 GlobalDecl initializedGlobalDecl;
489 std::unique_ptr<SanitizerMetadata> SanitizerMD;
493 llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
495 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
497 /// Mapping from canonical types to their metadata identifiers. We need to
498 /// maintain this mapping because identifiers may be formed from distinct
500 typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
501 MetadataTypeMap MetadataIdMap;
502 MetadataTypeMap GeneralizedMetadataIdMap;
505 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
506 const PreprocessorOptions &ppopts,
507 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
508 DiagnosticsEngine &Diags,
509 CoverageSourceInfo *CoverageInfo = nullptr);
515 /// Finalize LLVM code generation.
518 /// Return true if we should emit location information for expressions.
519 bool getExpressionLocationsEnabled() const;
521 /// Return a reference to the configured Objective-C runtime.
522 CGObjCRuntime &getObjCRuntime() {
523 if (!ObjCRuntime) createObjCRuntime();
527 /// Return true iff an Objective-C runtime has been configured.
528 bool hasObjCRuntime() { return !!ObjCRuntime; }
530 /// Return a reference to the configured OpenCL runtime.
531 CGOpenCLRuntime &getOpenCLRuntime() {
532 assert(OpenCLRuntime != nullptr);
533 return *OpenCLRuntime;
536 /// Return a reference to the configured OpenMP runtime.
537 CGOpenMPRuntime &getOpenMPRuntime() {
538 assert(OpenMPRuntime != nullptr);
539 return *OpenMPRuntime;
542 /// Return a reference to the configured CUDA runtime.
543 CGCUDARuntime &getCUDARuntime() {
544 assert(CUDARuntime != nullptr);
548 ObjCEntrypoints &getObjCEntrypoints() const {
549 assert(ObjCData != nullptr);
553 // Version checking function, used to implement ObjC's @available:
554 // i32 @__isOSVersionAtLeast(i32, i32, i32)
555 llvm::Constant *IsOSVersionAtLeastFn = nullptr;
557 InstrProfStats &getPGOStats() { return PGOStats; }
558 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
560 CoverageMappingModuleGen *getCoverageMapping() const {
561 return CoverageMapping.get();
564 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
565 return StaticLocalDeclMap[D];
567 void setStaticLocalDeclAddress(const VarDecl *D,
569 StaticLocalDeclMap[D] = C;
573 getOrCreateStaticVarDecl(const VarDecl &D,
574 llvm::GlobalValue::LinkageTypes Linkage);
576 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
577 return StaticLocalDeclGuardMap[D];
579 void setStaticLocalDeclGuardAddress(const VarDecl *D,
580 llvm::GlobalVariable *C) {
581 StaticLocalDeclGuardMap[D] = C;
584 bool lookupRepresentativeDecl(StringRef MangledName,
585 GlobalDecl &Result) const;
587 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
588 return AtomicSetterHelperFnMap[Ty];
590 void setAtomicSetterHelperFnMap(QualType Ty,
591 llvm::Constant *Fn) {
592 AtomicSetterHelperFnMap[Ty] = Fn;
595 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
596 return AtomicGetterHelperFnMap[Ty];
598 void setAtomicGetterHelperFnMap(QualType Ty,
599 llvm::Constant *Fn) {
600 AtomicGetterHelperFnMap[Ty] = Fn;
603 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
604 return TypeDescriptorMap[Ty];
606 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
607 TypeDescriptorMap[Ty] = C;
610 CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
612 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
613 if (!NoObjCARCExceptionsMetadata)
614 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
615 return NoObjCARCExceptionsMetadata;
618 ASTContext &getContext() const { return Context; }
619 const LangOptions &getLangOpts() const { return LangOpts; }
620 const HeaderSearchOptions &getHeaderSearchOpts()
621 const { return HeaderSearchOpts; }
622 const PreprocessorOptions &getPreprocessorOpts()
623 const { return PreprocessorOpts; }
624 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
625 llvm::Module &getModule() const { return TheModule; }
626 DiagnosticsEngine &getDiags() const { return Diags; }
627 const llvm::DataLayout &getDataLayout() const {
628 return TheModule.getDataLayout();
630 const TargetInfo &getTarget() const { return Target; }
631 const llvm::Triple &getTriple() const { return Target.getTriple(); }
632 bool supportsCOMDAT() const;
633 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
635 CGCXXABI &getCXXABI() const { return *ABI; }
636 llvm::LLVMContext &getLLVMContext() { return VMContext; }
638 bool shouldUseTBAA() const { return TBAA != nullptr; }
640 const TargetCodeGenInfo &getTargetCodeGenInfo();
642 CodeGenTypes &getTypes() { return Types; }
644 CodeGenVTables &getVTables() { return VTables; }
646 ItaniumVTableContext &getItaniumVTableContext() {
647 return VTables.getItaniumVTableContext();
650 MicrosoftVTableContext &getMicrosoftVTableContext() {
651 return VTables.getMicrosoftVTableContext();
654 CtorList &getGlobalCtors() { return GlobalCtors; }
655 CtorList &getGlobalDtors() { return GlobalDtors; }
657 /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
659 llvm::MDNode *getTBAATypeInfo(QualType QTy);
661 /// getTBAAAccessInfo - Get TBAA information that describes an access to
662 /// an object of the given type.
663 TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
665 /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
666 /// access to a virtual table pointer.
667 TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
669 llvm::MDNode *getTBAAStructInfo(QualType QTy);
671 /// getTBAABaseTypeInfo - Get metadata that describes the given base access
672 /// type. Return null if the type is not suitable for use in TBAA access tags.
673 llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
675 /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
676 llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
678 /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
680 TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
681 TBAAAccessInfo TargetInfo);
683 /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
684 /// purposes of conditional operator.
685 TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
686 TBAAAccessInfo InfoB);
688 /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
690 TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
691 if (Base.getTBAAInfo().isMayAlias())
692 return TBAAAccessInfo::getMayAliasInfo();
693 return getTBAAAccessInfo(AccessType);
696 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
698 bool isPaddedAtomicType(QualType type);
699 bool isPaddedAtomicType(const AtomicType *type);
701 /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
702 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
703 TBAAAccessInfo TBAAInfo);
705 /// Adds !invariant.barrier !tag to instruction
706 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
707 const CXXRecordDecl *RD);
709 /// Emit the given number of characters as a value of type size_t.
710 llvm::ConstantInt *getSize(CharUnits numChars);
712 /// Set the visibility for the given LLVM GlobalValue.
713 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D,
714 ForDefinition_t IsForDefinition) const;
716 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
717 /// variable declaration D.
718 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
720 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
722 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
723 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
724 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
726 llvm_unreachable("unknown visibility!");
729 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
730 ForDefinition_t IsForDefinition
733 /// Will return a global variable of the given type. If a variable with a
734 /// different type already exists then a new variable with the right type
735 /// will be created and all uses of the old variable will be replaced with a
736 /// bitcast to the new variable.
737 llvm::GlobalVariable *
738 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
739 llvm::GlobalValue::LinkageTypes Linkage);
742 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
743 const CGFunctionInfo &FI,
744 SourceLocation Loc = SourceLocation(),
747 /// Return the AST address space of the underlying global variable for D, as
748 /// determined by its declaration. Normally this is the same as the address
749 /// space of D's type, but in CUDA, address spaces are associated with
750 /// declarations, not types. If D is nullptr, return the default address
751 /// space for global variable.
753 /// For languages without explicit address spaces, if D has default address
754 /// space, target-specific global or constant address space may be returned.
755 LangAS GetGlobalVarAddressSpace(const VarDecl *D);
757 /// Return the llvm::Constant for the address of the given global variable.
758 /// If Ty is non-null and if the global doesn't exist, then it will be created
759 /// with the specified type instead of whatever the normal requested type
760 /// would be. If IsForDefinition is true, it is guranteed that an actual
761 /// global with type Ty will be returned, not conversion of a variable with
762 /// the same mangled name but some other type.
763 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
764 llvm::Type *Ty = nullptr,
765 ForDefinition_t IsForDefinition
768 /// Return the address of the given function. If Ty is non-null, then this
769 /// function will use the specified type if it has to create it.
770 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
771 bool ForVTable = false,
772 bool DontDefer = false,
773 ForDefinition_t IsForDefinition
776 /// Get the address of the RTTI descriptor for the given type.
777 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
779 /// Get the address of a uuid descriptor .
780 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
782 /// Get the address of the thunk for the given global decl.
783 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
785 /// Get a reference to the target of VD.
786 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
788 /// Returns the assumed alignment of an opaque pointer to the given class.
789 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
791 /// Returns the assumed alignment of a virtual base of a class.
792 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
793 const CXXRecordDecl *Derived,
794 const CXXRecordDecl *VBase);
796 /// Given a class pointer with an actual known alignment, and the
797 /// expected alignment of an object at a dynamic offset w.r.t that
798 /// pointer, return the alignment to assume at the offset.
799 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
800 const CXXRecordDecl *Class,
801 CharUnits ExpectedTargetAlign);
804 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
805 CastExpr::path_const_iterator Start,
806 CastExpr::path_const_iterator End);
808 /// Returns the offset from a derived class to a class. Returns null if the
811 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
812 CastExpr::path_const_iterator PathBegin,
813 CastExpr::path_const_iterator PathEnd);
815 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
817 /// Fetches the global unique block count.
818 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
820 /// Fetches the type of a generic block descriptor.
821 llvm::Type *getBlockDescriptorType();
823 /// The type of a generic block literal.
824 llvm::Type *getGenericBlockLiteralType();
826 /// Gets the address of a block which requires no captures.
827 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
829 /// Returns the address of a block which requires no caputres, or null if
830 /// we've yet to emit the block for BE.
831 llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
832 return EmittedGlobalBlocks.lookup(BE);
835 /// Notes that BE's global block is available via Addr. Asserts that BE
836 /// isn't already emitted.
837 void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
839 /// Return a pointer to a constant CFString object for the given string.
840 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
842 /// Return a pointer to a constant NSString object for the given string. Or a
843 /// user defined String object as defined via
844 /// -fconstant-string-class=class_name option.
845 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
847 /// Return a constant array for the given string.
848 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
850 /// Return a pointer to a constant array for the given string literal.
852 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
853 StringRef Name = ".str");
855 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
857 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
859 /// Returns a pointer to a character array containing the literal and a
860 /// terminating '\0' character. The result has pointer to array type.
862 /// \param GlobalName If provided, the name to use for the global (if one is
865 GetAddrOfConstantCString(const std::string &Str,
866 const char *GlobalName = nullptr);
868 /// Returns a pointer to a constant global variable for the given file-scope
869 /// compound literal expression.
870 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
872 /// If it's been emitted already, returns the GlobalVariable corresponding to
873 /// a compound literal. Otherwise, returns null.
874 llvm::GlobalVariable *
875 getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
877 /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
879 void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
880 llvm::GlobalVariable *GV);
882 /// \brief Returns a pointer to a global variable representing a temporary
883 /// with static or thread storage duration.
884 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
887 /// \brief Retrieve the record type that describes the state of an
888 /// Objective-C fast enumeration loop (for..in).
889 QualType getObjCFastEnumerationStateType();
891 // Produce code for this constructor/destructor. This method doesn't try
892 // to apply any ABI rules about which other constructors/destructors
893 // are needed or if they are alias to each other.
894 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
897 /// Return the address of the constructor/destructor of the given type.
899 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
900 const CGFunctionInfo *FnInfo = nullptr,
901 llvm::FunctionType *FnType = nullptr,
902 bool DontDefer = false,
903 ForDefinition_t IsForDefinition = NotForDefinition);
905 /// Given a builtin id for a function like "__builtin_fabsf", return a
906 /// Function* for "fabsf".
907 llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
910 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
912 /// Emit code for a single top level declaration.
913 void EmitTopLevelDecl(Decl *D);
915 /// \brief Stored a deferred empty coverage mapping for an unused
916 /// and thus uninstrumented top level declaration.
917 void AddDeferredUnusedCoverageMapping(Decl *D);
919 /// \brief Remove the deferred empty coverage mapping as this
920 /// declaration is actually instrumented.
921 void ClearUnusedCoverageMapping(const Decl *D);
923 /// \brief Emit all the deferred coverage mappings
924 /// for the uninstrumented functions.
925 void EmitDeferredUnusedCoverageMappings();
927 /// Tell the consumer that this variable has been instantiated.
928 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
930 /// \brief If the declaration has internal linkage but is inside an
931 /// extern "C" linkage specification, prepare to emit an alias for it
932 /// to the expected name.
933 template<typename SomeDecl>
934 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
936 /// Add a global to a list to be added to the llvm.used metadata.
937 void addUsedGlobal(llvm::GlobalValue *GV);
939 /// Add a global to a list to be added to the llvm.compiler.used metadata.
940 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
942 /// Add a destructor and object to add to the C++ global destructor function.
943 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
944 CXXGlobalDtors.emplace_back(DtorFn, Object);
947 /// Create a new runtime function with the specified type and name.
949 CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
950 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
953 /// Create a new compiler builtin function with the specified type and name.
955 CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name,
956 llvm::AttributeList ExtraAttrs = llvm::AttributeList());
957 /// Create a new runtime global variable with the specified type and name.
958 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
961 ///@name Custom Blocks Runtime Interfaces
964 llvm::Constant *getNSConcreteGlobalBlock();
965 llvm::Constant *getNSConcreteStackBlock();
966 llvm::Constant *getBlockObjectAssign();
967 llvm::Constant *getBlockObjectDispose();
971 llvm::Constant *getLLVMLifetimeStartFn();
972 llvm::Constant *getLLVMLifetimeEndFn();
974 // Make sure that this type is translated.
975 void UpdateCompletedType(const TagDecl *TD);
977 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
979 /// \brief Emit type info if type of an expression is a variably modified
980 /// type. Also emit proper debug info for cast types.
981 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
982 CodeGenFunction *CGF = nullptr);
984 /// Return the result of value-initializing the given type, i.e. a null
985 /// expression of the given type. This is usually, but not always, an LLVM
987 llvm::Constant *EmitNullConstant(QualType T);
989 /// Return a null constant appropriate for zero-initializing a base class with
990 /// the given type. This is usually, but not always, an LLVM null constant.
991 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
993 /// Emit a general error that something can't be done.
994 void Error(SourceLocation loc, StringRef error);
996 /// Print out an error that codegen doesn't support the specified stmt yet.
997 void ErrorUnsupported(const Stmt *S, const char *Type);
999 /// Print out an error that codegen doesn't support the specified decl yet.
1000 void ErrorUnsupported(const Decl *D, const char *Type);
1002 /// Set the attributes on the LLVM function for the given decl and function
1003 /// info. This applies attributes necessary for handling the ABI as well as
1004 /// user specified attributes like section.
1005 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
1006 const CGFunctionInfo &FI);
1008 /// Set the LLVM function attributes (sext, zext, etc).
1009 void SetLLVMFunctionAttributes(const Decl *D,
1010 const CGFunctionInfo &Info,
1013 /// Set the LLVM function attributes which only apply to a function
1015 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1017 /// Return true iff the given type uses 'sret' when used as a return type.
1018 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1020 /// Return true iff the given type uses an argument slot when 'sret' is used
1021 /// as a return type.
1022 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1024 /// Return true iff the given type uses 'fpret' when used as a return type.
1025 bool ReturnTypeUsesFPRet(QualType ResultType);
1027 /// Return true iff the given type uses 'fp2ret' when used as a return type.
1028 bool ReturnTypeUsesFP2Ret(QualType ResultType);
1030 /// Get the LLVM attributes and calling convention to use for a particular
1033 /// \param Name - The function name.
1034 /// \param Info - The function type information.
1035 /// \param CalleeInfo - The callee information these attributes are being
1036 /// constructed for. If valid, the attributes applied to this decl may
1037 /// contribute to the function attributes and calling convention.
1038 /// \param Attrs [out] - On return, the attribute list to use.
1039 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1040 void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1041 CGCalleeInfo CalleeInfo,
1042 llvm::AttributeList &Attrs, unsigned &CallingConv,
1043 bool AttrOnCallSite);
1045 /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1046 /// though we had emitted it ourselves. We remove any attributes on F that
1047 /// conflict with the attributes we add here.
1049 /// This is useful for adding attrs to bitcode modules that you want to link
1050 /// with but don't control, such as CUDA's libdevice. When linking with such
1051 /// a bitcode library, you might want to set e.g. its functions'
1052 /// "unsafe-fp-math" attribute to match the attr of the functions you're
1053 /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
1054 /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1055 /// will propagate unsafe-fp-math=false up to every transitive caller of a
1056 /// function in the bitcode library!
1058 /// With the exception of fast-math attrs, this will only make the attributes
1059 /// on the function more conservative. But it's unsafe to call this on a
1060 /// function which relies on particular fast-math attributes for correctness.
1061 /// It's up to you to ensure that this is safe.
1062 void AddDefaultFnAttrs(llvm::Function &F);
1064 // Fills in the supplied string map with the set of target features for the
1065 // passed in function.
1066 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
1067 const FunctionDecl *FD);
1069 StringRef getMangledName(GlobalDecl GD);
1070 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1072 void EmitTentativeDefinition(const VarDecl *D);
1074 void EmitVTable(CXXRecordDecl *Class);
1076 void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1078 /// \brief Appends Opts to the "llvm.linker.options" metadata value.
1079 void AppendLinkerOptions(StringRef Opts);
1081 /// \brief Appends a detect mismatch command to the linker options.
1082 void AddDetectMismatch(StringRef Name, StringRef Value);
1084 /// \brief Appends a dependent lib to the "llvm.linker.options" metadata
1086 void AddDependentLib(StringRef Lib);
1088 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1090 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1091 F->setLinkage(getFunctionLinkage(GD));
1094 /// Set the DLL storage class on F.
1095 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1097 /// Return the appropriate linkage for the vtable, VTT, and type information
1098 /// of the given class.
1099 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1101 /// Return the store size, in character units, of the given LLVM type.
1102 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1104 /// Returns LLVM linkage for a declarator.
1105 llvm::GlobalValue::LinkageTypes
1106 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1107 bool IsConstantVariable);
1109 /// Returns LLVM linkage for a declarator.
1110 llvm::GlobalValue::LinkageTypes
1111 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1113 /// Emit all the global annotations.
1114 void EmitGlobalAnnotations();
1116 /// Emit an annotation string.
1117 llvm::Constant *EmitAnnotationString(StringRef Str);
1119 /// Emit the annotation's translation unit.
1120 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1122 /// Emit the annotation line number.
1123 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1125 /// Generate the llvm::ConstantStruct which contains the annotation
1126 /// information for a given GlobalValue. The annotation struct is
1127 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1128 /// GlobalValue being annotated. The second field is the constant string
1129 /// created from the AnnotateAttr's annotation. The third field is a constant
1130 /// string containing the name of the translation unit. The fourth field is
1131 /// the line number in the file of the annotated value declaration.
1132 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1133 const AnnotateAttr *AA,
1136 /// Add global annotations that are set on D, for the global GV. Those
1137 /// annotations are emitted during finalization of the LLVM code.
1138 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1140 bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1141 SourceLocation Loc) const;
1143 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1145 StringRef Category = StringRef()) const;
1147 /// Imbue XRay attributes to a function, applying the always/never attribute
1148 /// lists in the process. Returns true if we did imbue attributes this way,
1149 /// false otherwise.
1150 bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1151 StringRef Category = StringRef()) const;
1153 SanitizerMetadata *getSanitizerMetadata() {
1154 return SanitizerMD.get();
1157 void addDeferredVTable(const CXXRecordDecl *RD) {
1158 DeferredVTables.push_back(RD);
1161 /// Emit code for a singal global function or var decl. Forward declarations
1162 /// are emitted lazily.
1163 void EmitGlobal(GlobalDecl D);
1165 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
1166 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1168 /// Set attributes for a global definition.
1169 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1172 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1174 /// Set attributes which are common to any form of a global definition (alias,
1175 /// Objective-C method, function, global variable).
1177 /// NOTE: This should only be called for definitions.
1178 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1180 /// Set attributes which must be preserved by an alias. This includes common
1181 /// attributes (i.e. it includes a call to SetCommonAttributes).
1183 /// NOTE: This should only be called for definitions.
1184 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1186 void addReplacement(StringRef Name, llvm::Constant *C);
1188 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1190 /// \brief Emit a code for threadprivate directive.
1191 /// \param D Threadprivate declaration.
1192 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1194 /// \brief Emit a code for declare reduction construct.
1195 void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1196 CodeGenFunction *CGF = nullptr);
1198 /// Returns whether the given record has hidden LTO visibility and therefore
1199 /// may participate in (single-module) CFI and whole-program vtable
1201 bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1203 /// Emit type metadata for the given vtable using the given layout.
1204 void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1205 const VTableLayout &VTLayout);
1207 /// Generate a cross-DSO type identifier for MD.
1208 llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1210 /// Create a metadata identifier for the given type. This may either be an
1211 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1212 /// internal identifiers).
1213 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1215 /// Create a metadata identifier for the generalization of the given type.
1216 /// This may either be an MDString (for external identifiers) or a distinct
1217 /// unnamed MDNode (for internal identifiers).
1218 llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1220 /// Create and attach type metadata to the given function.
1221 void CreateFunctionTypeMetadata(const FunctionDecl *FD, llvm::Function *F);
1223 /// Returns whether this module needs the "all-vtables" type identifier.
1224 bool NeedAllVtablesTypeId() const;
1226 /// Create and attach type metadata for the given vtable.
1227 void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1228 const CXXRecordDecl *RD);
1230 /// \brief Get the declaration of std::terminate for the platform.
1231 llvm::Constant *getTerminateFn();
1233 llvm::SanitizerStatReport &getSanStats();
1236 createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1238 /// Get target specific null pointer.
1239 /// \param T is the LLVM type of the null pointer.
1240 /// \param QT is the clang QualType of the null pointer.
1241 llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1244 llvm::Constant *GetOrCreateLLVMFunction(
1245 StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1246 bool DontDefer = false, bool IsThunk = false,
1247 llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1248 ForDefinition_t IsForDefinition = NotForDefinition);
1250 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1251 llvm::PointerType *PTy,
1253 ForDefinition_t IsForDefinition
1254 = NotForDefinition);
1256 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1258 /// Set function attributes for a function declaration.
1259 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1260 bool IsIncompleteFunction, bool IsThunk,
1261 ForDefinition_t IsForDefinition);
1263 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1265 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1266 void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1267 void EmitAliasDefinition(GlobalDecl GD);
1268 void emitIFuncDefinition(GlobalDecl GD);
1269 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1270 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1272 // C++ related functions.
1274 void EmitDeclContext(const DeclContext *DC);
1275 void EmitLinkageSpec(const LinkageSpecDecl *D);
1277 /// \brief Emit the function that initializes C++ thread_local variables.
1278 void EmitCXXThreadLocalInitFunc();
1280 /// Emit the function that initializes C++ globals.
1281 void EmitCXXGlobalInitFunc();
1283 /// Emit the function that destroys C++ globals.
1284 void EmitCXXGlobalDtorFunc();
1286 /// Emit the function that initializes the specified global (if PerformInit is
1287 /// true) and registers its destructor.
1288 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1289 llvm::GlobalVariable *Addr,
1292 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1293 llvm::Function *InitFunc, InitSegAttr *ISA);
1295 // FIXME: Hardcoding priority here is gross.
1296 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1297 llvm::Constant *AssociatedData = nullptr);
1298 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1300 /// EmitCtorList - Generates a global array of functions and priorities using
1301 /// the given list and name. This array will have appending linkage and is
1302 /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1303 void EmitCtorList(CtorList &Fns, const char *GlobalName);
1305 /// Emit any needed decls for which code generation was deferred.
1306 void EmitDeferred();
1308 /// Try to emit external vtables as available_externally if they have emitted
1309 /// all inlined virtual functions. It runs after EmitDeferred() and therefore
1310 /// is not allowed to create new references to things that need to be emitted
1312 void EmitVTablesOpportunistically();
1314 /// Call replaceAllUsesWith on all pairs in Replacements.
1315 void applyReplacements();
1317 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1318 void applyGlobalValReplacements();
1320 void checkAliases();
1322 /// Emit any vtables which we deferred and still have a use for.
1323 void EmitDeferredVTables();
1325 /// Emit a dummy function that reference a CoreFoundation symbol when
1326 /// @available is used on Darwin.
1327 void emitAtAvailableLinkGuard();
1329 /// Emit the llvm.used and llvm.compiler.used metadata.
1330 void emitLLVMUsed();
1332 /// \brief Emit the link options introduced by imported modules.
1333 void EmitModuleLinkOptions();
1335 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1336 /// linkage specifications, giving them the "expected" name where possible.
1337 void EmitStaticExternCAliases();
1339 void EmitDeclMetadata();
1341 /// \brief Emit the Clang version as llvm.ident metadata.
1342 void EmitVersionIdentMetadata();
1344 /// Emits target specific Metadata for global declarations.
1345 void EmitTargetMetadata();
1347 /// Emits OpenCL specific Metadata e.g. OpenCL version.
1348 void EmitOpenCLMetadata();
1350 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1351 /// .gcda files in a way that persists in .bc files.
1352 void EmitCoverageFile();
1354 /// Emits the initializer for a uuidof string.
1355 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1357 /// Determine whether the definition must be emitted; if this returns \c
1358 /// false, the definition can be emitted lazily if it's used.
1359 bool MustBeEmitted(const ValueDecl *D);
1361 /// Determine whether the definition can be emitted eagerly, or should be
1362 /// delayed until the end of the translation unit. This is relevant for
1363 /// definitions whose linkage can change, e.g. implicit function instantions
1364 /// which may later be explicitly instantiated.
1365 bool MayBeEmittedEagerly(const ValueDecl *D);
1367 /// Check whether we can use a "simpler", more core exceptions personality
1369 void SimplifyPersonality();
1371 /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1372 /// Constructs an AttrList for a function with the given properties.
1373 void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1374 bool AttrOnCallSite,
1375 llvm::AttrBuilder &FuncAttrs);
1378 } // end namespace CodeGen
1379 } // end namespace clang
1381 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H