1 //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation of RTTI descriptors.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/AST/Type.h"
19 #include "clang/Frontend/CodeGenOptions.h"
21 using namespace clang;
22 using namespace CodeGen;
26 CodeGenModule &CGM; // Per-module state.
27 llvm::LLVMContext &VMContext;
29 /// Fields - The fields of the RTTI descriptor currently being built.
30 SmallVector<llvm::Constant *, 16> Fields;
32 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
33 llvm::GlobalVariable *
34 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
36 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
37 /// descriptor of the given type.
38 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
40 /// BuildVTablePointer - Build the vtable pointer for the given type.
41 void BuildVTablePointer(const Type *Ty);
43 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
44 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
45 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
47 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
48 /// classes with bases that do not satisfy the abi::__si_class_type_info
49 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
50 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
52 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
53 /// for pointer types.
54 void BuildPointerTypeInfo(QualType PointeeTy);
56 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
57 /// type_info for an object type.
58 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
60 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
61 /// struct, used for member pointer types.
62 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
65 RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
66 VMContext(CGM.getModule().getContext()) { }
68 // Pointer type info flags.
70 /// PTI_Const - Type has const qualifier.
73 /// PTI_Volatile - Type has volatile qualifier.
76 /// PTI_Restrict - Type has restrict qualifier.
79 /// PTI_Incomplete - Type is incomplete.
82 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
83 /// (in pointer to member).
84 PTI_ContainingClassIncomplete = 0x10
87 // VMI type info flags.
89 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
90 VMI_NonDiamondRepeat = 0x1,
92 /// VMI_DiamondShaped - Class is diamond shaped.
93 VMI_DiamondShaped = 0x2
96 // Base class type info flags.
98 /// BCTI_Virtual - Base class is virtual.
101 /// BCTI_Public - Base class is public.
105 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
107 /// \param Force - true to force the creation of this RTTI value
108 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
112 llvm::GlobalVariable *
113 RTTIBuilder::GetAddrOfTypeName(QualType Ty,
114 llvm::GlobalVariable::LinkageTypes Linkage) {
115 SmallString<256> OutName;
116 llvm::raw_svector_ostream Out(OutName);
117 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
119 StringRef Name = OutName.str();
121 // We know that the mangled name of the type starts at index 4 of the
122 // mangled name of the typename, so we can just index into it in order to
123 // get the mangled name of the type.
124 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
127 llvm::GlobalVariable *GV =
128 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
130 GV->setInitializer(Init);
135 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
136 // Mangle the RTTI name.
137 SmallString<256> OutName;
138 llvm::raw_svector_ostream Out(OutName);
139 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
141 StringRef Name = OutName.str();
143 // Look for an existing global.
144 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
147 // Create a new global variable.
148 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
150 llvm::GlobalValue::ExternalLinkage, 0, Name);
153 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
156 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
157 /// info for that type is defined in the standard library.
158 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
159 // Itanium C++ ABI 2.9.2:
160 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
161 // the run-time support library. Specifically, the run-time support
162 // library should contain type_info objects for the types X, X* and
163 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
164 // unsigned char, signed char, short, unsigned short, int, unsigned int,
165 // long, unsigned long, long long, unsigned long long, float, double,
166 // long double, char16_t, char32_t, and the IEEE 754r decimal and
167 // half-precision floating point types.
168 switch (Ty->getKind()) {
169 case BuiltinType::Void:
170 case BuiltinType::NullPtr:
171 case BuiltinType::Bool:
172 case BuiltinType::WChar_S:
173 case BuiltinType::WChar_U:
174 case BuiltinType::Char_U:
175 case BuiltinType::Char_S:
176 case BuiltinType::UChar:
177 case BuiltinType::SChar:
178 case BuiltinType::Short:
179 case BuiltinType::UShort:
180 case BuiltinType::Int:
181 case BuiltinType::UInt:
182 case BuiltinType::Long:
183 case BuiltinType::ULong:
184 case BuiltinType::LongLong:
185 case BuiltinType::ULongLong:
186 case BuiltinType::Half:
187 case BuiltinType::Float:
188 case BuiltinType::Double:
189 case BuiltinType::LongDouble:
190 case BuiltinType::Char16:
191 case BuiltinType::Char32:
192 case BuiltinType::Int128:
193 case BuiltinType::UInt128:
194 case BuiltinType::OCLImage1d:
195 case BuiltinType::OCLImage1dArray:
196 case BuiltinType::OCLImage1dBuffer:
197 case BuiltinType::OCLImage2d:
198 case BuiltinType::OCLImage2dArray:
199 case BuiltinType::OCLImage3d:
200 case BuiltinType::OCLSampler:
201 case BuiltinType::OCLEvent:
204 case BuiltinType::Dependent:
205 #define BUILTIN_TYPE(Id, SingletonId)
206 #define PLACEHOLDER_TYPE(Id, SingletonId) \
207 case BuiltinType::Id:
208 #include "clang/AST/BuiltinTypes.def"
209 llvm_unreachable("asking for RRTI for a placeholder type!");
211 case BuiltinType::ObjCId:
212 case BuiltinType::ObjCClass:
213 case BuiltinType::ObjCSel:
214 llvm_unreachable("FIXME: Objective-C types are unsupported!");
217 llvm_unreachable("Invalid BuiltinType Kind!");
220 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
221 QualType PointeeTy = PointerTy->getPointeeType();
222 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
226 // Check the qualifiers.
227 Qualifiers Quals = PointeeTy.getQualifiers();
233 return TypeInfoIsInStandardLibrary(BuiltinTy);
236 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
237 /// information for the given type exists in the standard library.
238 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
239 // Type info for builtin types is defined in the standard library.
240 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
241 return TypeInfoIsInStandardLibrary(BuiltinTy);
243 // Type info for some pointer types to builtin types is defined in the
245 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
246 return TypeInfoIsInStandardLibrary(PointerTy);
251 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
252 /// the given type exists somewhere else, and that we should not emit the type
253 /// information in this translation unit. Assumes that it is not a
254 /// standard-library type.
255 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
257 ASTContext &Context = CGM.getContext();
259 // If RTTI is disabled, assume it might be disabled in the
260 // translation unit that defines any potential key function, too.
261 if (!Context.getLangOpts().RTTI) return false;
263 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
264 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
265 if (!RD->hasDefinition())
268 if (!RD->isDynamicClass())
271 // FIXME: this may need to be reconsidered if the key function
273 return CGM.getVTables().isVTableExternal(RD);
279 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
280 static bool IsIncompleteClassType(const RecordType *RecordTy) {
281 return !RecordTy->getDecl()->isCompleteDefinition();
284 /// ContainsIncompleteClassType - Returns whether the given type contains an
285 /// incomplete class type. This is true if
287 /// * The given type is an incomplete class type.
288 /// * The given type is a pointer type whose pointee type contains an
289 /// incomplete class type.
290 /// * The given type is a member pointer type whose class is an incomplete
292 /// * The given type is a member pointer type whoise pointee type contains an
293 /// incomplete class type.
294 /// is an indirect or direct pointer to an incomplete class type.
295 static bool ContainsIncompleteClassType(QualType Ty) {
296 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
297 if (IsIncompleteClassType(RecordTy))
301 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
302 return ContainsIncompleteClassType(PointerTy->getPointeeType());
304 if (const MemberPointerType *MemberPointerTy =
305 dyn_cast<MemberPointerType>(Ty)) {
306 // Check if the class type is incomplete.
307 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
308 if (IsIncompleteClassType(ClassType))
311 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
317 /// getTypeInfoLinkage - Return the linkage that the type info and type info
318 /// name constants should have for the given type.
319 static llvm::GlobalVariable::LinkageTypes
320 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
321 // Itanium C++ ABI 2.9.5p7:
322 // In addition, it and all of the intermediate abi::__pointer_type_info
323 // structs in the chain down to the abi::__class_type_info for the
324 // incomplete class type must be prevented from resolving to the
325 // corresponding type_info structs for the complete class type, possibly
326 // by making them local static objects. Finally, a dummy class RTTI is
327 // generated for the incomplete type that will not resolve to the final
328 // complete class RTTI (because the latter need not exist), possibly by
329 // making it a local static object.
330 if (ContainsIncompleteClassType(Ty))
331 return llvm::GlobalValue::InternalLinkage;
333 switch (Ty->getLinkage()) {
335 case InternalLinkage:
336 case UniqueExternalLinkage:
337 return llvm::GlobalValue::InternalLinkage;
339 case ExternalLinkage:
340 if (!CGM.getLangOpts().RTTI) {
341 // RTTI is not enabled, which means that this type info struct is going
342 // to be used for exception handling. Give it linkonce_odr linkage.
343 return llvm::GlobalValue::LinkOnceODRLinkage;
346 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
347 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
348 if (RD->hasAttr<WeakAttr>())
349 return llvm::GlobalValue::WeakODRLinkage;
350 if (RD->isDynamicClass())
351 return CGM.getVTableLinkage(RD);
354 return llvm::GlobalValue::LinkOnceODRLinkage;
357 llvm_unreachable("Invalid linkage!");
360 // CanUseSingleInheritance - Return whether the given record decl has a "single,
361 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
362 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
363 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
364 // Check the number of bases.
365 if (RD->getNumBases() != 1)
369 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
371 // Check that the base is not virtual.
372 if (Base->isVirtual())
375 // Check that the base is public.
376 if (Base->getAccessSpecifier() != AS_public)
379 // Check that the class is dynamic iff the base is.
380 const CXXRecordDecl *BaseDecl =
381 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
382 if (!BaseDecl->isEmpty() &&
383 BaseDecl->isDynamicClass() != RD->isDynamicClass())
389 void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
390 // abi::__class_type_info.
391 static const char * const ClassTypeInfo =
392 "_ZTVN10__cxxabiv117__class_type_infoE";
393 // abi::__si_class_type_info.
394 static const char * const SIClassTypeInfo =
395 "_ZTVN10__cxxabiv120__si_class_type_infoE";
396 // abi::__vmi_class_type_info.
397 static const char * const VMIClassTypeInfo =
398 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
400 const char *VTableName = 0;
402 switch (Ty->getTypeClass()) {
403 #define TYPE(Class, Base)
404 #define ABSTRACT_TYPE(Class, Base)
405 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
406 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
407 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
408 #include "clang/AST/TypeNodes.def"
409 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
411 case Type::LValueReference:
412 case Type::RValueReference:
413 llvm_unreachable("References shouldn't get here");
416 llvm_unreachable("Undeduced auto type shouldn't get here");
419 // GCC treats vector and complex types as fundamental types.
421 case Type::ExtVector:
424 // FIXME: GCC treats block pointers as fundamental types?!
425 case Type::BlockPointer:
426 // abi::__fundamental_type_info.
427 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
430 case Type::ConstantArray:
431 case Type::IncompleteArray:
432 case Type::VariableArray:
433 // abi::__array_type_info.
434 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
437 case Type::FunctionNoProto:
438 case Type::FunctionProto:
439 // abi::__function_type_info.
440 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
444 // abi::__enum_type_info.
445 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
449 const CXXRecordDecl *RD =
450 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
452 if (!RD->hasDefinition() || !RD->getNumBases()) {
453 VTableName = ClassTypeInfo;
454 } else if (CanUseSingleInheritance(RD)) {
455 VTableName = SIClassTypeInfo;
457 VTableName = VMIClassTypeInfo;
463 case Type::ObjCObject:
464 // Ignore protocol qualifiers.
465 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
467 // Handle id and Class.
468 if (isa<BuiltinType>(Ty)) {
469 VTableName = ClassTypeInfo;
473 assert(isa<ObjCInterfaceType>(Ty));
476 case Type::ObjCInterface:
477 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
478 VTableName = SIClassTypeInfo;
480 VTableName = ClassTypeInfo;
484 case Type::ObjCObjectPointer:
486 // abi::__pointer_type_info.
487 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
490 case Type::MemberPointer:
491 // abi::__pointer_to_member_type_info.
492 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
496 llvm::Constant *VTable =
497 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
499 llvm::Type *PtrDiffTy =
500 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
502 // The vtable address point is 2.
503 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
504 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
505 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
507 Fields.push_back(VTable);
510 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
511 // from available_externally to the correct linkage if necessary. An example of
518 // const std::type_info &g() {
524 // When we're generating the typeid(A) expression, we do not yet know that
525 // A's key function is defined in this translation unit, so we will give the
526 // typeinfo and typename structures available_externally linkage. When A::f
527 // forces the vtable to be generated, we need to change the linkage of the
528 // typeinfo and typename structs, otherwise we'll end up with undefined
529 // externals when linking.
531 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
533 // We're only interested in globals with available_externally linkage.
534 if (!GV->hasAvailableExternallyLinkage())
537 // Get the real linkage for the type.
538 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
540 // If variable is supposed to have available_externally linkage, we don't
541 // need to do anything.
542 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
545 // Update the typeinfo linkage.
546 GV->setLinkage(Linkage);
548 // Get the typename global.
549 SmallString<256> OutName;
550 llvm::raw_svector_ostream Out(OutName);
551 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
553 StringRef Name = OutName.str();
555 llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
557 assert(TypeNameGV->hasAvailableExternallyLinkage() &&
558 "Type name has different linkage from type info!");
560 // And update its linkage.
561 TypeNameGV->setLinkage(Linkage);
564 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
565 // We want to operate on the canonical type.
566 Ty = CGM.getContext().getCanonicalType(Ty);
568 // Check if we've already emitted an RTTI descriptor for this type.
569 SmallString<256> OutName;
570 llvm::raw_svector_ostream Out(OutName);
571 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
573 StringRef Name = OutName.str();
575 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
576 if (OldGV && !OldGV->isDeclaration()) {
577 maybeUpdateRTTILinkage(CGM, OldGV, Ty);
579 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
582 // Check if there is already an external RTTI descriptor for this type.
583 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
584 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
585 return GetAddrOfExternalRTTIDescriptor(Ty);
587 // Emit the standard library with external linkage.
588 llvm::GlobalVariable::LinkageTypes Linkage;
590 Linkage = llvm::GlobalValue::ExternalLinkage;
592 Linkage = getTypeInfoLinkage(CGM, Ty);
594 // Add the vtable pointer.
595 BuildVTablePointer(cast<Type>(Ty));
598 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
600 Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
602 switch (Ty->getTypeClass()) {
603 #define TYPE(Class, Base)
604 #define ABSTRACT_TYPE(Class, Base)
605 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
606 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
607 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
608 #include "clang/AST/TypeNodes.def"
609 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
611 // GCC treats vector types as fundamental types.
614 case Type::ExtVector:
616 case Type::BlockPointer:
617 // Itanium C++ ABI 2.9.5p4:
618 // abi::__fundamental_type_info adds no data members to std::type_info.
621 case Type::LValueReference:
622 case Type::RValueReference:
623 llvm_unreachable("References shouldn't get here");
626 llvm_unreachable("Undeduced auto type shouldn't get here");
628 case Type::ConstantArray:
629 case Type::IncompleteArray:
630 case Type::VariableArray:
631 // Itanium C++ ABI 2.9.5p5:
632 // abi::__array_type_info adds no data members to std::type_info.
635 case Type::FunctionNoProto:
636 case Type::FunctionProto:
637 // Itanium C++ ABI 2.9.5p5:
638 // abi::__function_type_info adds no data members to std::type_info.
642 // Itanium C++ ABI 2.9.5p5:
643 // abi::__enum_type_info adds no data members to std::type_info.
647 const CXXRecordDecl *RD =
648 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
649 if (!RD->hasDefinition() || !RD->getNumBases()) {
650 // We don't need to emit any fields.
654 if (CanUseSingleInheritance(RD))
655 BuildSIClassTypeInfo(RD);
657 BuildVMIClassTypeInfo(RD);
662 case Type::ObjCObject:
663 case Type::ObjCInterface:
664 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
667 case Type::ObjCObjectPointer:
668 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
672 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
675 case Type::MemberPointer:
676 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
680 // No fields, at least for the moment.
684 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
686 llvm::GlobalVariable *GV =
687 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
688 /*Constant=*/true, Linkage, Init, Name);
690 // If there's already an old global variable, replace it with the new one.
693 llvm::Constant *NewPtr =
694 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
695 OldGV->replaceAllUsesWith(NewPtr);
696 OldGV->eraseFromParent();
699 // GCC only relies on the uniqueness of the type names, not the
700 // type_infos themselves, so we can emit these as hidden symbols.
701 // But don't do this if we're worried about strict visibility
703 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
704 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
706 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
707 CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
709 Visibility TypeInfoVisibility = DefaultVisibility;
710 if (CGM.getCodeGenOpts().HiddenWeakVTables &&
711 Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
712 TypeInfoVisibility = HiddenVisibility;
714 // The type name should have the same visibility as the type itself.
715 Visibility ExplicitVisibility = Ty->getVisibility();
716 TypeName->setVisibility(CodeGenModule::
717 GetLLVMVisibility(ExplicitVisibility));
719 TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
720 GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
723 GV->setUnnamedAddr(true);
725 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
728 /// ComputeQualifierFlags - Compute the pointer type info flags from the
730 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
733 if (Quals.hasConst())
734 Flags |= RTTIBuilder::PTI_Const;
735 if (Quals.hasVolatile())
736 Flags |= RTTIBuilder::PTI_Volatile;
737 if (Quals.hasRestrict())
738 Flags |= RTTIBuilder::PTI_Restrict;
743 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
744 /// for the given Objective-C object type.
745 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
747 const Type *T = OT->getBaseType().getTypePtr();
748 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
750 // The builtin types are abi::__class_type_infos and don't require
752 if (isa<BuiltinType>(T)) return;
754 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
755 ObjCInterfaceDecl *Super = Class->getSuperClass();
757 // Root classes are also __class_type_info.
760 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
762 // Everything else is single inheritance.
763 llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
764 Fields.push_back(BaseTypeInfo);
767 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
768 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
769 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
770 // Itanium C++ ABI 2.9.5p6b:
771 // It adds to abi::__class_type_info a single member pointing to the
772 // type_info structure for the base type,
773 llvm::Constant *BaseTypeInfo =
774 RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
775 Fields.push_back(BaseTypeInfo);
779 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
780 /// a class hierarchy.
782 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
783 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
787 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
788 /// abi::__vmi_class_type_info.
790 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
795 const CXXRecordDecl *BaseDecl =
796 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
798 if (Base->isVirtual()) {
799 // Mark the virtual base as seen.
800 if (!Bases.VirtualBases.insert(BaseDecl)) {
801 // If this virtual base has been seen before, then the class is diamond
803 Flags |= RTTIBuilder::VMI_DiamondShaped;
805 if (Bases.NonVirtualBases.count(BaseDecl))
806 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
809 // Mark the non-virtual base as seen.
810 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
811 // If this non-virtual base has been seen before, then the class has non-
812 // diamond shaped repeated inheritance.
813 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
815 if (Bases.VirtualBases.count(BaseDecl))
816 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
821 for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
822 E = BaseDecl->bases_end(); I != E; ++I)
823 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
828 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
833 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
834 E = RD->bases_end(); I != E; ++I)
835 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
840 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
841 /// classes with bases that do not satisfy the abi::__si_class_type_info
842 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
843 void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
844 llvm::Type *UnsignedIntLTy =
845 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
847 // Itanium C++ ABI 2.9.5p6c:
848 // __flags is a word with flags describing details about the class
849 // structure, which may be referenced by using the __flags_masks
850 // enumeration. These flags refer to both direct and indirect bases.
851 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
852 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
854 // Itanium C++ ABI 2.9.5p6c:
855 // __base_count is a word with the number of direct proper base class
856 // descriptions that follow.
857 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
859 if (!RD->getNumBases())
862 llvm::Type *LongLTy =
863 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
865 // Now add the base class descriptions.
867 // Itanium C++ ABI 2.9.5p6c:
868 // __base_info[] is an array of base class descriptions -- one for every
869 // direct proper base. Each description is of the type:
871 // struct abi::__base_class_type_info {
873 // const __class_type_info *__base_type;
874 // long __offset_flags;
876 // enum __offset_flags_masks {
877 // __virtual_mask = 0x1,
878 // __public_mask = 0x2,
879 // __offset_shift = 8
882 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
883 E = RD->bases_end(); I != E; ++I) {
884 const CXXBaseSpecifier *Base = I;
886 // The __base_type member points to the RTTI for the base type.
887 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
889 const CXXRecordDecl *BaseDecl =
890 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
892 int64_t OffsetFlags = 0;
894 // All but the lower 8 bits of __offset_flags are a signed offset.
895 // For a non-virtual base, this is the offset in the object of the base
896 // subobject. For a virtual base, this is the offset in the virtual table of
897 // the virtual base offset for the virtual base referenced (negative).
899 if (Base->isVirtual())
901 CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
903 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
904 Offset = Layout.getBaseClassOffset(BaseDecl);
907 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
909 // The low-order byte of __offset_flags contains flags, as given by the
910 // masks from the enumeration __offset_flags_masks.
911 if (Base->isVirtual())
912 OffsetFlags |= BCTI_Virtual;
913 if (Base->getAccessSpecifier() == AS_public)
914 OffsetFlags |= BCTI_Public;
916 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
920 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
921 /// used for pointer types.
922 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
924 QualType UnqualifiedPointeeTy =
925 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
927 // Itanium C++ ABI 2.9.5p7:
928 // __flags is a flag word describing the cv-qualification and other
929 // attributes of the type pointed to
930 unsigned Flags = ComputeQualifierFlags(Quals);
932 // Itanium C++ ABI 2.9.5p7:
933 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
934 // incomplete class type, the incomplete target type flag is set.
935 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
936 Flags |= PTI_Incomplete;
938 llvm::Type *UnsignedIntLTy =
939 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
940 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
942 // Itanium C++ ABI 2.9.5p7:
943 // __pointee is a pointer to the std::type_info derivation for the
944 // unqualified type being pointed to.
945 llvm::Constant *PointeeTypeInfo =
946 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
947 Fields.push_back(PointeeTypeInfo);
950 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
951 /// struct, used for member pointer types.
952 void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
953 QualType PointeeTy = Ty->getPointeeType();
956 QualType UnqualifiedPointeeTy =
957 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
959 // Itanium C++ ABI 2.9.5p7:
960 // __flags is a flag word describing the cv-qualification and other
961 // attributes of the type pointed to.
962 unsigned Flags = ComputeQualifierFlags(Quals);
964 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
966 // Itanium C++ ABI 2.9.5p7:
967 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
968 // incomplete class type, the incomplete target type flag is set.
969 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
970 Flags |= PTI_Incomplete;
972 if (IsIncompleteClassType(ClassType))
973 Flags |= PTI_ContainingClassIncomplete;
975 llvm::Type *UnsignedIntLTy =
976 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
977 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
979 // Itanium C++ ABI 2.9.5p7:
980 // __pointee is a pointer to the std::type_info derivation for the
981 // unqualified type being pointed to.
982 llvm::Constant *PointeeTypeInfo =
983 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
984 Fields.push_back(PointeeTypeInfo);
986 // Itanium C++ ABI 2.9.5p9:
987 // __context is a pointer to an abi::__class_type_info corresponding to the
988 // class type containing the member pointed to
989 // (e.g., the "A" in "int A::*").
990 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
993 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
995 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
996 // FIXME: should we even be calling this method if RTTI is disabled
997 // and it's not for EH?
998 if (!ForEH && !getLangOpts().RTTI)
999 return llvm::Constant::getNullValue(Int8PtrTy);
1001 if (ForEH && Ty->isObjCObjectPointerType() &&
1002 LangOpts.ObjCRuntime.isGNUFamily())
1003 return ObjCRuntime->GetEHType(Ty);
1005 return RTTIBuilder(*this).BuildTypeInfo(Ty);
1008 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
1009 QualType PointerType = Context.getPointerType(Type);
1010 QualType PointerTypeConst = Context.getPointerType(Type.withConst());
1011 RTTIBuilder(*this).BuildTypeInfo(Type, true);
1012 RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
1013 RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
1016 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
1017 QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
1018 Context.BoolTy, Context.WCharTy,
1019 Context.CharTy, Context.UnsignedCharTy,
1020 Context.SignedCharTy, Context.ShortTy,
1021 Context.UnsignedShortTy, Context.IntTy,
1022 Context.UnsignedIntTy, Context.LongTy,
1023 Context.UnsignedLongTy, Context.LongLongTy,
1024 Context.UnsignedLongLongTy, Context.FloatTy,
1025 Context.DoubleTy, Context.LongDoubleTy,
1026 Context.Char16Ty, Context.Char32Ty };
1027 for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
1028 EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);