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