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;
82 class BlockByrefHelpers;
84 class CodeGenFunction;
89 class CGOpenCLRuntime;
90 class CGOpenMPRuntime;
92 class BlockFieldFlags;
93 class FunctionArgList;
94 class CoverageMappingModuleGen;
96 struct OrderGlobalInits {
97 unsigned int priority;
98 unsigned int lex_order;
99 OrderGlobalInits(unsigned int p, unsigned int l)
100 : priority(p), lex_order(l) {}
102 bool operator==(const OrderGlobalInits &RHS) const {
103 return priority == RHS.priority && lex_order == RHS.lex_order;
106 bool operator<(const OrderGlobalInits &RHS) const {
107 return std::tie(priority, lex_order) <
108 std::tie(RHS.priority, RHS.lex_order);
112 struct RREntrypoints {
113 RREntrypoints() { 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;
121 struct ARCEntrypoints {
122 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
124 /// id objc_autorelease(id);
125 llvm::Constant *objc_autorelease;
127 /// id objc_autoreleaseReturnValue(id);
128 llvm::Constant *objc_autoreleaseReturnValue;
130 /// void objc_copyWeak(id *dest, id *src);
131 llvm::Constant *objc_copyWeak;
133 /// void objc_destroyWeak(id*);
134 llvm::Constant *objc_destroyWeak;
136 /// id objc_initWeak(id*, id);
137 llvm::Constant *objc_initWeak;
139 /// id objc_loadWeak(id*);
140 llvm::Constant *objc_loadWeak;
142 /// id objc_loadWeakRetained(id*);
143 llvm::Constant *objc_loadWeakRetained;
145 /// void objc_moveWeak(id *dest, id *src);
146 llvm::Constant *objc_moveWeak;
148 /// id objc_retain(id);
149 llvm::Constant *objc_retain;
151 /// id objc_retainAutorelease(id);
152 llvm::Constant *objc_retainAutorelease;
154 /// id objc_retainAutoreleaseReturnValue(id);
155 llvm::Constant *objc_retainAutoreleaseReturnValue;
157 /// id objc_retainAutoreleasedReturnValue(id);
158 llvm::Constant *objc_retainAutoreleasedReturnValue;
160 /// id objc_retainBlock(id);
161 llvm::Constant *objc_retainBlock;
163 /// void objc_release(id);
164 llvm::Constant *objc_release;
166 /// id objc_storeStrong(id*, id);
167 llvm::Constant *objc_storeStrong;
169 /// id objc_storeWeak(id*, id);
170 llvm::Constant *objc_storeWeak;
172 /// A void(void) inline asm to use to mark that the return value of
173 /// a call will be immediately retain.
174 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
176 /// void clang.arc.use(...);
177 llvm::Constant *clang_arc_use;
180 /// This class records statistics on instrumentation based profiling.
181 class InstrProfStats {
182 uint32_t VisitedInMainFile;
183 uint32_t MissingInMainFile;
190 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
192 /// Record that we've visited a function and whether or not that function was
193 /// in the main source file.
194 void addVisited(bool MainFile) {
199 /// Record that a function we've visited has no profile data.
200 void addMissing(bool MainFile) {
205 /// Record that a function we've visited has mismatched profile data.
206 void addMismatched(bool MainFile) { ++Mismatched; }
207 /// Whether or not the stats we've gathered indicate any potential problems.
208 bool hasDiagnostics() { return Missing || Mismatched; }
209 /// Report potential problems we've found to \c Diags.
210 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
213 /// This class organizes the cross-function state that is used while generating
215 class CodeGenModule : public CodeGenTypeCache {
216 CodeGenModule(const CodeGenModule &) = delete;
217 void operator=(const CodeGenModule &) = delete;
221 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
222 Structor(int Priority, llvm::Constant *Initializer,
223 llvm::Constant *AssociatedData)
224 : Priority(Priority), Initializer(Initializer),
225 AssociatedData(AssociatedData) {}
227 llvm::Constant *Initializer;
228 llvm::Constant *AssociatedData;
231 typedef std::vector<Structor> CtorList;
235 const LangOptions &LangOpts;
236 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
237 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
238 const CodeGenOptions &CodeGenOpts;
239 llvm::Module &TheModule;
240 DiagnosticsEngine &Diags;
241 const TargetInfo &Target;
242 std::unique_ptr<CGCXXABI> ABI;
243 llvm::LLVMContext &VMContext;
247 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
249 // This should not be moved earlier, since its initialization depends on some
250 // of the previous reference members being already initialized and also checks
251 // if TheTargetCodeGenInfo is NULL
254 /// Holds information about C++ vtables.
255 CodeGenVTables VTables;
257 CGObjCRuntime* ObjCRuntime;
258 CGOpenCLRuntime* OpenCLRuntime;
259 CGOpenMPRuntime* OpenMPRuntime;
260 CGCUDARuntime* CUDARuntime;
261 CGDebugInfo* DebugInfo;
262 ARCEntrypoints *ARCData;
263 llvm::MDNode *NoObjCARCExceptionsMetadata;
264 RREntrypoints *RRData;
265 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
266 InstrProfStats PGOStats;
268 // A set of references that have only been seen via a weakref so far. This is
269 // used to remove the weak of the reference if we ever see a direct reference
271 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
273 /// This contains all the decls which have definitions but/ which are deferred
274 /// for emission and therefore should only be output if they are actually
275 /// used. If a decl is in this, then it is known to have not been referenced
277 std::map<StringRef, GlobalDecl> DeferredDecls;
279 /// This is a list of deferred decls which we have seen that *are* actually
280 /// referenced. These get code generated when the module is done.
281 struct DeferredGlobal {
282 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
283 llvm::TrackingVH<llvm::GlobalValue> GV;
286 std::vector<DeferredGlobal> DeferredDeclsToEmit;
287 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
288 DeferredDeclsToEmit.emplace_back(GV, GD);
291 /// List of alias we have emitted. Used to make sure that what they point to
292 /// is defined once we get to the end of the of the translation unit.
293 std::vector<GlobalDecl> Aliases;
295 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
296 ReplacementsTy Replacements;
298 /// List of global values to be replaced with something else. Used when we
299 /// want to replace a GlobalValue but can't identify it by its mangled name
300 /// anymore (because the name is already taken).
301 llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
302 GlobalValReplacements;
304 /// Set of global decls for which we already diagnosed mangled name conflict.
305 /// Required to not issue a warning (on a mangling conflict) multiple times
306 /// for the same decl.
307 llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
309 /// A queue of (optional) vtables to consider emitting.
310 std::vector<const CXXRecordDecl*> DeferredVTables;
312 /// List of global values which are required to be present in the object file;
313 /// bitcast to i8*. This is used for forcing visibility of symbols which may
314 /// otherwise be optimized out.
315 std::vector<llvm::WeakVH> LLVMUsed;
316 std::vector<llvm::WeakVH> LLVMCompilerUsed;
318 /// Store the list of global constructors and their respective priorities to
319 /// be emitted when the translation unit is complete.
320 CtorList GlobalCtors;
322 /// Store the list of global destructors and their respective priorities to be
323 /// emitted when the translation unit is complete.
324 CtorList GlobalDtors;
326 /// An ordered map of canonical GlobalDecls to their mangled names.
327 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
328 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
330 /// Global annotations.
331 std::vector<llvm::Constant*> Annotations;
333 /// Map used to get unique annotation strings.
334 llvm::StringMap<llvm::Constant*> AnnotationStrings;
336 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
338 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
339 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
340 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
341 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
343 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
344 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
346 /// Map used to get unique type descriptor constants for sanitizers.
347 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
349 /// Map used to track internal linkage functions declared within
350 /// extern "C" regions.
351 typedef llvm::MapVector<IdentifierInfo *,
352 llvm::GlobalValue *> StaticExternCMap;
353 StaticExternCMap StaticExternCValues;
355 /// \brief thread_local variables defined or used in this TU.
356 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
359 /// \brief thread_local variables with initializers that need to run
360 /// before any thread_local variable in this TU is odr-used.
361 std::vector<llvm::Function *> CXXThreadLocalInits;
362 std::vector<llvm::GlobalVariable *> CXXThreadLocalInitVars;
364 /// Global variables with initializers that need to run before main.
365 std::vector<llvm::Function *> CXXGlobalInits;
367 /// When a C++ decl with an initializer is deferred, null is
368 /// appended to CXXGlobalInits, and the index of that null is placed
369 /// here so that the initializer will be performed in the correct
370 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
371 /// that we don't re-emit the initializer.
372 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
374 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
376 struct GlobalInitPriorityCmp {
377 bool operator()(const GlobalInitData &LHS,
378 const GlobalInitData &RHS) const {
379 return LHS.first.priority < RHS.first.priority;
383 /// Global variables with initializers whose order of initialization is set by
384 /// init_priority attribute.
385 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
387 /// Global destructor functions and arguments that need to run on termination.
388 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
390 /// \brief The complete set of modules that has been imported.
391 llvm::SetVector<clang::Module *> ImportedModules;
393 /// \brief A vector of metadata strings.
394 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
396 /// @name Cache for Objective-C runtime types
399 /// Cached reference to the class for constant strings. This value has type
400 /// int * but is actually an Obj-C class pointer.
401 llvm::WeakVH CFConstantStringClassRef;
403 /// Cached reference to the class for constant strings. This value has type
404 /// int * but is actually an Obj-C class pointer.
405 llvm::WeakVH ConstantStringClassRef;
407 /// \brief The LLVM type corresponding to NSConstantString.
408 llvm::StructType *NSConstantStringType;
410 /// \brief The type used to describe the state of a fast enumeration in
411 /// Objective-C's for..in loop.
412 QualType ObjCFastEnumerationStateType;
416 /// Lazily create the Objective-C runtime
417 void createObjCRuntime();
419 void createOpenCLRuntime();
420 void createOpenMPRuntime();
421 void createCUDARuntime();
423 bool isTriviallyRecursive(const FunctionDecl *F);
424 bool shouldEmitFunction(GlobalDecl GD);
426 /// @name Cache for Blocks Runtime Globals
429 llvm::Constant *NSConcreteGlobalBlock;
430 llvm::Constant *NSConcreteStackBlock;
432 llvm::Constant *BlockObjectAssign;
433 llvm::Constant *BlockObjectDispose;
435 llvm::Type *BlockDescriptorType;
436 llvm::Type *GenericBlockLiteralType;
439 int GlobalUniqueCount;
442 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
443 llvm::Constant *LifetimeStartFn;
445 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
446 llvm::Constant *LifetimeEndFn;
448 GlobalDecl initializedGlobalDecl;
450 std::unique_ptr<SanitizerMetadata> SanitizerMD;
454 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
456 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
458 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
459 const PreprocessorOptions &ppopts,
460 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
461 DiagnosticsEngine &Diags,
462 CoverageSourceInfo *CoverageInfo = nullptr);
468 /// Finalize LLVM code generation.
471 /// Return a reference to the configured Objective-C runtime.
472 CGObjCRuntime &getObjCRuntime() {
473 if (!ObjCRuntime) createObjCRuntime();
477 /// Return true iff an Objective-C runtime has been configured.
478 bool hasObjCRuntime() { return !!ObjCRuntime; }
480 /// Return a reference to the configured OpenCL runtime.
481 CGOpenCLRuntime &getOpenCLRuntime() {
482 assert(OpenCLRuntime != nullptr);
483 return *OpenCLRuntime;
486 /// Return a reference to the configured OpenMP runtime.
487 CGOpenMPRuntime &getOpenMPRuntime() {
488 assert(OpenMPRuntime != nullptr);
489 return *OpenMPRuntime;
492 /// Return a reference to the configured CUDA runtime.
493 CGCUDARuntime &getCUDARuntime() {
494 assert(CUDARuntime != nullptr);
498 ARCEntrypoints &getARCEntrypoints() const {
499 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
503 RREntrypoints &getRREntrypoints() const {
504 assert(RRData != nullptr);
508 InstrProfStats &getPGOStats() { return PGOStats; }
509 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
511 CoverageMappingModuleGen *getCoverageMapping() const {
512 return CoverageMapping.get();
515 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
516 return StaticLocalDeclMap[D];
518 void setStaticLocalDeclAddress(const VarDecl *D,
520 StaticLocalDeclMap[D] = C;
524 getOrCreateStaticVarDecl(const VarDecl &D,
525 llvm::GlobalValue::LinkageTypes Linkage);
527 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
528 return StaticLocalDeclGuardMap[D];
530 void setStaticLocalDeclGuardAddress(const VarDecl *D,
531 llvm::GlobalVariable *C) {
532 StaticLocalDeclGuardMap[D] = C;
535 bool lookupRepresentativeDecl(StringRef MangledName,
536 GlobalDecl &Result) const;
538 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
539 return AtomicSetterHelperFnMap[Ty];
541 void setAtomicSetterHelperFnMap(QualType Ty,
542 llvm::Constant *Fn) {
543 AtomicSetterHelperFnMap[Ty] = Fn;
546 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
547 return AtomicGetterHelperFnMap[Ty];
549 void setAtomicGetterHelperFnMap(QualType Ty,
550 llvm::Constant *Fn) {
551 AtomicGetterHelperFnMap[Ty] = Fn;
554 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
555 return TypeDescriptorMap[Ty];
557 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
558 TypeDescriptorMap[Ty] = C;
561 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
563 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
564 if (!NoObjCARCExceptionsMetadata)
565 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
566 return NoObjCARCExceptionsMetadata;
569 ASTContext &getContext() const { return Context; }
570 const LangOptions &getLangOpts() const { return LangOpts; }
571 const HeaderSearchOptions &getHeaderSearchOpts()
572 const { return HeaderSearchOpts; }
573 const PreprocessorOptions &getPreprocessorOpts()
574 const { return PreprocessorOpts; }
575 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
576 llvm::Module &getModule() const { return TheModule; }
577 DiagnosticsEngine &getDiags() const { return Diags; }
578 const llvm::DataLayout &getDataLayout() const {
579 return TheModule.getDataLayout();
581 const TargetInfo &getTarget() const { return Target; }
582 const llvm::Triple &getTriple() const;
583 bool supportsCOMDAT() const;
584 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
586 CGCXXABI &getCXXABI() const { return *ABI; }
587 llvm::LLVMContext &getLLVMContext() { return VMContext; }
589 bool shouldUseTBAA() const { return TBAA != nullptr; }
591 const TargetCodeGenInfo &getTargetCodeGenInfo();
593 CodeGenTypes &getTypes() { return Types; }
595 CodeGenVTables &getVTables() { return VTables; }
597 ItaniumVTableContext &getItaniumVTableContext() {
598 return VTables.getItaniumVTableContext();
601 MicrosoftVTableContext &getMicrosoftVTableContext() {
602 return VTables.getMicrosoftVTableContext();
605 CtorList &getGlobalCtors() { return GlobalCtors; }
606 CtorList &getGlobalDtors() { return GlobalDtors; }
608 llvm::MDNode *getTBAAInfo(QualType QTy);
609 llvm::MDNode *getTBAAInfoForVTablePtr();
610 llvm::MDNode *getTBAAStructInfo(QualType QTy);
611 /// Return the MDNode in the type DAG for the given struct type.
612 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
613 /// Return the path-aware tag for given base type, access node and offset.
614 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
617 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
619 bool isPaddedAtomicType(QualType type);
620 bool isPaddedAtomicType(const AtomicType *type);
622 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
623 /// is the same as the type. For struct-path aware TBAA, the tag
624 /// is different from the type: base type, access type and offset.
625 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
626 void DecorateInstruction(llvm::Instruction *Inst,
627 llvm::MDNode *TBAAInfo,
628 bool ConvertTypeToTag = true);
630 /// Emit the given number of characters as a value of type size_t.
631 llvm::ConstantInt *getSize(CharUnits numChars);
633 /// Set the visibility for the given LLVM GlobalValue.
634 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
636 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
637 /// variable declaration D.
638 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
640 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
642 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
643 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
644 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
646 llvm_unreachable("unknown visibility!");
649 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
651 /// Will return a global variable of the given type. If a variable with a
652 /// different type already exists then a new variable with the right type
653 /// will be created and all uses of the old variable will be replaced with a
654 /// bitcast to the new variable.
655 llvm::GlobalVariable *
656 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
657 llvm::GlobalValue::LinkageTypes Linkage);
660 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
661 SourceLocation Loc = SourceLocation(),
664 /// Return the address space of the underlying global variable for D, as
665 /// determined by its declaration. Normally this is the same as the address
666 /// space of D's type, but in CUDA, address spaces are associated with
667 /// declarations, not types.
668 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
670 /// Return the llvm::Constant for the address of the given global variable.
671 /// If Ty is non-null and if the global doesn't exist, then it will be greated
672 /// with the specified type instead of whatever the normal requested type
674 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
675 llvm::Type *Ty = nullptr);
677 /// Return the address of the given function. If Ty is non-null, then this
678 /// function will use the specified type if it has to create it.
679 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
680 bool ForVTable = false,
681 bool DontDefer = false,
682 bool IsForDefinition = false);
684 /// Get the address of the RTTI descriptor for the given type.
685 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
687 llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
688 QualType CatchHandlerType);
690 /// Get the address of a uuid descriptor .
691 ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
693 /// Get the address of the thunk for the given global decl.
694 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
696 /// Get a reference to the target of VD.
697 ConstantAddress GetWeakRefReference(const ValueDecl *VD);
699 /// Returns the assumed alignment of an opaque pointer to the given class.
700 CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
702 /// Returns the assumed alignment of a virtual base of a class.
703 CharUnits getVBaseAlignment(CharUnits DerivedAlign,
704 const CXXRecordDecl *Derived,
705 const CXXRecordDecl *VBase);
707 /// Given a class pointer with an actual known alignment, and the
708 /// expected alignment of an object at a dynamic offset w.r.t that
709 /// pointer, return the alignment to assume at the offset.
710 CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
711 const CXXRecordDecl *Class,
712 CharUnits ExpectedTargetAlign);
715 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
716 CastExpr::path_const_iterator Start,
717 CastExpr::path_const_iterator End);
719 /// Returns the offset from a derived class to a class. Returns null if the
722 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
723 CastExpr::path_const_iterator PathBegin,
724 CastExpr::path_const_iterator PathEnd);
726 llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
728 /// Fetches the global unique block count.
729 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
731 /// Fetches the type of a generic block descriptor.
732 llvm::Type *getBlockDescriptorType();
734 /// The type of a generic block literal.
735 llvm::Type *getGenericBlockLiteralType();
737 /// Gets the address of a block which requires no captures.
738 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
740 /// Return a pointer to a constant CFString object for the given string.
741 ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
743 /// Return a pointer to a constant NSString object for the given string. Or a
744 /// user defined String object as defined via
745 /// -fconstant-string-class=class_name option.
746 ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
748 /// Return a constant array for the given string.
749 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
751 /// Return a pointer to a constant array for the given string literal.
753 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
754 StringRef Name = ".str");
756 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
758 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
760 /// Returns a pointer to a character array containing the literal and a
761 /// terminating '\0' character. The result has pointer to array type.
763 /// \param GlobalName If provided, the name to use for the global (if one is
766 GetAddrOfConstantCString(const std::string &Str,
767 const char *GlobalName = nullptr);
769 /// Returns a pointer to a constant global variable for the given file-scope
770 /// compound literal expression.
771 ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
773 /// \brief Returns a pointer to a global variable representing a temporary
774 /// with static or thread storage duration.
775 ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
778 /// \brief Retrieve the record type that describes the state of an
779 /// Objective-C fast enumeration loop (for..in).
780 QualType getObjCFastEnumerationStateType();
782 // Produce code for this constructor/destructor. This method doesn't try
783 // to apply any ABI rules about which other constructors/destructors
784 // are needed or if they are alias to each other.
785 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
788 /// Return the address of the constructor/destructor of the given type.
790 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
791 const CGFunctionInfo *FnInfo = nullptr,
792 llvm::FunctionType *FnType = nullptr,
793 bool DontDefer = false, bool IsForDefinition = false);
795 /// Given a builtin id for a function like "__builtin_fabsf", return a
796 /// Function* for "fabsf".
797 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
800 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
802 /// Emit code for a single top level declaration.
803 void EmitTopLevelDecl(Decl *D);
805 /// \brief Stored a deferred empty coverage mapping for an unused
806 /// and thus uninstrumented top level declaration.
807 void AddDeferredUnusedCoverageMapping(Decl *D);
809 /// \brief Remove the deferred empty coverage mapping as this
810 /// declaration is actually instrumented.
811 void ClearUnusedCoverageMapping(const Decl *D);
813 /// \brief Emit all the deferred coverage mappings
814 /// for the uninstrumented functions.
815 void EmitDeferredUnusedCoverageMappings();
817 /// Tell the consumer that this variable has been instantiated.
818 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
820 /// \brief If the declaration has internal linkage but is inside an
821 /// extern "C" linkage specification, prepare to emit an alias for it
822 /// to the expected name.
823 template<typename SomeDecl>
824 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
826 /// Add a global to a list to be added to the llvm.used metadata.
827 void addUsedGlobal(llvm::GlobalValue *GV);
829 /// Add a global to a list to be added to the llvm.compiler.used metadata.
830 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
832 /// Add a destructor and object to add to the C++ global destructor function.
833 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
834 CXXGlobalDtors.emplace_back(DtorFn, Object);
837 /// Create a new runtime function with the specified type and name.
838 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
840 llvm::AttributeSet ExtraAttrs =
841 llvm::AttributeSet());
842 /// Create a new compiler builtin function with the specified type and name.
843 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
845 llvm::AttributeSet ExtraAttrs =
846 llvm::AttributeSet());
847 /// Create a new runtime global variable with the specified type and name.
848 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
851 ///@name Custom Blocks Runtime Interfaces
854 llvm::Constant *getNSConcreteGlobalBlock();
855 llvm::Constant *getNSConcreteStackBlock();
856 llvm::Constant *getBlockObjectAssign();
857 llvm::Constant *getBlockObjectDispose();
861 llvm::Constant *getLLVMLifetimeStartFn();
862 llvm::Constant *getLLVMLifetimeEndFn();
864 // Make sure that this type is translated.
865 void UpdateCompletedType(const TagDecl *TD);
867 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
869 /// Try to emit the initializer for the given declaration as a constant;
870 /// returns 0 if the expression cannot be emitted as a constant.
871 llvm::Constant *EmitConstantInit(const VarDecl &D,
872 CodeGenFunction *CGF = nullptr);
874 /// Try to emit the given expression as a constant; returns 0 if the
875 /// expression cannot be emitted as a constant.
876 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
877 CodeGenFunction *CGF = nullptr);
879 /// Emit the given constant value as a constant, in the type's scalar
881 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
882 CodeGenFunction *CGF = nullptr);
884 /// Emit the given constant value as a constant, in the type's memory
886 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
888 CodeGenFunction *CGF = nullptr);
890 /// Return the result of value-initializing the given type, i.e. a null
891 /// expression of the given type. This is usually, but not always, an LLVM
893 llvm::Constant *EmitNullConstant(QualType T);
895 /// Return a null constant appropriate for zero-initializing a base class with
896 /// the given type. This is usually, but not always, an LLVM null constant.
897 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
899 /// Emit a general error that something can't be done.
900 void Error(SourceLocation loc, StringRef error);
902 /// Print out an error that codegen doesn't support the specified stmt yet.
903 void ErrorUnsupported(const Stmt *S, const char *Type);
905 /// Print out an error that codegen doesn't support the specified decl yet.
906 void ErrorUnsupported(const Decl *D, const char *Type);
908 /// Set the attributes on the LLVM function for the given decl and function
909 /// info. This applies attributes necessary for handling the ABI as well as
910 /// user specified attributes like section.
911 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
912 const CGFunctionInfo &FI);
914 /// Set the LLVM function attributes (sext, zext, etc).
915 void SetLLVMFunctionAttributes(const Decl *D,
916 const CGFunctionInfo &Info,
919 /// Set the LLVM function attributes which only apply to a function
921 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
923 /// Return true iff the given type uses 'sret' when used as a return type.
924 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
926 /// Return true iff the given type uses an argument slot when 'sret' is used
927 /// as a return type.
928 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
930 /// Return true iff the given type uses 'fpret' when used as a return type.
931 bool ReturnTypeUsesFPRet(QualType ResultType);
933 /// Return true iff the given type uses 'fp2ret' when used as a return type.
934 bool ReturnTypeUsesFP2Ret(QualType ResultType);
936 /// Get the LLVM attributes and calling convention to use for a particular
939 /// \param Info - The function type information.
940 /// \param TargetDecl - The decl these attributes are being constructed
941 /// for. If supplied the attributes applied to this decl may contribute to the
942 /// function attributes and calling convention.
943 /// \param PAL [out] - On return, the attribute list to use.
944 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
945 void ConstructAttributeList(const CGFunctionInfo &Info,
946 const Decl *TargetDecl,
947 AttributeListType &PAL,
948 unsigned &CallingConv,
949 bool AttrOnCallSite);
951 StringRef getMangledName(GlobalDecl GD);
952 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
954 void EmitTentativeDefinition(const VarDecl *D);
956 void EmitVTable(CXXRecordDecl *Class);
958 /// Emit the RTTI descriptors for the builtin types.
959 void EmitFundamentalRTTIDescriptors();
961 /// \brief Appends Opts to the "Linker Options" metadata value.
962 void AppendLinkerOptions(StringRef Opts);
964 /// \brief Appends a detect mismatch command to the linker options.
965 void AddDetectMismatch(StringRef Name, StringRef Value);
967 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
968 void AddDependentLib(StringRef Lib);
970 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
972 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
973 F->setLinkage(getFunctionLinkage(GD));
976 /// Set the DLL storage class on F.
977 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
979 /// Return the appropriate linkage for the vtable, VTT, and type information
980 /// of the given class.
981 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
983 /// Return the store size, in character units, of the given LLVM type.
984 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
986 /// Returns LLVM linkage for a declarator.
987 llvm::GlobalValue::LinkageTypes
988 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
989 bool IsConstantVariable);
991 /// Returns LLVM linkage for a declarator.
992 llvm::GlobalValue::LinkageTypes
993 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
995 /// Emit all the global annotations.
996 void EmitGlobalAnnotations();
998 /// Emit an annotation string.
999 llvm::Constant *EmitAnnotationString(StringRef Str);
1001 /// Emit the annotation's translation unit.
1002 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1004 /// Emit the annotation line number.
1005 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1007 /// Generate the llvm::ConstantStruct which contains the annotation
1008 /// information for a given GlobalValue. The annotation struct is
1009 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1010 /// GlobalValue being annotated. The second field is the constant string
1011 /// created from the AnnotateAttr's annotation. The third field is a constant
1012 /// string containing the name of the translation unit. The fourth field is
1013 /// the line number in the file of the annotated value declaration.
1014 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1015 const AnnotateAttr *AA,
1018 /// Add global annotations that are set on D, for the global GV. Those
1019 /// annotations are emitted during finalization of the LLVM code.
1020 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1022 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1024 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1026 StringRef Category = StringRef()) const;
1028 SanitizerMetadata *getSanitizerMetadata() {
1029 return SanitizerMD.get();
1032 void addDeferredVTable(const CXXRecordDecl *RD) {
1033 DeferredVTables.push_back(RD);
1036 /// Emit code for a singal global function or var decl. Forward declarations
1037 /// are emitted lazily.
1038 void EmitGlobal(GlobalDecl D);
1041 HasTrivialDestructorBody(ASTContext &Context,
1042 const CXXRecordDecl *BaseClassDecl,
1043 const CXXRecordDecl *MostDerivedClassDecl);
1045 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1047 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1049 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1051 /// Set attributes for a global definition.
1052 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1055 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1057 /// Set attributes which are common to any form of a global definition (alias,
1058 /// Objective-C method, function, global variable).
1060 /// NOTE: This should only be called for definitions.
1061 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1063 /// Set attributes which must be preserved by an alias. This includes common
1064 /// attributes (i.e. it includes a call to SetCommonAttributes).
1066 /// NOTE: This should only be called for definitions.
1067 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1069 void addReplacement(StringRef Name, llvm::Constant *C);
1071 void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1073 /// \brief Emit a code for threadprivate directive.
1074 /// \param D Threadprivate declaration.
1075 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1077 /// Returns whether the given record is blacklisted from control flow
1078 /// integrity checks.
1079 bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
1081 /// Emit bit set entries for the given vtable using the given layout if
1082 /// vptr CFI is enabled.
1083 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1084 const VTableLayout &VTLayout);
1086 /// Create a bitset entry for the given vtable.
1087 llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
1089 const CXXRecordDecl *RD);
1091 /// \breif Get the declaration of std::terminate for the platform.
1092 llvm::Constant *getTerminateFn();
1096 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1097 bool ForVTable, bool DontDefer = false,
1098 bool IsThunk = false,
1099 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
1100 bool IsForDefinition = false);
1102 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1103 llvm::PointerType *PTy,
1106 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1108 /// Set function attributes for a function declaration.
1109 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1110 bool IsIncompleteFunction, bool IsThunk);
1112 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1114 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1115 void EmitGlobalVarDefinition(const VarDecl *D);
1116 void EmitAliasDefinition(GlobalDecl GD);
1117 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1118 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1120 // C++ related functions.
1122 void EmitNamespace(const NamespaceDecl *D);
1123 void EmitLinkageSpec(const LinkageSpecDecl *D);
1124 void CompleteDIClassType(const CXXMethodDecl* D);
1126 /// \brief Emit the function that initializes C++ thread_local variables.
1127 void EmitCXXThreadLocalInitFunc();
1129 /// Emit the function that initializes C++ globals.
1130 void EmitCXXGlobalInitFunc();
1132 /// Emit the function that destroys C++ globals.
1133 void EmitCXXGlobalDtorFunc();
1135 /// Emit the function that initializes the specified global (if PerformInit is
1136 /// true) and registers its destructor.
1137 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1138 llvm::GlobalVariable *Addr,
1141 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1142 llvm::Function *InitFunc, InitSegAttr *ISA);
1144 // FIXME: Hardcoding priority here is gross.
1145 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1146 llvm::Constant *AssociatedData = 0);
1147 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1149 /// Generates a global array of functions and priorities using the given list
1150 /// and name. This array will have appending linkage and is suitable for use
1151 /// as a LLVM constructor or destructor array.
1152 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1154 /// Emit the RTTI descriptors for the given type.
1155 void EmitFundamentalRTTIDescriptor(QualType Type);
1157 /// Emit any needed decls for which code generation was deferred.
1158 void EmitDeferred();
1160 /// Call replaceAllUsesWith on all pairs in Replacements.
1161 void applyReplacements();
1163 /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1164 void applyGlobalValReplacements();
1166 void checkAliases();
1168 /// Emit any vtables which we deferred and still have a use for.
1169 void EmitDeferredVTables();
1171 /// Emit the llvm.used and llvm.compiler.used metadata.
1172 void emitLLVMUsed();
1174 /// \brief Emit the link options introduced by imported modules.
1175 void EmitModuleLinkOptions();
1177 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1178 /// linkage specifications, giving them the "expected" name where possible.
1179 void EmitStaticExternCAliases();
1181 void EmitDeclMetadata();
1183 /// \brief Emit the Clang version as llvm.ident metadata.
1184 void EmitVersionIdentMetadata();
1186 /// Emits target specific Metadata for global declarations.
1187 void EmitTargetMetadata();
1189 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1190 /// .gcda files in a way that persists in .bc files.
1191 void EmitCoverageFile();
1193 /// Emits the initializer for a uuidof string.
1194 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1196 /// Determine whether the definition must be emitted; if this returns \c
1197 /// false, the definition can be emitted lazily if it's used.
1198 bool MustBeEmitted(const ValueDecl *D);
1200 /// Determine whether the definition can be emitted eagerly, or should be
1201 /// delayed until the end of the translation unit. This is relevant for
1202 /// definitions whose linkage can change, e.g. implicit function instantions
1203 /// which may later be explicitly instantiated.
1204 bool MayBeEmittedEagerly(const ValueDecl *D);
1206 /// Check whether we can use a "simpler", more core exceptions personality
1208 void SimplifyPersonality();
1210 } // end namespace CodeGen
1211 } // end namespace clang