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