CodeGenModule.h 37 KB

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