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 CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
17 #include "CGVTables.h"
18 #include "CodeGenTypes.h"
19 #include "SanitizerBlacklist.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 "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueHandle.h"
45 class IndexedInstrProfReader;
49 class TargetCodeGenInfo;
55 class ObjCImplementationDecl;
56 class ObjCCategoryImplDecl;
57 class ObjCProtocolDecl;
71 class DiagnosticsEngine;
73 class CXXDestructorDecl;
79 class CodeGenFunction;
84 class CGOpenCLRuntime;
85 class CGOpenMPRuntime;
87 class BlockFieldFlags;
88 class FunctionArgList;
90 struct OrderGlobalInits {
91 unsigned int priority;
92 unsigned int lex_order;
93 OrderGlobalInits(unsigned int p, unsigned int l)
94 : priority(p), lex_order(l) {}
96 bool operator==(const OrderGlobalInits &RHS) const {
97 return priority == RHS.priority && lex_order == RHS.lex_order;
100 bool operator<(const OrderGlobalInits &RHS) const {
101 return std::tie(priority, lex_order) <
102 std::tie(RHS.priority, RHS.lex_order);
106 struct CodeGenTypeCache {
110 /// i8, i16, i32, and i64
111 llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
113 llvm::Type *FloatTy, *DoubleTy;
116 llvm::IntegerType *IntTy;
118 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
120 llvm::IntegerType *IntPtrTy;
121 llvm::IntegerType *SizeTy;
122 llvm::IntegerType *PtrDiffTy;
125 /// void* in address space 0
127 llvm::PointerType *VoidPtrTy;
128 llvm::PointerType *Int8PtrTy;
131 /// void** in address space 0
133 llvm::PointerType *VoidPtrPtrTy;
134 llvm::PointerType *Int8PtrPtrTy;
137 /// The width of a pointer into the generic address space.
138 unsigned char PointerWidthInBits;
140 /// The size and alignment of a pointer into the generic address
143 unsigned char PointerAlignInBytes;
144 unsigned char PointerSizeInBytes;
145 unsigned char SizeSizeInBytes; // sizeof(size_t)
148 llvm::CallingConv::ID RuntimeCC;
149 llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
152 struct RREntrypoints {
153 RREntrypoints() { memset(this, 0, sizeof(*this)); }
154 /// void objc_autoreleasePoolPop(void*);
155 llvm::Constant *objc_autoreleasePoolPop;
157 /// void *objc_autoreleasePoolPush(void);
158 llvm::Constant *objc_autoreleasePoolPush;
161 struct ARCEntrypoints {
162 ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
164 /// id objc_autorelease(id);
165 llvm::Constant *objc_autorelease;
167 /// id objc_autoreleaseReturnValue(id);
168 llvm::Constant *objc_autoreleaseReturnValue;
170 /// void objc_copyWeak(id *dest, id *src);
171 llvm::Constant *objc_copyWeak;
173 /// void objc_destroyWeak(id*);
174 llvm::Constant *objc_destroyWeak;
176 /// id objc_initWeak(id*, id);
177 llvm::Constant *objc_initWeak;
179 /// id objc_loadWeak(id*);
180 llvm::Constant *objc_loadWeak;
182 /// id objc_loadWeakRetained(id*);
183 llvm::Constant *objc_loadWeakRetained;
185 /// void objc_moveWeak(id *dest, id *src);
186 llvm::Constant *objc_moveWeak;
188 /// id objc_retain(id);
189 llvm::Constant *objc_retain;
191 /// id objc_retainAutorelease(id);
192 llvm::Constant *objc_retainAutorelease;
194 /// id objc_retainAutoreleaseReturnValue(id);
195 llvm::Constant *objc_retainAutoreleaseReturnValue;
197 /// id objc_retainAutoreleasedReturnValue(id);
198 llvm::Constant *objc_retainAutoreleasedReturnValue;
200 /// id objc_retainBlock(id);
201 llvm::Constant *objc_retainBlock;
203 /// void objc_release(id);
204 llvm::Constant *objc_release;
206 /// id objc_storeStrong(id*, id);
207 llvm::Constant *objc_storeStrong;
209 /// id objc_storeWeak(id*, id);
210 llvm::Constant *objc_storeWeak;
212 /// A void(void) inline asm to use to mark that the return value of
213 /// a call will be immediately retain.
214 llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
216 /// void clang.arc.use(...);
217 llvm::Constant *clang_arc_use;
220 /// This class records statistics on instrumentation based profiling.
221 class InstrProfStats {
222 uint32_t VisitedInMainFile;
223 uint32_t MissingInMainFile;
230 : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
232 /// Record that we've visited a function and whether or not that function was
233 /// in the main source file.
234 void addVisited(bool MainFile) {
239 /// Record that a function we've visited has no profile data.
240 void addMissing(bool MainFile) {
245 /// Record that a function we've visited has mismatched profile data.
246 void addMismatched(bool MainFile) { ++Mismatched; }
247 /// Whether or not the stats we've gathered indicate any potential problems.
248 bool hasDiagnostics() { return Missing || Mismatched; }
249 /// Report potential problems we've found to \c Diags.
250 void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
253 /// This class organizes the cross-function state that is used while generating
255 class CodeGenModule : public CodeGenTypeCache {
256 CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
257 void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
260 Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
261 Structor(int Priority, llvm::Constant *Initializer,
262 llvm::Constant *AssociatedData)
263 : Priority(Priority), Initializer(Initializer),
264 AssociatedData(AssociatedData) {}
266 llvm::Constant *Initializer;
267 llvm::Constant *AssociatedData;
270 typedef std::vector<Structor> CtorList;
273 const LangOptions &LangOpts;
274 const CodeGenOptions &CodeGenOpts;
275 llvm::Module &TheModule;
276 DiagnosticsEngine &Diags;
277 const llvm::DataLayout &TheDataLayout;
278 const TargetInfo &Target;
279 std::unique_ptr<CGCXXABI> ABI;
280 llvm::LLVMContext &VMContext;
284 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
286 // This should not be moved earlier, since its initialization depends on some
287 // of the previous reference members being already initialized and also checks
288 // if TheTargetCodeGenInfo is NULL
291 /// Holds information about C++ vtables.
292 CodeGenVTables VTables;
294 CGObjCRuntime* ObjCRuntime;
295 CGOpenCLRuntime* OpenCLRuntime;
296 CGOpenMPRuntime* OpenMPRuntime;
297 CGCUDARuntime* CUDARuntime;
298 CGDebugInfo* DebugInfo;
299 ARCEntrypoints *ARCData;
300 llvm::MDNode *NoObjCARCExceptionsMetadata;
301 RREntrypoints *RRData;
302 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
303 InstrProfStats PGOStats;
305 // A set of references that have only been seen via a weakref so far. This is
306 // used to remove the weak of the reference if we ever see a direct reference
308 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
310 /// This contains all the decls which have definitions but/ which are deferred
311 /// for emission and therefore should only be output if they are actually
312 /// used. If a decl is in this, then it is known to have not been referenced
314 std::map<StringRef, GlobalDecl> DeferredDecls;
316 /// This is a list of deferred decls which we have seen that *are* actually
317 /// referenced. These get code generated when the module is done.
318 struct DeferredGlobal {
319 DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
320 llvm::AssertingVH<llvm::GlobalValue> GV;
323 std::vector<DeferredGlobal> DeferredDeclsToEmit;
324 void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
325 DeferredDeclsToEmit.push_back(DeferredGlobal(GV, GD));
328 /// List of alias we have emitted. Used to make sure that what they point to
329 /// is defined once we get to the end of the of the translation unit.
330 std::vector<GlobalDecl> Aliases;
332 typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
333 ReplacementsTy Replacements;
335 /// A queue of (optional) vtables to consider emitting.
336 std::vector<const CXXRecordDecl*> DeferredVTables;
338 /// List of global values which are required to be present in the object file;
339 /// bitcast to i8*. This is used for forcing visibility of symbols which may
340 /// otherwise be optimized out.
341 std::vector<llvm::WeakVH> LLVMUsed;
342 std::vector<llvm::WeakVH> LLVMCompilerUsed;
344 /// Store the list of global constructors and their respective priorities to
345 /// be emitted when the translation unit is complete.
346 CtorList GlobalCtors;
348 /// Store the list of global destructors and their respective priorities to be
349 /// emitted when the translation unit is complete.
350 CtorList GlobalDtors;
352 /// An ordered map of canonical GlobalDecls to their mangled names.
353 llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
354 llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
356 /// Global annotations.
357 std::vector<llvm::Constant*> Annotations;
359 /// Map used to get unique annotation strings.
360 llvm::StringMap<llvm::Constant*> AnnotationStrings;
362 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
364 llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
365 llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
366 llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
367 llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
369 llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
370 llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
372 /// Map used to get unique type descriptor constants for sanitizers.
373 llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
375 /// Map used to track internal linkage functions declared within
376 /// extern "C" regions.
377 typedef llvm::MapVector<IdentifierInfo *,
378 llvm::GlobalValue *> StaticExternCMap;
379 StaticExternCMap StaticExternCValues;
381 /// \brief thread_local variables defined or used in this TU.
382 std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
385 /// \brief thread_local variables with initializers that need to run
386 /// before any thread_local variable in this TU is odr-used.
387 std::vector<llvm::Constant*> CXXThreadLocalInits;
389 /// Global variables with initializers that need to run before main.
390 std::vector<llvm::Constant*> CXXGlobalInits;
392 /// When a C++ decl with an initializer is deferred, null is
393 /// appended to CXXGlobalInits, and the index of that null is placed
394 /// here so that the initializer will be performed in the correct
396 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
398 typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
400 struct GlobalInitPriorityCmp {
401 bool operator()(const GlobalInitData &LHS,
402 const GlobalInitData &RHS) const {
403 return LHS.first.priority < RHS.first.priority;
407 /// Global variables with initializers whose order of initialization is set by
408 /// init_priority attribute.
409 SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
411 /// Global destructor functions and arguments that need to run on termination.
412 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
414 /// \brief The complete set of modules that has been imported.
415 llvm::SetVector<clang::Module *> ImportedModules;
417 /// \brief A vector of metadata strings.
418 SmallVector<llvm::Value *, 16> LinkerOptionsMetadata;
420 /// @name Cache for Objective-C runtime types
423 /// Cached reference to the class for constant strings. This value has type
424 /// int * but is actually an Obj-C class pointer.
425 llvm::WeakVH CFConstantStringClassRef;
427 /// Cached reference to the class for constant strings. This value has type
428 /// int * but is actually an Obj-C class pointer.
429 llvm::WeakVH ConstantStringClassRef;
431 /// \brief The LLVM type corresponding to NSConstantString.
432 llvm::StructType *NSConstantStringType;
434 /// \brief The type used to describe the state of a fast enumeration in
435 /// Objective-C's for..in loop.
436 QualType ObjCFastEnumerationStateType;
440 /// Lazily create the Objective-C runtime
441 void createObjCRuntime();
443 void createOpenCLRuntime();
444 void createOpenMPRuntime();
445 void createCUDARuntime();
447 bool isTriviallyRecursive(const FunctionDecl *F);
448 bool shouldEmitFunction(GlobalDecl GD);
450 /// @name Cache for Blocks Runtime Globals
453 llvm::Constant *NSConcreteGlobalBlock;
454 llvm::Constant *NSConcreteStackBlock;
456 llvm::Constant *BlockObjectAssign;
457 llvm::Constant *BlockObjectDispose;
459 llvm::Type *BlockDescriptorType;
460 llvm::Type *GenericBlockLiteralType;
463 int GlobalUniqueCount;
466 /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
467 llvm::Constant *LifetimeStartFn;
469 /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
470 llvm::Constant *LifetimeEndFn;
472 GlobalDecl initializedGlobalDecl;
474 SanitizerBlacklist SanitizerBL;
478 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
479 llvm::Module &M, const llvm::DataLayout &TD,
480 DiagnosticsEngine &Diags);
486 /// Finalize LLVM code generation.
489 /// Return a reference to the configured Objective-C runtime.
490 CGObjCRuntime &getObjCRuntime() {
491 if (!ObjCRuntime) createObjCRuntime();
495 /// Return true iff an Objective-C runtime has been configured.
496 bool hasObjCRuntime() { return !!ObjCRuntime; }
498 /// Return a reference to the configured OpenCL runtime.
499 CGOpenCLRuntime &getOpenCLRuntime() {
500 assert(OpenCLRuntime != nullptr);
501 return *OpenCLRuntime;
504 /// Return a reference to the configured OpenMP runtime.
505 CGOpenMPRuntime &getOpenMPRuntime() {
506 assert(OpenMPRuntime != nullptr);
507 return *OpenMPRuntime;
510 /// Return a reference to the configured CUDA runtime.
511 CGCUDARuntime &getCUDARuntime() {
512 assert(CUDARuntime != nullptr);
516 ARCEntrypoints &getARCEntrypoints() const {
517 assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
521 RREntrypoints &getRREntrypoints() const {
522 assert(RRData != nullptr);
526 InstrProfStats &getPGOStats() { return PGOStats; }
527 llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
529 llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
530 return StaticLocalDeclMap[D];
532 void setStaticLocalDeclAddress(const VarDecl *D,
534 StaticLocalDeclMap[D] = C;
537 llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
538 return StaticLocalDeclGuardMap[D];
540 void setStaticLocalDeclGuardAddress(const VarDecl *D,
541 llvm::GlobalVariable *C) {
542 StaticLocalDeclGuardMap[D] = C;
545 bool lookupRepresentativeDecl(StringRef MangledName,
546 GlobalDecl &Result) const;
548 llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
549 return AtomicSetterHelperFnMap[Ty];
551 void setAtomicSetterHelperFnMap(QualType Ty,
552 llvm::Constant *Fn) {
553 AtomicSetterHelperFnMap[Ty] = Fn;
556 llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
557 return AtomicGetterHelperFnMap[Ty];
559 void setAtomicGetterHelperFnMap(QualType Ty,
560 llvm::Constant *Fn) {
561 AtomicGetterHelperFnMap[Ty] = Fn;
564 llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
565 return TypeDescriptorMap[Ty];
567 void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
568 TypeDescriptorMap[Ty] = C;
571 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
573 llvm::MDNode *getNoObjCARCExceptionsMetadata() {
574 if (!NoObjCARCExceptionsMetadata)
575 NoObjCARCExceptionsMetadata =
576 llvm::MDNode::get(getLLVMContext(),
577 SmallVector<llvm::Value*,1>());
578 return NoObjCARCExceptionsMetadata;
581 ASTContext &getContext() const { return Context; }
582 const LangOptions &getLangOpts() const { return LangOpts; }
583 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
584 llvm::Module &getModule() const { return TheModule; }
585 DiagnosticsEngine &getDiags() const { return Diags; }
586 const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
587 const TargetInfo &getTarget() const { return Target; }
588 CGCXXABI &getCXXABI() const { return *ABI; }
589 llvm::LLVMContext &getLLVMContext() { return VMContext; }
591 bool shouldUseTBAA() const { return TBAA != nullptr; }
593 const TargetCodeGenInfo &getTargetCodeGenInfo();
595 CodeGenTypes &getTypes() { return Types; }
597 CodeGenVTables &getVTables() { return VTables; }
599 ItaniumVTableContext &getItaniumVTableContext() {
600 return VTables.getItaniumVTableContext();
603 MicrosoftVTableContext &getMicrosoftVTableContext() {
604 return VTables.getMicrosoftVTableContext();
607 llvm::MDNode *getTBAAInfo(QualType QTy);
608 llvm::MDNode *getTBAAInfoForVTablePtr();
609 llvm::MDNode *getTBAAStructInfo(QualType QTy);
610 /// Return the MDNode in the type DAG for the given struct type.
611 llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
612 /// Return the path-aware tag for given base type, access node and offset.
613 llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
616 bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
618 bool isPaddedAtomicType(QualType type);
619 bool isPaddedAtomicType(const AtomicType *type);
621 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
622 /// is the same as the type. For struct-path aware TBAA, the tag
623 /// is different from the type: base type, access type and offset.
624 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
625 void DecorateInstruction(llvm::Instruction *Inst,
626 llvm::MDNode *TBAAInfo,
627 bool ConvertTypeToTag = true);
629 /// Emit the given number of characters as a value of type size_t.
630 llvm::ConstantInt *getSize(CharUnits numChars);
632 /// Set the visibility for the given LLVM GlobalValue.
633 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
635 /// Set the TLS mode for the given LLVM GlobalVariable for the thread-local
636 /// variable declaration D.
637 void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
639 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
641 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
642 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
643 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
645 llvm_unreachable("unknown visibility!");
648 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
649 if (isa<CXXConstructorDecl>(GD.getDecl()))
650 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
652 else if (isa<CXXDestructorDecl>(GD.getDecl()))
653 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
655 else if (isa<FunctionDecl>(GD.getDecl()))
656 return GetAddrOfFunction(GD);
658 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
661 /// Will return a global variable of the given type. If a variable with a
662 /// different type already exists then a new variable with the right type
663 /// will be created and all uses of the old variable will be replaced with a
664 /// bitcast to the new variable.
665 llvm::GlobalVariable *
666 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
667 llvm::GlobalValue::LinkageTypes Linkage);
669 /// Return the address space of the underlying global variable for D, as
670 /// determined by its declaration. Normally this is the same as the address
671 /// space of D's type, but in CUDA, address spaces are associated with
672 /// declarations, not types.
673 unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
675 /// Return the llvm::Constant for the address of the given global variable.
676 /// If Ty is non-null and if the global doesn't exist, then it will be greated
677 /// with the specified type instead of whatever the normal requested type
679 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
680 llvm::Type *Ty = nullptr);
682 /// Return the address of the given function. If Ty is non-null, then this
683 /// function will use the specified type if it has to create it.
684 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
685 bool ForVTable = false,
686 bool DontDefer = false);
688 /// Get the address of the RTTI descriptor for the given type.
689 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
691 /// Get the address of a uuid descriptor .
692 llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
694 /// Get the address of the thunk for the given global decl.
695 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
697 /// Get a reference to the target of VD.
698 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
700 /// Returns the offset from a derived class to a class. Returns null if the
703 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
704 CastExpr::path_const_iterator PathBegin,
705 CastExpr::path_const_iterator PathEnd);
707 /// A pair of helper functions for a __block variable.
708 class ByrefHelpers : public llvm::FoldingSetNode {
710 llvm::Constant *CopyHelper;
711 llvm::Constant *DisposeHelper;
713 /// The alignment of the field. This is important because
714 /// different offsets to the field within the byref struct need to
715 /// have different helper functions.
718 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
719 virtual ~ByrefHelpers();
721 void Profile(llvm::FoldingSetNodeID &id) const {
722 id.AddInteger(Alignment.getQuantity());
725 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
727 virtual bool needsCopy() const { return true; }
728 virtual void emitCopy(CodeGenFunction &CGF,
729 llvm::Value *dest, llvm::Value *src) = 0;
731 virtual bool needsDispose() const { return true; }
732 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
735 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
737 /// Fetches the global unique block count.
738 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
740 /// Fetches the type of a generic block descriptor.
741 llvm::Type *getBlockDescriptorType();
743 /// The type of a generic block literal.
744 llvm::Type *getGenericBlockLiteralType();
746 /// Gets the address of a block which requires no captures.
747 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
749 /// Return a pointer to a constant CFString object for the given string.
750 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
752 /// Return a pointer to a constant NSString object for the given string. Or a
753 /// user defined String object as defined via
754 /// -fconstant-string-class=class_name option.
755 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
757 /// Return a constant array for the given string.
758 llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
760 /// Return a pointer to a constant array for the given string literal.
761 llvm::GlobalVariable *
762 GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
764 /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
765 llvm::GlobalVariable *
766 GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
768 /// Returns a pointer to a character array containing the literal and a
769 /// terminating '\0' character. The result has pointer to array type.
771 /// \param GlobalName If provided, the name to use for the global (if one is
773 llvm::GlobalVariable *
774 GetAddrOfConstantCString(const std::string &Str,
775 const char *GlobalName = nullptr,
776 unsigned Alignment = 0);
778 /// Returns a pointer to a constant global variable for the given file-scope
779 /// compound literal expression.
780 llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
782 /// \brief Returns a pointer to a global variable representing a temporary
783 /// with static or thread storage duration.
784 llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
787 /// \brief Retrieve the record type that describes the state of an
788 /// Objective-C fast enumeration loop (for..in).
789 QualType getObjCFastEnumerationStateType();
791 /// Return the address of the constructor of the given type.
793 GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, CXXCtorType ctorType,
794 const CGFunctionInfo *fnInfo = nullptr,
795 bool DontDefer = false);
797 /// Return the address of the constructor of the given type.
799 GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
800 CXXDtorType dtorType,
801 const CGFunctionInfo *fnInfo = nullptr,
802 llvm::FunctionType *fnType = nullptr,
803 bool DontDefer = false);
805 /// Given a builtin id for a function like "__builtin_fabsf", return a
806 /// Function* for "fabsf".
807 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
810 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
812 /// Emit code for a single top level declaration.
813 void EmitTopLevelDecl(Decl *D);
815 /// Tell the consumer that this variable has been instantiated.
816 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
818 /// \brief If the declaration has internal linkage but is inside an
819 /// extern "C" linkage specification, prepare to emit an alias for it
820 /// to the expected name.
821 template<typename SomeDecl>
822 void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
824 /// Add a global to a list to be added to the llvm.used metadata.
825 void addUsedGlobal(llvm::GlobalValue *GV);
827 /// Add a global to a list to be added to the llvm.compiler.used metadata.
828 void addCompilerUsedGlobal(llvm::GlobalValue *GV);
830 /// Add a destructor and object to add to the C++ global destructor function.
831 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
832 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
835 /// Create a new runtime function with the specified type and name.
836 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
838 llvm::AttributeSet ExtraAttrs =
839 llvm::AttributeSet());
840 /// Create a new runtime global variable with the specified type and name.
841 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
844 ///@name Custom Blocks Runtime Interfaces
847 llvm::Constant *getNSConcreteGlobalBlock();
848 llvm::Constant *getNSConcreteStackBlock();
849 llvm::Constant *getBlockObjectAssign();
850 llvm::Constant *getBlockObjectDispose();
854 llvm::Constant *getLLVMLifetimeStartFn();
855 llvm::Constant *getLLVMLifetimeEndFn();
857 // Make sure that this type is translated.
858 void UpdateCompletedType(const TagDecl *TD);
860 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
862 /// Try to emit the initializer for the given declaration as a constant;
863 /// returns 0 if the expression cannot be emitted as a constant.
864 llvm::Constant *EmitConstantInit(const VarDecl &D,
865 CodeGenFunction *CGF = nullptr);
867 /// Try to emit the given expression as a constant; returns 0 if the
868 /// expression cannot be emitted as a constant.
869 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
870 CodeGenFunction *CGF = nullptr);
872 /// Emit the given constant value as a constant, in the type's scalar
874 llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
875 CodeGenFunction *CGF = nullptr);
877 /// Emit the given constant value as a constant, in the type's memory
879 llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
881 CodeGenFunction *CGF = nullptr);
883 /// Return the result of value-initializing the given type, i.e. a null
884 /// expression of the given type. This is usually, but not always, an LLVM
886 llvm::Constant *EmitNullConstant(QualType T);
888 /// Return a null constant appropriate for zero-initializing a base class with
889 /// the given type. This is usually, but not always, an LLVM null constant.
890 llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
892 /// Emit a general error that something can't be done.
893 void Error(SourceLocation loc, StringRef error);
895 /// Print out an error that codegen doesn't support the specified stmt yet.
896 void ErrorUnsupported(const Stmt *S, const char *Type);
898 /// Print out an error that codegen doesn't support the specified decl yet.
899 void ErrorUnsupported(const Decl *D, const char *Type);
901 /// Set the attributes on the LLVM function for the given decl and function
902 /// info. This applies attributes necessary for handling the ABI as well as
903 /// user specified attributes like section.
904 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
905 const CGFunctionInfo &FI);
907 /// Set the LLVM function attributes (sext, zext, etc).
908 void SetLLVMFunctionAttributes(const Decl *D,
909 const CGFunctionInfo &Info,
912 /// Set the LLVM function attributes which only apply to a function
914 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
916 /// Return true iff the given type uses 'sret' when used as a return type.
917 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
919 /// Return true iff the given type uses an argument slot when 'sret' is used
920 /// as a return type.
921 bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
923 /// Return true iff the given type uses 'fpret' when used as a return type.
924 bool ReturnTypeUsesFPRet(QualType ResultType);
926 /// Return true iff the given type uses 'fp2ret' when used as a return type.
927 bool ReturnTypeUsesFP2Ret(QualType ResultType);
929 /// Get the LLVM attributes and calling convention to use for a particular
932 /// \param Info - The function type information.
933 /// \param TargetDecl - The decl these attributes are being constructed
934 /// for. If supplied the attributes applied to this decl may contribute to the
935 /// function attributes and calling convention.
936 /// \param PAL [out] - On return, the attribute list to use.
937 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
938 void ConstructAttributeList(const CGFunctionInfo &Info,
939 const Decl *TargetDecl,
940 AttributeListType &PAL,
941 unsigned &CallingConv,
942 bool AttrOnCallSite);
944 StringRef getMangledName(GlobalDecl GD);
945 StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
947 void EmitTentativeDefinition(const VarDecl *D);
949 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
951 /// Emit the RTTI descriptors for the builtin types.
952 void EmitFundamentalRTTIDescriptors();
954 /// \brief Appends Opts to the "Linker Options" metadata value.
955 void AppendLinkerOptions(StringRef Opts);
957 /// \brief Appends a detect mismatch command to the linker options.
958 void AddDetectMismatch(StringRef Name, StringRef Value);
960 /// \brief Appends a dependent lib to the "Linker Options" metadata value.
961 void AddDependentLib(StringRef Lib);
963 llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
965 void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
966 F->setLinkage(getFunctionLinkage(GD));
969 /// Return the appropriate linkage for the vtable, VTT, and type information
970 /// of the given class.
971 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
973 /// Return the store size, in character units, of the given LLVM type.
974 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
976 /// Returns LLVM linkage for a declarator.
977 llvm::GlobalValue::LinkageTypes
978 getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
979 bool IsConstantVariable);
981 /// Returns LLVM linkage for a declarator.
982 llvm::GlobalValue::LinkageTypes
983 getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
985 /// Emit all the global annotations.
986 void EmitGlobalAnnotations();
988 /// Emit an annotation string.
989 llvm::Constant *EmitAnnotationString(StringRef Str);
991 /// Emit the annotation's translation unit.
992 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
994 /// Emit the annotation line number.
995 llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
997 /// Generate the llvm::ConstantStruct which contains the annotation
998 /// information for a given GlobalValue. The annotation struct is
999 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1000 /// GlobalValue being annotated. The second field is the constant string
1001 /// created from the AnnotateAttr's annotation. The third field is a constant
1002 /// string containing the name of the translation unit. The fourth field is
1003 /// the line number in the file of the annotated value declaration.
1004 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1005 const AnnotateAttr *AA,
1008 /// Add global annotations that are set on D, for the global GV. Those
1009 /// annotations are emitted during finalization of the LLVM code.
1010 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1012 const SanitizerBlacklist &getSanitizerBlacklist() const {
1016 void reportGlobalToASan(llvm::GlobalVariable *GV, const VarDecl &D,
1017 bool IsDynInit = false);
1018 void reportGlobalToASan(llvm::GlobalVariable *GV, SourceLocation Loc,
1019 StringRef Name, bool IsDynInit = false,
1020 bool IsBlacklisted = false);
1022 /// Disable sanitizer instrumentation for this global.
1023 void disableSanitizerForGlobal(llvm::GlobalVariable *GV);
1025 void addDeferredVTable(const CXXRecordDecl *RD) {
1026 DeferredVTables.push_back(RD);
1029 /// Emit code for a singal global function or var decl. Forward declarations
1030 /// are emitted lazily.
1031 void EmitGlobal(GlobalDecl D);
1034 llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1037 GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1038 bool ForVTable, bool DontDefer = false,
1039 llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1041 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1042 llvm::PointerType *PTy,
1045 /// Set attributes which are common to any form of a global definition (alias,
1046 /// Objective-C method, function, global variable).
1048 /// NOTE: This should only be called for definitions.
1049 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1051 void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1053 /// Set attributes for a global definition.
1054 void setFunctionDefinitionAttributes(const FunctionDecl *D,
1057 /// Set function attributes for a function declaration.
1058 void SetFunctionAttributes(GlobalDecl GD,
1060 bool IsIncompleteFunction);
1062 void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1064 void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1065 void EmitGlobalVarDefinition(const VarDecl *D);
1066 void EmitAliasDefinition(GlobalDecl GD);
1067 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1068 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1070 // C++ related functions.
1072 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1074 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1076 void EmitNamespace(const NamespaceDecl *D);
1077 void EmitLinkageSpec(const LinkageSpecDecl *D);
1078 void CompleteDIClassType(const CXXMethodDecl* D);
1080 /// Emit a single constructor with the given type from a C++ constructor Decl.
1081 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
1083 /// Emit a single destructor with the given type from a C++ destructor Decl.
1084 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
1086 /// \brief Emit the function that initializes C++ thread_local variables.
1087 void EmitCXXThreadLocalInitFunc();
1089 /// Emit the function that initializes C++ globals.
1090 void EmitCXXGlobalInitFunc();
1092 /// Emit the function that destroys C++ globals.
1093 void EmitCXXGlobalDtorFunc();
1095 /// Emit the function that initializes the specified global (if PerformInit is
1096 /// true) and registers its destructor.
1097 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1098 llvm::GlobalVariable *Addr,
1101 void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1102 llvm::Function *InitFunc, InitSegAttr *ISA);
1104 // FIXME: Hardcoding priority here is gross.
1105 void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1106 llvm::Constant *AssociatedData = 0);
1107 void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1109 /// Generates a global array of functions and priorities using the given list
1110 /// and name. This array will have appending linkage and is suitable for use
1111 /// as a LLVM constructor or destructor array.
1112 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1114 /// Emit the RTTI descriptors for the given type.
1115 void EmitFundamentalRTTIDescriptor(QualType Type);
1117 /// Emit any needed decls for which code generation was deferred.
1118 void EmitDeferred();
1120 /// Call replaceAllUsesWith on all pairs in Replacements.
1121 void applyReplacements();
1123 void checkAliases();
1125 /// Emit any vtables which we deferred and still have a use for.
1126 void EmitDeferredVTables();
1128 /// Emit the llvm.used and llvm.compiler.used metadata.
1129 void emitLLVMUsed();
1131 /// \brief Emit the link options introduced by imported modules.
1132 void EmitModuleLinkOptions();
1134 /// \brief Emit aliases for internal-linkage declarations inside "C" language
1135 /// linkage specifications, giving them the "expected" name where possible.
1136 void EmitStaticExternCAliases();
1138 void EmitDeclMetadata();
1140 /// \brief Emit the Clang version as llvm.ident metadata.
1141 void EmitVersionIdentMetadata();
1143 /// Emits target specific Metadata for global declarations.
1144 void EmitTargetMetadata();
1146 /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1147 /// .gcda files in a way that persists in .bc files.
1148 void EmitCoverageFile();
1150 /// Emits the initializer for a uuidof string.
1151 llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
1153 /// Determine if the given decl can be emitted lazily; this is only relevant
1154 /// for definitions. The given decl must be either a function or var decl.
1155 bool MayDeferGeneration(const ValueDecl *D);
1157 /// Check whether we can use a "simpler", more core exceptions personality
1159 void SimplifyPersonality();
1161 } // end namespace CodeGen
1162 } // end namespace clang