CodeGenModule.h 46 KB

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