CGRTTI.cpp 35 KB

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