CodeGenModule.h 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the internal per-translation-unit state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  15. #include "CGVTables.h"
  16. #include "CodeGenTypeCache.h"
  17. #include "CodeGenTypes.h"
  18. #include "SanitizerMetadata.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/GlobalDecl.h"
  23. #include "clang/AST/Mangle.h"
  24. #include "clang/Basic/ABI.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Basic/Module.h"
  27. #include "clang/Basic/SanitizerBlacklist.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/Module.h"
  33. #include "llvm/IR/ValueHandle.h"
  34. #include "llvm/Transforms/Utils/SanitizerStats.h"
  35. namespace llvm {
  36. class Module;
  37. class Constant;
  38. class ConstantInt;
  39. class Function;
  40. class GlobalValue;
  41. class DataLayout;
  42. class FunctionType;
  43. class LLVMContext;
  44. class IndexedInstrProfReader;
  45. }
  46. namespace clang {
  47. class TargetCodeGenInfo;
  48. class ASTContext;
  49. class AtomicType;
  50. class FunctionDecl;
  51. class IdentifierInfo;
  52. class ObjCMethodDecl;
  53. class ObjCImplementationDecl;
  54. class ObjCCategoryImplDecl;
  55. class ObjCProtocolDecl;
  56. class ObjCEncodeExpr;
  57. class BlockExpr;
  58. class CharUnits;
  59. class Decl;
  60. class Expr;
  61. class Stmt;
  62. class InitListExpr;
  63. class StringLiteral;
  64. class NamedDecl;
  65. class ValueDecl;
  66. class VarDecl;
  67. class LangOptions;
  68. class CodeGenOptions;
  69. class HeaderSearchOptions;
  70. class PreprocessorOptions;
  71. class DiagnosticsEngine;
  72. class AnnotateAttr;
  73. class CXXDestructorDecl;
  74. class Module;
  75. class CoverageSourceInfo;
  76. namespace CodeGen {
  77. class CallArgList;
  78. class CodeGenFunction;
  79. class CodeGenTBAA;
  80. class CGCXXABI;
  81. class CGDebugInfo;
  82. class CGObjCRuntime;
  83. class CGOpenCLRuntime;
  84. class CGOpenMPRuntime;
  85. class CGCUDARuntime;
  86. class BlockFieldFlags;
  87. class FunctionArgList;
  88. class CoverageMappingModuleGen;
  89. struct OrderGlobalInits {
  90. unsigned int priority;
  91. unsigned int lex_order;
  92. OrderGlobalInits(unsigned int p, unsigned int l)
  93. : priority(p), lex_order(l) {}
  94. bool operator==(const OrderGlobalInits &RHS) const {
  95. return priority == RHS.priority && lex_order == RHS.lex_order;
  96. }
  97. bool operator<(const OrderGlobalInits &RHS) const {
  98. return std::tie(priority, lex_order) <
  99. std::tie(RHS.priority, RHS.lex_order);
  100. }
  101. };
  102. struct ObjCEntrypoints {
  103. ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
  104. /// void objc_autoreleasePoolPop(void*);
  105. llvm::Constant *objc_autoreleasePoolPop;
  106. /// void *objc_autoreleasePoolPush(void);
  107. llvm::Constant *objc_autoreleasePoolPush;
  108. /// id objc_autorelease(id);
  109. llvm::Constant *objc_autorelease;
  110. /// id objc_autoreleaseReturnValue(id);
  111. llvm::Constant *objc_autoreleaseReturnValue;
  112. /// void objc_copyWeak(id *dest, id *src);
  113. llvm::Constant *objc_copyWeak;
  114. /// void objc_destroyWeak(id*);
  115. llvm::Constant *objc_destroyWeak;
  116. /// id objc_initWeak(id*, id);
  117. llvm::Constant *objc_initWeak;
  118. /// id objc_loadWeak(id*);
  119. llvm::Constant *objc_loadWeak;
  120. /// id objc_loadWeakRetained(id*);
  121. llvm::Constant *objc_loadWeakRetained;
  122. /// void objc_moveWeak(id *dest, id *src);
  123. llvm::Constant *objc_moveWeak;
  124. /// id objc_retain(id);
  125. llvm::Constant *objc_retain;
  126. /// id objc_retainAutorelease(id);
  127. llvm::Constant *objc_retainAutorelease;
  128. /// id objc_retainAutoreleaseReturnValue(id);
  129. llvm::Constant *objc_retainAutoreleaseReturnValue;
  130. /// id objc_retainAutoreleasedReturnValue(id);
  131. llvm::Constant *objc_retainAutoreleasedReturnValue;
  132. /// id objc_retainBlock(id);
  133. llvm::Constant *objc_retainBlock;
  134. /// void objc_release(id);
  135. llvm::Constant *objc_release;
  136. /// id objc_storeStrong(id*, id);
  137. llvm::Constant *objc_storeStrong;
  138. /// id objc_storeWeak(id*, id);
  139. llvm::Constant *objc_storeWeak;
  140. /// id objc_unsafeClaimAutoreleasedReturnValue(id);
  141. llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
  142. /// A void(void) inline asm to use to mark that the return value of
  143. /// a call will be immediately retain.
  144. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  145. /// void clang.arc.use(...);
  146. llvm::Constant *clang_arc_use;
  147. };
  148. /// This class records statistics on instrumentation based profiling.
  149. class InstrProfStats {
  150. uint32_t VisitedInMainFile;
  151. uint32_t MissingInMainFile;
  152. uint32_t Visited;
  153. uint32_t Missing;
  154. uint32_t Mismatched;
  155. public:
  156. InstrProfStats()
  157. : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
  158. Mismatched(0) {}
  159. /// Record that we've visited a function and whether or not that function was
  160. /// in the main source file.
  161. void addVisited(bool MainFile) {
  162. if (MainFile)
  163. ++VisitedInMainFile;
  164. ++Visited;
  165. }
  166. /// Record that a function we've visited has no profile data.
  167. void addMissing(bool MainFile) {
  168. if (MainFile)
  169. ++MissingInMainFile;
  170. ++Missing;
  171. }
  172. /// Record that a function we've visited has mismatched profile data.
  173. void addMismatched(bool MainFile) { ++Mismatched; }
  174. /// Whether or not the stats we've gathered indicate any potential problems.
  175. bool hasDiagnostics() { return Missing || Mismatched; }
  176. /// Report potential problems we've found to \c Diags.
  177. void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
  178. };
  179. /// A pair of helper functions for a __block variable.
  180. class BlockByrefHelpers : public llvm::FoldingSetNode {
  181. // MSVC requires this type to be complete in order to process this
  182. // header.
  183. public:
  184. llvm::Constant *CopyHelper;
  185. llvm::Constant *DisposeHelper;
  186. /// The alignment of the field. This is important because
  187. /// different offsets to the field within the byref struct need to
  188. /// have different helper functions.
  189. CharUnits Alignment;
  190. BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
  191. BlockByrefHelpers(const BlockByrefHelpers &) = default;
  192. virtual ~BlockByrefHelpers();
  193. void Profile(llvm::FoldingSetNodeID &id) const {
  194. id.AddInteger(Alignment.getQuantity());
  195. profileImpl(id);
  196. }
  197. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  198. virtual bool needsCopy() const { return true; }
  199. virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
  200. virtual bool needsDispose() const { return true; }
  201. virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
  202. };
  203. /// This class organizes the cross-function state that is used while generating
  204. /// LLVM code.
  205. class CodeGenModule : public CodeGenTypeCache {
  206. CodeGenModule(const CodeGenModule &) = delete;
  207. void operator=(const CodeGenModule &) = delete;
  208. public:
  209. struct Structor {
  210. Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
  211. Structor(int Priority, llvm::Constant *Initializer,
  212. llvm::Constant *AssociatedData)
  213. : Priority(Priority), Initializer(Initializer),
  214. AssociatedData(AssociatedData) {}
  215. int Priority;
  216. llvm::Constant *Initializer;
  217. llvm::Constant *AssociatedData;
  218. };
  219. typedef std::vector<Structor> CtorList;
  220. private:
  221. ASTContext &Context;
  222. const LangOptions &LangOpts;
  223. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  224. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  225. const CodeGenOptions &CodeGenOpts;
  226. llvm::Module &TheModule;
  227. DiagnosticsEngine &Diags;
  228. const TargetInfo &Target;
  229. std::unique_ptr<CGCXXABI> ABI;
  230. llvm::LLVMContext &VMContext;
  231. CodeGenTBAA *TBAA;
  232. mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
  233. // This should not be moved earlier, since its initialization depends on some
  234. // of the previous reference members being already initialized and also checks
  235. // if TheTargetCodeGenInfo is NULL
  236. CodeGenTypes Types;
  237. /// Holds information about C++ vtables.
  238. CodeGenVTables VTables;
  239. CGObjCRuntime* ObjCRuntime;
  240. CGOpenCLRuntime* OpenCLRuntime;
  241. CGOpenMPRuntime* OpenMPRuntime;
  242. CGCUDARuntime* CUDARuntime;
  243. CGDebugInfo* DebugInfo;
  244. ObjCEntrypoints *ObjCData;
  245. llvm::MDNode *NoObjCARCExceptionsMetadata;
  246. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
  247. InstrProfStats PGOStats;
  248. std::unique_ptr<llvm::SanitizerStatReport> SanStats;
  249. // A set of references that have only been seen via a weakref so far. This is
  250. // used to remove the weak of the reference if we ever see a direct reference
  251. // or a definition.
  252. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  253. /// This contains all the decls which have definitions but/ which are deferred
  254. /// for emission and therefore should only be output if they are actually
  255. /// used. If a decl is in this, then it is known to have not been referenced
  256. /// yet.
  257. std::map<StringRef, GlobalDecl> DeferredDecls;
  258. /// This is a list of deferred decls which we have seen that *are* actually
  259. /// referenced. These get code generated when the module is done.
  260. struct DeferredGlobal {
  261. DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
  262. llvm::TrackingVH<llvm::GlobalValue> GV;
  263. GlobalDecl GD;
  264. };
  265. std::vector<DeferredGlobal> DeferredDeclsToEmit;
  266. void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
  267. DeferredDeclsToEmit.emplace_back(GV, GD);
  268. }
  269. /// List of alias we have emitted. Used to make sure that what they point to
  270. /// is defined once we get to the end of the of the translation unit.
  271. std::vector<GlobalDecl> Aliases;
  272. typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
  273. ReplacementsTy Replacements;
  274. /// List of global values to be replaced with something else. Used when we
  275. /// want to replace a GlobalValue but can't identify it by its mangled name
  276. /// anymore (because the name is already taken).
  277. llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
  278. GlobalValReplacements;
  279. /// Set of global decls for which we already diagnosed mangled name conflict.
  280. /// Required to not issue a warning (on a mangling conflict) multiple times
  281. /// for the same decl.
  282. llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
  283. /// A queue of (optional) vtables to consider emitting.
  284. std::vector<const CXXRecordDecl*> DeferredVTables;
  285. /// List of global values which are required to be present in the object file;
  286. /// bitcast to i8*. This is used for forcing visibility of symbols which may
  287. /// otherwise be optimized out.
  288. std::vector<llvm::WeakVH> LLVMUsed;
  289. std::vector<llvm::WeakVH> LLVMCompilerUsed;
  290. /// Store the list of global constructors and their respective priorities to
  291. /// be emitted when the translation unit is complete.
  292. CtorList GlobalCtors;
  293. /// Store the list of global destructors and their respective priorities to be
  294. /// emitted when the translation unit is complete.
  295. CtorList GlobalDtors;
  296. /// An ordered map of canonical GlobalDecls to their mangled names.
  297. llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
  298. llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
  299. /// Global annotations.
  300. std::vector<llvm::Constant*> Annotations;
  301. /// Map used to get unique annotation strings.
  302. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  303. llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
  304. llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
  305. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  306. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  307. llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
  308. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  309. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  310. /// Map used to get unique type descriptor constants for sanitizers.
  311. llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
  312. /// Map used to track internal linkage functions declared within
  313. /// extern "C" regions.
  314. typedef llvm::MapVector<IdentifierInfo *,
  315. llvm::GlobalValue *> StaticExternCMap;
  316. StaticExternCMap StaticExternCValues;
  317. /// \brief thread_local variables defined or used in this TU.
  318. std::vector<const VarDecl *> CXXThreadLocals;
  319. /// \brief thread_local variables with initializers that need to run
  320. /// before any thread_local variable in this TU is odr-used.
  321. std::vector<llvm::Function *> CXXThreadLocalInits;
  322. std::vector<const VarDecl *> CXXThreadLocalInitVars;
  323. /// Global variables with initializers that need to run before main.
  324. std::vector<llvm::Function *> CXXGlobalInits;
  325. /// When a C++ decl with an initializer is deferred, null is
  326. /// appended to CXXGlobalInits, and the index of that null is placed
  327. /// here so that the initializer will be performed in the correct
  328. /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
  329. /// that we don't re-emit the initializer.
  330. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
  331. typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
  332. struct GlobalInitPriorityCmp {
  333. bool operator()(const GlobalInitData &LHS,
  334. const GlobalInitData &RHS) const {
  335. return LHS.first.priority < RHS.first.priority;
  336. }
  337. };
  338. /// Global variables with initializers whose order of initialization is set by
  339. /// init_priority attribute.
  340. SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
  341. /// Global destructor functions and arguments that need to run on termination.
  342. std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
  343. /// \brief The complete set of modules that has been imported.
  344. llvm::SetVector<clang::Module *> ImportedModules;
  345. /// \brief A vector of metadata strings.
  346. SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
  347. /// @name Cache for Objective-C runtime types
  348. /// @{
  349. /// Cached reference to the class for constant strings. This value has type
  350. /// int * but is actually an Obj-C class pointer.
  351. llvm::WeakVH CFConstantStringClassRef;
  352. /// Cached reference to the class for constant strings. This value has type
  353. /// int * but is actually an Obj-C class pointer.
  354. llvm::WeakVH ConstantStringClassRef;
  355. /// \brief The LLVM type corresponding to NSConstantString.
  356. llvm::StructType *NSConstantStringType;
  357. /// \brief The type used to describe the state of a fast enumeration in
  358. /// Objective-C's for..in loop.
  359. QualType ObjCFastEnumerationStateType;
  360. /// @}
  361. /// Lazily create the Objective-C runtime
  362. void createObjCRuntime();
  363. void createOpenCLRuntime();
  364. void createOpenMPRuntime();
  365. void createCUDARuntime();
  366. bool isTriviallyRecursive(const FunctionDecl *F);
  367. bool shouldEmitFunction(GlobalDecl GD);
  368. /// @name Cache for Blocks Runtime Globals
  369. /// @{
  370. llvm::Constant *NSConcreteGlobalBlock;
  371. llvm::Constant *NSConcreteStackBlock;
  372. llvm::Constant *BlockObjectAssign;
  373. llvm::Constant *BlockObjectDispose;
  374. llvm::Type *BlockDescriptorType;
  375. llvm::Type *GenericBlockLiteralType;
  376. struct {
  377. int GlobalUniqueCount;
  378. } Block;
  379. /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
  380. llvm::Constant *LifetimeStartFn;
  381. /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
  382. llvm::Constant *LifetimeEndFn;
  383. GlobalDecl initializedGlobalDecl;
  384. std::unique_ptr<SanitizerMetadata> SanitizerMD;
  385. /// @}
  386. llvm::DenseMap<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
  387. std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
  388. /// Mapping from canonical types to their metadata identifiers. We need to
  389. /// maintain this mapping because identifiers may be formed from distinct
  390. /// MDNodes.
  391. llvm::DenseMap<QualType, llvm::Metadata *> MetadataIdMap;
  392. public:
  393. CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
  394. const PreprocessorOptions &ppopts,
  395. const CodeGenOptions &CodeGenOpts, llvm::Module &M,
  396. DiagnosticsEngine &Diags,
  397. CoverageSourceInfo *CoverageInfo = nullptr);
  398. ~CodeGenModule();
  399. void clear();
  400. /// Finalize LLVM code generation.
  401. void Release();
  402. /// Return a reference to the configured Objective-C runtime.
  403. CGObjCRuntime &getObjCRuntime() {
  404. if (!ObjCRuntime) createObjCRuntime();
  405. return *ObjCRuntime;
  406. }
  407. /// Return true iff an Objective-C runtime has been configured.
  408. bool hasObjCRuntime() { return !!ObjCRuntime; }
  409. /// Return a reference to the configured OpenCL runtime.
  410. CGOpenCLRuntime &getOpenCLRuntime() {
  411. assert(OpenCLRuntime != nullptr);
  412. return *OpenCLRuntime;
  413. }
  414. /// Return a reference to the configured OpenMP runtime.
  415. CGOpenMPRuntime &getOpenMPRuntime() {
  416. assert(OpenMPRuntime != nullptr);
  417. return *OpenMPRuntime;
  418. }
  419. /// Return a reference to the configured CUDA runtime.
  420. CGCUDARuntime &getCUDARuntime() {
  421. assert(CUDARuntime != nullptr);
  422. return *CUDARuntime;
  423. }
  424. ObjCEntrypoints &getObjCEntrypoints() const {
  425. assert(ObjCData != nullptr);
  426. return *ObjCData;
  427. }
  428. InstrProfStats &getPGOStats() { return PGOStats; }
  429. llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
  430. CoverageMappingModuleGen *getCoverageMapping() const {
  431. return CoverageMapping.get();
  432. }
  433. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  434. return StaticLocalDeclMap[D];
  435. }
  436. void setStaticLocalDeclAddress(const VarDecl *D,
  437. llvm::Constant *C) {
  438. StaticLocalDeclMap[D] = C;
  439. }
  440. llvm::Constant *
  441. getOrCreateStaticVarDecl(const VarDecl &D,
  442. llvm::GlobalValue::LinkageTypes Linkage);
  443. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  444. return StaticLocalDeclGuardMap[D];
  445. }
  446. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  447. llvm::GlobalVariable *C) {
  448. StaticLocalDeclGuardMap[D] = C;
  449. }
  450. bool lookupRepresentativeDecl(StringRef MangledName,
  451. GlobalDecl &Result) const;
  452. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  453. return AtomicSetterHelperFnMap[Ty];
  454. }
  455. void setAtomicSetterHelperFnMap(QualType Ty,
  456. llvm::Constant *Fn) {
  457. AtomicSetterHelperFnMap[Ty] = Fn;
  458. }
  459. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  460. return AtomicGetterHelperFnMap[Ty];
  461. }
  462. void setAtomicGetterHelperFnMap(QualType Ty,
  463. llvm::Constant *Fn) {
  464. AtomicGetterHelperFnMap[Ty] = Fn;
  465. }
  466. llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
  467. return TypeDescriptorMap[Ty];
  468. }
  469. void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
  470. TypeDescriptorMap[Ty] = C;
  471. }
  472. CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
  473. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  474. if (!NoObjCARCExceptionsMetadata)
  475. NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
  476. return NoObjCARCExceptionsMetadata;
  477. }
  478. ASTContext &getContext() const { return Context; }
  479. const LangOptions &getLangOpts() const { return LangOpts; }
  480. const HeaderSearchOptions &getHeaderSearchOpts()
  481. const { return HeaderSearchOpts; }
  482. const PreprocessorOptions &getPreprocessorOpts()
  483. const { return PreprocessorOpts; }
  484. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  485. llvm::Module &getModule() const { return TheModule; }
  486. DiagnosticsEngine &getDiags() const { return Diags; }
  487. const llvm::DataLayout &getDataLayout() const {
  488. return TheModule.getDataLayout();
  489. }
  490. const TargetInfo &getTarget() const { return Target; }
  491. const llvm::Triple &getTriple() const;
  492. bool supportsCOMDAT() const;
  493. void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
  494. CGCXXABI &getCXXABI() const { return *ABI; }
  495. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  496. bool shouldUseTBAA() const { return TBAA != nullptr; }
  497. const TargetCodeGenInfo &getTargetCodeGenInfo();
  498. CodeGenTypes &getTypes() { return Types; }
  499. CodeGenVTables &getVTables() { return VTables; }
  500. ItaniumVTableContext &getItaniumVTableContext() {
  501. return VTables.getItaniumVTableContext();
  502. }
  503. MicrosoftVTableContext &getMicrosoftVTableContext() {
  504. return VTables.getMicrosoftVTableContext();
  505. }
  506. CtorList &getGlobalCtors() { return GlobalCtors; }
  507. CtorList &getGlobalDtors() { return GlobalDtors; }
  508. llvm::MDNode *getTBAAInfo(QualType QTy);
  509. llvm::MDNode *getTBAAInfoForVTablePtr();
  510. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  511. /// Return the path-aware tag for given base type, access node and offset.
  512. llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
  513. uint64_t O);
  514. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  515. bool isPaddedAtomicType(QualType type);
  516. bool isPaddedAtomicType(const AtomicType *type);
  517. /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
  518. /// is the same as the type. For struct-path aware TBAA, the tag
  519. /// is different from the type: base type, access type and offset.
  520. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  521. void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  522. llvm::MDNode *TBAAInfo,
  523. bool ConvertTypeToTag = true);
  524. /// Adds !invariant.barrier !tag to instruction
  525. void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
  526. const CXXRecordDecl *RD);
  527. /// Emit the given number of characters as a value of type size_t.
  528. llvm::ConstantInt *getSize(CharUnits numChars);
  529. /// Set the visibility for the given LLVM GlobalValue.
  530. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  531. /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
  532. /// variable declaration D.
  533. void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
  534. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  535. switch (V) {
  536. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  537. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  538. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  539. }
  540. llvm_unreachable("unknown visibility!");
  541. }
  542. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD, bool IsForDefinition = false);
  543. /// Will return a global variable of the given type. If a variable with a
  544. /// different type already exists then a new variable with the right type
  545. /// will be created and all uses of the old variable will be replaced with a
  546. /// bitcast to the new variable.
  547. llvm::GlobalVariable *
  548. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  549. llvm::GlobalValue::LinkageTypes Linkage);
  550. llvm::Function *
  551. CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
  552. const CGFunctionInfo &FI,
  553. SourceLocation Loc = SourceLocation(),
  554. bool TLS = false);
  555. /// Return the address space of the underlying global variable for D, as
  556. /// determined by its declaration. Normally this is the same as the address
  557. /// space of D's type, but in CUDA, address spaces are associated with
  558. /// declarations, not types.
  559. unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
  560. /// Return the llvm::Constant for the address of the given global variable.
  561. /// If Ty is non-null and if the global doesn't exist, then it will be created
  562. /// with the specified type instead of whatever the normal requested type
  563. /// would be. If IsForDefinition is true, it is guranteed that an actual
  564. /// global with type Ty will be returned, not conversion of a variable with
  565. /// the same mangled name but some other type.
  566. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  567. llvm::Type *Ty = nullptr,
  568. bool IsForDefinition = false);
  569. /// Return the address of the given function. If Ty is non-null, then this
  570. /// function will use the specified type if it has to create it.
  571. llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
  572. bool ForVTable = false,
  573. bool DontDefer = false,
  574. bool IsForDefinition = false);
  575. /// Get the address of the RTTI descriptor for the given type.
  576. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  577. /// Get the address of a uuid descriptor .
  578. ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
  579. /// Get the address of the thunk for the given global decl.
  580. llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
  581. /// Get a reference to the target of VD.
  582. ConstantAddress GetWeakRefReference(const ValueDecl *VD);
  583. /// Returns the assumed alignment of an opaque pointer to the given class.
  584. CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
  585. /// Returns the assumed alignment of a virtual base of a class.
  586. CharUnits getVBaseAlignment(CharUnits DerivedAlign,
  587. const CXXRecordDecl *Derived,
  588. const CXXRecordDecl *VBase);
  589. /// Given a class pointer with an actual known alignment, and the
  590. /// expected alignment of an object at a dynamic offset w.r.t that
  591. /// pointer, return the alignment to assume at the offset.
  592. CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
  593. const CXXRecordDecl *Class,
  594. CharUnits ExpectedTargetAlign);
  595. CharUnits
  596. computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
  597. CastExpr::path_const_iterator Start,
  598. CastExpr::path_const_iterator End);
  599. /// Returns the offset from a derived class to a class. Returns null if the
  600. /// offset is 0.
  601. llvm::Constant *
  602. GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  603. CastExpr::path_const_iterator PathBegin,
  604. CastExpr::path_const_iterator PathEnd);
  605. llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
  606. /// Fetches the global unique block count.
  607. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
  608. /// Fetches the type of a generic block descriptor.
  609. llvm::Type *getBlockDescriptorType();
  610. /// The type of a generic block literal.
  611. llvm::Type *getGenericBlockLiteralType();
  612. /// Gets the address of a block which requires no captures.
  613. llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
  614. /// Return a pointer to a constant CFString object for the given string.
  615. ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
  616. /// Return a pointer to a constant NSString object for the given string. Or a
  617. /// user defined String object as defined via
  618. /// -fconstant-string-class=class_name option.
  619. ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
  620. /// Return a constant array for the given string.
  621. llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
  622. /// Return a pointer to a constant array for the given string literal.
  623. ConstantAddress
  624. GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  625. StringRef Name = ".str");
  626. /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
  627. ConstantAddress
  628. GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
  629. /// Returns a pointer to a character array containing the literal and a
  630. /// terminating '\0' character. The result has pointer to array type.
  631. ///
  632. /// \param GlobalName If provided, the name to use for the global (if one is
  633. /// created).
  634. ConstantAddress
  635. GetAddrOfConstantCString(const std::string &Str,
  636. const char *GlobalName = nullptr);
  637. /// Returns a pointer to a constant global variable for the given file-scope
  638. /// compound literal expression.
  639. ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
  640. /// \brief Returns a pointer to a global variable representing a temporary
  641. /// with static or thread storage duration.
  642. ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
  643. const Expr *Inner);
  644. /// \brief Retrieve the record type that describes the state of an
  645. /// Objective-C fast enumeration loop (for..in).
  646. QualType getObjCFastEnumerationStateType();
  647. // Produce code for this constructor/destructor. This method doesn't try
  648. // to apply any ABI rules about which other constructors/destructors
  649. // are needed or if they are alias to each other.
  650. llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
  651. StructorType Type);
  652. /// Return the address of the constructor/destructor of the given type.
  653. llvm::Constant *
  654. getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
  655. const CGFunctionInfo *FnInfo = nullptr,
  656. llvm::FunctionType *FnType = nullptr,
  657. bool DontDefer = false, bool IsForDefinition = false);
  658. /// Given a builtin id for a function like "__builtin_fabsf", return a
  659. /// Function* for "fabsf".
  660. llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
  661. unsigned BuiltinID);
  662. llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
  663. /// Emit code for a single top level declaration.
  664. void EmitTopLevelDecl(Decl *D);
  665. /// \brief Stored a deferred empty coverage mapping for an unused
  666. /// and thus uninstrumented top level declaration.
  667. void AddDeferredUnusedCoverageMapping(Decl *D);
  668. /// \brief Remove the deferred empty coverage mapping as this
  669. /// declaration is actually instrumented.
  670. void ClearUnusedCoverageMapping(const Decl *D);
  671. /// \brief Emit all the deferred coverage mappings
  672. /// for the uninstrumented functions.
  673. void EmitDeferredUnusedCoverageMappings();
  674. /// Tell the consumer that this variable has been instantiated.
  675. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
  676. /// \brief If the declaration has internal linkage but is inside an
  677. /// extern "C" linkage specification, prepare to emit an alias for it
  678. /// to the expected name.
  679. template<typename SomeDecl>
  680. void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
  681. /// Add a global to a list to be added to the llvm.used metadata.
  682. void addUsedGlobal(llvm::GlobalValue *GV);
  683. /// Add a global to a list to be added to the llvm.compiler.used metadata.
  684. void addCompilerUsedGlobal(llvm::GlobalValue *GV);
  685. /// Add a destructor and object to add to the C++ global destructor function.
  686. void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
  687. CXXGlobalDtors.emplace_back(DtorFn, Object);
  688. }
  689. /// Create a new runtime function with the specified type and name.
  690. llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
  691. StringRef Name,
  692. llvm::AttributeSet ExtraAttrs =
  693. llvm::AttributeSet());
  694. /// Create a new compiler builtin function with the specified type and name.
  695. llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
  696. StringRef Name,
  697. llvm::AttributeSet ExtraAttrs =
  698. llvm::AttributeSet());
  699. /// Create a new runtime global variable with the specified type and name.
  700. llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
  701. StringRef Name);
  702. ///@name Custom Blocks Runtime Interfaces
  703. ///@{
  704. llvm::Constant *getNSConcreteGlobalBlock();
  705. llvm::Constant *getNSConcreteStackBlock();
  706. llvm::Constant *getBlockObjectAssign();
  707. llvm::Constant *getBlockObjectDispose();
  708. ///@}
  709. llvm::Constant *getLLVMLifetimeStartFn();
  710. llvm::Constant *getLLVMLifetimeEndFn();
  711. // Make sure that this type is translated.
  712. void UpdateCompletedType(const TagDecl *TD);
  713. llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
  714. /// Try to emit the initializer for the given declaration as a constant;
  715. /// returns 0 if the expression cannot be emitted as a constant.
  716. llvm::Constant *EmitConstantInit(const VarDecl &D,
  717. CodeGenFunction *CGF = nullptr);
  718. /// Try to emit the given expression as a constant; returns 0 if the
  719. /// expression cannot be emitted as a constant.
  720. llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
  721. CodeGenFunction *CGF = nullptr);
  722. /// Emit the given constant value as a constant, in the type's scalar
  723. /// representation.
  724. llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
  725. CodeGenFunction *CGF = nullptr);
  726. /// Emit the given constant value as a constant, in the type's memory
  727. /// representation.
  728. llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
  729. QualType DestType,
  730. CodeGenFunction *CGF = nullptr);
  731. /// \brief Emit type info if type of an expression is a variably modified
  732. /// type. Also emit proper debug info for cast types.
  733. void EmitExplicitCastExprType(const ExplicitCastExpr *E,
  734. CodeGenFunction *CGF = nullptr);
  735. /// Return the result of value-initializing the given type, i.e. a null
  736. /// expression of the given type. This is usually, but not always, an LLVM
  737. /// null constant.
  738. llvm::Constant *EmitNullConstant(QualType T);
  739. /// Return a null constant appropriate for zero-initializing a base class with
  740. /// the given type. This is usually, but not always, an LLVM null constant.
  741. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  742. /// Emit a general error that something can't be done.
  743. void Error(SourceLocation loc, StringRef error);
  744. /// Print out an error that codegen doesn't support the specified stmt yet.
  745. void ErrorUnsupported(const Stmt *S, const char *Type);
  746. /// Print out an error that codegen doesn't support the specified decl yet.
  747. void ErrorUnsupported(const Decl *D, const char *Type);
  748. /// Set the attributes on the LLVM function for the given decl and function
  749. /// info. This applies attributes necessary for handling the ABI as well as
  750. /// user specified attributes like section.
  751. void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
  752. const CGFunctionInfo &FI);
  753. /// Set the LLVM function attributes (sext, zext, etc).
  754. void SetLLVMFunctionAttributes(const Decl *D,
  755. const CGFunctionInfo &Info,
  756. llvm::Function *F);
  757. /// Set the LLVM function attributes which only apply to a function
  758. /// definition.
  759. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  760. /// Return true iff the given type uses 'sret' when used as a return type.
  761. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  762. /// Return true iff the given type uses an argument slot when 'sret' is used
  763. /// as a return type.
  764. bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
  765. /// Return true iff the given type uses 'fpret' when used as a return type.
  766. bool ReturnTypeUsesFPRet(QualType ResultType);
  767. /// Return true iff the given type uses 'fp2ret' when used as a return type.
  768. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  769. /// Get the LLVM attributes and calling convention to use for a particular
  770. /// function type.
  771. ///
  772. /// \param Name - The function name.
  773. /// \param Info - The function type information.
  774. /// \param CalleeInfo - The callee information these attributes are being
  775. /// constructed for. If valid, the attributes applied to this decl may
  776. /// contribute to the function attributes and calling convention.
  777. /// \param PAL [out] - On return, the attribute list to use.
  778. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  779. void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
  780. CGCalleeInfo CalleeInfo, AttributeListType &PAL,
  781. unsigned &CallingConv, bool AttrOnCallSite);
  782. // Fills in the supplied string map with the set of target features for the
  783. // passed in function.
  784. void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  785. const FunctionDecl *FD);
  786. StringRef getMangledName(GlobalDecl GD);
  787. StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
  788. void EmitTentativeDefinition(const VarDecl *D);
  789. void EmitVTable(CXXRecordDecl *Class);
  790. void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
  791. /// \brief Appends Opts to the "Linker Options" metadata value.
  792. void AppendLinkerOptions(StringRef Opts);
  793. /// \brief Appends a detect mismatch command to the linker options.
  794. void AddDetectMismatch(StringRef Name, StringRef Value);
  795. /// \brief Appends a dependent lib to the "Linker Options" metadata value.
  796. void AddDependentLib(StringRef Lib);
  797. llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
  798. void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
  799. F->setLinkage(getFunctionLinkage(GD));
  800. }
  801. /// Set the DLL storage class on F.
  802. void setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F);
  803. /// Return the appropriate linkage for the vtable, VTT, and type information
  804. /// of the given class.
  805. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  806. /// Return the store size, in character units, of the given LLVM type.
  807. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  808. /// Returns LLVM linkage for a declarator.
  809. llvm::GlobalValue::LinkageTypes
  810. getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
  811. bool IsConstantVariable);
  812. /// Returns LLVM linkage for a declarator.
  813. llvm::GlobalValue::LinkageTypes
  814. getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
  815. /// Emit all the global annotations.
  816. void EmitGlobalAnnotations();
  817. /// Emit an annotation string.
  818. llvm::Constant *EmitAnnotationString(StringRef Str);
  819. /// Emit the annotation's translation unit.
  820. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  821. /// Emit the annotation line number.
  822. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  823. /// Generate the llvm::ConstantStruct which contains the annotation
  824. /// information for a given GlobalValue. The annotation struct is
  825. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  826. /// GlobalValue being annotated. The second field is the constant string
  827. /// created from the AnnotateAttr's annotation. The third field is a constant
  828. /// string containing the name of the translation unit. The fourth field is
  829. /// the line number in the file of the annotated value declaration.
  830. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  831. const AnnotateAttr *AA,
  832. SourceLocation L);
  833. /// Add global annotations that are set on D, for the global GV. Those
  834. /// annotations are emitted during finalization of the LLVM code.
  835. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  836. bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const;
  837. bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
  838. QualType Ty,
  839. StringRef Category = StringRef()) const;
  840. SanitizerMetadata *getSanitizerMetadata() {
  841. return SanitizerMD.get();
  842. }
  843. void addDeferredVTable(const CXXRecordDecl *RD) {
  844. DeferredVTables.push_back(RD);
  845. }
  846. /// Emit code for a singal global function or var decl. Forward declarations
  847. /// are emitted lazily.
  848. void EmitGlobal(GlobalDecl D);
  849. bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
  850. bool InEveryTU);
  851. bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
  852. /// Set attributes for a global definition.
  853. void setFunctionDefinitionAttributes(const FunctionDecl *D,
  854. llvm::Function *F);
  855. llvm::GlobalValue *GetGlobalValue(StringRef Ref);
  856. /// Set attributes which are common to any form of a global definition (alias,
  857. /// Objective-C method, function, global variable).
  858. ///
  859. /// NOTE: This should only be called for definitions.
  860. void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
  861. /// Set attributes which must be preserved by an alias. This includes common
  862. /// attributes (i.e. it includes a call to SetCommonAttributes).
  863. ///
  864. /// NOTE: This should only be called for definitions.
  865. void setAliasAttributes(const Decl *D, llvm::GlobalValue *GV);
  866. void addReplacement(StringRef Name, llvm::Constant *C);
  867. void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
  868. /// \brief Emit a code for threadprivate directive.
  869. /// \param D Threadprivate declaration.
  870. void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
  871. /// Returns whether the given record is blacklisted from control flow
  872. /// integrity checks.
  873. bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD);
  874. /// Emit bit set entries for the given vtable using the given layout if
  875. /// vptr CFI is enabled.
  876. void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
  877. const VTableLayout &VTLayout);
  878. /// Generate a cross-DSO type identifier for type.
  879. llvm::ConstantInt *CreateCfiIdForTypeMetadata(llvm::Metadata *MD);
  880. /// Create a metadata identifier for the given type. This may either be an
  881. /// MDString (for external identifiers) or a distinct unnamed MDNode (for
  882. /// internal identifiers).
  883. llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
  884. /// Create a bitset entry for the given function and add it to BitsetsMD.
  885. void CreateFunctionBitSetEntry(const FunctionDecl *FD, llvm::Function *F);
  886. /// Returns whether this module needs the "all-vtables" bitset.
  887. bool NeedAllVtablesBitSet() const;
  888. /// Create a bitset entry for the given vtable and add it to BitsetsMD.
  889. void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
  890. llvm::GlobalVariable *VTable, CharUnits Offset,
  891. const CXXRecordDecl *RD);
  892. /// \breif Get the declaration of std::terminate for the platform.
  893. llvm::Constant *getTerminateFn();
  894. llvm::SanitizerStatReport &getSanStats();
  895. private:
  896. llvm::Constant *
  897. GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
  898. bool ForVTable, bool DontDefer = false,
  899. bool IsThunk = false,
  900. llvm::AttributeSet ExtraAttrs = llvm::AttributeSet(),
  901. bool IsForDefinition = false);
  902. llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
  903. llvm::PointerType *PTy,
  904. const VarDecl *D,
  905. bool IsForDefinition = false);
  906. void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
  907. /// Set function attributes for a function declaration.
  908. void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  909. bool IsIncompleteFunction, bool IsThunk);
  910. void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
  911. void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  912. void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
  913. void EmitAliasDefinition(GlobalDecl GD);
  914. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  915. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  916. // C++ related functions.
  917. void EmitNamespace(const NamespaceDecl *D);
  918. void EmitLinkageSpec(const LinkageSpecDecl *D);
  919. void CompleteDIClassType(const CXXMethodDecl* D);
  920. /// \brief Emit the function that initializes C++ thread_local variables.
  921. void EmitCXXThreadLocalInitFunc();
  922. /// Emit the function that initializes C++ globals.
  923. void EmitCXXGlobalInitFunc();
  924. /// Emit the function that destroys C++ globals.
  925. void EmitCXXGlobalDtorFunc();
  926. /// Emit the function that initializes the specified global (if PerformInit is
  927. /// true) and registers its destructor.
  928. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  929. llvm::GlobalVariable *Addr,
  930. bool PerformInit);
  931. void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
  932. llvm::Function *InitFunc, InitSegAttr *ISA);
  933. // FIXME: Hardcoding priority here is gross.
  934. void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
  935. llvm::Constant *AssociatedData = nullptr);
  936. void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
  937. /// Generates a global array of functions and priorities using the given list
  938. /// and name. This array will have appending linkage and is suitable for use
  939. /// as a LLVM constructor or destructor array.
  940. void EmitCtorList(const CtorList &Fns, const char *GlobalName);
  941. /// Emit any needed decls for which code generation was deferred.
  942. void EmitDeferred();
  943. /// Call replaceAllUsesWith on all pairs in Replacements.
  944. void applyReplacements();
  945. /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
  946. void applyGlobalValReplacements();
  947. void checkAliases();
  948. /// Emit any vtables which we deferred and still have a use for.
  949. void EmitDeferredVTables();
  950. /// Emit the llvm.used and llvm.compiler.used metadata.
  951. void emitLLVMUsed();
  952. /// \brief Emit the link options introduced by imported modules.
  953. void EmitModuleLinkOptions();
  954. /// \brief Emit aliases for internal-linkage declarations inside "C" language
  955. /// linkage specifications, giving them the "expected" name where possible.
  956. void EmitStaticExternCAliases();
  957. void EmitDeclMetadata();
  958. /// \brief Emit the Clang version as llvm.ident metadata.
  959. void EmitVersionIdentMetadata();
  960. /// Emits target specific Metadata for global declarations.
  961. void EmitTargetMetadata();
  962. /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
  963. /// .gcda files in a way that persists in .bc files.
  964. void EmitCoverageFile();
  965. /// Emits the initializer for a uuidof string.
  966. llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
  967. /// Determine whether the definition must be emitted; if this returns \c
  968. /// false, the definition can be emitted lazily if it's used.
  969. bool MustBeEmitted(const ValueDecl *D);
  970. /// Determine whether the definition can be emitted eagerly, or should be
  971. /// delayed until the end of the translation unit. This is relevant for
  972. /// definitions whose linkage can change, e.g. implicit function instantions
  973. /// which may later be explicitly instantiated.
  974. bool MayBeEmittedEagerly(const ValueDecl *D);
  975. /// Check whether we can use a "simpler", more core exceptions personality
  976. /// function.
  977. void SimplifyPersonality();
  978. };
  979. } // end namespace CodeGen
  980. } // end namespace clang
  981. #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H