CodeGenModule.h 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the internal per-translation-unit state used for llvm translation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  13. #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
  14. #include "CGVTables.h"
  15. #include "CodeGenTypeCache.h"
  16. #include "CodeGenTypes.h"
  17. #include "SanitizerMetadata.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/GlobalDecl.h"
  22. #include "clang/AST/Mangle.h"
  23. #include "clang/Basic/ABI.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/Basic/Module.h"
  26. #include "clang/Basic/NoSanitizeList.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Basic/XRayLists.h"
  29. #include "clang/Lex/PreprocessorOptions.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/SetVector.h"
  32. #include "llvm/ADT/SmallPtrSet.h"
  33. #include "llvm/ADT/StringMap.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/IR/ValueHandle.h"
  36. #include "llvm/Transforms/Utils/SanitizerStats.h"
  37. namespace llvm {
  38. class Module;
  39. class Constant;
  40. class ConstantInt;
  41. class Function;
  42. class GlobalValue;
  43. class DataLayout;
  44. class FunctionType;
  45. class LLVMContext;
  46. class IndexedInstrProfReader;
  47. }
  48. namespace clang {
  49. class ASTContext;
  50. class AtomicType;
  51. class FunctionDecl;
  52. class IdentifierInfo;
  53. class ObjCImplementationDecl;
  54. class ObjCEncodeExpr;
  55. class BlockExpr;
  56. class CharUnits;
  57. class Decl;
  58. class Expr;
  59. class Stmt;
  60. class StringLiteral;
  61. class NamedDecl;
  62. class ValueDecl;
  63. class VarDecl;
  64. class LangOptions;
  65. class CodeGenOptions;
  66. class HeaderSearchOptions;
  67. class DiagnosticsEngine;
  68. class AnnotateAttr;
  69. class CXXDestructorDecl;
  70. class Module;
  71. class CoverageSourceInfo;
  72. class InitSegAttr;
  73. namespace CodeGen {
  74. class CodeGenFunction;
  75. class CodeGenTBAA;
  76. class CGCXXABI;
  77. class CGDebugInfo;
  78. class CGObjCRuntime;
  79. class CGOpenCLRuntime;
  80. class CGOpenMPRuntime;
  81. class CGCUDARuntime;
  82. class CoverageMappingModuleGen;
  83. class TargetCodeGenInfo;
  84. enum ForDefinition_t : bool {
  85. NotForDefinition = false,
  86. ForDefinition = true
  87. };
  88. struct OrderGlobalInitsOrStermFinalizers {
  89. unsigned int priority;
  90. unsigned int lex_order;
  91. OrderGlobalInitsOrStermFinalizers(unsigned int p, unsigned int l)
  92. : priority(p), lex_order(l) {}
  93. bool operator==(const OrderGlobalInitsOrStermFinalizers &RHS) const {
  94. return priority == RHS.priority && lex_order == RHS.lex_order;
  95. }
  96. bool operator<(const OrderGlobalInitsOrStermFinalizers &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_alloc(id);
  104. llvm::FunctionCallee objc_alloc;
  105. /// void objc_allocWithZone(id);
  106. llvm::FunctionCallee objc_allocWithZone;
  107. /// void objc_alloc_init(id);
  108. llvm::FunctionCallee objc_alloc_init;
  109. /// void objc_autoreleasePoolPop(void*);
  110. llvm::FunctionCallee objc_autoreleasePoolPop;
  111. /// void objc_autoreleasePoolPop(void*);
  112. /// Note this method is used when we are using exception handling
  113. llvm::FunctionCallee objc_autoreleasePoolPopInvoke;
  114. /// void *objc_autoreleasePoolPush(void);
  115. llvm::Function *objc_autoreleasePoolPush;
  116. /// id objc_autorelease(id);
  117. llvm::Function *objc_autorelease;
  118. /// id objc_autorelease(id);
  119. /// Note this is the runtime method not the intrinsic.
  120. llvm::FunctionCallee objc_autoreleaseRuntimeFunction;
  121. /// id objc_autoreleaseReturnValue(id);
  122. llvm::Function *objc_autoreleaseReturnValue;
  123. /// void objc_copyWeak(id *dest, id *src);
  124. llvm::Function *objc_copyWeak;
  125. /// void objc_destroyWeak(id*);
  126. llvm::Function *objc_destroyWeak;
  127. /// id objc_initWeak(id*, id);
  128. llvm::Function *objc_initWeak;
  129. /// id objc_loadWeak(id*);
  130. llvm::Function *objc_loadWeak;
  131. /// id objc_loadWeakRetained(id*);
  132. llvm::Function *objc_loadWeakRetained;
  133. /// void objc_moveWeak(id *dest, id *src);
  134. llvm::Function *objc_moveWeak;
  135. /// id objc_retain(id);
  136. llvm::Function *objc_retain;
  137. /// id objc_retain(id);
  138. /// Note this is the runtime method not the intrinsic.
  139. llvm::FunctionCallee objc_retainRuntimeFunction;
  140. /// id objc_retainAutorelease(id);
  141. llvm::Function *objc_retainAutorelease;
  142. /// id objc_retainAutoreleaseReturnValue(id);
  143. llvm::Function *objc_retainAutoreleaseReturnValue;
  144. /// id objc_retainAutoreleasedReturnValue(id);
  145. llvm::Function *objc_retainAutoreleasedReturnValue;
  146. /// id objc_retainBlock(id);
  147. llvm::Function *objc_retainBlock;
  148. /// void objc_release(id);
  149. llvm::Function *objc_release;
  150. /// void objc_release(id);
  151. /// Note this is the runtime method not the intrinsic.
  152. llvm::FunctionCallee objc_releaseRuntimeFunction;
  153. /// void objc_storeStrong(id*, id);
  154. llvm::Function *objc_storeStrong;
  155. /// id objc_storeWeak(id*, id);
  156. llvm::Function *objc_storeWeak;
  157. /// id objc_unsafeClaimAutoreleasedReturnValue(id);
  158. llvm::Function *objc_unsafeClaimAutoreleasedReturnValue;
  159. /// A void(void) inline asm to use to mark that the return value of
  160. /// a call will be immediately retain.
  161. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  162. /// void clang.arc.use(...);
  163. llvm::Function *clang_arc_use;
  164. /// void clang.arc.noop.use(...);
  165. llvm::Function *clang_arc_noop_use;
  166. };
  167. /// This class records statistics on instrumentation based profiling.
  168. class InstrProfStats {
  169. uint32_t VisitedInMainFile;
  170. uint32_t MissingInMainFile;
  171. uint32_t Visited;
  172. uint32_t Missing;
  173. uint32_t Mismatched;
  174. public:
  175. InstrProfStats()
  176. : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
  177. Mismatched(0) {}
  178. /// Record that we've visited a function and whether or not that function was
  179. /// in the main source file.
  180. void addVisited(bool MainFile) {
  181. if (MainFile)
  182. ++VisitedInMainFile;
  183. ++Visited;
  184. }
  185. /// Record that a function we've visited has no profile data.
  186. void addMissing(bool MainFile) {
  187. if (MainFile)
  188. ++MissingInMainFile;
  189. ++Missing;
  190. }
  191. /// Record that a function we've visited has mismatched profile data.
  192. void addMismatched(bool MainFile) { ++Mismatched; }
  193. /// Whether or not the stats we've gathered indicate any potential problems.
  194. bool hasDiagnostics() { return Missing || Mismatched; }
  195. /// Report potential problems we've found to \c Diags.
  196. void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
  197. };
  198. /// A pair of helper functions for a __block variable.
  199. class BlockByrefHelpers : public llvm::FoldingSetNode {
  200. // MSVC requires this type to be complete in order to process this
  201. // header.
  202. public:
  203. llvm::Constant *CopyHelper;
  204. llvm::Constant *DisposeHelper;
  205. /// The alignment of the field. This is important because
  206. /// different offsets to the field within the byref struct need to
  207. /// have different helper functions.
  208. CharUnits Alignment;
  209. BlockByrefHelpers(CharUnits alignment)
  210. : CopyHelper(nullptr), DisposeHelper(nullptr), Alignment(alignment) {}
  211. BlockByrefHelpers(const BlockByrefHelpers &) = default;
  212. virtual ~BlockByrefHelpers();
  213. void Profile(llvm::FoldingSetNodeID &id) const {
  214. id.AddInteger(Alignment.getQuantity());
  215. profileImpl(id);
  216. }
  217. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  218. virtual bool needsCopy() const { return true; }
  219. virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
  220. virtual bool needsDispose() const { return true; }
  221. virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
  222. };
  223. /// This class organizes the cross-function state that is used while generating
  224. /// LLVM code.
  225. class CodeGenModule : public CodeGenTypeCache {
  226. CodeGenModule(const CodeGenModule &) = delete;
  227. void operator=(const CodeGenModule &) = delete;
  228. public:
  229. struct Structor {
  230. Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
  231. Structor(int Priority, llvm::Constant *Initializer,
  232. llvm::Constant *AssociatedData)
  233. : Priority(Priority), Initializer(Initializer),
  234. AssociatedData(AssociatedData) {}
  235. int Priority;
  236. llvm::Constant *Initializer;
  237. llvm::Constant *AssociatedData;
  238. };
  239. typedef std::vector<Structor> CtorList;
  240. private:
  241. ASTContext &Context;
  242. const LangOptions &LangOpts;
  243. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  244. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  245. const CodeGenOptions &CodeGenOpts;
  246. unsigned NumAutoVarInit = 0;
  247. llvm::Module &TheModule;
  248. DiagnosticsEngine &Diags;
  249. const TargetInfo &Target;
  250. std::unique_ptr<CGCXXABI> ABI;
  251. llvm::LLVMContext &VMContext;
  252. std::string ModuleNameHash;
  253. std::unique_ptr<CodeGenTBAA> TBAA;
  254. mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
  255. // This should not be moved earlier, since its initialization depends on some
  256. // of the previous reference members being already initialized and also checks
  257. // if TheTargetCodeGenInfo is NULL
  258. CodeGenTypes Types;
  259. /// Holds information about C++ vtables.
  260. CodeGenVTables VTables;
  261. std::unique_ptr<CGObjCRuntime> ObjCRuntime;
  262. std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
  263. std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
  264. std::unique_ptr<CGCUDARuntime> CUDARuntime;
  265. std::unique_ptr<CGDebugInfo> DebugInfo;
  266. std::unique_ptr<ObjCEntrypoints> ObjCData;
  267. llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
  268. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
  269. InstrProfStats PGOStats;
  270. std::unique_ptr<llvm::SanitizerStatReport> SanStats;
  271. // A set of references that have only been seen via a weakref so far. This is
  272. // used to remove the weak of the reference if we ever see a direct reference
  273. // or a definition.
  274. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  275. /// This contains all the decls which have definitions but/ which are deferred
  276. /// for emission and therefore should only be output if they are actually
  277. /// used. If a decl is in this, then it is known to have not been referenced
  278. /// yet.
  279. llvm::DenseMap<StringRef, GlobalDecl> DeferredDecls;
  280. /// This is a list of deferred decls which we have seen that *are* actually
  281. /// referenced. These get code generated when the module is done.
  282. std::vector<GlobalDecl> DeferredDeclsToEmit;
  283. void addDeferredDeclToEmit(GlobalDecl GD) {
  284. DeferredDeclsToEmit.emplace_back(GD);
  285. }
  286. /// List of alias we have emitted. Used to make sure that what they point to
  287. /// is defined once we get to the end of the of the translation unit.
  288. std::vector<GlobalDecl> Aliases;
  289. /// List of multiversion functions that have to be emitted. Used to make sure
  290. /// we properly emit the iFunc.
  291. std::vector<GlobalDecl> MultiVersionFuncs;
  292. typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
  293. ReplacementsTy Replacements;
  294. /// List of global values to be replaced with something else. Used when we
  295. /// want to replace a GlobalValue but can't identify it by its mangled name
  296. /// anymore (because the name is already taken).
  297. llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
  298. GlobalValReplacements;
  299. /// Variables for which we've emitted globals containing their constant
  300. /// values along with the corresponding globals, for opportunistic reuse.
  301. llvm::DenseMap<const VarDecl*, llvm::GlobalVariable*> InitializerConstants;
  302. /// Set of global decls for which we already diagnosed mangled name conflict.
  303. /// Required to not issue a warning (on a mangling conflict) multiple times
  304. /// for the same decl.
  305. llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
  306. /// A queue of (optional) vtables to consider emitting.
  307. std::vector<const CXXRecordDecl*> DeferredVTables;
  308. /// A queue of (optional) vtables that may be emitted opportunistically.
  309. std::vector<const CXXRecordDecl *> OpportunisticVTables;
  310. /// List of global values which are required to be present in the object file;
  311. /// bitcast to i8*. This is used for forcing visibility of symbols which may
  312. /// otherwise be optimized out.
  313. std::vector<llvm::WeakTrackingVH> LLVMUsed;
  314. std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
  315. /// Store the list of global constructors and their respective priorities to
  316. /// be emitted when the translation unit is complete.
  317. CtorList GlobalCtors;
  318. /// Store the list of global destructors and their respective priorities to be
  319. /// emitted when the translation unit is complete.
  320. CtorList GlobalDtors;
  321. /// An ordered map of canonical GlobalDecls to their mangled names.
  322. llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
  323. llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
  324. /// Global annotations.
  325. std::vector<llvm::Constant*> Annotations;
  326. /// Map used to get unique annotation strings.
  327. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  328. /// Used for uniquing of annotation arguments.
  329. llvm::DenseMap<unsigned, llvm::Constant *> AnnotationArgs;
  330. llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
  331. llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
  332. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  333. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  334. llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
  335. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  336. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  337. /// Map used to get unique type descriptor constants for sanitizers.
  338. llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
  339. /// Map used to track internal linkage functions declared within
  340. /// extern "C" regions.
  341. typedef llvm::MapVector<IdentifierInfo *,
  342. llvm::GlobalValue *> StaticExternCMap;
  343. StaticExternCMap StaticExternCValues;
  344. /// thread_local variables defined or used in this TU.
  345. std::vector<const VarDecl *> CXXThreadLocals;
  346. /// thread_local variables with initializers that need to run
  347. /// before any thread_local variable in this TU is odr-used.
  348. std::vector<llvm::Function *> CXXThreadLocalInits;
  349. std::vector<const VarDecl *> CXXThreadLocalInitVars;
  350. /// Global variables with initializers that need to run before main.
  351. std::vector<llvm::Function *> CXXGlobalInits;
  352. /// When a C++ decl with an initializer is deferred, null is
  353. /// appended to CXXGlobalInits, and the index of that null is placed
  354. /// here so that the initializer will be performed in the correct
  355. /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
  356. /// that we don't re-emit the initializer.
  357. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
  358. typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
  359. GlobalInitData;
  360. struct GlobalInitPriorityCmp {
  361. bool operator()(const GlobalInitData &LHS,
  362. const GlobalInitData &RHS) const {
  363. return LHS.first.priority < RHS.first.priority;
  364. }
  365. };
  366. /// Global variables with initializers whose order of initialization is set by
  367. /// init_priority attribute.
  368. SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
  369. /// Global destructor functions and arguments that need to run on termination.
  370. /// When UseSinitAndSterm is set, it instead contains sterm finalizer
  371. /// functions, which also run on unloading a shared library.
  372. typedef std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
  373. llvm::Constant *>
  374. CXXGlobalDtorsOrStermFinalizer_t;
  375. SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8>
  376. CXXGlobalDtorsOrStermFinalizers;
  377. typedef std::pair<OrderGlobalInitsOrStermFinalizers, llvm::Function *>
  378. StermFinalizerData;
  379. struct StermFinalizerPriorityCmp {
  380. bool operator()(const StermFinalizerData &LHS,
  381. const StermFinalizerData &RHS) const {
  382. return LHS.first.priority < RHS.first.priority;
  383. }
  384. };
  385. /// Global variables with sterm finalizers whose order of initialization is
  386. /// set by init_priority attribute.
  387. SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
  388. /// The complete set of modules that has been imported.
  389. llvm::SetVector<clang::Module *> ImportedModules;
  390. /// The set of modules for which the module initializers
  391. /// have been emitted.
  392. llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
  393. /// A vector of metadata strings for linker options.
  394. SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
  395. /// A vector of metadata strings for dependent libraries for ELF.
  396. SmallVector<llvm::MDNode *, 16> ELFDependentLibraries;
  397. /// @name Cache for Objective-C runtime types
  398. /// @{
  399. /// Cached reference to the class for constant strings. This value has type
  400. /// int * but is actually an Obj-C class pointer.
  401. llvm::WeakTrackingVH CFConstantStringClassRef;
  402. /// The type used to describe the state of a fast enumeration in
  403. /// Objective-C's for..in loop.
  404. QualType ObjCFastEnumerationStateType;
  405. /// @}
  406. /// Lazily create the Objective-C runtime
  407. void createObjCRuntime();
  408. void createOpenCLRuntime();
  409. void createOpenMPRuntime();
  410. void createCUDARuntime();
  411. bool isTriviallyRecursive(const FunctionDecl *F);
  412. bool shouldEmitFunction(GlobalDecl GD);
  413. bool shouldOpportunisticallyEmitVTables();
  414. /// Map used to be sure we don't emit the same CompoundLiteral twice.
  415. llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
  416. EmittedCompoundLiterals;
  417. /// Map of the global blocks we've emitted, so that we don't have to re-emit
  418. /// them if the constexpr evaluator gets aggressive.
  419. llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
  420. /// @name Cache for Blocks Runtime Globals
  421. /// @{
  422. llvm::Constant *NSConcreteGlobalBlock = nullptr;
  423. llvm::Constant *NSConcreteStackBlock = nullptr;
  424. llvm::FunctionCallee BlockObjectAssign = nullptr;
  425. llvm::FunctionCallee BlockObjectDispose = nullptr;
  426. llvm::Type *BlockDescriptorType = nullptr;
  427. llvm::Type *GenericBlockLiteralType = nullptr;
  428. struct {
  429. int GlobalUniqueCount;
  430. } Block;
  431. GlobalDecl initializedGlobalDecl;
  432. /// @}
  433. /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
  434. llvm::Function *LifetimeStartFn = nullptr;
  435. /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
  436. llvm::Function *LifetimeEndFn = nullptr;
  437. std::unique_ptr<SanitizerMetadata> SanitizerMD;
  438. llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
  439. std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
  440. /// Mapping from canonical types to their metadata identifiers. We need to
  441. /// maintain this mapping because identifiers may be formed from distinct
  442. /// MDNodes.
  443. typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
  444. MetadataTypeMap MetadataIdMap;
  445. MetadataTypeMap VirtualMetadataIdMap;
  446. MetadataTypeMap GeneralizedMetadataIdMap;
  447. public:
  448. CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
  449. const PreprocessorOptions &ppopts,
  450. const CodeGenOptions &CodeGenOpts, llvm::Module &M,
  451. DiagnosticsEngine &Diags,
  452. CoverageSourceInfo *CoverageInfo = nullptr);
  453. ~CodeGenModule();
  454. void clear();
  455. /// Finalize LLVM code generation.
  456. void Release();
  457. /// Return true if we should emit location information for expressions.
  458. bool getExpressionLocationsEnabled() const;
  459. /// Return a reference to the configured Objective-C runtime.
  460. CGObjCRuntime &getObjCRuntime() {
  461. if (!ObjCRuntime) createObjCRuntime();
  462. return *ObjCRuntime;
  463. }
  464. /// Return true iff an Objective-C runtime has been configured.
  465. bool hasObjCRuntime() { return !!ObjCRuntime; }
  466. const std::string &getModuleNameHash() const { return ModuleNameHash; }
  467. /// Return a reference to the configured OpenCL runtime.
  468. CGOpenCLRuntime &getOpenCLRuntime() {
  469. assert(OpenCLRuntime != nullptr);
  470. return *OpenCLRuntime;
  471. }
  472. /// Return a reference to the configured OpenMP runtime.
  473. CGOpenMPRuntime &getOpenMPRuntime() {
  474. assert(OpenMPRuntime != nullptr);
  475. return *OpenMPRuntime;
  476. }
  477. /// Return a reference to the configured CUDA runtime.
  478. CGCUDARuntime &getCUDARuntime() {
  479. assert(CUDARuntime != nullptr);
  480. return *CUDARuntime;
  481. }
  482. ObjCEntrypoints &getObjCEntrypoints() const {
  483. assert(ObjCData != nullptr);
  484. return *ObjCData;
  485. }
  486. // Version checking functions, used to implement ObjC's @available:
  487. // i32 @__isOSVersionAtLeast(i32, i32, i32)
  488. llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
  489. // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
  490. llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
  491. InstrProfStats &getPGOStats() { return PGOStats; }
  492. llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
  493. CoverageMappingModuleGen *getCoverageMapping() const {
  494. return CoverageMapping.get();
  495. }
  496. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  497. return StaticLocalDeclMap[D];
  498. }
  499. void setStaticLocalDeclAddress(const VarDecl *D,
  500. llvm::Constant *C) {
  501. StaticLocalDeclMap[D] = C;
  502. }
  503. llvm::Constant *
  504. getOrCreateStaticVarDecl(const VarDecl &D,
  505. llvm::GlobalValue::LinkageTypes Linkage);
  506. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  507. return StaticLocalDeclGuardMap[D];
  508. }
  509. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  510. llvm::GlobalVariable *C) {
  511. StaticLocalDeclGuardMap[D] = C;
  512. }
  513. Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant,
  514. CharUnits Align);
  515. bool lookupRepresentativeDecl(StringRef MangledName,
  516. GlobalDecl &Result) const;
  517. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  518. return AtomicSetterHelperFnMap[Ty];
  519. }
  520. void setAtomicSetterHelperFnMap(QualType Ty,
  521. llvm::Constant *Fn) {
  522. AtomicSetterHelperFnMap[Ty] = Fn;
  523. }
  524. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  525. return AtomicGetterHelperFnMap[Ty];
  526. }
  527. void setAtomicGetterHelperFnMap(QualType Ty,
  528. llvm::Constant *Fn) {
  529. AtomicGetterHelperFnMap[Ty] = Fn;
  530. }
  531. llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
  532. return TypeDescriptorMap[Ty];
  533. }
  534. void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
  535. TypeDescriptorMap[Ty] = C;
  536. }
  537. CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
  538. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  539. if (!NoObjCARCExceptionsMetadata)
  540. NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
  541. return NoObjCARCExceptionsMetadata;
  542. }
  543. ASTContext &getContext() const { return Context; }
  544. const LangOptions &getLangOpts() const { return LangOpts; }
  545. const HeaderSearchOptions &getHeaderSearchOpts()
  546. const { return HeaderSearchOpts; }
  547. const PreprocessorOptions &getPreprocessorOpts()
  548. const { return PreprocessorOpts; }
  549. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  550. llvm::Module &getModule() const { return TheModule; }
  551. DiagnosticsEngine &getDiags() const { return Diags; }
  552. const llvm::DataLayout &getDataLayout() const {
  553. return TheModule.getDataLayout();
  554. }
  555. const TargetInfo &getTarget() const { return Target; }
  556. const llvm::Triple &getTriple() const { return Target.getTriple(); }
  557. bool supportsCOMDAT() const;
  558. void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
  559. CGCXXABI &getCXXABI() const { return *ABI; }
  560. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  561. bool shouldUseTBAA() const { return TBAA != nullptr; }
  562. const TargetCodeGenInfo &getTargetCodeGenInfo();
  563. CodeGenTypes &getTypes() { return Types; }
  564. CodeGenVTables &getVTables() { return VTables; }
  565. ItaniumVTableContext &getItaniumVTableContext() {
  566. return VTables.getItaniumVTableContext();
  567. }
  568. MicrosoftVTableContext &getMicrosoftVTableContext() {
  569. return VTables.getMicrosoftVTableContext();
  570. }
  571. CtorList &getGlobalCtors() { return GlobalCtors; }
  572. CtorList &getGlobalDtors() { return GlobalDtors; }
  573. /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
  574. /// the given type.
  575. llvm::MDNode *getTBAATypeInfo(QualType QTy);
  576. /// getTBAAAccessInfo - Get TBAA information that describes an access to
  577. /// an object of the given type.
  578. TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
  579. /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
  580. /// access to a virtual table pointer.
  581. TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
  582. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  583. /// getTBAABaseTypeInfo - Get metadata that describes the given base access
  584. /// type. Return null if the type is not suitable for use in TBAA access tags.
  585. llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
  586. /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
  587. llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
  588. /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
  589. /// type casts.
  590. TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  591. TBAAAccessInfo TargetInfo);
  592. /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
  593. /// purposes of conditional operator.
  594. TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  595. TBAAAccessInfo InfoB);
  596. /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
  597. /// purposes of memory transfer calls.
  598. TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  599. TBAAAccessInfo SrcInfo);
  600. /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
  601. /// base lvalue.
  602. TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
  603. if (Base.getTBAAInfo().isMayAlias())
  604. return TBAAAccessInfo::getMayAliasInfo();
  605. return getTBAAAccessInfo(AccessType);
  606. }
  607. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  608. bool isPaddedAtomicType(QualType type);
  609. bool isPaddedAtomicType(const AtomicType *type);
  610. /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
  611. void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  612. TBAAAccessInfo TBAAInfo);
  613. /// Adds !invariant.barrier !tag to instruction
  614. void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
  615. const CXXRecordDecl *RD);
  616. /// Emit the given number of characters as a value of type size_t.
  617. llvm::ConstantInt *getSize(CharUnits numChars);
  618. /// Set the visibility for the given LLVM GlobalValue.
  619. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  620. void setDSOLocal(llvm::GlobalValue *GV) const;
  621. void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
  622. void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
  623. /// Set visibility, dllimport/dllexport and dso_local.
  624. /// This must be called after dllimport/dllexport is set.
  625. void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
  626. void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
  627. void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const;
  628. /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
  629. /// variable declaration D.
  630. void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
  631. /// Get LLVM TLS mode from CodeGenOptions.
  632. llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const;
  633. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  634. switch (V) {
  635. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  636. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  637. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  638. }
  639. llvm_unreachable("unknown visibility!");
  640. }
  641. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
  642. ForDefinition_t IsForDefinition
  643. = NotForDefinition);
  644. /// Will return a global variable of the given type. If a variable with a
  645. /// different type already exists then a new variable with the right type
  646. /// will be created and all uses of the old variable will be replaced with a
  647. /// bitcast to the new variable.
  648. llvm::GlobalVariable *
  649. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  650. llvm::GlobalValue::LinkageTypes Linkage,
  651. unsigned Alignment);
  652. llvm::Function *CreateGlobalInitOrCleanUpFunction(
  653. llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI,
  654. SourceLocation Loc = SourceLocation(), bool TLS = false);
  655. /// Return the AST address space of the underlying global variable for D, as
  656. /// determined by its declaration. Normally this is the same as the address
  657. /// space of D's type, but in CUDA, address spaces are associated with
  658. /// declarations, not types. If D is nullptr, return the default address
  659. /// space for global variable.
  660. ///
  661. /// For languages without explicit address spaces, if D has default address
  662. /// space, target-specific global or constant address space may be returned.
  663. LangAS GetGlobalVarAddressSpace(const VarDecl *D);
  664. /// Return the AST address space of constant literal, which is used to emit
  665. /// the constant literal as global variable in LLVM IR.
  666. /// Note: This is not necessarily the address space of the constant literal
  667. /// in AST. For address space agnostic language, e.g. C++, constant literal
  668. /// in AST is always in default address space.
  669. LangAS GetGlobalConstantAddressSpace() const;
  670. /// Return the llvm::Constant for the address of the given global variable.
  671. /// If Ty is non-null and if the global doesn't exist, then it will be created
  672. /// with the specified type instead of whatever the normal requested type
  673. /// would be. If IsForDefinition is true, it is guaranteed that an actual
  674. /// global with type Ty will be returned, not conversion of a variable with
  675. /// the same mangled name but some other type.
  676. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  677. llvm::Type *Ty = nullptr,
  678. ForDefinition_t IsForDefinition
  679. = NotForDefinition);
  680. /// Return the address of the given function. If Ty is non-null, then this
  681. /// function will use the specified type if it has to create it.
  682. llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
  683. bool ForVTable = false,
  684. bool DontDefer = false,
  685. ForDefinition_t IsForDefinition
  686. = NotForDefinition);
  687. // Return the function body address of the given function.
  688. llvm::Constant *GetFunctionStart(const ValueDecl *Decl);
  689. /// Get the address of the RTTI descriptor for the given type.
  690. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  691. /// Get the address of a GUID.
  692. ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD);
  693. /// Get the address of a template parameter object.
  694. ConstantAddress
  695. GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO);
  696. /// Get the address of the thunk for the given global decl.
  697. llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
  698. GlobalDecl GD);
  699. /// Get a reference to the target of VD.
  700. ConstantAddress GetWeakRefReference(const ValueDecl *VD);
  701. /// Returns the assumed alignment of an opaque pointer to the given class.
  702. CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
  703. /// Returns the minimum object size for an object of the given class type
  704. /// (or a class derived from it).
  705. CharUnits getMinimumClassObjectSize(const CXXRecordDecl *CD);
  706. /// Returns the minimum object size for an object of the given type.
  707. CharUnits getMinimumObjectSize(QualType Ty) {
  708. if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
  709. return getMinimumClassObjectSize(RD);
  710. return getContext().getTypeSizeInChars(Ty);
  711. }
  712. /// Returns the assumed alignment of a virtual base of a class.
  713. CharUnits getVBaseAlignment(CharUnits DerivedAlign,
  714. const CXXRecordDecl *Derived,
  715. const CXXRecordDecl *VBase);
  716. /// Given a class pointer with an actual known alignment, and the
  717. /// expected alignment of an object at a dynamic offset w.r.t that
  718. /// pointer, return the alignment to assume at the offset.
  719. CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
  720. const CXXRecordDecl *Class,
  721. CharUnits ExpectedTargetAlign);
  722. CharUnits
  723. computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
  724. CastExpr::path_const_iterator Start,
  725. CastExpr::path_const_iterator End);
  726. /// Returns the offset from a derived class to a class. Returns null if the
  727. /// offset is 0.
  728. llvm::Constant *
  729. GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  730. CastExpr::path_const_iterator PathBegin,
  731. CastExpr::path_const_iterator PathEnd);
  732. llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
  733. /// Fetches the global unique block count.
  734. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
  735. /// Fetches the type of a generic block descriptor.
  736. llvm::Type *getBlockDescriptorType();
  737. /// The type of a generic block literal.
  738. llvm::Type *getGenericBlockLiteralType();
  739. /// Gets the address of a block which requires no captures.
  740. llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
  741. /// Returns the address of a block which requires no caputres, or null if
  742. /// we've yet to emit the block for BE.
  743. llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
  744. return EmittedGlobalBlocks.lookup(BE);
  745. }
  746. /// Notes that BE's global block is available via Addr. Asserts that BE
  747. /// isn't already emitted.
  748. void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
  749. /// Return a pointer to a constant CFString object for the given string.
  750. ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
  751. /// Return a pointer to a constant NSString object for the given string. Or a
  752. /// user defined String object as defined via
  753. /// -fconstant-string-class=class_name option.
  754. ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
  755. /// Return a constant array for the given string.
  756. llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
  757. /// Return a pointer to a constant array for the given string literal.
  758. ConstantAddress
  759. GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  760. StringRef Name = ".str");
  761. /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
  762. ConstantAddress
  763. GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
  764. /// Returns a pointer to a character array containing the literal and a
  765. /// terminating '\0' character. The result has pointer to array type.
  766. ///
  767. /// \param GlobalName If provided, the name to use for the global (if one is
  768. /// created).
  769. ConstantAddress
  770. GetAddrOfConstantCString(const std::string &Str,
  771. const char *GlobalName = nullptr);
  772. /// Returns a pointer to a constant global variable for the given file-scope
  773. /// compound literal expression.
  774. ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
  775. /// If it's been emitted already, returns the GlobalVariable corresponding to
  776. /// a compound literal. Otherwise, returns null.
  777. llvm::GlobalVariable *
  778. getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
  779. /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
  780. /// emitted.
  781. void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
  782. llvm::GlobalVariable *GV);
  783. /// Returns a pointer to a global variable representing a temporary
  784. /// with static or thread storage duration.
  785. ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
  786. const Expr *Inner);
  787. /// Retrieve the record type that describes the state of an
  788. /// Objective-C fast enumeration loop (for..in).
  789. QualType getObjCFastEnumerationStateType();
  790. // Produce code for this constructor/destructor. This method doesn't try
  791. // to apply any ABI rules about which other constructors/destructors
  792. // are needed or if they are alias to each other.
  793. llvm::Function *codegenCXXStructor(GlobalDecl GD);
  794. /// Return the address of the constructor/destructor of the given type.
  795. llvm::Constant *
  796. getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
  797. llvm::FunctionType *FnType = nullptr,
  798. bool DontDefer = false,
  799. ForDefinition_t IsForDefinition = NotForDefinition) {
  800. return cast<llvm::Constant>(getAddrAndTypeOfCXXStructor(GD, FnInfo, FnType,
  801. DontDefer,
  802. IsForDefinition)
  803. .getCallee());
  804. }
  805. llvm::FunctionCallee getAddrAndTypeOfCXXStructor(
  806. GlobalDecl GD, const CGFunctionInfo *FnInfo = nullptr,
  807. llvm::FunctionType *FnType = nullptr, bool DontDefer = false,
  808. ForDefinition_t IsForDefinition = NotForDefinition);
  809. /// Given a builtin id for a function like "__builtin_fabsf", return a
  810. /// Function* for "fabsf".
  811. llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
  812. unsigned BuiltinID);
  813. llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
  814. /// Emit code for a single top level declaration.
  815. void EmitTopLevelDecl(Decl *D);
  816. /// Stored a deferred empty coverage mapping for an unused
  817. /// and thus uninstrumented top level declaration.
  818. void AddDeferredUnusedCoverageMapping(Decl *D);
  819. /// Remove the deferred empty coverage mapping as this
  820. /// declaration is actually instrumented.
  821. void ClearUnusedCoverageMapping(const Decl *D);
  822. /// Emit all the deferred coverage mappings
  823. /// for the uninstrumented functions.
  824. void EmitDeferredUnusedCoverageMappings();
  825. /// Emit an alias for "main" if it has no arguments (needed for wasm).
  826. void EmitMainVoidAlias();
  827. /// Tell the consumer that this variable has been instantiated.
  828. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
  829. /// If the declaration has internal linkage but is inside an
  830. /// extern "C" linkage specification, prepare to emit an alias for it
  831. /// to the expected name.
  832. template<typename SomeDecl>
  833. void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
  834. /// Add a global to a list to be added to the llvm.used metadata.
  835. void addUsedGlobal(llvm::GlobalValue *GV);
  836. /// Add a global to a list to be added to the llvm.compiler.used metadata.
  837. void addCompilerUsedGlobal(llvm::GlobalValue *GV);
  838. /// Add a global to a list to be added to the llvm.compiler.used metadata.
  839. void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV);
  840. /// Add a destructor and object to add to the C++ global destructor function.
  841. void AddCXXDtorEntry(llvm::FunctionCallee DtorFn, llvm::Constant *Object) {
  842. CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
  843. DtorFn.getCallee(), Object);
  844. }
  845. /// Add an sterm finalizer to the C++ global cleanup function.
  846. void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn) {
  847. CXXGlobalDtorsOrStermFinalizers.emplace_back(DtorFn.getFunctionType(),
  848. DtorFn.getCallee(), nullptr);
  849. }
  850. /// Add an sterm finalizer to its own llvm.global_dtors entry.
  851. void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer,
  852. int Priority) {
  853. AddGlobalDtor(StermFinalizer, Priority);
  854. }
  855. void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer,
  856. int Priority) {
  857. OrderGlobalInitsOrStermFinalizers Key(Priority,
  858. PrioritizedCXXStermFinalizers.size());
  859. PrioritizedCXXStermFinalizers.push_back(
  860. std::make_pair(Key, StermFinalizer));
  861. }
  862. /// Create or return a runtime function declaration with the specified type
  863. /// and name. If \p AssumeConvergent is true, the call will have the
  864. /// convergent attribute added.
  865. llvm::FunctionCallee
  866. CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
  867. llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
  868. bool Local = false, bool AssumeConvergent = false);
  869. /// Create a new runtime global variable with the specified type and name.
  870. llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
  871. StringRef Name);
  872. ///@name Custom Blocks Runtime Interfaces
  873. ///@{
  874. llvm::Constant *getNSConcreteGlobalBlock();
  875. llvm::Constant *getNSConcreteStackBlock();
  876. llvm::FunctionCallee getBlockObjectAssign();
  877. llvm::FunctionCallee getBlockObjectDispose();
  878. ///@}
  879. llvm::Function *getLLVMLifetimeStartFn();
  880. llvm::Function *getLLVMLifetimeEndFn();
  881. // Make sure that this type is translated.
  882. void UpdateCompletedType(const TagDecl *TD);
  883. llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
  884. /// Emit type info if type of an expression is a variably modified
  885. /// type. Also emit proper debug info for cast types.
  886. void EmitExplicitCastExprType(const ExplicitCastExpr *E,
  887. CodeGenFunction *CGF = nullptr);
  888. /// Return the result of value-initializing the given type, i.e. a null
  889. /// expression of the given type. This is usually, but not always, an LLVM
  890. /// null constant.
  891. llvm::Constant *EmitNullConstant(QualType T);
  892. /// Return a null constant appropriate for zero-initializing a base class with
  893. /// the given type. This is usually, but not always, an LLVM null constant.
  894. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  895. /// Emit a general error that something can't be done.
  896. void Error(SourceLocation loc, StringRef error);
  897. /// Print out an error that codegen doesn't support the specified stmt yet.
  898. void ErrorUnsupported(const Stmt *S, const char *Type);
  899. /// Print out an error that codegen doesn't support the specified decl yet.
  900. void ErrorUnsupported(const Decl *D, const char *Type);
  901. /// Set the attributes on the LLVM function for the given decl and function
  902. /// info. This applies attributes necessary for handling the ABI as well as
  903. /// user specified attributes like section.
  904. void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  905. const CGFunctionInfo &FI);
  906. /// Set the LLVM function attributes (sext, zext, etc).
  907. void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
  908. llvm::Function *F, bool IsThunk);
  909. /// Set the LLVM function attributes which only apply to a function
  910. /// definition.
  911. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  912. /// Set the LLVM function attributes that represent floating point
  913. /// environment.
  914. void setLLVMFunctionFEnvAttributes(const FunctionDecl *D, llvm::Function *F);
  915. /// Return true iff the given type uses 'sret' when used as a return type.
  916. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  917. /// Return true iff the given type uses an argument slot when 'sret' is used
  918. /// as a return type.
  919. bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
  920. /// Return true iff the given type uses 'fpret' when used as a return type.
  921. bool ReturnTypeUsesFPRet(QualType ResultType);
  922. /// Return true iff the given type uses 'fp2ret' when used as a return type.
  923. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  924. /// Get the LLVM attributes and calling convention to use for a particular
  925. /// function type.
  926. ///
  927. /// \param Name - The function name.
  928. /// \param Info - The function type information.
  929. /// \param CalleeInfo - The callee information these attributes are being
  930. /// constructed for. If valid, the attributes applied to this decl may
  931. /// contribute to the function attributes and calling convention.
  932. /// \param Attrs [out] - On return, the attribute list to use.
  933. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  934. void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
  935. CGCalleeInfo CalleeInfo,
  936. llvm::AttributeList &Attrs, unsigned &CallingConv,
  937. bool AttrOnCallSite, bool IsThunk);
  938. /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
  939. /// though we had emitted it ourselves. We remove any attributes on F that
  940. /// conflict with the attributes we add here.
  941. ///
  942. /// This is useful for adding attrs to bitcode modules that you want to link
  943. /// with but don't control, such as CUDA's libdevice. When linking with such
  944. /// a bitcode library, you might want to set e.g. its functions'
  945. /// "unsafe-fp-math" attribute to match the attr of the functions you're
  946. /// codegen'ing. Otherwise, LLVM will interpret the bitcode module's lack of
  947. /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
  948. /// will propagate unsafe-fp-math=false up to every transitive caller of a
  949. /// function in the bitcode library!
  950. ///
  951. /// With the exception of fast-math attrs, this will only make the attributes
  952. /// on the function more conservative. But it's unsafe to call this on a
  953. /// function which relies on particular fast-math attributes for correctness.
  954. /// It's up to you to ensure that this is safe.
  955. void addDefaultFunctionDefinitionAttributes(llvm::Function &F);
  956. /// Like the overload taking a `Function &`, but intended specifically
  957. /// for frontends that want to build on Clang's target-configuration logic.
  958. void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs);
  959. StringRef getMangledName(GlobalDecl GD);
  960. StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
  961. void EmitTentativeDefinition(const VarDecl *D);
  962. void EmitExternalDeclaration(const VarDecl *D);
  963. void EmitVTable(CXXRecordDecl *Class);
  964. void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
  965. /// Appends Opts to the "llvm.linker.options" metadata value.
  966. void AppendLinkerOptions(StringRef Opts);
  967. /// Appends a detect mismatch command to the linker options.
  968. void AddDetectMismatch(StringRef Name, StringRef Value);
  969. /// Appends a dependent lib to the appropriate metadata value.
  970. void AddDependentLib(StringRef Lib);
  971. llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
  972. void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
  973. F->setLinkage(getFunctionLinkage(GD));
  974. }
  975. /// Return the appropriate linkage for the vtable, VTT, and type information
  976. /// of the given class.
  977. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  978. /// Return the store size, in character units, of the given LLVM type.
  979. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  980. /// Returns LLVM linkage for a declarator.
  981. llvm::GlobalValue::LinkageTypes
  982. getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
  983. bool IsConstantVariable);
  984. /// Returns LLVM linkage for a declarator.
  985. llvm::GlobalValue::LinkageTypes
  986. getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
  987. /// Emit all the global annotations.
  988. void EmitGlobalAnnotations();
  989. /// Emit an annotation string.
  990. llvm::Constant *EmitAnnotationString(StringRef Str);
  991. /// Emit the annotation's translation unit.
  992. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  993. /// Emit the annotation line number.
  994. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  995. /// Emit additional args of the annotation.
  996. llvm::Constant *EmitAnnotationArgs(const AnnotateAttr *Attr);
  997. /// Generate the llvm::ConstantStruct which contains the annotation
  998. /// information for a given GlobalValue. The annotation struct is
  999. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  1000. /// GlobalValue being annotated. The second field is the constant string
  1001. /// created from the AnnotateAttr's annotation. The third field is a constant
  1002. /// string containing the name of the translation unit. The fourth field is
  1003. /// the line number in the file of the annotated value declaration.
  1004. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  1005. const AnnotateAttr *AA,
  1006. SourceLocation L);
  1007. /// Add global annotations that are set on D, for the global GV. Those
  1008. /// annotations are emitted during finalization of the LLVM code.
  1009. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  1010. bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
  1011. SourceLocation Loc) const;
  1012. bool isInNoSanitizeList(llvm::GlobalVariable *GV, SourceLocation Loc,
  1013. QualType Ty, StringRef Category = StringRef()) const;
  1014. /// Imbue XRay attributes to a function, applying the always/never attribute
  1015. /// lists in the process. Returns true if we did imbue attributes this way,
  1016. /// false otherwise.
  1017. bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1018. StringRef Category = StringRef()) const;
  1019. /// Returns true if function at the given location should be excluded from
  1020. /// profile instrumentation.
  1021. bool isProfileInstrExcluded(llvm::Function *Fn, SourceLocation Loc) const;
  1022. SanitizerMetadata *getSanitizerMetadata() {
  1023. return SanitizerMD.get();
  1024. }
  1025. void addDeferredVTable(const CXXRecordDecl *RD) {
  1026. DeferredVTables.push_back(RD);
  1027. }
  1028. /// Emit code for a single global function or var decl. Forward declarations
  1029. /// are emitted lazily.
  1030. void EmitGlobal(GlobalDecl D);
  1031. bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
  1032. llvm::GlobalValue *GetGlobalValue(StringRef Ref);
  1033. /// Set attributes which are common to any form of a global definition (alias,
  1034. /// Objective-C method, function, global variable).
  1035. ///
  1036. /// NOTE: This should only be called for definitions.
  1037. void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
  1038. void addReplacement(StringRef Name, llvm::Constant *C);
  1039. void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
  1040. /// Emit a code for threadprivate directive.
  1041. /// \param D Threadprivate declaration.
  1042. void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
  1043. /// Emit a code for declare reduction construct.
  1044. void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1045. CodeGenFunction *CGF = nullptr);
  1046. /// Emit a code for declare mapper construct.
  1047. void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
  1048. CodeGenFunction *CGF = nullptr);
  1049. /// Emit a code for requires directive.
  1050. /// \param D Requires declaration
  1051. void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
  1052. /// Emit a code for the allocate directive.
  1053. /// \param D The allocate declaration
  1054. void EmitOMPAllocateDecl(const OMPAllocateDecl *D);
  1055. /// Returns whether the given record has hidden LTO visibility and therefore
  1056. /// may participate in (single-module) CFI and whole-program vtable
  1057. /// optimization.
  1058. bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
  1059. /// Returns whether the given record has public std LTO visibility
  1060. /// and therefore may not participate in (single-module) CFI and whole-program
  1061. /// vtable optimization.
  1062. bool HasLTOVisibilityPublicStd(const CXXRecordDecl *RD);
  1063. /// Returns the vcall visibility of the given type. This is the scope in which
  1064. /// a virtual function call could be made which ends up being dispatched to a
  1065. /// member function of this class. This scope can be wider than the visibility
  1066. /// of the class itself when the class has a more-visible dynamic base class.
  1067. /// The client should pass in an empty Visited set, which is used to prevent
  1068. /// redundant recursive processing.
  1069. llvm::GlobalObject::VCallVisibility
  1070. GetVCallVisibilityLevel(const CXXRecordDecl *RD,
  1071. llvm::DenseSet<const CXXRecordDecl *> &Visited);
  1072. /// Emit type metadata for the given vtable using the given layout.
  1073. void EmitVTableTypeMetadata(const CXXRecordDecl *RD,
  1074. llvm::GlobalVariable *VTable,
  1075. const VTableLayout &VTLayout);
  1076. /// Generate a cross-DSO type identifier for MD.
  1077. llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
  1078. /// Create a metadata identifier for the given type. This may either be an
  1079. /// MDString (for external identifiers) or a distinct unnamed MDNode (for
  1080. /// internal identifiers).
  1081. llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
  1082. /// Create a metadata identifier that is intended to be used to check virtual
  1083. /// calls via a member function pointer.
  1084. llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
  1085. /// Create a metadata identifier for the generalization of the given type.
  1086. /// This may either be an MDString (for external identifiers) or a distinct
  1087. /// unnamed MDNode (for internal identifiers).
  1088. llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
  1089. /// Create and attach type metadata to the given function.
  1090. void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
  1091. llvm::Function *F);
  1092. /// Whether this function's return type has no side effects, and thus may
  1093. /// be trivially discarded if it is unused.
  1094. bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType);
  1095. /// Returns whether this module needs the "all-vtables" type identifier.
  1096. bool NeedAllVtablesTypeId() const;
  1097. /// Create and attach type metadata for the given vtable.
  1098. void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
  1099. const CXXRecordDecl *RD);
  1100. /// Return a vector of most-base classes for RD. This is used to implement
  1101. /// control flow integrity checks for member function pointers.
  1102. ///
  1103. /// A most-base class of a class C is defined as a recursive base class of C,
  1104. /// including C itself, that does not have any bases.
  1105. std::vector<const CXXRecordDecl *>
  1106. getMostBaseClasses(const CXXRecordDecl *RD);
  1107. /// Get the declaration of std::terminate for the platform.
  1108. llvm::FunctionCallee getTerminateFn();
  1109. llvm::SanitizerStatReport &getSanStats();
  1110. llvm::Value *
  1111. createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
  1112. /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  1113. /// information in the program executable. The argument information stored
  1114. /// includes the argument name, its type, the address and access qualifiers
  1115. /// used. This helper can be used to generate metadata for source code kernel
  1116. /// function as well as generated implicitly kernels. If a kernel is generated
  1117. /// implicitly null value has to be passed to the last two parameters,
  1118. /// otherwise all parameters must have valid non-null values.
  1119. /// \param FN is a pointer to IR function being generated.
  1120. /// \param FD is a pointer to function declaration if any.
  1121. /// \param CGF is a pointer to CodeGenFunction that generates this function.
  1122. void GenOpenCLArgMetadata(llvm::Function *FN,
  1123. const FunctionDecl *FD = nullptr,
  1124. CodeGenFunction *CGF = nullptr);
  1125. /// Get target specific null pointer.
  1126. /// \param T is the LLVM type of the null pointer.
  1127. /// \param QT is the clang QualType of the null pointer.
  1128. llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
  1129. CharUnits getNaturalTypeAlignment(QualType T,
  1130. LValueBaseInfo *BaseInfo = nullptr,
  1131. TBAAAccessInfo *TBAAInfo = nullptr,
  1132. bool forPointeeType = false);
  1133. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1134. LValueBaseInfo *BaseInfo = nullptr,
  1135. TBAAAccessInfo *TBAAInfo = nullptr);
  1136. bool stopAutoInit();
  1137. /// Print the postfix for externalized static variable or kernels for single
  1138. /// source offloading languages CUDA and HIP.
  1139. void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
  1140. const Decl *D) const;
  1141. private:
  1142. llvm::Constant *GetOrCreateLLVMFunction(
  1143. StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
  1144. bool DontDefer = false, bool IsThunk = false,
  1145. llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
  1146. ForDefinition_t IsForDefinition = NotForDefinition);
  1147. llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
  1148. llvm::Type *DeclTy,
  1149. const FunctionDecl *FD);
  1150. void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD,
  1151. StringRef &CurName);
  1152. llvm::Constant *
  1153. GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace,
  1154. const VarDecl *D,
  1155. ForDefinition_t IsForDefinition = NotForDefinition);
  1156. bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
  1157. llvm::AttrBuilder &AttrBuilder);
  1158. void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
  1159. /// Set function attributes for a function declaration.
  1160. void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1161. bool IsIncompleteFunction, bool IsThunk);
  1162. void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
  1163. void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  1164. void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
  1165. void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
  1166. void EmitExternalVarDeclaration(const VarDecl *D);
  1167. void EmitAliasDefinition(GlobalDecl GD);
  1168. void emitIFuncDefinition(GlobalDecl GD);
  1169. void emitCPUDispatchDefinition(GlobalDecl GD);
  1170. void EmitTargetClonesResolver(GlobalDecl GD);
  1171. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  1172. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  1173. // C++ related functions.
  1174. void EmitDeclContext(const DeclContext *DC);
  1175. void EmitLinkageSpec(const LinkageSpecDecl *D);
  1176. /// Emit the function that initializes C++ thread_local variables.
  1177. void EmitCXXThreadLocalInitFunc();
  1178. /// Emit the function that initializes C++ globals.
  1179. void EmitCXXGlobalInitFunc();
  1180. /// Emit the function that performs cleanup associated with C++ globals.
  1181. void EmitCXXGlobalCleanUpFunc();
  1182. /// Emit the function that initializes the specified global (if PerformInit is
  1183. /// true) and registers its destructor.
  1184. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  1185. llvm::GlobalVariable *Addr,
  1186. bool PerformInit);
  1187. void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
  1188. llvm::Function *InitFunc, InitSegAttr *ISA);
  1189. // FIXME: Hardcoding priority here is gross.
  1190. void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
  1191. llvm::Constant *AssociatedData = nullptr);
  1192. void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
  1193. bool IsDtorAttrFunc = false);
  1194. /// EmitCtorList - Generates a global array of functions and priorities using
  1195. /// the given list and name. This array will have appending linkage and is
  1196. /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
  1197. void EmitCtorList(CtorList &Fns, const char *GlobalName);
  1198. /// Emit any needed decls for which code generation was deferred.
  1199. void EmitDeferred();
  1200. /// Try to emit external vtables as available_externally if they have emitted
  1201. /// all inlined virtual functions. It runs after EmitDeferred() and therefore
  1202. /// is not allowed to create new references to things that need to be emitted
  1203. /// lazily.
  1204. void EmitVTablesOpportunistically();
  1205. /// Call replaceAllUsesWith on all pairs in Replacements.
  1206. void applyReplacements();
  1207. /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
  1208. void applyGlobalValReplacements();
  1209. void checkAliases();
  1210. std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
  1211. /// Register functions annotated with __attribute__((destructor)) using
  1212. /// __cxa_atexit, if it is available, or atexit otherwise.
  1213. void registerGlobalDtorsWithAtExit();
  1214. // When using sinit and sterm functions, unregister
  1215. // __attribute__((destructor)) annotated functions which were previously
  1216. // registered by the atexit subroutine using unatexit.
  1217. void unregisterGlobalDtorsWithUnAtExit();
  1218. void emitMultiVersionFunctions();
  1219. /// Emit any vtables which we deferred and still have a use for.
  1220. void EmitDeferredVTables();
  1221. /// Emit a dummy function that reference a CoreFoundation symbol when
  1222. /// @available is used on Darwin.
  1223. void emitAtAvailableLinkGuard();
  1224. /// Emit the llvm.used and llvm.compiler.used metadata.
  1225. void emitLLVMUsed();
  1226. /// Emit the link options introduced by imported modules.
  1227. void EmitModuleLinkOptions();
  1228. /// Emit aliases for internal-linkage declarations inside "C" language
  1229. /// linkage specifications, giving them the "expected" name where possible.
  1230. void EmitStaticExternCAliases();
  1231. void EmitDeclMetadata();
  1232. /// Emit the Clang version as llvm.ident metadata.
  1233. void EmitVersionIdentMetadata();
  1234. /// Emit the Clang commandline as llvm.commandline metadata.
  1235. void EmitCommandLineMetadata();
  1236. /// Emit the module flag metadata used to pass options controlling the
  1237. /// the backend to LLVM.
  1238. void EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts);
  1239. /// Emits OpenCL specific Metadata e.g. OpenCL version.
  1240. void EmitOpenCLMetadata();
  1241. /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
  1242. /// .gcda files in a way that persists in .bc files.
  1243. void EmitCoverageFile();
  1244. /// Determine whether the definition must be emitted; if this returns \c
  1245. /// false, the definition can be emitted lazily if it's used.
  1246. bool MustBeEmitted(const ValueDecl *D);
  1247. /// Determine whether the definition can be emitted eagerly, or should be
  1248. /// delayed until the end of the translation unit. This is relevant for
  1249. /// definitions whose linkage can change, e.g. implicit function instantions
  1250. /// which may later be explicitly instantiated.
  1251. bool MayBeEmittedEagerly(const ValueDecl *D);
  1252. /// Check whether we can use a "simpler", more core exceptions personality
  1253. /// function.
  1254. void SimplifyPersonality();
  1255. /// Helper function for ConstructAttributeList and
  1256. /// addDefaultFunctionDefinitionAttributes. Builds a set of function
  1257. /// attributes to add to a function with the given properties.
  1258. void getDefaultFunctionAttributes(StringRef Name, bool HasOptnone,
  1259. bool AttrOnCallSite,
  1260. llvm::AttrBuilder &FuncAttrs);
  1261. llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
  1262. StringRef Suffix);
  1263. };
  1264. } // end namespace CodeGen
  1265. } // end namespace clang
  1266. #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H