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/GlobalDecl.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/SanitizerBlacklist.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ValueHandle.h"
46 class IndexedInstrProfReader;
50 class TargetCodeGenInfo;
56 class ObjCImplementationDecl;
57 class ObjCCategoryImplDecl;
58 class ObjCProtocolDecl;
72 class HeaderSearchOptions;
73 class PreprocessorOptions;
74 class DiagnosticsEngine;
76 class CXXDestructorDecl;
78 class CoverageSourceInfo;
83 class CodeGenFunction;
88 class CGOpenCLRuntime;
89 class CGOpenMPRuntime;
91 class BlockFieldFlags;
92 class FunctionArgList;
93 class CoverageMappingModuleGen;
95 struct OrderGlobalInits {
96 unsigned int priority;
97 unsigned int lex_order;
98 OrderGlobalInits(unsigned int p, unsigned int l)
99 : priority(p), lex_order(l) {}
101 bool operator==(const OrderGlobalInits &RHS) const {
102 return priority == RHS.priority && lex_order == RHS.lex_order;
105 bool operator<(const OrderGlobalInits &RHS) const {
106 return std::tie(priority, lex_order) <
107 std::tie(RHS.priority, RHS.lex_order);
111 struct ObjCEntrypoints {
112 ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
114 /// void objc_autoreleasePoolPop(void*);
115 llvm::Constant *objc_autoreleasePoolPop;
117 /// void *objc_autoreleasePoolPush(void);
118 llvm::Constant *objc_autoreleasePoolPush;
120 /// id objc_autorelease(id);
121 llvm::Constant *objc_autorelease;
123 /// id objc_autoreleaseReturnValue(id);
124 llvm::Constant *objc_autoreleaseReturnValue;
126 /// void objc_copyWeak(id *dest, id *src);
127 llvm::Constant *objc_copyWeak;
129 /// void objc_destroyWeak(id*);
130 llvm::Constant *objc_destroyWeak;
132 /// id objc_initWeak(id*, id);
133 llvm::Constant *objc_initWeak;
135 /// id objc_loadWeak(id*);
136 llvm::Constant *objc_loadWeak;
138 /// id objc_loadWeakRetained(id*);
139 llvm::Constant *objc_loadWeakRetained;
141 /// void objc_moveWeak(id *dest, id *src);
142 llvm::Constant *objc_moveWeak;
144 /// id objc_retain(id);
145 llvm::Constant *objc_retain;
147 /// id objc_retainAutorelease(id);
148 llvm::Constant *objc_retainAutorelease;
150 /// id objc_retainAutoreleaseReturnValue(id);
151 llvm::Constant *objc_retainAutoreleaseReturnValue;
153 /// id objc_retainAutoreleasedReturnValue(id);
154 llvm::Constant *objc_retainAutoreleasedReturnValue;
156 /// id objc_retainBlock(id);
157 llvm::Constant *objc_retainBlock;
159 /// void objc_release(id);
160 llvm::Constant *objc_release;
162 /// id objc_storeStrong(id*, id);
163 llvm::Constant *objc_storeStrong;
165 /// id objc_storeWeak(id*, id);
166 llvm::Constant *objc_storeWeak;
168 /// A void(void) inline asm to use to mark that the return value of
169 /// a call will be immediately retain.
170 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
172 /// void clang.arc.use(...);
173 llvm::Constant *clang_arc_use;
176 /// This class records statistics on instrumentation based profiling.
177 class InstrProfStats {
178 uint32_t VisitedInMainFile;
179 uint32_t MissingInMainFile;
186 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
188 /// Record that we've visited a function and whether or not that function was
189 /// in the main source file.
190 void addVisited(bool MainFile) {
195 /// Record that a function we've visited has no profile data.
196 void addMissing(bool MainFile) {
201 /// Record that a function we've visited has mismatched profile data.
202 void addMismatched(bool MainFile) { ++Mismatched; }
203 /// Whether or not the stats we've gathered indicate any potential problems.
204 bool hasDiagnostics() { return Missing || Mismatched; }
205 /// Report potential problems we've found to \c Diags.
206 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
209 /// A pair of helper functions for a __block variable.
210 class BlockByrefHelpers : public llvm::FoldingSetNode {
211 // MSVC requires this type to be complete in order to process this
214 llvm::Constant *CopyHelper;
215 llvm::Constant *DisposeHelper;
217 /// The alignment of the field. This is important because
218 /// different offsets to the field within the byref struct need to
219 /// have different helper functions.
222 BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
223 BlockByrefHelpers(const BlockByrefHelpers &) = default;
224 virtual ~BlockByrefHelpers();
226 void Profile(llvm::FoldingSetNodeID &id) const {
227 id.AddInteger(Alignment.getQuantity());
230 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
232 virtual bool needsCopy() const { return true; }
233 virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
235 virtual bool needsDispose() const { return true; }
236 virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
239 /// This class organizes the cross-function state that is used while generating
241 class CodeGenModule : public CodeGenTypeCache {
242 CodeGenModule(const CodeGenModule &) = delete;
243 void operator=(const CodeGenModule &) = delete;
247 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
248 Structor(int Priority, llvm::Constant *Initializer,
249 llvm::Constant *AssociatedData)
250 : Priority(Priority), Initializer(Initializer),
251 AssociatedData(AssociatedData) {}
253 llvm::Constant *Initializer;
254 llvm::Constant *AssociatedData;
257 typedef std::vector<Structor> CtorList;
261 const LangOptions &LangOpts;
262 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
263 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
264 const CodeGenOptions &CodeGenOpts;
265 llvm::Module &TheModule;
266 DiagnosticsEngine &Diags;
267 const TargetInfo &Target;
268 std::unique_ptr<CGCXXABI> ABI;
269 llvm::LLVMContext &VMContext;
273 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
275 // This should not be moved earlier, since its initialization depends on some
276 // of the previous reference members being already initialized and also checks
277 // if TheTargetCodeGenInfo is NULL
280 /// Holds information about C++ vtables.
281 CodeGenVTables VTables;
283 CGObjCRuntime* ObjCRuntime;
284 CGOpenCLRuntime* OpenCLRuntime;
285 CGOpenMPRuntime* OpenMPRuntime;
286 CGCUDARuntime* CUDARuntime;
287 CGDebugInfo* DebugInfo;
288 ObjCEntrypoints *ObjCData;
289 llvm::MDNode *NoObjCARCExceptionsMetadata;
290 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
291 InstrProfStats PGOStats;
293 // A set of references that have only been seen via a weakref so far. This is
294 // used to remove the weak of the reference if we ever see a direct reference
296 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
298 /// This contains all the decls which have definitions but/ which are deferred
299 /// for emission and therefore should only be output if they are actually
300 /// used. If a decl is in this, then it is known to have not been referenced
302 std::map<StringRef, GlobalDecl> DeferredDecls;
304 /// This is a list of deferred decls which we have seen that *are* actually
305 /// referenced. These get code generated when the module is done.
306 struct DeferredGlobal {
307 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
308 llvm::TrackingVH<llvm::GlobalValue> GV;
311 std::vector<DeferredGlobal> DeferredDeclsToEmit;
312 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
313 DeferredDeclsToEmit.emplace_back(GV, GD);
316 /// List of alias we have emitted. Used to make sure that what they point to
317 /// is defined once we get to the end of the of the translation unit.
318 std::vector<GlobalDecl> Aliases;
320 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
321 ReplacementsTy Replacements;
323 /// List of global values to be replaced with something else. Used when we
324 /// want to replace a GlobalValue but can't identify it by its mangled name
325 /// anymore (because the name is already taken).
326 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
327 GlobalValReplacements;
329 /// Set of global decls for which we already diagnosed mangled name conflict.
330 /// Required to not issue a warning (on a mangling conflict) multiple times
331 /// for the same decl.
332 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
334 /// A queue of (optional) vtables to consider emitting.
335 std::vector<const CXXRecordDecl*> DeferredVTables;
337 /// List of global values which are required to be present in the object file;
338 /// bitcast to i8*. This is used for forcing visibility of symbols which may
339 /// otherwise be optimized out.
340 std::vector<llvm::WeakVH> LLVMUsed;
341 std::vector<llvm::WeakVH> LLVMCompilerUsed;
343 /// Store the list of global constructors and their respective priorities to
344 /// be emitted when the translation unit is complete.
345 CtorList GlobalCtors;
347 /// Store the list of global destructors and their respective priorities to be
348 /// emitted when the translation unit is complete.
349 CtorList GlobalDtors;
351 /// An ordered map of canonical GlobalDecls to their mangled names.
352 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
353 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
355 /// Global annotations.
356 std::vector<llvm::Constant*> Annotations;
358 /// Map used to get unique annotation strings.
359 llvm::StringMap<llvm::Constant*> AnnotationStrings;
361 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
363 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
364 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
365 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
366 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
368 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
369 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
371 /// Map used to get unique type descriptor constants for sanitizers.
372 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
374 /// Map used to track internal linkage functions declared within
375 /// extern "C" regions.
376 typedef llvm::MapVector<IdentifierInfo *,
377 llvm::GlobalValue *> StaticExternCMap;
378 StaticExternCMap StaticExternCValues;
380 /// \brief thread_local variables defined or used in this TU.
381 std::vector<const VarDecl *> CXXThreadLocals;
383 /// \brief thread_local variables with initializers that need to run
384 /// before any thread_local variable in this TU is odr-used.
385 std::vector<llvm::Function *> CXXThreadLocalInits;
386 std::vector<const VarDecl *> CXXThreadLocalInitVars;
388 /// Global variables with initializers that need to run before main.
389 std::vector<llvm::Function *> CXXGlobalInits;
391 /// When a C++ decl with an initializer is deferred, null is
392 /// appended to CXXGlobalInits, and the index of that null is placed
393 /// here so that the initializer will be performed in the correct
394 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
395 /// that we don't re-emit the initializer.
396 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
398 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
400 struct GlobalInitPriorityCmp {
401 bool operator()(const GlobalInitData &LHS,
402 const GlobalInitData &RHS) const {
403 return LHS.first.priority < RHS.first.priority;
407 /// Global variables with initializers whose order of initialization is set by
408 /// init_priority attribute.
409 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
411 /// Global destructor functions and arguments that need to run on termination.
412 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
414 /// \brief The complete set of modules that has been imported.
415 llvm::SetVector<clang::Module *> ImportedModules;
417 /// \brief A vector of metadata strings.
418 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
420 /// @name Cache for Objective-C runtime types
423 /// Cached reference to the class for constant strings. This value has type
424 /// int * but is actually an Obj-C class pointer.
425 llvm::WeakVH CFConstantStringClassRef;
427 /// Cached reference to the class for constant strings. This value has type
428 /// int * but is actually an Obj-C class pointer.
429 llvm::WeakVH ConstantStringClassRef;
431 /// \brief The LLVM type corresponding to NSConstantString.
432 llvm::StructType *NSConstantStringType;
434 /// \brief The type used to describe the state of a fast enumeration in
435 /// Objective-C's for..in loop.
436 QualType ObjCFastEnumerationStateType;
440 /// Lazily create the Objective-C runtime
441 void createObjCRuntime();
443 void createOpenCLRuntime();
444 void createOpenMPRuntime();
445 void createCUDARuntime();
447 bool isTriviallyRecursive(const FunctionDecl *F);
448 bool shouldEmitFunction(GlobalDecl GD);
450 /// @name Cache for Blocks Runtime Globals
453 llvm::Constant *NSConcreteGlobalBlock;
454 llvm::Constant *NSConcreteStackBlock;
456 llvm::Constant *BlockObjectAssign;
457 llvm::Constant *BlockObjectDispose;
459 llvm::Type *BlockDescriptorType;
460 llvm::Type *GenericBlockLiteralType;
463 int GlobalUniqueCount;
466 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
467 llvm::Constant *LifetimeStartFn;
469 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
470 llvm::Constant *LifetimeEndFn;
472 GlobalDecl initializedGlobalDecl;
474 std::unique_ptr<SanitizerMetadata> SanitizerMD;
478 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
480 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
482 /// Mapping from canonical types to their metadata identifiers. We need to
483 /// maintain this mapping because identifiers may be formed from distinct
485 llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
488 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
489 const PreprocessorOptions &ppopts,
490 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
491 DiagnosticsEngine &Diags,
492 CoverageSourceInfo *CoverageInfo = nullptr);
498 /// Finalize LLVM code generation.
501 /// Return a reference to the configured Objective-C runtime.
502 CGObjCRuntime &getObjCRuntime() {
503 if (!ObjCRuntime) createObjCRuntime();
507 /// Return true iff an Objective-C runtime has been configured.
508 bool hasObjCRuntime() { return !!ObjCRuntime; }
510 /// Return a reference to the configured OpenCL runtime.
511 CGOpenCLRuntime &getOpenCLRuntime() {
512 assert(OpenCLRuntime != nullptr);
513 return *OpenCLRuntime;
516 /// Return a reference to the configured OpenMP runtime.
517 CGOpenMPRuntime &getOpenMPRuntime() {
518 assert(OpenMPRuntime != nullptr);
519 return *OpenMPRuntime;
522 /// Return a reference to the configured CUDA runtime.
523 CGCUDARuntime &getCUDARuntime() {
524 assert(CUDARuntime != nullptr);
528 ObjCEntrypoints &getObjCEntrypoints() const {
529 assert(ObjCData != nullptr);
533 InstrProfStats &getPGOStats() { return PGOStats; }
534 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
536 CoverageMappingModuleGen *getCoverageMapping() const {
537 return CoverageMapping.get();
540 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
541 return StaticLocalDeclMap[D];
543 void setStaticLocalDeclAddress(const VarDecl *D,
545 StaticLocalDeclMap[D] = C;
549 getOrCreateStaticVarDecl(const VarDecl &D,
550 llvm::GlobalValue::LinkageTypes Linkage);
552 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
553 return StaticLocalDeclGuardMap[D];
555 void setStaticLocalDeclGuardAddress(const VarDecl *D,
556 llvm::GlobalVariable *C) {
557 StaticLocalDeclGuardMap[D] = C;
560 bool lookupRepresentativeDecl(StringRef MangledName,
561 GlobalDecl &Result) const;
563 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
564 return AtomicSetterHelperFnMap[Ty];
566 void setAtomicSetterHelperFnMap(QualType Ty,
567 llvm::Constant *Fn) {
568 AtomicSetterHelperFnMap[Ty] = Fn;
571 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
572 return AtomicGetterHelperFnMap[Ty];
574 void setAtomicGetterHelperFnMap(QualType Ty,
575 llvm::Constant *Fn) {
576 AtomicGetterHelperFnMap[Ty] = Fn;
579 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
580 return TypeDescriptorMap[Ty];
582 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
583 TypeDescriptorMap[Ty] = C;
586 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
588 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
589 if (!NoObjCARCExceptionsMetadata)
590 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
591 return NoObjCARCExceptionsMetadata;
594 ASTContext &getContext() const { return Context; }
595 const LangOptions &getLangOpts() const { return LangOpts; }
596 const HeaderSearchOptions &getHeaderSearchOpts()
597 const { return HeaderSearchOpts; }
598 const PreprocessorOptions &getPreprocessorOpts()
599 const { return PreprocessorOpts; }
600 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
601 llvm::Module &getModule() const { return TheModule; }
602 DiagnosticsEngine &getDiags() const { return Diags; }
603 const llvm::DataLayout &getDataLayout() const {
604 return TheModule.getDataLayout();
606 const TargetInfo &getTarget() const { return Target; }
607 const llvm::Triple &getTriple() const;
608 bool supportsCOMDAT() const;
609 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
611 CGCXXABI &getCXXABI() const { return *ABI; }
612 llvm::LLVMContext &getLLVMContext() { return VMContext; }
614 bool shouldUseTBAA() const { return TBAA != nullptr; }
616 const TargetCodeGenInfo &getTargetCodeGenInfo();
618 CodeGenTypes &getTypes() { return Types; }
620 CodeGenVTables &getVTables() { return VTables; }
622 ItaniumVTableContext &getItaniumVTableContext() {
623 return VTables.getItaniumVTableContext();
626 MicrosoftVTableContext &getMicrosoftVTableContext() {
627 return VTables.getMicrosoftVTableContext();
630 CtorList &getGlobalCtors() { return GlobalCtors; }
631 CtorList &getGlobalDtors() { return GlobalDtors; }
633 llvm::MDNode *getTBAAInfo(QualType QTy);
634 llvm::MDNode *getTBAAInfoForVTablePtr();
635 llvm::MDNode *getTBAAStructInfo(QualType QTy);
636 /// Return the path-aware tag for given base type, access node and offset.
637 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
640 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
642 bool isPaddedAtomicType(QualType type);
643 bool isPaddedAtomicType(const AtomicType *type);
645 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
646 /// is the same as the type. For struct-path aware TBAA, the tag
647 /// is different from the type: base type, access type and offset.
648 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
649 void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
650 llvm::MDNode *TBAAInfo,
651 bool ConvertTypeToTag = true);
653 /// Adds !invariant.barrier !tag to instruction
654 void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
655 const CXXRecordDecl *RD);
657 /// Emit the given number of characters as a value of type size_t.
658 llvm::ConstantInt *getSize(CharUnits numChars);
660 /// Set the visibility for the given LLVM GlobalValue.
661 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
663 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
664 /// variable declaration D.
665 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
667 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
669 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
670 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
671 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
673 llvm_unreachable("unknown visibility!");
676 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
678 /// Will return a global variable of the given type. If a variable with a
679 /// different type already exists then a new variable with the right type
680 /// will be created and all uses of the old variable will be replaced with a
681 /// bitcast to the new variable.
682 llvm::GlobalVariable *
683 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
684 llvm::GlobalValue::LinkageTypes Linkage);
687 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
688 const CGFunctionInfo &FI,
689 SourceLocation Loc = SourceLocation(),
692 /// Return the address space of the underlying global variable for D, as
693 /// determined by its declaration. Normally this is the same as the address
694 /// space of D's type, but in CUDA, address spaces are associated with
695 /// declarations, not types.
696 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
698 /// Return the llvm::Constant for the address of the given global variable.
699 /// If Ty is non-null and if the global doesn't exist, then it will be greated
700 /// with the specified type instead of whatever the normal requested type
702 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
703 llvm::Type *Ty = nullptr);
705 /// Return the address of the given function. If Ty is non-null, then this
706 /// function will use the specified type if it has to create it.
707 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
708 bool ForVTable = false,
709 bool DontDefer = false,
710 bool IsForDefinition = false);
712 /// Get the address of the RTTI descriptor for the given type.
713 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
715 /// Get the address of a uuid descriptor .
716 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
718 /// Get the address of the thunk for the given global decl.
719 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
721 /// Get a reference to the target of VD.
722 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
724 /// Returns the assumed alignment of an opaque pointer to the given class.
725 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
727 /// Returns the assumed alignment of a virtual base of a class.
728 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
729 const CXXRecordDecl *Derived,
730 const CXXRecordDecl *VBase);
732 /// Given a class pointer with an actual known alignment, and the
733 /// expected alignment of an object at a dynamic offset w.r.t that
734 /// pointer, return the alignment to assume at the offset.
735 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
736 const CXXRecordDecl *Class,
737 CharUnits ExpectedTargetAlign);
740 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
741 CastExpr::path_const_iterator Start,
742 CastExpr::path_const_iterator End);
744 /// Returns the offset from a derived class to a class. Returns null if the
747 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
748 CastExpr::path_const_iterator PathBegin,
749 CastExpr::path_const_iterator PathEnd);
751 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
753 /// Fetches the global unique block count.
754 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
756 /// Fetches the type of a generic block descriptor.
757 llvm::Type *getBlockDescriptorType();
759 /// The type of a generic block literal.
760 llvm::Type *getGenericBlockLiteralType();
762 /// Gets the address of a block which requires no captures.
763 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
765 /// Return a pointer to a constant CFString object for the given string.
766 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
768 /// Return a pointer to a constant NSString object for the given string. Or a
769 /// user defined String object as defined via
770 /// -fconstant-string-class=class_name option.
771 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
773 /// Return a constant array for the given string.
774 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
776 /// Return a pointer to a constant array for the given string literal.
778 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
779 StringRef Name = ".str");
781 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
783 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
785 /// Returns a pointer to a character array containing the literal and a
786 /// terminating '\0' character. The result has pointer to array type.
788 /// \param GlobalName If provided, the name to use for the global (if one is
791 GetAddrOfConstantCString(const std::string &Str,
792 const char *GlobalName = nullptr);
794 /// Returns a pointer to a constant global variable for the given file-scope
795 /// compound literal expression.
796 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
798 /// \brief Returns a pointer to a global variable representing a temporary
799 /// with static or thread storage duration.
800 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
803 /// \brief Retrieve the record type that describes the state of an
804 /// Objective-C fast enumeration loop (for..in).
805 QualType getObjCFastEnumerationStateType();
807 // Produce code for this constructor/destructor. This method doesn't try
808 // to apply any ABI rules about which other constructors/destructors
809 // are needed or if they are alias to each other.
810 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
813 /// Return the address of the constructor/destructor of the given type.
815 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
816 const CGFunctionInfo *FnInfo = nullptr,
817 llvm::FunctionType *FnType = nullptr,
818 bool DontDefer = false, bool IsForDefinition = false);
820 /// Given a builtin id for a function like "__builtin_fabsf", return a
821 /// Function* for "fabsf".
822 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
825 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
827 /// Emit code for a single top level declaration.
828 void EmitTopLevelDecl(Decl *D);
830 /// \brief Stored a deferred empty coverage mapping for an unused
831 /// and thus uninstrumented top level declaration.
832 void AddDeferredUnusedCoverageMapping(Decl *D);
834 /// \brief Remove the deferred empty coverage mapping as this
835 /// declaration is actually instrumented.
836 void ClearUnusedCoverageMapping(const Decl *D);
838 /// \brief Emit all the deferred coverage mappings
839 /// for the uninstrumented functions.
840 void EmitDeferredUnusedCoverageMappings();
842 /// Tell the consumer that this variable has been instantiated.
843 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
845 /// \brief If the declaration has internal linkage but is inside an
846 /// extern "C" linkage specification, prepare to emit an alias for it
847 /// to the expected name.
848 template<typename SomeDecl>
849 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
851 /// Add a global to a list to be added to the llvm.used metadata.
852 void addUsedGlobal(llvm::GlobalValue *GV);
854 /// Add a global to a list to be added to the llvm.compiler.used metadata.
855 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
857 /// Add a destructor and object to add to the C++ global destructor function.
858 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
859 CXXGlobalDtors.emplace_back(DtorFn, Object);
862 /// Create a new runtime function with the specified type and name.
863 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
865 llvm::AttributeSet ExtraAttrs =
866 llvm::AttributeSet());
867 /// Create a new compiler builtin function with the specified type and name.
868 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
870 llvm::AttributeSet ExtraAttrs =
871 llvm::AttributeSet());
872 /// Create a new runtime global variable with the specified type and name.
873 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
876 ///@name Custom Blocks Runtime Interfaces
879 llvm::Constant *getNSConcreteGlobalBlock();
880 llvm::Constant *getNSConcreteStackBlock();
881 llvm::Constant *getBlockObjectAssign();
882 llvm::Constant *getBlockObjectDispose();
886 llvm::Constant *getLLVMLifetimeStartFn();
887 llvm::Constant *getLLVMLifetimeEndFn();
889 // Make sure that this type is translated.
890 void UpdateCompletedType(const TagDecl *TD);
892 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
894 /// Try to emit the initializer for the given declaration as a constant;
895 /// returns 0 if the expression cannot be emitted as a constant.
896 llvm::Constant *EmitConstantInit(const VarDecl &D,
897 CodeGenFunction *CGF = nullptr);
899 /// Try to emit the given expression as a constant; returns 0 if the
900 /// expression cannot be emitted as a constant.
901 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
902 CodeGenFunction *CGF = nullptr);
904 /// Emit the given constant value as a constant, in the type's scalar
906 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
907 CodeGenFunction *CGF = nullptr);
909 /// Emit the given constant value as a constant, in the type's memory
911 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
913 CodeGenFunction *CGF = nullptr);
915 /// \brief Emit type info if type of an expression is a variably modified
916 /// type. Also emit proper debug info for cast types.
917 void EmitExplicitCastExprType(const ExplicitCastExpr *E,
918 CodeGenFunction *CGF = nullptr);
920 /// Return the result of value-initializing the given type, i.e. a null
921 /// expression of the given type. This is usually, but not always, an LLVM
923 llvm::Constant *EmitNullConstant(QualType T);
925 /// Return a null constant appropriate for zero-initializing a base class with
926 /// the given type. This is usually, but not always, an LLVM null constant.
927 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
929 /// Emit a general error that something can't be done.
930 void Error(SourceLocation loc, StringRef error);
932 /// Print out an error that codegen doesn't support the specified stmt yet.
933 void ErrorUnsupported(const Stmt *S, const char *Type);
935 /// Print out an error that codegen doesn't support the specified decl yet.
936 void ErrorUnsupported(const Decl *D, const char *Type);
938 /// Set the attributes on the LLVM function for the given decl and function
939 /// info. This applies attributes necessary for handling the ABI as well as
940 /// user specified attributes like section.
941 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
942 const CGFunctionInfo &FI);
944 /// Set the LLVM function attributes (sext, zext, etc).
945 void SetLLVMFunctionAttributes(const Decl *D,
946 const CGFunctionInfo &Info,
949 /// Set the LLVM function attributes which only apply to a function
951 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
953 /// Return true iff the given type uses 'sret' when used as a return type.
954 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
956 /// Return true iff the given type uses an argument slot when 'sret' is used
957 /// as a return type.
958 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
960 /// Return true iff the given type uses 'fpret' when used as a return type.
961 bool ReturnTypeUsesFPRet(QualType ResultType);
963 /// Return true iff the given type uses 'fp2ret' when used as a return type.
964 bool ReturnTypeUsesFP2Ret(QualType ResultType);
966 /// Get the LLVM attributes and calling convention to use for a particular
969 /// \param Info - The function type information.
970 /// \param CalleeInfo - The callee information these attributes are being
971 /// constructed for. If valid, the attributes applied to this decl may
972 /// contribute to the function attributes and calling convention.
973 /// \param PAL [out] - On return, the attribute list to use.
974 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
975 void ConstructAttributeList(const CGFunctionInfo &Info,
976 CGCalleeInfo CalleeInfo, AttributeListType &PAL,
977 unsigned &CallingConv, bool AttrOnCallSite);
979 // Fills in the supplied string map with the set of target features for the
980 // passed in function.
981 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
982 const FunctionDecl *FD);
984 StringRef getMangledName(GlobalDecl GD);
985 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
987 void EmitTentativeDefinition(const VarDecl *D);
989 void EmitVTable(CXXRecordDecl *Class);
991 /// \brief Appends Opts to the "Linker Options" metadata value.
992 void AppendLinkerOptions(StringRef Opts);
994 /// \brief Appends a detect mismatch command to the linker options.
995 void AddDetectMismatch(StringRef Name, StringRef Value);
997 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
998 void AddDependentLib(StringRef Lib);
1000 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1002 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1003 F->setLinkage(getFunctionLinkage(GD));
1006 /// Set the DLL storage class on F.
1007 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1009 /// Return the appropriate linkage for the vtable, VTT, and type information
1010 /// of the given class.
1011 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1013 /// Return the store size, in character units, of the given LLVM type.
1014 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1016 /// Returns LLVM linkage for a declarator.
1017 llvm::GlobalValue::LinkageTypes
1018 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1019 bool IsConstantVariable);
1021 /// Returns LLVM linkage for a declarator.
1022 llvm::GlobalValue::LinkageTypes
1023 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1025 /// Emit all the global annotations.
1026 void EmitGlobalAnnotations();
1028 /// Emit an annotation string.
1029 llvm::Constant *EmitAnnotationString(StringRef Str);
1031 /// Emit the annotation's translation unit.
1032 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1034 /// Emit the annotation line number.
1035 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1037 /// Generate the llvm::ConstantStruct which contains the annotation
1038 /// information for a given GlobalValue. The annotation struct is
1039 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1040 /// GlobalValue being annotated. The second field is the constant string
1041 /// created from the AnnotateAttr's annotation. The third field is a constant
1042 /// string containing the name of the translation unit. The fourth field is
1043 /// the line number in the file of the annotated value declaration.
1044 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1045 const AnnotateAttr *AA,
1048 /// Add global annotations that are set on D, for the global GV. Those
1049 /// annotations are emitted during finalization of the LLVM code.
1050 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1052 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1054 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1056 StringRef Category = StringRef()) const;
1058 SanitizerMetadata *getSanitizerMetadata() {
1059 return SanitizerMD.get();
1062 void addDeferredVTable(const CXXRecordDecl *RD) {
1063 DeferredVTables.push_back(RD);
1066 /// Emit code for a singal global function or var decl. Forward declarations
1067 /// are emitted lazily.
1068 void EmitGlobal(GlobalDecl D);
1070 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1072 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1074 /// Set attributes for a global definition.
1075 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1078 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1080 /// Set attributes which are common to any form of a global definition (alias,
1081 /// Objective-C method, function, global variable).
1083 /// NOTE: This should only be called for definitions.
1084 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1086 /// Set attributes which must be preserved by an alias. This includes common
1087 /// attributes (i.e. it includes a call to SetCommonAttributes).
1089 /// NOTE: This should only be called for definitions.
1090 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1092 void addReplacement(StringRef Name, llvm::Constant *C);
1094 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1096 /// \brief Emit a code for threadprivate directive.
1097 /// \param D Threadprivate declaration.
1098 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1100 /// Returns whether the given record is blacklisted from control flow
1101 /// integrity checks.
1102 bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
1104 /// Emit bit set entries for the given vtable using the given layout if
1105 /// vptr CFI is enabled.
1106 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1107 const VTableLayout &VTLayout);
1109 /// Generate a cross-DSO type identifier for type.
1110 llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
1112 /// Create a metadata identifier for the given type. This may either be an
1113 /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1114 /// internal identifiers).
1115 llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1117 /// Create a bitset entry for the given function and add it to BitsetsMD.
1118 void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
1120 /// Create a bitset entry for the given vtable and add it to BitsetsMD.
1121 void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
1122 llvm::GlobalVariable *VTable, CharUnits Offset,
1123 const CXXRecordDecl *RD);
1125 /// \breif Get the declaration of std::terminate for the platform.
1126 llvm::Constant *getTerminateFn();
1130 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1131 bool ForVTable, bool DontDefer = false,
1132 bool IsThunk = false,
1133 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
1134 bool IsForDefinition = false);
1136 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1137 llvm::PointerType *PTy,
1140 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1142 /// Set function attributes for a function declaration.
1143 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1144 bool IsIncompleteFunction, bool IsThunk);
1146 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1148 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1149 void EmitGlobalVarDefinition(const VarDecl *D);
1150 void EmitAliasDefinition(GlobalDecl GD);
1151 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1152 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1154 // C++ related functions.
1156 void EmitNamespace(const NamespaceDecl *D);
1157 void EmitLinkageSpec(const LinkageSpecDecl *D);
1158 void CompleteDIClassType(const CXXMethodDecl* D);
1160 /// \brief Emit the function that initializes C++ thread_local variables.
1161 void EmitCXXThreadLocalInitFunc();
1163 /// Emit the function that initializes C++ globals.
1164 void EmitCXXGlobalInitFunc();
1166 /// Emit the function that destroys C++ globals.
1167 void EmitCXXGlobalDtorFunc();
1169 /// Emit the function that initializes the specified global (if PerformInit is
1170 /// true) and registers its destructor.
1171 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1172 llvm::GlobalVariable *Addr,
1175 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1176 llvm::Function *InitFunc, InitSegAttr *ISA);
1178 // FIXME: Hardcoding priority here is gross.
1179 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1180 llvm::Constant *AssociatedData = nullptr);
1181 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1183 /// Generates a global array of functions and priorities using the given list
1184 /// and name. This array will have appending linkage and is suitable for use
1185 /// as a LLVM constructor or destructor array.
1186 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1188 /// Emit any needed decls for which code generation was deferred.
1189 void EmitDeferred();
1191 /// Call replaceAllUsesWith on all pairs in Replacements.
1192 void applyReplacements();
1194 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1195 void applyGlobalValReplacements();
1197 void checkAliases();
1199 /// Emit any vtables which we deferred and still have a use for.
1200 void EmitDeferredVTables();
1202 /// Emit the llvm.used and llvm.compiler.used metadata.
1203 void emitLLVMUsed();
1205 /// \brief Emit the link options introduced by imported modules.
1206 void EmitModuleLinkOptions();
1208 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1209 /// linkage specifications, giving them the "expected" name where possible.
1210 void EmitStaticExternCAliases();
1212 void EmitDeclMetadata();
1214 /// \brief Emit the Clang version as llvm.ident metadata.
1215 void EmitVersionIdentMetadata();
1217 /// Emits target specific Metadata for global declarations.
1218 void EmitTargetMetadata();
1220 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1221 /// .gcda files in a way that persists in .bc files.
1222 void EmitCoverageFile();
1224 /// Emits the initializer for a uuidof string.
1225 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1227 /// Determine whether the definition must be emitted; if this returns \c
1228 /// false, the definition can be emitted lazily if it's used.
1229 bool MustBeEmitted(const ValueDecl *D);
1231 /// Determine whether the definition can be emitted eagerly, or should be
1232 /// delayed until the end of the translation unit. This is relevant for
1233 /// definitions whose linkage can change, e.g. implicit function instantions
1234 /// which may later be explicitly instantiated.
1235 bool MayBeEmittedEagerly(const ValueDecl *D);
1237 /// Check whether we can use a "simpler", more core exceptions personality
1239 void SimplifyPersonality();
1241 } // end namespace CodeGen
1242 } // end namespace clang
1244 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H