CodeGenModule.h 55 KB

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