CodeGenModule.h 36 KB

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