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 "CodeGenTypes.h"
19 #include "SanitizerMetadata.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/GlobalDecl.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/Basic/ABI.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/SanitizerBlacklist.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/IR/CallingConv.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 DiagnosticsEngine;
74 class CXXDestructorDecl;
76 class CoverageSourceInfo;
81 class CodeGenFunction;
86 class CGOpenCLRuntime;
87 class CGOpenMPRuntime;
89 class BlockFieldFlags;
90 class FunctionArgList;
91 class CoverageMappingModuleGen;
93 struct OrderGlobalInits {
94 unsigned int priority;
95 unsigned int lex_order;
96 OrderGlobalInits(unsigned int p, unsigned int l)
97 : priority(p), lex_order(l) {}
99 bool operator==(const OrderGlobalInits &RHS) const {
100 return priority == RHS.priority && lex_order == RHS.lex_order;
103 bool operator<(const OrderGlobalInits &RHS) const {
104 return std::tie(priority, lex_order) <
105 std::tie(RHS.priority, RHS.lex_order);
109 struct CodeGenTypeCache {
113 /// i8, i16, i32, and i64
114 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
116 llvm::Type *FloatTy, *DoubleTy;
119 llvm::IntegerType *IntTy;
121 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
123 llvm::IntegerType *IntPtrTy;
124 llvm::IntegerType *SizeTy;
125 llvm::IntegerType *PtrDiffTy;
128 /// void* in address space 0
130 llvm::PointerType *VoidPtrTy;
131 llvm::PointerType *Int8PtrTy;
134 /// void** in address space 0
136 llvm::PointerType *VoidPtrPtrTy;
137 llvm::PointerType *Int8PtrPtrTy;
140 /// The width of a pointer into the generic address space.
141 unsigned char PointerWidthInBits;
143 /// The size and alignment of a pointer into the generic address
146 unsigned char PointerAlignInBytes;
147 unsigned char PointerSizeInBytes;
148 unsigned char SizeSizeInBytes; // sizeof(size_t)
151 llvm::CallingConv::ID RuntimeCC;
152 llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
153 llvm::CallingConv::ID BuiltinCC;
154 llvm::CallingConv::ID getBuiltinCC() const { return BuiltinCC; }
157 struct RREntrypoints {
158 RREntrypoints() { memset(this, 0, sizeof(*this)); }
159 /// void objc_autoreleasePoolPop(void*);
160 llvm::Constant *objc_autoreleasePoolPop;
162 /// void *objc_autoreleasePoolPush(void);
163 llvm::Constant *objc_autoreleasePoolPush;
166 struct ARCEntrypoints {
167 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
169 /// id objc_autorelease(id);
170 llvm::Constant *objc_autorelease;
172 /// id objc_autoreleaseReturnValue(id);
173 llvm::Constant *objc_autoreleaseReturnValue;
175 /// void objc_copyWeak(id *dest, id *src);
176 llvm::Constant *objc_copyWeak;
178 /// void objc_destroyWeak(id*);
179 llvm::Constant *objc_destroyWeak;
181 /// id objc_initWeak(id*, id);
182 llvm::Constant *objc_initWeak;
184 /// id objc_loadWeak(id*);
185 llvm::Constant *objc_loadWeak;
187 /// id objc_loadWeakRetained(id*);
188 llvm::Constant *objc_loadWeakRetained;
190 /// void objc_moveWeak(id *dest, id *src);
191 llvm::Constant *objc_moveWeak;
193 /// id objc_retain(id);
194 llvm::Constant *objc_retain;
196 /// id objc_retainAutorelease(id);
197 llvm::Constant *objc_retainAutorelease;
199 /// id objc_retainAutoreleaseReturnValue(id);
200 llvm::Constant *objc_retainAutoreleaseReturnValue;
202 /// id objc_retainAutoreleasedReturnValue(id);
203 llvm::Constant *objc_retainAutoreleasedReturnValue;
205 /// id objc_retainBlock(id);
206 llvm::Constant *objc_retainBlock;
208 /// void objc_release(id);
209 llvm::Constant *objc_release;
211 /// id objc_storeStrong(id*, id);
212 llvm::Constant *objc_storeStrong;
214 /// id objc_storeWeak(id*, id);
215 llvm::Constant *objc_storeWeak;
217 /// A void(void) inline asm to use to mark that the return value of
218 /// a call will be immediately retain.
219 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
221 /// void clang.arc.use(...);
222 llvm::Constant *clang_arc_use;
225 /// This class records statistics on instrumentation based profiling.
226 class InstrProfStats {
227 uint32_t VisitedInMainFile;
228 uint32_t MissingInMainFile;
235 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
237 /// Record that we've visited a function and whether or not that function was
238 /// in the main source file.
239 void addVisited(bool MainFile) {
244 /// Record that a function we've visited has no profile data.
245 void addMissing(bool MainFile) {
250 /// Record that a function we've visited has mismatched profile data.
251 void addMismatched(bool MainFile) { ++Mismatched; }
252 /// Whether or not the stats we've gathered indicate any potential problems.
253 bool hasDiagnostics() { return Missing || Mismatched; }
254 /// Report potential problems we've found to \c Diags.
255 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
258 /// This class organizes the cross-function state that is used while generating
260 class CodeGenModule : public CodeGenTypeCache {
261 CodeGenModule(const CodeGenModule &) = delete;
262 void operator=(const CodeGenModule &) = delete;
266 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
267 Structor(int Priority, llvm::Constant *Initializer,
268 llvm::Constant *AssociatedData)
269 : Priority(Priority), Initializer(Initializer),
270 AssociatedData(AssociatedData) {}
272 llvm::Constant *Initializer;
273 llvm::Constant *AssociatedData;
276 typedef std::vector<Structor> CtorList;
280 const LangOptions &LangOpts;
281 const CodeGenOptions &CodeGenOpts;
282 llvm::Module &TheModule;
283 DiagnosticsEngine &Diags;
284 const llvm::DataLayout &TheDataLayout;
285 const TargetInfo &Target;
286 std::unique_ptr<CGCXXABI> ABI;
287 llvm::LLVMContext &VMContext;
291 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
293 // This should not be moved earlier, since its initialization depends on some
294 // of the previous reference members being already initialized and also checks
295 // if TheTargetCodeGenInfo is NULL
298 /// Holds information about C++ vtables.
299 CodeGenVTables VTables;
301 CGObjCRuntime* ObjCRuntime;
302 CGOpenCLRuntime* OpenCLRuntime;
303 CGOpenMPRuntime* OpenMPRuntime;
304 CGCUDARuntime* CUDARuntime;
305 CGDebugInfo* DebugInfo;
306 ARCEntrypoints *ARCData;
307 llvm::MDNode *NoObjCARCExceptionsMetadata;
308 RREntrypoints *RRData;
309 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
310 InstrProfStats PGOStats;
312 // A set of references that have only been seen via a weakref so far. This is
313 // used to remove the weak of the reference if we ever see a direct reference
315 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
317 /// This contains all the decls which have definitions but/ which are deferred
318 /// for emission and therefore should only be output if they are actually
319 /// used. If a decl is in this, then it is known to have not been referenced
321 std::map<StringRef, GlobalDecl> DeferredDecls;
323 /// This is a list of deferred decls which we have seen that *are* actually
324 /// referenced. These get code generated when the module is done.
325 struct DeferredGlobal {
326 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
327 llvm::TrackingVH<llvm::GlobalValue> GV;
330 std::vector<DeferredGlobal> DeferredDeclsToEmit;
331 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
332 DeferredDeclsToEmit.emplace_back(GV, GD);
335 /// List of alias we have emitted. Used to make sure that what they point to
336 /// is defined once we get to the end of the of the translation unit.
337 std::vector<GlobalDecl> Aliases;
339 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
340 ReplacementsTy Replacements;
342 /// A queue of (optional) vtables to consider emitting.
343 std::vector<const CXXRecordDecl*> DeferredVTables;
345 /// List of global values which are required to be present in the object file;
346 /// bitcast to i8*. This is used for forcing visibility of symbols which may
347 /// otherwise be optimized out.
348 std::vector<llvm::WeakVH> LLVMUsed;
349 std::vector<llvm::WeakVH> LLVMCompilerUsed;
351 /// Store the list of global constructors and their respective priorities to
352 /// be emitted when the translation unit is complete.
353 CtorList GlobalCtors;
355 /// Store the list of global destructors and their respective priorities to be
356 /// emitted when the translation unit is complete.
357 CtorList GlobalDtors;
359 /// An ordered map of canonical GlobalDecls to their mangled names.
360 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
361 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
363 /// Global annotations.
364 std::vector<llvm::Constant*> Annotations;
366 /// Map used to get unique annotation strings.
367 llvm::StringMap<llvm::Constant*> AnnotationStrings;
369 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
371 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
372 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
373 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
374 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
376 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
377 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
379 /// Map used to get unique type descriptor constants for sanitizers.
380 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
382 /// Map used to track internal linkage functions declared within
383 /// extern "C" regions.
384 typedef llvm::MapVector<IdentifierInfo *,
385 llvm::GlobalValue *> StaticExternCMap;
386 StaticExternCMap StaticExternCValues;
388 /// \brief thread_local variables defined or used in this TU.
389 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
392 /// \brief thread_local variables with initializers that need to run
393 /// before any thread_local variable in this TU is odr-used.
394 std::vector<llvm::Function *> CXXThreadLocalInits;
395 std::vector<llvm::GlobalVariable *> CXXThreadLocalInitVars;
397 /// Global variables with initializers that need to run before main.
398 std::vector<llvm::Function *> CXXGlobalInits;
400 /// When a C++ decl with an initializer is deferred, null is
401 /// appended to CXXGlobalInits, and the index of that null is placed
402 /// here so that the initializer will be performed in the correct
403 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
404 /// that we don't re-emit the initializer.
405 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
407 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
409 struct GlobalInitPriorityCmp {
410 bool operator()(const GlobalInitData &LHS,
411 const GlobalInitData &RHS) const {
412 return LHS.first.priority < RHS.first.priority;
416 /// Global variables with initializers whose order of initialization is set by
417 /// init_priority attribute.
418 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
420 /// Global destructor functions and arguments that need to run on termination.
421 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
423 /// \brief The complete set of modules that has been imported.
424 llvm::SetVector<clang::Module *> ImportedModules;
426 /// \brief A vector of metadata strings.
427 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
429 /// @name Cache for Objective-C runtime types
432 /// Cached reference to the class for constant strings. This value has type
433 /// int * but is actually an Obj-C class pointer.
434 llvm::WeakVH CFConstantStringClassRef;
436 /// Cached reference to the class for constant strings. This value has type
437 /// int * but is actually an Obj-C class pointer.
438 llvm::WeakVH ConstantStringClassRef;
440 /// \brief The LLVM type corresponding to NSConstantString.
441 llvm::StructType *NSConstantStringType;
443 /// \brief The type used to describe the state of a fast enumeration in
444 /// Objective-C's for..in loop.
445 QualType ObjCFastEnumerationStateType;
449 /// Lazily create the Objective-C runtime
450 void createObjCRuntime();
452 void createOpenCLRuntime();
453 void createOpenMPRuntime();
454 void createCUDARuntime();
456 bool isTriviallyRecursive(const FunctionDecl *F);
457 bool shouldEmitFunction(GlobalDecl GD);
459 /// @name Cache for Blocks Runtime Globals
462 llvm::Constant *NSConcreteGlobalBlock;
463 llvm::Constant *NSConcreteStackBlock;
465 llvm::Constant *BlockObjectAssign;
466 llvm::Constant *BlockObjectDispose;
468 llvm::Type *BlockDescriptorType;
469 llvm::Type *GenericBlockLiteralType;
472 int GlobalUniqueCount;
475 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
476 llvm::Constant *LifetimeStartFn;
478 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
479 llvm::Constant *LifetimeEndFn;
481 GlobalDecl initializedGlobalDecl;
483 std::unique_ptr<SanitizerMetadata> SanitizerMD;
487 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
489 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
491 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
492 llvm::Module &M, const llvm::DataLayout &TD,
493 DiagnosticsEngine &Diags,
494 CoverageSourceInfo *CoverageInfo = nullptr);
500 /// Finalize LLVM code generation.
503 /// Return a reference to the configured Objective-C runtime.
504 CGObjCRuntime &getObjCRuntime() {
505 if (!ObjCRuntime) createObjCRuntime();
509 /// Return true iff an Objective-C runtime has been configured.
510 bool hasObjCRuntime() { return !!ObjCRuntime; }
512 /// Return a reference to the configured OpenCL runtime.
513 CGOpenCLRuntime &getOpenCLRuntime() {
514 assert(OpenCLRuntime != nullptr);
515 return *OpenCLRuntime;
518 /// Return a reference to the configured OpenMP runtime.
519 CGOpenMPRuntime &getOpenMPRuntime() {
520 assert(OpenMPRuntime != nullptr);
521 return *OpenMPRuntime;
524 /// Return a reference to the configured CUDA runtime.
525 CGCUDARuntime &getCUDARuntime() {
526 assert(CUDARuntime != nullptr);
530 ARCEntrypoints &getARCEntrypoints() const {
531 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
535 RREntrypoints &getRREntrypoints() const {
536 assert(RRData != nullptr);
540 InstrProfStats &getPGOStats() { return PGOStats; }
541 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
543 CoverageMappingModuleGen *getCoverageMapping() const {
544 return CoverageMapping.get();
547 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
548 return StaticLocalDeclMap[D];
550 void setStaticLocalDeclAddress(const VarDecl *D,
552 StaticLocalDeclMap[D] = C;
556 getOrCreateStaticVarDecl(const VarDecl &D,
557 llvm::GlobalValue::LinkageTypes Linkage);
559 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
560 return StaticLocalDeclGuardMap[D];
562 void setStaticLocalDeclGuardAddress(const VarDecl *D,
563 llvm::GlobalVariable *C) {
564 StaticLocalDeclGuardMap[D] = C;
567 bool lookupRepresentativeDecl(StringRef MangledName,
568 GlobalDecl &Result) const;
570 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
571 return AtomicSetterHelperFnMap[Ty];
573 void setAtomicSetterHelperFnMap(QualType Ty,
574 llvm::Constant *Fn) {
575 AtomicSetterHelperFnMap[Ty] = Fn;
578 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
579 return AtomicGetterHelperFnMap[Ty];
581 void setAtomicGetterHelperFnMap(QualType Ty,
582 llvm::Constant *Fn) {
583 AtomicGetterHelperFnMap[Ty] = Fn;
586 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
587 return TypeDescriptorMap[Ty];
589 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
590 TypeDescriptorMap[Ty] = C;
593 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
595 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
596 if (!NoObjCARCExceptionsMetadata)
597 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
598 return NoObjCARCExceptionsMetadata;
601 ASTContext &getContext() const { return Context; }
602 const LangOptions &getLangOpts() const { return LangOpts; }
603 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
604 llvm::Module &getModule() const { return TheModule; }
605 DiagnosticsEngine &getDiags() const { return Diags; }
606 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
607 const TargetInfo &getTarget() const { return Target; }
608 const llvm::Triple &getTriple() const;
609 bool supportsCOMDAT() const;
610 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
612 CGCXXABI &getCXXABI() const { return *ABI; }
613 llvm::LLVMContext &getLLVMContext() { return VMContext; }
615 bool shouldUseTBAA() const { return TBAA != nullptr; }
617 const TargetCodeGenInfo &getTargetCodeGenInfo();
619 CodeGenTypes &getTypes() { return Types; }
621 CodeGenVTables &getVTables() { return VTables; }
623 ItaniumVTableContext &getItaniumVTableContext() {
624 return VTables.getItaniumVTableContext();
627 MicrosoftVTableContext &getMicrosoftVTableContext() {
628 return VTables.getMicrosoftVTableContext();
631 CtorList &getGlobalCtors() { return GlobalCtors; }
632 CtorList &getGlobalDtors() { return GlobalDtors; }
634 llvm::MDNode *getTBAAInfo(QualType QTy);
635 llvm::MDNode *getTBAAInfoForVTablePtr();
636 llvm::MDNode *getTBAAStructInfo(QualType QTy);
637 /// Return the MDNode in the type DAG for the given struct type.
638 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
639 /// Return the path-aware tag for given base type, access node and offset.
640 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
643 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
645 bool isPaddedAtomicType(QualType type);
646 bool isPaddedAtomicType(const AtomicType *type);
648 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
649 /// is the same as the type. For struct-path aware TBAA, the tag
650 /// is different from the type: base type, access type and offset.
651 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
652 void DecorateInstruction(llvm::Instruction *Inst,
653 llvm::MDNode *TBAAInfo,
654 bool ConvertTypeToTag = true);
656 /// Emit the given number of characters as a value of type size_t.
657 llvm::ConstantInt *getSize(CharUnits numChars);
659 /// Set the visibility for the given LLVM GlobalValue.
660 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
662 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
663 /// variable declaration D.
664 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
666 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
668 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
669 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
670 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
672 llvm_unreachable("unknown visibility!");
675 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
676 if (isa<CXXConstructorDecl>(GD.getDecl()))
677 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
678 getFromCtorType(GD.getCtorType()));
679 else if (isa<CXXDestructorDecl>(GD.getDecl()))
680 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
681 getFromDtorType(GD.getDtorType()));
682 else if (isa<FunctionDecl>(GD.getDecl()))
683 return GetAddrOfFunction(GD);
685 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
688 /// Will return a global variable of the given type. If a variable with a
689 /// different type already exists then a new variable with the right type
690 /// will be created and all uses of the old variable will be replaced with a
691 /// bitcast to the new variable.
692 llvm::GlobalVariable *
693 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
694 llvm::GlobalValue::LinkageTypes Linkage);
697 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
698 SourceLocation Loc = SourceLocation(),
701 /// Return the address space of the underlying global variable for D, as
702 /// determined by its declaration. Normally this is the same as the address
703 /// space of D's type, but in CUDA, address spaces are associated with
704 /// declarations, not types.
705 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
707 /// Return the llvm::Constant for the address of the given global variable.
708 /// If Ty is non-null and if the global doesn't exist, then it will be greated
709 /// with the specified type instead of whatever the normal requested type
711 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
712 llvm::Type *Ty = nullptr);
714 /// Return the address of the given function. If Ty is non-null, then this
715 /// function will use the specified type if it has to create it.
716 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
717 bool ForVTable = false,
718 bool DontDefer = false);
720 /// Get the address of the RTTI descriptor for the given type.
721 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
723 llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
724 QualType CatchHandlerType);
726 /// Get the address of a uuid descriptor .
727 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
729 /// Get the address of the thunk for the given global decl.
730 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
732 /// Get a reference to the target of VD.
733 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
736 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
737 CastExpr::path_const_iterator Start,
738 CastExpr::path_const_iterator End);
740 /// Returns the offset from a derived class to a class. Returns null if the
743 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
744 CastExpr::path_const_iterator PathBegin,
745 CastExpr::path_const_iterator PathEnd);
747 /// A pair of helper functions for a __block variable.
748 class ByrefHelpers : public llvm::FoldingSetNode {
750 llvm::Constant *CopyHelper;
751 llvm::Constant *DisposeHelper;
753 /// The alignment of the field. This is important because
754 /// different offsets to the field within the byref struct need to
755 /// have different helper functions.
758 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
759 virtual ~ByrefHelpers();
761 void Profile(llvm::FoldingSetNodeID &id) const {
762 id.AddInteger(Alignment.getQuantity());
765 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
767 virtual bool needsCopy() const { return true; }
768 virtual void emitCopy(CodeGenFunction &CGF,
769 llvm::Value *dest, llvm::Value *src) = 0;
771 virtual bool needsDispose() const { return true; }
772 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
775 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
777 /// Fetches the global unique block count.
778 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
780 /// Fetches the type of a generic block descriptor.
781 llvm::Type *getBlockDescriptorType();
783 /// The type of a generic block literal.
784 llvm::Type *getGenericBlockLiteralType();
786 /// Gets the address of a block which requires no captures.
787 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
789 /// Return a pointer to a constant CFString object for the given string.
790 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
792 /// Return a pointer to a constant NSString object for the given string. Or a
793 /// user defined String object as defined via
794 /// -fconstant-string-class=class_name option.
795 llvm::GlobalVariable *GetAddrOfConstantString(const StringLiteral *Literal);
797 /// Return a constant array for the given string.
798 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
800 /// Return a pointer to a constant array for the given string literal.
801 llvm::GlobalVariable *
802 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
803 StringRef Name = ".str");
805 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
806 llvm::GlobalVariable *
807 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
809 /// Returns a pointer to a character array containing the literal and a
810 /// terminating '\0' character. The result has pointer to array type.
812 /// \param GlobalName If provided, the name to use for the global (if one is
814 llvm::GlobalVariable *
815 GetAddrOfConstantCString(const std::string &Str,
816 const char *GlobalName = nullptr,
817 unsigned Alignment = 0);
819 /// Returns a pointer to a constant global variable for the given file-scope
820 /// compound literal expression.
821 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
823 /// \brief Returns a pointer to a global variable representing a temporary
824 /// with static or thread storage duration.
825 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
828 /// \brief Retrieve the record type that describes the state of an
829 /// Objective-C fast enumeration loop (for..in).
830 QualType getObjCFastEnumerationStateType();
832 // Produce code for this constructor/destructor. This method doesn't try
833 // to apply any ABI rules about which other constructors/destructors
834 // are needed or if they are alias to each other.
835 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
838 /// Return the address of the constructor/destructor of the given type.
840 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
841 const CGFunctionInfo *FnInfo = nullptr,
842 llvm::FunctionType *FnType = nullptr,
843 bool DontDefer = false);
845 /// Given a builtin id for a function like "__builtin_fabsf", return a
846 /// Function* for "fabsf".
847 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
850 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
852 /// Emit code for a single top level declaration.
853 void EmitTopLevelDecl(Decl *D);
855 /// \brief Stored a deferred empty coverage mapping for an unused
856 /// and thus uninstrumented top level declaration.
857 void AddDeferredUnusedCoverageMapping(Decl *D);
859 /// \brief Remove the deferred empty coverage mapping as this
860 /// declaration is actually instrumented.
861 void ClearUnusedCoverageMapping(const Decl *D);
863 /// \brief Emit all the deferred coverage mappings
864 /// for the uninstrumented functions.
865 void EmitDeferredUnusedCoverageMappings();
867 /// Tell the consumer that this variable has been instantiated.
868 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
870 /// \brief If the declaration has internal linkage but is inside an
871 /// extern "C" linkage specification, prepare to emit an alias for it
872 /// to the expected name.
873 template<typename SomeDecl>
874 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
876 /// Add a global to a list to be added to the llvm.used metadata.
877 void addUsedGlobal(llvm::GlobalValue *GV);
879 /// Add a global to a list to be added to the llvm.compiler.used metadata.
880 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
882 /// Add a destructor and object to add to the C++ global destructor function.
883 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
884 CXXGlobalDtors.emplace_back(DtorFn, Object);
887 /// Create a new runtime function with the specified type and name.
888 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
890 llvm::AttributeSet ExtraAttrs =
891 llvm::AttributeSet());
892 /// Create a new compiler builtin function with the specified type and name.
893 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
895 llvm::AttributeSet ExtraAttrs =
896 llvm::AttributeSet());
897 /// Create a new runtime global variable with the specified type and name.
898 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
901 ///@name Custom Blocks Runtime Interfaces
904 llvm::Constant *getNSConcreteGlobalBlock();
905 llvm::Constant *getNSConcreteStackBlock();
906 llvm::Constant *getBlockObjectAssign();
907 llvm::Constant *getBlockObjectDispose();
911 llvm::Constant *getLLVMLifetimeStartFn();
912 llvm::Constant *getLLVMLifetimeEndFn();
914 // Make sure that this type is translated.
915 void UpdateCompletedType(const TagDecl *TD);
917 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
919 /// Try to emit the initializer for the given declaration as a constant;
920 /// returns 0 if the expression cannot be emitted as a constant.
921 llvm::Constant *EmitConstantInit(const VarDecl &D,
922 CodeGenFunction *CGF = nullptr);
924 /// Try to emit the given expression as a constant; returns 0 if the
925 /// expression cannot be emitted as a constant.
926 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
927 CodeGenFunction *CGF = nullptr);
929 /// Emit the given constant value as a constant, in the type's scalar
931 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
932 CodeGenFunction *CGF = nullptr);
934 /// Emit the given constant value as a constant, in the type's memory
936 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
938 CodeGenFunction *CGF = nullptr);
940 /// Return the result of value-initializing the given type, i.e. a null
941 /// expression of the given type. This is usually, but not always, an LLVM
943 llvm::Constant *EmitNullConstant(QualType T);
945 /// Return a null constant appropriate for zero-initializing a base class with
946 /// the given type. This is usually, but not always, an LLVM null constant.
947 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
949 /// Emit a general error that something can't be done.
950 void Error(SourceLocation loc, StringRef error);
952 /// Print out an error that codegen doesn't support the specified stmt yet.
953 void ErrorUnsupported(const Stmt *S, const char *Type);
955 /// Print out an error that codegen doesn't support the specified decl yet.
956 void ErrorUnsupported(const Decl *D, const char *Type);
958 /// Set the attributes on the LLVM function for the given decl and function
959 /// info. This applies attributes necessary for handling the ABI as well as
960 /// user specified attributes like section.
961 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
962 const CGFunctionInfo &FI);
964 /// Set the LLVM function attributes (sext, zext, etc).
965 void SetLLVMFunctionAttributes(const Decl *D,
966 const CGFunctionInfo &Info,
969 /// Set the LLVM function attributes which only apply to a function
971 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
973 /// Return true iff the given type uses 'sret' when used as a return type.
974 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
976 /// Return true iff the given type uses an argument slot when 'sret' is used
977 /// as a return type.
978 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
980 /// Return true iff the given type uses 'fpret' when used as a return type.
981 bool ReturnTypeUsesFPRet(QualType ResultType);
983 /// Return true iff the given type uses 'fp2ret' when used as a return type.
984 bool ReturnTypeUsesFP2Ret(QualType ResultType);
986 /// Get the LLVM attributes and calling convention to use for a particular
989 /// \param Info - The function type information.
990 /// \param TargetDecl - The decl these attributes are being constructed
991 /// for. If supplied the attributes applied to this decl may contribute to the
992 /// function attributes and calling convention.
993 /// \param PAL [out] - On return, the attribute list to use.
994 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
995 void ConstructAttributeList(const CGFunctionInfo &Info,
996 const Decl *TargetDecl,
997 AttributeListType &PAL,
998 unsigned &CallingConv,
999 bool AttrOnCallSite);
1001 StringRef getMangledName(GlobalDecl GD);
1002 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1004 void EmitTentativeDefinition(const VarDecl *D);
1006 void EmitVTable(CXXRecordDecl *Class);
1008 /// Emit the RTTI descriptors for the builtin types.
1009 void EmitFundamentalRTTIDescriptors();
1011 /// \brief Appends Opts to the "Linker Options" metadata value.
1012 void AppendLinkerOptions(StringRef Opts);
1014 /// \brief Appends a detect mismatch command to the linker options.
1015 void AddDetectMismatch(StringRef Name, StringRef Value);
1017 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1018 void AddDependentLib(StringRef Lib);
1020 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1022 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1023 F->setLinkage(getFunctionLinkage(GD));
1026 /// Set the DLL storage class on F.
1027 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1029 /// Return the appropriate linkage for the vtable, VTT, and type information
1030 /// of the given class.
1031 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1033 /// Return the store size, in character units, of the given LLVM type.
1034 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1036 /// Returns LLVM linkage for a declarator.
1037 llvm::GlobalValue::LinkageTypes
1038 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1039 bool IsConstantVariable);
1041 /// Returns LLVM linkage for a declarator.
1042 llvm::GlobalValue::LinkageTypes
1043 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1045 /// Emit all the global annotations.
1046 void EmitGlobalAnnotations();
1048 /// Emit an annotation string.
1049 llvm::Constant *EmitAnnotationString(StringRef Str);
1051 /// Emit the annotation's translation unit.
1052 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1054 /// Emit the annotation line number.
1055 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1057 /// Generate the llvm::ConstantStruct which contains the annotation
1058 /// information for a given GlobalValue. The annotation struct is
1059 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1060 /// GlobalValue being annotated. The second field is the constant string
1061 /// created from the AnnotateAttr's annotation. The third field is a constant
1062 /// string containing the name of the translation unit. The fourth field is
1063 /// the line number in the file of the annotated value declaration.
1064 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1065 const AnnotateAttr *AA,
1068 /// Add global annotations that are set on D, for the global GV. Those
1069 /// annotations are emitted during finalization of the LLVM code.
1070 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1072 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1074 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1076 StringRef Category = StringRef()) const;
1078 SanitizerMetadata *getSanitizerMetadata() {
1079 return SanitizerMD.get();
1082 void addDeferredVTable(const CXXRecordDecl *RD) {
1083 DeferredVTables.push_back(RD);
1086 /// Emit code for a singal global function or var decl. Forward declarations
1087 /// are emitted lazily.
1088 void EmitGlobal(GlobalDecl D);
1090 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1092 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1094 /// Set attributes for a global definition.
1095 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1098 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1100 /// Set attributes which are common to any form of a global definition (alias,
1101 /// Objective-C method, function, global variable).
1103 /// NOTE: This should only be called for definitions.
1104 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1106 /// Set attributes which must be preserved by an alias. This includes common
1107 /// attributes (i.e. it includes a call to SetCommonAttributes).
1109 /// NOTE: This should only be called for definitions.
1110 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1112 void addReplacement(StringRef Name, llvm::Constant *C);
1114 /// \brief Emit a code for threadprivate directive.
1115 /// \param D Threadprivate declaration.
1116 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1118 /// Emit bit set entries for the given vtable using the given layout if
1119 /// vptr CFI is enabled.
1120 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1121 const VTableLayout &VTLayout);
1123 /// Create a bitset entry for the given vtable.
1124 llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
1126 const CXXRecordDecl *RD);
1128 /// \breif Get the declaration of std::terminate for the platform.
1129 llvm::Constant *getTerminateFn();
1133 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1134 bool ForVTable, bool DontDefer = false,
1135 bool IsThunk = false,
1136 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1138 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1139 llvm::PointerType *PTy,
1142 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1144 /// Set function attributes for a function declaration.
1145 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1146 bool IsIncompleteFunction, bool IsThunk);
1148 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1150 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1151 void EmitGlobalVarDefinition(const VarDecl *D);
1152 void EmitAliasDefinition(GlobalDecl GD);
1153 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1154 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1156 // C++ related functions.
1158 void EmitNamespace(const NamespaceDecl *D);
1159 void EmitLinkageSpec(const LinkageSpecDecl *D);
1160 void CompleteDIClassType(const CXXMethodDecl* D);
1162 /// \brief Emit the function that initializes C++ thread_local variables.
1163 void EmitCXXThreadLocalInitFunc();
1165 /// Emit the function that initializes C++ globals.
1166 void EmitCXXGlobalInitFunc();
1168 /// Emit the function that destroys C++ globals.
1169 void EmitCXXGlobalDtorFunc();
1171 /// Emit the function that initializes the specified global (if PerformInit is
1172 /// true) and registers its destructor.
1173 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1174 llvm::GlobalVariable *Addr,
1177 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1178 llvm::Function *InitFunc, InitSegAttr *ISA);
1180 // FIXME: Hardcoding priority here is gross.
1181 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1182 llvm::Constant *AssociatedData = 0);
1183 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1185 /// Generates a global array of functions and priorities using the given list
1186 /// and name. This array will have appending linkage and is suitable for use
1187 /// as a LLVM constructor or destructor array.
1188 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1190 /// Emit the RTTI descriptors for the given type.
1191 void EmitFundamentalRTTIDescriptor(QualType Type);
1193 /// Emit any needed decls for which code generation was deferred.
1194 void EmitDeferred();
1196 /// Call replaceAllUsesWith on all pairs in Replacements.
1197 void applyReplacements();
1199 void checkAliases();
1201 /// Emit any vtables which we deferred and still have a use for.
1202 void EmitDeferredVTables();
1204 /// Emit the llvm.used and llvm.compiler.used metadata.
1205 void emitLLVMUsed();
1207 /// \brief Emit the link options introduced by imported modules.
1208 void EmitModuleLinkOptions();
1210 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1211 /// linkage specifications, giving them the "expected" name where possible.
1212 void EmitStaticExternCAliases();
1214 void EmitDeclMetadata();
1216 /// \brief Emit the Clang version as llvm.ident metadata.
1217 void EmitVersionIdentMetadata();
1219 /// Emits target specific Metadata for global declarations.
1220 void EmitTargetMetadata();
1222 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1223 /// .gcda files in a way that persists in .bc files.
1224 void EmitCoverageFile();
1226 /// Emits the initializer for a uuidof string.
1227 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1229 /// Determine whether the definition must be emitted; if this returns \c
1230 /// false, the definition can be emitted lazily if it's used.
1231 bool MustBeEmitted(const ValueDecl *D);
1233 /// Determine whether the definition can be emitted eagerly, or should be
1234 /// delayed until the end of the translation unit. This is relevant for
1235 /// definitions whose linkage can change, e.g. implicit function instantions
1236 /// which may later be explicitly instantiated.
1237 bool MayBeEmittedEagerly(const ValueDecl *D);
1239 /// Check whether we can use a "simpler", more core exceptions personality
1241 void SimplifyPersonality();
1243 } // end namespace CodeGen
1244 } // end namespace clang