CodeGenModule.h 48 KB

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