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 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 CodeGenTypeCache {
115 /// i8, i16, i32, and i64
116 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
118 llvm::Type *FloatTy, *DoubleTy;
121 llvm::IntegerType *IntTy;
123 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
125 llvm::IntegerType *IntPtrTy;
126 llvm::IntegerType *SizeTy;
127 llvm::IntegerType *PtrDiffTy;
130 /// void* in address space 0
132 llvm::PointerType *VoidPtrTy;
133 llvm::PointerType *Int8PtrTy;
136 /// void** in address space 0
138 llvm::PointerType *VoidPtrPtrTy;
139 llvm::PointerType *Int8PtrPtrTy;
142 /// The width of a pointer into the generic address space.
143 unsigned char PointerWidthInBits;
145 /// The size and alignment of a pointer into the generic address
148 unsigned char PointerAlignInBytes;
149 unsigned char PointerSizeInBytes;
150 unsigned char SizeSizeInBytes; // sizeof(size_t)
153 llvm::CallingConv::ID RuntimeCC;
154 llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
155 llvm::CallingConv::ID BuiltinCC;
156 llvm::CallingConv::ID getBuiltinCC() const { return BuiltinCC; }
159 struct RREntrypoints {
160 RREntrypoints() { memset(this, 0, sizeof(*this)); }
161 /// void objc_autoreleasePoolPop(void*);
162 llvm::Constant *objc_autoreleasePoolPop;
164 /// void *objc_autoreleasePoolPush(void);
165 llvm::Constant *objc_autoreleasePoolPush;
168 struct ARCEntrypoints {
169 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
171 /// id objc_autorelease(id);
172 llvm::Constant *objc_autorelease;
174 /// id objc_autoreleaseReturnValue(id);
175 llvm::Constant *objc_autoreleaseReturnValue;
177 /// void objc_copyWeak(id *dest, id *src);
178 llvm::Constant *objc_copyWeak;
180 /// void objc_destroyWeak(id*);
181 llvm::Constant *objc_destroyWeak;
183 /// id objc_initWeak(id*, id);
184 llvm::Constant *objc_initWeak;
186 /// id objc_loadWeak(id*);
187 llvm::Constant *objc_loadWeak;
189 /// id objc_loadWeakRetained(id*);
190 llvm::Constant *objc_loadWeakRetained;
192 /// void objc_moveWeak(id *dest, id *src);
193 llvm::Constant *objc_moveWeak;
195 /// id objc_retain(id);
196 llvm::Constant *objc_retain;
198 /// id objc_retainAutorelease(id);
199 llvm::Constant *objc_retainAutorelease;
201 /// id objc_retainAutoreleaseReturnValue(id);
202 llvm::Constant *objc_retainAutoreleaseReturnValue;
204 /// id objc_retainAutoreleasedReturnValue(id);
205 llvm::Constant *objc_retainAutoreleasedReturnValue;
207 /// id objc_retainBlock(id);
208 llvm::Constant *objc_retainBlock;
210 /// void objc_release(id);
211 llvm::Constant *objc_release;
213 /// id objc_storeStrong(id*, id);
214 llvm::Constant *objc_storeStrong;
216 /// id objc_storeWeak(id*, id);
217 llvm::Constant *objc_storeWeak;
219 /// A void(void) inline asm to use to mark that the return value of
220 /// a call will be immediately retain.
221 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
223 /// void clang.arc.use(...);
224 llvm::Constant *clang_arc_use;
227 /// This class records statistics on instrumentation based profiling.
228 class InstrProfStats {
229 uint32_t VisitedInMainFile;
230 uint32_t MissingInMainFile;
237 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
239 /// Record that we've visited a function and whether or not that function was
240 /// in the main source file.
241 void addVisited(bool MainFile) {
246 /// Record that a function we've visited has no profile data.
247 void addMissing(bool MainFile) {
252 /// Record that a function we've visited has mismatched profile data.
253 void addMismatched(bool MainFile) { ++Mismatched; }
254 /// Whether or not the stats we've gathered indicate any potential problems.
255 bool hasDiagnostics() { return Missing || Mismatched; }
256 /// Report potential problems we've found to \c Diags.
257 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
260 /// This class organizes the cross-function state that is used while generating
262 class CodeGenModule : public CodeGenTypeCache {
263 CodeGenModule(const CodeGenModule &) = delete;
264 void operator=(const CodeGenModule &) = delete;
268 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
269 Structor(int Priority, llvm::Constant *Initializer,
270 llvm::Constant *AssociatedData)
271 : Priority(Priority), Initializer(Initializer),
272 AssociatedData(AssociatedData) {}
274 llvm::Constant *Initializer;
275 llvm::Constant *AssociatedData;
278 typedef std::vector<Structor> CtorList;
282 const LangOptions &LangOpts;
283 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
284 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
285 const CodeGenOptions &CodeGenOpts;
286 llvm::Module &TheModule;
287 DiagnosticsEngine &Diags;
288 const TargetInfo &Target;
289 std::unique_ptr<CGCXXABI> ABI;
290 llvm::LLVMContext &VMContext;
294 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
296 // This should not be moved earlier, since its initialization depends on some
297 // of the previous reference members being already initialized and also checks
298 // if TheTargetCodeGenInfo is NULL
301 /// Holds information about C++ vtables.
302 CodeGenVTables VTables;
304 CGObjCRuntime* ObjCRuntime;
305 CGOpenCLRuntime* OpenCLRuntime;
306 CGOpenMPRuntime* OpenMPRuntime;
307 CGCUDARuntime* CUDARuntime;
308 CGDebugInfo* DebugInfo;
309 ARCEntrypoints *ARCData;
310 llvm::MDNode *NoObjCARCExceptionsMetadata;
311 RREntrypoints *RRData;
312 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
313 InstrProfStats PGOStats;
315 // A set of references that have only been seen via a weakref so far. This is
316 // used to remove the weak of the reference if we ever see a direct reference
318 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
320 /// This contains all the decls which have definitions but/ which are deferred
321 /// for emission and therefore should only be output if they are actually
322 /// used. If a decl is in this, then it is known to have not been referenced
324 std::map<StringRef, GlobalDecl> DeferredDecls;
326 /// This is a list of deferred decls which we have seen that *are* actually
327 /// referenced. These get code generated when the module is done.
328 struct DeferredGlobal {
329 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
330 llvm::TrackingVH<llvm::GlobalValue> GV;
333 std::vector<DeferredGlobal> DeferredDeclsToEmit;
334 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
335 DeferredDeclsToEmit.emplace_back(GV, GD);
338 /// List of alias we have emitted. Used to make sure that what they point to
339 /// is defined once we get to the end of the of the translation unit.
340 std::vector<GlobalDecl> Aliases;
342 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
343 ReplacementsTy Replacements;
345 /// A queue of (optional) vtables to consider emitting.
346 std::vector<const CXXRecordDecl*> DeferredVTables;
348 /// List of global values which are required to be present in the object file;
349 /// bitcast to i8*. This is used for forcing visibility of symbols which may
350 /// otherwise be optimized out.
351 std::vector<llvm::WeakVH> LLVMUsed;
352 std::vector<llvm::WeakVH> LLVMCompilerUsed;
354 /// Store the list of global constructors and their respective priorities to
355 /// be emitted when the translation unit is complete.
356 CtorList GlobalCtors;
358 /// Store the list of global destructors and their respective priorities to be
359 /// emitted when the translation unit is complete.
360 CtorList GlobalDtors;
362 /// An ordered map of canonical GlobalDecls to their mangled names.
363 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
364 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
366 /// Global annotations.
367 std::vector<llvm::Constant*> Annotations;
369 /// Map used to get unique annotation strings.
370 llvm::StringMap<llvm::Constant*> AnnotationStrings;
372 llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
374 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
375 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
376 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
377 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
379 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
380 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
382 /// Map used to get unique type descriptor constants for sanitizers.
383 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
385 /// Map used to track internal linkage functions declared within
386 /// extern "C" regions.
387 typedef llvm::MapVector<IdentifierInfo *,
388 llvm::GlobalValue *> StaticExternCMap;
389 StaticExternCMap StaticExternCValues;
391 /// \brief thread_local variables defined or used in this TU.
392 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
395 /// \brief thread_local variables with initializers that need to run
396 /// before any thread_local variable in this TU is odr-used.
397 std::vector<llvm::Function *> CXXThreadLocalInits;
398 std::vector<llvm::GlobalVariable *> CXXThreadLocalInitVars;
400 /// Global variables with initializers that need to run before main.
401 std::vector<llvm::Function *> CXXGlobalInits;
403 /// When a C++ decl with an initializer is deferred, null is
404 /// appended to CXXGlobalInits, and the index of that null is placed
405 /// here so that the initializer will be performed in the correct
406 /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
407 /// that we don't re-emit the initializer.
408 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
410 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
412 struct GlobalInitPriorityCmp {
413 bool operator()(const GlobalInitData &LHS,
414 const GlobalInitData &RHS) const {
415 return LHS.first.priority < RHS.first.priority;
419 /// Global variables with initializers whose order of initialization is set by
420 /// init_priority attribute.
421 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
423 /// Global destructor functions and arguments that need to run on termination.
424 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
426 /// \brief The complete set of modules that has been imported.
427 llvm::SetVector<clang::Module *> ImportedModules;
429 /// \brief A vector of metadata strings.
430 SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
432 /// @name Cache for Objective-C runtime types
435 /// Cached reference to the class for constant strings. This value has type
436 /// int * but is actually an Obj-C class pointer.
437 llvm::WeakVH CFConstantStringClassRef;
439 /// Cached reference to the class for constant strings. This value has type
440 /// int * but is actually an Obj-C class pointer.
441 llvm::WeakVH ConstantStringClassRef;
443 /// \brief The LLVM type corresponding to NSConstantString.
444 llvm::StructType *NSConstantStringType;
446 /// \brief The type used to describe the state of a fast enumeration in
447 /// Objective-C's for..in loop.
448 QualType ObjCFastEnumerationStateType;
452 /// Lazily create the Objective-C runtime
453 void createObjCRuntime();
455 void createOpenCLRuntime();
456 void createOpenMPRuntime();
457 void createCUDARuntime();
459 bool isTriviallyRecursive(const FunctionDecl *F);
460 bool shouldEmitFunction(GlobalDecl GD);
462 /// @name Cache for Blocks Runtime Globals
465 llvm::Constant *NSConcreteGlobalBlock;
466 llvm::Constant *NSConcreteStackBlock;
468 llvm::Constant *BlockObjectAssign;
469 llvm::Constant *BlockObjectDispose;
471 llvm::Type *BlockDescriptorType;
472 llvm::Type *GenericBlockLiteralType;
475 int GlobalUniqueCount;
478 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
479 llvm::Constant *LifetimeStartFn;
481 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
482 llvm::Constant *LifetimeEndFn;
484 GlobalDecl initializedGlobalDecl;
486 std::unique_ptr<SanitizerMetadata> SanitizerMD;
490 llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
492 std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
494 CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
495 const PreprocessorOptions &ppopts,
496 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
497 DiagnosticsEngine &Diags,
498 CoverageSourceInfo *CoverageInfo = nullptr);
504 /// Finalize LLVM code generation.
507 /// Return a reference to the configured Objective-C runtime.
508 CGObjCRuntime &getObjCRuntime() {
509 if (!ObjCRuntime) createObjCRuntime();
513 /// Return true iff an Objective-C runtime has been configured.
514 bool hasObjCRuntime() { return !!ObjCRuntime; }
516 /// Return a reference to the configured OpenCL runtime.
517 CGOpenCLRuntime &getOpenCLRuntime() {
518 assert(OpenCLRuntime != nullptr);
519 return *OpenCLRuntime;
522 /// Return a reference to the configured OpenMP runtime.
523 CGOpenMPRuntime &getOpenMPRuntime() {
524 assert(OpenMPRuntime != nullptr);
525 return *OpenMPRuntime;
528 /// Return a reference to the configured CUDA runtime.
529 CGCUDARuntime &getCUDARuntime() {
530 assert(CUDARuntime != nullptr);
534 ARCEntrypoints &getARCEntrypoints() const {
535 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
539 RREntrypoints &getRREntrypoints() const {
540 assert(RRData != nullptr);
544 InstrProfStats &getPGOStats() { return PGOStats; }
545 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
547 CoverageMappingModuleGen *getCoverageMapping() const {
548 return CoverageMapping.get();
551 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
552 return StaticLocalDeclMap[D];
554 void setStaticLocalDeclAddress(const VarDecl *D,
556 StaticLocalDeclMap[D] = C;
560 getOrCreateStaticVarDecl(const VarDecl &D,
561 llvm::GlobalValue::LinkageTypes Linkage);
563 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
564 return StaticLocalDeclGuardMap[D];
566 void setStaticLocalDeclGuardAddress(const VarDecl *D,
567 llvm::GlobalVariable *C) {
568 StaticLocalDeclGuardMap[D] = C;
571 bool lookupRepresentativeDecl(StringRef MangledName,
572 GlobalDecl &Result) const;
574 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
575 return AtomicSetterHelperFnMap[Ty];
577 void setAtomicSetterHelperFnMap(QualType Ty,
578 llvm::Constant *Fn) {
579 AtomicSetterHelperFnMap[Ty] = Fn;
582 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
583 return AtomicGetterHelperFnMap[Ty];
585 void setAtomicGetterHelperFnMap(QualType Ty,
586 llvm::Constant *Fn) {
587 AtomicGetterHelperFnMap[Ty] = Fn;
590 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
591 return TypeDescriptorMap[Ty];
593 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
594 TypeDescriptorMap[Ty] = C;
597 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
599 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
600 if (!NoObjCARCExceptionsMetadata)
601 NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
602 return NoObjCARCExceptionsMetadata;
605 ASTContext &getContext() const { return Context; }
606 const LangOptions &getLangOpts() const { return LangOpts; }
607 const HeaderSearchOptions &getHeaderSearchOpts()
608 const { return HeaderSearchOpts; }
609 const PreprocessorOptions &getPreprocessorOpts()
610 const { return PreprocessorOpts; }
611 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
612 llvm::Module &getModule() const { return TheModule; }
613 DiagnosticsEngine &getDiags() const { return Diags; }
614 const llvm::DataLayout &getDataLayout() const {
615 return TheModule.getDataLayout();
617 const TargetInfo &getTarget() const { return Target; }
618 const llvm::Triple &getTriple() const;
619 bool supportsCOMDAT() const;
620 void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
622 CGCXXABI &getCXXABI() const { return *ABI; }
623 llvm::LLVMContext &getLLVMContext() { return VMContext; }
625 bool shouldUseTBAA() const { return TBAA != nullptr; }
627 const TargetCodeGenInfo &getTargetCodeGenInfo();
629 CodeGenTypes &getTypes() { return Types; }
631 CodeGenVTables &getVTables() { return VTables; }
633 ItaniumVTableContext &getItaniumVTableContext() {
634 return VTables.getItaniumVTableContext();
637 MicrosoftVTableContext &getMicrosoftVTableContext() {
638 return VTables.getMicrosoftVTableContext();
641 CtorList &getGlobalCtors() { return GlobalCtors; }
642 CtorList &getGlobalDtors() { return GlobalDtors; }
644 llvm::MDNode *getTBAAInfo(QualType QTy);
645 llvm::MDNode *getTBAAInfoForVTablePtr();
646 llvm::MDNode *getTBAAStructInfo(QualType QTy);
647 /// Return the MDNode in the type DAG for the given struct type.
648 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
649 /// Return the path-aware tag for given base type, access node and offset.
650 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
653 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
655 bool isPaddedAtomicType(QualType type);
656 bool isPaddedAtomicType(const AtomicType *type);
658 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
659 /// is the same as the type. For struct-path aware TBAA, the tag
660 /// is different from the type: base type, access type and offset.
661 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
662 void DecorateInstruction(llvm::Instruction *Inst,
663 llvm::MDNode *TBAAInfo,
664 bool ConvertTypeToTag = true);
666 /// Emit the given number of characters as a value of type size_t.
667 llvm::ConstantInt *getSize(CharUnits numChars);
669 /// Set the visibility for the given LLVM GlobalValue.
670 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
672 /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
673 /// variable declaration D.
674 void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
676 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
678 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
679 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
680 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
682 llvm_unreachable("unknown visibility!");
685 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
686 if (isa<CXXConstructorDecl>(GD.getDecl()))
687 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
688 getFromCtorType(GD.getCtorType()));
689 else if (isa<CXXDestructorDecl>(GD.getDecl()))
690 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
691 getFromDtorType(GD.getDtorType()));
692 else if (isa<FunctionDecl>(GD.getDecl()))
693 return GetAddrOfFunction(GD);
695 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
698 /// Will return a global variable of the given type. If a variable with a
699 /// different type already exists then a new variable with the right type
700 /// will be created and all uses of the old variable will be replaced with a
701 /// bitcast to the new variable.
702 llvm::GlobalVariable *
703 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
704 llvm::GlobalValue::LinkageTypes Linkage);
707 CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
708 SourceLocation Loc = SourceLocation(),
711 /// Return the address space of the underlying global variable for D, as
712 /// determined by its declaration. Normally this is the same as the address
713 /// space of D's type, but in CUDA, address spaces are associated with
714 /// declarations, not types.
715 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
717 /// Return the llvm::Constant for the address of the given global variable.
718 /// If Ty is non-null and if the global doesn't exist, then it will be greated
719 /// with the specified type instead of whatever the normal requested type
721 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
722 llvm::Type *Ty = nullptr);
724 /// Return the address of the given function. If Ty is non-null, then this
725 /// function will use the specified type if it has to create it.
726 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
727 bool ForVTable = false,
728 bool DontDefer = false);
730 /// Get the address of the RTTI descriptor for the given type.
731 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
733 llvm::Constant *getAddrOfCXXCatchHandlerType(QualType Ty,
734 QualType CatchHandlerType);
736 /// Get the address of a uuid descriptor .
737 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
739 /// Get the address of the thunk for the given global decl.
740 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
742 /// Get a reference to the target of VD.
743 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
746 computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
747 CastExpr::path_const_iterator Start,
748 CastExpr::path_const_iterator End);
750 /// Returns the offset from a derived class to a class. Returns null if the
753 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
754 CastExpr::path_const_iterator PathBegin,
755 CastExpr::path_const_iterator PathEnd);
757 /// A pair of helper functions for a __block variable.
758 class ByrefHelpers : public llvm::FoldingSetNode {
760 llvm::Constant *CopyHelper;
761 llvm::Constant *DisposeHelper;
763 /// The alignment of the field. This is important because
764 /// different offsets to the field within the byref struct need to
765 /// have different helper functions.
768 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
769 virtual ~ByrefHelpers();
771 void Profile(llvm::FoldingSetNodeID &id) const {
772 id.AddInteger(Alignment.getQuantity());
775 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
777 virtual bool needsCopy() const { return true; }
778 virtual void emitCopy(CodeGenFunction &CGF,
779 llvm::Value *dest, llvm::Value *src) = 0;
781 virtual bool needsDispose() const { return true; }
782 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
785 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
787 /// Fetches the global unique block count.
788 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
790 /// Fetches the type of a generic block descriptor.
791 llvm::Type *getBlockDescriptorType();
793 /// The type of a generic block literal.
794 llvm::Type *getGenericBlockLiteralType();
796 /// Gets the address of a block which requires no captures.
797 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
799 /// Return a pointer to a constant CFString object for the given string.
800 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
802 /// Return a pointer to a constant NSString object for the given string. Or a
803 /// user defined String object as defined via
804 /// -fconstant-string-class=class_name option.
805 llvm::GlobalVariable *GetAddrOfConstantString(const StringLiteral *Literal);
807 /// Return a constant array for the given string.
808 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
810 /// Return a pointer to a constant array for the given string literal.
811 llvm::GlobalVariable *
812 GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
813 StringRef Name = ".str");
815 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
816 llvm::GlobalVariable *
817 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
819 /// Returns a pointer to a character array containing the literal and a
820 /// terminating '\0' character. The result has pointer to array type.
822 /// \param GlobalName If provided, the name to use for the global (if one is
824 llvm::GlobalVariable *
825 GetAddrOfConstantCString(const std::string &Str,
826 const char *GlobalName = nullptr,
827 unsigned Alignment = 0);
829 /// Returns a pointer to a constant global variable for the given file-scope
830 /// compound literal expression.
831 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
833 /// \brief Returns a pointer to a global variable representing a temporary
834 /// with static or thread storage duration.
835 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
838 /// \brief Retrieve the record type that describes the state of an
839 /// Objective-C fast enumeration loop (for..in).
840 QualType getObjCFastEnumerationStateType();
842 // Produce code for this constructor/destructor. This method doesn't try
843 // to apply any ABI rules about which other constructors/destructors
844 // are needed or if they are alias to each other.
845 llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
848 /// Return the address of the constructor/destructor of the given type.
850 getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
851 const CGFunctionInfo *FnInfo = nullptr,
852 llvm::FunctionType *FnType = nullptr,
853 bool DontDefer = false);
855 /// Given a builtin id for a function like "__builtin_fabsf", return a
856 /// Function* for "fabsf".
857 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
860 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
862 /// Emit code for a single top level declaration.
863 void EmitTopLevelDecl(Decl *D);
865 /// \brief Stored a deferred empty coverage mapping for an unused
866 /// and thus uninstrumented top level declaration.
867 void AddDeferredUnusedCoverageMapping(Decl *D);
869 /// \brief Remove the deferred empty coverage mapping as this
870 /// declaration is actually instrumented.
871 void ClearUnusedCoverageMapping(const Decl *D);
873 /// \brief Emit all the deferred coverage mappings
874 /// for the uninstrumented functions.
875 void EmitDeferredUnusedCoverageMappings();
877 /// Tell the consumer that this variable has been instantiated.
878 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
880 /// \brief If the declaration has internal linkage but is inside an
881 /// extern "C" linkage specification, prepare to emit an alias for it
882 /// to the expected name.
883 template<typename SomeDecl>
884 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
886 /// Add a global to a list to be added to the llvm.used metadata.
887 void addUsedGlobal(llvm::GlobalValue *GV);
889 /// Add a global to a list to be added to the llvm.compiler.used metadata.
890 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
892 /// Add a destructor and object to add to the C++ global destructor function.
893 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
894 CXXGlobalDtors.emplace_back(DtorFn, Object);
897 /// Create a new runtime function with the specified type and name.
898 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
900 llvm::AttributeSet ExtraAttrs =
901 llvm::AttributeSet());
902 /// Create a new compiler builtin function with the specified type and name.
903 llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
905 llvm::AttributeSet ExtraAttrs =
906 llvm::AttributeSet());
907 /// Create a new runtime global variable with the specified type and name.
908 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
911 ///@name Custom Blocks Runtime Interfaces
914 llvm::Constant *getNSConcreteGlobalBlock();
915 llvm::Constant *getNSConcreteStackBlock();
916 llvm::Constant *getBlockObjectAssign();
917 llvm::Constant *getBlockObjectDispose();
921 llvm::Constant *getLLVMLifetimeStartFn();
922 llvm::Constant *getLLVMLifetimeEndFn();
924 // Make sure that this type is translated.
925 void UpdateCompletedType(const TagDecl *TD);
927 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
929 /// Try to emit the initializer for the given declaration as a constant;
930 /// returns 0 if the expression cannot be emitted as a constant.
931 llvm::Constant *EmitConstantInit(const VarDecl &D,
932 CodeGenFunction *CGF = nullptr);
934 /// Try to emit the given expression as a constant; returns 0 if the
935 /// expression cannot be emitted as a constant.
936 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
937 CodeGenFunction *CGF = nullptr);
939 /// Emit the given constant value as a constant, in the type's scalar
941 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
942 CodeGenFunction *CGF = nullptr);
944 /// Emit the given constant value as a constant, in the type's memory
946 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
948 CodeGenFunction *CGF = nullptr);
950 /// Return the result of value-initializing the given type, i.e. a null
951 /// expression of the given type. This is usually, but not always, an LLVM
953 llvm::Constant *EmitNullConstant(QualType T);
955 /// Return a null constant appropriate for zero-initializing a base class with
956 /// the given type. This is usually, but not always, an LLVM null constant.
957 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
959 /// Emit a general error that something can't be done.
960 void Error(SourceLocation loc, StringRef error);
962 /// Print out an error that codegen doesn't support the specified stmt yet.
963 void ErrorUnsupported(const Stmt *S, const char *Type);
965 /// Print out an error that codegen doesn't support the specified decl yet.
966 void ErrorUnsupported(const Decl *D, const char *Type);
968 /// Set the attributes on the LLVM function for the given decl and function
969 /// info. This applies attributes necessary for handling the ABI as well as
970 /// user specified attributes like section.
971 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
972 const CGFunctionInfo &FI);
974 /// Set the LLVM function attributes (sext, zext, etc).
975 void SetLLVMFunctionAttributes(const Decl *D,
976 const CGFunctionInfo &Info,
979 /// Set the LLVM function attributes which only apply to a function
981 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
983 /// Return true iff the given type uses 'sret' when used as a return type.
984 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
986 /// Return true iff the given type uses an argument slot when 'sret' is used
987 /// as a return type.
988 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
990 /// Return true iff the given type uses 'fpret' when used as a return type.
991 bool ReturnTypeUsesFPRet(QualType ResultType);
993 /// Return true iff the given type uses 'fp2ret' when used as a return type.
994 bool ReturnTypeUsesFP2Ret(QualType ResultType);
996 /// Get the LLVM attributes and calling convention to use for a particular
999 /// \param Info - The function type information.
1000 /// \param TargetDecl - The decl these attributes are being constructed
1001 /// for. If supplied the attributes applied to this decl may contribute to the
1002 /// function attributes and calling convention.
1003 /// \param PAL [out] - On return, the attribute list to use.
1004 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1005 void ConstructAttributeList(const CGFunctionInfo &Info,
1006 const Decl *TargetDecl,
1007 AttributeListType &PAL,
1008 unsigned &CallingConv,
1009 bool AttrOnCallSite);
1011 StringRef getMangledName(GlobalDecl GD);
1012 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1014 void EmitTentativeDefinition(const VarDecl *D);
1016 void EmitVTable(CXXRecordDecl *Class);
1018 /// Emit the RTTI descriptors for the builtin types.
1019 void EmitFundamentalRTTIDescriptors();
1021 /// \brief Appends Opts to the "Linker Options" metadata value.
1022 void AppendLinkerOptions(StringRef Opts);
1024 /// \brief Appends a detect mismatch command to the linker options.
1025 void AddDetectMismatch(StringRef Name, StringRef Value);
1027 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
1028 void AddDependentLib(StringRef Lib);
1030 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1032 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1033 F->setLinkage(getFunctionLinkage(GD));
1036 /// Set the DLL storage class on F.
1037 void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
1039 /// Return the appropriate linkage for the vtable, VTT, and type information
1040 /// of the given class.
1041 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1043 /// Return the store size, in character units, of the given LLVM type.
1044 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1046 /// Returns LLVM linkage for a declarator.
1047 llvm::GlobalValue::LinkageTypes
1048 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1049 bool IsConstantVariable);
1051 /// Returns LLVM linkage for a declarator.
1052 llvm::GlobalValue::LinkageTypes
1053 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1055 /// Emit all the global annotations.
1056 void EmitGlobalAnnotations();
1058 /// Emit an annotation string.
1059 llvm::Constant *EmitAnnotationString(StringRef Str);
1061 /// Emit the annotation's translation unit.
1062 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1064 /// Emit the annotation line number.
1065 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1067 /// Generate the llvm::ConstantStruct which contains the annotation
1068 /// information for a given GlobalValue. The annotation struct is
1069 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1070 /// GlobalValue being annotated. The second field is the constant string
1071 /// created from the AnnotateAttr's annotation. The third field is a constant
1072 /// string containing the name of the translation unit. The fourth field is
1073 /// the line number in the file of the annotated value declaration.
1074 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1075 const AnnotateAttr *AA,
1078 /// Add global annotations that are set on D, for the global GV. Those
1079 /// annotations are emitted during finalization of the LLVM code.
1080 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1082 bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
1084 bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1086 StringRef Category = StringRef()) const;
1088 SanitizerMetadata *getSanitizerMetadata() {
1089 return SanitizerMD.get();
1092 void addDeferredVTable(const CXXRecordDecl *RD) {
1093 DeferredVTables.push_back(RD);
1096 /// Emit code for a singal global function or var decl. Forward declarations
1097 /// are emitted lazily.
1098 void EmitGlobal(GlobalDecl D);
1100 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1102 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1104 /// Set attributes for a global definition.
1105 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1108 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1110 /// Set attributes which are common to any form of a global definition (alias,
1111 /// Objective-C method, function, global variable).
1113 /// NOTE: This should only be called for definitions.
1114 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1116 /// Set attributes which must be preserved by an alias. This includes common
1117 /// attributes (i.e. it includes a call to SetCommonAttributes).
1119 /// NOTE: This should only be called for definitions.
1120 void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
1122 void addReplacement(StringRef Name, llvm::Constant *C);
1124 /// \brief Emit a code for threadprivate directive.
1125 /// \param D Threadprivate declaration.
1126 void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1128 /// Returns whether the given record is blacklisted from control flow
1129 /// integrity checks.
1130 bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
1132 /// Emit bit set entries for the given vtable using the given layout if
1133 /// vptr CFI is enabled.
1134 void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
1135 const VTableLayout &VTLayout);
1137 /// Create a bitset entry for the given vtable.
1138 llvm::MDTuple *CreateVTableBitSetEntry(llvm::GlobalVariable *VTable,
1140 const CXXRecordDecl *RD);
1142 /// \breif Get the declaration of std::terminate for the platform.
1143 llvm::Constant *getTerminateFn();
1147 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1148 bool ForVTable, bool DontDefer = false,
1149 bool IsThunk = false,
1150 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1152 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1153 llvm::PointerType *PTy,
1156 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1158 /// Set function attributes for a function declaration.
1159 void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1160 bool IsIncompleteFunction, bool IsThunk);
1162 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1164 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1165 void EmitGlobalVarDefinition(const VarDecl *D);
1166 void EmitAliasDefinition(GlobalDecl GD);
1167 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1168 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1170 // C++ related functions.
1172 void EmitNamespace(const NamespaceDecl *D);
1173 void EmitLinkageSpec(const LinkageSpecDecl *D);
1174 void CompleteDIClassType(const CXXMethodDecl* D);
1176 /// \brief Emit the function that initializes C++ thread_local variables.
1177 void EmitCXXThreadLocalInitFunc();
1179 /// Emit the function that initializes C++ globals.
1180 void EmitCXXGlobalInitFunc();
1182 /// Emit the function that destroys C++ globals.
1183 void EmitCXXGlobalDtorFunc();
1185 /// Emit the function that initializes the specified global (if PerformInit is
1186 /// true) and registers its destructor.
1187 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1188 llvm::GlobalVariable *Addr,
1191 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1192 llvm::Function *InitFunc, InitSegAttr *ISA);
1194 // FIXME: Hardcoding priority here is gross.
1195 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1196 llvm::Constant *AssociatedData = 0);
1197 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1199 /// Generates a global array of functions and priorities using the given list
1200 /// and name. This array will have appending linkage and is suitable for use
1201 /// as a LLVM constructor or destructor array.
1202 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1204 /// Emit the RTTI descriptors for the given type.
1205 void EmitFundamentalRTTIDescriptor(QualType Type);
1207 /// Emit any needed decls for which code generation was deferred.
1208 void EmitDeferred();
1210 /// Call replaceAllUsesWith on all pairs in Replacements.
1211 void applyReplacements();
1213 void checkAliases();
1215 /// Emit any vtables which we deferred and still have a use for.
1216 void EmitDeferredVTables();
1218 /// Emit the llvm.used and llvm.compiler.used metadata.
1219 void emitLLVMUsed();
1221 /// \brief Emit the link options introduced by imported modules.
1222 void EmitModuleLinkOptions();
1224 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1225 /// linkage specifications, giving them the "expected" name where possible.
1226 void EmitStaticExternCAliases();
1228 void EmitDeclMetadata();
1230 /// \brief Emit the Clang version as llvm.ident metadata.
1231 void EmitVersionIdentMetadata();
1233 /// Emits target specific Metadata for global declarations.
1234 void EmitTargetMetadata();
1236 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1237 /// .gcda files in a way that persists in .bc files.
1238 void EmitCoverageFile();
1240 /// Emits the initializer for a uuidof string.
1241 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1243 /// Determine whether the definition must be emitted; if this returns \c
1244 /// false, the definition can be emitted lazily if it's used.
1245 bool MustBeEmitted(const ValueDecl *D);
1247 /// Determine whether the definition can be emitted eagerly, or should be
1248 /// delayed until the end of the translation unit. This is relevant for
1249 /// definitions whose linkage can change, e.g. implicit function instantions
1250 /// which may later be explicitly instantiated.
1251 bool MayBeEmittedEagerly(const ValueDecl *D);
1253 /// Check whether we can use a "simpler", more core exceptions personality
1255 void SimplifyPersonality();
1257 } // end namespace CodeGen
1258 } // end namespace clang