CodeGenModule.h 56 KB

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