CGRTTI.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
  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 contains code dealing with C++ code generation of RTTI descriptors.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGCXXABI.h"
  15. #include "clang/AST/RecordLayout.h"
  16. #include "clang/AST/Type.h"
  17. #include "clang/Frontend/CodeGenOptions.h"
  18. #include "CGObjCRuntime.h"
  19. using namespace clang;
  20. using namespace CodeGen;
  21. namespace {
  22. class RTTIBuilder {
  23. CodeGenModule &CGM; // Per-module state.
  24. llvm::LLVMContext &VMContext;
  25. /// Fields - The fields of the RTTI descriptor currently being built.
  26. SmallVector<llvm::Constant *, 16> Fields;
  27. /// GetAddrOfTypeName - Returns the mangled type name of the given type.
  28. llvm::GlobalVariable *
  29. GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
  30. /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
  31. /// descriptor of the given type.
  32. llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
  33. /// BuildVTablePointer - Build the vtable pointer for the given type.
  34. void BuildVTablePointer(const Type *Ty);
  35. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  36. /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
  37. void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
  38. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  39. /// classes with bases that do not satisfy the abi::__si_class_type_info
  40. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  41. void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
  42. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
  43. /// for pointer types.
  44. void BuildPointerTypeInfo(QualType PointeeTy);
  45. /// BuildObjCObjectTypeInfo - Build the appropriate kind of
  46. /// type_info for an object type.
  47. void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
  48. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  49. /// struct, used for member pointer types.
  50. void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
  51. public:
  52. RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
  53. VMContext(CGM.getModule().getContext()) { }
  54. // Pointer type info flags.
  55. enum {
  56. /// PTI_Const - Type has const qualifier.
  57. PTI_Const = 0x1,
  58. /// PTI_Volatile - Type has volatile qualifier.
  59. PTI_Volatile = 0x2,
  60. /// PTI_Restrict - Type has restrict qualifier.
  61. PTI_Restrict = 0x4,
  62. /// PTI_Incomplete - Type is incomplete.
  63. PTI_Incomplete = 0x8,
  64. /// PTI_ContainingClassIncomplete - Containing class is incomplete.
  65. /// (in pointer to member).
  66. PTI_ContainingClassIncomplete = 0x10
  67. };
  68. // VMI type info flags.
  69. enum {
  70. /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
  71. VMI_NonDiamondRepeat = 0x1,
  72. /// VMI_DiamondShaped - Class is diamond shaped.
  73. VMI_DiamondShaped = 0x2
  74. };
  75. // Base class type info flags.
  76. enum {
  77. /// BCTI_Virtual - Base class is virtual.
  78. BCTI_Virtual = 0x1,
  79. /// BCTI_Public - Base class is public.
  80. BCTI_Public = 0x2
  81. };
  82. /// BuildTypeInfo - Build the RTTI type info struct for the given type.
  83. ///
  84. /// \param Force - true to force the creation of this RTTI value
  85. llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
  86. };
  87. }
  88. llvm::GlobalVariable *
  89. RTTIBuilder::GetAddrOfTypeName(QualType Ty,
  90. llvm::GlobalVariable::LinkageTypes Linkage) {
  91. SmallString<256> OutName;
  92. llvm::raw_svector_ostream Out(OutName);
  93. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
  94. Out.flush();
  95. StringRef Name = OutName.str();
  96. // We know that the mangled name of the type starts at index 4 of the
  97. // mangled name of the typename, so we can just index into it in order to
  98. // get the mangled name of the type.
  99. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
  100. Name.substr(4));
  101. llvm::GlobalVariable *GV =
  102. CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
  103. GV->setInitializer(Init);
  104. return GV;
  105. }
  106. llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
  107. // Mangle the RTTI name.
  108. SmallString<256> OutName;
  109. llvm::raw_svector_ostream Out(OutName);
  110. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  111. Out.flush();
  112. StringRef Name = OutName.str();
  113. // Look for an existing global.
  114. llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
  115. if (!GV) {
  116. // Create a new global variable.
  117. GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
  118. /*Constant=*/true,
  119. llvm::GlobalValue::ExternalLinkage, 0, Name);
  120. }
  121. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  122. }
  123. /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
  124. /// info for that type is defined in the standard library.
  125. static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
  126. // Itanium C++ ABI 2.9.2:
  127. // Basic type information (e.g. for "int", "bool", etc.) will be kept in
  128. // the run-time support library. Specifically, the run-time support
  129. // library should contain type_info objects for the types X, X* and
  130. // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
  131. // unsigned char, signed char, short, unsigned short, int, unsigned int,
  132. // long, unsigned long, long long, unsigned long long, float, double,
  133. // long double, char16_t, char32_t, and the IEEE 754r decimal and
  134. // half-precision floating point types.
  135. switch (Ty->getKind()) {
  136. case BuiltinType::Void:
  137. case BuiltinType::NullPtr:
  138. case BuiltinType::Bool:
  139. case BuiltinType::WChar_S:
  140. case BuiltinType::WChar_U:
  141. case BuiltinType::Char_U:
  142. case BuiltinType::Char_S:
  143. case BuiltinType::UChar:
  144. case BuiltinType::SChar:
  145. case BuiltinType::Short:
  146. case BuiltinType::UShort:
  147. case BuiltinType::Int:
  148. case BuiltinType::UInt:
  149. case BuiltinType::Long:
  150. case BuiltinType::ULong:
  151. case BuiltinType::LongLong:
  152. case BuiltinType::ULongLong:
  153. case BuiltinType::Half:
  154. case BuiltinType::Float:
  155. case BuiltinType::Double:
  156. case BuiltinType::LongDouble:
  157. case BuiltinType::Char16:
  158. case BuiltinType::Char32:
  159. case BuiltinType::Int128:
  160. case BuiltinType::UInt128:
  161. return true;
  162. case BuiltinType::Dependent:
  163. #define BUILTIN_TYPE(Id, SingletonId)
  164. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  165. case BuiltinType::Id:
  166. #include "clang/AST/BuiltinTypes.def"
  167. llvm_unreachable("asking for RRTI for a placeholder type!");
  168. case BuiltinType::ObjCId:
  169. case BuiltinType::ObjCClass:
  170. case BuiltinType::ObjCSel:
  171. llvm_unreachable("FIXME: Objective-C types are unsupported!");
  172. }
  173. llvm_unreachable("Invalid BuiltinType Kind!");
  174. }
  175. static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
  176. QualType PointeeTy = PointerTy->getPointeeType();
  177. const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
  178. if (!BuiltinTy)
  179. return false;
  180. // Check the qualifiers.
  181. Qualifiers Quals = PointeeTy.getQualifiers();
  182. Quals.removeConst();
  183. if (!Quals.empty())
  184. return false;
  185. return TypeInfoIsInStandardLibrary(BuiltinTy);
  186. }
  187. /// IsStandardLibraryRTTIDescriptor - Returns whether the type
  188. /// information for the given type exists in the standard library.
  189. static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
  190. // Type info for builtin types is defined in the standard library.
  191. if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
  192. return TypeInfoIsInStandardLibrary(BuiltinTy);
  193. // Type info for some pointer types to builtin types is defined in the
  194. // standard library.
  195. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  196. return TypeInfoIsInStandardLibrary(PointerTy);
  197. return false;
  198. }
  199. /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
  200. /// the given type exists somewhere else, and that we should not emit the type
  201. /// information in this translation unit. Assumes that it is not a
  202. /// standard-library type.
  203. static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) {
  204. ASTContext &Context = CGM.getContext();
  205. // If RTTI is disabled, don't consider key functions.
  206. if (!Context.getLangOpts().RTTI) return false;
  207. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  208. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  209. if (!RD->hasDefinition())
  210. return false;
  211. if (!RD->isDynamicClass())
  212. return false;
  213. return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
  214. }
  215. return false;
  216. }
  217. /// IsIncompleteClassType - Returns whether the given record type is incomplete.
  218. static bool IsIncompleteClassType(const RecordType *RecordTy) {
  219. return !RecordTy->getDecl()->isCompleteDefinition();
  220. }
  221. /// ContainsIncompleteClassType - Returns whether the given type contains an
  222. /// incomplete class type. This is true if
  223. ///
  224. /// * The given type is an incomplete class type.
  225. /// * The given type is a pointer type whose pointee type contains an
  226. /// incomplete class type.
  227. /// * The given type is a member pointer type whose class is an incomplete
  228. /// class type.
  229. /// * The given type is a member pointer type whoise pointee type contains an
  230. /// incomplete class type.
  231. /// is an indirect or direct pointer to an incomplete class type.
  232. static bool ContainsIncompleteClassType(QualType Ty) {
  233. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  234. if (IsIncompleteClassType(RecordTy))
  235. return true;
  236. }
  237. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  238. return ContainsIncompleteClassType(PointerTy->getPointeeType());
  239. if (const MemberPointerType *MemberPointerTy =
  240. dyn_cast<MemberPointerType>(Ty)) {
  241. // Check if the class type is incomplete.
  242. const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
  243. if (IsIncompleteClassType(ClassType))
  244. return true;
  245. return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
  246. }
  247. return false;
  248. }
  249. /// getTypeInfoLinkage - Return the linkage that the type info and type info
  250. /// name constants should have for the given type.
  251. static llvm::GlobalVariable::LinkageTypes
  252. getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
  253. // Itanium C++ ABI 2.9.5p7:
  254. // In addition, it and all of the intermediate abi::__pointer_type_info
  255. // structs in the chain down to the abi::__class_type_info for the
  256. // incomplete class type must be prevented from resolving to the
  257. // corresponding type_info structs for the complete class type, possibly
  258. // by making them local static objects. Finally, a dummy class RTTI is
  259. // generated for the incomplete type that will not resolve to the final
  260. // complete class RTTI (because the latter need not exist), possibly by
  261. // making it a local static object.
  262. if (ContainsIncompleteClassType(Ty))
  263. return llvm::GlobalValue::InternalLinkage;
  264. switch (Ty->getLinkage()) {
  265. case NoLinkage:
  266. case InternalLinkage:
  267. case UniqueExternalLinkage:
  268. return llvm::GlobalValue::InternalLinkage;
  269. case ExternalLinkage:
  270. if (!CGM.getLangOpts().RTTI) {
  271. // RTTI is not enabled, which means that this type info struct is going
  272. // to be used for exception handling. Give it linkonce_odr linkage.
  273. return llvm::GlobalValue::LinkOnceODRLinkage;
  274. }
  275. if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
  276. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  277. if (RD->hasAttr<WeakAttr>())
  278. return llvm::GlobalValue::WeakODRLinkage;
  279. if (RD->isDynamicClass())
  280. return CGM.getVTableLinkage(RD);
  281. }
  282. return llvm::GlobalValue::LinkOnceODRLinkage;
  283. }
  284. llvm_unreachable("Invalid linkage!");
  285. }
  286. // CanUseSingleInheritance - Return whether the given record decl has a "single,
  287. // public, non-virtual base at offset zero (i.e. the derived class is dynamic
  288. // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
  289. static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
  290. // Check the number of bases.
  291. if (RD->getNumBases() != 1)
  292. return false;
  293. // Get the base.
  294. CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
  295. // Check that the base is not virtual.
  296. if (Base->isVirtual())
  297. return false;
  298. // Check that the base is public.
  299. if (Base->getAccessSpecifier() != AS_public)
  300. return false;
  301. // Check that the class is dynamic iff the base is.
  302. const CXXRecordDecl *BaseDecl =
  303. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  304. if (!BaseDecl->isEmpty() &&
  305. BaseDecl->isDynamicClass() != RD->isDynamicClass())
  306. return false;
  307. return true;
  308. }
  309. void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
  310. // abi::__class_type_info.
  311. static const char * const ClassTypeInfo =
  312. "_ZTVN10__cxxabiv117__class_type_infoE";
  313. // abi::__si_class_type_info.
  314. static const char * const SIClassTypeInfo =
  315. "_ZTVN10__cxxabiv120__si_class_type_infoE";
  316. // abi::__vmi_class_type_info.
  317. static const char * const VMIClassTypeInfo =
  318. "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
  319. const char *VTableName = 0;
  320. switch (Ty->getTypeClass()) {
  321. #define TYPE(Class, Base)
  322. #define ABSTRACT_TYPE(Class, Base)
  323. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  324. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  325. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  326. #include "clang/AST/TypeNodes.def"
  327. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  328. case Type::LValueReference:
  329. case Type::RValueReference:
  330. llvm_unreachable("References shouldn't get here");
  331. case Type::Builtin:
  332. // GCC treats vector and complex types as fundamental types.
  333. case Type::Vector:
  334. case Type::ExtVector:
  335. case Type::Complex:
  336. case Type::Atomic:
  337. // FIXME: GCC treats block pointers as fundamental types?!
  338. case Type::BlockPointer:
  339. // abi::__fundamental_type_info.
  340. VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
  341. break;
  342. case Type::ConstantArray:
  343. case Type::IncompleteArray:
  344. case Type::VariableArray:
  345. // abi::__array_type_info.
  346. VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
  347. break;
  348. case Type::FunctionNoProto:
  349. case Type::FunctionProto:
  350. // abi::__function_type_info.
  351. VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
  352. break;
  353. case Type::Enum:
  354. // abi::__enum_type_info.
  355. VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
  356. break;
  357. case Type::Record: {
  358. const CXXRecordDecl *RD =
  359. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  360. if (!RD->hasDefinition() || !RD->getNumBases()) {
  361. VTableName = ClassTypeInfo;
  362. } else if (CanUseSingleInheritance(RD)) {
  363. VTableName = SIClassTypeInfo;
  364. } else {
  365. VTableName = VMIClassTypeInfo;
  366. }
  367. break;
  368. }
  369. case Type::ObjCObject:
  370. // Ignore protocol qualifiers.
  371. Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
  372. // Handle id and Class.
  373. if (isa<BuiltinType>(Ty)) {
  374. VTableName = ClassTypeInfo;
  375. break;
  376. }
  377. assert(isa<ObjCInterfaceType>(Ty));
  378. // Fall through.
  379. case Type::ObjCInterface:
  380. if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
  381. VTableName = SIClassTypeInfo;
  382. } else {
  383. VTableName = ClassTypeInfo;
  384. }
  385. break;
  386. case Type::ObjCObjectPointer:
  387. case Type::Pointer:
  388. // abi::__pointer_type_info.
  389. VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
  390. break;
  391. case Type::MemberPointer:
  392. // abi::__pointer_to_member_type_info.
  393. VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
  394. break;
  395. }
  396. llvm::Constant *VTable =
  397. CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
  398. llvm::Type *PtrDiffTy =
  399. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  400. // The vtable address point is 2.
  401. llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
  402. VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
  403. VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
  404. Fields.push_back(VTable);
  405. }
  406. // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
  407. // from available_externally to the correct linkage if necessary. An example of
  408. // this is:
  409. //
  410. // struct A {
  411. // virtual void f();
  412. // };
  413. //
  414. // const std::type_info &g() {
  415. // return typeid(A);
  416. // }
  417. //
  418. // void A::f() { }
  419. //
  420. // When we're generating the typeid(A) expression, we do not yet know that
  421. // A's key function is defined in this translation unit, so we will give the
  422. // typeinfo and typename structures available_externally linkage. When A::f
  423. // forces the vtable to be generated, we need to change the linkage of the
  424. // typeinfo and typename structs, otherwise we'll end up with undefined
  425. // externals when linking.
  426. static void
  427. maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
  428. QualType Ty) {
  429. // We're only interested in globals with available_externally linkage.
  430. if (!GV->hasAvailableExternallyLinkage())
  431. return;
  432. // Get the real linkage for the type.
  433. llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
  434. // If variable is supposed to have available_externally linkage, we don't
  435. // need to do anything.
  436. if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
  437. return;
  438. // Update the typeinfo linkage.
  439. GV->setLinkage(Linkage);
  440. // Get the typename global.
  441. SmallString<256> OutName;
  442. llvm::raw_svector_ostream Out(OutName);
  443. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
  444. Out.flush();
  445. StringRef Name = OutName.str();
  446. llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
  447. assert(TypeNameGV->hasAvailableExternallyLinkage() &&
  448. "Type name has different linkage from type info!");
  449. // And update its linkage.
  450. TypeNameGV->setLinkage(Linkage);
  451. }
  452. llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
  453. // We want to operate on the canonical type.
  454. Ty = CGM.getContext().getCanonicalType(Ty);
  455. // Check if we've already emitted an RTTI descriptor for this type.
  456. SmallString<256> OutName;
  457. llvm::raw_svector_ostream Out(OutName);
  458. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  459. Out.flush();
  460. StringRef Name = OutName.str();
  461. llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
  462. if (OldGV && !OldGV->isDeclaration()) {
  463. maybeUpdateRTTILinkage(CGM, OldGV, Ty);
  464. return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
  465. }
  466. // Check if there is already an external RTTI descriptor for this type.
  467. bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
  468. if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
  469. return GetAddrOfExternalRTTIDescriptor(Ty);
  470. // Emit the standard library with external linkage.
  471. llvm::GlobalVariable::LinkageTypes Linkage;
  472. if (IsStdLib)
  473. Linkage = llvm::GlobalValue::ExternalLinkage;
  474. else
  475. Linkage = getTypeInfoLinkage(CGM, Ty);
  476. // Add the vtable pointer.
  477. BuildVTablePointer(cast<Type>(Ty));
  478. // And the name.
  479. llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
  480. Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
  481. switch (Ty->getTypeClass()) {
  482. #define TYPE(Class, Base)
  483. #define ABSTRACT_TYPE(Class, Base)
  484. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  485. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  486. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  487. #include "clang/AST/TypeNodes.def"
  488. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  489. // GCC treats vector types as fundamental types.
  490. case Type::Builtin:
  491. case Type::Vector:
  492. case Type::ExtVector:
  493. case Type::Complex:
  494. case Type::BlockPointer:
  495. // Itanium C++ ABI 2.9.5p4:
  496. // abi::__fundamental_type_info adds no data members to std::type_info.
  497. break;
  498. case Type::LValueReference:
  499. case Type::RValueReference:
  500. llvm_unreachable("References shouldn't get here");
  501. case Type::ConstantArray:
  502. case Type::IncompleteArray:
  503. case Type::VariableArray:
  504. // Itanium C++ ABI 2.9.5p5:
  505. // abi::__array_type_info adds no data members to std::type_info.
  506. break;
  507. case Type::FunctionNoProto:
  508. case Type::FunctionProto:
  509. // Itanium C++ ABI 2.9.5p5:
  510. // abi::__function_type_info adds no data members to std::type_info.
  511. break;
  512. case Type::Enum:
  513. // Itanium C++ ABI 2.9.5p5:
  514. // abi::__enum_type_info adds no data members to std::type_info.
  515. break;
  516. case Type::Record: {
  517. const CXXRecordDecl *RD =
  518. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  519. if (!RD->hasDefinition() || !RD->getNumBases()) {
  520. // We don't need to emit any fields.
  521. break;
  522. }
  523. if (CanUseSingleInheritance(RD))
  524. BuildSIClassTypeInfo(RD);
  525. else
  526. BuildVMIClassTypeInfo(RD);
  527. break;
  528. }
  529. case Type::ObjCObject:
  530. case Type::ObjCInterface:
  531. BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
  532. break;
  533. case Type::ObjCObjectPointer:
  534. BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  535. break;
  536. case Type::Pointer:
  537. BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
  538. break;
  539. case Type::MemberPointer:
  540. BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
  541. break;
  542. case Type::Atomic:
  543. // No fields, at least for the moment.
  544. break;
  545. }
  546. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
  547. llvm::GlobalVariable *GV =
  548. new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  549. /*Constant=*/true, Linkage, Init, Name);
  550. // If there's already an old global variable, replace it with the new one.
  551. if (OldGV) {
  552. GV->takeName(OldGV);
  553. llvm::Constant *NewPtr =
  554. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  555. OldGV->replaceAllUsesWith(NewPtr);
  556. OldGV->eraseFromParent();
  557. }
  558. // GCC only relies on the uniqueness of the type names, not the
  559. // type_infos themselves, so we can emit these as hidden symbols.
  560. // But don't do this if we're worried about strict visibility
  561. // compatibility.
  562. if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
  563. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  564. CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
  565. CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
  566. } else {
  567. Visibility TypeInfoVisibility = DefaultVisibility;
  568. if (CGM.getCodeGenOpts().HiddenWeakVTables &&
  569. Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
  570. TypeInfoVisibility = HiddenVisibility;
  571. // The type name should have the same visibility as the type itself.
  572. Visibility ExplicitVisibility = Ty->getVisibility();
  573. TypeName->setVisibility(CodeGenModule::
  574. GetLLVMVisibility(ExplicitVisibility));
  575. TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
  576. GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
  577. }
  578. GV->setUnnamedAddr(true);
  579. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  580. }
  581. /// ComputeQualifierFlags - Compute the pointer type info flags from the
  582. /// given qualifier.
  583. static unsigned ComputeQualifierFlags(Qualifiers Quals) {
  584. unsigned Flags = 0;
  585. if (Quals.hasConst())
  586. Flags |= RTTIBuilder::PTI_Const;
  587. if (Quals.hasVolatile())
  588. Flags |= RTTIBuilder::PTI_Volatile;
  589. if (Quals.hasRestrict())
  590. Flags |= RTTIBuilder::PTI_Restrict;
  591. return Flags;
  592. }
  593. /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
  594. /// for the given Objective-C object type.
  595. void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
  596. // Drop qualifiers.
  597. const Type *T = OT->getBaseType().getTypePtr();
  598. assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
  599. // The builtin types are abi::__class_type_infos and don't require
  600. // extra fields.
  601. if (isa<BuiltinType>(T)) return;
  602. ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
  603. ObjCInterfaceDecl *Super = Class->getSuperClass();
  604. // Root classes are also __class_type_info.
  605. if (!Super) return;
  606. QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
  607. // Everything else is single inheritance.
  608. llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
  609. Fields.push_back(BaseTypeInfo);
  610. }
  611. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  612. /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
  613. void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
  614. // Itanium C++ ABI 2.9.5p6b:
  615. // It adds to abi::__class_type_info a single member pointing to the
  616. // type_info structure for the base type,
  617. llvm::Constant *BaseTypeInfo =
  618. RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
  619. Fields.push_back(BaseTypeInfo);
  620. }
  621. namespace {
  622. /// SeenBases - Contains virtual and non-virtual bases seen when traversing
  623. /// a class hierarchy.
  624. struct SeenBases {
  625. llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
  626. llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
  627. };
  628. }
  629. /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
  630. /// abi::__vmi_class_type_info.
  631. ///
  632. static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
  633. SeenBases &Bases) {
  634. unsigned Flags = 0;
  635. const CXXRecordDecl *BaseDecl =
  636. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  637. if (Base->isVirtual()) {
  638. // Mark the virtual base as seen.
  639. if (!Bases.VirtualBases.insert(BaseDecl)) {
  640. // If this virtual base has been seen before, then the class is diamond
  641. // shaped.
  642. Flags |= RTTIBuilder::VMI_DiamondShaped;
  643. } else {
  644. if (Bases.NonVirtualBases.count(BaseDecl))
  645. Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
  646. }
  647. } else {
  648. // Mark the non-virtual base as seen.
  649. if (!Bases.NonVirtualBases.insert(BaseDecl)) {
  650. // If this non-virtual base has been seen before, then the class has non-
  651. // diamond shaped repeated inheritance.
  652. Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
  653. } else {
  654. if (Bases.VirtualBases.count(BaseDecl))
  655. Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
  656. }
  657. }
  658. // Walk all bases.
  659. for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
  660. E = BaseDecl->bases_end(); I != E; ++I)
  661. Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
  662. return Flags;
  663. }
  664. static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
  665. unsigned Flags = 0;
  666. SeenBases Bases;
  667. // Walk all bases.
  668. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  669. E = RD->bases_end(); I != E; ++I)
  670. Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
  671. return Flags;
  672. }
  673. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  674. /// classes with bases that do not satisfy the abi::__si_class_type_info
  675. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  676. void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
  677. llvm::Type *UnsignedIntLTy =
  678. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  679. // Itanium C++ ABI 2.9.5p6c:
  680. // __flags is a word with flags describing details about the class
  681. // structure, which may be referenced by using the __flags_masks
  682. // enumeration. These flags refer to both direct and indirect bases.
  683. unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
  684. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  685. // Itanium C++ ABI 2.9.5p6c:
  686. // __base_count is a word with the number of direct proper base class
  687. // descriptions that follow.
  688. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
  689. if (!RD->getNumBases())
  690. return;
  691. llvm::Type *LongLTy =
  692. CGM.getTypes().ConvertType(CGM.getContext().LongTy);
  693. // Now add the base class descriptions.
  694. // Itanium C++ ABI 2.9.5p6c:
  695. // __base_info[] is an array of base class descriptions -- one for every
  696. // direct proper base. Each description is of the type:
  697. //
  698. // struct abi::__base_class_type_info {
  699. // public:
  700. // const __class_type_info *__base_type;
  701. // long __offset_flags;
  702. //
  703. // enum __offset_flags_masks {
  704. // __virtual_mask = 0x1,
  705. // __public_mask = 0x2,
  706. // __offset_shift = 8
  707. // };
  708. // };
  709. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  710. E = RD->bases_end(); I != E; ++I) {
  711. const CXXBaseSpecifier *Base = I;
  712. // The __base_type member points to the RTTI for the base type.
  713. Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
  714. const CXXRecordDecl *BaseDecl =
  715. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  716. int64_t OffsetFlags = 0;
  717. // All but the lower 8 bits of __offset_flags are a signed offset.
  718. // For a non-virtual base, this is the offset in the object of the base
  719. // subobject. For a virtual base, this is the offset in the virtual table of
  720. // the virtual base offset for the virtual base referenced (negative).
  721. CharUnits Offset;
  722. if (Base->isVirtual())
  723. Offset =
  724. CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
  725. else {
  726. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  727. Offset = Layout.getBaseClassOffset(BaseDecl);
  728. };
  729. OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
  730. // The low-order byte of __offset_flags contains flags, as given by the
  731. // masks from the enumeration __offset_flags_masks.
  732. if (Base->isVirtual())
  733. OffsetFlags |= BCTI_Virtual;
  734. if (Base->getAccessSpecifier() == AS_public)
  735. OffsetFlags |= BCTI_Public;
  736. Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
  737. }
  738. }
  739. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
  740. /// used for pointer types.
  741. void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
  742. Qualifiers Quals;
  743. QualType UnqualifiedPointeeTy =
  744. CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
  745. // Itanium C++ ABI 2.9.5p7:
  746. // __flags is a flag word describing the cv-qualification and other
  747. // attributes of the type pointed to
  748. unsigned Flags = ComputeQualifierFlags(Quals);
  749. // Itanium C++ ABI 2.9.5p7:
  750. // When the abi::__pbase_type_info is for a direct or indirect pointer to an
  751. // incomplete class type, the incomplete target type flag is set.
  752. if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
  753. Flags |= PTI_Incomplete;
  754. llvm::Type *UnsignedIntLTy =
  755. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  756. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  757. // Itanium C++ ABI 2.9.5p7:
  758. // __pointee is a pointer to the std::type_info derivation for the
  759. // unqualified type being pointed to.
  760. llvm::Constant *PointeeTypeInfo =
  761. RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
  762. Fields.push_back(PointeeTypeInfo);
  763. }
  764. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  765. /// struct, used for member pointer types.
  766. void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
  767. QualType PointeeTy = Ty->getPointeeType();
  768. Qualifiers Quals;
  769. QualType UnqualifiedPointeeTy =
  770. CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
  771. // Itanium C++ ABI 2.9.5p7:
  772. // __flags is a flag word describing the cv-qualification and other
  773. // attributes of the type pointed to.
  774. unsigned Flags = ComputeQualifierFlags(Quals);
  775. const RecordType *ClassType = cast<RecordType>(Ty->getClass());
  776. // Itanium C++ ABI 2.9.5p7:
  777. // When the abi::__pbase_type_info is for a direct or indirect pointer to an
  778. // incomplete class type, the incomplete target type flag is set.
  779. if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
  780. Flags |= PTI_Incomplete;
  781. if (IsIncompleteClassType(ClassType))
  782. Flags |= PTI_ContainingClassIncomplete;
  783. llvm::Type *UnsignedIntLTy =
  784. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  785. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  786. // Itanium C++ ABI 2.9.5p7:
  787. // __pointee is a pointer to the std::type_info derivation for the
  788. // unqualified type being pointed to.
  789. llvm::Constant *PointeeTypeInfo =
  790. RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
  791. Fields.push_back(PointeeTypeInfo);
  792. // Itanium C++ ABI 2.9.5p9:
  793. // __context is a pointer to an abi::__class_type_info corresponding to the
  794. // class type containing the member pointed to
  795. // (e.g., the "A" in "int A::*").
  796. Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
  797. }
  798. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  799. bool ForEH) {
  800. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  801. // FIXME: should we even be calling this method if RTTI is disabled
  802. // and it's not for EH?
  803. if (!ForEH && !getContext().getLangOpts().RTTI)
  804. return llvm::Constant::getNullValue(Int8PtrTy);
  805. if (ForEH && Ty->isObjCObjectPointerType() &&
  806. LangOpts.ObjCRuntime.isGNUFamily())
  807. return ObjCRuntime->GetEHType(Ty);
  808. return RTTIBuilder(*this).BuildTypeInfo(Ty);
  809. }
  810. void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
  811. QualType PointerType = Context.getPointerType(Type);
  812. QualType PointerTypeConst = Context.getPointerType(Type.withConst());
  813. RTTIBuilder(*this).BuildTypeInfo(Type, true);
  814. RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
  815. RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
  816. }
  817. void CodeGenModule::EmitFundamentalRTTIDescriptors() {
  818. QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
  819. Context.BoolTy, Context.WCharTy,
  820. Context.CharTy, Context.UnsignedCharTy,
  821. Context.SignedCharTy, Context.ShortTy,
  822. Context.UnsignedShortTy, Context.IntTy,
  823. Context.UnsignedIntTy, Context.LongTy,
  824. Context.UnsignedLongTy, Context.LongLongTy,
  825. Context.UnsignedLongLongTy, Context.FloatTy,
  826. Context.DoubleTy, Context.LongDoubleTy,
  827. Context.Char16Ty, Context.Char32Ty };
  828. for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
  829. EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);
  830. }