CodeGenModule.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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 CLANG_CODEGEN_CODEGENMODULE_H
  14. #define CLANG_CODEGEN_CODEGENMODULE_H
  15. #include "CGVTables.h"
  16. #include "CodeGenTypes.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/GlobalDecl.h"
  21. #include "clang/AST/Mangle.h"
  22. #include "clang/Basic/ABI.h"
  23. #include "clang/Basic/LangOptions.h"
  24. #include "clang/Basic/Module.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/SetVector.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/StringMap.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/Support/ValueHandle.h"
  31. #include "llvm/Transforms/Utils/BlackList.h"
  32. namespace llvm {
  33. class Module;
  34. class Constant;
  35. class ConstantInt;
  36. class Function;
  37. class GlobalValue;
  38. class DataLayout;
  39. class FunctionType;
  40. class LLVMContext;
  41. }
  42. namespace clang {
  43. class TargetCodeGenInfo;
  44. class ASTContext;
  45. class FunctionDecl;
  46. class IdentifierInfo;
  47. class ObjCMethodDecl;
  48. class ObjCImplementationDecl;
  49. class ObjCCategoryImplDecl;
  50. class ObjCProtocolDecl;
  51. class ObjCEncodeExpr;
  52. class BlockExpr;
  53. class CharUnits;
  54. class Decl;
  55. class Expr;
  56. class Stmt;
  57. class InitListExpr;
  58. class StringLiteral;
  59. class NamedDecl;
  60. class ValueDecl;
  61. class VarDecl;
  62. class LangOptions;
  63. class CodeGenOptions;
  64. class DiagnosticsEngine;
  65. class AnnotateAttr;
  66. class CXXDestructorDecl;
  67. class MangleBuffer;
  68. class Module;
  69. namespace CodeGen {
  70. class CallArgList;
  71. class CodeGenFunction;
  72. class CodeGenTBAA;
  73. class CGCXXABI;
  74. class CGDebugInfo;
  75. class CGObjCRuntime;
  76. class CGOpenCLRuntime;
  77. class CGCUDARuntime;
  78. class BlockFieldFlags;
  79. class FunctionArgList;
  80. struct OrderGlobalInits {
  81. unsigned int priority;
  82. unsigned int lex_order;
  83. OrderGlobalInits(unsigned int p, unsigned int l)
  84. : priority(p), lex_order(l) {}
  85. bool operator==(const OrderGlobalInits &RHS) const {
  86. return priority == RHS.priority &&
  87. lex_order == RHS.lex_order;
  88. }
  89. bool operator<(const OrderGlobalInits &RHS) const {
  90. if (priority < RHS.priority)
  91. return true;
  92. return priority == RHS.priority && lex_order < RHS.lex_order;
  93. }
  94. };
  95. struct CodeGenTypeCache {
  96. /// void
  97. llvm::Type *VoidTy;
  98. /// i8, i16, i32, and i64
  99. llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
  100. /// float, double
  101. llvm::Type *FloatTy, *DoubleTy;
  102. /// int
  103. llvm::IntegerType *IntTy;
  104. /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
  105. union {
  106. llvm::IntegerType *IntPtrTy;
  107. llvm::IntegerType *SizeTy;
  108. llvm::IntegerType *PtrDiffTy;
  109. };
  110. /// void* in address space 0
  111. union {
  112. llvm::PointerType *VoidPtrTy;
  113. llvm::PointerType *Int8PtrTy;
  114. };
  115. /// void** in address space 0
  116. union {
  117. llvm::PointerType *VoidPtrPtrTy;
  118. llvm::PointerType *Int8PtrPtrTy;
  119. };
  120. /// The width of a pointer into the generic address space.
  121. unsigned char PointerWidthInBits;
  122. /// The size and alignment of a pointer into the generic address
  123. /// space.
  124. union {
  125. unsigned char PointerAlignInBytes;
  126. unsigned char PointerSizeInBytes;
  127. unsigned char SizeSizeInBytes; // sizeof(size_t)
  128. };
  129. };
  130. struct RREntrypoints {
  131. RREntrypoints() { memset(this, 0, sizeof(*this)); }
  132. /// void objc_autoreleasePoolPop(void*);
  133. llvm::Constant *objc_autoreleasePoolPop;
  134. /// void *objc_autoreleasePoolPush(void);
  135. llvm::Constant *objc_autoreleasePoolPush;
  136. };
  137. struct ARCEntrypoints {
  138. ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
  139. /// id objc_autorelease(id);
  140. llvm::Constant *objc_autorelease;
  141. /// id objc_autoreleaseReturnValue(id);
  142. llvm::Constant *objc_autoreleaseReturnValue;
  143. /// void objc_copyWeak(id *dest, id *src);
  144. llvm::Constant *objc_copyWeak;
  145. /// void objc_destroyWeak(id*);
  146. llvm::Constant *objc_destroyWeak;
  147. /// id objc_initWeak(id*, id);
  148. llvm::Constant *objc_initWeak;
  149. /// id objc_loadWeak(id*);
  150. llvm::Constant *objc_loadWeak;
  151. /// id objc_loadWeakRetained(id*);
  152. llvm::Constant *objc_loadWeakRetained;
  153. /// void objc_moveWeak(id *dest, id *src);
  154. llvm::Constant *objc_moveWeak;
  155. /// id objc_retain(id);
  156. llvm::Constant *objc_retain;
  157. /// id objc_retainAutorelease(id);
  158. llvm::Constant *objc_retainAutorelease;
  159. /// id objc_retainAutoreleaseReturnValue(id);
  160. llvm::Constant *objc_retainAutoreleaseReturnValue;
  161. /// id objc_retainAutoreleasedReturnValue(id);
  162. llvm::Constant *objc_retainAutoreleasedReturnValue;
  163. /// id objc_retainBlock(id);
  164. llvm::Constant *objc_retainBlock;
  165. /// void objc_release(id);
  166. llvm::Constant *objc_release;
  167. /// id objc_storeStrong(id*, id);
  168. llvm::Constant *objc_storeStrong;
  169. /// id objc_storeWeak(id*, id);
  170. llvm::Constant *objc_storeWeak;
  171. /// A void(void) inline asm to use to mark that the return value of
  172. /// a call will be immediately retain.
  173. llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
  174. };
  175. /// CodeGenModule - This class organizes the cross-function state that is used
  176. /// while generating LLVM code.
  177. class CodeGenModule : public CodeGenTypeCache {
  178. CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
  179. void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
  180. typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
  181. ASTContext &Context;
  182. const LangOptions &LangOpts;
  183. const CodeGenOptions &CodeGenOpts;
  184. llvm::Module &TheModule;
  185. const llvm::DataLayout &TheDataLayout;
  186. mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
  187. DiagnosticsEngine &Diags;
  188. CGCXXABI &ABI;
  189. CodeGenTypes Types;
  190. CodeGenTBAA *TBAA;
  191. /// VTables - Holds information about C++ vtables.
  192. CodeGenVTables VTables;
  193. friend class CodeGenVTables;
  194. CGObjCRuntime* ObjCRuntime;
  195. CGOpenCLRuntime* OpenCLRuntime;
  196. CGCUDARuntime* CUDARuntime;
  197. CGDebugInfo* DebugInfo;
  198. ARCEntrypoints *ARCData;
  199. llvm::MDNode *NoObjCARCExceptionsMetadata;
  200. RREntrypoints *RRData;
  201. // WeakRefReferences - A set of references that have only been seen via
  202. // a weakref so far. This is used to remove the weak of the reference if we ever
  203. // see a direct reference or a definition.
  204. llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
  205. /// DeferredDecls - This contains all the decls which have definitions but
  206. /// which are deferred for emission and therefore should only be output if
  207. /// they are actually used. If a decl is in this, then it is known to have
  208. /// not been referenced yet.
  209. llvm::StringMap<GlobalDecl> DeferredDecls;
  210. /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
  211. /// that *are* actually referenced. These get code generated when the module
  212. /// is done.
  213. std::vector<GlobalDecl> DeferredDeclsToEmit;
  214. /// LLVMUsed - List of global values which are required to be
  215. /// present in the object file; bitcast to i8*. This is used for
  216. /// forcing visibility of symbols which may otherwise be optimized
  217. /// out.
  218. std::vector<llvm::WeakVH> LLVMUsed;
  219. /// GlobalCtors - Store the list of global constructors and their respective
  220. /// priorities to be emitted when the translation unit is complete.
  221. CtorList GlobalCtors;
  222. /// GlobalDtors - Store the list of global destructors and their respective
  223. /// priorities to be emitted when the translation unit is complete.
  224. CtorList GlobalDtors;
  225. /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
  226. llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
  227. llvm::BumpPtrAllocator MangledNamesAllocator;
  228. /// Global annotations.
  229. std::vector<llvm::Constant*> Annotations;
  230. /// Map used to get unique annotation strings.
  231. llvm::StringMap<llvm::Constant*> AnnotationStrings;
  232. llvm::StringMap<llvm::Constant*> CFConstantStringMap;
  233. llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
  234. llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
  235. llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
  236. llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
  237. llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
  238. /// CXXGlobalInits - Global variables with initializers that need to run
  239. /// before main.
  240. std::vector<llvm::Constant*> CXXGlobalInits;
  241. /// When a C++ decl with an initializer is deferred, null is
  242. /// appended to CXXGlobalInits, and the index of that null is placed
  243. /// here so that the initializer will be performed in the correct
  244. /// order.
  245. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
  246. typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
  247. struct GlobalInitPriorityCmp {
  248. bool operator()(const GlobalInitData &LHS,
  249. const GlobalInitData &RHS) const {
  250. return LHS.first.priority < RHS.first.priority;
  251. }
  252. };
  253. /// - Global variables with initializers whose order of initialization
  254. /// is set by init_priority attribute.
  255. SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
  256. /// CXXGlobalDtors - Global destructor functions and arguments that need to
  257. /// run on termination.
  258. std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
  259. /// \brief The complete set of modules that has been imported.
  260. llvm::SetVector<clang::Module *> ImportedModules;
  261. /// @name Cache for Objective-C runtime types
  262. /// @{
  263. /// CFConstantStringClassRef - Cached reference to the class for constant
  264. /// strings. This value has type int * but is actually an Obj-C class pointer.
  265. llvm::Constant *CFConstantStringClassRef;
  266. /// ConstantStringClassRef - Cached reference to the class for constant
  267. /// strings. This value has type int * but is actually an Obj-C class pointer.
  268. llvm::Constant *ConstantStringClassRef;
  269. /// \brief The LLVM type corresponding to NSConstantString.
  270. llvm::StructType *NSConstantStringType;
  271. /// \brief The type used to describe the state of a fast enumeration in
  272. /// Objective-C's for..in loop.
  273. QualType ObjCFastEnumerationStateType;
  274. /// @}
  275. /// Lazily create the Objective-C runtime
  276. void createObjCRuntime();
  277. void createOpenCLRuntime();
  278. void createCUDARuntime();
  279. bool isTriviallyRecursive(const FunctionDecl *F);
  280. bool shouldEmitFunction(const FunctionDecl *F);
  281. llvm::LLVMContext &VMContext;
  282. /// @name Cache for Blocks Runtime Globals
  283. /// @{
  284. llvm::Constant *NSConcreteGlobalBlock;
  285. llvm::Constant *NSConcreteStackBlock;
  286. llvm::Constant *BlockObjectAssign;
  287. llvm::Constant *BlockObjectDispose;
  288. llvm::Type *BlockDescriptorType;
  289. llvm::Type *GenericBlockLiteralType;
  290. struct {
  291. int GlobalUniqueCount;
  292. } Block;
  293. GlobalDecl initializedGlobalDecl;
  294. llvm::BlackList SanitizerBlacklist;
  295. const SanitizerOptions &SanOpts;
  296. /// @}
  297. public:
  298. CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
  299. llvm::Module &M, const llvm::DataLayout &TD,
  300. DiagnosticsEngine &Diags);
  301. ~CodeGenModule();
  302. /// Release - Finalize LLVM code generation.
  303. void Release();
  304. /// getObjCRuntime() - Return a reference to the configured
  305. /// Objective-C runtime.
  306. CGObjCRuntime &getObjCRuntime() {
  307. if (!ObjCRuntime) createObjCRuntime();
  308. return *ObjCRuntime;
  309. }
  310. /// hasObjCRuntime() - Return true iff an Objective-C runtime has
  311. /// been configured.
  312. bool hasObjCRuntime() { return !!ObjCRuntime; }
  313. /// getOpenCLRuntime() - Return a reference to the configured OpenCL runtime.
  314. CGOpenCLRuntime &getOpenCLRuntime() {
  315. assert(OpenCLRuntime != 0);
  316. return *OpenCLRuntime;
  317. }
  318. /// getCUDARuntime() - Return a reference to the configured CUDA runtime.
  319. CGCUDARuntime &getCUDARuntime() {
  320. assert(CUDARuntime != 0);
  321. return *CUDARuntime;
  322. }
  323. /// getCXXABI() - Return a reference to the configured C++ ABI.
  324. CGCXXABI &getCXXABI() { return ABI; }
  325. ARCEntrypoints &getARCEntrypoints() const {
  326. assert(getLangOpts().ObjCAutoRefCount && ARCData != 0);
  327. return *ARCData;
  328. }
  329. RREntrypoints &getRREntrypoints() const {
  330. assert(RRData != 0);
  331. return *RRData;
  332. }
  333. llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
  334. return StaticLocalDeclMap[D];
  335. }
  336. void setStaticLocalDeclAddress(const VarDecl *D,
  337. llvm::Constant *C) {
  338. StaticLocalDeclMap[D] = C;
  339. }
  340. llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
  341. return StaticLocalDeclGuardMap[D];
  342. }
  343. void setStaticLocalDeclGuardAddress(const VarDecl *D,
  344. llvm::GlobalVariable *C) {
  345. StaticLocalDeclGuardMap[D] = C;
  346. }
  347. llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
  348. return AtomicSetterHelperFnMap[Ty];
  349. }
  350. void setAtomicSetterHelperFnMap(QualType Ty,
  351. llvm::Constant *Fn) {
  352. AtomicSetterHelperFnMap[Ty] = Fn;
  353. }
  354. llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
  355. return AtomicGetterHelperFnMap[Ty];
  356. }
  357. void setAtomicGetterHelperFnMap(QualType Ty,
  358. llvm::Constant *Fn) {
  359. AtomicGetterHelperFnMap[Ty] = Fn;
  360. }
  361. CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
  362. llvm::MDNode *getNoObjCARCExceptionsMetadata() {
  363. if (!NoObjCARCExceptionsMetadata)
  364. NoObjCARCExceptionsMetadata =
  365. llvm::MDNode::get(getLLVMContext(),
  366. SmallVector<llvm::Value*,1>());
  367. return NoObjCARCExceptionsMetadata;
  368. }
  369. ASTContext &getContext() const { return Context; }
  370. const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
  371. const LangOptions &getLangOpts() const { return LangOpts; }
  372. llvm::Module &getModule() const { return TheModule; }
  373. CodeGenTypes &getTypes() { return Types; }
  374. CodeGenVTables &getVTables() { return VTables; }
  375. VTableContext &getVTableContext() { return VTables.getVTableContext(); }
  376. DiagnosticsEngine &getDiags() const { return Diags; }
  377. const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
  378. const TargetInfo &getTarget() const { return Context.getTargetInfo(); }
  379. llvm::LLVMContext &getLLVMContext() { return VMContext; }
  380. const TargetCodeGenInfo &getTargetCodeGenInfo();
  381. bool isTargetDarwin() const;
  382. bool shouldUseTBAA() const { return TBAA != 0; }
  383. llvm::MDNode *getTBAAInfo(QualType QTy);
  384. llvm::MDNode *getTBAAInfoForVTablePtr();
  385. llvm::MDNode *getTBAAStructInfo(QualType QTy);
  386. bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
  387. static void DecorateInstruction(llvm::Instruction *Inst,
  388. llvm::MDNode *TBAAInfo);
  389. /// getSize - Emit the given number of characters as a value of type size_t.
  390. llvm::ConstantInt *getSize(CharUnits numChars);
  391. /// setGlobalVisibility - Set the visibility for the given LLVM
  392. /// GlobalValue.
  393. void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
  394. /// setTLSMode - Set the TLS mode for the given LLVM GlobalVariable
  395. /// for the thread-local variable declaration D.
  396. void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
  397. /// TypeVisibilityKind - The kind of global variable that is passed to
  398. /// setTypeVisibility
  399. enum TypeVisibilityKind {
  400. TVK_ForVTT,
  401. TVK_ForVTable,
  402. TVK_ForConstructionVTable,
  403. TVK_ForRTTI,
  404. TVK_ForRTTIName
  405. };
  406. /// setTypeVisibility - Set the visibility for the given global
  407. /// value which holds information about a type.
  408. void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
  409. TypeVisibilityKind TVK) const;
  410. static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
  411. switch (V) {
  412. case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
  413. case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
  414. case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
  415. }
  416. llvm_unreachable("unknown visibility!");
  417. }
  418. llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
  419. if (isa<CXXConstructorDecl>(GD.getDecl()))
  420. return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
  421. GD.getCtorType());
  422. else if (isa<CXXDestructorDecl>(GD.getDecl()))
  423. return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
  424. GD.getDtorType());
  425. else if (isa<FunctionDecl>(GD.getDecl()))
  426. return GetAddrOfFunction(GD);
  427. else
  428. return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
  429. }
  430. /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given
  431. /// type. If a variable with a different type already exists then a new
  432. /// variable with the right type will be created and all uses of the old
  433. /// variable will be replaced with a bitcast to the new variable.
  434. llvm::GlobalVariable *
  435. CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
  436. llvm::GlobalValue::LinkageTypes Linkage);
  437. /// GetGlobalVarAddressSpace - Return the address space of the underlying
  438. /// global variable for D, as determined by its declaration. Normally this
  439. /// is the same as the address space of D's type, but in CUDA, address spaces
  440. /// are associated with declarations, not types.
  441. unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
  442. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  443. /// given global variable. If Ty is non-null and if the global doesn't exist,
  444. /// then it will be greated with the specified type instead of whatever the
  445. /// normal requested type would be.
  446. llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
  447. llvm::Type *Ty = 0);
  448. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  449. /// non-null, then this function will use the specified type if it has to
  450. /// create it.
  451. llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
  452. llvm::Type *Ty = 0,
  453. bool ForVTable = false);
  454. /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
  455. /// for the given type.
  456. llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
  457. /// GetAddrOfUuidDescriptor - Get the address of a uuid descriptor .
  458. llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
  459. /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
  460. llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
  461. /// GetWeakRefReference - Get a reference to the target of VD.
  462. llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
  463. /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
  464. /// a class. Returns null if the offset is 0.
  465. llvm::Constant *
  466. GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  467. CastExpr::path_const_iterator PathBegin,
  468. CastExpr::path_const_iterator PathEnd);
  469. /// A pair of helper functions for a __block variable.
  470. class ByrefHelpers : public llvm::FoldingSetNode {
  471. public:
  472. llvm::Constant *CopyHelper;
  473. llvm::Constant *DisposeHelper;
  474. /// The alignment of the field. This is important because
  475. /// different offsets to the field within the byref struct need to
  476. /// have different helper functions.
  477. CharUnits Alignment;
  478. ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
  479. virtual ~ByrefHelpers();
  480. void Profile(llvm::FoldingSetNodeID &id) const {
  481. id.AddInteger(Alignment.getQuantity());
  482. profileImpl(id);
  483. }
  484. virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
  485. virtual bool needsCopy() const { return true; }
  486. virtual void emitCopy(CodeGenFunction &CGF,
  487. llvm::Value *dest, llvm::Value *src) = 0;
  488. virtual bool needsDispose() const { return true; }
  489. virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
  490. };
  491. llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
  492. /// getUniqueBlockCount - Fetches the global unique block count.
  493. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
  494. /// getBlockDescriptorType - Fetches the type of a generic block
  495. /// descriptor.
  496. llvm::Type *getBlockDescriptorType();
  497. /// getGenericBlockLiteralType - The type of a generic block literal.
  498. llvm::Type *getGenericBlockLiteralType();
  499. /// GetAddrOfGlobalBlock - Gets the address of a block which
  500. /// requires no captures.
  501. llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
  502. /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
  503. /// for the given string.
  504. llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
  505. /// GetAddrOfConstantString - Return a pointer to a constant NSString object
  506. /// for the given string. Or a user defined String object as defined via
  507. /// -fconstant-string-class=class_name option.
  508. llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
  509. /// GetConstantArrayFromStringLiteral - Return a constant array for the given
  510. /// string.
  511. llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
  512. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
  513. /// for the given string literal.
  514. llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
  515. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  516. /// array for the given ObjCEncodeExpr node.
  517. llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
  518. /// GetAddrOfConstantString - Returns a pointer to a character array
  519. /// containing the literal. This contents are exactly that of the given
  520. /// string, i.e. it will not be null terminated automatically; see
  521. /// GetAddrOfConstantCString. Note that whether the result is actually a
  522. /// pointer to an LLVM constant depends on Feature.WriteableStrings.
  523. ///
  524. /// The result has pointer to array type.
  525. ///
  526. /// \param GlobalName If provided, the name to use for the global
  527. /// (if one is created).
  528. llvm::Constant *GetAddrOfConstantString(StringRef Str,
  529. const char *GlobalName=0,
  530. unsigned Alignment=1);
  531. /// GetAddrOfConstantCString - Returns a pointer to a character array
  532. /// containing the literal and a terminating '\0' character. The result has
  533. /// pointer to array type.
  534. ///
  535. /// \param GlobalName If provided, the name to use for the global (if one is
  536. /// created).
  537. llvm::Constant *GetAddrOfConstantCString(const std::string &str,
  538. const char *GlobalName=0,
  539. unsigned Alignment=1);
  540. /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global
  541. /// variable for the given file-scope compound literal expression.
  542. llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
  543. /// \brief Retrieve the record type that describes the state of an
  544. /// Objective-C fast enumeration loop (for..in).
  545. QualType getObjCFastEnumerationStateType();
  546. /// GetAddrOfCXXConstructor - Return the address of the constructor of the
  547. /// given type.
  548. llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
  549. CXXCtorType ctorType,
  550. const CGFunctionInfo *fnInfo = 0);
  551. /// GetAddrOfCXXDestructor - Return the address of the constructor of the
  552. /// given type.
  553. llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
  554. CXXDtorType dtorType,
  555. const CGFunctionInfo *fnInfo = 0);
  556. /// getBuiltinLibFunction - Given a builtin id for a function like
  557. /// "__builtin_fabsf", return a Function* for "fabsf".
  558. llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
  559. unsigned BuiltinID);
  560. llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys =
  561. ArrayRef<llvm::Type*>());
  562. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  563. void EmitTopLevelDecl(Decl *D);
  564. /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
  565. // variable has been instantiated.
  566. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
  567. /// AddUsedGlobal - Add a global which should be forced to be
  568. /// present in the object file; these are emitted to the llvm.used
  569. /// metadata global.
  570. void AddUsedGlobal(llvm::GlobalValue *GV);
  571. /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
  572. /// destructor function.
  573. void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
  574. CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
  575. }
  576. /// CreateRuntimeFunction - Create a new runtime function with the specified
  577. /// type and name.
  578. llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
  579. StringRef Name,
  580. llvm::Attribute ExtraAttrs =
  581. llvm::Attribute());
  582. /// CreateRuntimeVariable - Create a new runtime global variable with the
  583. /// specified type and name.
  584. llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
  585. StringRef Name);
  586. ///@name Custom Blocks Runtime Interfaces
  587. ///@{
  588. llvm::Constant *getNSConcreteGlobalBlock();
  589. llvm::Constant *getNSConcreteStackBlock();
  590. llvm::Constant *getBlockObjectAssign();
  591. llvm::Constant *getBlockObjectDispose();
  592. ///@}
  593. // UpdateCompleteType - Make sure that this type is translated.
  594. void UpdateCompletedType(const TagDecl *TD);
  595. llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
  596. /// EmitConstantInit - Try to emit the initializer for the given declaration
  597. /// as a constant; returns 0 if the expression cannot be emitted as a
  598. /// constant.
  599. llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF = 0);
  600. /// EmitConstantExpr - Try to emit the given expression as a
  601. /// constant; returns 0 if the expression cannot be emitted as a
  602. /// constant.
  603. llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
  604. CodeGenFunction *CGF = 0);
  605. /// EmitConstantValue - Emit the given constant value as a constant, in the
  606. /// type's scalar representation.
  607. llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
  608. CodeGenFunction *CGF = 0);
  609. /// EmitConstantValueForMemory - Emit the given constant value as a constant,
  610. /// in the type's memory representation.
  611. llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
  612. QualType DestType,
  613. CodeGenFunction *CGF = 0);
  614. /// EmitNullConstant - Return the result of value-initializing the given
  615. /// type, i.e. a null expression of the given type. This is usually,
  616. /// but not always, an LLVM null constant.
  617. llvm::Constant *EmitNullConstant(QualType T);
  618. /// EmitNullConstantForBase - Return a null constant appropriate for
  619. /// zero-initializing a base class with the given type. This is usually,
  620. /// but not always, an LLVM null constant.
  621. llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
  622. /// Error - Emit a general error that something can't be done.
  623. void Error(SourceLocation loc, StringRef error);
  624. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  625. /// specified stmt yet.
  626. /// \param OmitOnError - If true, then this error should only be emitted if no
  627. /// other errors have been reported.
  628. void ErrorUnsupported(const Stmt *S, const char *Type,
  629. bool OmitOnError=false);
  630. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  631. /// specified decl yet.
  632. /// \param OmitOnError - If true, then this error should only be emitted if no
  633. /// other errors have been reported.
  634. void ErrorUnsupported(const Decl *D, const char *Type,
  635. bool OmitOnError=false);
  636. /// SetInternalFunctionAttributes - Set the attributes on the LLVM
  637. /// function for the given decl and function info. This applies
  638. /// attributes necessary for handling the ABI as well as user
  639. /// specified attributes like section.
  640. void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
  641. const CGFunctionInfo &FI);
  642. /// SetLLVMFunctionAttributes - Set the LLVM function attributes
  643. /// (sext, zext, etc).
  644. void SetLLVMFunctionAttributes(const Decl *D,
  645. const CGFunctionInfo &Info,
  646. llvm::Function *F);
  647. /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
  648. /// which only apply to a function definintion.
  649. void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
  650. /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
  651. /// as a return type.
  652. bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
  653. /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' when
  654. /// used as a return type.
  655. bool ReturnTypeUsesFPRet(QualType ResultType);
  656. /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' when
  657. /// used as a return type.
  658. bool ReturnTypeUsesFP2Ret(QualType ResultType);
  659. /// ConstructAttributeList - Get the LLVM attributes and calling convention to
  660. /// use for a particular function type.
  661. ///
  662. /// \param Info - The function type information.
  663. /// \param TargetDecl - The decl these attributes are being constructed
  664. /// for. If supplied the attributes applied to this decl may contribute to the
  665. /// function attributes and calling convention.
  666. /// \param PAL [out] - On return, the attribute list to use.
  667. /// \param CallingConv [out] - On return, the LLVM calling convention to use.
  668. void ConstructAttributeList(const CGFunctionInfo &Info,
  669. const Decl *TargetDecl,
  670. AttributeListType &PAL,
  671. unsigned &CallingConv);
  672. StringRef getMangledName(GlobalDecl GD);
  673. void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  674. const BlockDecl *BD);
  675. void EmitTentativeDefinition(const VarDecl *D);
  676. void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
  677. llvm::GlobalVariable::LinkageTypes
  678. getFunctionLinkage(const FunctionDecl *FD);
  679. void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
  680. V->setLinkage(getFunctionLinkage(FD));
  681. }
  682. /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
  683. /// and type information of the given class.
  684. llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
  685. /// GetTargetTypeStoreSize - Return the store size, in character units, of
  686. /// the given LLVM type.
  687. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
  688. /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global
  689. /// variable.
  690. llvm::GlobalValue::LinkageTypes
  691. GetLLVMLinkageVarDefinition(const VarDecl *D,
  692. llvm::GlobalVariable *GV);
  693. std::vector<const CXXRecordDecl*> DeferredVTables;
  694. /// Emit all the global annotations.
  695. void EmitGlobalAnnotations();
  696. /// Emit an annotation string.
  697. llvm::Constant *EmitAnnotationString(StringRef Str);
  698. /// Emit the annotation's translation unit.
  699. llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
  700. /// Emit the annotation line number.
  701. llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
  702. /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
  703. /// annotation information for a given GlobalValue. The annotation struct is
  704. /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
  705. /// GlobalValue being annotated. The second field is the constant string
  706. /// created from the AnnotateAttr's annotation. The third field is a constant
  707. /// string containing the name of the translation unit. The fourth field is
  708. /// the line number in the file of the annotated value declaration.
  709. llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
  710. const AnnotateAttr *AA,
  711. SourceLocation L);
  712. /// Add global annotations that are set on D, for the global GV. Those
  713. /// annotations are emitted during finalization of the LLVM code.
  714. void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
  715. const llvm::BlackList &getSanitizerBlacklist() const {
  716. return SanitizerBlacklist;
  717. }
  718. const SanitizerOptions &getSanOpts() const { return SanOpts; }
  719. private:
  720. llvm::GlobalValue *GetGlobalValue(StringRef Ref);
  721. llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName,
  722. llvm::Type *Ty,
  723. GlobalDecl D,
  724. bool ForVTable,
  725. llvm::Attribute ExtraAttrs =
  726. llvm::Attribute());
  727. llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
  728. llvm::PointerType *PTy,
  729. const VarDecl *D,
  730. bool UnnamedAddr = false);
  731. /// SetCommonAttributes - Set attributes which are common to any
  732. /// form of a global definition (alias, Objective-C method,
  733. /// function, global variable).
  734. ///
  735. /// NOTE: This should only be called for definitions.
  736. void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
  737. /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
  738. void SetFunctionDefinitionAttributes(const FunctionDecl *D,
  739. llvm::GlobalValue *GV);
  740. /// SetFunctionAttributes - Set function attributes for a function
  741. /// declaration.
  742. void SetFunctionAttributes(GlobalDecl GD,
  743. llvm::Function *F,
  744. bool IsIncompleteFunction);
  745. /// EmitGlobal - Emit code for a singal global function or var decl. Forward
  746. /// declarations are emitted lazily.
  747. void EmitGlobal(GlobalDecl D);
  748. void EmitGlobalDefinition(GlobalDecl D);
  749. void EmitGlobalFunctionDefinition(GlobalDecl GD);
  750. void EmitGlobalVarDefinition(const VarDecl *D);
  751. llvm::Constant *MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
  752. const Expr *init);
  753. void EmitAliasDefinition(GlobalDecl GD);
  754. void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
  755. void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
  756. // C++ related functions.
  757. bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
  758. bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
  759. void EmitNamespace(const NamespaceDecl *D);
  760. void EmitLinkageSpec(const LinkageSpecDecl *D);
  761. /// EmitCXXConstructors - Emit constructors (base, complete) from a
  762. /// C++ constructor Decl.
  763. void EmitCXXConstructors(const CXXConstructorDecl *D);
  764. /// EmitCXXConstructor - Emit a single constructor with the given type from
  765. /// a C++ constructor Decl.
  766. void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
  767. /// EmitCXXDestructors - Emit destructors (base, complete) from a
  768. /// C++ destructor Decl.
  769. void EmitCXXDestructors(const CXXDestructorDecl *D);
  770. /// EmitCXXDestructor - Emit a single destructor with the given type from
  771. /// a C++ destructor Decl.
  772. void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
  773. /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
  774. void EmitCXXGlobalInitFunc();
  775. /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
  776. void EmitCXXGlobalDtorFunc();
  777. /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the
  778. /// specified global (if PerformInit is true) and registers its destructor.
  779. void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  780. llvm::GlobalVariable *Addr,
  781. bool PerformInit);
  782. // FIXME: Hardcoding priority here is gross.
  783. void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
  784. void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
  785. /// EmitCtorList - Generates a global array of functions and priorities using
  786. /// the given list and name. This array will have appending linkage and is
  787. /// suitable for use as a LLVM constructor or destructor array.
  788. void EmitCtorList(const CtorList &Fns, const char *GlobalName);
  789. /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
  790. /// given type.
  791. void EmitFundamentalRTTIDescriptor(QualType Type);
  792. /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
  793. /// builtin types.
  794. void EmitFundamentalRTTIDescriptors();
  795. /// EmitDeferred - Emit any needed decls for which code generation
  796. /// was deferred.
  797. void EmitDeferred();
  798. /// EmitLLVMUsed - Emit the llvm.used metadata used to force
  799. /// references to global which may otherwise be optimized out.
  800. void EmitLLVMUsed();
  801. /// \brief Emit the link options introduced by imported modules.
  802. void EmitModuleLinkOptions();
  803. void EmitDeclMetadata();
  804. /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
  805. /// to emit the .gcno and .gcda files in a way that persists in .bc files.
  806. void EmitCoverageFile();
  807. /// Emits the initializer for a uuidof string.
  808. llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
  809. /// MayDeferGeneration - Determine if the given decl can be emitted
  810. /// lazily; this is only relevant for definitions. The given decl
  811. /// must be either a function or var decl.
  812. bool MayDeferGeneration(const ValueDecl *D);
  813. /// SimplifyPersonality - Check whether we can use a "simpler", more
  814. /// core exceptions personality function.
  815. void SimplifyPersonality();
  816. };
  817. } // end namespace CodeGen
  818. } // end namespace clang
  819. #endif